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