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