xref: /dragonfly/sys/vm/vm_map.c (revision e7d467f4)
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
39  *
40  *
41  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42  * All rights reserved.
43  *
44  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
45  *
46  * Permission to use, copy, modify and distribute this software and
47  * its documentation is hereby granted, provided that both the copyright
48  * notice and this permission notice appear in all copies of the
49  * software, derivative works or modified versions, and any portions
50  * thereof, and that both notices appear in supporting documentation.
51  *
52  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
53  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
54  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
55  *
56  * Carnegie Mellon requests users of this software to return to
57  *
58  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
59  *  School of Computer Science
60  *  Carnegie Mellon University
61  *  Pittsburgh PA 15213-3890
62  *
63  * any improvements or extensions that they make and grant Carnegie the
64  * rights to redistribute these changes.
65  *
66  * $FreeBSD: src/sys/vm/vm_map.c,v 1.187.2.19 2003/05/27 00:47:02 alc Exp $
67  */
68 
69 /*
70  *	Virtual memory mapping module.
71  */
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kernel.h>
76 #include <sys/proc.h>
77 #include <sys/serialize.h>
78 #include <sys/lock.h>
79 #include <sys/vmmeter.h>
80 #include <sys/mman.h>
81 #include <sys/vnode.h>
82 #include <sys/resourcevar.h>
83 #include <sys/shm.h>
84 #include <sys/tree.h>
85 #include <sys/malloc.h>
86 
87 #include <vm/vm.h>
88 #include <vm/vm_param.h>
89 #include <vm/pmap.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_page.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_pager.h>
94 #include <vm/vm_kern.h>
95 #include <vm/vm_extern.h>
96 #include <vm/swap_pager.h>
97 #include <vm/vm_zone.h>
98 
99 #include <sys/thread2.h>
100 #include <sys/sysref2.h>
101 #include <sys/random.h>
102 #include <sys/sysctl.h>
103 
104 /*
105  * Virtual memory maps provide for the mapping, protection, and sharing
106  * of virtual memory objects.  In addition, this module provides for an
107  * efficient virtual copy of memory from one map to another.
108  *
109  * Synchronization is required prior to most operations.
110  *
111  * Maps consist of an ordered doubly-linked list of simple entries.
112  * A hint and a RB tree is used to speed-up lookups.
113  *
114  * Callers looking to modify maps specify start/end addresses which cause
115  * the related map entry to be clipped if necessary, and then later
116  * recombined if the pieces remained compatible.
117  *
118  * Virtual copy operations are performed by copying VM object references
119  * from one map to another, and then marking both regions as copy-on-write.
120  */
121 static void vmspace_terminate(struct vmspace *vm);
122 static void vmspace_lock(struct vmspace *vm);
123 static void vmspace_unlock(struct vmspace *vm);
124 static void vmspace_dtor(void *obj, void *private);
125 
126 MALLOC_DEFINE(M_VMSPACE, "vmspace", "vmspace objcache backingstore");
127 
128 struct sysref_class vmspace_sysref_class = {
129 	.name =		"vmspace",
130 	.mtype =	M_VMSPACE,
131 	.proto =	SYSREF_PROTO_VMSPACE,
132 	.offset =	offsetof(struct vmspace, vm_sysref),
133 	.objsize =	sizeof(struct vmspace),
134 	.nom_cache =	32,
135 	.flags = SRC_MANAGEDINIT,
136 	.dtor = vmspace_dtor,
137 	.ops = {
138 		.terminate = (sysref_terminate_func_t)vmspace_terminate,
139 		.lock = (sysref_lock_func_t)vmspace_lock,
140 		.unlock = (sysref_lock_func_t)vmspace_unlock
141 	}
142 };
143 
144 /*
145  * per-cpu page table cross mappings are initialized in early boot
146  * and might require a considerable number of vm_map_entry structures.
147  */
148 #define VMEPERCPU	(MAXCPU+1)
149 
150 static struct vm_zone mapentzone_store, mapzone_store;
151 static vm_zone_t mapentzone, mapzone;
152 static struct vm_object mapentobj, mapobj;
153 
154 static struct vm_map_entry map_entry_init[MAX_MAPENT];
155 static struct vm_map_entry cpu_map_entry_init[MAXCPU][VMEPERCPU];
156 static struct vm_map map_init[MAX_KMAP];
157 
158 static int randomize_mmap;
159 SYSCTL_INT(_vm, OID_AUTO, randomize_mmap, CTLFLAG_RW, &randomize_mmap, 0,
160     "Randomize mmap offsets");
161 static int vm_map_relock_enable = 1;
162 SYSCTL_INT(_vm, OID_AUTO, map_relock_enable, CTLFLAG_RW,
163 	   &vm_map_relock_enable, 0, "Randomize mmap offsets");
164 
165 static void vm_map_entry_shadow(vm_map_entry_t entry, int addref);
166 static vm_map_entry_t vm_map_entry_create(vm_map_t map, int *);
167 static void vm_map_entry_dispose (vm_map_t map, vm_map_entry_t entry, int *);
168 static void _vm_map_clip_end (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
169 static void _vm_map_clip_start (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
170 static void vm_map_entry_delete (vm_map_t, vm_map_entry_t, int *);
171 static void vm_map_entry_unwire (vm_map_t, vm_map_entry_t);
172 static void vm_map_copy_entry (vm_map_t, vm_map_t, vm_map_entry_t,
173 		vm_map_entry_t);
174 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);
175 
176 /*
177  * Initialize the vm_map module.  Must be called before any other vm_map
178  * routines.
179  *
180  * Map and entry structures are allocated from the general purpose
181  * memory pool with some exceptions:
182  *
183  *	- The kernel map is allocated statically.
184  *	- Initial kernel map entries are allocated out of a static pool.
185  *
186  *	These restrictions are necessary since malloc() uses the
187  *	maps and requires map entries.
188  *
189  * Called from the low level boot code only.
190  */
191 void
192 vm_map_startup(void)
193 {
194 	mapzone = &mapzone_store;
195 	zbootinit(mapzone, "MAP", sizeof (struct vm_map),
196 		map_init, MAX_KMAP);
197 	mapentzone = &mapentzone_store;
198 	zbootinit(mapentzone, "MAP ENTRY", sizeof (struct vm_map_entry),
199 		map_entry_init, MAX_MAPENT);
200 }
201 
202 /*
203  * Called prior to any vmspace allocations.
204  *
205  * Called from the low level boot code only.
206  */
207 void
208 vm_init2(void)
209 {
210 	zinitna(mapentzone, &mapentobj, NULL, 0, 0,
211 		ZONE_USE_RESERVE | ZONE_SPECIAL, 1);
212 	zinitna(mapzone, &mapobj, NULL, 0, 0, 0, 1);
213 	pmap_init2();
214 	vm_object_init2();
215 }
216 
217 
218 /*
219  * Red black tree functions
220  *
221  * The caller must hold the related map lock.
222  */
223 static int rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b);
224 RB_GENERATE(vm_map_rb_tree, vm_map_entry, rb_entry, rb_vm_map_compare);
225 
226 /* a->start is address, and the only field has to be initialized */
227 static int
228 rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b)
229 {
230 	if (a->start < b->start)
231 		return(-1);
232 	else if (a->start > b->start)
233 		return(1);
234 	return(0);
235 }
236 
237 /*
238  * Allocate a vmspace structure, including a vm_map and pmap.
239  * Initialize numerous fields.  While the initial allocation is zerod,
240  * subsequence reuse from the objcache leaves elements of the structure
241  * intact (particularly the pmap), so portions must be zerod.
242  *
243  * The structure is not considered activated until we call sysref_activate().
244  *
245  * No requirements.
246  */
247 struct vmspace *
248 vmspace_alloc(vm_offset_t min, vm_offset_t max)
249 {
250 	struct vmspace *vm;
251 
252 	vm = sysref_alloc(&vmspace_sysref_class);
253 	bzero(&vm->vm_startcopy,
254 	      (char *)&vm->vm_endcopy - (char *)&vm->vm_startcopy);
255 	vm_map_init(&vm->vm_map, min, max, NULL);	/* initializes token */
256 
257 	/*
258 	 * Use a hold to prevent any additional racing hold from terminating
259 	 * the vmspace before we manage to activate it.  This also acquires
260 	 * the token for safety.
261 	 */
262 	KKASSERT(vm->vm_holdcount == 0);
263 	KKASSERT(vm->vm_exitingcnt == 0);
264 	vmspace_hold(vm);
265 	pmap_pinit(vmspace_pmap(vm));		/* (some fields reused) */
266 	vm->vm_map.pmap = vmspace_pmap(vm);		/* XXX */
267 	vm->vm_shm = NULL;
268 	vm->vm_flags = 0;
269 	cpu_vmspace_alloc(vm);
270 	sysref_activate(&vm->vm_sysref);
271 	vmspace_drop(vm);
272 
273 	return (vm);
274 }
275 
276 /*
277  * Free a primary reference to a vmspace.  This can trigger a
278  * stage-1 termination.
279  */
280 void
281 vmspace_free(struct vmspace *vm)
282 {
283 	/*
284 	 * We want all finalization to occur via vmspace_drop() so we
285 	 * need to hold the vm around the put.
286 	 */
287 	vmspace_hold(vm);
288 	sysref_put(&vm->vm_sysref);
289 	vmspace_drop(vm);
290 }
291 
292 void
293 vmspace_ref(struct vmspace *vm)
294 {
295 	sysref_get(&vm->vm_sysref);
296 }
297 
298 void
299 vmspace_hold(struct vmspace *vm)
300 {
301 	refcount_acquire(&vm->vm_holdcount);
302 	lwkt_gettoken(&vm->vm_map.token);
303 }
304 
305 void
306 vmspace_drop(struct vmspace *vm)
307 {
308 	lwkt_reltoken(&vm->vm_map.token);
309 	if (refcount_release(&vm->vm_holdcount)) {
310 		if (vm->vm_exitingcnt == 0 &&
311 		    sysref_isinactive(&vm->vm_sysref)) {
312 			vmspace_terminate(vm);
313 		}
314 	}
315 }
316 
317 /*
318  * dtor function - Some elements of the pmap are retained in the
319  * free-cached vmspaces to improve performance.  We have to clean them up
320  * here before returning the vmspace to the memory pool.
321  *
322  * No requirements.
323  */
324 static void
325 vmspace_dtor(void *obj, void *private)
326 {
327 	struct vmspace *vm = obj;
328 
329 	pmap_puninit(vmspace_pmap(vm));
330 }
331 
332 /*
333  * Called in three cases:
334  *
335  * (1) When the last sysref is dropped and the vmspace becomes inactive.
336  *     (holdcount will not be 0 because the vmspace is held through the op)
337  *
338  * (2) When exitingcount becomes 0 on the last reap
339  *     (holdcount will not be 0 because the vmspace is held through the op)
340  *
341  * (3) When the holdcount becomes 0 in addition to the above two
342  *
343  * sysref will not scrap the object until we call sysref_put() once more
344  * after the last ref has been dropped.
345  *
346  * VMSPACE_EXIT1 flags the primary deactivation
347  * VMSPACE_EXIT2 flags the last reap
348  */
349 static void
350 vmspace_terminate(struct vmspace *vm)
351 {
352 	int count;
353 
354 	/*
355 	 *
356 	 */
357 	lwkt_gettoken(&vm->vm_map.token);
358 	if ((vm->vm_flags & VMSPACE_EXIT1) == 0) {
359 		vm->vm_flags |= VMSPACE_EXIT1;
360 		shmexit(vm);
361 		pmap_remove_pages(vmspace_pmap(vm), VM_MIN_USER_ADDRESS,
362 				  VM_MAX_USER_ADDRESS);
363 		vm_map_remove(&vm->vm_map, VM_MIN_USER_ADDRESS,
364 			      VM_MAX_USER_ADDRESS);
365 	}
366 	if ((vm->vm_flags & VMSPACE_EXIT2) == 0 && vm->vm_exitingcnt == 0) {
367 		vm->vm_flags |= VMSPACE_EXIT2;
368 		cpu_vmspace_free(vm);
369 		shmexit(vm);
370 
371 		/*
372 		 * Lock the map, to wait out all other references to it.
373 		 * Delete all of the mappings and pages they hold, then call
374 		 * the pmap module to reclaim anything left.
375 		 */
376 		count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
377 		vm_map_lock(&vm->vm_map);
378 		vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
379 			      vm->vm_map.max_offset, &count);
380 		vm_map_unlock(&vm->vm_map);
381 		vm_map_entry_release(count);
382 
383 		lwkt_gettoken(&vmspace_pmap(vm)->pm_token);
384 		pmap_release(vmspace_pmap(vm));
385 		lwkt_reltoken(&vmspace_pmap(vm)->pm_token);
386 	}
387 
388 	lwkt_reltoken(&vm->vm_map.token);
389 	if (vm->vm_exitingcnt == 0 && vm->vm_holdcount == 0) {
390 		KKASSERT(vm->vm_flags & VMSPACE_EXIT1);
391 		KKASSERT(vm->vm_flags & VMSPACE_EXIT2);
392 		sysref_put(&vm->vm_sysref);
393 	}
394 }
395 
396 /*
397  * vmspaces are not currently locked.
398  */
399 static void
400 vmspace_lock(struct vmspace *vm __unused)
401 {
402 }
403 
404 static void
405 vmspace_unlock(struct vmspace *vm __unused)
406 {
407 }
408 
409 /*
410  * This is called during exit indicating that the vmspace is no
411  * longer in used by an exiting process, but the process has not yet
412  * been reaped.
413  *
414  * No requirements.
415  */
416 void
417 vmspace_exitbump(struct vmspace *vm)
418 {
419 	vmspace_hold(vm);
420 	++vm->vm_exitingcnt;
421 	vmspace_drop(vm);	/* handles termination sequencing */
422 }
423 
424 /*
425  * Decrement the exitingcnt and issue the stage-2 termination if it becomes
426  * zero and the stage1 termination has already occured.
427  *
428  * No requirements.
429  */
430 void
431 vmspace_exitfree(struct proc *p)
432 {
433 	struct vmspace *vm;
434 
435 	vm = p->p_vmspace;
436 	p->p_vmspace = NULL;
437 	vmspace_hold(vm);
438 	KKASSERT(vm->vm_exitingcnt > 0);
439 	if (--vm->vm_exitingcnt == 0 && sysref_isinactive(&vm->vm_sysref))
440 		vmspace_terminate(vm);
441 	vmspace_drop(vm);	/* handles termination sequencing */
442 }
443 
444 /*
445  * Swap useage is determined by taking the proportional swap used by
446  * VM objects backing the VM map.  To make up for fractional losses,
447  * if the VM object has any swap use at all the associated map entries
448  * count for at least 1 swap page.
449  *
450  * No requirements.
451  */
452 int
453 vmspace_swap_count(struct vmspace *vm)
454 {
455 	vm_map_t map = &vm->vm_map;
456 	vm_map_entry_t cur;
457 	vm_object_t object;
458 	int count = 0;
459 	int n;
460 
461 	vmspace_hold(vm);
462 	for (cur = map->header.next; cur != &map->header; cur = cur->next) {
463 		switch(cur->maptype) {
464 		case VM_MAPTYPE_NORMAL:
465 		case VM_MAPTYPE_VPAGETABLE:
466 			if ((object = cur->object.vm_object) == NULL)
467 				break;
468 			if (object->swblock_count) {
469 				n = (cur->end - cur->start) / PAGE_SIZE;
470 				count += object->swblock_count *
471 				    SWAP_META_PAGES * n / object->size + 1;
472 			}
473 			break;
474 		default:
475 			break;
476 		}
477 	}
478 	vmspace_drop(vm);
479 
480 	return(count);
481 }
482 
483 /*
484  * Calculate the approximate number of anonymous pages in use by
485  * this vmspace.  To make up for fractional losses, we count each
486  * VM object as having at least 1 anonymous page.
487  *
488  * No requirements.
489  */
490 int
491 vmspace_anonymous_count(struct vmspace *vm)
492 {
493 	vm_map_t map = &vm->vm_map;
494 	vm_map_entry_t cur;
495 	vm_object_t object;
496 	int count = 0;
497 
498 	vmspace_hold(vm);
499 	for (cur = map->header.next; cur != &map->header; cur = cur->next) {
500 		switch(cur->maptype) {
501 		case VM_MAPTYPE_NORMAL:
502 		case VM_MAPTYPE_VPAGETABLE:
503 			if ((object = cur->object.vm_object) == NULL)
504 				break;
505 			if (object->type != OBJT_DEFAULT &&
506 			    object->type != OBJT_SWAP) {
507 				break;
508 			}
509 			count += object->resident_page_count;
510 			break;
511 		default:
512 			break;
513 		}
514 	}
515 	vmspace_drop(vm);
516 
517 	return(count);
518 }
519 
520 /*
521  * Creates and returns a new empty VM map with the given physical map
522  * structure, and having the given lower and upper address bounds.
523  *
524  * No requirements.
525  */
526 vm_map_t
527 vm_map_create(vm_map_t result, pmap_t pmap, vm_offset_t min, vm_offset_t max)
528 {
529 	if (result == NULL)
530 		result = zalloc(mapzone);
531 	vm_map_init(result, min, max, pmap);
532 	return (result);
533 }
534 
535 /*
536  * Initialize an existing vm_map structure such as that in the vmspace
537  * structure.  The pmap is initialized elsewhere.
538  *
539  * No requirements.
540  */
541 void
542 vm_map_init(struct vm_map *map, vm_offset_t min, vm_offset_t max, pmap_t pmap)
543 {
544 	map->header.next = map->header.prev = &map->header;
545 	RB_INIT(&map->rb_root);
546 	map->nentries = 0;
547 	map->size = 0;
548 	map->system_map = 0;
549 	map->min_offset = min;
550 	map->max_offset = max;
551 	map->pmap = pmap;
552 	map->first_free = &map->header;
553 	map->hint = &map->header;
554 	map->timestamp = 0;
555 	map->flags = 0;
556 	lwkt_token_init(&map->token, "vm_map");
557 	lockinit(&map->lock, "thrd_sleep", (hz + 9) / 10, 0);
558 	TUNABLE_INT("vm.cache_vmspaces", &vmspace_sysref_class.nom_cache);
559 }
560 
561 /*
562  * Shadow the vm_map_entry's object.  This typically needs to be done when
563  * a write fault is taken on an entry which had previously been cloned by
564  * fork().  The shared object (which might be NULL) must become private so
565  * we add a shadow layer above it.
566  *
567  * Object allocation for anonymous mappings is defered as long as possible.
568  * When creating a shadow, however, the underlying object must be instantiated
569  * so it can be shared.
570  *
571  * If the map segment is governed by a virtual page table then it is
572  * possible to address offsets beyond the mapped area.  Just allocate
573  * a maximally sized object for this case.
574  *
575  * The vm_map must be exclusively locked.
576  * No other requirements.
577  */
578 static
579 void
580 vm_map_entry_shadow(vm_map_entry_t entry, int addref)
581 {
582 	if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
583 		vm_object_shadow(&entry->object.vm_object, &entry->offset,
584 				 0x7FFFFFFF, addref);	/* XXX */
585 	} else {
586 		vm_object_shadow(&entry->object.vm_object, &entry->offset,
587 				 atop(entry->end - entry->start), addref);
588 	}
589 	entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
590 }
591 
592 /*
593  * Allocate an object for a vm_map_entry.
594  *
595  * Object allocation for anonymous mappings is defered as long as possible.
596  * This function is called when we can defer no longer, generally when a map
597  * entry might be split or forked or takes a page fault.
598  *
599  * If the map segment is governed by a virtual page table then it is
600  * possible to address offsets beyond the mapped area.  Just allocate
601  * a maximally sized object for this case.
602  *
603  * The vm_map must be exclusively locked.
604  * No other requirements.
605  */
606 void
607 vm_map_entry_allocate_object(vm_map_entry_t entry)
608 {
609 	vm_object_t obj;
610 
611 	if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
612 		obj = vm_object_allocate(OBJT_DEFAULT, 0x7FFFFFFF); /* XXX */
613 	} else {
614 		obj = vm_object_allocate(OBJT_DEFAULT,
615 					 atop(entry->end - entry->start));
616 	}
617 	entry->object.vm_object = obj;
618 	entry->offset = 0;
619 }
620 
621 /*
622  * Set an initial negative count so the first attempt to reserve
623  * space preloads a bunch of vm_map_entry's for this cpu.  Also
624  * pre-allocate 2 vm_map_entries which will be needed by zalloc() to
625  * map a new page for vm_map_entry structures.  SMP systems are
626  * particularly sensitive.
627  *
628  * This routine is called in early boot so we cannot just call
629  * vm_map_entry_reserve().
630  *
631  * Called from the low level boot code only (for each cpu)
632  */
633 void
634 vm_map_entry_reserve_cpu_init(globaldata_t gd)
635 {
636 	vm_map_entry_t entry;
637 	int i;
638 
639 	gd->gd_vme_avail -= MAP_RESERVE_COUNT * 2;
640 	entry = &cpu_map_entry_init[gd->gd_cpuid][0];
641 	for (i = 0; i < VMEPERCPU; ++i, ++entry) {
642 		entry->next = gd->gd_vme_base;
643 		gd->gd_vme_base = entry;
644 	}
645 }
646 
647 /*
648  * Reserves vm_map_entry structures so code later on can manipulate
649  * map_entry structures within a locked map without blocking trying
650  * to allocate a new vm_map_entry.
651  *
652  * No requirements.
653  */
654 int
655 vm_map_entry_reserve(int count)
656 {
657 	struct globaldata *gd = mycpu;
658 	vm_map_entry_t entry;
659 
660 	/*
661 	 * Make sure we have enough structures in gd_vme_base to handle
662 	 * the reservation request.
663 	 *
664 	 * The critical section protects access to the per-cpu gd.
665 	 */
666 	crit_enter();
667 	while (gd->gd_vme_avail < count) {
668 		entry = zalloc(mapentzone);
669 		entry->next = gd->gd_vme_base;
670 		gd->gd_vme_base = entry;
671 		++gd->gd_vme_avail;
672 	}
673 	gd->gd_vme_avail -= count;
674 	crit_exit();
675 
676 	return(count);
677 }
678 
679 /*
680  * Releases previously reserved vm_map_entry structures that were not
681  * used.  If we have too much junk in our per-cpu cache clean some of
682  * it out.
683  *
684  * No requirements.
685  */
686 void
687 vm_map_entry_release(int count)
688 {
689 	struct globaldata *gd = mycpu;
690 	vm_map_entry_t entry;
691 
692 	crit_enter();
693 	gd->gd_vme_avail += count;
694 	while (gd->gd_vme_avail > MAP_RESERVE_SLOP) {
695 		entry = gd->gd_vme_base;
696 		KKASSERT(entry != NULL);
697 		gd->gd_vme_base = entry->next;
698 		--gd->gd_vme_avail;
699 		crit_exit();
700 		zfree(mapentzone, entry);
701 		crit_enter();
702 	}
703 	crit_exit();
704 }
705 
706 /*
707  * Reserve map entry structures for use in kernel_map itself.  These
708  * entries have *ALREADY* been reserved on a per-cpu basis when the map
709  * was inited.  This function is used by zalloc() to avoid a recursion
710  * when zalloc() itself needs to allocate additional kernel memory.
711  *
712  * This function works like the normal reserve but does not load the
713  * vm_map_entry cache (because that would result in an infinite
714  * recursion).  Note that gd_vme_avail may go negative.  This is expected.
715  *
716  * Any caller of this function must be sure to renormalize after
717  * potentially eating entries to ensure that the reserve supply
718  * remains intact.
719  *
720  * No requirements.
721  */
722 int
723 vm_map_entry_kreserve(int count)
724 {
725 	struct globaldata *gd = mycpu;
726 
727 	crit_enter();
728 	gd->gd_vme_avail -= count;
729 	crit_exit();
730 	KASSERT(gd->gd_vme_base != NULL,
731 		("no reserved entries left, gd_vme_avail = %d",
732 		gd->gd_vme_avail));
733 	return(count);
734 }
735 
736 /*
737  * Release previously reserved map entries for kernel_map.  We do not
738  * attempt to clean up like the normal release function as this would
739  * cause an unnecessary (but probably not fatal) deep procedure call.
740  *
741  * No requirements.
742  */
743 void
744 vm_map_entry_krelease(int count)
745 {
746 	struct globaldata *gd = mycpu;
747 
748 	crit_enter();
749 	gd->gd_vme_avail += count;
750 	crit_exit();
751 }
752 
753 /*
754  * Allocates a VM map entry for insertion.  No entry fields are filled in.
755  *
756  * The entries should have previously been reserved.  The reservation count
757  * is tracked in (*countp).
758  *
759  * No requirements.
760  */
761 static vm_map_entry_t
762 vm_map_entry_create(vm_map_t map, int *countp)
763 {
764 	struct globaldata *gd = mycpu;
765 	vm_map_entry_t entry;
766 
767 	KKASSERT(*countp > 0);
768 	--*countp;
769 	crit_enter();
770 	entry = gd->gd_vme_base;
771 	KASSERT(entry != NULL, ("gd_vme_base NULL! count %d", *countp));
772 	gd->gd_vme_base = entry->next;
773 	crit_exit();
774 
775 	return(entry);
776 }
777 
778 /*
779  * Dispose of a vm_map_entry that is no longer being referenced.
780  *
781  * No requirements.
782  */
783 static void
784 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry, int *countp)
785 {
786 	struct globaldata *gd = mycpu;
787 
788 	KKASSERT(map->hint != entry);
789 	KKASSERT(map->first_free != entry);
790 
791 	++*countp;
792 	crit_enter();
793 	entry->next = gd->gd_vme_base;
794 	gd->gd_vme_base = entry;
795 	crit_exit();
796 }
797 
798 
799 /*
800  * Insert/remove entries from maps.
801  *
802  * The related map must be exclusively locked.
803  * The caller must hold map->token
804  * No other requirements.
805  */
806 static __inline void
807 vm_map_entry_link(vm_map_t map,
808 		  vm_map_entry_t after_where,
809 		  vm_map_entry_t entry)
810 {
811 	ASSERT_VM_MAP_LOCKED(map);
812 
813 	map->nentries++;
814 	entry->prev = after_where;
815 	entry->next = after_where->next;
816 	entry->next->prev = entry;
817 	after_where->next = entry;
818 	if (vm_map_rb_tree_RB_INSERT(&map->rb_root, entry))
819 		panic("vm_map_entry_link: dup addr map %p ent %p", map, entry);
820 }
821 
822 static __inline void
823 vm_map_entry_unlink(vm_map_t map,
824 		    vm_map_entry_t entry)
825 {
826 	vm_map_entry_t prev;
827 	vm_map_entry_t next;
828 
829 	ASSERT_VM_MAP_LOCKED(map);
830 
831 	if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
832 		panic("vm_map_entry_unlink: attempt to mess with "
833 		      "locked entry! %p", entry);
834 	}
835 	prev = entry->prev;
836 	next = entry->next;
837 	next->prev = prev;
838 	prev->next = next;
839 	vm_map_rb_tree_RB_REMOVE(&map->rb_root, entry);
840 	map->nentries--;
841 }
842 
843 /*
844  * Finds the map entry containing (or immediately preceding) the specified
845  * address in the given map.  The entry is returned in (*entry).
846  *
847  * The boolean result indicates whether the address is actually contained
848  * in the map.
849  *
850  * The related map must be locked.
851  * No other requirements.
852  */
853 boolean_t
854 vm_map_lookup_entry(vm_map_t map, vm_offset_t address, vm_map_entry_t *entry)
855 {
856 	vm_map_entry_t tmp;
857 	vm_map_entry_t last;
858 
859 	ASSERT_VM_MAP_LOCKED(map);
860 #if 0
861 	/*
862 	 * XXX TEMPORARILY DISABLED.  For some reason our attempt to revive
863 	 * the hint code with the red-black lookup meets with system crashes
864 	 * and lockups.  We do not yet know why.
865 	 *
866 	 * It is possible that the problem is related to the setting
867 	 * of the hint during map_entry deletion, in the code specified
868 	 * at the GGG comment later on in this file.
869 	 *
870 	 * YYY More likely it's because this function can be called with
871 	 * a shared lock on the map, resulting in map->hint updates possibly
872 	 * racing.  Fixed now but untested.
873 	 */
874 	/*
875 	 * Quickly check the cached hint, there's a good chance of a match.
876 	 */
877 	tmp = map->hint;
878 	cpu_ccfence();
879 	if (tmp != &map->header) {
880 		if (address >= tmp->start && address < tmp->end) {
881 			*entry = tmp;
882 			return(TRUE);
883 		}
884 	}
885 #endif
886 
887 	/*
888 	 * Locate the record from the top of the tree.  'last' tracks the
889 	 * closest prior record and is returned if no match is found, which
890 	 * in binary tree terms means tracking the most recent right-branch
891 	 * taken.  If there is no prior record, &map->header is returned.
892 	 */
893 	last = &map->header;
894 	tmp = RB_ROOT(&map->rb_root);
895 
896 	while (tmp) {
897 		if (address >= tmp->start) {
898 			if (address < tmp->end) {
899 				*entry = tmp;
900 				map->hint = tmp;
901 				return(TRUE);
902 			}
903 			last = tmp;
904 			tmp = RB_RIGHT(tmp, rb_entry);
905 		} else {
906 			tmp = RB_LEFT(tmp, rb_entry);
907 		}
908 	}
909 	*entry = last;
910 	return (FALSE);
911 }
912 
913 /*
914  * Inserts the given whole VM object into the target map at the specified
915  * address range.  The object's size should match that of the address range.
916  *
917  * The map must be exclusively locked.
918  * The object must be held.
919  * The caller must have reserved sufficient vm_map_entry structures.
920  *
921  * If object is non-NULL, ref count must be bumped by caller prior to
922  * making call to account for the new entry.
923  */
924 int
925 vm_map_insert(vm_map_t map, int *countp,
926 	      vm_object_t object, vm_ooffset_t offset,
927 	      vm_offset_t start, vm_offset_t end,
928 	      vm_maptype_t maptype,
929 	      vm_prot_t prot, vm_prot_t max,
930 	      int cow)
931 {
932 	vm_map_entry_t new_entry;
933 	vm_map_entry_t prev_entry;
934 	vm_map_entry_t temp_entry;
935 	vm_eflags_t protoeflags;
936 	int must_drop = 0;
937 
938 	ASSERT_VM_MAP_LOCKED(map);
939 	if (object)
940 		ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
941 
942 	/*
943 	 * Check that the start and end points are not bogus.
944 	 */
945 	if ((start < map->min_offset) || (end > map->max_offset) ||
946 	    (start >= end))
947 		return (KERN_INVALID_ADDRESS);
948 
949 	/*
950 	 * Find the entry prior to the proposed starting address; if it's part
951 	 * of an existing entry, this range is bogus.
952 	 */
953 	if (vm_map_lookup_entry(map, start, &temp_entry))
954 		return (KERN_NO_SPACE);
955 
956 	prev_entry = temp_entry;
957 
958 	/*
959 	 * Assert that the next entry doesn't overlap the end point.
960 	 */
961 
962 	if ((prev_entry->next != &map->header) &&
963 	    (prev_entry->next->start < end))
964 		return (KERN_NO_SPACE);
965 
966 	protoeflags = 0;
967 
968 	if (cow & MAP_COPY_ON_WRITE)
969 		protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
970 
971 	if (cow & MAP_NOFAULT) {
972 		protoeflags |= MAP_ENTRY_NOFAULT;
973 
974 		KASSERT(object == NULL,
975 			("vm_map_insert: paradoxical MAP_NOFAULT request"));
976 	}
977 	if (cow & MAP_DISABLE_SYNCER)
978 		protoeflags |= MAP_ENTRY_NOSYNC;
979 	if (cow & MAP_DISABLE_COREDUMP)
980 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
981 	if (cow & MAP_IS_STACK)
982 		protoeflags |= MAP_ENTRY_STACK;
983 	if (cow & MAP_IS_KSTACK)
984 		protoeflags |= MAP_ENTRY_KSTACK;
985 
986 	lwkt_gettoken(&map->token);
987 
988 	if (object) {
989 		/*
990 		 * When object is non-NULL, it could be shared with another
991 		 * process.  We have to set or clear OBJ_ONEMAPPING
992 		 * appropriately.
993 		 *
994 		 * NOTE: This flag is only applicable to DEFAULT and SWAP
995 		 *	 objects and will already be clear in other types
996 		 *	 of objects, so a shared object lock is ok for
997 		 *	 VNODE objects.
998 		 */
999 		if ((object->ref_count > 1) || (object->shadow_count != 0)) {
1000 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
1001 		}
1002 	}
1003 	else if ((prev_entry != &map->header) &&
1004 		 (prev_entry->eflags == protoeflags) &&
1005 		 (prev_entry->end == start) &&
1006 		 (prev_entry->wired_count == 0) &&
1007 		 prev_entry->maptype == maptype &&
1008 		 ((prev_entry->object.vm_object == NULL) ||
1009 		  vm_object_coalesce(prev_entry->object.vm_object,
1010 				     OFF_TO_IDX(prev_entry->offset),
1011 				     (vm_size_t)(prev_entry->end - prev_entry->start),
1012 				     (vm_size_t)(end - prev_entry->end)))) {
1013 		/*
1014 		 * We were able to extend the object.  Determine if we
1015 		 * can extend the previous map entry to include the
1016 		 * new range as well.
1017 		 */
1018 		if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
1019 		    (prev_entry->protection == prot) &&
1020 		    (prev_entry->max_protection == max)) {
1021 			map->size += (end - prev_entry->end);
1022 			prev_entry->end = end;
1023 			vm_map_simplify_entry(map, prev_entry, countp);
1024 			lwkt_reltoken(&map->token);
1025 			return (KERN_SUCCESS);
1026 		}
1027 
1028 		/*
1029 		 * If we can extend the object but cannot extend the
1030 		 * map entry, we have to create a new map entry.  We
1031 		 * must bump the ref count on the extended object to
1032 		 * account for it.  object may be NULL.
1033 		 */
1034 		object = prev_entry->object.vm_object;
1035 		offset = prev_entry->offset +
1036 			(prev_entry->end - prev_entry->start);
1037 		if (object) {
1038 			vm_object_hold(object);
1039 			vm_object_chain_wait(object);
1040 			vm_object_reference_locked(object);
1041 			must_drop = 1;
1042 		}
1043 	}
1044 
1045 	/*
1046 	 * NOTE: if conditionals fail, object can be NULL here.  This occurs
1047 	 * in things like the buffer map where we manage kva but do not manage
1048 	 * backing objects.
1049 	 */
1050 
1051 	/*
1052 	 * Create a new entry
1053 	 */
1054 
1055 	new_entry = vm_map_entry_create(map, countp);
1056 	new_entry->start = start;
1057 	new_entry->end = end;
1058 
1059 	new_entry->maptype = maptype;
1060 	new_entry->eflags = protoeflags;
1061 	new_entry->object.vm_object = object;
1062 	new_entry->offset = offset;
1063 	new_entry->aux.master_pde = 0;
1064 
1065 	new_entry->inheritance = VM_INHERIT_DEFAULT;
1066 	new_entry->protection = prot;
1067 	new_entry->max_protection = max;
1068 	new_entry->wired_count = 0;
1069 
1070 	/*
1071 	 * Insert the new entry into the list
1072 	 */
1073 
1074 	vm_map_entry_link(map, prev_entry, new_entry);
1075 	map->size += new_entry->end - new_entry->start;
1076 
1077 	/*
1078 	 * Update the free space hint.  Entries cannot overlap.
1079 	 * An exact comparison is needed to avoid matching
1080 	 * against the map->header.
1081 	 */
1082 	if ((map->first_free == prev_entry) &&
1083 	    (prev_entry->end == new_entry->start)) {
1084 		map->first_free = new_entry;
1085 	}
1086 
1087 #if 0
1088 	/*
1089 	 * Temporarily removed to avoid MAP_STACK panic, due to
1090 	 * MAP_STACK being a huge hack.  Will be added back in
1091 	 * when MAP_STACK (and the user stack mapping) is fixed.
1092 	 */
1093 	/*
1094 	 * It may be possible to simplify the entry
1095 	 */
1096 	vm_map_simplify_entry(map, new_entry, countp);
1097 #endif
1098 
1099 	/*
1100 	 * Try to pre-populate the page table.  Mappings governed by virtual
1101 	 * page tables cannot be prepopulated without a lot of work, so
1102 	 * don't try.
1103 	 */
1104 	if ((cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) &&
1105 	    maptype != VM_MAPTYPE_VPAGETABLE) {
1106 		int dorelock = 0;
1107 		if (vm_map_relock_enable && (cow & MAP_PREFAULT_RELOCK)) {
1108 			dorelock = 1;
1109 			vm_object_lock_swap();
1110 			vm_object_drop(object);
1111 		}
1112 		pmap_object_init_pt(map->pmap, start, prot,
1113 				    object, OFF_TO_IDX(offset), end - start,
1114 				    cow & MAP_PREFAULT_PARTIAL);
1115 		if (dorelock) {
1116 			vm_object_hold(object);
1117 			vm_object_lock_swap();
1118 		}
1119 	}
1120 	if (must_drop)
1121 		vm_object_drop(object);
1122 
1123 	lwkt_reltoken(&map->token);
1124 	return (KERN_SUCCESS);
1125 }
1126 
1127 /*
1128  * Find sufficient space for `length' bytes in the given map, starting at
1129  * `start'.  Returns 0 on success, 1 on no space.
1130  *
1131  * This function will returned an arbitrarily aligned pointer.  If no
1132  * particular alignment is required you should pass align as 1.  Note that
1133  * the map may return PAGE_SIZE aligned pointers if all the lengths used in
1134  * the map are a multiple of PAGE_SIZE, even if you pass a smaller align
1135  * argument.
1136  *
1137  * 'align' should be a power of 2 but is not required to be.
1138  *
1139  * The map must be exclusively locked.
1140  * No other requirements.
1141  */
1142 int
1143 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
1144 		 vm_size_t align, int flags, vm_offset_t *addr)
1145 {
1146 	vm_map_entry_t entry, next;
1147 	vm_offset_t end;
1148 	vm_offset_t align_mask;
1149 
1150 	if (start < map->min_offset)
1151 		start = map->min_offset;
1152 	if (start > map->max_offset)
1153 		return (1);
1154 
1155 	/*
1156 	 * If the alignment is not a power of 2 we will have to use
1157 	 * a mod/division, set align_mask to a special value.
1158 	 */
1159 	if ((align | (align - 1)) + 1 != (align << 1))
1160 		align_mask = (vm_offset_t)-1;
1161 	else
1162 		align_mask = align - 1;
1163 
1164 	/*
1165 	 * Look for the first possible address; if there's already something
1166 	 * at this address, we have to start after it.
1167 	 */
1168 	if (start == map->min_offset) {
1169 		if ((entry = map->first_free) != &map->header)
1170 			start = entry->end;
1171 	} else {
1172 		vm_map_entry_t tmp;
1173 
1174 		if (vm_map_lookup_entry(map, start, &tmp))
1175 			start = tmp->end;
1176 		entry = tmp;
1177 	}
1178 
1179 	/*
1180 	 * Look through the rest of the map, trying to fit a new region in the
1181 	 * gap between existing regions, or after the very last region.
1182 	 */
1183 	for (;; start = (entry = next)->end) {
1184 		/*
1185 		 * Adjust the proposed start by the requested alignment,
1186 		 * be sure that we didn't wrap the address.
1187 		 */
1188 		if (align_mask == (vm_offset_t)-1)
1189 			end = ((start + align - 1) / align) * align;
1190 		else
1191 			end = (start + align_mask) & ~align_mask;
1192 		if (end < start)
1193 			return (1);
1194 		start = end;
1195 		/*
1196 		 * Find the end of the proposed new region.  Be sure we didn't
1197 		 * go beyond the end of the map, or wrap around the address.
1198 		 * Then check to see if this is the last entry or if the
1199 		 * proposed end fits in the gap between this and the next
1200 		 * entry.
1201 		 */
1202 		end = start + length;
1203 		if (end > map->max_offset || end < start)
1204 			return (1);
1205 		next = entry->next;
1206 
1207 		/*
1208 		 * If the next entry's start address is beyond the desired
1209 		 * end address we may have found a good entry.
1210 		 *
1211 		 * If the next entry is a stack mapping we do not map into
1212 		 * the stack's reserved space.
1213 		 *
1214 		 * XXX continue to allow mapping into the stack's reserved
1215 		 * space if doing a MAP_STACK mapping inside a MAP_STACK
1216 		 * mapping, for backwards compatibility.  But the caller
1217 		 * really should use MAP_STACK | MAP_TRYFIXED if they
1218 		 * want to do that.
1219 		 */
1220 		if (next == &map->header)
1221 			break;
1222 		if (next->start >= end) {
1223 			if ((next->eflags & MAP_ENTRY_STACK) == 0)
1224 				break;
1225 			if (flags & MAP_STACK)
1226 				break;
1227 			if (next->start - next->aux.avail_ssize >= end)
1228 				break;
1229 		}
1230 	}
1231 	map->hint = entry;
1232 
1233 	/*
1234 	 * Grow the kernel_map if necessary.  pmap_growkernel() will panic
1235 	 * if it fails.  The kernel_map is locked and nothing can steal
1236 	 * our address space if pmap_growkernel() blocks.
1237 	 *
1238 	 * NOTE: This may be unconditionally called for kldload areas on
1239 	 *	 x86_64 because these do not bump kernel_vm_end (which would
1240 	 *	 fill 128G worth of page tables!).  Therefore we must not
1241 	 *	 retry.
1242 	 */
1243 	if (map == &kernel_map) {
1244 		vm_offset_t kstop;
1245 
1246 		kstop = round_page(start + length);
1247 		if (kstop > kernel_vm_end)
1248 			pmap_growkernel(start, kstop);
1249 	}
1250 	*addr = start;
1251 	return (0);
1252 }
1253 
1254 /*
1255  * vm_map_find finds an unallocated region in the target address map with
1256  * the given length and allocates it.  The search is defined to be first-fit
1257  * from the specified address; the region found is returned in the same
1258  * parameter.
1259  *
1260  * If object is non-NULL, ref count must be bumped by caller
1261  * prior to making call to account for the new entry.
1262  *
1263  * No requirements.  This function will lock the map temporarily.
1264  */
1265 int
1266 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1267 	    vm_offset_t *addr,	vm_size_t length, vm_size_t align,
1268 	    boolean_t fitit,
1269 	    vm_maptype_t maptype,
1270 	    vm_prot_t prot, vm_prot_t max,
1271 	    int cow)
1272 {
1273 	vm_offset_t start;
1274 	int result;
1275 	int count;
1276 
1277 	start = *addr;
1278 
1279 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1280 	vm_map_lock(map);
1281 	if (object)
1282 		vm_object_hold(object);
1283 	if (fitit) {
1284 		if (vm_map_findspace(map, start, length, align, 0, addr)) {
1285 			if (object)
1286 				vm_object_drop(object);
1287 			vm_map_unlock(map);
1288 			vm_map_entry_release(count);
1289 			return (KERN_NO_SPACE);
1290 		}
1291 		start = *addr;
1292 	}
1293 	result = vm_map_insert(map, &count, object, offset,
1294 			       start, start + length,
1295 			       maptype,
1296 			       prot, max,
1297 			       cow);
1298 	if (object)
1299 		vm_object_drop(object);
1300 	vm_map_unlock(map);
1301 	vm_map_entry_release(count);
1302 
1303 	return (result);
1304 }
1305 
1306 /*
1307  * Simplify the given map entry by merging with either neighbor.  This
1308  * routine also has the ability to merge with both neighbors.
1309  *
1310  * This routine guarentees that the passed entry remains valid (though
1311  * possibly extended).  When merging, this routine may delete one or
1312  * both neighbors.  No action is taken on entries which have their
1313  * in-transition flag set.
1314  *
1315  * The map must be exclusively locked.
1316  */
1317 void
1318 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry, int *countp)
1319 {
1320 	vm_map_entry_t next, prev;
1321 	vm_size_t prevsize, esize;
1322 
1323 	if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1324 		++mycpu->gd_cnt.v_intrans_coll;
1325 		return;
1326 	}
1327 
1328 	if (entry->maptype == VM_MAPTYPE_SUBMAP)
1329 		return;
1330 
1331 	prev = entry->prev;
1332 	if (prev != &map->header) {
1333 		prevsize = prev->end - prev->start;
1334 		if ( (prev->end == entry->start) &&
1335 		     (prev->maptype == entry->maptype) &&
1336 		     (prev->object.vm_object == entry->object.vm_object) &&
1337 		     (!prev->object.vm_object ||
1338 			(prev->offset + prevsize == entry->offset)) &&
1339 		     (prev->eflags == entry->eflags) &&
1340 		     (prev->protection == entry->protection) &&
1341 		     (prev->max_protection == entry->max_protection) &&
1342 		     (prev->inheritance == entry->inheritance) &&
1343 		     (prev->wired_count == entry->wired_count)) {
1344 			if (map->first_free == prev)
1345 				map->first_free = entry;
1346 			if (map->hint == prev)
1347 				map->hint = entry;
1348 			vm_map_entry_unlink(map, prev);
1349 			entry->start = prev->start;
1350 			entry->offset = prev->offset;
1351 			if (prev->object.vm_object)
1352 				vm_object_deallocate(prev->object.vm_object);
1353 			vm_map_entry_dispose(map, prev, countp);
1354 		}
1355 	}
1356 
1357 	next = entry->next;
1358 	if (next != &map->header) {
1359 		esize = entry->end - entry->start;
1360 		if ((entry->end == next->start) &&
1361 		    (next->maptype == entry->maptype) &&
1362 		    (next->object.vm_object == entry->object.vm_object) &&
1363 		     (!entry->object.vm_object ||
1364 			(entry->offset + esize == next->offset)) &&
1365 		    (next->eflags == entry->eflags) &&
1366 		    (next->protection == entry->protection) &&
1367 		    (next->max_protection == entry->max_protection) &&
1368 		    (next->inheritance == entry->inheritance) &&
1369 		    (next->wired_count == entry->wired_count)) {
1370 			if (map->first_free == next)
1371 				map->first_free = entry;
1372 			if (map->hint == next)
1373 				map->hint = entry;
1374 			vm_map_entry_unlink(map, next);
1375 			entry->end = next->end;
1376 			if (next->object.vm_object)
1377 				vm_object_deallocate(next->object.vm_object);
1378 			vm_map_entry_dispose(map, next, countp);
1379 	        }
1380 	}
1381 }
1382 
1383 /*
1384  * Asserts that the given entry begins at or after the specified address.
1385  * If necessary, it splits the entry into two.
1386  */
1387 #define vm_map_clip_start(map, entry, startaddr, countp)		\
1388 {									\
1389 	if (startaddr > entry->start)					\
1390 		_vm_map_clip_start(map, entry, startaddr, countp);	\
1391 }
1392 
1393 /*
1394  * This routine is called only when it is known that the entry must be split.
1395  *
1396  * The map must be exclusively locked.
1397  */
1398 static void
1399 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start,
1400 		   int *countp)
1401 {
1402 	vm_map_entry_t new_entry;
1403 
1404 	/*
1405 	 * Split off the front portion -- note that we must insert the new
1406 	 * entry BEFORE this one, so that this entry has the specified
1407 	 * starting address.
1408 	 */
1409 
1410 	vm_map_simplify_entry(map, entry, countp);
1411 
1412 	/*
1413 	 * If there is no object backing this entry, we might as well create
1414 	 * one now.  If we defer it, an object can get created after the map
1415 	 * is clipped, and individual objects will be created for the split-up
1416 	 * map.  This is a bit of a hack, but is also about the best place to
1417 	 * put this improvement.
1418 	 */
1419 	if (entry->object.vm_object == NULL && !map->system_map) {
1420 		vm_map_entry_allocate_object(entry);
1421 	}
1422 
1423 	new_entry = vm_map_entry_create(map, countp);
1424 	*new_entry = *entry;
1425 
1426 	new_entry->end = start;
1427 	entry->offset += (start - entry->start);
1428 	entry->start = start;
1429 
1430 	vm_map_entry_link(map, entry->prev, new_entry);
1431 
1432 	switch(entry->maptype) {
1433 	case VM_MAPTYPE_NORMAL:
1434 	case VM_MAPTYPE_VPAGETABLE:
1435 		if (new_entry->object.vm_object) {
1436 			vm_object_hold(new_entry->object.vm_object);
1437 			vm_object_chain_wait(new_entry->object.vm_object);
1438 			vm_object_reference_locked(new_entry->object.vm_object);
1439 			vm_object_drop(new_entry->object.vm_object);
1440 		}
1441 		break;
1442 	default:
1443 		break;
1444 	}
1445 }
1446 
1447 /*
1448  * Asserts that the given entry ends at or before the specified address.
1449  * If necessary, it splits the entry into two.
1450  *
1451  * The map must be exclusively locked.
1452  */
1453 #define vm_map_clip_end(map, entry, endaddr, countp)		\
1454 {								\
1455 	if (endaddr < entry->end)				\
1456 		_vm_map_clip_end(map, entry, endaddr, countp);	\
1457 }
1458 
1459 /*
1460  * This routine is called only when it is known that the entry must be split.
1461  *
1462  * The map must be exclusively locked.
1463  */
1464 static void
1465 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end,
1466 		 int *countp)
1467 {
1468 	vm_map_entry_t new_entry;
1469 
1470 	/*
1471 	 * If there is no object backing this entry, we might as well create
1472 	 * one now.  If we defer it, an object can get created after the map
1473 	 * is clipped, and individual objects will be created for the split-up
1474 	 * map.  This is a bit of a hack, but is also about the best place to
1475 	 * put this improvement.
1476 	 */
1477 
1478 	if (entry->object.vm_object == NULL && !map->system_map) {
1479 		vm_map_entry_allocate_object(entry);
1480 	}
1481 
1482 	/*
1483 	 * Create a new entry and insert it AFTER the specified entry
1484 	 */
1485 
1486 	new_entry = vm_map_entry_create(map, countp);
1487 	*new_entry = *entry;
1488 
1489 	new_entry->start = entry->end = end;
1490 	new_entry->offset += (end - entry->start);
1491 
1492 	vm_map_entry_link(map, entry, new_entry);
1493 
1494 	switch(entry->maptype) {
1495 	case VM_MAPTYPE_NORMAL:
1496 	case VM_MAPTYPE_VPAGETABLE:
1497 		if (new_entry->object.vm_object) {
1498 			vm_object_hold(new_entry->object.vm_object);
1499 			vm_object_chain_wait(new_entry->object.vm_object);
1500 			vm_object_reference_locked(new_entry->object.vm_object);
1501 			vm_object_drop(new_entry->object.vm_object);
1502 		}
1503 		break;
1504 	default:
1505 		break;
1506 	}
1507 }
1508 
1509 /*
1510  * Asserts that the starting and ending region addresses fall within the
1511  * valid range for the map.
1512  */
1513 #define	VM_MAP_RANGE_CHECK(map, start, end)	\
1514 {						\
1515 	if (start < vm_map_min(map))		\
1516 		start = vm_map_min(map);	\
1517 	if (end > vm_map_max(map))		\
1518 		end = vm_map_max(map);		\
1519 	if (start > end)			\
1520 		start = end;			\
1521 }
1522 
1523 /*
1524  * Used to block when an in-transition collison occurs.  The map
1525  * is unlocked for the sleep and relocked before the return.
1526  */
1527 void
1528 vm_map_transition_wait(vm_map_t map)
1529 {
1530 	tsleep_interlock(map, 0);
1531 	vm_map_unlock(map);
1532 	tsleep(map, PINTERLOCKED, "vment", 0);
1533 	vm_map_lock(map);
1534 }
1535 
1536 /*
1537  * When we do blocking operations with the map lock held it is
1538  * possible that a clip might have occured on our in-transit entry,
1539  * requiring an adjustment to the entry in our loop.  These macros
1540  * help the pageable and clip_range code deal with the case.  The
1541  * conditional costs virtually nothing if no clipping has occured.
1542  */
1543 
1544 #define CLIP_CHECK_BACK(entry, save_start)		\
1545     do {						\
1546 	    while (entry->start != save_start) {	\
1547 		    entry = entry->prev;		\
1548 		    KASSERT(entry != &map->header, ("bad entry clip")); \
1549 	    }						\
1550     } while(0)
1551 
1552 #define CLIP_CHECK_FWD(entry, save_end)			\
1553     do {						\
1554 	    while (entry->end != save_end) {		\
1555 		    entry = entry->next;		\
1556 		    KASSERT(entry != &map->header, ("bad entry clip")); \
1557 	    }						\
1558     } while(0)
1559 
1560 
1561 /*
1562  * Clip the specified range and return the base entry.  The
1563  * range may cover several entries starting at the returned base
1564  * and the first and last entry in the covering sequence will be
1565  * properly clipped to the requested start and end address.
1566  *
1567  * If no holes are allowed you should pass the MAP_CLIP_NO_HOLES
1568  * flag.
1569  *
1570  * The MAP_ENTRY_IN_TRANSITION flag will be set for the entries
1571  * covered by the requested range.
1572  *
1573  * The map must be exclusively locked on entry and will remain locked
1574  * on return. If no range exists or the range contains holes and you
1575  * specified that no holes were allowed, NULL will be returned.  This
1576  * routine may temporarily unlock the map in order avoid a deadlock when
1577  * sleeping.
1578  */
1579 static
1580 vm_map_entry_t
1581 vm_map_clip_range(vm_map_t map, vm_offset_t start, vm_offset_t end,
1582 		  int *countp, int flags)
1583 {
1584 	vm_map_entry_t start_entry;
1585 	vm_map_entry_t entry;
1586 
1587 	/*
1588 	 * Locate the entry and effect initial clipping.  The in-transition
1589 	 * case does not occur very often so do not try to optimize it.
1590 	 */
1591 again:
1592 	if (vm_map_lookup_entry(map, start, &start_entry) == FALSE)
1593 		return (NULL);
1594 	entry = start_entry;
1595 	if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1596 		entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1597 		++mycpu->gd_cnt.v_intrans_coll;
1598 		++mycpu->gd_cnt.v_intrans_wait;
1599 		vm_map_transition_wait(map);
1600 		/*
1601 		 * entry and/or start_entry may have been clipped while
1602 		 * we slept, or may have gone away entirely.  We have
1603 		 * to restart from the lookup.
1604 		 */
1605 		goto again;
1606 	}
1607 
1608 	/*
1609 	 * Since we hold an exclusive map lock we do not have to restart
1610 	 * after clipping, even though clipping may block in zalloc.
1611 	 */
1612 	vm_map_clip_start(map, entry, start, countp);
1613 	vm_map_clip_end(map, entry, end, countp);
1614 	entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1615 
1616 	/*
1617 	 * Scan entries covered by the range.  When working on the next
1618 	 * entry a restart need only re-loop on the current entry which
1619 	 * we have already locked, since 'next' may have changed.  Also,
1620 	 * even though entry is safe, it may have been clipped so we
1621 	 * have to iterate forwards through the clip after sleeping.
1622 	 */
1623 	while (entry->next != &map->header && entry->next->start < end) {
1624 		vm_map_entry_t next = entry->next;
1625 
1626 		if (flags & MAP_CLIP_NO_HOLES) {
1627 			if (next->start > entry->end) {
1628 				vm_map_unclip_range(map, start_entry,
1629 					start, entry->end, countp, flags);
1630 				return(NULL);
1631 			}
1632 		}
1633 
1634 		if (next->eflags & MAP_ENTRY_IN_TRANSITION) {
1635 			vm_offset_t save_end = entry->end;
1636 			next->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1637 			++mycpu->gd_cnt.v_intrans_coll;
1638 			++mycpu->gd_cnt.v_intrans_wait;
1639 			vm_map_transition_wait(map);
1640 
1641 			/*
1642 			 * clips might have occured while we blocked.
1643 			 */
1644 			CLIP_CHECK_FWD(entry, save_end);
1645 			CLIP_CHECK_BACK(start_entry, start);
1646 			continue;
1647 		}
1648 		/*
1649 		 * No restart necessary even though clip_end may block, we
1650 		 * are holding the map lock.
1651 		 */
1652 		vm_map_clip_end(map, next, end, countp);
1653 		next->eflags |= MAP_ENTRY_IN_TRANSITION;
1654 		entry = next;
1655 	}
1656 	if (flags & MAP_CLIP_NO_HOLES) {
1657 		if (entry->end != end) {
1658 			vm_map_unclip_range(map, start_entry,
1659 				start, entry->end, countp, flags);
1660 			return(NULL);
1661 		}
1662 	}
1663 	return(start_entry);
1664 }
1665 
1666 /*
1667  * Undo the effect of vm_map_clip_range().  You should pass the same
1668  * flags and the same range that you passed to vm_map_clip_range().
1669  * This code will clear the in-transition flag on the entries and
1670  * wake up anyone waiting.  This code will also simplify the sequence
1671  * and attempt to merge it with entries before and after the sequence.
1672  *
1673  * The map must be locked on entry and will remain locked on return.
1674  *
1675  * Note that you should also pass the start_entry returned by
1676  * vm_map_clip_range().  However, if you block between the two calls
1677  * with the map unlocked please be aware that the start_entry may
1678  * have been clipped and you may need to scan it backwards to find
1679  * the entry corresponding with the original start address.  You are
1680  * responsible for this, vm_map_unclip_range() expects the correct
1681  * start_entry to be passed to it and will KASSERT otherwise.
1682  */
1683 static
1684 void
1685 vm_map_unclip_range(vm_map_t map, vm_map_entry_t start_entry,
1686 		    vm_offset_t start, vm_offset_t end,
1687 		    int *countp, int flags)
1688 {
1689 	vm_map_entry_t entry;
1690 
1691 	entry = start_entry;
1692 
1693 	KASSERT(entry->start == start, ("unclip_range: illegal base entry"));
1694 	while (entry != &map->header && entry->start < end) {
1695 		KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
1696 			("in-transition flag not set during unclip on: %p",
1697 			entry));
1698 		KASSERT(entry->end <= end,
1699 			("unclip_range: tail wasn't clipped"));
1700 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1701 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1702 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1703 			wakeup(map);
1704 		}
1705 		entry = entry->next;
1706 	}
1707 
1708 	/*
1709 	 * Simplification does not block so there is no restart case.
1710 	 */
1711 	entry = start_entry;
1712 	while (entry != &map->header && entry->start < end) {
1713 		vm_map_simplify_entry(map, entry, countp);
1714 		entry = entry->next;
1715 	}
1716 }
1717 
1718 /*
1719  * Mark the given range as handled by a subordinate map.
1720  *
1721  * This range must have been created with vm_map_find(), and no other
1722  * operations may have been performed on this range prior to calling
1723  * vm_map_submap().
1724  *
1725  * Submappings cannot be removed.
1726  *
1727  * No requirements.
1728  */
1729 int
1730 vm_map_submap(vm_map_t map, vm_offset_t start, vm_offset_t end, vm_map_t submap)
1731 {
1732 	vm_map_entry_t entry;
1733 	int result = KERN_INVALID_ARGUMENT;
1734 	int count;
1735 
1736 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1737 	vm_map_lock(map);
1738 
1739 	VM_MAP_RANGE_CHECK(map, start, end);
1740 
1741 	if (vm_map_lookup_entry(map, start, &entry)) {
1742 		vm_map_clip_start(map, entry, start, &count);
1743 	} else {
1744 		entry = entry->next;
1745 	}
1746 
1747 	vm_map_clip_end(map, entry, end, &count);
1748 
1749 	if ((entry->start == start) && (entry->end == end) &&
1750 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1751 	    (entry->object.vm_object == NULL)) {
1752 		entry->object.sub_map = submap;
1753 		entry->maptype = VM_MAPTYPE_SUBMAP;
1754 		result = KERN_SUCCESS;
1755 	}
1756 	vm_map_unlock(map);
1757 	vm_map_entry_release(count);
1758 
1759 	return (result);
1760 }
1761 
1762 /*
1763  * Sets the protection of the specified address region in the target map.
1764  * If "set_max" is specified, the maximum protection is to be set;
1765  * otherwise, only the current protection is affected.
1766  *
1767  * The protection is not applicable to submaps, but is applicable to normal
1768  * maps and maps governed by virtual page tables.  For example, when operating
1769  * on a virtual page table our protection basically controls how COW occurs
1770  * on the backing object, whereas the virtual page table abstraction itself
1771  * is an abstraction for userland.
1772  *
1773  * No requirements.
1774  */
1775 int
1776 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1777 	       vm_prot_t new_prot, boolean_t set_max)
1778 {
1779 	vm_map_entry_t current;
1780 	vm_map_entry_t entry;
1781 	int count;
1782 
1783 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1784 	vm_map_lock(map);
1785 
1786 	VM_MAP_RANGE_CHECK(map, start, end);
1787 
1788 	if (vm_map_lookup_entry(map, start, &entry)) {
1789 		vm_map_clip_start(map, entry, start, &count);
1790 	} else {
1791 		entry = entry->next;
1792 	}
1793 
1794 	/*
1795 	 * Make a first pass to check for protection violations.
1796 	 */
1797 	current = entry;
1798 	while ((current != &map->header) && (current->start < end)) {
1799 		if (current->maptype == VM_MAPTYPE_SUBMAP) {
1800 			vm_map_unlock(map);
1801 			vm_map_entry_release(count);
1802 			return (KERN_INVALID_ARGUMENT);
1803 		}
1804 		if ((new_prot & current->max_protection) != new_prot) {
1805 			vm_map_unlock(map);
1806 			vm_map_entry_release(count);
1807 			return (KERN_PROTECTION_FAILURE);
1808 		}
1809 		current = current->next;
1810 	}
1811 
1812 	/*
1813 	 * Go back and fix up protections. [Note that clipping is not
1814 	 * necessary the second time.]
1815 	 */
1816 	current = entry;
1817 
1818 	while ((current != &map->header) && (current->start < end)) {
1819 		vm_prot_t old_prot;
1820 
1821 		vm_map_clip_end(map, current, end, &count);
1822 
1823 		old_prot = current->protection;
1824 		if (set_max) {
1825 			current->protection =
1826 			    (current->max_protection = new_prot) &
1827 			    old_prot;
1828 		} else {
1829 			current->protection = new_prot;
1830 		}
1831 
1832 		/*
1833 		 * Update physical map if necessary. Worry about copy-on-write
1834 		 * here -- CHECK THIS XXX
1835 		 */
1836 
1837 		if (current->protection != old_prot) {
1838 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1839 							VM_PROT_ALL)
1840 
1841 			pmap_protect(map->pmap, current->start,
1842 			    current->end,
1843 			    current->protection & MASK(current));
1844 #undef	MASK
1845 		}
1846 
1847 		vm_map_simplify_entry(map, current, &count);
1848 
1849 		current = current->next;
1850 	}
1851 
1852 	vm_map_unlock(map);
1853 	vm_map_entry_release(count);
1854 	return (KERN_SUCCESS);
1855 }
1856 
1857 /*
1858  * This routine traverses a processes map handling the madvise
1859  * system call.  Advisories are classified as either those effecting
1860  * the vm_map_entry structure, or those effecting the underlying
1861  * objects.
1862  *
1863  * The <value> argument is used for extended madvise calls.
1864  *
1865  * No requirements.
1866  */
1867 int
1868 vm_map_madvise(vm_map_t map, vm_offset_t start, vm_offset_t end,
1869 	       int behav, off_t value)
1870 {
1871 	vm_map_entry_t current, entry;
1872 	int modify_map = 0;
1873 	int error = 0;
1874 	int count;
1875 
1876 	/*
1877 	 * Some madvise calls directly modify the vm_map_entry, in which case
1878 	 * we need to use an exclusive lock on the map and we need to perform
1879 	 * various clipping operations.  Otherwise we only need a read-lock
1880 	 * on the map.
1881 	 */
1882 
1883 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1884 
1885 	switch(behav) {
1886 	case MADV_NORMAL:
1887 	case MADV_SEQUENTIAL:
1888 	case MADV_RANDOM:
1889 	case MADV_NOSYNC:
1890 	case MADV_AUTOSYNC:
1891 	case MADV_NOCORE:
1892 	case MADV_CORE:
1893 	case MADV_SETMAP:
1894 	case MADV_INVAL:
1895 		modify_map = 1;
1896 		vm_map_lock(map);
1897 		break;
1898 	case MADV_WILLNEED:
1899 	case MADV_DONTNEED:
1900 	case MADV_FREE:
1901 		vm_map_lock_read(map);
1902 		break;
1903 	default:
1904 		vm_map_entry_release(count);
1905 		return (EINVAL);
1906 	}
1907 
1908 	/*
1909 	 * Locate starting entry and clip if necessary.
1910 	 */
1911 
1912 	VM_MAP_RANGE_CHECK(map, start, end);
1913 
1914 	if (vm_map_lookup_entry(map, start, &entry)) {
1915 		if (modify_map)
1916 			vm_map_clip_start(map, entry, start, &count);
1917 	} else {
1918 		entry = entry->next;
1919 	}
1920 
1921 	if (modify_map) {
1922 		/*
1923 		 * madvise behaviors that are implemented in the vm_map_entry.
1924 		 *
1925 		 * We clip the vm_map_entry so that behavioral changes are
1926 		 * limited to the specified address range.
1927 		 */
1928 		for (current = entry;
1929 		     (current != &map->header) && (current->start < end);
1930 		     current = current->next
1931 		) {
1932 			if (current->maptype == VM_MAPTYPE_SUBMAP)
1933 				continue;
1934 
1935 			vm_map_clip_end(map, current, end, &count);
1936 
1937 			switch (behav) {
1938 			case MADV_NORMAL:
1939 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1940 				break;
1941 			case MADV_SEQUENTIAL:
1942 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1943 				break;
1944 			case MADV_RANDOM:
1945 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1946 				break;
1947 			case MADV_NOSYNC:
1948 				current->eflags |= MAP_ENTRY_NOSYNC;
1949 				break;
1950 			case MADV_AUTOSYNC:
1951 				current->eflags &= ~MAP_ENTRY_NOSYNC;
1952 				break;
1953 			case MADV_NOCORE:
1954 				current->eflags |= MAP_ENTRY_NOCOREDUMP;
1955 				break;
1956 			case MADV_CORE:
1957 				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
1958 				break;
1959 			case MADV_INVAL:
1960 				/*
1961 				 * Invalidate the related pmap entries, used
1962 				 * to flush portions of the real kernel's
1963 				 * pmap when the caller has removed or
1964 				 * modified existing mappings in a virtual
1965 				 * page table.
1966 				 */
1967 				pmap_remove(map->pmap,
1968 					    current->start, current->end);
1969 				break;
1970 			case MADV_SETMAP:
1971 				/*
1972 				 * Set the page directory page for a map
1973 				 * governed by a virtual page table.  Mark
1974 				 * the entry as being governed by a virtual
1975 				 * page table if it is not.
1976 				 *
1977 				 * XXX the page directory page is stored
1978 				 * in the avail_ssize field if the map_entry.
1979 				 *
1980 				 * XXX the map simplification code does not
1981 				 * compare this field so weird things may
1982 				 * happen if you do not apply this function
1983 				 * to the entire mapping governed by the
1984 				 * virtual page table.
1985 				 */
1986 				if (current->maptype != VM_MAPTYPE_VPAGETABLE) {
1987 					error = EINVAL;
1988 					break;
1989 				}
1990 				current->aux.master_pde = value;
1991 				pmap_remove(map->pmap,
1992 					    current->start, current->end);
1993 				break;
1994 			default:
1995 				error = EINVAL;
1996 				break;
1997 			}
1998 			vm_map_simplify_entry(map, current, &count);
1999 		}
2000 		vm_map_unlock(map);
2001 	} else {
2002 		vm_pindex_t pindex;
2003 		int count;
2004 
2005 		/*
2006 		 * madvise behaviors that are implemented in the underlying
2007 		 * vm_object.
2008 		 *
2009 		 * Since we don't clip the vm_map_entry, we have to clip
2010 		 * the vm_object pindex and count.
2011 		 *
2012 		 * NOTE!  We currently do not support these functions on
2013 		 * virtual page tables.
2014 		 */
2015 		for (current = entry;
2016 		     (current != &map->header) && (current->start < end);
2017 		     current = current->next
2018 		) {
2019 			vm_offset_t useStart;
2020 
2021 			if (current->maptype != VM_MAPTYPE_NORMAL)
2022 				continue;
2023 
2024 			pindex = OFF_TO_IDX(current->offset);
2025 			count = atop(current->end - current->start);
2026 			useStart = current->start;
2027 
2028 			if (current->start < start) {
2029 				pindex += atop(start - current->start);
2030 				count -= atop(start - current->start);
2031 				useStart = start;
2032 			}
2033 			if (current->end > end)
2034 				count -= atop(current->end - end);
2035 
2036 			if (count <= 0)
2037 				continue;
2038 
2039 			vm_object_madvise(current->object.vm_object,
2040 					  pindex, count, behav);
2041 
2042 			/*
2043 			 * Try to populate the page table.  Mappings governed
2044 			 * by virtual page tables cannot be pre-populated
2045 			 * without a lot of work so don't try.
2046 			 */
2047 			if (behav == MADV_WILLNEED &&
2048 			    current->maptype != VM_MAPTYPE_VPAGETABLE) {
2049 				pmap_object_init_pt(
2050 				    map->pmap,
2051 				    useStart,
2052 				    current->protection,
2053 				    current->object.vm_object,
2054 				    pindex,
2055 				    (count << PAGE_SHIFT),
2056 				    MAP_PREFAULT_MADVISE
2057 				);
2058 			}
2059 		}
2060 		vm_map_unlock_read(map);
2061 	}
2062 	vm_map_entry_release(count);
2063 	return(error);
2064 }
2065 
2066 
2067 /*
2068  * Sets the inheritance of the specified address range in the target map.
2069  * Inheritance affects how the map will be shared with child maps at the
2070  * time of vm_map_fork.
2071  */
2072 int
2073 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2074 	       vm_inherit_t new_inheritance)
2075 {
2076 	vm_map_entry_t entry;
2077 	vm_map_entry_t temp_entry;
2078 	int count;
2079 
2080 	switch (new_inheritance) {
2081 	case VM_INHERIT_NONE:
2082 	case VM_INHERIT_COPY:
2083 	case VM_INHERIT_SHARE:
2084 		break;
2085 	default:
2086 		return (KERN_INVALID_ARGUMENT);
2087 	}
2088 
2089 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2090 	vm_map_lock(map);
2091 
2092 	VM_MAP_RANGE_CHECK(map, start, end);
2093 
2094 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
2095 		entry = temp_entry;
2096 		vm_map_clip_start(map, entry, start, &count);
2097 	} else
2098 		entry = temp_entry->next;
2099 
2100 	while ((entry != &map->header) && (entry->start < end)) {
2101 		vm_map_clip_end(map, entry, end, &count);
2102 
2103 		entry->inheritance = new_inheritance;
2104 
2105 		vm_map_simplify_entry(map, entry, &count);
2106 
2107 		entry = entry->next;
2108 	}
2109 	vm_map_unlock(map);
2110 	vm_map_entry_release(count);
2111 	return (KERN_SUCCESS);
2112 }
2113 
2114 /*
2115  * Implement the semantics of mlock
2116  */
2117 int
2118 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t real_end,
2119 	      boolean_t new_pageable)
2120 {
2121 	vm_map_entry_t entry;
2122 	vm_map_entry_t start_entry;
2123 	vm_offset_t end;
2124 	int rv = KERN_SUCCESS;
2125 	int count;
2126 
2127 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2128 	vm_map_lock(map);
2129 	VM_MAP_RANGE_CHECK(map, start, real_end);
2130 	end = real_end;
2131 
2132 	start_entry = vm_map_clip_range(map, start, end, &count,
2133 					MAP_CLIP_NO_HOLES);
2134 	if (start_entry == NULL) {
2135 		vm_map_unlock(map);
2136 		vm_map_entry_release(count);
2137 		return (KERN_INVALID_ADDRESS);
2138 	}
2139 
2140 	if (new_pageable == 0) {
2141 		entry = start_entry;
2142 		while ((entry != &map->header) && (entry->start < end)) {
2143 			vm_offset_t save_start;
2144 			vm_offset_t save_end;
2145 
2146 			/*
2147 			 * Already user wired or hard wired (trivial cases)
2148 			 */
2149 			if (entry->eflags & MAP_ENTRY_USER_WIRED) {
2150 				entry = entry->next;
2151 				continue;
2152 			}
2153 			if (entry->wired_count != 0) {
2154 				entry->wired_count++;
2155 				entry->eflags |= MAP_ENTRY_USER_WIRED;
2156 				entry = entry->next;
2157 				continue;
2158 			}
2159 
2160 			/*
2161 			 * A new wiring requires instantiation of appropriate
2162 			 * management structures and the faulting in of the
2163 			 * page.
2164 			 */
2165 			if (entry->maptype != VM_MAPTYPE_SUBMAP) {
2166 				int copyflag = entry->eflags &
2167 					       MAP_ENTRY_NEEDS_COPY;
2168 				if (copyflag && ((entry->protection &
2169 						  VM_PROT_WRITE) != 0)) {
2170 					vm_map_entry_shadow(entry, 0);
2171 				} else if (entry->object.vm_object == NULL &&
2172 					   !map->system_map) {
2173 					vm_map_entry_allocate_object(entry);
2174 				}
2175 			}
2176 			entry->wired_count++;
2177 			entry->eflags |= MAP_ENTRY_USER_WIRED;
2178 
2179 			/*
2180 			 * Now fault in the area.  Note that vm_fault_wire()
2181 			 * may release the map lock temporarily, it will be
2182 			 * relocked on return.  The in-transition
2183 			 * flag protects the entries.
2184 			 */
2185 			save_start = entry->start;
2186 			save_end = entry->end;
2187 			rv = vm_fault_wire(map, entry, TRUE);
2188 			if (rv) {
2189 				CLIP_CHECK_BACK(entry, save_start);
2190 				for (;;) {
2191 					KASSERT(entry->wired_count == 1, ("bad wired_count on entry"));
2192 					entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2193 					entry->wired_count = 0;
2194 					if (entry->end == save_end)
2195 						break;
2196 					entry = entry->next;
2197 					KASSERT(entry != &map->header, ("bad entry clip during backout"));
2198 				}
2199 				end = save_start;	/* unwire the rest */
2200 				break;
2201 			}
2202 			/*
2203 			 * note that even though the entry might have been
2204 			 * clipped, the USER_WIRED flag we set prevents
2205 			 * duplication so we do not have to do a
2206 			 * clip check.
2207 			 */
2208 			entry = entry->next;
2209 		}
2210 
2211 		/*
2212 		 * If we failed fall through to the unwiring section to
2213 		 * unwire what we had wired so far.  'end' has already
2214 		 * been adjusted.
2215 		 */
2216 		if (rv)
2217 			new_pageable = 1;
2218 
2219 		/*
2220 		 * start_entry might have been clipped if we unlocked the
2221 		 * map and blocked.  No matter how clipped it has gotten
2222 		 * there should be a fragment that is on our start boundary.
2223 		 */
2224 		CLIP_CHECK_BACK(start_entry, start);
2225 	}
2226 
2227 	/*
2228 	 * Deal with the unwiring case.
2229 	 */
2230 	if (new_pageable) {
2231 		/*
2232 		 * This is the unwiring case.  We must first ensure that the
2233 		 * range to be unwired is really wired down.  We know there
2234 		 * are no holes.
2235 		 */
2236 		entry = start_entry;
2237 		while ((entry != &map->header) && (entry->start < end)) {
2238 			if ((entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2239 				rv = KERN_INVALID_ARGUMENT;
2240 				goto done;
2241 			}
2242 			KASSERT(entry->wired_count != 0, ("wired count was 0 with USER_WIRED set! %p", entry));
2243 			entry = entry->next;
2244 		}
2245 
2246 		/*
2247 		 * Now decrement the wiring count for each region. If a region
2248 		 * becomes completely unwired, unwire its physical pages and
2249 		 * mappings.
2250 		 */
2251 		/*
2252 		 * The map entries are processed in a loop, checking to
2253 		 * make sure the entry is wired and asserting it has a wired
2254 		 * count. However, another loop was inserted more-or-less in
2255 		 * the middle of the unwiring path. This loop picks up the
2256 		 * "entry" loop variable from the first loop without first
2257 		 * setting it to start_entry. Naturally, the secound loop
2258 		 * is never entered and the pages backing the entries are
2259 		 * never unwired. This can lead to a leak of wired pages.
2260 		 */
2261 		entry = start_entry;
2262 		while ((entry != &map->header) && (entry->start < end)) {
2263 			KASSERT(entry->eflags & MAP_ENTRY_USER_WIRED,
2264 				("expected USER_WIRED on entry %p", entry));
2265 			entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2266 			entry->wired_count--;
2267 			if (entry->wired_count == 0)
2268 				vm_fault_unwire(map, entry);
2269 			entry = entry->next;
2270 		}
2271 	}
2272 done:
2273 	vm_map_unclip_range(map, start_entry, start, real_end, &count,
2274 		MAP_CLIP_NO_HOLES);
2275 	map->timestamp++;
2276 	vm_map_unlock(map);
2277 	vm_map_entry_release(count);
2278 	return (rv);
2279 }
2280 
2281 /*
2282  * Sets the pageability of the specified address range in the target map.
2283  * Regions specified as not pageable require locked-down physical
2284  * memory and physical page maps.
2285  *
2286  * The map must not be locked, but a reference must remain to the map
2287  * throughout the call.
2288  *
2289  * This function may be called via the zalloc path and must properly
2290  * reserve map entries for kernel_map.
2291  *
2292  * No requirements.
2293  */
2294 int
2295 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t real_end, int kmflags)
2296 {
2297 	vm_map_entry_t entry;
2298 	vm_map_entry_t start_entry;
2299 	vm_offset_t end;
2300 	int rv = KERN_SUCCESS;
2301 	int count;
2302 
2303 	if (kmflags & KM_KRESERVE)
2304 		count = vm_map_entry_kreserve(MAP_RESERVE_COUNT);
2305 	else
2306 		count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2307 	vm_map_lock(map);
2308 	VM_MAP_RANGE_CHECK(map, start, real_end);
2309 	end = real_end;
2310 
2311 	start_entry = vm_map_clip_range(map, start, end, &count,
2312 					MAP_CLIP_NO_HOLES);
2313 	if (start_entry == NULL) {
2314 		vm_map_unlock(map);
2315 		rv = KERN_INVALID_ADDRESS;
2316 		goto failure;
2317 	}
2318 	if ((kmflags & KM_PAGEABLE) == 0) {
2319 		/*
2320 		 * Wiring.
2321 		 *
2322 		 * 1.  Holding the write lock, we create any shadow or zero-fill
2323 		 * objects that need to be created. Then we clip each map
2324 		 * entry to the region to be wired and increment its wiring
2325 		 * count.  We create objects before clipping the map entries
2326 		 * to avoid object proliferation.
2327 		 *
2328 		 * 2.  We downgrade to a read lock, and call vm_fault_wire to
2329 		 * fault in the pages for any newly wired area (wired_count is
2330 		 * 1).
2331 		 *
2332 		 * Downgrading to a read lock for vm_fault_wire avoids a
2333 		 * possible deadlock with another process that may have faulted
2334 		 * on one of the pages to be wired (it would mark the page busy,
2335 		 * blocking us, then in turn block on the map lock that we
2336 		 * hold).  Because of problems in the recursive lock package,
2337 		 * we cannot upgrade to a write lock in vm_map_lookup.  Thus,
2338 		 * any actions that require the write lock must be done
2339 		 * beforehand.  Because we keep the read lock on the map, the
2340 		 * copy-on-write status of the entries we modify here cannot
2341 		 * change.
2342 		 */
2343 		entry = start_entry;
2344 		while ((entry != &map->header) && (entry->start < end)) {
2345 			/*
2346 			 * Trivial case if the entry is already wired
2347 			 */
2348 			if (entry->wired_count) {
2349 				entry->wired_count++;
2350 				entry = entry->next;
2351 				continue;
2352 			}
2353 
2354 			/*
2355 			 * The entry is being newly wired, we have to setup
2356 			 * appropriate management structures.  A shadow
2357 			 * object is required for a copy-on-write region,
2358 			 * or a normal object for a zero-fill region.  We
2359 			 * do not have to do this for entries that point to sub
2360 			 * maps because we won't hold the lock on the sub map.
2361 			 */
2362 			if (entry->maptype != VM_MAPTYPE_SUBMAP) {
2363 				int copyflag = entry->eflags &
2364 					       MAP_ENTRY_NEEDS_COPY;
2365 				if (copyflag && ((entry->protection &
2366 						  VM_PROT_WRITE) != 0)) {
2367 					vm_map_entry_shadow(entry, 0);
2368 				} else if (entry->object.vm_object == NULL &&
2369 					   !map->system_map) {
2370 					vm_map_entry_allocate_object(entry);
2371 				}
2372 			}
2373 
2374 			entry->wired_count++;
2375 			entry = entry->next;
2376 		}
2377 
2378 		/*
2379 		 * Pass 2.
2380 		 */
2381 
2382 		/*
2383 		 * HACK HACK HACK HACK
2384 		 *
2385 		 * vm_fault_wire() temporarily unlocks the map to avoid
2386 		 * deadlocks.  The in-transition flag from vm_map_clip_range
2387 		 * call should protect us from changes while the map is
2388 		 * unlocked.  T
2389 		 *
2390 		 * NOTE: Previously this comment stated that clipping might
2391 		 *	 still occur while the entry is unlocked, but from
2392 		 *	 what I can tell it actually cannot.
2393 		 *
2394 		 *	 It is unclear whether the CLIP_CHECK_*() calls
2395 		 *	 are still needed but we keep them in anyway.
2396 		 *
2397 		 * HACK HACK HACK HACK
2398 		 */
2399 
2400 		entry = start_entry;
2401 		while (entry != &map->header && entry->start < end) {
2402 			/*
2403 			 * If vm_fault_wire fails for any page we need to undo
2404 			 * what has been done.  We decrement the wiring count
2405 			 * for those pages which have not yet been wired (now)
2406 			 * and unwire those that have (later).
2407 			 */
2408 			vm_offset_t save_start = entry->start;
2409 			vm_offset_t save_end = entry->end;
2410 
2411 			if (entry->wired_count == 1)
2412 				rv = vm_fault_wire(map, entry, FALSE);
2413 			if (rv) {
2414 				CLIP_CHECK_BACK(entry, save_start);
2415 				for (;;) {
2416 					KASSERT(entry->wired_count == 1, ("wired_count changed unexpectedly"));
2417 					entry->wired_count = 0;
2418 					if (entry->end == save_end)
2419 						break;
2420 					entry = entry->next;
2421 					KASSERT(entry != &map->header, ("bad entry clip during backout"));
2422 				}
2423 				end = save_start;
2424 				break;
2425 			}
2426 			CLIP_CHECK_FWD(entry, save_end);
2427 			entry = entry->next;
2428 		}
2429 
2430 		/*
2431 		 * If a failure occured undo everything by falling through
2432 		 * to the unwiring code.  'end' has already been adjusted
2433 		 * appropriately.
2434 		 */
2435 		if (rv)
2436 			kmflags |= KM_PAGEABLE;
2437 
2438 		/*
2439 		 * start_entry is still IN_TRANSITION but may have been
2440 		 * clipped since vm_fault_wire() unlocks and relocks the
2441 		 * map.  No matter how clipped it has gotten there should
2442 		 * be a fragment that is on our start boundary.
2443 		 */
2444 		CLIP_CHECK_BACK(start_entry, start);
2445 	}
2446 
2447 	if (kmflags & KM_PAGEABLE) {
2448 		/*
2449 		 * This is the unwiring case.  We must first ensure that the
2450 		 * range to be unwired is really wired down.  We know there
2451 		 * are no holes.
2452 		 */
2453 		entry = start_entry;
2454 		while ((entry != &map->header) && (entry->start < end)) {
2455 			if (entry->wired_count == 0) {
2456 				rv = KERN_INVALID_ARGUMENT;
2457 				goto done;
2458 			}
2459 			entry = entry->next;
2460 		}
2461 
2462 		/*
2463 		 * Now decrement the wiring count for each region. If a region
2464 		 * becomes completely unwired, unwire its physical pages and
2465 		 * mappings.
2466 		 */
2467 		entry = start_entry;
2468 		while ((entry != &map->header) && (entry->start < end)) {
2469 			entry->wired_count--;
2470 			if (entry->wired_count == 0)
2471 				vm_fault_unwire(map, entry);
2472 			entry = entry->next;
2473 		}
2474 	}
2475 done:
2476 	vm_map_unclip_range(map, start_entry, start, real_end,
2477 			    &count, MAP_CLIP_NO_HOLES);
2478 	map->timestamp++;
2479 	vm_map_unlock(map);
2480 failure:
2481 	if (kmflags & KM_KRESERVE)
2482 		vm_map_entry_krelease(count);
2483 	else
2484 		vm_map_entry_release(count);
2485 	return (rv);
2486 }
2487 
2488 /*
2489  * Mark a newly allocated address range as wired but do not fault in
2490  * the pages.  The caller is expected to load the pages into the object.
2491  *
2492  * The map must be locked on entry and will remain locked on return.
2493  * No other requirements.
2494  */
2495 void
2496 vm_map_set_wired_quick(vm_map_t map, vm_offset_t addr, vm_size_t size,
2497 		       int *countp)
2498 {
2499 	vm_map_entry_t scan;
2500 	vm_map_entry_t entry;
2501 
2502 	entry = vm_map_clip_range(map, addr, addr + size,
2503 				  countp, MAP_CLIP_NO_HOLES);
2504 	for (scan = entry;
2505 	     scan != &map->header && scan->start < addr + size;
2506 	     scan = scan->next) {
2507 	    KKASSERT(scan->wired_count == 0);
2508 	    scan->wired_count = 1;
2509 	}
2510 	vm_map_unclip_range(map, entry, addr, addr + size,
2511 			    countp, MAP_CLIP_NO_HOLES);
2512 }
2513 
2514 /*
2515  * Push any dirty cached pages in the address range to their pager.
2516  * If syncio is TRUE, dirty pages are written synchronously.
2517  * If invalidate is TRUE, any cached pages are freed as well.
2518  *
2519  * This routine is called by sys_msync()
2520  *
2521  * Returns an error if any part of the specified range is not mapped.
2522  *
2523  * No requirements.
2524  */
2525 int
2526 vm_map_clean(vm_map_t map, vm_offset_t start, vm_offset_t end,
2527 	     boolean_t syncio, boolean_t invalidate)
2528 {
2529 	vm_map_entry_t current;
2530 	vm_map_entry_t entry;
2531 	vm_size_t size;
2532 	vm_object_t object;
2533 	vm_object_t tobj;
2534 	vm_ooffset_t offset;
2535 
2536 	vm_map_lock_read(map);
2537 	VM_MAP_RANGE_CHECK(map, start, end);
2538 	if (!vm_map_lookup_entry(map, start, &entry)) {
2539 		vm_map_unlock_read(map);
2540 		return (KERN_INVALID_ADDRESS);
2541 	}
2542 	lwkt_gettoken(&map->token);
2543 
2544 	/*
2545 	 * Make a first pass to check for holes.
2546 	 */
2547 	for (current = entry; current->start < end; current = current->next) {
2548 		if (current->maptype == VM_MAPTYPE_SUBMAP) {
2549 			lwkt_reltoken(&map->token);
2550 			vm_map_unlock_read(map);
2551 			return (KERN_INVALID_ARGUMENT);
2552 		}
2553 		if (end > current->end &&
2554 		    (current->next == &map->header ||
2555 			current->end != current->next->start)) {
2556 			lwkt_reltoken(&map->token);
2557 			vm_map_unlock_read(map);
2558 			return (KERN_INVALID_ADDRESS);
2559 		}
2560 	}
2561 
2562 	if (invalidate)
2563 		pmap_remove(vm_map_pmap(map), start, end);
2564 
2565 	/*
2566 	 * Make a second pass, cleaning/uncaching pages from the indicated
2567 	 * objects as we go.
2568 	 */
2569 	for (current = entry; current->start < end; current = current->next) {
2570 		offset = current->offset + (start - current->start);
2571 		size = (end <= current->end ? end : current->end) - start;
2572 		if (current->maptype == VM_MAPTYPE_SUBMAP) {
2573 			vm_map_t smap;
2574 			vm_map_entry_t tentry;
2575 			vm_size_t tsize;
2576 
2577 			smap = current->object.sub_map;
2578 			vm_map_lock_read(smap);
2579 			vm_map_lookup_entry(smap, offset, &tentry);
2580 			tsize = tentry->end - offset;
2581 			if (tsize < size)
2582 				size = tsize;
2583 			object = tentry->object.vm_object;
2584 			offset = tentry->offset + (offset - tentry->start);
2585 			vm_map_unlock_read(smap);
2586 		} else {
2587 			object = current->object.vm_object;
2588 		}
2589 
2590 		if (object)
2591 			vm_object_hold(object);
2592 
2593 		/*
2594 		 * Note that there is absolutely no sense in writing out
2595 		 * anonymous objects, so we track down the vnode object
2596 		 * to write out.
2597 		 * We invalidate (remove) all pages from the address space
2598 		 * anyway, for semantic correctness.
2599 		 *
2600 		 * note: certain anonymous maps, such as MAP_NOSYNC maps,
2601 		 * may start out with a NULL object.
2602 		 */
2603 		while (object && (tobj = object->backing_object) != NULL) {
2604 			vm_object_hold(tobj);
2605 			if (tobj == object->backing_object) {
2606 				vm_object_lock_swap();
2607 				offset += object->backing_object_offset;
2608 				vm_object_drop(object);
2609 				object = tobj;
2610 				if (object->size < OFF_TO_IDX(offset + size))
2611 					size = IDX_TO_OFF(object->size) -
2612 					       offset;
2613 				break;
2614 			}
2615 			vm_object_drop(tobj);
2616 		}
2617 		if (object && (object->type == OBJT_VNODE) &&
2618 		    (current->protection & VM_PROT_WRITE) &&
2619 		    (object->flags & OBJ_NOMSYNC) == 0) {
2620 			/*
2621 			 * Flush pages if writing is allowed, invalidate them
2622 			 * if invalidation requested.  Pages undergoing I/O
2623 			 * will be ignored by vm_object_page_remove().
2624 			 *
2625 			 * We cannot lock the vnode and then wait for paging
2626 			 * to complete without deadlocking against vm_fault.
2627 			 * Instead we simply call vm_object_page_remove() and
2628 			 * allow it to block internally on a page-by-page
2629 			 * basis when it encounters pages undergoing async
2630 			 * I/O.
2631 			 */
2632 			int flags;
2633 
2634 			/* no chain wait needed for vnode objects */
2635 			vm_object_reference_locked(object);
2636 			vn_lock(object->handle, LK_EXCLUSIVE | LK_RETRY);
2637 			flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
2638 			flags |= invalidate ? OBJPC_INVAL : 0;
2639 
2640 			/*
2641 			 * When operating on a virtual page table just
2642 			 * flush the whole object.  XXX we probably ought
2643 			 * to
2644 			 */
2645 			switch(current->maptype) {
2646 			case VM_MAPTYPE_NORMAL:
2647 				vm_object_page_clean(object,
2648 				    OFF_TO_IDX(offset),
2649 				    OFF_TO_IDX(offset + size + PAGE_MASK),
2650 				    flags);
2651 				break;
2652 			case VM_MAPTYPE_VPAGETABLE:
2653 				vm_object_page_clean(object, 0, 0, flags);
2654 				break;
2655 			}
2656 			vn_unlock(((struct vnode *)object->handle));
2657 			vm_object_deallocate_locked(object);
2658 		}
2659 		if (object && invalidate &&
2660 		   ((object->type == OBJT_VNODE) ||
2661 		    (object->type == OBJT_DEVICE))) {
2662 			int clean_only =
2663 				(object->type == OBJT_DEVICE) ? FALSE : TRUE;
2664 			/* no chain wait needed for vnode/device objects */
2665 			vm_object_reference_locked(object);
2666 			switch(current->maptype) {
2667 			case VM_MAPTYPE_NORMAL:
2668 				vm_object_page_remove(object,
2669 				    OFF_TO_IDX(offset),
2670 				    OFF_TO_IDX(offset + size + PAGE_MASK),
2671 				    clean_only);
2672 				break;
2673 			case VM_MAPTYPE_VPAGETABLE:
2674 				vm_object_page_remove(object, 0, 0, clean_only);
2675 				break;
2676 			}
2677 			vm_object_deallocate_locked(object);
2678 		}
2679 		start += size;
2680 		if (object)
2681 			vm_object_drop(object);
2682 	}
2683 
2684 	lwkt_reltoken(&map->token);
2685 	vm_map_unlock_read(map);
2686 
2687 	return (KERN_SUCCESS);
2688 }
2689 
2690 /*
2691  * Make the region specified by this entry pageable.
2692  *
2693  * The vm_map must be exclusively locked.
2694  */
2695 static void
2696 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2697 {
2698 	entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2699 	entry->wired_count = 0;
2700 	vm_fault_unwire(map, entry);
2701 }
2702 
2703 /*
2704  * Deallocate the given entry from the target map.
2705  *
2706  * The vm_map must be exclusively locked.
2707  */
2708 static void
2709 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry, int *countp)
2710 {
2711 	vm_map_entry_unlink(map, entry);
2712 	map->size -= entry->end - entry->start;
2713 
2714 	switch(entry->maptype) {
2715 	case VM_MAPTYPE_NORMAL:
2716 	case VM_MAPTYPE_VPAGETABLE:
2717 		vm_object_deallocate(entry->object.vm_object);
2718 		break;
2719 	default:
2720 		break;
2721 	}
2722 
2723 	vm_map_entry_dispose(map, entry, countp);
2724 }
2725 
2726 /*
2727  * Deallocates the given address range from the target map.
2728  *
2729  * The vm_map must be exclusively locked.
2730  */
2731 int
2732 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end, int *countp)
2733 {
2734 	vm_object_t object;
2735 	vm_map_entry_t entry;
2736 	vm_map_entry_t first_entry;
2737 
2738 	ASSERT_VM_MAP_LOCKED(map);
2739 	lwkt_gettoken(&map->token);
2740 again:
2741 	/*
2742 	 * Find the start of the region, and clip it.  Set entry to point
2743 	 * at the first record containing the requested address or, if no
2744 	 * such record exists, the next record with a greater address.  The
2745 	 * loop will run from this point until a record beyond the termination
2746 	 * address is encountered.
2747 	 *
2748 	 * map->hint must be adjusted to not point to anything we delete,
2749 	 * so set it to the entry prior to the one being deleted.
2750 	 *
2751 	 * GGG see other GGG comment.
2752 	 */
2753 	if (vm_map_lookup_entry(map, start, &first_entry)) {
2754 		entry = first_entry;
2755 		vm_map_clip_start(map, entry, start, countp);
2756 		map->hint = entry->prev;	/* possible problem XXX */
2757 	} else {
2758 		map->hint = first_entry;	/* possible problem XXX */
2759 		entry = first_entry->next;
2760 	}
2761 
2762 	/*
2763 	 * If a hole opens up prior to the current first_free then
2764 	 * adjust first_free.  As with map->hint, map->first_free
2765 	 * cannot be left set to anything we might delete.
2766 	 */
2767 	if (entry == &map->header) {
2768 		map->first_free = &map->header;
2769 	} else if (map->first_free->start >= start) {
2770 		map->first_free = entry->prev;
2771 	}
2772 
2773 	/*
2774 	 * Step through all entries in this region
2775 	 */
2776 	while ((entry != &map->header) && (entry->start < end)) {
2777 		vm_map_entry_t next;
2778 		vm_offset_t s, e;
2779 		vm_pindex_t offidxstart, offidxend, count;
2780 
2781 		/*
2782 		 * If we hit an in-transition entry we have to sleep and
2783 		 * retry.  It's easier (and not really slower) to just retry
2784 		 * since this case occurs so rarely and the hint is already
2785 		 * pointing at the right place.  We have to reset the
2786 		 * start offset so as not to accidently delete an entry
2787 		 * another process just created in vacated space.
2788 		 */
2789 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2790 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2791 			start = entry->start;
2792 			++mycpu->gd_cnt.v_intrans_coll;
2793 			++mycpu->gd_cnt.v_intrans_wait;
2794 			vm_map_transition_wait(map);
2795 			goto again;
2796 		}
2797 		vm_map_clip_end(map, entry, end, countp);
2798 
2799 		s = entry->start;
2800 		e = entry->end;
2801 		next = entry->next;
2802 
2803 		offidxstart = OFF_TO_IDX(entry->offset);
2804 		count = OFF_TO_IDX(e - s);
2805 		object = entry->object.vm_object;
2806 
2807 		/*
2808 		 * Unwire before removing addresses from the pmap; otherwise,
2809 		 * unwiring will put the entries back in the pmap.
2810 		 */
2811 		if (entry->wired_count != 0)
2812 			vm_map_entry_unwire(map, entry);
2813 
2814 		offidxend = offidxstart + count;
2815 
2816 		if (object == &kernel_object) {
2817 			vm_object_hold(object);
2818 			vm_object_page_remove(object, offidxstart,
2819 					      offidxend, FALSE);
2820 			vm_object_drop(object);
2821 		} else if (object && object->type != OBJT_DEFAULT &&
2822 			   object->type != OBJT_SWAP) {
2823 			/*
2824 			 * vnode object routines cannot be chain-locked,
2825 			 * but since we aren't removing pages from the
2826 			 * object here we can use a shared hold.
2827 			 */
2828 			vm_object_hold_shared(object);
2829 			pmap_remove(map->pmap, s, e);
2830 			vm_object_drop(object);
2831 		} else if (object) {
2832 			vm_object_hold(object);
2833 			vm_object_chain_acquire(object);
2834 			pmap_remove(map->pmap, s, e);
2835 
2836 			if (object != NULL &&
2837 			    object->ref_count != 1 &&
2838 			    (object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) ==
2839 			     OBJ_ONEMAPPING &&
2840 			    (object->type == OBJT_DEFAULT ||
2841 			     object->type == OBJT_SWAP)) {
2842 				vm_object_collapse(object, NULL);
2843 				vm_object_page_remove(object, offidxstart,
2844 						      offidxend, FALSE);
2845 				if (object->type == OBJT_SWAP) {
2846 					swap_pager_freespace(object,
2847 							     offidxstart,
2848 							     count);
2849 				}
2850 				if (offidxend >= object->size &&
2851 				    offidxstart < object->size) {
2852 					object->size = offidxstart;
2853 				}
2854 			}
2855 			vm_object_chain_release(object);
2856 			vm_object_drop(object);
2857 		}
2858 
2859 		/*
2860 		 * Delete the entry (which may delete the object) only after
2861 		 * removing all pmap entries pointing to its pages.
2862 		 * (Otherwise, its page frames may be reallocated, and any
2863 		 * modify bits will be set in the wrong object!)
2864 		 */
2865 		vm_map_entry_delete(map, entry, countp);
2866 		entry = next;
2867 	}
2868 	lwkt_reltoken(&map->token);
2869 	return (KERN_SUCCESS);
2870 }
2871 
2872 /*
2873  * Remove the given address range from the target map.
2874  * This is the exported form of vm_map_delete.
2875  *
2876  * No requirements.
2877  */
2878 int
2879 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2880 {
2881 	int result;
2882 	int count;
2883 
2884 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2885 	vm_map_lock(map);
2886 	VM_MAP_RANGE_CHECK(map, start, end);
2887 	result = vm_map_delete(map, start, end, &count);
2888 	vm_map_unlock(map);
2889 	vm_map_entry_release(count);
2890 
2891 	return (result);
2892 }
2893 
2894 /*
2895  * Assert that the target map allows the specified privilege on the
2896  * entire address region given.  The entire region must be allocated.
2897  *
2898  * The caller must specify whether the vm_map is already locked or not.
2899  */
2900 boolean_t
2901 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2902 			vm_prot_t protection, boolean_t have_lock)
2903 {
2904 	vm_map_entry_t entry;
2905 	vm_map_entry_t tmp_entry;
2906 	boolean_t result;
2907 
2908 	if (have_lock == FALSE)
2909 		vm_map_lock_read(map);
2910 
2911 	if (!vm_map_lookup_entry(map, start, &tmp_entry)) {
2912 		if (have_lock == FALSE)
2913 			vm_map_unlock_read(map);
2914 		return (FALSE);
2915 	}
2916 	entry = tmp_entry;
2917 
2918 	result = TRUE;
2919 	while (start < end) {
2920 		if (entry == &map->header) {
2921 			result = FALSE;
2922 			break;
2923 		}
2924 		/*
2925 		 * No holes allowed!
2926 		 */
2927 
2928 		if (start < entry->start) {
2929 			result = FALSE;
2930 			break;
2931 		}
2932 		/*
2933 		 * Check protection associated with entry.
2934 		 */
2935 
2936 		if ((entry->protection & protection) != protection) {
2937 			result = FALSE;
2938 			break;
2939 		}
2940 		/* go to next entry */
2941 
2942 		start = entry->end;
2943 		entry = entry->next;
2944 	}
2945 	if (have_lock == FALSE)
2946 		vm_map_unlock_read(map);
2947 	return (result);
2948 }
2949 
2950 /*
2951  * If appropriate this function shadows the original object with a new object
2952  * and moves the VM pages from the original object to the new object.
2953  * The original object will also be collapsed, if possible.
2954  *
2955  * We can only do this for normal memory objects with a single mapping, and
2956  * it only makes sense to do it if there are 2 or more refs on the original
2957  * object.  i.e. typically a memory object that has been extended into
2958  * multiple vm_map_entry's with non-overlapping ranges.
2959  *
2960  * This makes it easier to remove unused pages and keeps object inheritance
2961  * from being a negative impact on memory usage.
2962  *
2963  * On return the (possibly new) entry->object.vm_object will have an
2964  * additional ref on it for the caller to dispose of (usually by cloning
2965  * the vm_map_entry).  The additional ref had to be done in this routine
2966  * to avoid racing a collapse.  The object's ONEMAPPING flag will also be
2967  * cleared.
2968  *
2969  * The vm_map must be locked and its token held.
2970  */
2971 static void
2972 vm_map_split(vm_map_entry_t entry)
2973 {
2974 #if 0
2975 	/* UNOPTIMIZED */
2976 	vm_object_t oobject;
2977 
2978 	oobject = entry->object.vm_object;
2979 	vm_object_hold(oobject);
2980 	vm_object_chain_wait(oobject);
2981 	vm_object_reference_locked(oobject);
2982 	vm_object_clear_flag(oobject, OBJ_ONEMAPPING);
2983 	vm_object_drop(oobject);
2984 #else
2985 	/* OPTIMIZED */
2986 	vm_object_t oobject, nobject, bobject;
2987 	vm_offset_t s, e;
2988 	vm_page_t m;
2989 	vm_pindex_t offidxstart, offidxend, idx;
2990 	vm_size_t size;
2991 	vm_ooffset_t offset;
2992 
2993 	/*
2994 	 * Setup.  Chain lock the original object throughout the entire
2995 	 * routine to prevent new page faults from occuring.
2996 	 *
2997 	 * XXX can madvise WILLNEED interfere with us too?
2998 	 */
2999 	oobject = entry->object.vm_object;
3000 	vm_object_hold(oobject);
3001 	vm_object_chain_acquire(oobject);
3002 
3003 	/*
3004 	 * Original object cannot be split?
3005 	 */
3006 	if (oobject->handle == NULL || (oobject->type != OBJT_DEFAULT &&
3007 					oobject->type != OBJT_SWAP)) {
3008 		vm_object_chain_release(oobject);
3009 		vm_object_reference_locked(oobject);
3010 		vm_object_clear_flag(oobject, OBJ_ONEMAPPING);
3011 		vm_object_drop(oobject);
3012 		return;
3013 	}
3014 
3015 	/*
3016 	 * Collapse original object with its backing store as an
3017 	 * optimization to reduce chain lengths when possible.
3018 	 *
3019 	 * If ref_count <= 1 there aren't other non-overlapping vm_map_entry's
3020 	 * for oobject, so there's no point collapsing it.
3021 	 *
3022 	 * Then re-check whether the object can be split.
3023 	 */
3024 	vm_object_collapse(oobject, NULL);
3025 
3026 	if (oobject->ref_count <= 1 ||
3027 	    (oobject->type != OBJT_DEFAULT && oobject->type != OBJT_SWAP) ||
3028 	    (oobject->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) != OBJ_ONEMAPPING) {
3029 		vm_object_chain_release(oobject);
3030 		vm_object_reference_locked(oobject);
3031 		vm_object_clear_flag(oobject, OBJ_ONEMAPPING);
3032 		vm_object_drop(oobject);
3033 		return;
3034 	}
3035 
3036 	/*
3037 	 * Acquire the chain lock on the backing object.
3038 	 *
3039 	 * Give bobject an additional ref count for when it will be shadowed
3040 	 * by nobject.
3041 	 */
3042 	if ((bobject = oobject->backing_object) != NULL) {
3043 		vm_object_hold(bobject);
3044 		vm_object_chain_wait(bobject);
3045 		vm_object_reference_locked(bobject);
3046 		vm_object_chain_acquire(bobject);
3047 		KKASSERT(bobject->backing_object == bobject);
3048 		KKASSERT((bobject->flags & OBJ_DEAD) == 0);
3049 	}
3050 
3051 	/*
3052 	 * Calculate the object page range and allocate the new object.
3053 	 */
3054 	offset = entry->offset;
3055 	s = entry->start;
3056 	e = entry->end;
3057 
3058 	offidxstart = OFF_TO_IDX(offset);
3059 	offidxend = offidxstart + OFF_TO_IDX(e - s);
3060 	size = offidxend - offidxstart;
3061 
3062 	switch(oobject->type) {
3063 	case OBJT_DEFAULT:
3064 		nobject = default_pager_alloc(NULL, IDX_TO_OFF(size),
3065 					      VM_PROT_ALL, 0);
3066 		break;
3067 	case OBJT_SWAP:
3068 		nobject = swap_pager_alloc(NULL, IDX_TO_OFF(size),
3069 					   VM_PROT_ALL, 0);
3070 		break;
3071 	default:
3072 		/* not reached */
3073 		nobject = NULL;
3074 		KKASSERT(0);
3075 	}
3076 
3077 	if (nobject == NULL) {
3078 		if (bobject) {
3079 			vm_object_chain_release(bobject);
3080 			vm_object_deallocate(bobject);
3081 			vm_object_drop(bobject);
3082 		}
3083 		vm_object_chain_release(oobject);
3084 		vm_object_reference_locked(oobject);
3085 		vm_object_clear_flag(oobject, OBJ_ONEMAPPING);
3086 		vm_object_drop(oobject);
3087 		return;
3088 	}
3089 
3090 	/*
3091 	 * The new object will replace entry->object.vm_object so it needs
3092 	 * a second reference (the caller expects an additional ref).
3093 	 */
3094 	vm_object_hold(nobject);
3095 	vm_object_reference_locked(nobject);
3096 	vm_object_chain_acquire(nobject);
3097 
3098 	/*
3099 	 * nobject shadows bobject (oobject already shadows bobject).
3100 	 */
3101 	if (bobject) {
3102 		nobject->backing_object_offset =
3103 		    oobject->backing_object_offset + IDX_TO_OFF(offidxstart);
3104 		nobject->backing_object = bobject;
3105 		bobject->shadow_count++;
3106 		bobject->generation++;
3107 		LIST_INSERT_HEAD(&bobject->shadow_head, nobject, shadow_list);
3108 		vm_object_clear_flag(bobject, OBJ_ONEMAPPING); /* XXX? */
3109 		vm_object_chain_release(bobject);
3110 		vm_object_drop(bobject);
3111 	}
3112 
3113 	/*
3114 	 * Move the VM pages from oobject to nobject
3115 	 */
3116 	for (idx = 0; idx < size; idx++) {
3117 		vm_page_t m;
3118 
3119 		m = vm_page_lookup_busy_wait(oobject, offidxstart + idx,
3120 					     TRUE, "vmpg");
3121 		if (m == NULL)
3122 			continue;
3123 
3124 		/*
3125 		 * We must wait for pending I/O to complete before we can
3126 		 * rename the page.
3127 		 *
3128 		 * We do not have to VM_PROT_NONE the page as mappings should
3129 		 * not be changed by this operation.
3130 		 *
3131 		 * NOTE: The act of renaming a page updates chaingen for both
3132 		 *	 objects.
3133 		 */
3134 		vm_page_rename(m, nobject, idx);
3135 		/* page automatically made dirty by rename and cache handled */
3136 		/* page remains busy */
3137 	}
3138 
3139 	if (oobject->type == OBJT_SWAP) {
3140 		vm_object_pip_add(oobject, 1);
3141 		/*
3142 		 * copy oobject pages into nobject and destroy unneeded
3143 		 * pages in shadow object.
3144 		 */
3145 		swap_pager_copy(oobject, nobject, offidxstart, 0);
3146 		vm_object_pip_wakeup(oobject);
3147 	}
3148 
3149 	/*
3150 	 * Wakeup the pages we played with.  No spl protection is needed
3151 	 * for a simple wakeup.
3152 	 */
3153 	for (idx = 0; idx < size; idx++) {
3154 		m = vm_page_lookup(nobject, idx);
3155 		if (m) {
3156 			KKASSERT(m->flags & PG_BUSY);
3157 			vm_page_wakeup(m);
3158 		}
3159 	}
3160 	entry->object.vm_object = nobject;
3161 	entry->offset = 0LL;
3162 
3163 	/*
3164 	 * Cleanup
3165 	 *
3166 	 * NOTE: There is no need to remove OBJ_ONEMAPPING from oobject, the
3167 	 *	 related pages were moved and are no longer applicable to the
3168 	 *	 original object.
3169 	 *
3170 	 * NOTE: Deallocate oobject (due to its entry->object.vm_object being
3171 	 *	 replaced by nobject).
3172 	 */
3173 	vm_object_chain_release(nobject);
3174 	vm_object_drop(nobject);
3175 	if (bobject) {
3176 		vm_object_chain_release(bobject);
3177 		vm_object_drop(bobject);
3178 	}
3179 	vm_object_chain_release(oobject);
3180 	/*vm_object_clear_flag(oobject, OBJ_ONEMAPPING);*/
3181 	vm_object_deallocate_locked(oobject);
3182 	vm_object_drop(oobject);
3183 #endif
3184 }
3185 
3186 /*
3187  * Copies the contents of the source entry to the destination
3188  * entry.  The entries *must* be aligned properly.
3189  *
3190  * The vm_maps must be exclusively locked.
3191  * The vm_map's token must be held.
3192  *
3193  * Because the maps are locked no faults can be in progress during the
3194  * operation.
3195  */
3196 static void
3197 vm_map_copy_entry(vm_map_t src_map, vm_map_t dst_map,
3198 		  vm_map_entry_t src_entry, vm_map_entry_t dst_entry)
3199 {
3200 	vm_object_t src_object;
3201 
3202 	if (dst_entry->maptype == VM_MAPTYPE_SUBMAP)
3203 		return;
3204 	if (src_entry->maptype == VM_MAPTYPE_SUBMAP)
3205 		return;
3206 
3207 	if (src_entry->wired_count == 0) {
3208 		/*
3209 		 * If the source entry is marked needs_copy, it is already
3210 		 * write-protected.
3211 		 */
3212 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
3213 			pmap_protect(src_map->pmap,
3214 			    src_entry->start,
3215 			    src_entry->end,
3216 			    src_entry->protection & ~VM_PROT_WRITE);
3217 		}
3218 
3219 		/*
3220 		 * Make a copy of the object.
3221 		 *
3222 		 * The object must be locked prior to checking the object type
3223 		 * and for the call to vm_object_collapse() and vm_map_split().
3224 		 * We cannot use *_hold() here because the split code will
3225 		 * probably try to destroy the object.  The lock is a pool
3226 		 * token and doesn't care.
3227 		 *
3228 		 * We must bump src_map->timestamp when setting
3229 		 * MAP_ENTRY_NEEDS_COPY to force any concurrent fault
3230 		 * to retry, otherwise the concurrent fault might improperly
3231 		 * install a RW pte when its supposed to be a RO(COW) pte.
3232 		 * This race can occur because a vnode-backed fault may have
3233 		 * to temporarily release the map lock.
3234 		 */
3235 		if (src_entry->object.vm_object != NULL) {
3236 			vm_map_split(src_entry);
3237 			src_object = src_entry->object.vm_object;
3238 			dst_entry->object.vm_object = src_object;
3239 			src_entry->eflags |= (MAP_ENTRY_COW |
3240 					      MAP_ENTRY_NEEDS_COPY);
3241 			dst_entry->eflags |= (MAP_ENTRY_COW |
3242 					      MAP_ENTRY_NEEDS_COPY);
3243 			dst_entry->offset = src_entry->offset;
3244 			++src_map->timestamp;
3245 		} else {
3246 			dst_entry->object.vm_object = NULL;
3247 			dst_entry->offset = 0;
3248 		}
3249 
3250 		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
3251 		    dst_entry->end - dst_entry->start, src_entry->start);
3252 	} else {
3253 		/*
3254 		 * Of course, wired down pages can't be set copy-on-write.
3255 		 * Cause wired pages to be copied into the new map by
3256 		 * simulating faults (the new pages are pageable)
3257 		 */
3258 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
3259 	}
3260 }
3261 
3262 /*
3263  * vmspace_fork:
3264  * Create a new process vmspace structure and vm_map
3265  * based on those of an existing process.  The new map
3266  * is based on the old map, according to the inheritance
3267  * values on the regions in that map.
3268  *
3269  * The source map must not be locked.
3270  * No requirements.
3271  */
3272 struct vmspace *
3273 vmspace_fork(struct vmspace *vm1)
3274 {
3275 	struct vmspace *vm2;
3276 	vm_map_t old_map = &vm1->vm_map;
3277 	vm_map_t new_map;
3278 	vm_map_entry_t old_entry;
3279 	vm_map_entry_t new_entry;
3280 	vm_object_t object;
3281 	int count;
3282 
3283 	lwkt_gettoken(&vm1->vm_map.token);
3284 	vm_map_lock(old_map);
3285 
3286 	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
3287 	lwkt_gettoken(&vm2->vm_map.token);
3288 	bcopy(&vm1->vm_startcopy, &vm2->vm_startcopy,
3289 	    (caddr_t)&vm1->vm_endcopy - (caddr_t)&vm1->vm_startcopy);
3290 	new_map = &vm2->vm_map;	/* XXX */
3291 	new_map->timestamp = 1;
3292 
3293 	vm_map_lock(new_map);
3294 
3295 	count = 0;
3296 	old_entry = old_map->header.next;
3297 	while (old_entry != &old_map->header) {
3298 		++count;
3299 		old_entry = old_entry->next;
3300 	}
3301 
3302 	count = vm_map_entry_reserve(count + MAP_RESERVE_COUNT);
3303 
3304 	old_entry = old_map->header.next;
3305 	while (old_entry != &old_map->header) {
3306 		if (old_entry->maptype == VM_MAPTYPE_SUBMAP)
3307 			panic("vm_map_fork: encountered a submap");
3308 
3309 		switch (old_entry->inheritance) {
3310 		case VM_INHERIT_NONE:
3311 			break;
3312 		case VM_INHERIT_SHARE:
3313 			/*
3314 			 * Clone the entry, creating the shared object if
3315 			 * necessary.
3316 			 */
3317 			if (old_entry->object.vm_object == NULL)
3318 				vm_map_entry_allocate_object(old_entry);
3319 
3320 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3321 				/*
3322 				 * Shadow a map_entry which needs a copy,
3323 				 * replacing its object with a new object
3324 				 * that points to the old one.  Ask the
3325 				 * shadow code to automatically add an
3326 				 * additional ref.  We can't do it afterwords
3327 				 * because we might race a collapse.  The call
3328 				 * to vm_map_entry_shadow() will also clear
3329 				 * OBJ_ONEMAPPING.
3330 				 */
3331 				vm_map_entry_shadow(old_entry, 1);
3332 			} else {
3333 				/*
3334 				 * We will make a shared copy of the object,
3335 				 * and must clear OBJ_ONEMAPPING.
3336 				 *
3337 				 * XXX assert that object.vm_object != NULL
3338 				 *     since we allocate it above.
3339 				 */
3340 				if (old_entry->object.vm_object) {
3341 					object = old_entry->object.vm_object;
3342 					vm_object_hold(object);
3343 					vm_object_chain_wait(object);
3344 					vm_object_reference_locked(object);
3345 					vm_object_clear_flag(object,
3346 							     OBJ_ONEMAPPING);
3347 					vm_object_drop(object);
3348 				}
3349 			}
3350 
3351 			/*
3352 			 * Clone the entry.  We've already bumped the ref on
3353 			 * any vm_object.
3354 			 */
3355 			new_entry = vm_map_entry_create(new_map, &count);
3356 			*new_entry = *old_entry;
3357 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3358 			new_entry->wired_count = 0;
3359 
3360 			/*
3361 			 * Insert the entry into the new map -- we know we're
3362 			 * inserting at the end of the new map.
3363 			 */
3364 
3365 			vm_map_entry_link(new_map, new_map->header.prev,
3366 					  new_entry);
3367 
3368 			/*
3369 			 * Update the physical map
3370 			 */
3371 			pmap_copy(new_map->pmap, old_map->pmap,
3372 			    new_entry->start,
3373 			    (old_entry->end - old_entry->start),
3374 			    old_entry->start);
3375 			break;
3376 		case VM_INHERIT_COPY:
3377 			/*
3378 			 * Clone the entry and link into the map.
3379 			 */
3380 			new_entry = vm_map_entry_create(new_map, &count);
3381 			*new_entry = *old_entry;
3382 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3383 			new_entry->wired_count = 0;
3384 			new_entry->object.vm_object = NULL;
3385 			vm_map_entry_link(new_map, new_map->header.prev,
3386 					  new_entry);
3387 			vm_map_copy_entry(old_map, new_map, old_entry,
3388 					  new_entry);
3389 			break;
3390 		}
3391 		old_entry = old_entry->next;
3392 	}
3393 
3394 	new_map->size = old_map->size;
3395 	vm_map_unlock(old_map);
3396 	vm_map_unlock(new_map);
3397 	vm_map_entry_release(count);
3398 
3399 	lwkt_reltoken(&vm2->vm_map.token);
3400 	lwkt_reltoken(&vm1->vm_map.token);
3401 
3402 	return (vm2);
3403 }
3404 
3405 /*
3406  * Create an auto-grow stack entry
3407  *
3408  * No requirements.
3409  */
3410 int
3411 vm_map_stack (vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3412 	      int flags, vm_prot_t prot, vm_prot_t max, int cow)
3413 {
3414 	vm_map_entry_t	prev_entry;
3415 	vm_map_entry_t	new_stack_entry;
3416 	vm_size_t	init_ssize;
3417 	int		rv;
3418 	int		count;
3419 	vm_offset_t	tmpaddr;
3420 
3421 	cow |= MAP_IS_STACK;
3422 
3423 	if (max_ssize < sgrowsiz)
3424 		init_ssize = max_ssize;
3425 	else
3426 		init_ssize = sgrowsiz;
3427 
3428 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
3429 	vm_map_lock(map);
3430 
3431 	/*
3432 	 * Find space for the mapping
3433 	 */
3434 	if ((flags & (MAP_FIXED | MAP_TRYFIXED)) == 0) {
3435 		if (vm_map_findspace(map, addrbos, max_ssize, 1,
3436 				     flags, &tmpaddr)) {
3437 			vm_map_unlock(map);
3438 			vm_map_entry_release(count);
3439 			return (KERN_NO_SPACE);
3440 		}
3441 		addrbos = tmpaddr;
3442 	}
3443 
3444 	/* If addr is already mapped, no go */
3445 	if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
3446 		vm_map_unlock(map);
3447 		vm_map_entry_release(count);
3448 		return (KERN_NO_SPACE);
3449 	}
3450 
3451 #if 0
3452 	/* XXX already handled by kern_mmap() */
3453 	/* If we would blow our VMEM resource limit, no go */
3454 	if (map->size + init_ssize >
3455 	    curproc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
3456 		vm_map_unlock(map);
3457 		vm_map_entry_release(count);
3458 		return (KERN_NO_SPACE);
3459 	}
3460 #endif
3461 
3462 	/*
3463 	 * If we can't accomodate max_ssize in the current mapping,
3464 	 * no go.  However, we need to be aware that subsequent user
3465 	 * mappings might map into the space we have reserved for
3466 	 * stack, and currently this space is not protected.
3467 	 *
3468 	 * Hopefully we will at least detect this condition
3469 	 * when we try to grow the stack.
3470 	 */
3471 	if ((prev_entry->next != &map->header) &&
3472 	    (prev_entry->next->start < addrbos + max_ssize)) {
3473 		vm_map_unlock(map);
3474 		vm_map_entry_release(count);
3475 		return (KERN_NO_SPACE);
3476 	}
3477 
3478 	/*
3479 	 * We initially map a stack of only init_ssize.  We will
3480 	 * grow as needed later.  Since this is to be a grow
3481 	 * down stack, we map at the top of the range.
3482 	 *
3483 	 * Note: we would normally expect prot and max to be
3484 	 * VM_PROT_ALL, and cow to be 0.  Possibly we should
3485 	 * eliminate these as input parameters, and just
3486 	 * pass these values here in the insert call.
3487 	 */
3488 	rv = vm_map_insert(map, &count,
3489 			   NULL, 0, addrbos + max_ssize - init_ssize,
3490 	                   addrbos + max_ssize,
3491 			   VM_MAPTYPE_NORMAL,
3492 			   prot, max,
3493 			   cow);
3494 
3495 	/* Now set the avail_ssize amount */
3496 	if (rv == KERN_SUCCESS) {
3497 		if (prev_entry != &map->header)
3498 			vm_map_clip_end(map, prev_entry, addrbos + max_ssize - init_ssize, &count);
3499 		new_stack_entry = prev_entry->next;
3500 		if (new_stack_entry->end   != addrbos + max_ssize ||
3501 		    new_stack_entry->start != addrbos + max_ssize - init_ssize)
3502 			panic ("Bad entry start/end for new stack entry");
3503 		else
3504 			new_stack_entry->aux.avail_ssize = max_ssize - init_ssize;
3505 	}
3506 
3507 	vm_map_unlock(map);
3508 	vm_map_entry_release(count);
3509 	return (rv);
3510 }
3511 
3512 /*
3513  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
3514  * desired address is already mapped, or if we successfully grow
3515  * the stack.  Also returns KERN_SUCCESS if addr is outside the
3516  * stack range (this is strange, but preserves compatibility with
3517  * the grow function in vm_machdep.c).
3518  *
3519  * No requirements.
3520  */
3521 int
3522 vm_map_growstack (struct proc *p, vm_offset_t addr)
3523 {
3524 	vm_map_entry_t prev_entry;
3525 	vm_map_entry_t stack_entry;
3526 	vm_map_entry_t new_stack_entry;
3527 	struct vmspace *vm = p->p_vmspace;
3528 	vm_map_t map = &vm->vm_map;
3529 	vm_offset_t    end;
3530 	int grow_amount;
3531 	int rv = KERN_SUCCESS;
3532 	int is_procstack;
3533 	int use_read_lock = 1;
3534 	int count;
3535 
3536 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
3537 Retry:
3538 	if (use_read_lock)
3539 		vm_map_lock_read(map);
3540 	else
3541 		vm_map_lock(map);
3542 
3543 	/* If addr is already in the entry range, no need to grow.*/
3544 	if (vm_map_lookup_entry(map, addr, &prev_entry))
3545 		goto done;
3546 
3547 	if ((stack_entry = prev_entry->next) == &map->header)
3548 		goto done;
3549 	if (prev_entry == &map->header)
3550 		end = stack_entry->start - stack_entry->aux.avail_ssize;
3551 	else
3552 		end = prev_entry->end;
3553 
3554 	/*
3555 	 * This next test mimics the old grow function in vm_machdep.c.
3556 	 * It really doesn't quite make sense, but we do it anyway
3557 	 * for compatibility.
3558 	 *
3559 	 * If not growable stack, return success.  This signals the
3560 	 * caller to proceed as he would normally with normal vm.
3561 	 */
3562 	if (stack_entry->aux.avail_ssize < 1 ||
3563 	    addr >= stack_entry->start ||
3564 	    addr <  stack_entry->start - stack_entry->aux.avail_ssize) {
3565 		goto done;
3566 	}
3567 
3568 	/* Find the minimum grow amount */
3569 	grow_amount = roundup (stack_entry->start - addr, PAGE_SIZE);
3570 	if (grow_amount > stack_entry->aux.avail_ssize) {
3571 		rv = KERN_NO_SPACE;
3572 		goto done;
3573 	}
3574 
3575 	/*
3576 	 * If there is no longer enough space between the entries
3577 	 * nogo, and adjust the available space.  Note: this
3578 	 * should only happen if the user has mapped into the
3579 	 * stack area after the stack was created, and is
3580 	 * probably an error.
3581 	 *
3582 	 * This also effectively destroys any guard page the user
3583 	 * might have intended by limiting the stack size.
3584 	 */
3585 	if (grow_amount > stack_entry->start - end) {
3586 		if (use_read_lock && vm_map_lock_upgrade(map)) {
3587 			/* lost lock */
3588 			use_read_lock = 0;
3589 			goto Retry;
3590 		}
3591 		use_read_lock = 0;
3592 		stack_entry->aux.avail_ssize = stack_entry->start - end;
3593 		rv = KERN_NO_SPACE;
3594 		goto done;
3595 	}
3596 
3597 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr;
3598 
3599 	/* If this is the main process stack, see if we're over the
3600 	 * stack limit.
3601 	 */
3602 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
3603 			     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
3604 		rv = KERN_NO_SPACE;
3605 		goto done;
3606 	}
3607 
3608 	/* Round up the grow amount modulo SGROWSIZ */
3609 	grow_amount = roundup (grow_amount, sgrowsiz);
3610 	if (grow_amount > stack_entry->aux.avail_ssize) {
3611 		grow_amount = stack_entry->aux.avail_ssize;
3612 	}
3613 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
3614 	                     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
3615 		grow_amount = p->p_rlimit[RLIMIT_STACK].rlim_cur -
3616 		              ctob(vm->vm_ssize);
3617 	}
3618 
3619 	/* If we would blow our VMEM resource limit, no go */
3620 	if (map->size + grow_amount > p->p_rlimit[RLIMIT_VMEM].rlim_cur) {
3621 		rv = KERN_NO_SPACE;
3622 		goto done;
3623 	}
3624 
3625 	if (use_read_lock && vm_map_lock_upgrade(map)) {
3626 		/* lost lock */
3627 		use_read_lock = 0;
3628 		goto Retry;
3629 	}
3630 	use_read_lock = 0;
3631 
3632 	/* Get the preliminary new entry start value */
3633 	addr = stack_entry->start - grow_amount;
3634 
3635 	/* If this puts us into the previous entry, cut back our growth
3636 	 * to the available space.  Also, see the note above.
3637 	 */
3638 	if (addr < end) {
3639 		stack_entry->aux.avail_ssize = stack_entry->start - end;
3640 		addr = end;
3641 	}
3642 
3643 	rv = vm_map_insert(map, &count,
3644 			   NULL, 0, addr, stack_entry->start,
3645 			   VM_MAPTYPE_NORMAL,
3646 			   VM_PROT_ALL, VM_PROT_ALL,
3647 			   0);
3648 
3649 	/* Adjust the available stack space by the amount we grew. */
3650 	if (rv == KERN_SUCCESS) {
3651 		if (prev_entry != &map->header)
3652 			vm_map_clip_end(map, prev_entry, addr, &count);
3653 		new_stack_entry = prev_entry->next;
3654 		if (new_stack_entry->end   != stack_entry->start  ||
3655 		    new_stack_entry->start != addr)
3656 			panic ("Bad stack grow start/end in new stack entry");
3657 		else {
3658 			new_stack_entry->aux.avail_ssize =
3659 				stack_entry->aux.avail_ssize -
3660 				(new_stack_entry->end - new_stack_entry->start);
3661 			if (is_procstack)
3662 				vm->vm_ssize += btoc(new_stack_entry->end -
3663 						     new_stack_entry->start);
3664 		}
3665 
3666 		if (map->flags & MAP_WIREFUTURE)
3667 			vm_map_unwire(map, new_stack_entry->start,
3668 				      new_stack_entry->end, FALSE);
3669 	}
3670 
3671 done:
3672 	if (use_read_lock)
3673 		vm_map_unlock_read(map);
3674 	else
3675 		vm_map_unlock(map);
3676 	vm_map_entry_release(count);
3677 	return (rv);
3678 }
3679 
3680 /*
3681  * Unshare the specified VM space for exec.  If other processes are
3682  * mapped to it, then create a new one.  The new vmspace is null.
3683  *
3684  * No requirements.
3685  */
3686 void
3687 vmspace_exec(struct proc *p, struct vmspace *vmcopy)
3688 {
3689 	struct vmspace *oldvmspace = p->p_vmspace;
3690 	struct vmspace *newvmspace;
3691 	vm_map_t map = &p->p_vmspace->vm_map;
3692 
3693 	/*
3694 	 * If we are execing a resident vmspace we fork it, otherwise
3695 	 * we create a new vmspace.  Note that exitingcnt is not
3696 	 * copied to the new vmspace.
3697 	 */
3698 	lwkt_gettoken(&oldvmspace->vm_map.token);
3699 	if (vmcopy)  {
3700 		newvmspace = vmspace_fork(vmcopy);
3701 		lwkt_gettoken(&newvmspace->vm_map.token);
3702 	} else {
3703 		newvmspace = vmspace_alloc(map->min_offset, map->max_offset);
3704 		lwkt_gettoken(&newvmspace->vm_map.token);
3705 		bcopy(&oldvmspace->vm_startcopy, &newvmspace->vm_startcopy,
3706 		      (caddr_t)&oldvmspace->vm_endcopy -
3707 		       (caddr_t)&oldvmspace->vm_startcopy);
3708 	}
3709 
3710 	/*
3711 	 * Finish initializing the vmspace before assigning it
3712 	 * to the process.  The vmspace will become the current vmspace
3713 	 * if p == curproc.
3714 	 */
3715 	pmap_pinit2(vmspace_pmap(newvmspace));
3716 	pmap_replacevm(p, newvmspace, 0);
3717 	lwkt_reltoken(&newvmspace->vm_map.token);
3718 	lwkt_reltoken(&oldvmspace->vm_map.token);
3719 	vmspace_free(oldvmspace);
3720 }
3721 
3722 /*
3723  * Unshare the specified VM space for forcing COW.  This
3724  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3725  */
3726 void
3727 vmspace_unshare(struct proc *p)
3728 {
3729 	struct vmspace *oldvmspace = p->p_vmspace;
3730 	struct vmspace *newvmspace;
3731 
3732 	lwkt_gettoken(&oldvmspace->vm_map.token);
3733 	if (oldvmspace->vm_sysref.refcnt == 1) {
3734 		lwkt_reltoken(&oldvmspace->vm_map.token);
3735 		return;
3736 	}
3737 	newvmspace = vmspace_fork(oldvmspace);
3738 	lwkt_gettoken(&newvmspace->vm_map.token);
3739 	pmap_pinit2(vmspace_pmap(newvmspace));
3740 	pmap_replacevm(p, newvmspace, 0);
3741 	lwkt_reltoken(&newvmspace->vm_map.token);
3742 	lwkt_reltoken(&oldvmspace->vm_map.token);
3743 	vmspace_free(oldvmspace);
3744 }
3745 
3746 /*
3747  * vm_map_hint: return the beginning of the best area suitable for
3748  * creating a new mapping with "prot" protection.
3749  *
3750  * No requirements.
3751  */
3752 vm_offset_t
3753 vm_map_hint(struct proc *p, vm_offset_t addr, vm_prot_t prot)
3754 {
3755 	struct vmspace *vms = p->p_vmspace;
3756 
3757 	if (!randomize_mmap) {
3758 		/*
3759 		 * Set a reasonable start point for the hint if it was
3760 		 * not specified or if it falls within the heap space.
3761 		 * Hinted mmap()s do not allocate out of the heap space.
3762 		 */
3763 		if (addr == 0 ||
3764 		    (addr >= round_page((vm_offset_t)vms->vm_taddr) &&
3765 		     addr < round_page((vm_offset_t)vms->vm_daddr + maxdsiz))) {
3766 			addr = round_page((vm_offset_t)vms->vm_daddr + maxdsiz);
3767 		}
3768 
3769 		return addr;
3770 	}
3771 
3772 	if (addr != 0 && addr >= (vm_offset_t)vms->vm_daddr)
3773 		return addr;
3774 
3775 #ifdef notyet
3776 #ifdef __i386__
3777 	/*
3778 	 * If executable skip first two pages, otherwise start
3779 	 * after data + heap region.
3780 	 */
3781 	if ((prot & VM_PROT_EXECUTE) &&
3782 	    ((vm_offset_t)vms->vm_daddr >= I386_MAX_EXE_ADDR)) {
3783 		addr = (PAGE_SIZE * 2) +
3784 		    (karc4random() & (I386_MAX_EXE_ADDR / 2 - 1));
3785 		return (round_page(addr));
3786 	}
3787 #endif /* __i386__ */
3788 #endif /* notyet */
3789 
3790 	addr = (vm_offset_t)vms->vm_daddr + MAXDSIZ;
3791 	addr += karc4random() & (MIN((256 * 1024 * 1024), MAXDSIZ) - 1);
3792 
3793 	return (round_page(addr));
3794 }
3795 
3796 /*
3797  * Finds the VM object, offset, and protection for a given virtual address
3798  * in the specified map, assuming a page fault of the type specified.
3799  *
3800  * Leaves the map in question locked for read; return values are guaranteed
3801  * until a vm_map_lookup_done call is performed.  Note that the map argument
3802  * is in/out; the returned map must be used in the call to vm_map_lookup_done.
3803  *
3804  * A handle (out_entry) is returned for use in vm_map_lookup_done, to make
3805  * that fast.
3806  *
3807  * If a lookup is requested with "write protection" specified, the map may
3808  * be changed to perform virtual copying operations, although the data
3809  * referenced will remain the same.
3810  *
3811  * No requirements.
3812  */
3813 int
3814 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
3815 	      vm_offset_t vaddr,
3816 	      vm_prot_t fault_typea,
3817 	      vm_map_entry_t *out_entry,	/* OUT */
3818 	      vm_object_t *object,		/* OUT */
3819 	      vm_pindex_t *pindex,		/* OUT */
3820 	      vm_prot_t *out_prot,		/* OUT */
3821 	      boolean_t *wired)			/* OUT */
3822 {
3823 	vm_map_entry_t entry;
3824 	vm_map_t map = *var_map;
3825 	vm_prot_t prot;
3826 	vm_prot_t fault_type = fault_typea;
3827 	int use_read_lock = 1;
3828 	int rv = KERN_SUCCESS;
3829 
3830 RetryLookup:
3831 	if (use_read_lock)
3832 		vm_map_lock_read(map);
3833 	else
3834 		vm_map_lock(map);
3835 
3836 	/*
3837 	 * If the map has an interesting hint, try it before calling full
3838 	 * blown lookup routine.
3839 	 */
3840 	entry = map->hint;
3841 	cpu_ccfence();
3842 	*out_entry = entry;
3843 	*object = NULL;
3844 
3845 	if ((entry == &map->header) ||
3846 	    (vaddr < entry->start) || (vaddr >= entry->end)) {
3847 		vm_map_entry_t tmp_entry;
3848 
3849 		/*
3850 		 * Entry was either not a valid hint, or the vaddr was not
3851 		 * contained in the entry, so do a full lookup.
3852 		 */
3853 		if (!vm_map_lookup_entry(map, vaddr, &tmp_entry)) {
3854 			rv = KERN_INVALID_ADDRESS;
3855 			goto done;
3856 		}
3857 
3858 		entry = tmp_entry;
3859 		*out_entry = entry;
3860 	}
3861 
3862 	/*
3863 	 * Handle submaps.
3864 	 */
3865 	if (entry->maptype == VM_MAPTYPE_SUBMAP) {
3866 		vm_map_t old_map = map;
3867 
3868 		*var_map = map = entry->object.sub_map;
3869 		if (use_read_lock)
3870 			vm_map_unlock_read(old_map);
3871 		else
3872 			vm_map_unlock(old_map);
3873 		use_read_lock = 1;
3874 		goto RetryLookup;
3875 	}
3876 
3877 	/*
3878 	 * Check whether this task is allowed to have this page.
3879 	 * Note the special case for MAP_ENTRY_COW
3880 	 * pages with an override.  This is to implement a forced
3881 	 * COW for debuggers.
3882 	 */
3883 
3884 	if (fault_type & VM_PROT_OVERRIDE_WRITE)
3885 		prot = entry->max_protection;
3886 	else
3887 		prot = entry->protection;
3888 
3889 	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3890 	if ((fault_type & prot) != fault_type) {
3891 		rv = KERN_PROTECTION_FAILURE;
3892 		goto done;
3893 	}
3894 
3895 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3896 	    (entry->eflags & MAP_ENTRY_COW) &&
3897 	    (fault_type & VM_PROT_WRITE) &&
3898 	    (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
3899 		rv = KERN_PROTECTION_FAILURE;
3900 		goto done;
3901 	}
3902 
3903 	/*
3904 	 * If this page is not pageable, we have to get it for all possible
3905 	 * accesses.
3906 	 */
3907 	*wired = (entry->wired_count != 0);
3908 	if (*wired)
3909 		prot = fault_type = entry->protection;
3910 
3911 	/*
3912 	 * Virtual page tables may need to update the accessed (A) bit
3913 	 * in a page table entry.  Upgrade the fault to a write fault for
3914 	 * that case if the map will support it.  If the map does not support
3915 	 * it the page table entry simply will not be updated.
3916 	 */
3917 	if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
3918 		if (prot & VM_PROT_WRITE)
3919 			fault_type |= VM_PROT_WRITE;
3920 	}
3921 
3922 	/*
3923 	 * If the entry was copy-on-write, we either ...
3924 	 */
3925 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3926 		/*
3927 		 * If we want to write the page, we may as well handle that
3928 		 * now since we've got the map locked.
3929 		 *
3930 		 * If we don't need to write the page, we just demote the
3931 		 * permissions allowed.
3932 		 */
3933 
3934 		if (fault_type & VM_PROT_WRITE) {
3935 			/*
3936 			 * Make a new object, and place it in the object
3937 			 * chain.  Note that no new references have appeared
3938 			 * -- one just moved from the map to the new
3939 			 * object.
3940 			 */
3941 
3942 			if (use_read_lock && vm_map_lock_upgrade(map)) {
3943 				/* lost lock */
3944 				use_read_lock = 0;
3945 				goto RetryLookup;
3946 			}
3947 			use_read_lock = 0;
3948 
3949 			vm_map_entry_shadow(entry, 0);
3950 		} else {
3951 			/*
3952 			 * We're attempting to read a copy-on-write page --
3953 			 * don't allow writes.
3954 			 */
3955 
3956 			prot &= ~VM_PROT_WRITE;
3957 		}
3958 	}
3959 
3960 	/*
3961 	 * Create an object if necessary.
3962 	 */
3963 	if (entry->object.vm_object == NULL && !map->system_map) {
3964 		if (use_read_lock && vm_map_lock_upgrade(map))  {
3965 			/* lost lock */
3966 			use_read_lock = 0;
3967 			goto RetryLookup;
3968 		}
3969 		use_read_lock = 0;
3970 		vm_map_entry_allocate_object(entry);
3971 	}
3972 
3973 	/*
3974 	 * Return the object/offset from this entry.  If the entry was
3975 	 * copy-on-write or empty, it has been fixed up.
3976 	 */
3977 
3978 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3979 	*object = entry->object.vm_object;
3980 
3981 	/*
3982 	 * Return whether this is the only map sharing this data.  On
3983 	 * success we return with a read lock held on the map.  On failure
3984 	 * we return with the map unlocked.
3985 	 */
3986 	*out_prot = prot;
3987 done:
3988 	if (rv == KERN_SUCCESS) {
3989 		if (use_read_lock == 0)
3990 			vm_map_lock_downgrade(map);
3991 	} else if (use_read_lock) {
3992 		vm_map_unlock_read(map);
3993 	} else {
3994 		vm_map_unlock(map);
3995 	}
3996 	return (rv);
3997 }
3998 
3999 /*
4000  * Releases locks acquired by a vm_map_lookup()
4001  * (according to the handle returned by that lookup).
4002  *
4003  * No other requirements.
4004  */
4005 void
4006 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry, int count)
4007 {
4008 	/*
4009 	 * Unlock the main-level map
4010 	 */
4011 	vm_map_unlock_read(map);
4012 	if (count)
4013 		vm_map_entry_release(count);
4014 }
4015 
4016 #include "opt_ddb.h"
4017 #ifdef DDB
4018 #include <sys/kernel.h>
4019 
4020 #include <ddb/ddb.h>
4021 
4022 /*
4023  * Debugging only
4024  */
4025 DB_SHOW_COMMAND(map, vm_map_print)
4026 {
4027 	static int nlines;
4028 	/* XXX convert args. */
4029 	vm_map_t map = (vm_map_t)addr;
4030 	boolean_t full = have_addr;
4031 
4032 	vm_map_entry_t entry;
4033 
4034 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4035 	    (void *)map,
4036 	    (void *)map->pmap, map->nentries, map->timestamp);
4037 	nlines++;
4038 
4039 	if (!full && db_indent)
4040 		return;
4041 
4042 	db_indent += 2;
4043 	for (entry = map->header.next; entry != &map->header;
4044 	    entry = entry->next) {
4045 		db_iprintf("map entry %p: start=%p, end=%p\n",
4046 		    (void *)entry, (void *)entry->start, (void *)entry->end);
4047 		nlines++;
4048 		{
4049 			static char *inheritance_name[4] =
4050 			{"share", "copy", "none", "donate_copy"};
4051 
4052 			db_iprintf(" prot=%x/%x/%s",
4053 			    entry->protection,
4054 			    entry->max_protection,
4055 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
4056 			if (entry->wired_count != 0)
4057 				db_printf(", wired");
4058 		}
4059 		if (entry->maptype == VM_MAPTYPE_SUBMAP) {
4060 			/* XXX no %qd in kernel.  Truncate entry->offset. */
4061 			db_printf(", share=%p, offset=0x%lx\n",
4062 			    (void *)entry->object.sub_map,
4063 			    (long)entry->offset);
4064 			nlines++;
4065 			if ((entry->prev == &map->header) ||
4066 			    (entry->prev->object.sub_map !=
4067 				entry->object.sub_map)) {
4068 				db_indent += 2;
4069 				vm_map_print((db_expr_t)(intptr_t)
4070 					     entry->object.sub_map,
4071 					     full, 0, NULL);
4072 				db_indent -= 2;
4073 			}
4074 		} else {
4075 			/* XXX no %qd in kernel.  Truncate entry->offset. */
4076 			db_printf(", object=%p, offset=0x%lx",
4077 			    (void *)entry->object.vm_object,
4078 			    (long)entry->offset);
4079 			if (entry->eflags & MAP_ENTRY_COW)
4080 				db_printf(", copy (%s)",
4081 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4082 			db_printf("\n");
4083 			nlines++;
4084 
4085 			if ((entry->prev == &map->header) ||
4086 			    (entry->prev->object.vm_object !=
4087 				entry->object.vm_object)) {
4088 				db_indent += 2;
4089 				vm_object_print((db_expr_t)(intptr_t)
4090 						entry->object.vm_object,
4091 						full, 0, NULL);
4092 				nlines += 4;
4093 				db_indent -= 2;
4094 			}
4095 		}
4096 	}
4097 	db_indent -= 2;
4098 	if (db_indent == 0)
4099 		nlines = 0;
4100 }
4101 
4102 /*
4103  * Debugging only
4104  */
4105 DB_SHOW_COMMAND(procvm, procvm)
4106 {
4107 	struct proc *p;
4108 
4109 	if (have_addr) {
4110 		p = (struct proc *) addr;
4111 	} else {
4112 		p = curproc;
4113 	}
4114 
4115 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4116 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4117 	    (void *)vmspace_pmap(p->p_vmspace));
4118 
4119 	vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
4120 }
4121 
4122 #endif /* DDB */
4123