xref: /freebsd/sys/vm/vm_map.c (revision 5773cccf19ef7b97e56c1101aa481c43149224da)
1 /*
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
37  *
38  *
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
43  *
44  * Permission to use, copy, modify and distribute this software and
45  * its documentation is hereby granted, provided that both the copyright
46  * notice and this permission notice appear in all copies of the
47  * software, derivative works or modified versions, and any portions
48  * thereof, and that both notices appear in supporting documentation.
49  *
50  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
53  *
54  * Carnegie Mellon requests users of this software to return to
55  *
56  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
57  *  School of Computer Science
58  *  Carnegie Mellon University
59  *  Pittsburgh PA 15213-3890
60  *
61  * any improvements or extensions that they make and grant Carnegie the
62  * rights to redistribute these changes.
63  *
64  * $FreeBSD$
65  */
66 
67 /*
68  *	Virtual memory mapping module.
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/ktr.h>
74 #include <sys/lock.h>
75 #include <sys/mutex.h>
76 #include <sys/proc.h>
77 #include <sys/vmmeter.h>
78 #include <sys/mman.h>
79 #include <sys/vnode.h>
80 #include <sys/resourcevar.h>
81 #include <sys/sysent.h>
82 #include <sys/stdint.h>
83 
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_pager.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
93 #include <vm/swap_pager.h>
94 #include <vm/uma.h>
95 
96 /*
97  *	Virtual memory maps provide for the mapping, protection,
98  *	and sharing of virtual memory objects.  In addition,
99  *	this module provides for an efficient virtual copy of
100  *	memory from one map to another.
101  *
102  *	Synchronization is required prior to most operations.
103  *
104  *	Maps consist of an ordered doubly-linked list of simple
105  *	entries; a single hint is used to speed up lookups.
106  *
107  *	Since portions of maps are specified by start/end addresses,
108  *	which may not align with existing map entries, all
109  *	routines merely "clip" entries to these start/end values.
110  *	[That is, an entry is split into two, bordering at a
111  *	start or end value.]  Note that these clippings may not
112  *	always be necessary (as the two resulting entries are then
113  *	not changed); however, the clipping is done for convenience.
114  *
115  *	As mentioned above, virtual copy operations are performed
116  *	by copying VM object references from one map to
117  *	another, and then marking both regions as copy-on-write.
118  */
119 
120 /*
121  *	vm_map_startup:
122  *
123  *	Initialize the vm_map module.  Must be called before
124  *	any other vm_map routines.
125  *
126  *	Map and entry structures are allocated from the general
127  *	purpose memory pool with some exceptions:
128  *
129  *	- The kernel map and kmem submap are allocated statically.
130  *	- Kernel map entries are allocated out of a static pool.
131  *
132  *	These restrictions are necessary since malloc() uses the
133  *	maps and requires map entries.
134  */
135 
136 static uma_zone_t mapentzone;
137 static uma_zone_t kmapentzone;
138 static uma_zone_t mapzone;
139 static uma_zone_t vmspace_zone;
140 static struct vm_object kmapentobj;
141 static void vmspace_zinit(void *mem, int size);
142 static void vmspace_zfini(void *mem, int size);
143 static void vm_map_zinit(void *mem, int size);
144 static void vm_map_zfini(void *mem, int size);
145 static void _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max);
146 
147 #ifdef INVARIANTS
148 static void vm_map_zdtor(void *mem, int size, void *arg);
149 static void vmspace_zdtor(void *mem, int size, void *arg);
150 #endif
151 
152 void
153 vm_map_startup(void)
154 {
155 	mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
156 #ifdef INVARIANTS
157 	    vm_map_zdtor,
158 #else
159 	    NULL,
160 #endif
161 	    vm_map_zinit, vm_map_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
162 	uma_prealloc(mapzone, MAX_KMAP);
163 	kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
164 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
165 	    UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
166 	uma_prealloc(kmapentzone, MAX_KMAPENT);
167 	mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
168 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
169 	uma_prealloc(mapentzone, MAX_MAPENT);
170 }
171 
172 static void
173 vmspace_zfini(void *mem, int size)
174 {
175 	struct vmspace *vm;
176 
177 	vm = (struct vmspace *)mem;
178 
179 	vm_map_zfini(&vm->vm_map, sizeof(vm->vm_map));
180 }
181 
182 static void
183 vmspace_zinit(void *mem, int size)
184 {
185 	struct vmspace *vm;
186 
187 	vm = (struct vmspace *)mem;
188 
189 	vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map));
190 }
191 
192 static void
193 vm_map_zfini(void *mem, int size)
194 {
195 	vm_map_t map;
196 
197 	map = (vm_map_t)mem;
198 
199 	lockdestroy(&map->lock);
200 }
201 
202 static void
203 vm_map_zinit(void *mem, int size)
204 {
205 	vm_map_t map;
206 
207 	map = (vm_map_t)mem;
208 	map->nentries = 0;
209 	map->size = 0;
210 	map->infork = 0;
211 	lockinit(&map->lock, PVM, "thrd_sleep", 0, LK_NOPAUSE);
212 }
213 
214 #ifdef INVARIANTS
215 static void
216 vmspace_zdtor(void *mem, int size, void *arg)
217 {
218 	struct vmspace *vm;
219 
220 	vm = (struct vmspace *)mem;
221 
222 	vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
223 }
224 static void
225 vm_map_zdtor(void *mem, int size, void *arg)
226 {
227 	vm_map_t map;
228 
229 	map = (vm_map_t)mem;
230 	KASSERT(map->nentries == 0,
231 	    ("map %p nentries == %d on free.",
232 	    map, map->nentries));
233 	KASSERT(map->size == 0,
234 	    ("map %p size == %lu on free.",
235 	    map, (unsigned long)map->size));
236 	KASSERT(map->infork == 0,
237 	    ("map %p infork == %d on free.",
238 	    map, map->infork));
239 }
240 #endif	/* INVARIANTS */
241 
242 /*
243  * Allocate a vmspace structure, including a vm_map and pmap,
244  * and initialize those structures.  The refcnt is set to 1.
245  * The remaining fields must be initialized by the caller.
246  */
247 struct vmspace *
248 vmspace_alloc(min, max)
249 	vm_offset_t min, max;
250 {
251 	struct vmspace *vm;
252 
253 	GIANT_REQUIRED;
254 	vm = uma_zalloc(vmspace_zone, M_WAITOK);
255 	CTR1(KTR_VM, "vmspace_alloc: %p", vm);
256 	_vm_map_init(&vm->vm_map, min, max);
257 	pmap_pinit(vmspace_pmap(vm));
258 	vm->vm_map.pmap = vmspace_pmap(vm);		/* XXX */
259 	vm->vm_refcnt = 1;
260 	vm->vm_shm = NULL;
261 	vm->vm_freer = NULL;
262 	return (vm);
263 }
264 
265 void
266 vm_init2(void)
267 {
268 	uma_zone_set_obj(kmapentzone, &kmapentobj, lmin(cnt.v_page_count,
269 	    (VM_MAX_KERNEL_ADDRESS - KERNBASE) / PAGE_SIZE) / 8);
270 	vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
271 #ifdef INVARIANTS
272 	    vmspace_zdtor,
273 #else
274 	    NULL,
275 #endif
276 	    vmspace_zinit, vmspace_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
277 	pmap_init2();
278 	vm_object_init2();
279 }
280 
281 static __inline void
282 vmspace_dofree(struct vmspace *vm)
283 {
284 	CTR1(KTR_VM, "vmspace_free: %p", vm);
285 	/*
286 	 * Lock the map, to wait out all other references to it.
287 	 * Delete all of the mappings and pages they hold, then call
288 	 * the pmap module to reclaim anything left.
289 	 */
290 	vm_map_lock(&vm->vm_map);
291 	(void) vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
292 	    vm->vm_map.max_offset);
293 	vm_map_unlock(&vm->vm_map);
294 
295 	pmap_release(vmspace_pmap(vm));
296 	uma_zfree(vmspace_zone, vm);
297 }
298 
299 void
300 vmspace_free(struct vmspace *vm)
301 {
302 	GIANT_REQUIRED;
303 
304 	if (vm->vm_refcnt == 0)
305 		panic("vmspace_free: attempt to free already freed vmspace");
306 
307 	if (--vm->vm_refcnt == 0)
308 		vmspace_dofree(vm);
309 }
310 
311 void
312 vmspace_exitfree(struct proc *p)
313 {
314 	struct vmspace *vm;
315 
316 	GIANT_REQUIRED;
317 	if (p == p->p_vmspace->vm_freer) {
318 		vm = p->p_vmspace;
319 		p->p_vmspace = NULL;
320 		vmspace_dofree(vm);
321 	}
322 }
323 
324 /*
325  * vmspace_swap_count() - count the approximate swap useage in pages for a
326  *			  vmspace.
327  *
328  *	Swap useage is determined by taking the proportional swap used by
329  *	VM objects backing the VM map.  To make up for fractional losses,
330  *	if the VM object has any swap use at all the associated map entries
331  *	count for at least 1 swap page.
332  */
333 int
334 vmspace_swap_count(struct vmspace *vmspace)
335 {
336 	vm_map_t map = &vmspace->vm_map;
337 	vm_map_entry_t cur;
338 	int count = 0;
339 
340 	vm_map_lock_read(map);
341 	for (cur = map->header.next; cur != &map->header; cur = cur->next) {
342 		vm_object_t object;
343 
344 		if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
345 		    (object = cur->object.vm_object) != NULL &&
346 		    object->type == OBJT_SWAP
347 		) {
348 			int n = (cur->end - cur->start) / PAGE_SIZE;
349 
350 			if (object->un_pager.swp.swp_bcount) {
351 				count += object->un_pager.swp.swp_bcount *
352 				    SWAP_META_PAGES * n / object->size + 1;
353 			}
354 		}
355 	}
356 	vm_map_unlock_read(map);
357 	return (count);
358 }
359 
360 void
361 _vm_map_lock(vm_map_t map, const char *file, int line)
362 {
363 	int error;
364 
365 	if (map->system_map)
366 		GIANT_REQUIRED;
367 	error = lockmgr(&map->lock, LK_EXCLUSIVE, NULL, curthread);
368 	KASSERT(error == 0, ("%s: failed to get lock", __func__));
369 	map->timestamp++;
370 }
371 
372 void
373 _vm_map_unlock(vm_map_t map, const char *file, int line)
374 {
375 
376 	lockmgr(&map->lock, LK_RELEASE, NULL, curthread);
377 }
378 
379 void
380 _vm_map_lock_read(vm_map_t map, const char *file, int line)
381 {
382 	int error;
383 
384 	if (map->system_map)
385 		GIANT_REQUIRED;
386 	error = lockmgr(&map->lock, LK_EXCLUSIVE, NULL, curthread);
387 	KASSERT(error == 0, ("%s: failed to get lock", __func__));
388 }
389 
390 void
391 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
392 {
393 
394 	lockmgr(&map->lock, LK_RELEASE, NULL, curthread);
395 }
396 
397 int
398 _vm_map_trylock(vm_map_t map, const char *file, int line)
399 {
400 	int error;
401 
402 	if (map->system_map)
403 		GIANT_REQUIRED;
404 	error = lockmgr(&map->lock, LK_EXCLUSIVE | LK_NOWAIT, NULL, curthread);
405 	return (error == 0);
406 }
407 
408 int
409 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
410 {
411 
412 	KASSERT(lockstatus(&map->lock, curthread) == LK_EXCLUSIVE,
413 		("%s: lock not held", __func__));
414 	map->timestamp++;
415 	return (0);
416 }
417 
418 void
419 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
420 {
421 
422 	KASSERT(lockstatus(&map->lock, curthread) == LK_EXCLUSIVE,
423 		("%s: lock not held", __func__));
424 }
425 
426 /*
427  *	vm_map_unlock_and_wait:
428  */
429 int
430 vm_map_unlock_and_wait(vm_map_t map, boolean_t user_wait)
431 {
432 	int retval;
433 
434 	mtx_lock(&Giant);
435 	vm_map_unlock(map);
436 	retval = tsleep(&map->root, PVM, "vmmapw", 0);
437 	mtx_unlock(&Giant);
438 	return (retval);
439 }
440 
441 /*
442  *	vm_map_wakeup:
443  */
444 void
445 vm_map_wakeup(vm_map_t map)
446 {
447 
448 	/*
449 	 * Acquire and release Giant to prevent a wakeup() from being
450 	 * performed (and lost) between the vm_map_unlock() and the
451 	 * tsleep() in vm_map_unlock_and_wait().
452 	 */
453 	mtx_lock(&Giant);
454 	mtx_unlock(&Giant);
455 	wakeup(&map->root);
456 }
457 
458 long
459 vmspace_resident_count(struct vmspace *vmspace)
460 {
461 	return pmap_resident_count(vmspace_pmap(vmspace));
462 }
463 
464 /*
465  *	vm_map_create:
466  *
467  *	Creates and returns a new empty VM map with
468  *	the given physical map structure, and having
469  *	the given lower and upper address bounds.
470  */
471 vm_map_t
472 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
473 {
474 	vm_map_t result;
475 
476 	result = uma_zalloc(mapzone, M_WAITOK);
477 	CTR1(KTR_VM, "vm_map_create: %p", result);
478 	_vm_map_init(result, min, max);
479 	result->pmap = pmap;
480 	return (result);
481 }
482 
483 /*
484  * Initialize an existing vm_map structure
485  * such as that in the vmspace structure.
486  * The pmap is set elsewhere.
487  */
488 static void
489 _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
490 {
491 
492 	map->header.next = map->header.prev = &map->header;
493 	map->needs_wakeup = FALSE;
494 	map->system_map = 0;
495 	map->min_offset = min;
496 	map->max_offset = max;
497 	map->first_free = &map->header;
498 	map->root = NULL;
499 	map->timestamp = 0;
500 }
501 
502 void
503 vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
504 {
505 	_vm_map_init(map, min, max);
506 	lockinit(&map->lock, PVM, "thrd_sleep", 0, LK_NOPAUSE);
507 }
508 
509 /*
510  *	vm_map_entry_dispose:	[ internal use only ]
511  *
512  *	Inverse of vm_map_entry_create.
513  */
514 static void
515 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
516 {
517 	uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
518 }
519 
520 /*
521  *	vm_map_entry_create:	[ internal use only ]
522  *
523  *	Allocates a VM map entry for insertion.
524  *	No entry fields are filled in.
525  */
526 static vm_map_entry_t
527 vm_map_entry_create(vm_map_t map)
528 {
529 	vm_map_entry_t new_entry;
530 
531 	if (map->system_map)
532 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
533 	else
534 		new_entry = uma_zalloc(mapentzone, M_WAITOK);
535 	if (new_entry == NULL)
536 		panic("vm_map_entry_create: kernel resources exhausted");
537 	return (new_entry);
538 }
539 
540 /*
541  *	vm_map_entry_set_behavior:
542  *
543  *	Set the expected access behavior, either normal, random, or
544  *	sequential.
545  */
546 static __inline void
547 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
548 {
549 	entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
550 	    (behavior & MAP_ENTRY_BEHAV_MASK);
551 }
552 
553 /*
554  *	vm_map_entry_splay:
555  *
556  *	Implements Sleator and Tarjan's top-down splay algorithm.  Returns
557  *	the vm_map_entry containing the given address.  If, however, that
558  *	address is not found in the vm_map, returns a vm_map_entry that is
559  *	adjacent to the address, coming before or after it.
560  */
561 static vm_map_entry_t
562 vm_map_entry_splay(vm_offset_t address, vm_map_entry_t root)
563 {
564 	struct vm_map_entry dummy;
565 	vm_map_entry_t lefttreemax, righttreemin, y;
566 
567 	if (root == NULL)
568 		return (root);
569 	lefttreemax = righttreemin = &dummy;
570 	for (;; root = y) {
571 		if (address < root->start) {
572 			if ((y = root->left) == NULL)
573 				break;
574 			if (address < y->start) {
575 				/* Rotate right. */
576 				root->left = y->right;
577 				y->right = root;
578 				root = y;
579 				if ((y = root->left) == NULL)
580 					break;
581 			}
582 			/* Link into the new root's right tree. */
583 			righttreemin->left = root;
584 			righttreemin = root;
585 		} else if (address >= root->end) {
586 			if ((y = root->right) == NULL)
587 				break;
588 			if (address >= y->end) {
589 				/* Rotate left. */
590 				root->right = y->left;
591 				y->left = root;
592 				root = y;
593 				if ((y = root->right) == NULL)
594 					break;
595 			}
596 			/* Link into the new root's left tree. */
597 			lefttreemax->right = root;
598 			lefttreemax = root;
599 		} else
600 			break;
601 	}
602 	/* Assemble the new root. */
603 	lefttreemax->right = root->left;
604 	righttreemin->left = root->right;
605 	root->left = dummy.right;
606 	root->right = dummy.left;
607 	return (root);
608 }
609 
610 /*
611  *	vm_map_entry_{un,}link:
612  *
613  *	Insert/remove entries from maps.
614  */
615 static void
616 vm_map_entry_link(vm_map_t map,
617 		  vm_map_entry_t after_where,
618 		  vm_map_entry_t entry)
619 {
620 
621 	CTR4(KTR_VM,
622 	    "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
623 	    map->nentries, entry, after_where);
624 	map->nentries++;
625 	entry->prev = after_where;
626 	entry->next = after_where->next;
627 	entry->next->prev = entry;
628 	after_where->next = entry;
629 
630 	if (after_where != &map->header) {
631 		if (after_where != map->root)
632 			vm_map_entry_splay(after_where->start, map->root);
633 		entry->right = after_where->right;
634 		entry->left = after_where;
635 		after_where->right = NULL;
636 	} else {
637 		entry->right = map->root;
638 		entry->left = NULL;
639 	}
640 	map->root = entry;
641 }
642 
643 static void
644 vm_map_entry_unlink(vm_map_t map,
645 		    vm_map_entry_t entry)
646 {
647 	vm_map_entry_t next, prev, root;
648 
649 	if (entry != map->root)
650 		vm_map_entry_splay(entry->start, map->root);
651 	if (entry->left == NULL)
652 		root = entry->right;
653 	else {
654 		root = vm_map_entry_splay(entry->start, entry->left);
655 		root->right = entry->right;
656 	}
657 	map->root = root;
658 
659 	prev = entry->prev;
660 	next = entry->next;
661 	next->prev = prev;
662 	prev->next = next;
663 	map->nentries--;
664 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
665 	    map->nentries, entry);
666 }
667 
668 /*
669  *	vm_map_lookup_entry:	[ internal use only ]
670  *
671  *	Finds the map entry containing (or
672  *	immediately preceding) the specified address
673  *	in the given map; the entry is returned
674  *	in the "entry" parameter.  The boolean
675  *	result indicates whether the address is
676  *	actually contained in the map.
677  */
678 boolean_t
679 vm_map_lookup_entry(
680 	vm_map_t map,
681 	vm_offset_t address,
682 	vm_map_entry_t *entry)	/* OUT */
683 {
684 	vm_map_entry_t cur;
685 
686 	cur = vm_map_entry_splay(address, map->root);
687 	if (cur == NULL)
688 		*entry = &map->header;
689 	else {
690 		map->root = cur;
691 
692 		if (address >= cur->start) {
693 			*entry = cur;
694 			if (cur->end > address)
695 				return (TRUE);
696 		} else
697 			*entry = cur->prev;
698 	}
699 	return (FALSE);
700 }
701 
702 /*
703  *	vm_map_insert:
704  *
705  *	Inserts the given whole VM object into the target
706  *	map at the specified address range.  The object's
707  *	size should match that of the address range.
708  *
709  *	Requires that the map be locked, and leaves it so.
710  *
711  *	If object is non-NULL, ref count must be bumped by caller
712  *	prior to making call to account for the new entry.
713  */
714 int
715 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
716 	      vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max,
717 	      int cow)
718 {
719 	vm_map_entry_t new_entry;
720 	vm_map_entry_t prev_entry;
721 	vm_map_entry_t temp_entry;
722 	vm_eflags_t protoeflags;
723 
724 	/*
725 	 * Check that the start and end points are not bogus.
726 	 */
727 	if ((start < map->min_offset) || (end > map->max_offset) ||
728 	    (start >= end))
729 		return (KERN_INVALID_ADDRESS);
730 
731 	/*
732 	 * Find the entry prior to the proposed starting address; if it's part
733 	 * of an existing entry, this range is bogus.
734 	 */
735 	if (vm_map_lookup_entry(map, start, &temp_entry))
736 		return (KERN_NO_SPACE);
737 
738 	prev_entry = temp_entry;
739 
740 	/*
741 	 * Assert that the next entry doesn't overlap the end point.
742 	 */
743 	if ((prev_entry->next != &map->header) &&
744 	    (prev_entry->next->start < end))
745 		return (KERN_NO_SPACE);
746 
747 	protoeflags = 0;
748 
749 	if (cow & MAP_COPY_ON_WRITE)
750 		protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
751 
752 	if (cow & MAP_NOFAULT) {
753 		protoeflags |= MAP_ENTRY_NOFAULT;
754 
755 		KASSERT(object == NULL,
756 			("vm_map_insert: paradoxical MAP_NOFAULT request"));
757 	}
758 	if (cow & MAP_DISABLE_SYNCER)
759 		protoeflags |= MAP_ENTRY_NOSYNC;
760 	if (cow & MAP_DISABLE_COREDUMP)
761 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
762 
763 	if (object) {
764 		/*
765 		 * When object is non-NULL, it could be shared with another
766 		 * process.  We have to set or clear OBJ_ONEMAPPING
767 		 * appropriately.
768 		 */
769 		vm_object_lock(object);
770 		if ((object->ref_count > 1) || (object->shadow_count != 0)) {
771 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
772 		}
773 		vm_object_unlock(object);
774 	}
775 	else if ((prev_entry != &map->header) &&
776 		 (prev_entry->eflags == protoeflags) &&
777 		 (prev_entry->end == start) &&
778 		 (prev_entry->wired_count == 0) &&
779 		 ((prev_entry->object.vm_object == NULL) ||
780 		  vm_object_coalesce(prev_entry->object.vm_object,
781 				     OFF_TO_IDX(prev_entry->offset),
782 				     (vm_size_t)(prev_entry->end - prev_entry->start),
783 				     (vm_size_t)(end - prev_entry->end)))) {
784 		/*
785 		 * We were able to extend the object.  Determine if we
786 		 * can extend the previous map entry to include the
787 		 * new range as well.
788 		 */
789 		if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
790 		    (prev_entry->protection == prot) &&
791 		    (prev_entry->max_protection == max)) {
792 			map->size += (end - prev_entry->end);
793 			prev_entry->end = end;
794 			vm_map_simplify_entry(map, prev_entry);
795 			return (KERN_SUCCESS);
796 		}
797 
798 		/*
799 		 * If we can extend the object but cannot extend the
800 		 * map entry, we have to create a new map entry.  We
801 		 * must bump the ref count on the extended object to
802 		 * account for it.  object may be NULL.
803 		 */
804 		object = prev_entry->object.vm_object;
805 		offset = prev_entry->offset +
806 			(prev_entry->end - prev_entry->start);
807 		vm_object_reference(object);
808 	}
809 
810 	/*
811 	 * NOTE: if conditionals fail, object can be NULL here.  This occurs
812 	 * in things like the buffer map where we manage kva but do not manage
813 	 * backing objects.
814 	 */
815 
816 	/*
817 	 * Create a new entry
818 	 */
819 	new_entry = vm_map_entry_create(map);
820 	new_entry->start = start;
821 	new_entry->end = end;
822 
823 	new_entry->eflags = protoeflags;
824 	new_entry->object.vm_object = object;
825 	new_entry->offset = offset;
826 	new_entry->avail_ssize = 0;
827 
828 	new_entry->inheritance = VM_INHERIT_DEFAULT;
829 	new_entry->protection = prot;
830 	new_entry->max_protection = max;
831 	new_entry->wired_count = 0;
832 
833 	/*
834 	 * Insert the new entry into the list
835 	 */
836 	vm_map_entry_link(map, prev_entry, new_entry);
837 	map->size += new_entry->end - new_entry->start;
838 
839 	/*
840 	 * Update the free space hint
841 	 */
842 	if ((map->first_free == prev_entry) &&
843 	    (prev_entry->end >= new_entry->start)) {
844 		map->first_free = new_entry;
845 	}
846 
847 #if 0
848 	/*
849 	 * Temporarily removed to avoid MAP_STACK panic, due to
850 	 * MAP_STACK being a huge hack.  Will be added back in
851 	 * when MAP_STACK (and the user stack mapping) is fixed.
852 	 */
853 	/*
854 	 * It may be possible to simplify the entry
855 	 */
856 	vm_map_simplify_entry(map, new_entry);
857 #endif
858 
859 	if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
860 		mtx_lock(&Giant);
861 		pmap_object_init_pt(map->pmap, start,
862 				    object, OFF_TO_IDX(offset), end - start,
863 				    cow & MAP_PREFAULT_PARTIAL);
864 		mtx_unlock(&Giant);
865 	}
866 
867 	return (KERN_SUCCESS);
868 }
869 
870 /*
871  * Find sufficient space for `length' bytes in the given map, starting at
872  * `start'.  The map must be locked.  Returns 0 on success, 1 on no space.
873  */
874 int
875 vm_map_findspace(
876 	vm_map_t map,
877 	vm_offset_t start,
878 	vm_size_t length,
879 	vm_offset_t *addr)
880 {
881 	vm_map_entry_t entry, next;
882 	vm_offset_t end;
883 
884 	if (start < map->min_offset)
885 		start = map->min_offset;
886 	if (start > map->max_offset)
887 		return (1);
888 
889 	/*
890 	 * Look for the first possible address; if there's already something
891 	 * at this address, we have to start after it.
892 	 */
893 	if (start == map->min_offset) {
894 		if ((entry = map->first_free) != &map->header)
895 			start = entry->end;
896 	} else {
897 		vm_map_entry_t tmp;
898 
899 		if (vm_map_lookup_entry(map, start, &tmp))
900 			start = tmp->end;
901 		entry = tmp;
902 	}
903 
904 	/*
905 	 * Look through the rest of the map, trying to fit a new region in the
906 	 * gap between existing regions, or after the very last region.
907 	 */
908 	for (;; start = (entry = next)->end) {
909 		/*
910 		 * Find the end of the proposed new region.  Be sure we didn't
911 		 * go beyond the end of the map, or wrap around the address;
912 		 * if so, we lose.  Otherwise, if this is the last entry, or
913 		 * if the proposed new region fits before the next entry, we
914 		 * win.
915 		 */
916 		end = start + length;
917 		if (end > map->max_offset || end < start)
918 			return (1);
919 		next = entry->next;
920 		if (next == &map->header || next->start >= end)
921 			break;
922 	}
923 	*addr = start;
924 	if (map == kernel_map) {
925 		vm_offset_t ksize;
926 		if ((ksize = round_page(start + length)) > kernel_vm_end) {
927 			mtx_lock(&Giant);
928 			pmap_growkernel(ksize);
929 			mtx_unlock(&Giant);
930 		}
931 	}
932 	return (0);
933 }
934 
935 /*
936  *	vm_map_find finds an unallocated region in the target address
937  *	map with the given length.  The search is defined to be
938  *	first-fit from the specified address; the region found is
939  *	returned in the same parameter.
940  *
941  *	If object is non-NULL, ref count must be bumped by caller
942  *	prior to making call to account for the new entry.
943  */
944 int
945 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
946 	    vm_offset_t *addr,	/* IN/OUT */
947 	    vm_size_t length, boolean_t find_space, vm_prot_t prot,
948 	    vm_prot_t max, int cow)
949 {
950 	vm_offset_t start;
951 	int result, s = 0;
952 
953 	start = *addr;
954 
955 	if (map == kmem_map)
956 		s = splvm();
957 
958 	vm_map_lock(map);
959 	if (find_space) {
960 		if (vm_map_findspace(map, start, length, addr)) {
961 			vm_map_unlock(map);
962 			if (map == kmem_map)
963 				splx(s);
964 			return (KERN_NO_SPACE);
965 		}
966 		start = *addr;
967 	}
968 	result = vm_map_insert(map, object, offset,
969 		start, start + length, prot, max, cow);
970 	vm_map_unlock(map);
971 
972 	if (map == kmem_map)
973 		splx(s);
974 
975 	return (result);
976 }
977 
978 /*
979  *	vm_map_simplify_entry:
980  *
981  *	Simplify the given map entry by merging with either neighbor.  This
982  *	routine also has the ability to merge with both neighbors.
983  *
984  *	The map must be locked.
985  *
986  *	This routine guarentees that the passed entry remains valid (though
987  *	possibly extended).  When merging, this routine may delete one or
988  *	both neighbors.
989  */
990 void
991 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
992 {
993 	vm_map_entry_t next, prev;
994 	vm_size_t prevsize, esize;
995 
996 	if (entry->eflags & (MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP))
997 		return;
998 
999 	prev = entry->prev;
1000 	if (prev != &map->header) {
1001 		prevsize = prev->end - prev->start;
1002 		if ( (prev->end == entry->start) &&
1003 		     (prev->object.vm_object == entry->object.vm_object) &&
1004 		     (!prev->object.vm_object ||
1005 			(prev->offset + prevsize == entry->offset)) &&
1006 		     (prev->eflags == entry->eflags) &&
1007 		     (prev->protection == entry->protection) &&
1008 		     (prev->max_protection == entry->max_protection) &&
1009 		     (prev->inheritance == entry->inheritance) &&
1010 		     (prev->wired_count == entry->wired_count)) {
1011 			if (map->first_free == prev)
1012 				map->first_free = entry;
1013 			vm_map_entry_unlink(map, prev);
1014 			entry->start = prev->start;
1015 			entry->offset = prev->offset;
1016 			if (prev->object.vm_object)
1017 				vm_object_deallocate(prev->object.vm_object);
1018 			vm_map_entry_dispose(map, prev);
1019 		}
1020 	}
1021 
1022 	next = entry->next;
1023 	if (next != &map->header) {
1024 		esize = entry->end - entry->start;
1025 		if ((entry->end == next->start) &&
1026 		    (next->object.vm_object == entry->object.vm_object) &&
1027 		     (!entry->object.vm_object ||
1028 			(entry->offset + esize == next->offset)) &&
1029 		    (next->eflags == entry->eflags) &&
1030 		    (next->protection == entry->protection) &&
1031 		    (next->max_protection == entry->max_protection) &&
1032 		    (next->inheritance == entry->inheritance) &&
1033 		    (next->wired_count == entry->wired_count)) {
1034 			if (map->first_free == next)
1035 				map->first_free = entry;
1036 			vm_map_entry_unlink(map, next);
1037 			entry->end = next->end;
1038 			if (next->object.vm_object)
1039 				vm_object_deallocate(next->object.vm_object);
1040 			vm_map_entry_dispose(map, next);
1041 	        }
1042 	}
1043 }
1044 /*
1045  *	vm_map_clip_start:	[ internal use only ]
1046  *
1047  *	Asserts that the given entry begins at or after
1048  *	the specified address; if necessary,
1049  *	it splits the entry into two.
1050  */
1051 #define vm_map_clip_start(map, entry, startaddr) \
1052 { \
1053 	if (startaddr > entry->start) \
1054 		_vm_map_clip_start(map, entry, startaddr); \
1055 }
1056 
1057 /*
1058  *	This routine is called only when it is known that
1059  *	the entry must be split.
1060  */
1061 static void
1062 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
1063 {
1064 	vm_map_entry_t new_entry;
1065 
1066 	/*
1067 	 * Split off the front portion -- note that we must insert the new
1068 	 * entry BEFORE this one, so that this entry has the specified
1069 	 * starting address.
1070 	 */
1071 	vm_map_simplify_entry(map, entry);
1072 
1073 	/*
1074 	 * If there is no object backing this entry, we might as well create
1075 	 * one now.  If we defer it, an object can get created after the map
1076 	 * is clipped, and individual objects will be created for the split-up
1077 	 * map.  This is a bit of a hack, but is also about the best place to
1078 	 * put this improvement.
1079 	 */
1080 	if (entry->object.vm_object == NULL && !map->system_map) {
1081 		vm_object_t object;
1082 		object = vm_object_allocate(OBJT_DEFAULT,
1083 				atop(entry->end - entry->start));
1084 		entry->object.vm_object = object;
1085 		entry->offset = 0;
1086 	}
1087 
1088 	new_entry = vm_map_entry_create(map);
1089 	*new_entry = *entry;
1090 
1091 	new_entry->end = start;
1092 	entry->offset += (start - entry->start);
1093 	entry->start = start;
1094 
1095 	vm_map_entry_link(map, entry->prev, new_entry);
1096 
1097 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1098 		vm_object_reference(new_entry->object.vm_object);
1099 	}
1100 }
1101 
1102 /*
1103  *	vm_map_clip_end:	[ internal use only ]
1104  *
1105  *	Asserts that the given entry ends at or before
1106  *	the specified address; if necessary,
1107  *	it splits the entry into two.
1108  */
1109 #define vm_map_clip_end(map, entry, endaddr) \
1110 { \
1111 	if ((endaddr) < (entry->end)) \
1112 		_vm_map_clip_end((map), (entry), (endaddr)); \
1113 }
1114 
1115 /*
1116  *	This routine is called only when it is known that
1117  *	the entry must be split.
1118  */
1119 static void
1120 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
1121 {
1122 	vm_map_entry_t new_entry;
1123 
1124 	/*
1125 	 * If there is no object backing this entry, we might as well create
1126 	 * one now.  If we defer it, an object can get created after the map
1127 	 * is clipped, and individual objects will be created for the split-up
1128 	 * map.  This is a bit of a hack, but is also about the best place to
1129 	 * put this improvement.
1130 	 */
1131 	if (entry->object.vm_object == NULL && !map->system_map) {
1132 		vm_object_t object;
1133 		object = vm_object_allocate(OBJT_DEFAULT,
1134 				atop(entry->end - entry->start));
1135 		entry->object.vm_object = object;
1136 		entry->offset = 0;
1137 	}
1138 
1139 	/*
1140 	 * Create a new entry and insert it AFTER the specified entry
1141 	 */
1142 	new_entry = vm_map_entry_create(map);
1143 	*new_entry = *entry;
1144 
1145 	new_entry->start = entry->end = end;
1146 	new_entry->offset += (end - entry->start);
1147 
1148 	vm_map_entry_link(map, entry, new_entry);
1149 
1150 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1151 		vm_object_reference(new_entry->object.vm_object);
1152 	}
1153 }
1154 
1155 /*
1156  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
1157  *
1158  *	Asserts that the starting and ending region
1159  *	addresses fall within the valid range of the map.
1160  */
1161 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
1162 		{					\
1163 		if (start < vm_map_min(map))		\
1164 			start = vm_map_min(map);	\
1165 		if (end > vm_map_max(map))		\
1166 			end = vm_map_max(map);		\
1167 		if (start > end)			\
1168 			start = end;			\
1169 		}
1170 
1171 /*
1172  *	vm_map_submap:		[ kernel use only ]
1173  *
1174  *	Mark the given range as handled by a subordinate map.
1175  *
1176  *	This range must have been created with vm_map_find,
1177  *	and no other operations may have been performed on this
1178  *	range prior to calling vm_map_submap.
1179  *
1180  *	Only a limited number of operations can be performed
1181  *	within this rage after calling vm_map_submap:
1182  *		vm_fault
1183  *	[Don't try vm_map_copy!]
1184  *
1185  *	To remove a submapping, one must first remove the
1186  *	range from the superior map, and then destroy the
1187  *	submap (if desired).  [Better yet, don't try it.]
1188  */
1189 int
1190 vm_map_submap(
1191 	vm_map_t map,
1192 	vm_offset_t start,
1193 	vm_offset_t end,
1194 	vm_map_t submap)
1195 {
1196 	vm_map_entry_t entry;
1197 	int result = KERN_INVALID_ARGUMENT;
1198 
1199 	vm_map_lock(map);
1200 
1201 	VM_MAP_RANGE_CHECK(map, start, end);
1202 
1203 	if (vm_map_lookup_entry(map, start, &entry)) {
1204 		vm_map_clip_start(map, entry, start);
1205 	} else
1206 		entry = entry->next;
1207 
1208 	vm_map_clip_end(map, entry, end);
1209 
1210 	if ((entry->start == start) && (entry->end == end) &&
1211 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1212 	    (entry->object.vm_object == NULL)) {
1213 		entry->object.sub_map = submap;
1214 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
1215 		result = KERN_SUCCESS;
1216 	}
1217 	vm_map_unlock(map);
1218 
1219 	return (result);
1220 }
1221 
1222 /*
1223  *	vm_map_protect:
1224  *
1225  *	Sets the protection of the specified address
1226  *	region in the target map.  If "set_max" is
1227  *	specified, the maximum protection is to be set;
1228  *	otherwise, only the current protection is affected.
1229  */
1230 int
1231 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1232 	       vm_prot_t new_prot, boolean_t set_max)
1233 {
1234 	vm_map_entry_t current;
1235 	vm_map_entry_t entry;
1236 
1237 	vm_map_lock(map);
1238 
1239 	VM_MAP_RANGE_CHECK(map, start, end);
1240 
1241 	if (vm_map_lookup_entry(map, start, &entry)) {
1242 		vm_map_clip_start(map, entry, start);
1243 	} else {
1244 		entry = entry->next;
1245 	}
1246 
1247 	/*
1248 	 * Make a first pass to check for protection violations.
1249 	 */
1250 	current = entry;
1251 	while ((current != &map->header) && (current->start < end)) {
1252 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1253 			vm_map_unlock(map);
1254 			return (KERN_INVALID_ARGUMENT);
1255 		}
1256 		if ((new_prot & current->max_protection) != new_prot) {
1257 			vm_map_unlock(map);
1258 			return (KERN_PROTECTION_FAILURE);
1259 		}
1260 		current = current->next;
1261 	}
1262 
1263 	/*
1264 	 * Go back and fix up protections. [Note that clipping is not
1265 	 * necessary the second time.]
1266 	 */
1267 	current = entry;
1268 	while ((current != &map->header) && (current->start < end)) {
1269 		vm_prot_t old_prot;
1270 
1271 		vm_map_clip_end(map, current, end);
1272 
1273 		old_prot = current->protection;
1274 		if (set_max)
1275 			current->protection =
1276 			    (current->max_protection = new_prot) &
1277 			    old_prot;
1278 		else
1279 			current->protection = new_prot;
1280 
1281 		/*
1282 		 * Update physical map if necessary. Worry about copy-on-write
1283 		 * here -- CHECK THIS XXX
1284 		 */
1285 		if (current->protection != old_prot) {
1286 			mtx_lock(&Giant);
1287 			vm_page_lock_queues();
1288 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1289 							VM_PROT_ALL)
1290 			pmap_protect(map->pmap, current->start,
1291 			    current->end,
1292 			    current->protection & MASK(current));
1293 #undef	MASK
1294 			vm_page_unlock_queues();
1295 			mtx_unlock(&Giant);
1296 		}
1297 		vm_map_simplify_entry(map, current);
1298 		current = current->next;
1299 	}
1300 	vm_map_unlock(map);
1301 	return (KERN_SUCCESS);
1302 }
1303 
1304 /*
1305  *	vm_map_madvise:
1306  *
1307  * 	This routine traverses a processes map handling the madvise
1308  *	system call.  Advisories are classified as either those effecting
1309  *	the vm_map_entry structure, or those effecting the underlying
1310  *	objects.
1311  */
1312 int
1313 vm_map_madvise(
1314 	vm_map_t map,
1315 	vm_offset_t start,
1316 	vm_offset_t end,
1317 	int behav)
1318 {
1319 	vm_map_entry_t current, entry;
1320 	int modify_map = 0;
1321 
1322 	/*
1323 	 * Some madvise calls directly modify the vm_map_entry, in which case
1324 	 * we need to use an exclusive lock on the map and we need to perform
1325 	 * various clipping operations.  Otherwise we only need a read-lock
1326 	 * on the map.
1327 	 */
1328 	switch(behav) {
1329 	case MADV_NORMAL:
1330 	case MADV_SEQUENTIAL:
1331 	case MADV_RANDOM:
1332 	case MADV_NOSYNC:
1333 	case MADV_AUTOSYNC:
1334 	case MADV_NOCORE:
1335 	case MADV_CORE:
1336 		modify_map = 1;
1337 		vm_map_lock(map);
1338 		break;
1339 	case MADV_WILLNEED:
1340 	case MADV_DONTNEED:
1341 	case MADV_FREE:
1342 		vm_map_lock_read(map);
1343 		break;
1344 	default:
1345 		return (KERN_INVALID_ARGUMENT);
1346 	}
1347 
1348 	/*
1349 	 * Locate starting entry and clip if necessary.
1350 	 */
1351 	VM_MAP_RANGE_CHECK(map, start, end);
1352 
1353 	if (vm_map_lookup_entry(map, start, &entry)) {
1354 		if (modify_map)
1355 			vm_map_clip_start(map, entry, start);
1356 	} else {
1357 		entry = entry->next;
1358 	}
1359 
1360 	if (modify_map) {
1361 		/*
1362 		 * madvise behaviors that are implemented in the vm_map_entry.
1363 		 *
1364 		 * We clip the vm_map_entry so that behavioral changes are
1365 		 * limited to the specified address range.
1366 		 */
1367 		for (current = entry;
1368 		     (current != &map->header) && (current->start < end);
1369 		     current = current->next
1370 		) {
1371 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1372 				continue;
1373 
1374 			vm_map_clip_end(map, current, end);
1375 
1376 			switch (behav) {
1377 			case MADV_NORMAL:
1378 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1379 				break;
1380 			case MADV_SEQUENTIAL:
1381 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1382 				break;
1383 			case MADV_RANDOM:
1384 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1385 				break;
1386 			case MADV_NOSYNC:
1387 				current->eflags |= MAP_ENTRY_NOSYNC;
1388 				break;
1389 			case MADV_AUTOSYNC:
1390 				current->eflags &= ~MAP_ENTRY_NOSYNC;
1391 				break;
1392 			case MADV_NOCORE:
1393 				current->eflags |= MAP_ENTRY_NOCOREDUMP;
1394 				break;
1395 			case MADV_CORE:
1396 				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
1397 				break;
1398 			default:
1399 				break;
1400 			}
1401 			vm_map_simplify_entry(map, current);
1402 		}
1403 		vm_map_unlock(map);
1404 	} else {
1405 		vm_pindex_t pindex;
1406 		int count;
1407 
1408 		/*
1409 		 * madvise behaviors that are implemented in the underlying
1410 		 * vm_object.
1411 		 *
1412 		 * Since we don't clip the vm_map_entry, we have to clip
1413 		 * the vm_object pindex and count.
1414 		 */
1415 		for (current = entry;
1416 		     (current != &map->header) && (current->start < end);
1417 		     current = current->next
1418 		) {
1419 			vm_offset_t useStart;
1420 
1421 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1422 				continue;
1423 
1424 			pindex = OFF_TO_IDX(current->offset);
1425 			count = atop(current->end - current->start);
1426 			useStart = current->start;
1427 
1428 			if (current->start < start) {
1429 				pindex += atop(start - current->start);
1430 				count -= atop(start - current->start);
1431 				useStart = start;
1432 			}
1433 			if (current->end > end)
1434 				count -= atop(current->end - end);
1435 
1436 			if (count <= 0)
1437 				continue;
1438 
1439 			vm_object_madvise(current->object.vm_object,
1440 					  pindex, count, behav);
1441 			if (behav == MADV_WILLNEED) {
1442 				mtx_lock(&Giant);
1443 				pmap_object_init_pt(
1444 				    map->pmap,
1445 				    useStart,
1446 				    current->object.vm_object,
1447 				    pindex,
1448 				    (count << PAGE_SHIFT),
1449 				    MAP_PREFAULT_MADVISE
1450 				);
1451 				mtx_unlock(&Giant);
1452 			}
1453 		}
1454 		vm_map_unlock_read(map);
1455 	}
1456 	return (0);
1457 }
1458 
1459 
1460 /*
1461  *	vm_map_inherit:
1462  *
1463  *	Sets the inheritance of the specified address
1464  *	range in the target map.  Inheritance
1465  *	affects how the map will be shared with
1466  *	child maps at the time of vm_map_fork.
1467  */
1468 int
1469 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
1470 	       vm_inherit_t new_inheritance)
1471 {
1472 	vm_map_entry_t entry;
1473 	vm_map_entry_t temp_entry;
1474 
1475 	switch (new_inheritance) {
1476 	case VM_INHERIT_NONE:
1477 	case VM_INHERIT_COPY:
1478 	case VM_INHERIT_SHARE:
1479 		break;
1480 	default:
1481 		return (KERN_INVALID_ARGUMENT);
1482 	}
1483 	vm_map_lock(map);
1484 	VM_MAP_RANGE_CHECK(map, start, end);
1485 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
1486 		entry = temp_entry;
1487 		vm_map_clip_start(map, entry, start);
1488 	} else
1489 		entry = temp_entry->next;
1490 	while ((entry != &map->header) && (entry->start < end)) {
1491 		vm_map_clip_end(map, entry, end);
1492 		entry->inheritance = new_inheritance;
1493 		vm_map_simplify_entry(map, entry);
1494 		entry = entry->next;
1495 	}
1496 	vm_map_unlock(map);
1497 	return (KERN_SUCCESS);
1498 }
1499 
1500 /*
1501  *	vm_map_unwire:
1502  *
1503  *	Implements both kernel and user unwiring.
1504  */
1505 int
1506 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
1507 	boolean_t user_unwire)
1508 {
1509 	vm_map_entry_t entry, first_entry, tmp_entry;
1510 	vm_offset_t saved_start;
1511 	unsigned int last_timestamp;
1512 	int rv;
1513 	boolean_t need_wakeup, result;
1514 
1515 	vm_map_lock(map);
1516 	VM_MAP_RANGE_CHECK(map, start, end);
1517 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
1518 		vm_map_unlock(map);
1519 		return (KERN_INVALID_ADDRESS);
1520 	}
1521 	last_timestamp = map->timestamp;
1522 	entry = first_entry;
1523 	while (entry != &map->header && entry->start < end) {
1524 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1525 			/*
1526 			 * We have not yet clipped the entry.
1527 			 */
1528 			saved_start = (start >= entry->start) ? start :
1529 			    entry->start;
1530 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1531 			if (vm_map_unlock_and_wait(map, user_unwire)) {
1532 				/*
1533 				 * Allow interruption of user unwiring?
1534 				 */
1535 			}
1536 			vm_map_lock(map);
1537 			if (last_timestamp+1 != map->timestamp) {
1538 				/*
1539 				 * Look again for the entry because the map was
1540 				 * modified while it was unlocked.
1541 				 * Specifically, the entry may have been
1542 				 * clipped, merged, or deleted.
1543 				 */
1544 				if (!vm_map_lookup_entry(map, saved_start,
1545 				    &tmp_entry)) {
1546 					if (saved_start == start) {
1547 						/*
1548 						 * First_entry has been deleted.
1549 						 */
1550 						vm_map_unlock(map);
1551 						return (KERN_INVALID_ADDRESS);
1552 					}
1553 					end = saved_start;
1554 					rv = KERN_INVALID_ADDRESS;
1555 					goto done;
1556 				}
1557 				if (entry == first_entry)
1558 					first_entry = tmp_entry;
1559 				else
1560 					first_entry = NULL;
1561 				entry = tmp_entry;
1562 			}
1563 			last_timestamp = map->timestamp;
1564 			continue;
1565 		}
1566 		vm_map_clip_start(map, entry, start);
1567 		vm_map_clip_end(map, entry, end);
1568 		/*
1569 		 * Mark the entry in case the map lock is released.  (See
1570 		 * above.)
1571 		 */
1572 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1573 		/*
1574 		 * Check the map for holes in the specified region.
1575 		 */
1576 		if (entry->end < end && (entry->next == &map->header ||
1577 		    entry->next->start > entry->end)) {
1578 			end = entry->end;
1579 			rv = KERN_INVALID_ADDRESS;
1580 			goto done;
1581 		}
1582 		/*
1583 		 * Require that the entry is wired.
1584 		 */
1585 		if (entry->wired_count == 0 || (user_unwire &&
1586 		    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0)) {
1587 			end = entry->end;
1588 			rv = KERN_INVALID_ARGUMENT;
1589 			goto done;
1590 		}
1591 		entry = entry->next;
1592 	}
1593 	rv = KERN_SUCCESS;
1594 done:
1595 	need_wakeup = FALSE;
1596 	if (first_entry == NULL) {
1597 		result = vm_map_lookup_entry(map, start, &first_entry);
1598 		KASSERT(result, ("vm_map_unwire: lookup failed"));
1599 	}
1600 	entry = first_entry;
1601 	while (entry != &map->header && entry->start < end) {
1602 		if (rv == KERN_SUCCESS) {
1603 			if (user_unwire)
1604 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1605 			entry->wired_count--;
1606 			if (entry->wired_count == 0) {
1607 				/*
1608 				 * Retain the map lock.
1609 				 */
1610 				vm_fault_unwire(map, entry->start, entry->end);
1611 			}
1612 		}
1613 		KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
1614 			("vm_map_unwire: in-transition flag missing"));
1615 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1616 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1617 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1618 			need_wakeup = TRUE;
1619 		}
1620 		vm_map_simplify_entry(map, entry);
1621 		entry = entry->next;
1622 	}
1623 	vm_map_unlock(map);
1624 	if (need_wakeup)
1625 		vm_map_wakeup(map);
1626 	return (rv);
1627 }
1628 
1629 /*
1630  *	vm_map_wire:
1631  *
1632  *	Implements both kernel and user wiring.
1633  */
1634 int
1635 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
1636 	boolean_t user_wire)
1637 {
1638 	vm_map_entry_t entry, first_entry, tmp_entry;
1639 	vm_offset_t saved_end, saved_start;
1640 	unsigned int last_timestamp;
1641 	int rv;
1642 	boolean_t need_wakeup, result;
1643 
1644 	vm_map_lock(map);
1645 	VM_MAP_RANGE_CHECK(map, start, end);
1646 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
1647 		vm_map_unlock(map);
1648 		return (KERN_INVALID_ADDRESS);
1649 	}
1650 	last_timestamp = map->timestamp;
1651 	entry = first_entry;
1652 	while (entry != &map->header && entry->start < end) {
1653 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1654 			/*
1655 			 * We have not yet clipped the entry.
1656 			 */
1657 			saved_start = (start >= entry->start) ? start :
1658 			    entry->start;
1659 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1660 			if (vm_map_unlock_and_wait(map, user_wire)) {
1661 				/*
1662 				 * Allow interruption of user wiring?
1663 				 */
1664 			}
1665 			vm_map_lock(map);
1666 			if (last_timestamp + 1 != map->timestamp) {
1667 				/*
1668 				 * Look again for the entry because the map was
1669 				 * modified while it was unlocked.
1670 				 * Specifically, the entry may have been
1671 				 * clipped, merged, or deleted.
1672 				 */
1673 				if (!vm_map_lookup_entry(map, saved_start,
1674 				    &tmp_entry)) {
1675 					if (saved_start == start) {
1676 						/*
1677 						 * first_entry has been deleted.
1678 						 */
1679 						vm_map_unlock(map);
1680 						return (KERN_INVALID_ADDRESS);
1681 					}
1682 					end = saved_start;
1683 					rv = KERN_INVALID_ADDRESS;
1684 					goto done;
1685 				}
1686 				if (entry == first_entry)
1687 					first_entry = tmp_entry;
1688 				else
1689 					first_entry = NULL;
1690 				entry = tmp_entry;
1691 			}
1692 			last_timestamp = map->timestamp;
1693 			continue;
1694 		}
1695 		vm_map_clip_start(map, entry, start);
1696 		vm_map_clip_end(map, entry, end);
1697 		/*
1698 		 * Mark the entry in case the map lock is released.  (See
1699 		 * above.)
1700 		 */
1701 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1702 		/*
1703 		 *
1704 		 */
1705 		if (entry->wired_count == 0) {
1706 			entry->wired_count++;
1707 			saved_start = entry->start;
1708 			saved_end = entry->end;
1709 			/*
1710 			 * Release the map lock, relying on the in-transition
1711 			 * mark.
1712 			 */
1713 			vm_map_unlock(map);
1714 			rv = vm_fault_wire(map, saved_start, saved_end,
1715 			    user_wire);
1716 			vm_map_lock(map);
1717 			if (last_timestamp + 1 != map->timestamp) {
1718 				/*
1719 				 * Look again for the entry because the map was
1720 				 * modified while it was unlocked.  The entry
1721 				 * may have been clipped, but NOT merged or
1722 				 * deleted.
1723 				 */
1724 				result = vm_map_lookup_entry(map, saved_start,
1725 				    &tmp_entry);
1726 				KASSERT(result, ("vm_map_wire: lookup failed"));
1727 				if (entry == first_entry)
1728 					first_entry = tmp_entry;
1729 				else
1730 					first_entry = NULL;
1731 				entry = tmp_entry;
1732 				while (entry->end < saved_end) {
1733 					if (rv != KERN_SUCCESS) {
1734 						KASSERT(entry->wired_count == 1,
1735 						    ("vm_map_wire: bad count"));
1736 						entry->wired_count = -1;
1737 					}
1738 					entry = entry->next;
1739 				}
1740 			}
1741 			last_timestamp = map->timestamp;
1742 			if (rv != KERN_SUCCESS) {
1743 				KASSERT(entry->wired_count == 1,
1744 				    ("vm_map_wire: bad count"));
1745 				/*
1746 				 * Assign an out-of-range value to represent
1747 				 * the failure to wire this entry.
1748 				 */
1749 				entry->wired_count = -1;
1750 				end = entry->end;
1751 				goto done;
1752 			}
1753 		} else if (!user_wire ||
1754 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
1755 			entry->wired_count++;
1756 		}
1757 		/*
1758 		 * Check the map for holes in the specified region.
1759 		 */
1760 		if (entry->end < end && (entry->next == &map->header ||
1761 		    entry->next->start > entry->end)) {
1762 			end = entry->end;
1763 			rv = KERN_INVALID_ADDRESS;
1764 			goto done;
1765 		}
1766 		entry = entry->next;
1767 	}
1768 	rv = KERN_SUCCESS;
1769 done:
1770 	need_wakeup = FALSE;
1771 	if (first_entry == NULL) {
1772 		result = vm_map_lookup_entry(map, start, &first_entry);
1773 		KASSERT(result, ("vm_map_wire: lookup failed"));
1774 	}
1775 	entry = first_entry;
1776 	while (entry != &map->header && entry->start < end) {
1777 		if (rv == KERN_SUCCESS) {
1778 			if (user_wire)
1779 				entry->eflags |= MAP_ENTRY_USER_WIRED;
1780 		} else if (entry->wired_count == -1) {
1781 			/*
1782 			 * Wiring failed on this entry.  Thus, unwiring is
1783 			 * unnecessary.
1784 			 */
1785 			entry->wired_count = 0;
1786 		} else {
1787 			if (!user_wire ||
1788 			    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0)
1789 				entry->wired_count--;
1790 			if (entry->wired_count == 0) {
1791 				/*
1792 				 * Retain the map lock.
1793 				 */
1794 				vm_fault_unwire(map, entry->start, entry->end);
1795 			}
1796 		}
1797 		KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
1798 			("vm_map_wire: in-transition flag missing"));
1799 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1800 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1801 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1802 			need_wakeup = TRUE;
1803 		}
1804 		vm_map_simplify_entry(map, entry);
1805 		entry = entry->next;
1806 	}
1807 	vm_map_unlock(map);
1808 	if (need_wakeup)
1809 		vm_map_wakeup(map);
1810 	return (rv);
1811 }
1812 
1813 /*
1814  * vm_map_clean
1815  *
1816  * Push any dirty cached pages in the address range to their pager.
1817  * If syncio is TRUE, dirty pages are written synchronously.
1818  * If invalidate is TRUE, any cached pages are freed as well.
1819  *
1820  * Returns an error if any part of the specified range is not mapped.
1821  */
1822 int
1823 vm_map_clean(
1824 	vm_map_t map,
1825 	vm_offset_t start,
1826 	vm_offset_t end,
1827 	boolean_t syncio,
1828 	boolean_t invalidate)
1829 {
1830 	vm_map_entry_t current;
1831 	vm_map_entry_t entry;
1832 	vm_size_t size;
1833 	vm_object_t object;
1834 	vm_ooffset_t offset;
1835 
1836 	GIANT_REQUIRED;
1837 
1838 	vm_map_lock_read(map);
1839 	VM_MAP_RANGE_CHECK(map, start, end);
1840 	if (!vm_map_lookup_entry(map, start, &entry)) {
1841 		vm_map_unlock_read(map);
1842 		return (KERN_INVALID_ADDRESS);
1843 	}
1844 	/*
1845 	 * Make a first pass to check for holes.
1846 	 */
1847 	for (current = entry; current->start < end; current = current->next) {
1848 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1849 			vm_map_unlock_read(map);
1850 			return (KERN_INVALID_ARGUMENT);
1851 		}
1852 		if (end > current->end &&
1853 		    (current->next == &map->header ||
1854 			current->end != current->next->start)) {
1855 			vm_map_unlock_read(map);
1856 			return (KERN_INVALID_ADDRESS);
1857 		}
1858 	}
1859 
1860 	if (invalidate)
1861 		pmap_remove(vm_map_pmap(map), start, end);
1862 	/*
1863 	 * Make a second pass, cleaning/uncaching pages from the indicated
1864 	 * objects as we go.
1865 	 */
1866 	for (current = entry; current->start < end; current = current->next) {
1867 		offset = current->offset + (start - current->start);
1868 		size = (end <= current->end ? end : current->end) - start;
1869 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1870 			vm_map_t smap;
1871 			vm_map_entry_t tentry;
1872 			vm_size_t tsize;
1873 
1874 			smap = current->object.sub_map;
1875 			vm_map_lock_read(smap);
1876 			(void) vm_map_lookup_entry(smap, offset, &tentry);
1877 			tsize = tentry->end - offset;
1878 			if (tsize < size)
1879 				size = tsize;
1880 			object = tentry->object.vm_object;
1881 			offset = tentry->offset + (offset - tentry->start);
1882 			vm_map_unlock_read(smap);
1883 		} else {
1884 			object = current->object.vm_object;
1885 		}
1886 		/*
1887 		 * Note that there is absolutely no sense in writing out
1888 		 * anonymous objects, so we track down the vnode object
1889 		 * to write out.
1890 		 * We invalidate (remove) all pages from the address space
1891 		 * anyway, for semantic correctness.
1892 		 *
1893 		 * note: certain anonymous maps, such as MAP_NOSYNC maps,
1894 		 * may start out with a NULL object.
1895 		 */
1896 		while (object && object->backing_object) {
1897 			object = object->backing_object;
1898 			offset += object->backing_object_offset;
1899 			if (object->size < OFF_TO_IDX(offset + size))
1900 				size = IDX_TO_OFF(object->size) - offset;
1901 		}
1902 		if (object && (object->type == OBJT_VNODE) &&
1903 		    (current->protection & VM_PROT_WRITE)) {
1904 			/*
1905 			 * Flush pages if writing is allowed, invalidate them
1906 			 * if invalidation requested.  Pages undergoing I/O
1907 			 * will be ignored by vm_object_page_remove().
1908 			 *
1909 			 * We cannot lock the vnode and then wait for paging
1910 			 * to complete without deadlocking against vm_fault.
1911 			 * Instead we simply call vm_object_page_remove() and
1912 			 * allow it to block internally on a page-by-page
1913 			 * basis when it encounters pages undergoing async
1914 			 * I/O.
1915 			 */
1916 			int flags;
1917 
1918 			vm_object_reference(object);
1919 			vn_lock(object->handle, LK_EXCLUSIVE | LK_RETRY, curthread);
1920 			flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
1921 			flags |= invalidate ? OBJPC_INVAL : 0;
1922 			vm_object_page_clean(object,
1923 			    OFF_TO_IDX(offset),
1924 			    OFF_TO_IDX(offset + size + PAGE_MASK),
1925 			    flags);
1926 			VOP_UNLOCK(object->handle, 0, curthread);
1927 			vm_object_deallocate(object);
1928 		}
1929 		if (object && invalidate &&
1930 		    ((object->type == OBJT_VNODE) ||
1931 		     (object->type == OBJT_DEVICE))) {
1932 			vm_object_reference(object);
1933 			vm_object_page_remove(object,
1934 			    OFF_TO_IDX(offset),
1935 			    OFF_TO_IDX(offset + size + PAGE_MASK),
1936 			    FALSE);
1937 			vm_object_deallocate(object);
1938                 }
1939 		start += size;
1940 	}
1941 
1942 	vm_map_unlock_read(map);
1943 	return (KERN_SUCCESS);
1944 }
1945 
1946 /*
1947  *	vm_map_entry_unwire:	[ internal use only ]
1948  *
1949  *	Make the region specified by this entry pageable.
1950  *
1951  *	The map in question should be locked.
1952  *	[This is the reason for this routine's existence.]
1953  */
1954 static void
1955 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
1956 {
1957 	vm_fault_unwire(map, entry->start, entry->end);
1958 	entry->wired_count = 0;
1959 }
1960 
1961 /*
1962  *	vm_map_entry_delete:	[ internal use only ]
1963  *
1964  *	Deallocate the given entry from the target map.
1965  */
1966 static void
1967 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
1968 {
1969 	vm_map_entry_unlink(map, entry);
1970 	map->size -= entry->end - entry->start;
1971 
1972 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1973 		vm_object_deallocate(entry->object.vm_object);
1974 	}
1975 
1976 	vm_map_entry_dispose(map, entry);
1977 }
1978 
1979 /*
1980  *	vm_map_delete:	[ internal use only ]
1981  *
1982  *	Deallocates the given address range from the target
1983  *	map.
1984  */
1985 int
1986 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
1987 {
1988 	vm_object_t object;
1989 	vm_map_entry_t entry;
1990 	vm_map_entry_t first_entry;
1991 
1992 	/*
1993 	 * Find the start of the region, and clip it
1994 	 */
1995 	if (!vm_map_lookup_entry(map, start, &first_entry))
1996 		entry = first_entry->next;
1997 	else {
1998 		entry = first_entry;
1999 		vm_map_clip_start(map, entry, start);
2000 	}
2001 
2002 	/*
2003 	 * Save the free space hint
2004 	 */
2005 	if (entry == &map->header) {
2006 		map->first_free = &map->header;
2007 	} else if (map->first_free->start >= start) {
2008 		map->first_free = entry->prev;
2009 	}
2010 
2011 	/*
2012 	 * Step through all entries in this region
2013 	 */
2014 	while ((entry != &map->header) && (entry->start < end)) {
2015 		vm_map_entry_t next;
2016 		vm_offset_t s, e;
2017 		vm_pindex_t offidxstart, offidxend, count;
2018 
2019 		/*
2020 		 * Wait for wiring or unwiring of an entry to complete.
2021 		 */
2022 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0) {
2023 			unsigned int last_timestamp;
2024 			vm_offset_t saved_start;
2025 			vm_map_entry_t tmp_entry;
2026 
2027 			saved_start = entry->start;
2028 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2029 			last_timestamp = map->timestamp;
2030 			(void) vm_map_unlock_and_wait(map, FALSE);
2031 			vm_map_lock(map);
2032 			if (last_timestamp + 1 != map->timestamp) {
2033 				/*
2034 				 * Look again for the entry because the map was
2035 				 * modified while it was unlocked.
2036 				 * Specifically, the entry may have been
2037 				 * clipped, merged, or deleted.
2038 				 */
2039 				if (!vm_map_lookup_entry(map, saved_start,
2040 							 &tmp_entry))
2041 					entry = tmp_entry->next;
2042 				else {
2043 					entry = tmp_entry;
2044 					vm_map_clip_start(map, entry,
2045 							  saved_start);
2046 				}
2047 			}
2048 			continue;
2049 		}
2050 		vm_map_clip_end(map, entry, end);
2051 
2052 		s = entry->start;
2053 		e = entry->end;
2054 		next = entry->next;
2055 
2056 		offidxstart = OFF_TO_IDX(entry->offset);
2057 		count = OFF_TO_IDX(e - s);
2058 		object = entry->object.vm_object;
2059 
2060 		/*
2061 		 * Unwire before removing addresses from the pmap; otherwise,
2062 		 * unwiring will put the entries back in the pmap.
2063 		 */
2064 		if (entry->wired_count != 0) {
2065 			vm_map_entry_unwire(map, entry);
2066 		}
2067 
2068 		offidxend = offidxstart + count;
2069 
2070 		if ((object == kernel_object) || (object == kmem_object)) {
2071 			vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2072 		} else {
2073 			mtx_lock(&Giant);
2074 			pmap_remove(map->pmap, s, e);
2075 			if (object != NULL &&
2076 			    object->ref_count != 1 &&
2077 			    (object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING &&
2078 			    (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2079 				vm_object_collapse(object);
2080 				vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2081 				if (object->type == OBJT_SWAP) {
2082 					swap_pager_freespace(object, offidxstart, count);
2083 				}
2084 				if (offidxend >= object->size &&
2085 				    offidxstart < object->size) {
2086 					object->size = offidxstart;
2087 				}
2088 			}
2089 			mtx_unlock(&Giant);
2090 		}
2091 
2092 		/*
2093 		 * Delete the entry (which may delete the object) only after
2094 		 * removing all pmap entries pointing to its pages.
2095 		 * (Otherwise, its page frames may be reallocated, and any
2096 		 * modify bits will be set in the wrong object!)
2097 		 */
2098 		vm_map_entry_delete(map, entry);
2099 		entry = next;
2100 	}
2101 	return (KERN_SUCCESS);
2102 }
2103 
2104 /*
2105  *	vm_map_remove:
2106  *
2107  *	Remove the given address range from the target map.
2108  *	This is the exported form of vm_map_delete.
2109  */
2110 int
2111 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2112 {
2113 	int result, s = 0;
2114 
2115 	if (map == kmem_map)
2116 		s = splvm();
2117 
2118 	vm_map_lock(map);
2119 	VM_MAP_RANGE_CHECK(map, start, end);
2120 	result = vm_map_delete(map, start, end);
2121 	vm_map_unlock(map);
2122 
2123 	if (map == kmem_map)
2124 		splx(s);
2125 
2126 	return (result);
2127 }
2128 
2129 /*
2130  *	vm_map_check_protection:
2131  *
2132  *	Assert that the target map allows the specified
2133  *	privilege on the entire address region given.
2134  *	The entire region must be allocated.
2135  */
2136 boolean_t
2137 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2138 			vm_prot_t protection)
2139 {
2140 	vm_map_entry_t entry;
2141 	vm_map_entry_t tmp_entry;
2142 
2143 	vm_map_lock_read(map);
2144 	if (!vm_map_lookup_entry(map, start, &tmp_entry)) {
2145 		vm_map_unlock_read(map);
2146 		return (FALSE);
2147 	}
2148 	entry = tmp_entry;
2149 
2150 	while (start < end) {
2151 		if (entry == &map->header) {
2152 			vm_map_unlock_read(map);
2153 			return (FALSE);
2154 		}
2155 		/*
2156 		 * No holes allowed!
2157 		 */
2158 		if (start < entry->start) {
2159 			vm_map_unlock_read(map);
2160 			return (FALSE);
2161 		}
2162 		/*
2163 		 * Check protection associated with entry.
2164 		 */
2165 		if ((entry->protection & protection) != protection) {
2166 			vm_map_unlock_read(map);
2167 			return (FALSE);
2168 		}
2169 		/* go to next entry */
2170 		start = entry->end;
2171 		entry = entry->next;
2172 	}
2173 	vm_map_unlock_read(map);
2174 	return (TRUE);
2175 }
2176 
2177 /*
2178  *	vm_map_copy_entry:
2179  *
2180  *	Copies the contents of the source entry to the destination
2181  *	entry.  The entries *must* be aligned properly.
2182  */
2183 static void
2184 vm_map_copy_entry(
2185 	vm_map_t src_map,
2186 	vm_map_t dst_map,
2187 	vm_map_entry_t src_entry,
2188 	vm_map_entry_t dst_entry)
2189 {
2190 	vm_object_t src_object;
2191 
2192 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
2193 		return;
2194 
2195 	if (src_entry->wired_count == 0) {
2196 
2197 		/*
2198 		 * If the source entry is marked needs_copy, it is already
2199 		 * write-protected.
2200 		 */
2201 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2202 			vm_page_lock_queues();
2203 			pmap_protect(src_map->pmap,
2204 			    src_entry->start,
2205 			    src_entry->end,
2206 			    src_entry->protection & ~VM_PROT_WRITE);
2207 			vm_page_unlock_queues();
2208 		}
2209 
2210 		/*
2211 		 * Make a copy of the object.
2212 		 */
2213 		if ((src_object = src_entry->object.vm_object) != NULL) {
2214 
2215 			if ((src_object->handle == NULL) &&
2216 				(src_object->type == OBJT_DEFAULT ||
2217 				 src_object->type == OBJT_SWAP)) {
2218 				vm_object_collapse(src_object);
2219 				if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
2220 					vm_object_split(src_entry);
2221 					src_object = src_entry->object.vm_object;
2222 				}
2223 			}
2224 
2225 			vm_object_reference(src_object);
2226 			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2227 			dst_entry->object.vm_object = src_object;
2228 			src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2229 			dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2230 			dst_entry->offset = src_entry->offset;
2231 		} else {
2232 			dst_entry->object.vm_object = NULL;
2233 			dst_entry->offset = 0;
2234 		}
2235 
2236 		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
2237 		    dst_entry->end - dst_entry->start, src_entry->start);
2238 	} else {
2239 		/*
2240 		 * Of course, wired down pages can't be set copy-on-write.
2241 		 * Cause wired pages to be copied into the new map by
2242 		 * simulating faults (the new pages are pageable)
2243 		 */
2244 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
2245 	}
2246 }
2247 
2248 /*
2249  * vmspace_fork:
2250  * Create a new process vmspace structure and vm_map
2251  * based on those of an existing process.  The new map
2252  * is based on the old map, according to the inheritance
2253  * values on the regions in that map.
2254  *
2255  * The source map must not be locked.
2256  */
2257 struct vmspace *
2258 vmspace_fork(struct vmspace *vm1)
2259 {
2260 	struct vmspace *vm2;
2261 	vm_map_t old_map = &vm1->vm_map;
2262 	vm_map_t new_map;
2263 	vm_map_entry_t old_entry;
2264 	vm_map_entry_t new_entry;
2265 	vm_object_t object;
2266 
2267 	GIANT_REQUIRED;
2268 
2269 	vm_map_lock(old_map);
2270 	old_map->infork = 1;
2271 
2272 	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
2273 	bcopy(&vm1->vm_startcopy, &vm2->vm_startcopy,
2274 	    (caddr_t) &vm1->vm_endcopy - (caddr_t) &vm1->vm_startcopy);
2275 	new_map = &vm2->vm_map;	/* XXX */
2276 	new_map->timestamp = 1;
2277 
2278 	old_entry = old_map->header.next;
2279 
2280 	while (old_entry != &old_map->header) {
2281 		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2282 			panic("vm_map_fork: encountered a submap");
2283 
2284 		switch (old_entry->inheritance) {
2285 		case VM_INHERIT_NONE:
2286 			break;
2287 
2288 		case VM_INHERIT_SHARE:
2289 			/*
2290 			 * Clone the entry, creating the shared object if necessary.
2291 			 */
2292 			object = old_entry->object.vm_object;
2293 			if (object == NULL) {
2294 				object = vm_object_allocate(OBJT_DEFAULT,
2295 					atop(old_entry->end - old_entry->start));
2296 				old_entry->object.vm_object = object;
2297 				old_entry->offset = (vm_offset_t) 0;
2298 			}
2299 
2300 			/*
2301 			 * Add the reference before calling vm_object_shadow
2302 			 * to insure that a shadow object is created.
2303 			 */
2304 			vm_object_reference(object);
2305 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2306 				vm_object_shadow(&old_entry->object.vm_object,
2307 					&old_entry->offset,
2308 					atop(old_entry->end - old_entry->start));
2309 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2310 				/* Transfer the second reference too. */
2311 				vm_object_reference(
2312 				    old_entry->object.vm_object);
2313 				vm_object_deallocate(object);
2314 				object = old_entry->object.vm_object;
2315 			}
2316 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
2317 
2318 			/*
2319 			 * Clone the entry, referencing the shared object.
2320 			 */
2321 			new_entry = vm_map_entry_create(new_map);
2322 			*new_entry = *old_entry;
2323 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2324 			new_entry->wired_count = 0;
2325 
2326 			/*
2327 			 * Insert the entry into the new map -- we know we're
2328 			 * inserting at the end of the new map.
2329 			 */
2330 			vm_map_entry_link(new_map, new_map->header.prev,
2331 			    new_entry);
2332 
2333 			/*
2334 			 * Update the physical map
2335 			 */
2336 			pmap_copy(new_map->pmap, old_map->pmap,
2337 			    new_entry->start,
2338 			    (old_entry->end - old_entry->start),
2339 			    old_entry->start);
2340 			break;
2341 
2342 		case VM_INHERIT_COPY:
2343 			/*
2344 			 * Clone the entry and link into the map.
2345 			 */
2346 			new_entry = vm_map_entry_create(new_map);
2347 			*new_entry = *old_entry;
2348 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2349 			new_entry->wired_count = 0;
2350 			new_entry->object.vm_object = NULL;
2351 			vm_map_entry_link(new_map, new_map->header.prev,
2352 			    new_entry);
2353 			vm_map_copy_entry(old_map, new_map, old_entry,
2354 			    new_entry);
2355 			break;
2356 		}
2357 		old_entry = old_entry->next;
2358 	}
2359 
2360 	new_map->size = old_map->size;
2361 	old_map->infork = 0;
2362 	vm_map_unlock(old_map);
2363 
2364 	return (vm2);
2365 }
2366 
2367 int
2368 vm_map_stack (vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
2369 	      vm_prot_t prot, vm_prot_t max, int cow)
2370 {
2371 	vm_map_entry_t prev_entry;
2372 	vm_map_entry_t new_stack_entry;
2373 	vm_size_t      init_ssize;
2374 	int            rv;
2375 
2376 	if (addrbos < vm_map_min(map))
2377 		return (KERN_NO_SPACE);
2378 
2379 	if (max_ssize < sgrowsiz)
2380 		init_ssize = max_ssize;
2381 	else
2382 		init_ssize = sgrowsiz;
2383 
2384 	vm_map_lock(map);
2385 
2386 	/* If addr is already mapped, no go */
2387 	if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
2388 		vm_map_unlock(map);
2389 		return (KERN_NO_SPACE);
2390 	}
2391 
2392 	/* If we would blow our VMEM resource limit, no go */
2393 	if (map->size + init_ssize >
2394 	    curthread->td_proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
2395 		vm_map_unlock(map);
2396 		return (KERN_NO_SPACE);
2397 	}
2398 
2399 	/* If we can't accomodate max_ssize in the current mapping,
2400 	 * no go.  However, we need to be aware that subsequent user
2401 	 * mappings might map into the space we have reserved for
2402 	 * stack, and currently this space is not protected.
2403 	 *
2404 	 * Hopefully we will at least detect this condition
2405 	 * when we try to grow the stack.
2406 	 */
2407 	if ((prev_entry->next != &map->header) &&
2408 	    (prev_entry->next->start < addrbos + max_ssize)) {
2409 		vm_map_unlock(map);
2410 		return (KERN_NO_SPACE);
2411 	}
2412 
2413 	/* We initially map a stack of only init_ssize.  We will
2414 	 * grow as needed later.  Since this is to be a grow
2415 	 * down stack, we map at the top of the range.
2416 	 *
2417 	 * Note: we would normally expect prot and max to be
2418 	 * VM_PROT_ALL, and cow to be 0.  Possibly we should
2419 	 * eliminate these as input parameters, and just
2420 	 * pass these values here in the insert call.
2421 	 */
2422 	rv = vm_map_insert(map, NULL, 0, addrbos + max_ssize - init_ssize,
2423 	                   addrbos + max_ssize, prot, max, cow);
2424 
2425 	/* Now set the avail_ssize amount */
2426 	if (rv == KERN_SUCCESS){
2427 		if (prev_entry != &map->header)
2428 			vm_map_clip_end(map, prev_entry, addrbos + max_ssize - init_ssize);
2429 		new_stack_entry = prev_entry->next;
2430 		if (new_stack_entry->end   != addrbos + max_ssize ||
2431 		    new_stack_entry->start != addrbos + max_ssize - init_ssize)
2432 			panic ("Bad entry start/end for new stack entry");
2433 		else
2434 			new_stack_entry->avail_ssize = max_ssize - init_ssize;
2435 	}
2436 
2437 	vm_map_unlock(map);
2438 	return (rv);
2439 }
2440 
2441 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
2442  * desired address is already mapped, or if we successfully grow
2443  * the stack.  Also returns KERN_SUCCESS if addr is outside the
2444  * stack range (this is strange, but preserves compatibility with
2445  * the grow function in vm_machdep.c).
2446  */
2447 int
2448 vm_map_growstack (struct proc *p, vm_offset_t addr)
2449 {
2450 	vm_map_entry_t prev_entry;
2451 	vm_map_entry_t stack_entry;
2452 	vm_map_entry_t new_stack_entry;
2453 	struct vmspace *vm = p->p_vmspace;
2454 	vm_map_t map = &vm->vm_map;
2455 	vm_offset_t    end;
2456 	int      grow_amount;
2457 	int      rv;
2458 	int      is_procstack;
2459 
2460 	GIANT_REQUIRED;
2461 
2462 Retry:
2463 	vm_map_lock_read(map);
2464 
2465 	/* If addr is already in the entry range, no need to grow.*/
2466 	if (vm_map_lookup_entry(map, addr, &prev_entry)) {
2467 		vm_map_unlock_read(map);
2468 		return (KERN_SUCCESS);
2469 	}
2470 
2471 	if ((stack_entry = prev_entry->next) == &map->header) {
2472 		vm_map_unlock_read(map);
2473 		return (KERN_SUCCESS);
2474 	}
2475 	if (prev_entry == &map->header)
2476 		end = stack_entry->start - stack_entry->avail_ssize;
2477 	else
2478 		end = prev_entry->end;
2479 
2480 	/* This next test mimics the old grow function in vm_machdep.c.
2481 	 * It really doesn't quite make sense, but we do it anyway
2482 	 * for compatibility.
2483 	 *
2484 	 * If not growable stack, return success.  This signals the
2485 	 * caller to proceed as he would normally with normal vm.
2486 	 */
2487 	if (stack_entry->avail_ssize < 1 ||
2488 	    addr >= stack_entry->start ||
2489 	    addr <  stack_entry->start - stack_entry->avail_ssize) {
2490 		vm_map_unlock_read(map);
2491 		return (KERN_SUCCESS);
2492 	}
2493 
2494 	/* Find the minimum grow amount */
2495 	grow_amount = roundup (stack_entry->start - addr, PAGE_SIZE);
2496 	if (grow_amount > stack_entry->avail_ssize) {
2497 		vm_map_unlock_read(map);
2498 		return (KERN_NO_SPACE);
2499 	}
2500 
2501 	/* If there is no longer enough space between the entries
2502 	 * nogo, and adjust the available space.  Note: this
2503 	 * should only happen if the user has mapped into the
2504 	 * stack area after the stack was created, and is
2505 	 * probably an error.
2506 	 *
2507 	 * This also effectively destroys any guard page the user
2508 	 * might have intended by limiting the stack size.
2509 	 */
2510 	if (grow_amount > stack_entry->start - end) {
2511 		if (vm_map_lock_upgrade(map))
2512 			goto Retry;
2513 
2514 		stack_entry->avail_ssize = stack_entry->start - end;
2515 
2516 		vm_map_unlock(map);
2517 		return (KERN_NO_SPACE);
2518 	}
2519 
2520 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr;
2521 
2522 	/* If this is the main process stack, see if we're over the
2523 	 * stack limit.
2524 	 */
2525 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2526 			     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2527 		vm_map_unlock_read(map);
2528 		return (KERN_NO_SPACE);
2529 	}
2530 
2531 	/* Round up the grow amount modulo SGROWSIZ */
2532 	grow_amount = roundup (grow_amount, sgrowsiz);
2533 	if (grow_amount > stack_entry->avail_ssize) {
2534 		grow_amount = stack_entry->avail_ssize;
2535 	}
2536 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2537 	                     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2538 		grow_amount = p->p_rlimit[RLIMIT_STACK].rlim_cur -
2539 		              ctob(vm->vm_ssize);
2540 	}
2541 
2542 	/* If we would blow our VMEM resource limit, no go */
2543 	if (map->size + grow_amount >
2544 	    curthread->td_proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
2545 		vm_map_unlock_read(map);
2546 		return (KERN_NO_SPACE);
2547 	}
2548 
2549 	if (vm_map_lock_upgrade(map))
2550 		goto Retry;
2551 
2552 	/* Get the preliminary new entry start value */
2553 	addr = stack_entry->start - grow_amount;
2554 
2555 	/* If this puts us into the previous entry, cut back our growth
2556 	 * to the available space.  Also, see the note above.
2557 	 */
2558 	if (addr < end) {
2559 		stack_entry->avail_ssize = stack_entry->start - end;
2560 		addr = end;
2561 	}
2562 
2563 	rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
2564 	    p->p_sysent->sv_stackprot, VM_PROT_ALL, 0);
2565 
2566 	/* Adjust the available stack space by the amount we grew. */
2567 	if (rv == KERN_SUCCESS) {
2568 		if (prev_entry != &map->header)
2569 			vm_map_clip_end(map, prev_entry, addr);
2570 		new_stack_entry = prev_entry->next;
2571 		if (new_stack_entry->end   != stack_entry->start  ||
2572 		    new_stack_entry->start != addr)
2573 			panic ("Bad stack grow start/end in new stack entry");
2574 		else {
2575 			new_stack_entry->avail_ssize = stack_entry->avail_ssize -
2576 							(new_stack_entry->end -
2577 							 new_stack_entry->start);
2578 			if (is_procstack)
2579 				vm->vm_ssize += btoc(new_stack_entry->end -
2580 						     new_stack_entry->start);
2581 		}
2582 	}
2583 
2584 	vm_map_unlock(map);
2585 	return (rv);
2586 }
2587 
2588 /*
2589  * Unshare the specified VM space for exec.  If other processes are
2590  * mapped to it, then create a new one.  The new vmspace is null.
2591  */
2592 void
2593 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
2594 {
2595 	struct vmspace *oldvmspace = p->p_vmspace;
2596 	struct vmspace *newvmspace;
2597 
2598 	GIANT_REQUIRED;
2599 	newvmspace = vmspace_alloc(minuser, maxuser);
2600 	bcopy(&oldvmspace->vm_startcopy, &newvmspace->vm_startcopy,
2601 	    (caddr_t) (newvmspace + 1) - (caddr_t) &newvmspace->vm_startcopy);
2602 	/*
2603 	 * This code is written like this for prototype purposes.  The
2604 	 * goal is to avoid running down the vmspace here, but let the
2605 	 * other process's that are still using the vmspace to finally
2606 	 * run it down.  Even though there is little or no chance of blocking
2607 	 * here, it is a good idea to keep this form for future mods.
2608 	 */
2609 	p->p_vmspace = newvmspace;
2610 	pmap_pinit2(vmspace_pmap(newvmspace));
2611 	vmspace_free(oldvmspace);
2612 	if (p == curthread->td_proc)		/* XXXKSE ? */
2613 		pmap_activate(curthread);
2614 }
2615 
2616 /*
2617  * Unshare the specified VM space for forcing COW.  This
2618  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
2619  */
2620 void
2621 vmspace_unshare(struct proc *p)
2622 {
2623 	struct vmspace *oldvmspace = p->p_vmspace;
2624 	struct vmspace *newvmspace;
2625 
2626 	GIANT_REQUIRED;
2627 	if (oldvmspace->vm_refcnt == 1)
2628 		return;
2629 	newvmspace = vmspace_fork(oldvmspace);
2630 	p->p_vmspace = newvmspace;
2631 	pmap_pinit2(vmspace_pmap(newvmspace));
2632 	vmspace_free(oldvmspace);
2633 	if (p == curthread->td_proc)		/* XXXKSE ? */
2634 		pmap_activate(curthread);
2635 }
2636 
2637 /*
2638  *	vm_map_lookup:
2639  *
2640  *	Finds the VM object, offset, and
2641  *	protection for a given virtual address in the
2642  *	specified map, assuming a page fault of the
2643  *	type specified.
2644  *
2645  *	Leaves the map in question locked for read; return
2646  *	values are guaranteed until a vm_map_lookup_done
2647  *	call is performed.  Note that the map argument
2648  *	is in/out; the returned map must be used in
2649  *	the call to vm_map_lookup_done.
2650  *
2651  *	A handle (out_entry) is returned for use in
2652  *	vm_map_lookup_done, to make that fast.
2653  *
2654  *	If a lookup is requested with "write protection"
2655  *	specified, the map may be changed to perform virtual
2656  *	copying operations, although the data referenced will
2657  *	remain the same.
2658  */
2659 int
2660 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
2661 	      vm_offset_t vaddr,
2662 	      vm_prot_t fault_typea,
2663 	      vm_map_entry_t *out_entry,	/* OUT */
2664 	      vm_object_t *object,		/* OUT */
2665 	      vm_pindex_t *pindex,		/* OUT */
2666 	      vm_prot_t *out_prot,		/* OUT */
2667 	      boolean_t *wired)			/* OUT */
2668 {
2669 	vm_map_entry_t entry;
2670 	vm_map_t map = *var_map;
2671 	vm_prot_t prot;
2672 	vm_prot_t fault_type = fault_typea;
2673 
2674 RetryLookup:;
2675 	/*
2676 	 * Lookup the faulting address.
2677 	 */
2678 
2679 	vm_map_lock_read(map);
2680 #define	RETURN(why) \
2681 		{ \
2682 		vm_map_unlock_read(map); \
2683 		return (why); \
2684 		}
2685 
2686 	/*
2687 	 * If the map has an interesting hint, try it before calling full
2688 	 * blown lookup routine.
2689 	 */
2690 	entry = map->root;
2691 	*out_entry = entry;
2692 	if (entry == NULL ||
2693 	    (vaddr < entry->start) || (vaddr >= entry->end)) {
2694 		/*
2695 		 * Entry was either not a valid hint, or the vaddr was not
2696 		 * contained in the entry, so do a full lookup.
2697 		 */
2698 		if (!vm_map_lookup_entry(map, vaddr, out_entry))
2699 			RETURN(KERN_INVALID_ADDRESS);
2700 
2701 		entry = *out_entry;
2702 	}
2703 
2704 	/*
2705 	 * Handle submaps.
2706 	 */
2707 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
2708 		vm_map_t old_map = map;
2709 
2710 		*var_map = map = entry->object.sub_map;
2711 		vm_map_unlock_read(old_map);
2712 		goto RetryLookup;
2713 	}
2714 
2715 	/*
2716 	 * Check whether this task is allowed to have this page.
2717 	 * Note the special case for MAP_ENTRY_COW
2718 	 * pages with an override.  This is to implement a forced
2719 	 * COW for debuggers.
2720 	 */
2721 	if (fault_type & VM_PROT_OVERRIDE_WRITE)
2722 		prot = entry->max_protection;
2723 	else
2724 		prot = entry->protection;
2725 	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
2726 	if ((fault_type & prot) != fault_type) {
2727 			RETURN(KERN_PROTECTION_FAILURE);
2728 	}
2729 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
2730 	    (entry->eflags & MAP_ENTRY_COW) &&
2731 	    (fault_type & VM_PROT_WRITE) &&
2732 	    (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
2733 		RETURN(KERN_PROTECTION_FAILURE);
2734 	}
2735 
2736 	/*
2737 	 * If this page is not pageable, we have to get it for all possible
2738 	 * accesses.
2739 	 */
2740 	*wired = (entry->wired_count != 0);
2741 	if (*wired)
2742 		prot = fault_type = entry->protection;
2743 
2744 	/*
2745 	 * If the entry was copy-on-write, we either ...
2746 	 */
2747 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2748 		/*
2749 		 * If we want to write the page, we may as well handle that
2750 		 * now since we've got the map locked.
2751 		 *
2752 		 * If we don't need to write the page, we just demote the
2753 		 * permissions allowed.
2754 		 */
2755 		if (fault_type & VM_PROT_WRITE) {
2756 			/*
2757 			 * Make a new object, and place it in the object
2758 			 * chain.  Note that no new references have appeared
2759 			 * -- one just moved from the map to the new
2760 			 * object.
2761 			 */
2762 			if (vm_map_lock_upgrade(map))
2763 				goto RetryLookup;
2764 
2765 			vm_object_shadow(
2766 			    &entry->object.vm_object,
2767 			    &entry->offset,
2768 			    atop(entry->end - entry->start));
2769 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2770 
2771 			vm_map_lock_downgrade(map);
2772 		} else {
2773 			/*
2774 			 * We're attempting to read a copy-on-write page --
2775 			 * don't allow writes.
2776 			 */
2777 			prot &= ~VM_PROT_WRITE;
2778 		}
2779 	}
2780 
2781 	/*
2782 	 * Create an object if necessary.
2783 	 */
2784 	if (entry->object.vm_object == NULL &&
2785 	    !map->system_map) {
2786 		if (vm_map_lock_upgrade(map))
2787 			goto RetryLookup;
2788 		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
2789 		    atop(entry->end - entry->start));
2790 		entry->offset = 0;
2791 		vm_map_lock_downgrade(map);
2792 	}
2793 
2794 	/*
2795 	 * Return the object/offset from this entry.  If the entry was
2796 	 * copy-on-write or empty, it has been fixed up.
2797 	 */
2798 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
2799 	*object = entry->object.vm_object;
2800 
2801 	/*
2802 	 * Return whether this is the only map sharing this data.
2803 	 */
2804 	*out_prot = prot;
2805 	return (KERN_SUCCESS);
2806 
2807 #undef	RETURN
2808 }
2809 
2810 /*
2811  *	vm_map_lookup_done:
2812  *
2813  *	Releases locks acquired by a vm_map_lookup
2814  *	(according to the handle returned by that lookup).
2815  */
2816 void
2817 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
2818 {
2819 	/*
2820 	 * Unlock the main-level map
2821 	 */
2822 	vm_map_unlock_read(map);
2823 }
2824 
2825 #ifdef ENABLE_VFS_IOOPT
2826 /*
2827  * Experimental support for zero-copy I/O
2828  *
2829  * Implement uiomove with VM operations.  This handles (and collateral changes)
2830  * support every combination of source object modification, and COW type
2831  * operations.
2832  */
2833 int
2834 vm_uiomove(
2835 	vm_map_t mapa,
2836 	vm_object_t srcobject,
2837 	off_t cp,
2838 	int cnta,
2839 	vm_offset_t uaddra,
2840 	int *npages)
2841 {
2842 	vm_map_t map;
2843 	vm_object_t first_object, oldobject, object;
2844 	vm_map_entry_t entry;
2845 	vm_prot_t prot;
2846 	boolean_t wired;
2847 	int tcnt, rv;
2848 	vm_offset_t uaddr, start, end, tend;
2849 	vm_pindex_t first_pindex, oindex;
2850 	vm_size_t osize;
2851 	off_t ooffset;
2852 	int cnt;
2853 
2854 	GIANT_REQUIRED;
2855 
2856 	if (npages)
2857 		*npages = 0;
2858 
2859 	cnt = cnta;
2860 	uaddr = uaddra;
2861 
2862 	while (cnt > 0) {
2863 		map = mapa;
2864 
2865 		if ((vm_map_lookup(&map, uaddr,
2866 			VM_PROT_READ, &entry, &first_object,
2867 			&first_pindex, &prot, &wired)) != KERN_SUCCESS) {
2868 			return EFAULT;
2869 		}
2870 
2871 		vm_map_clip_start(map, entry, uaddr);
2872 
2873 		tcnt = cnt;
2874 		tend = uaddr + tcnt;
2875 		if (tend > entry->end) {
2876 			tcnt = entry->end - uaddr;
2877 			tend = entry->end;
2878 		}
2879 
2880 		vm_map_clip_end(map, entry, tend);
2881 
2882 		start = entry->start;
2883 		end = entry->end;
2884 
2885 		osize = atop(tcnt);
2886 
2887 		oindex = OFF_TO_IDX(cp);
2888 		if (npages) {
2889 			vm_size_t idx;
2890 			for (idx = 0; idx < osize; idx++) {
2891 				vm_page_t m;
2892 				if ((m = vm_page_lookup(srcobject, oindex + idx)) == NULL) {
2893 					vm_map_lookup_done(map, entry);
2894 					return 0;
2895 				}
2896 				/*
2897 				 * disallow busy or invalid pages, but allow
2898 				 * m->busy pages if they are entirely valid.
2899 				 */
2900 				if ((m->flags & PG_BUSY) ||
2901 					((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL)) {
2902 					vm_map_lookup_done(map, entry);
2903 					return 0;
2904 				}
2905 			}
2906 		}
2907 
2908 /*
2909  * If we are changing an existing map entry, just redirect
2910  * the object, and change mappings.
2911  */
2912 		if ((first_object->type == OBJT_VNODE) &&
2913 			((oldobject = entry->object.vm_object) == first_object)) {
2914 
2915 			if ((entry->offset != cp) || (oldobject != srcobject)) {
2916 				/*
2917    				* Remove old window into the file
2918    				*/
2919 				pmap_remove (map->pmap, uaddr, tend);
2920 
2921 				/*
2922    				* Force copy on write for mmaped regions
2923    				*/
2924 				vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
2925 
2926 				/*
2927    				* Point the object appropriately
2928    				*/
2929 				if (oldobject != srcobject) {
2930 
2931 				/*
2932    				* Set the object optimization hint flag
2933    				*/
2934 					vm_object_set_flag(srcobject, OBJ_OPT);
2935 					vm_object_reference(srcobject);
2936 					entry->object.vm_object = srcobject;
2937 
2938 					if (oldobject) {
2939 						vm_object_deallocate(oldobject);
2940 					}
2941 				}
2942 
2943 				entry->offset = cp;
2944 				map->timestamp++;
2945 			} else {
2946 				pmap_remove (map->pmap, uaddr, tend);
2947 			}
2948 
2949 		} else if ((first_object->ref_count == 1) &&
2950 			(first_object->size == osize) &&
2951 			((first_object->type == OBJT_DEFAULT) ||
2952 				(first_object->type == OBJT_SWAP)) ) {
2953 
2954 			oldobject = first_object->backing_object;
2955 
2956 			if ((first_object->backing_object_offset != cp) ||
2957 				(oldobject != srcobject)) {
2958 				/*
2959    				* Remove old window into the file
2960    				*/
2961 				pmap_remove (map->pmap, uaddr, tend);
2962 
2963 				/*
2964 				 * Remove unneeded old pages
2965 				 */
2966 				vm_object_page_remove(first_object, 0, 0, 0);
2967 
2968 				/*
2969 				 * Invalidate swap space
2970 				 */
2971 				if (first_object->type == OBJT_SWAP) {
2972 					swap_pager_freespace(first_object,
2973 						0,
2974 						first_object->size);
2975 				}
2976 
2977 				/*
2978    				 * Force copy on write for mmaped regions
2979    				 */
2980 				vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
2981 
2982 				/*
2983    				 * Point the object appropriately
2984    				 */
2985 				if (oldobject != srcobject) {
2986 					/*
2987    					 * Set the object optimization hint flag
2988    					 */
2989 					vm_object_set_flag(srcobject, OBJ_OPT);
2990 					vm_object_reference(srcobject);
2991 
2992 					if (oldobject) {
2993 						TAILQ_REMOVE(&oldobject->shadow_head,
2994 							first_object, shadow_list);
2995 						oldobject->shadow_count--;
2996 						/* XXX bump generation? */
2997 						vm_object_deallocate(oldobject);
2998 					}
2999 
3000 					TAILQ_INSERT_TAIL(&srcobject->shadow_head,
3001 						first_object, shadow_list);
3002 					srcobject->shadow_count++;
3003 					/* XXX bump generation? */
3004 
3005 					first_object->backing_object = srcobject;
3006 				}
3007 				first_object->backing_object_offset = cp;
3008 				map->timestamp++;
3009 			} else {
3010 				pmap_remove (map->pmap, uaddr, tend);
3011 			}
3012 /*
3013  * Otherwise, we have to do a logical mmap.
3014  */
3015 		} else {
3016 
3017 			vm_object_set_flag(srcobject, OBJ_OPT);
3018 			vm_object_reference(srcobject);
3019 
3020 			pmap_remove (map->pmap, uaddr, tend);
3021 
3022 			vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
3023 			vm_map_lock_upgrade(map);
3024 
3025 			if (entry == &map->header) {
3026 				map->first_free = &map->header;
3027 			} else if (map->first_free->start >= start) {
3028 				map->first_free = entry->prev;
3029 			}
3030 
3031 			vm_map_entry_delete(map, entry);
3032 
3033 			object = srcobject;
3034 			ooffset = cp;
3035 
3036 			rv = vm_map_insert(map, object, ooffset, start, tend,
3037 				VM_PROT_ALL, VM_PROT_ALL, MAP_COPY_ON_WRITE);
3038 
3039 			if (rv != KERN_SUCCESS)
3040 				panic("vm_uiomove: could not insert new entry: %d", rv);
3041 		}
3042 
3043 /*
3044  * Map the window directly, if it is already in memory
3045  */
3046 		pmap_object_init_pt(map->pmap, uaddr,
3047 			srcobject, oindex, tcnt, 0);
3048 
3049 		map->timestamp++;
3050 		vm_map_unlock(map);
3051 
3052 		cnt -= tcnt;
3053 		uaddr += tcnt;
3054 		cp += tcnt;
3055 		if (npages)
3056 			*npages += osize;
3057 	}
3058 	return 0;
3059 }
3060 #endif
3061 
3062 #include "opt_ddb.h"
3063 #ifdef DDB
3064 #include <sys/kernel.h>
3065 
3066 #include <ddb/ddb.h>
3067 
3068 /*
3069  *	vm_map_print:	[ debug ]
3070  */
3071 DB_SHOW_COMMAND(map, vm_map_print)
3072 {
3073 	static int nlines;
3074 	/* XXX convert args. */
3075 	vm_map_t map = (vm_map_t)addr;
3076 	boolean_t full = have_addr;
3077 
3078 	vm_map_entry_t entry;
3079 
3080 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
3081 	    (void *)map,
3082 	    (void *)map->pmap, map->nentries, map->timestamp);
3083 	nlines++;
3084 
3085 	if (!full && db_indent)
3086 		return;
3087 
3088 	db_indent += 2;
3089 	for (entry = map->header.next; entry != &map->header;
3090 	    entry = entry->next) {
3091 		db_iprintf("map entry %p: start=%p, end=%p\n",
3092 		    (void *)entry, (void *)entry->start, (void *)entry->end);
3093 		nlines++;
3094 		{
3095 			static char *inheritance_name[4] =
3096 			{"share", "copy", "none", "donate_copy"};
3097 
3098 			db_iprintf(" prot=%x/%x/%s",
3099 			    entry->protection,
3100 			    entry->max_protection,
3101 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
3102 			if (entry->wired_count != 0)
3103 				db_printf(", wired");
3104 		}
3105 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3106 			db_printf(", share=%p, offset=0x%jx\n",
3107 			    (void *)entry->object.sub_map,
3108 			    (uintmax_t)entry->offset);
3109 			nlines++;
3110 			if ((entry->prev == &map->header) ||
3111 			    (entry->prev->object.sub_map !=
3112 				entry->object.sub_map)) {
3113 				db_indent += 2;
3114 				vm_map_print((db_expr_t)(intptr_t)
3115 					     entry->object.sub_map,
3116 					     full, 0, (char *)0);
3117 				db_indent -= 2;
3118 			}
3119 		} else {
3120 			db_printf(", object=%p, offset=0x%jx",
3121 			    (void *)entry->object.vm_object,
3122 			    (uintmax_t)entry->offset);
3123 			if (entry->eflags & MAP_ENTRY_COW)
3124 				db_printf(", copy (%s)",
3125 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
3126 			db_printf("\n");
3127 			nlines++;
3128 
3129 			if ((entry->prev == &map->header) ||
3130 			    (entry->prev->object.vm_object !=
3131 				entry->object.vm_object)) {
3132 				db_indent += 2;
3133 				vm_object_print((db_expr_t)(intptr_t)
3134 						entry->object.vm_object,
3135 						full, 0, (char *)0);
3136 				nlines += 4;
3137 				db_indent -= 2;
3138 			}
3139 		}
3140 	}
3141 	db_indent -= 2;
3142 	if (db_indent == 0)
3143 		nlines = 0;
3144 }
3145 
3146 
3147 DB_SHOW_COMMAND(procvm, procvm)
3148 {
3149 	struct proc *p;
3150 
3151 	if (have_addr) {
3152 		p = (struct proc *) addr;
3153 	} else {
3154 		p = curproc;
3155 	}
3156 
3157 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3158 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3159 	    (void *)vmspace_pmap(p->p_vmspace));
3160 
3161 	vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3162 }
3163 
3164 #endif /* DDB */
3165