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