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