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