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