Fix VM panic. Add required overflow check for MAP_STACK and MAP_FIXED mmaps
[dragonfly.git] / sys / vm / vm_map.c
blob1507336a852831932dba58b915d35dbf85888d5b
1 /*
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * The Mach Operating System project at Carnegie-Mellon University.
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.
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.
36 * from: @(#)vm_map.c 8.3 (Berkeley) 1/12/94
39 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40 * All rights reserved.
42 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
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.
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.
54 * Carnegie Mellon requests users of this software to return to
56 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
57 * School of Computer Science
58 * Carnegie Mellon University
59 * Pittsburgh PA 15213-3890
61 * any improvements or extensions that they make and grant Carnegie the
62 * rights to redistribute these changes.
64 * $FreeBSD: src/sys/vm/vm_map.c,v 1.187.2.19 2003/05/27 00:47:02 alc Exp $
65 * $DragonFly: src/sys/vm/vm_map.c,v 1.56 2007/04/29 18:25:41 dillon Exp $
69 * Virtual memory mapping module.
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>
75 #include <sys/proc.h>
76 #include <sys/lock.h>
77 #include <sys/vmmeter.h>
78 #include <sys/mman.h>
79 #include <sys/vnode.h>
80 #include <sys/resourcevar.h>
81 #include <sys/shm.h>
82 #include <sys/tree.h>
83 #include <sys/malloc.h>
85 #include <vm/vm.h>
86 #include <vm/vm_param.h>
87 #include <vm/pmap.h>
88 #include <vm/vm_map.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_object.h>
91 #include <vm/vm_pager.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_extern.h>
94 #include <vm/swap_pager.h>
95 #include <vm/vm_zone.h>
97 #include <sys/thread2.h>
98 #include <sys/sysref2.h>
101 * Virtual memory maps provide for the mapping, protection,
102 * and sharing of virtual memory objects. In addition,
103 * this module provides for an efficient virtual copy of
104 * memory from one map to another.
106 * Synchronization is required prior to most operations.
108 * Maps consist of an ordered doubly-linked list of simple
109 * entries; a single hint is used to speed up lookups.
111 * Since portions of maps are specified by start/end addresses,
112 * which may not align with existing map entries, all
113 * routines merely "clip" entries to these start/end values.
114 * [That is, an entry is split into two, bordering at a
115 * start or end value.] Note that these clippings may not
116 * always be necessary (as the two resulting entries are then
117 * not changed); however, the clipping is done for convenience.
119 * As mentioned above, virtual copy operations are performed
120 * by copying VM object references from one map to
121 * another, and then marking both regions as copy-on-write.
124 static void vmspace_terminate(struct vmspace *vm);
125 static void vmspace_dtor(void *obj, void *private);
127 MALLOC_DEFINE(M_VMSPACE, "vmspace", "vmspace objcache backingstore");
129 struct sysref_class vmspace_sysref_class = {
130 .name = "vmspace",
131 .mtype = M_VMSPACE,
132 .proto = SYSREF_PROTO_VMSPACE,
133 .offset = offsetof(struct vmspace, vm_sysref),
134 .objsize = sizeof(struct vmspace),
135 .mag_capacity = 32,
136 .flags = SRC_MANAGEDINIT,
137 .dtor = vmspace_dtor,
138 .ops = {
139 .terminate = (sysref_terminate_func_t)vmspace_terminate
143 #define VMEPERCPU 2
145 static struct vm_zone mapentzone_store, mapzone_store;
146 static vm_zone_t mapentzone, mapzone;
147 static struct vm_object mapentobj, mapobj;
149 static struct vm_map_entry map_entry_init[MAX_MAPENT];
150 static struct vm_map_entry cpu_map_entry_init[MAXCPU][VMEPERCPU];
151 static struct vm_map map_init[MAX_KMAP];
153 static void vm_map_entry_shadow(vm_map_entry_t entry);
154 static vm_map_entry_t vm_map_entry_create(vm_map_t map, int *);
155 static void vm_map_entry_dispose (vm_map_t map, vm_map_entry_t entry, int *);
156 static void _vm_map_clip_end (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
157 static void _vm_map_clip_start (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
158 static void vm_map_entry_delete (vm_map_t, vm_map_entry_t, int *);
159 static void vm_map_entry_unwire (vm_map_t, vm_map_entry_t);
160 static void vm_map_copy_entry (vm_map_t, vm_map_t, vm_map_entry_t,
161 vm_map_entry_t);
162 static void vm_map_split (vm_map_entry_t);
163 static void vm_map_unclip_range (vm_map_t map, vm_map_entry_t start_entry, vm_offset_t start, vm_offset_t end, int *count, int flags);
166 * vm_map_startup:
168 * Initialize the vm_map module. Must be called before
169 * any other vm_map routines.
171 * Map and entry structures are allocated from the general
172 * purpose memory pool with some exceptions:
174 * - The kernel map and kmem submap are allocated statically.
175 * - Kernel map entries are allocated out of a static pool.
177 * These restrictions are necessary since malloc() uses the
178 * maps and requires map entries.
180 void
181 vm_map_startup(void)
183 mapzone = &mapzone_store;
184 zbootinit(mapzone, "MAP", sizeof (struct vm_map),
185 map_init, MAX_KMAP);
186 mapentzone = &mapentzone_store;
187 zbootinit(mapentzone, "MAP ENTRY", sizeof (struct vm_map_entry),
188 map_entry_init, MAX_MAPENT);
192 * vm_init2 - called prior to any vmspace allocations
194 void
195 vm_init2(void)
197 zinitna(mapentzone, &mapentobj, NULL, 0, 0,
198 ZONE_USE_RESERVE | ZONE_SPECIAL, 1);
199 zinitna(mapzone, &mapobj, NULL, 0, 0, 0, 1);
200 pmap_init2();
201 vm_object_init2();
206 * Red black tree functions
208 static int rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b);
209 RB_GENERATE(vm_map_rb_tree, vm_map_entry, rb_entry, rb_vm_map_compare);
211 /* a->start is address, and the only field has to be initialized */
212 static int
213 rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b)
215 if (a->start < b->start)
216 return(-1);
217 else if (a->start > b->start)
218 return(1);
219 return(0);
223 * Allocate a vmspace structure, including a vm_map and pmap.
224 * Initialize numerous fields. While the initial allocation is zerod,
225 * subsequence reuse from the objcache leaves elements of the structure
226 * intact (particularly the pmap), so portions must be zerod.
228 * The structure is not considered activated until we call sysref_activate().
230 struct vmspace *
231 vmspace_alloc(vm_offset_t min, vm_offset_t max)
233 struct vmspace *vm;
235 vm = sysref_alloc(&vmspace_sysref_class);
236 bzero(&vm->vm_startcopy,
237 (char *)&vm->vm_endcopy - (char *)&vm->vm_startcopy);
238 vm_map_init(&vm->vm_map, min, max, NULL);
239 pmap_pinit(vmspace_pmap(vm)); /* (some fields reused) */
240 vm->vm_map.pmap = vmspace_pmap(vm); /* XXX */
241 vm->vm_shm = NULL;
242 vm->vm_exitingcnt = 0;
243 cpu_vmspace_alloc(vm);
244 sysref_activate(&vm->vm_sysref);
245 return (vm);
249 * dtor function - Some elements of the pmap are retained in the
250 * free-cached vmspaces to improve performance. We have to clean them up
251 * here before returning the vmspace to the memory pool.
253 static void
254 vmspace_dtor(void *obj, void *private)
256 struct vmspace *vm = obj;
258 pmap_puninit(vmspace_pmap(vm));
262 * Called in two cases:
264 * (1) When the last sysref is dropped, but exitingcnt might still be
265 * non-zero.
267 * (2) When there are no sysrefs (i.e. refcnt is negative) left and the
268 * exitingcnt becomes zero
270 * sysref will not scrap the object until we call sysref_put() once more
271 * after the last ref has been dropped.
273 static void
274 vmspace_terminate(struct vmspace *vm)
276 int count;
279 * If exitingcnt is non-zero we can't get rid of the entire vmspace
280 * yet, but we can scrap user memory.
282 if (vm->vm_exitingcnt) {
283 shmexit(vm);
284 pmap_remove_pages(vmspace_pmap(vm), VM_MIN_USER_ADDRESS,
285 VM_MAX_USER_ADDRESS);
286 vm_map_remove(&vm->vm_map, VM_MIN_USER_ADDRESS,
287 VM_MAX_USER_ADDRESS);
289 return;
291 cpu_vmspace_free(vm);
294 * Make sure any SysV shm is freed, it might not have in
295 * exit1()
297 shmexit(vm);
299 KKASSERT(vm->vm_upcalls == NULL);
302 * Lock the map, to wait out all other references to it.
303 * Delete all of the mappings and pages they hold, then call
304 * the pmap module to reclaim anything left.
306 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
307 vm_map_lock(&vm->vm_map);
308 vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
309 vm->vm_map.max_offset, &count);
310 vm_map_unlock(&vm->vm_map);
311 vm_map_entry_release(count);
313 pmap_release(vmspace_pmap(vm));
314 sysref_put(&vm->vm_sysref);
318 * This is called in the wait*() handling code. The vmspace can be terminated
319 * after the last wait is finished using it.
321 void
322 vmspace_exitfree(struct proc *p)
324 struct vmspace *vm;
326 vm = p->p_vmspace;
327 p->p_vmspace = NULL;
329 if (--vm->vm_exitingcnt == 0 && sysref_isinactive(&vm->vm_sysref))
330 vmspace_terminate(vm);
334 * vmspace_swap_count()
336 * Swap useage is determined by taking the proportional swap used by
337 * VM objects backing the VM map. To make up for fractional losses,
338 * if the VM object has any swap use at all the associated map entries
339 * count for at least 1 swap page.
342 vmspace_swap_count(struct vmspace *vmspace)
344 vm_map_t map = &vmspace->vm_map;
345 vm_map_entry_t cur;
346 vm_object_t object;
347 int count = 0;
348 int n;
350 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
351 switch(cur->maptype) {
352 case VM_MAPTYPE_NORMAL:
353 case VM_MAPTYPE_VPAGETABLE:
354 if ((object = cur->object.vm_object) == NULL)
355 break;
356 if (object->type != OBJT_SWAP)
357 break;
358 n = (cur->end - cur->start) / PAGE_SIZE;
359 if (object->un_pager.swp.swp_bcount) {
360 count += object->un_pager.swp.swp_bcount *
361 SWAP_META_PAGES * n / object->size + 1;
363 break;
364 default:
365 break;
368 return(count);
372 * vmspace_anonymous_count()
374 * Calculate the approximate number of anonymous pages in use by
375 * this vmspace. To make up for fractional losses, we count each
376 * VM object as having at least 1 anonymous page.
379 vmspace_anonymous_count(struct vmspace *vmspace)
381 vm_map_t map = &vmspace->vm_map;
382 vm_map_entry_t cur;
383 vm_object_t object;
384 int count = 0;
386 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
387 switch(cur->maptype) {
388 case VM_MAPTYPE_NORMAL:
389 case VM_MAPTYPE_VPAGETABLE:
390 if ((object = cur->object.vm_object) == NULL)
391 break;
392 if (object->type != OBJT_DEFAULT &&
393 object->type != OBJT_SWAP) {
394 break;
396 count += object->resident_page_count;
397 break;
398 default:
399 break;
402 return(count);
409 * vm_map_create:
411 * Creates and returns a new empty VM map with
412 * the given physical map structure, and having
413 * the given lower and upper address bounds.
415 vm_map_t
416 vm_map_create(vm_map_t result, pmap_t pmap, vm_offset_t min, vm_offset_t max)
418 if (result == NULL)
419 result = zalloc(mapzone);
420 vm_map_init(result, min, max, pmap);
421 return (result);
425 * Initialize an existing vm_map structure
426 * such as that in the vmspace structure.
427 * The pmap is set elsewhere.
429 void
430 vm_map_init(struct vm_map *map, vm_offset_t min, vm_offset_t max, pmap_t pmap)
432 map->header.next = map->header.prev = &map->header;
433 RB_INIT(&map->rb_root);
434 map->nentries = 0;
435 map->size = 0;
436 map->system_map = 0;
437 map->infork = 0;
438 map->min_offset = min;
439 map->max_offset = max;
440 map->pmap = pmap;
441 map->first_free = &map->header;
442 map->hint = &map->header;
443 map->timestamp = 0;
444 lockinit(&map->lock, "thrd_sleep", 0, 0);
448 * Shadow the vm_map_entry's object. This typically needs to be done when
449 * a write fault is taken on an entry which had previously been cloned by
450 * fork(). The shared object (which might be NULL) must become private so
451 * we add a shadow layer above it.
453 * Object allocation for anonymous mappings is defered as long as possible.
454 * When creating a shadow, however, the underlying object must be instantiated
455 * so it can be shared.
457 * If the map segment is governed by a virtual page table then it is
458 * possible to address offsets beyond the mapped area. Just allocate
459 * a maximally sized object for this case.
461 static
462 void
463 vm_map_entry_shadow(vm_map_entry_t entry)
465 if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
466 vm_object_shadow(&entry->object.vm_object, &entry->offset,
467 0x7FFFFFFF); /* XXX */
468 } else {
469 vm_object_shadow(&entry->object.vm_object, &entry->offset,
470 atop(entry->end - entry->start));
472 entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
476 * Allocate an object for a vm_map_entry.
478 * Object allocation for anonymous mappings is defered as long as possible.
479 * This function is called when we can defer no longer, generally when a map
480 * entry might be split or forked or takes a page fault.
482 * If the map segment is governed by a virtual page table then it is
483 * possible to address offsets beyond the mapped area. Just allocate
484 * a maximally sized object for this case.
486 void
487 vm_map_entry_allocate_object(vm_map_entry_t entry)
489 vm_object_t obj;
491 if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
492 obj = vm_object_allocate(OBJT_DEFAULT, 0x7FFFFFFF); /* XXX */
493 } else {
494 obj = vm_object_allocate(OBJT_DEFAULT,
495 atop(entry->end - entry->start));
497 entry->object.vm_object = obj;
498 entry->offset = 0;
502 * vm_map_entry_reserve_cpu_init:
504 * Set an initial negative count so the first attempt to reserve
505 * space preloads a bunch of vm_map_entry's for this cpu. Also
506 * pre-allocate 2 vm_map_entries which will be needed by zalloc() to
507 * map a new page for vm_map_entry structures. SMP systems are
508 * particularly sensitive.
510 * This routine is called in early boot so we cannot just call
511 * vm_map_entry_reserve().
513 * May be called for a gd other then mycpu, but may only be called
514 * during early boot.
516 void
517 vm_map_entry_reserve_cpu_init(globaldata_t gd)
519 vm_map_entry_t entry;
520 int i;
522 gd->gd_vme_avail -= MAP_RESERVE_COUNT * 2;
523 entry = &cpu_map_entry_init[gd->gd_cpuid][0];
524 for (i = 0; i < VMEPERCPU; ++i, ++entry) {
525 entry->next = gd->gd_vme_base;
526 gd->gd_vme_base = entry;
531 * vm_map_entry_reserve:
533 * Reserves vm_map_entry structures so code later on can manipulate
534 * map_entry structures within a locked map without blocking trying
535 * to allocate a new vm_map_entry.
538 vm_map_entry_reserve(int count)
540 struct globaldata *gd = mycpu;
541 vm_map_entry_t entry;
543 crit_enter();
546 * Make sure we have enough structures in gd_vme_base to handle
547 * the reservation request.
549 while (gd->gd_vme_avail < count) {
550 entry = zalloc(mapentzone);
551 entry->next = gd->gd_vme_base;
552 gd->gd_vme_base = entry;
553 ++gd->gd_vme_avail;
555 gd->gd_vme_avail -= count;
556 crit_exit();
557 return(count);
561 * vm_map_entry_release:
563 * Releases previously reserved vm_map_entry structures that were not
564 * used. If we have too much junk in our per-cpu cache clean some of
565 * it out.
567 void
568 vm_map_entry_release(int count)
570 struct globaldata *gd = mycpu;
571 vm_map_entry_t entry;
573 crit_enter();
574 gd->gd_vme_avail += count;
575 while (gd->gd_vme_avail > MAP_RESERVE_SLOP) {
576 entry = gd->gd_vme_base;
577 KKASSERT(entry != NULL);
578 gd->gd_vme_base = entry->next;
579 --gd->gd_vme_avail;
580 crit_exit();
581 zfree(mapentzone, entry);
582 crit_enter();
584 crit_exit();
588 * vm_map_entry_kreserve:
590 * Reserve map entry structures for use in kernel_map itself. These
591 * entries have *ALREADY* been reserved on a per-cpu basis when the map
592 * was inited. This function is used by zalloc() to avoid a recursion
593 * when zalloc() itself needs to allocate additional kernel memory.
595 * This function works like the normal reserve but does not load the
596 * vm_map_entry cache (because that would result in an infinite
597 * recursion). Note that gd_vme_avail may go negative. This is expected.
599 * Any caller of this function must be sure to renormalize after
600 * potentially eating entries to ensure that the reserve supply
601 * remains intact.
604 vm_map_entry_kreserve(int count)
606 struct globaldata *gd = mycpu;
608 crit_enter();
609 gd->gd_vme_avail -= count;
610 crit_exit();
611 KASSERT(gd->gd_vme_base != NULL, ("no reserved entries left, gd_vme_avail = %d\n", gd->gd_vme_avail));
612 return(count);
616 * vm_map_entry_krelease:
618 * Release previously reserved map entries for kernel_map. We do not
619 * attempt to clean up like the normal release function as this would
620 * cause an unnecessary (but probably not fatal) deep procedure call.
622 void
623 vm_map_entry_krelease(int count)
625 struct globaldata *gd = mycpu;
627 crit_enter();
628 gd->gd_vme_avail += count;
629 crit_exit();
633 * vm_map_entry_create: [ internal use only ]
635 * Allocates a VM map entry for insertion. No entry fields are filled
636 * in.
638 * This routine may be called from an interrupt thread but not a FAST
639 * interrupt. This routine may recurse the map lock.
641 static vm_map_entry_t
642 vm_map_entry_create(vm_map_t map, int *countp)
644 struct globaldata *gd = mycpu;
645 vm_map_entry_t entry;
647 KKASSERT(*countp > 0);
648 --*countp;
649 crit_enter();
650 entry = gd->gd_vme_base;
651 KASSERT(entry != NULL, ("gd_vme_base NULL! count %d", *countp));
652 gd->gd_vme_base = entry->next;
653 crit_exit();
654 return(entry);
658 * vm_map_entry_dispose: [ internal use only ]
660 * Dispose of a vm_map_entry that is no longer being referenced. This
661 * function may be called from an interrupt.
663 static void
664 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry, int *countp)
666 struct globaldata *gd = mycpu;
668 KKASSERT(map->hint != entry);
669 KKASSERT(map->first_free != entry);
671 ++*countp;
672 crit_enter();
673 entry->next = gd->gd_vme_base;
674 gd->gd_vme_base = entry;
675 crit_exit();
680 * vm_map_entry_{un,}link:
682 * Insert/remove entries from maps.
684 static __inline void
685 vm_map_entry_link(vm_map_t map,
686 vm_map_entry_t after_where,
687 vm_map_entry_t entry)
689 map->nentries++;
690 entry->prev = after_where;
691 entry->next = after_where->next;
692 entry->next->prev = entry;
693 after_where->next = entry;
694 if (vm_map_rb_tree_RB_INSERT(&map->rb_root, entry))
695 panic("vm_map_entry_link: dup addr map %p ent %p", map, entry);
698 static __inline void
699 vm_map_entry_unlink(vm_map_t map,
700 vm_map_entry_t entry)
702 vm_map_entry_t prev;
703 vm_map_entry_t next;
705 if (entry->eflags & MAP_ENTRY_IN_TRANSITION)
706 panic("vm_map_entry_unlink: attempt to mess with locked entry! %p", entry);
707 prev = entry->prev;
708 next = entry->next;
709 next->prev = prev;
710 prev->next = next;
711 vm_map_rb_tree_RB_REMOVE(&map->rb_root, entry);
712 map->nentries--;
716 * vm_map_lookup_entry: [ internal use only ]
718 * Finds the map entry containing (or
719 * immediately preceding) the specified address
720 * in the given map; the entry is returned
721 * in the "entry" parameter. The boolean
722 * result indicates whether the address is
723 * actually contained in the map.
725 boolean_t
726 vm_map_lookup_entry(vm_map_t map, vm_offset_t address,
727 vm_map_entry_t *entry /* OUT */)
729 vm_map_entry_t tmp;
730 vm_map_entry_t last;
732 #if 0
734 * XXX TEMPORARILY DISABLED. For some reason our attempt to revive
735 * the hint code with the red-black lookup meets with system crashes
736 * and lockups. We do not yet know why.
738 * It is possible that the problem is related to the setting
739 * of the hint during map_entry deletion, in the code specified
740 * at the GGG comment later on in this file.
743 * Quickly check the cached hint, there's a good chance of a match.
745 if (map->hint != &map->header) {
746 tmp = map->hint;
747 if (address >= tmp->start && address < tmp->end) {
748 *entry = tmp;
749 return(TRUE);
752 #endif
755 * Locate the record from the top of the tree. 'last' tracks the
756 * closest prior record and is returned if no match is found, which
757 * in binary tree terms means tracking the most recent right-branch
758 * taken. If there is no prior record, &map->header is returned.
760 last = &map->header;
761 tmp = RB_ROOT(&map->rb_root);
763 while (tmp) {
764 if (address >= tmp->start) {
765 if (address < tmp->end) {
766 *entry = tmp;
767 map->hint = tmp;
768 return(TRUE);
770 last = tmp;
771 tmp = RB_RIGHT(tmp, rb_entry);
772 } else {
773 tmp = RB_LEFT(tmp, rb_entry);
776 *entry = last;
777 return (FALSE);
781 * vm_map_insert:
783 * Inserts the given whole VM object into the target
784 * map at the specified address range. The object's
785 * size should match that of the address range.
787 * Requires that the map be locked, and leaves it so. Requires that
788 * sufficient vm_map_entry structures have been reserved and tracks
789 * the use via countp.
791 * If object is non-NULL, ref count must be bumped by caller
792 * prior to making call to account for the new entry.
795 vm_map_insert(vm_map_t map, int *countp,
796 vm_object_t object, vm_ooffset_t offset,
797 vm_offset_t start, vm_offset_t end,
798 vm_maptype_t maptype,
799 vm_prot_t prot, vm_prot_t max,
800 int cow)
802 vm_map_entry_t new_entry;
803 vm_map_entry_t prev_entry;
804 vm_map_entry_t temp_entry;
805 vm_eflags_t protoeflags;
808 * Check that the start and end points are not bogus.
811 if ((start < map->min_offset) || (end > map->max_offset) ||
812 (start >= end))
813 return (KERN_INVALID_ADDRESS);
816 * Find the entry prior to the proposed starting address; if it's part
817 * of an existing entry, this range is bogus.
820 if (vm_map_lookup_entry(map, start, &temp_entry))
821 return (KERN_NO_SPACE);
823 prev_entry = temp_entry;
826 * Assert that the next entry doesn't overlap the end point.
829 if ((prev_entry->next != &map->header) &&
830 (prev_entry->next->start < end))
831 return (KERN_NO_SPACE);
833 protoeflags = 0;
835 if (cow & MAP_COPY_ON_WRITE)
836 protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
838 if (cow & MAP_NOFAULT) {
839 protoeflags |= MAP_ENTRY_NOFAULT;
841 KASSERT(object == NULL,
842 ("vm_map_insert: paradoxical MAP_NOFAULT request"));
844 if (cow & MAP_DISABLE_SYNCER)
845 protoeflags |= MAP_ENTRY_NOSYNC;
846 if (cow & MAP_DISABLE_COREDUMP)
847 protoeflags |= MAP_ENTRY_NOCOREDUMP;
849 if (object) {
851 * When object is non-NULL, it could be shared with another
852 * process. We have to set or clear OBJ_ONEMAPPING
853 * appropriately.
855 if ((object->ref_count > 1) || (object->shadow_count != 0)) {
856 vm_object_clear_flag(object, OBJ_ONEMAPPING);
859 else if ((prev_entry != &map->header) &&
860 (prev_entry->eflags == protoeflags) &&
861 (prev_entry->end == start) &&
862 (prev_entry->wired_count == 0) &&
863 prev_entry->maptype == maptype &&
864 ((prev_entry->object.vm_object == NULL) ||
865 vm_object_coalesce(prev_entry->object.vm_object,
866 OFF_TO_IDX(prev_entry->offset),
867 (vm_size_t)(prev_entry->end - prev_entry->start),
868 (vm_size_t)(end - prev_entry->end)))) {
870 * We were able to extend the object. Determine if we
871 * can extend the previous map entry to include the
872 * new range as well.
874 if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
875 (prev_entry->protection == prot) &&
876 (prev_entry->max_protection == max)) {
877 map->size += (end - prev_entry->end);
878 prev_entry->end = end;
879 vm_map_simplify_entry(map, prev_entry, countp);
880 return (KERN_SUCCESS);
884 * If we can extend the object but cannot extend the
885 * map entry, we have to create a new map entry. We
886 * must bump the ref count on the extended object to
887 * account for it. object may be NULL.
889 object = prev_entry->object.vm_object;
890 offset = prev_entry->offset +
891 (prev_entry->end - prev_entry->start);
892 vm_object_reference(object);
896 * NOTE: if conditionals fail, object can be NULL here. This occurs
897 * in things like the buffer map where we manage kva but do not manage
898 * backing objects.
902 * Create a new entry
905 new_entry = vm_map_entry_create(map, countp);
906 new_entry->start = start;
907 new_entry->end = end;
909 new_entry->maptype = maptype;
910 new_entry->eflags = protoeflags;
911 new_entry->object.vm_object = object;
912 new_entry->offset = offset;
913 new_entry->aux.master_pde = 0;
915 new_entry->inheritance = VM_INHERIT_DEFAULT;
916 new_entry->protection = prot;
917 new_entry->max_protection = max;
918 new_entry->wired_count = 0;
921 * Insert the new entry into the list
924 vm_map_entry_link(map, prev_entry, new_entry);
925 map->size += new_entry->end - new_entry->start;
928 * Update the free space hint
930 if ((map->first_free == prev_entry) &&
931 (prev_entry->end >= new_entry->start)) {
932 map->first_free = new_entry;
935 #if 0
937 * Temporarily removed to avoid MAP_STACK panic, due to
938 * MAP_STACK being a huge hack. Will be added back in
939 * when MAP_STACK (and the user stack mapping) is fixed.
942 * It may be possible to simplify the entry
944 vm_map_simplify_entry(map, new_entry, countp);
945 #endif
948 * Try to pre-populate the page table. Mappings governed by virtual
949 * page tables cannot be prepopulated without a lot of work, so
950 * don't try.
952 if ((cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) &&
953 maptype != VM_MAPTYPE_VPAGETABLE) {
954 pmap_object_init_pt(map->pmap, start, prot,
955 object, OFF_TO_IDX(offset), end - start,
956 cow & MAP_PREFAULT_PARTIAL);
959 return (KERN_SUCCESS);
963 * Find sufficient space for `length' bytes in the given map, starting at
964 * `start'. The map must be locked. Returns 0 on success, 1 on no space.
966 * This function will returned an arbitrarily aligned pointer. If no
967 * particular alignment is required you should pass align as 1. Note that
968 * the map may return PAGE_SIZE aligned pointers if all the lengths used in
969 * the map are a multiple of PAGE_SIZE, even if you pass a smaller align
970 * argument.
972 * 'align' should be a power of 2 but is not required to be.
975 vm_map_findspace(
976 vm_map_t map,
977 vm_offset_t start,
978 vm_size_t length,
979 vm_offset_t align,
980 vm_offset_t *addr)
982 vm_map_entry_t entry, next;
983 vm_offset_t end;
984 vm_offset_t align_mask;
986 if (start < map->min_offset)
987 start = map->min_offset;
988 if (start > map->max_offset)
989 return (1);
992 * If the alignment is not a power of 2 we will have to use
993 * a mod/division, set align_mask to a special value.
995 if ((align | (align - 1)) + 1 != (align << 1))
996 align_mask = (vm_offset_t)-1;
997 else
998 align_mask = align - 1;
1000 retry:
1002 * Look for the first possible address; if there's already something
1003 * at this address, we have to start after it.
1005 if (start == map->min_offset) {
1006 if ((entry = map->first_free) != &map->header)
1007 start = entry->end;
1008 } else {
1009 vm_map_entry_t tmp;
1011 if (vm_map_lookup_entry(map, start, &tmp))
1012 start = tmp->end;
1013 entry = tmp;
1017 * Look through the rest of the map, trying to fit a new region in the
1018 * gap between existing regions, or after the very last region.
1020 for (;; start = (entry = next)->end) {
1022 * Adjust the proposed start by the requested alignment,
1023 * be sure that we didn't wrap the address.
1025 if (align_mask == (vm_offset_t)-1)
1026 end = ((start + align - 1) / align) * align;
1027 else
1028 end = (start + align_mask) & ~align_mask;
1029 if (end < start)
1030 return (1);
1031 start = end;
1033 * Find the end of the proposed new region. Be sure we didn't
1034 * go beyond the end of the map, or wrap around the address.
1035 * Then check to see if this is the last entry or if the
1036 * proposed end fits in the gap between this and the next
1037 * entry.
1039 end = start + length;
1040 if (end > map->max_offset || end < start)
1041 return (1);
1042 next = entry->next;
1043 if (next == &map->header || next->start >= end)
1044 break;
1046 map->hint = entry;
1047 if (map == &kernel_map) {
1048 vm_offset_t ksize;
1049 if ((ksize = round_page(start + length)) > kernel_vm_end) {
1050 pmap_growkernel(ksize);
1051 goto retry;
1054 *addr = start;
1055 return (0);
1059 * vm_map_find finds an unallocated region in the target address
1060 * map with the given length. The search is defined to be
1061 * first-fit from the specified address; the region found is
1062 * returned in the same parameter.
1064 * If object is non-NULL, ref count must be bumped by caller
1065 * prior to making call to account for the new entry.
1068 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1069 vm_offset_t *addr, vm_size_t length,
1070 boolean_t find_space,
1071 vm_maptype_t maptype,
1072 vm_prot_t prot, vm_prot_t max,
1073 int cow)
1075 vm_offset_t start;
1076 int result;
1077 int count;
1079 start = *addr;
1081 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1082 vm_map_lock(map);
1083 if (find_space) {
1084 if (vm_map_findspace(map, start, length, 1, addr)) {
1085 vm_map_unlock(map);
1086 vm_map_entry_release(count);
1087 return (KERN_NO_SPACE);
1089 start = *addr;
1091 result = vm_map_insert(map, &count, object, offset,
1092 start, start + length,
1093 maptype,
1094 prot, max,
1095 cow);
1096 vm_map_unlock(map);
1097 vm_map_entry_release(count);
1099 return (result);
1103 * vm_map_simplify_entry:
1105 * Simplify the given map entry by merging with either neighbor. This
1106 * routine also has the ability to merge with both neighbors.
1108 * The map must be locked.
1110 * This routine guarentees that the passed entry remains valid (though
1111 * possibly extended). When merging, this routine may delete one or
1112 * both neighbors. No action is taken on entries which have their
1113 * in-transition flag set.
1115 void
1116 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry, int *countp)
1118 vm_map_entry_t next, prev;
1119 vm_size_t prevsize, esize;
1121 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1122 ++mycpu->gd_cnt.v_intrans_coll;
1123 return;
1126 if (entry->maptype == VM_MAPTYPE_SUBMAP)
1127 return;
1129 prev = entry->prev;
1130 if (prev != &map->header) {
1131 prevsize = prev->end - prev->start;
1132 if ( (prev->end == entry->start) &&
1133 (prev->maptype == entry->maptype) &&
1134 (prev->object.vm_object == entry->object.vm_object) &&
1135 (!prev->object.vm_object ||
1136 (prev->offset + prevsize == entry->offset)) &&
1137 (prev->eflags == entry->eflags) &&
1138 (prev->protection == entry->protection) &&
1139 (prev->max_protection == entry->max_protection) &&
1140 (prev->inheritance == entry->inheritance) &&
1141 (prev->wired_count == entry->wired_count)) {
1142 if (map->first_free == prev)
1143 map->first_free = entry;
1144 if (map->hint == prev)
1145 map->hint = entry;
1146 vm_map_entry_unlink(map, prev);
1147 entry->start = prev->start;
1148 entry->offset = prev->offset;
1149 if (prev->object.vm_object)
1150 vm_object_deallocate(prev->object.vm_object);
1151 vm_map_entry_dispose(map, prev, countp);
1155 next = entry->next;
1156 if (next != &map->header) {
1157 esize = entry->end - entry->start;
1158 if ((entry->end == next->start) &&
1159 (next->maptype == entry->maptype) &&
1160 (next->object.vm_object == entry->object.vm_object) &&
1161 (!entry->object.vm_object ||
1162 (entry->offset + esize == next->offset)) &&
1163 (next->eflags == entry->eflags) &&
1164 (next->protection == entry->protection) &&
1165 (next->max_protection == entry->max_protection) &&
1166 (next->inheritance == entry->inheritance) &&
1167 (next->wired_count == entry->wired_count)) {
1168 if (map->first_free == next)
1169 map->first_free = entry;
1170 if (map->hint == next)
1171 map->hint = entry;
1172 vm_map_entry_unlink(map, next);
1173 entry->end = next->end;
1174 if (next->object.vm_object)
1175 vm_object_deallocate(next->object.vm_object);
1176 vm_map_entry_dispose(map, next, countp);
1181 * vm_map_clip_start: [ internal use only ]
1183 * Asserts that the given entry begins at or after
1184 * the specified address; if necessary,
1185 * it splits the entry into two.
1187 #define vm_map_clip_start(map, entry, startaddr, countp) \
1189 if (startaddr > entry->start) \
1190 _vm_map_clip_start(map, entry, startaddr, countp); \
1194 * This routine is called only when it is known that
1195 * the entry must be split.
1197 static void
1198 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start, int *countp)
1200 vm_map_entry_t new_entry;
1203 * Split off the front portion -- note that we must insert the new
1204 * entry BEFORE this one, so that this entry has the specified
1205 * starting address.
1208 vm_map_simplify_entry(map, entry, countp);
1211 * If there is no object backing this entry, we might as well create
1212 * one now. If we defer it, an object can get created after the map
1213 * is clipped, and individual objects will be created for the split-up
1214 * map. This is a bit of a hack, but is also about the best place to
1215 * put this improvement.
1217 if (entry->object.vm_object == NULL && !map->system_map) {
1218 vm_map_entry_allocate_object(entry);
1221 new_entry = vm_map_entry_create(map, countp);
1222 *new_entry = *entry;
1224 new_entry->end = start;
1225 entry->offset += (start - entry->start);
1226 entry->start = start;
1228 vm_map_entry_link(map, entry->prev, new_entry);
1230 switch(entry->maptype) {
1231 case VM_MAPTYPE_NORMAL:
1232 case VM_MAPTYPE_VPAGETABLE:
1233 vm_object_reference(new_entry->object.vm_object);
1234 break;
1235 default:
1236 break;
1241 * vm_map_clip_end: [ internal use only ]
1243 * Asserts that the given entry ends at or before
1244 * the specified address; if necessary,
1245 * it splits the entry into two.
1248 #define vm_map_clip_end(map, entry, endaddr, countp) \
1250 if (endaddr < entry->end) \
1251 _vm_map_clip_end(map, entry, endaddr, countp); \
1255 * This routine is called only when it is known that
1256 * the entry must be split.
1258 static void
1259 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end, int *countp)
1261 vm_map_entry_t new_entry;
1264 * If there is no object backing this entry, we might as well create
1265 * one now. If we defer it, an object can get created after the map
1266 * is clipped, and individual objects will be created for the split-up
1267 * map. This is a bit of a hack, but is also about the best place to
1268 * put this improvement.
1271 if (entry->object.vm_object == NULL && !map->system_map) {
1272 vm_map_entry_allocate_object(entry);
1276 * Create a new entry and insert it AFTER the specified entry
1279 new_entry = vm_map_entry_create(map, countp);
1280 *new_entry = *entry;
1282 new_entry->start = entry->end = end;
1283 new_entry->offset += (end - entry->start);
1285 vm_map_entry_link(map, entry, new_entry);
1287 switch(entry->maptype) {
1288 case VM_MAPTYPE_NORMAL:
1289 case VM_MAPTYPE_VPAGETABLE:
1290 vm_object_reference(new_entry->object.vm_object);
1291 break;
1292 default:
1293 break;
1298 * VM_MAP_RANGE_CHECK: [ internal use only ]
1300 * Asserts that the starting and ending region
1301 * addresses fall within the valid range of the map.
1303 #define VM_MAP_RANGE_CHECK(map, start, end) \
1305 if (start < vm_map_min(map)) \
1306 start = vm_map_min(map); \
1307 if (end > vm_map_max(map)) \
1308 end = vm_map_max(map); \
1309 if (start > end) \
1310 start = end; \
1314 * vm_map_transition_wait: [ kernel use only ]
1316 * Used to block when an in-transition collison occurs. The map
1317 * is unlocked for the sleep and relocked before the return.
1319 static
1320 void
1321 vm_map_transition_wait(vm_map_t map)
1323 vm_map_unlock(map);
1324 tsleep(map, 0, "vment", 0);
1325 vm_map_lock(map);
1329 * CLIP_CHECK_BACK
1330 * CLIP_CHECK_FWD
1332 * When we do blocking operations with the map lock held it is
1333 * possible that a clip might have occured on our in-transit entry,
1334 * requiring an adjustment to the entry in our loop. These macros
1335 * help the pageable and clip_range code deal with the case. The
1336 * conditional costs virtually nothing if no clipping has occured.
1339 #define CLIP_CHECK_BACK(entry, save_start) \
1340 do { \
1341 while (entry->start != save_start) { \
1342 entry = entry->prev; \
1343 KASSERT(entry != &map->header, ("bad entry clip")); \
1345 } while(0)
1347 #define CLIP_CHECK_FWD(entry, save_end) \
1348 do { \
1349 while (entry->end != save_end) { \
1350 entry = entry->next; \
1351 KASSERT(entry != &map->header, ("bad entry clip")); \
1353 } while(0)
1357 * vm_map_clip_range: [ kernel use only ]
1359 * Clip the specified range and return the base entry. The
1360 * range may cover several entries starting at the returned base
1361 * and the first and last entry in the covering sequence will be
1362 * properly clipped to the requested start and end address.
1364 * If no holes are allowed you should pass the MAP_CLIP_NO_HOLES
1365 * flag.
1367 * The MAP_ENTRY_IN_TRANSITION flag will be set for the entries
1368 * covered by the requested range.
1370 * The map must be exclusively locked on entry and will remain locked
1371 * on return. If no range exists or the range contains holes and you
1372 * specified that no holes were allowed, NULL will be returned. This
1373 * routine may temporarily unlock the map in order avoid a deadlock when
1374 * sleeping.
1376 static
1377 vm_map_entry_t
1378 vm_map_clip_range(vm_map_t map, vm_offset_t start, vm_offset_t end,
1379 int *countp, int flags)
1381 vm_map_entry_t start_entry;
1382 vm_map_entry_t entry;
1385 * Locate the entry and effect initial clipping. The in-transition
1386 * case does not occur very often so do not try to optimize it.
1388 again:
1389 if (vm_map_lookup_entry(map, start, &start_entry) == FALSE)
1390 return (NULL);
1391 entry = start_entry;
1392 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1393 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1394 ++mycpu->gd_cnt.v_intrans_coll;
1395 ++mycpu->gd_cnt.v_intrans_wait;
1396 vm_map_transition_wait(map);
1398 * entry and/or start_entry may have been clipped while
1399 * we slept, or may have gone away entirely. We have
1400 * to restart from the lookup.
1402 goto again;
1405 * Since we hold an exclusive map lock we do not have to restart
1406 * after clipping, even though clipping may block in zalloc.
1408 vm_map_clip_start(map, entry, start, countp);
1409 vm_map_clip_end(map, entry, end, countp);
1410 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1413 * Scan entries covered by the range. When working on the next
1414 * entry a restart need only re-loop on the current entry which
1415 * we have already locked, since 'next' may have changed. Also,
1416 * even though entry is safe, it may have been clipped so we
1417 * have to iterate forwards through the clip after sleeping.
1419 while (entry->next != &map->header && entry->next->start < end) {
1420 vm_map_entry_t next = entry->next;
1422 if (flags & MAP_CLIP_NO_HOLES) {
1423 if (next->start > entry->end) {
1424 vm_map_unclip_range(map, start_entry,
1425 start, entry->end, countp, flags);
1426 return(NULL);
1430 if (next->eflags & MAP_ENTRY_IN_TRANSITION) {
1431 vm_offset_t save_end = entry->end;
1432 next->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1433 ++mycpu->gd_cnt.v_intrans_coll;
1434 ++mycpu->gd_cnt.v_intrans_wait;
1435 vm_map_transition_wait(map);
1438 * clips might have occured while we blocked.
1440 CLIP_CHECK_FWD(entry, save_end);
1441 CLIP_CHECK_BACK(start_entry, start);
1442 continue;
1445 * No restart necessary even though clip_end may block, we
1446 * are holding the map lock.
1448 vm_map_clip_end(map, next, end, countp);
1449 next->eflags |= MAP_ENTRY_IN_TRANSITION;
1450 entry = next;
1452 if (flags & MAP_CLIP_NO_HOLES) {
1453 if (entry->end != end) {
1454 vm_map_unclip_range(map, start_entry,
1455 start, entry->end, countp, flags);
1456 return(NULL);
1459 return(start_entry);
1463 * vm_map_unclip_range: [ kernel use only ]
1465 * Undo the effect of vm_map_clip_range(). You should pass the same
1466 * flags and the same range that you passed to vm_map_clip_range().
1467 * This code will clear the in-transition flag on the entries and
1468 * wake up anyone waiting. This code will also simplify the sequence
1469 * and attempt to merge it with entries before and after the sequence.
1471 * The map must be locked on entry and will remain locked on return.
1473 * Note that you should also pass the start_entry returned by
1474 * vm_map_clip_range(). However, if you block between the two calls
1475 * with the map unlocked please be aware that the start_entry may
1476 * have been clipped and you may need to scan it backwards to find
1477 * the entry corresponding with the original start address. You are
1478 * responsible for this, vm_map_unclip_range() expects the correct
1479 * start_entry to be passed to it and will KASSERT otherwise.
1481 static
1482 void
1483 vm_map_unclip_range(
1484 vm_map_t map,
1485 vm_map_entry_t start_entry,
1486 vm_offset_t start,
1487 vm_offset_t end,
1488 int *countp,
1489 int flags)
1491 vm_map_entry_t entry;
1493 entry = start_entry;
1495 KASSERT(entry->start == start, ("unclip_range: illegal base entry"));
1496 while (entry != &map->header && entry->start < end) {
1497 KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION, ("in-transition flag not set during unclip on: %p", entry));
1498 KASSERT(entry->end <= end, ("unclip_range: tail wasn't clipped"));
1499 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1500 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1501 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1502 wakeup(map);
1504 entry = entry->next;
1508 * Simplification does not block so there is no restart case.
1510 entry = start_entry;
1511 while (entry != &map->header && entry->start < end) {
1512 vm_map_simplify_entry(map, entry, countp);
1513 entry = entry->next;
1518 * vm_map_submap: [ kernel use only ]
1520 * Mark the given range as handled by a subordinate map.
1522 * This range must have been created with vm_map_find,
1523 * and no other operations may have been performed on this
1524 * range prior to calling vm_map_submap.
1526 * Only a limited number of operations can be performed
1527 * within this rage after calling vm_map_submap:
1528 * vm_fault
1529 * [Don't try vm_map_copy!]
1531 * To remove a submapping, one must first remove the
1532 * range from the superior map, and then destroy the
1533 * submap (if desired). [Better yet, don't try it.]
1536 vm_map_submap(vm_map_t map, vm_offset_t start, vm_offset_t end, vm_map_t submap)
1538 vm_map_entry_t entry;
1539 int result = KERN_INVALID_ARGUMENT;
1540 int count;
1542 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1543 vm_map_lock(map);
1545 VM_MAP_RANGE_CHECK(map, start, end);
1547 if (vm_map_lookup_entry(map, start, &entry)) {
1548 vm_map_clip_start(map, entry, start, &count);
1549 } else {
1550 entry = entry->next;
1553 vm_map_clip_end(map, entry, end, &count);
1555 if ((entry->start == start) && (entry->end == end) &&
1556 ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1557 (entry->object.vm_object == NULL)) {
1558 entry->object.sub_map = submap;
1559 entry->maptype = VM_MAPTYPE_SUBMAP;
1560 result = KERN_SUCCESS;
1562 vm_map_unlock(map);
1563 vm_map_entry_release(count);
1565 return (result);
1569 * vm_map_protect:
1571 * Sets the protection of the specified address region in the target map.
1572 * If "set_max" is specified, the maximum protection is to be set;
1573 * otherwise, only the current protection is affected.
1575 * The protection is not applicable to submaps, but is applicable to normal
1576 * maps and maps governed by virtual page tables. For example, when operating
1577 * on a virtual page table our protection basically controls how COW occurs
1578 * on the backing object, whereas the virtual page table abstraction itself
1579 * is an abstraction for userland.
1582 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1583 vm_prot_t new_prot, boolean_t set_max)
1585 vm_map_entry_t current;
1586 vm_map_entry_t entry;
1587 int count;
1589 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1590 vm_map_lock(map);
1592 VM_MAP_RANGE_CHECK(map, start, end);
1594 if (vm_map_lookup_entry(map, start, &entry)) {
1595 vm_map_clip_start(map, entry, start, &count);
1596 } else {
1597 entry = entry->next;
1601 * Make a first pass to check for protection violations.
1603 current = entry;
1604 while ((current != &map->header) && (current->start < end)) {
1605 if (current->maptype == VM_MAPTYPE_SUBMAP) {
1606 vm_map_unlock(map);
1607 vm_map_entry_release(count);
1608 return (KERN_INVALID_ARGUMENT);
1610 if ((new_prot & current->max_protection) != new_prot) {
1611 vm_map_unlock(map);
1612 vm_map_entry_release(count);
1613 return (KERN_PROTECTION_FAILURE);
1615 current = current->next;
1619 * Go back and fix up protections. [Note that clipping is not
1620 * necessary the second time.]
1622 current = entry;
1624 while ((current != &map->header) && (current->start < end)) {
1625 vm_prot_t old_prot;
1627 vm_map_clip_end(map, current, end, &count);
1629 old_prot = current->protection;
1630 if (set_max) {
1631 current->protection =
1632 (current->max_protection = new_prot) &
1633 old_prot;
1634 } else {
1635 current->protection = new_prot;
1639 * Update physical map if necessary. Worry about copy-on-write
1640 * here -- CHECK THIS XXX
1643 if (current->protection != old_prot) {
1644 #define MASK(entry) (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1645 VM_PROT_ALL)
1647 pmap_protect(map->pmap, current->start,
1648 current->end,
1649 current->protection & MASK(current));
1650 #undef MASK
1653 vm_map_simplify_entry(map, current, &count);
1655 current = current->next;
1658 vm_map_unlock(map);
1659 vm_map_entry_release(count);
1660 return (KERN_SUCCESS);
1664 * vm_map_madvise:
1666 * This routine traverses a processes map handling the madvise
1667 * system call. Advisories are classified as either those effecting
1668 * the vm_map_entry structure, or those effecting the underlying
1669 * objects.
1671 * The <value> argument is used for extended madvise calls.
1674 vm_map_madvise(vm_map_t map, vm_offset_t start, vm_offset_t end,
1675 int behav, off_t value)
1677 vm_map_entry_t current, entry;
1678 int modify_map = 0;
1679 int error = 0;
1680 int count;
1683 * Some madvise calls directly modify the vm_map_entry, in which case
1684 * we need to use an exclusive lock on the map and we need to perform
1685 * various clipping operations. Otherwise we only need a read-lock
1686 * on the map.
1689 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1691 switch(behav) {
1692 case MADV_NORMAL:
1693 case MADV_SEQUENTIAL:
1694 case MADV_RANDOM:
1695 case MADV_NOSYNC:
1696 case MADV_AUTOSYNC:
1697 case MADV_NOCORE:
1698 case MADV_CORE:
1699 case MADV_SETMAP:
1700 case MADV_INVAL:
1701 modify_map = 1;
1702 vm_map_lock(map);
1703 break;
1704 case MADV_WILLNEED:
1705 case MADV_DONTNEED:
1706 case MADV_FREE:
1707 vm_map_lock_read(map);
1708 break;
1709 default:
1710 vm_map_entry_release(count);
1711 return (EINVAL);
1715 * Locate starting entry and clip if necessary.
1718 VM_MAP_RANGE_CHECK(map, start, end);
1720 if (vm_map_lookup_entry(map, start, &entry)) {
1721 if (modify_map)
1722 vm_map_clip_start(map, entry, start, &count);
1723 } else {
1724 entry = entry->next;
1727 if (modify_map) {
1729 * madvise behaviors that are implemented in the vm_map_entry.
1731 * We clip the vm_map_entry so that behavioral changes are
1732 * limited to the specified address range.
1734 for (current = entry;
1735 (current != &map->header) && (current->start < end);
1736 current = current->next
1738 if (current->maptype == VM_MAPTYPE_SUBMAP)
1739 continue;
1741 vm_map_clip_end(map, current, end, &count);
1743 switch (behav) {
1744 case MADV_NORMAL:
1745 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1746 break;
1747 case MADV_SEQUENTIAL:
1748 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1749 break;
1750 case MADV_RANDOM:
1751 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1752 break;
1753 case MADV_NOSYNC:
1754 current->eflags |= MAP_ENTRY_NOSYNC;
1755 break;
1756 case MADV_AUTOSYNC:
1757 current->eflags &= ~MAP_ENTRY_NOSYNC;
1758 break;
1759 case MADV_NOCORE:
1760 current->eflags |= MAP_ENTRY_NOCOREDUMP;
1761 break;
1762 case MADV_CORE:
1763 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
1764 break;
1765 case MADV_INVAL:
1767 * Invalidate the related pmap entries, used
1768 * to flush portions of the real kernel's
1769 * pmap when the caller has removed or
1770 * modified existing mappings in a virtual
1771 * page table.
1773 pmap_remove(map->pmap,
1774 current->start, current->end);
1775 break;
1776 case MADV_SETMAP:
1778 * Set the page directory page for a map
1779 * governed by a virtual page table. Mark
1780 * the entry as being governed by a virtual
1781 * page table if it is not.
1783 * XXX the page directory page is stored
1784 * in the avail_ssize field if the map_entry.
1786 * XXX the map simplification code does not
1787 * compare this field so weird things may
1788 * happen if you do not apply this function
1789 * to the entire mapping governed by the
1790 * virtual page table.
1792 if (current->maptype != VM_MAPTYPE_VPAGETABLE) {
1793 error = EINVAL;
1794 break;
1796 current->aux.master_pde = value;
1797 pmap_remove(map->pmap,
1798 current->start, current->end);
1799 break;
1800 default:
1801 error = EINVAL;
1802 break;
1804 vm_map_simplify_entry(map, current, &count);
1806 vm_map_unlock(map);
1807 } else {
1808 vm_pindex_t pindex;
1809 int count;
1812 * madvise behaviors that are implemented in the underlying
1813 * vm_object.
1815 * Since we don't clip the vm_map_entry, we have to clip
1816 * the vm_object pindex and count.
1818 * NOTE! We currently do not support these functions on
1819 * virtual page tables.
1821 for (current = entry;
1822 (current != &map->header) && (current->start < end);
1823 current = current->next
1825 vm_offset_t useStart;
1827 if (current->maptype != VM_MAPTYPE_NORMAL)
1828 continue;
1830 pindex = OFF_TO_IDX(current->offset);
1831 count = atop(current->end - current->start);
1832 useStart = current->start;
1834 if (current->start < start) {
1835 pindex += atop(start - current->start);
1836 count -= atop(start - current->start);
1837 useStart = start;
1839 if (current->end > end)
1840 count -= atop(current->end - end);
1842 if (count <= 0)
1843 continue;
1845 vm_object_madvise(current->object.vm_object,
1846 pindex, count, behav);
1849 * Try to populate the page table. Mappings governed
1850 * by virtual page tables cannot be pre-populated
1851 * without a lot of work so don't try.
1853 if (behav == MADV_WILLNEED &&
1854 current->maptype != VM_MAPTYPE_VPAGETABLE) {
1855 pmap_object_init_pt(
1856 map->pmap,
1857 useStart,
1858 current->protection,
1859 current->object.vm_object,
1860 pindex,
1861 (count << PAGE_SHIFT),
1862 MAP_PREFAULT_MADVISE
1866 vm_map_unlock_read(map);
1868 vm_map_entry_release(count);
1869 return(error);
1874 * vm_map_inherit:
1876 * Sets the inheritance of the specified address
1877 * range in the target map. Inheritance
1878 * affects how the map will be shared with
1879 * child maps at the time of vm_map_fork.
1882 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
1883 vm_inherit_t new_inheritance)
1885 vm_map_entry_t entry;
1886 vm_map_entry_t temp_entry;
1887 int count;
1889 switch (new_inheritance) {
1890 case VM_INHERIT_NONE:
1891 case VM_INHERIT_COPY:
1892 case VM_INHERIT_SHARE:
1893 break;
1894 default:
1895 return (KERN_INVALID_ARGUMENT);
1898 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1899 vm_map_lock(map);
1901 VM_MAP_RANGE_CHECK(map, start, end);
1903 if (vm_map_lookup_entry(map, start, &temp_entry)) {
1904 entry = temp_entry;
1905 vm_map_clip_start(map, entry, start, &count);
1906 } else
1907 entry = temp_entry->next;
1909 while ((entry != &map->header) && (entry->start < end)) {
1910 vm_map_clip_end(map, entry, end, &count);
1912 entry->inheritance = new_inheritance;
1914 vm_map_simplify_entry(map, entry, &count);
1916 entry = entry->next;
1918 vm_map_unlock(map);
1919 vm_map_entry_release(count);
1920 return (KERN_SUCCESS);
1924 * Implement the semantics of mlock
1927 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t real_end,
1928 boolean_t new_pageable)
1930 vm_map_entry_t entry;
1931 vm_map_entry_t start_entry;
1932 vm_offset_t end;
1933 int rv = KERN_SUCCESS;
1934 int count;
1936 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1937 vm_map_lock(map);
1938 VM_MAP_RANGE_CHECK(map, start, real_end);
1939 end = real_end;
1941 start_entry = vm_map_clip_range(map, start, end, &count, MAP_CLIP_NO_HOLES);
1942 if (start_entry == NULL) {
1943 vm_map_unlock(map);
1944 vm_map_entry_release(count);
1945 return (KERN_INVALID_ADDRESS);
1948 if (new_pageable == 0) {
1949 entry = start_entry;
1950 while ((entry != &map->header) && (entry->start < end)) {
1951 vm_offset_t save_start;
1952 vm_offset_t save_end;
1955 * Already user wired or hard wired (trivial cases)
1957 if (entry->eflags & MAP_ENTRY_USER_WIRED) {
1958 entry = entry->next;
1959 continue;
1961 if (entry->wired_count != 0) {
1962 entry->wired_count++;
1963 entry->eflags |= MAP_ENTRY_USER_WIRED;
1964 entry = entry->next;
1965 continue;
1969 * A new wiring requires instantiation of appropriate
1970 * management structures and the faulting in of the
1971 * page.
1973 if (entry->maptype != VM_MAPTYPE_SUBMAP) {
1974 int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
1975 if (copyflag && ((entry->protection & VM_PROT_WRITE) != 0)) {
1976 vm_map_entry_shadow(entry);
1977 } else if (entry->object.vm_object == NULL &&
1978 !map->system_map) {
1979 vm_map_entry_allocate_object(entry);
1982 entry->wired_count++;
1983 entry->eflags |= MAP_ENTRY_USER_WIRED;
1986 * Now fault in the area. Note that vm_fault_wire()
1987 * may release the map lock temporarily, it will be
1988 * relocked on return. The in-transition
1989 * flag protects the entries.
1991 save_start = entry->start;
1992 save_end = entry->end;
1993 rv = vm_fault_wire(map, entry, TRUE);
1994 if (rv) {
1995 CLIP_CHECK_BACK(entry, save_start);
1996 for (;;) {
1997 KASSERT(entry->wired_count == 1, ("bad wired_count on entry"));
1998 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1999 entry->wired_count = 0;
2000 if (entry->end == save_end)
2001 break;
2002 entry = entry->next;
2003 KASSERT(entry != &map->header, ("bad entry clip during backout"));
2005 end = save_start; /* unwire the rest */
2006 break;
2009 * note that even though the entry might have been
2010 * clipped, the USER_WIRED flag we set prevents
2011 * duplication so we do not have to do a
2012 * clip check.
2014 entry = entry->next;
2018 * If we failed fall through to the unwiring section to
2019 * unwire what we had wired so far. 'end' has already
2020 * been adjusted.
2022 if (rv)
2023 new_pageable = 1;
2026 * start_entry might have been clipped if we unlocked the
2027 * map and blocked. No matter how clipped it has gotten
2028 * there should be a fragment that is on our start boundary.
2030 CLIP_CHECK_BACK(start_entry, start);
2034 * Deal with the unwiring case.
2036 if (new_pageable) {
2038 * This is the unwiring case. We must first ensure that the
2039 * range to be unwired is really wired down. We know there
2040 * are no holes.
2042 entry = start_entry;
2043 while ((entry != &map->header) && (entry->start < end)) {
2044 if ((entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2045 rv = KERN_INVALID_ARGUMENT;
2046 goto done;
2048 KASSERT(entry->wired_count != 0, ("wired count was 0 with USER_WIRED set! %p", entry));
2049 entry = entry->next;
2053 * Now decrement the wiring count for each region. If a region
2054 * becomes completely unwired, unwire its physical pages and
2055 * mappings.
2058 * The map entries are processed in a loop, checking to
2059 * make sure the entry is wired and asserting it has a wired
2060 * count. However, another loop was inserted more-or-less in
2061 * the middle of the unwiring path. This loop picks up the
2062 * "entry" loop variable from the first loop without first
2063 * setting it to start_entry. Naturally, the secound loop
2064 * is never entered and the pages backing the entries are
2065 * never unwired. This can lead to a leak of wired pages.
2067 entry = start_entry;
2068 while ((entry != &map->header) && (entry->start < end)) {
2069 KASSERT(entry->eflags & MAP_ENTRY_USER_WIRED,
2070 ("expected USER_WIRED on entry %p", entry));
2071 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2072 entry->wired_count--;
2073 if (entry->wired_count == 0)
2074 vm_fault_unwire(map, entry);
2075 entry = entry->next;
2078 done:
2079 vm_map_unclip_range(map, start_entry, start, real_end, &count,
2080 MAP_CLIP_NO_HOLES);
2081 map->timestamp++;
2082 vm_map_unlock(map);
2083 vm_map_entry_release(count);
2084 return (rv);
2088 * vm_map_wire:
2090 * Sets the pageability of the specified address
2091 * range in the target map. Regions specified
2092 * as not pageable require locked-down physical
2093 * memory and physical page maps.
2095 * The map must not be locked, but a reference
2096 * must remain to the map throughout the call.
2098 * This function may be called via the zalloc path and must properly
2099 * reserve map entries for kernel_map.
2102 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t real_end, int kmflags)
2104 vm_map_entry_t entry;
2105 vm_map_entry_t start_entry;
2106 vm_offset_t end;
2107 int rv = KERN_SUCCESS;
2108 int count;
2110 if (kmflags & KM_KRESERVE)
2111 count = vm_map_entry_kreserve(MAP_RESERVE_COUNT);
2112 else
2113 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2114 vm_map_lock(map);
2115 VM_MAP_RANGE_CHECK(map, start, real_end);
2116 end = real_end;
2118 start_entry = vm_map_clip_range(map, start, end, &count, MAP_CLIP_NO_HOLES);
2119 if (start_entry == NULL) {
2120 vm_map_unlock(map);
2121 rv = KERN_INVALID_ADDRESS;
2122 goto failure;
2124 if ((kmflags & KM_PAGEABLE) == 0) {
2126 * Wiring.
2128 * 1. Holding the write lock, we create any shadow or zero-fill
2129 * objects that need to be created. Then we clip each map
2130 * entry to the region to be wired and increment its wiring
2131 * count. We create objects before clipping the map entries
2132 * to avoid object proliferation.
2134 * 2. We downgrade to a read lock, and call vm_fault_wire to
2135 * fault in the pages for any newly wired area (wired_count is
2136 * 1).
2138 * Downgrading to a read lock for vm_fault_wire avoids a
2139 * possible deadlock with another process that may have faulted
2140 * on one of the pages to be wired (it would mark the page busy,
2141 * blocking us, then in turn block on the map lock that we
2142 * hold). Because of problems in the recursive lock package,
2143 * we cannot upgrade to a write lock in vm_map_lookup. Thus,
2144 * any actions that require the write lock must be done
2145 * beforehand. Because we keep the read lock on the map, the
2146 * copy-on-write status of the entries we modify here cannot
2147 * change.
2150 entry = start_entry;
2151 while ((entry != &map->header) && (entry->start < end)) {
2153 * Trivial case if the entry is already wired
2155 if (entry->wired_count) {
2156 entry->wired_count++;
2157 entry = entry->next;
2158 continue;
2162 * The entry is being newly wired, we have to setup
2163 * appropriate management structures. A shadow
2164 * object is required for a copy-on-write region,
2165 * or a normal object for a zero-fill region. We
2166 * do not have to do this for entries that point to sub
2167 * maps because we won't hold the lock on the sub map.
2169 if (entry->maptype != VM_MAPTYPE_SUBMAP) {
2170 int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
2171 if (copyflag &&
2172 ((entry->protection & VM_PROT_WRITE) != 0)) {
2173 vm_map_entry_shadow(entry);
2174 } else if (entry->object.vm_object == NULL &&
2175 !map->system_map) {
2176 vm_map_entry_allocate_object(entry);
2180 entry->wired_count++;
2181 entry = entry->next;
2185 * Pass 2.
2189 * HACK HACK HACK HACK
2191 * Unlock the map to avoid deadlocks. The in-transit flag
2192 * protects us from most changes but note that
2193 * clipping may still occur. To prevent clipping from
2194 * occuring after the unlock, except for when we are
2195 * blocking in vm_fault_wire, we must run in a critical
2196 * section, otherwise our accesses to entry->start and
2197 * entry->end could be corrupted. We have to enter the
2198 * critical section prior to unlocking so start_entry does
2199 * not change out from under us at the very beginning of the
2200 * loop.
2202 * HACK HACK HACK HACK
2205 crit_enter();
2207 entry = start_entry;
2208 while (entry != &map->header && entry->start < end) {
2210 * If vm_fault_wire fails for any page we need to undo
2211 * what has been done. We decrement the wiring count
2212 * for those pages which have not yet been wired (now)
2213 * and unwire those that have (later).
2215 vm_offset_t save_start = entry->start;
2216 vm_offset_t save_end = entry->end;
2218 if (entry->wired_count == 1)
2219 rv = vm_fault_wire(map, entry, FALSE);
2220 if (rv) {
2221 CLIP_CHECK_BACK(entry, save_start);
2222 for (;;) {
2223 KASSERT(entry->wired_count == 1, ("wired_count changed unexpectedly"));
2224 entry->wired_count = 0;
2225 if (entry->end == save_end)
2226 break;
2227 entry = entry->next;
2228 KASSERT(entry != &map->header, ("bad entry clip during backout"));
2230 end = save_start;
2231 break;
2233 CLIP_CHECK_FWD(entry, save_end);
2234 entry = entry->next;
2236 crit_exit();
2239 * If a failure occured undo everything by falling through
2240 * to the unwiring code. 'end' has already been adjusted
2241 * appropriately.
2243 if (rv)
2244 kmflags |= KM_PAGEABLE;
2247 * start_entry is still IN_TRANSITION but may have been
2248 * clipped since vm_fault_wire() unlocks and relocks the
2249 * map. No matter how clipped it has gotten there should
2250 * be a fragment that is on our start boundary.
2252 CLIP_CHECK_BACK(start_entry, start);
2255 if (kmflags & KM_PAGEABLE) {
2257 * This is the unwiring case. We must first ensure that the
2258 * range to be unwired is really wired down. We know there
2259 * are no holes.
2261 entry = start_entry;
2262 while ((entry != &map->header) && (entry->start < end)) {
2263 if (entry->wired_count == 0) {
2264 rv = KERN_INVALID_ARGUMENT;
2265 goto done;
2267 entry = entry->next;
2271 * Now decrement the wiring count for each region. If a region
2272 * becomes completely unwired, unwire its physical pages and
2273 * mappings.
2275 entry = start_entry;
2276 while ((entry != &map->header) && (entry->start < end)) {
2277 entry->wired_count--;
2278 if (entry->wired_count == 0)
2279 vm_fault_unwire(map, entry);
2280 entry = entry->next;
2283 done:
2284 vm_map_unclip_range(map, start_entry, start, real_end, &count,
2285 MAP_CLIP_NO_HOLES);
2286 map->timestamp++;
2287 vm_map_unlock(map);
2288 failure:
2289 if (kmflags & KM_KRESERVE)
2290 vm_map_entry_krelease(count);
2291 else
2292 vm_map_entry_release(count);
2293 return (rv);
2297 * vm_map_set_wired_quick()
2299 * Mark a newly allocated address range as wired but do not fault in
2300 * the pages. The caller is expected to load the pages into the object.
2302 * The map must be locked on entry and will remain locked on return.
2304 void
2305 vm_map_set_wired_quick(vm_map_t map, vm_offset_t addr, vm_size_t size, int *countp)
2307 vm_map_entry_t scan;
2308 vm_map_entry_t entry;
2310 entry = vm_map_clip_range(map, addr, addr + size, countp, MAP_CLIP_NO_HOLES);
2311 for (scan = entry; scan != &map->header && scan->start < addr + size; scan = scan->next) {
2312 KKASSERT(entry->wired_count == 0);
2313 entry->wired_count = 1;
2315 vm_map_unclip_range(map, entry, addr, addr + size, countp, MAP_CLIP_NO_HOLES);
2319 * vm_map_clean
2321 * Push any dirty cached pages in the address range to their pager.
2322 * If syncio is TRUE, dirty pages are written synchronously.
2323 * If invalidate is TRUE, any cached pages are freed as well.
2325 * Returns an error if any part of the specified range is not mapped.
2328 vm_map_clean(vm_map_t map, vm_offset_t start, vm_offset_t end, boolean_t syncio,
2329 boolean_t invalidate)
2331 vm_map_entry_t current;
2332 vm_map_entry_t entry;
2333 vm_size_t size;
2334 vm_object_t object;
2335 vm_ooffset_t offset;
2337 vm_map_lock_read(map);
2338 VM_MAP_RANGE_CHECK(map, start, end);
2339 if (!vm_map_lookup_entry(map, start, &entry)) {
2340 vm_map_unlock_read(map);
2341 return (KERN_INVALID_ADDRESS);
2344 * Make a first pass to check for holes.
2346 for (current = entry; current->start < end; current = current->next) {
2347 if (current->maptype == VM_MAPTYPE_SUBMAP) {
2348 vm_map_unlock_read(map);
2349 return (KERN_INVALID_ARGUMENT);
2351 if (end > current->end &&
2352 (current->next == &map->header ||
2353 current->end != current->next->start)) {
2354 vm_map_unlock_read(map);
2355 return (KERN_INVALID_ADDRESS);
2359 if (invalidate)
2360 pmap_remove(vm_map_pmap(map), start, end);
2362 * Make a second pass, cleaning/uncaching pages from the indicated
2363 * objects as we go.
2365 for (current = entry; current->start < end; current = current->next) {
2366 offset = current->offset + (start - current->start);
2367 size = (end <= current->end ? end : current->end) - start;
2368 if (current->maptype == VM_MAPTYPE_SUBMAP) {
2369 vm_map_t smap;
2370 vm_map_entry_t tentry;
2371 vm_size_t tsize;
2373 smap = current->object.sub_map;
2374 vm_map_lock_read(smap);
2375 vm_map_lookup_entry(smap, offset, &tentry);
2376 tsize = tentry->end - offset;
2377 if (tsize < size)
2378 size = tsize;
2379 object = tentry->object.vm_object;
2380 offset = tentry->offset + (offset - tentry->start);
2381 vm_map_unlock_read(smap);
2382 } else {
2383 object = current->object.vm_object;
2386 * Note that there is absolutely no sense in writing out
2387 * anonymous objects, so we track down the vnode object
2388 * to write out.
2389 * We invalidate (remove) all pages from the address space
2390 * anyway, for semantic correctness.
2392 * note: certain anonymous maps, such as MAP_NOSYNC maps,
2393 * may start out with a NULL object.
2395 while (object && object->backing_object) {
2396 offset += object->backing_object_offset;
2397 object = object->backing_object;
2398 if (object->size < OFF_TO_IDX( offset + size))
2399 size = IDX_TO_OFF(object->size) - offset;
2401 if (object && (object->type == OBJT_VNODE) &&
2402 (current->protection & VM_PROT_WRITE)) {
2404 * Flush pages if writing is allowed, invalidate them
2405 * if invalidation requested. Pages undergoing I/O
2406 * will be ignored by vm_object_page_remove().
2408 * We cannot lock the vnode and then wait for paging
2409 * to complete without deadlocking against vm_fault.
2410 * Instead we simply call vm_object_page_remove() and
2411 * allow it to block internally on a page-by-page
2412 * basis when it encounters pages undergoing async
2413 * I/O.
2415 int flags;
2417 vm_object_reference(object);
2418 vn_lock(object->handle, LK_EXCLUSIVE | LK_RETRY);
2419 flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
2420 flags |= invalidate ? OBJPC_INVAL : 0;
2423 * When operating on a virtual page table just
2424 * flush the whole object. XXX we probably ought
2425 * to
2427 switch(current->maptype) {
2428 case VM_MAPTYPE_NORMAL:
2429 vm_object_page_clean(object,
2430 OFF_TO_IDX(offset),
2431 OFF_TO_IDX(offset + size + PAGE_MASK),
2432 flags);
2433 break;
2434 case VM_MAPTYPE_VPAGETABLE:
2435 vm_object_page_clean(object, 0, 0, flags);
2436 break;
2438 vn_unlock(((struct vnode *)object->handle));
2439 vm_object_deallocate(object);
2441 if (object && invalidate &&
2442 ((object->type == OBJT_VNODE) ||
2443 (object->type == OBJT_DEVICE))) {
2444 int clean_only =
2445 (object->type == OBJT_DEVICE) ? FALSE : TRUE;
2446 vm_object_reference(object);
2447 switch(current->maptype) {
2448 case VM_MAPTYPE_NORMAL:
2449 vm_object_page_remove(object,
2450 OFF_TO_IDX(offset),
2451 OFF_TO_IDX(offset + size + PAGE_MASK),
2452 clean_only);
2453 break;
2454 case VM_MAPTYPE_VPAGETABLE:
2455 vm_object_page_remove(object, 0, 0, clean_only);
2456 break;
2458 vm_object_deallocate(object);
2460 start += size;
2463 vm_map_unlock_read(map);
2464 return (KERN_SUCCESS);
2468 * vm_map_entry_unwire: [ internal use only ]
2470 * Make the region specified by this entry pageable.
2472 * The map in question should be locked.
2473 * [This is the reason for this routine's existence.]
2475 static void
2476 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2478 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2479 entry->wired_count = 0;
2480 vm_fault_unwire(map, entry);
2484 * vm_map_entry_delete: [ internal use only ]
2486 * Deallocate the given entry from the target map.
2488 static void
2489 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry, int *countp)
2491 vm_map_entry_unlink(map, entry);
2492 map->size -= entry->end - entry->start;
2494 switch(entry->maptype) {
2495 case VM_MAPTYPE_NORMAL:
2496 case VM_MAPTYPE_VPAGETABLE:
2497 vm_object_deallocate(entry->object.vm_object);
2498 break;
2499 default:
2500 break;
2503 vm_map_entry_dispose(map, entry, countp);
2507 * vm_map_delete: [ internal use only ]
2509 * Deallocates the given address range from the target
2510 * map.
2513 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end, int *countp)
2515 vm_object_t object;
2516 vm_map_entry_t entry;
2517 vm_map_entry_t first_entry;
2519 again:
2521 * Find the start of the region, and clip it. Set entry to point
2522 * at the first record containing the requested address or, if no
2523 * such record exists, the next record with a greater address. The
2524 * loop will run from this point until a record beyond the termination
2525 * address is encountered.
2527 * map->hint must be adjusted to not point to anything we delete,
2528 * so set it to the entry prior to the one being deleted.
2530 * GGG see other GGG comment.
2532 if (vm_map_lookup_entry(map, start, &first_entry)) {
2533 entry = first_entry;
2534 vm_map_clip_start(map, entry, start, countp);
2535 map->hint = entry->prev; /* possible problem XXX */
2536 } else {
2537 map->hint = first_entry; /* possible problem XXX */
2538 entry = first_entry->next;
2542 * If a hole opens up prior to the current first_free then
2543 * adjust first_free. As with map->hint, map->first_free
2544 * cannot be left set to anything we might delete.
2546 if (entry == &map->header) {
2547 map->first_free = &map->header;
2548 } else if (map->first_free->start >= start) {
2549 map->first_free = entry->prev;
2553 * Step through all entries in this region
2556 while ((entry != &map->header) && (entry->start < end)) {
2557 vm_map_entry_t next;
2558 vm_offset_t s, e;
2559 vm_pindex_t offidxstart, offidxend, count;
2562 * If we hit an in-transition entry we have to sleep and
2563 * retry. It's easier (and not really slower) to just retry
2564 * since this case occurs so rarely and the hint is already
2565 * pointing at the right place. We have to reset the
2566 * start offset so as not to accidently delete an entry
2567 * another process just created in vacated space.
2569 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2570 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2571 start = entry->start;
2572 ++mycpu->gd_cnt.v_intrans_coll;
2573 ++mycpu->gd_cnt.v_intrans_wait;
2574 vm_map_transition_wait(map);
2575 goto again;
2577 vm_map_clip_end(map, entry, end, countp);
2579 s = entry->start;
2580 e = entry->end;
2581 next = entry->next;
2583 offidxstart = OFF_TO_IDX(entry->offset);
2584 count = OFF_TO_IDX(e - s);
2585 object = entry->object.vm_object;
2588 * Unwire before removing addresses from the pmap; otherwise,
2589 * unwiring will put the entries back in the pmap.
2591 if (entry->wired_count != 0)
2592 vm_map_entry_unwire(map, entry);
2594 offidxend = offidxstart + count;
2596 if (object == &kernel_object) {
2597 vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2598 } else {
2599 pmap_remove(map->pmap, s, e);
2600 if (object != NULL &&
2601 object->ref_count != 1 &&
2602 (object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING &&
2603 (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2604 vm_object_collapse(object);
2605 vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2606 if (object->type == OBJT_SWAP) {
2607 swap_pager_freespace(object, offidxstart, count);
2609 if (offidxend >= object->size &&
2610 offidxstart < object->size) {
2611 object->size = offidxstart;
2617 * Delete the entry (which may delete the object) only after
2618 * removing all pmap entries pointing to its pages.
2619 * (Otherwise, its page frames may be reallocated, and any
2620 * modify bits will be set in the wrong object!)
2622 vm_map_entry_delete(map, entry, countp);
2623 entry = next;
2625 return (KERN_SUCCESS);
2629 * vm_map_remove:
2631 * Remove the given address range from the target map.
2632 * This is the exported form of vm_map_delete.
2635 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2637 int result;
2638 int count;
2640 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2641 vm_map_lock(map);
2642 VM_MAP_RANGE_CHECK(map, start, end);
2643 result = vm_map_delete(map, start, end, &count);
2644 vm_map_unlock(map);
2645 vm_map_entry_release(count);
2647 return (result);
2651 * vm_map_check_protection:
2653 * Assert that the target map allows the specified
2654 * privilege on the entire address region given.
2655 * The entire region must be allocated.
2657 boolean_t
2658 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2659 vm_prot_t protection)
2661 vm_map_entry_t entry;
2662 vm_map_entry_t tmp_entry;
2664 if (!vm_map_lookup_entry(map, start, &tmp_entry)) {
2665 return (FALSE);
2667 entry = tmp_entry;
2669 while (start < end) {
2670 if (entry == &map->header) {
2671 return (FALSE);
2674 * No holes allowed!
2677 if (start < entry->start) {
2678 return (FALSE);
2681 * Check protection associated with entry.
2684 if ((entry->protection & protection) != protection) {
2685 return (FALSE);
2687 /* go to next entry */
2689 start = entry->end;
2690 entry = entry->next;
2692 return (TRUE);
2696 * Split the pages in a map entry into a new object. This affords
2697 * easier removal of unused pages, and keeps object inheritance from
2698 * being a negative impact on memory usage.
2700 static void
2701 vm_map_split(vm_map_entry_t entry)
2703 vm_page_t m;
2704 vm_object_t orig_object, new_object, source;
2705 vm_offset_t s, e;
2706 vm_pindex_t offidxstart, offidxend, idx;
2707 vm_size_t size;
2708 vm_ooffset_t offset;
2710 orig_object = entry->object.vm_object;
2711 if (orig_object->type != OBJT_DEFAULT && orig_object->type != OBJT_SWAP)
2712 return;
2713 if (orig_object->ref_count <= 1)
2714 return;
2716 offset = entry->offset;
2717 s = entry->start;
2718 e = entry->end;
2720 offidxstart = OFF_TO_IDX(offset);
2721 offidxend = offidxstart + OFF_TO_IDX(e - s);
2722 size = offidxend - offidxstart;
2724 new_object = vm_pager_allocate(orig_object->type, NULL,
2725 IDX_TO_OFF(size), VM_PROT_ALL, 0);
2726 if (new_object == NULL)
2727 return;
2729 source = orig_object->backing_object;
2730 if (source != NULL) {
2731 vm_object_reference(source); /* Referenced by new_object */
2732 LIST_INSERT_HEAD(&source->shadow_head,
2733 new_object, shadow_list);
2734 vm_object_clear_flag(source, OBJ_ONEMAPPING);
2735 new_object->backing_object_offset =
2736 orig_object->backing_object_offset + IDX_TO_OFF(offidxstart);
2737 new_object->backing_object = source;
2738 source->shadow_count++;
2739 source->generation++;
2742 for (idx = 0; idx < size; idx++) {
2743 vm_page_t m;
2746 * A critical section is required to avoid a race between
2747 * the lookup and an interrupt/unbusy/free and our busy
2748 * check.
2750 crit_enter();
2751 retry:
2752 m = vm_page_lookup(orig_object, offidxstart + idx);
2753 if (m == NULL) {
2754 crit_exit();
2755 continue;
2759 * We must wait for pending I/O to complete before we can
2760 * rename the page.
2762 * We do not have to VM_PROT_NONE the page as mappings should
2763 * not be changed by this operation.
2765 if (vm_page_sleep_busy(m, TRUE, "spltwt"))
2766 goto retry;
2767 vm_page_busy(m);
2768 vm_page_rename(m, new_object, idx);
2769 /* page automatically made dirty by rename and cache handled */
2770 vm_page_busy(m);
2771 crit_exit();
2774 if (orig_object->type == OBJT_SWAP) {
2775 vm_object_pip_add(orig_object, 1);
2777 * copy orig_object pages into new_object
2778 * and destroy unneeded pages in
2779 * shadow object.
2781 swap_pager_copy(orig_object, new_object, offidxstart, 0);
2782 vm_object_pip_wakeup(orig_object);
2786 * Wakeup the pages we played with. No spl protection is needed
2787 * for a simple wakeup.
2789 for (idx = 0; idx < size; idx++) {
2790 m = vm_page_lookup(new_object, idx);
2791 if (m)
2792 vm_page_wakeup(m);
2795 entry->object.vm_object = new_object;
2796 entry->offset = 0LL;
2797 vm_object_deallocate(orig_object);
2801 * vm_map_copy_entry:
2803 * Copies the contents of the source entry to the destination
2804 * entry. The entries *must* be aligned properly.
2806 static void
2807 vm_map_copy_entry(vm_map_t src_map, vm_map_t dst_map,
2808 vm_map_entry_t src_entry, vm_map_entry_t dst_entry)
2810 vm_object_t src_object;
2812 if (dst_entry->maptype == VM_MAPTYPE_SUBMAP)
2813 return;
2814 if (src_entry->maptype == VM_MAPTYPE_SUBMAP)
2815 return;
2817 if (src_entry->wired_count == 0) {
2819 * If the source entry is marked needs_copy, it is already
2820 * write-protected.
2822 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2823 pmap_protect(src_map->pmap,
2824 src_entry->start,
2825 src_entry->end,
2826 src_entry->protection & ~VM_PROT_WRITE);
2830 * Make a copy of the object.
2832 if ((src_object = src_entry->object.vm_object) != NULL) {
2833 if ((src_object->handle == NULL) &&
2834 (src_object->type == OBJT_DEFAULT ||
2835 src_object->type == OBJT_SWAP)) {
2836 vm_object_collapse(src_object);
2837 if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
2838 vm_map_split(src_entry);
2839 src_object = src_entry->object.vm_object;
2843 vm_object_reference(src_object);
2844 vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2845 dst_entry->object.vm_object = src_object;
2846 src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2847 dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2848 dst_entry->offset = src_entry->offset;
2849 } else {
2850 dst_entry->object.vm_object = NULL;
2851 dst_entry->offset = 0;
2854 pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
2855 dst_entry->end - dst_entry->start, src_entry->start);
2856 } else {
2858 * Of course, wired down pages can't be set copy-on-write.
2859 * Cause wired pages to be copied into the new map by
2860 * simulating faults (the new pages are pageable)
2862 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
2867 * vmspace_fork:
2868 * Create a new process vmspace structure and vm_map
2869 * based on those of an existing process. The new map
2870 * is based on the old map, according to the inheritance
2871 * values on the regions in that map.
2873 * The source map must not be locked.
2875 struct vmspace *
2876 vmspace_fork(struct vmspace *vm1)
2878 struct vmspace *vm2;
2879 vm_map_t old_map = &vm1->vm_map;
2880 vm_map_t new_map;
2881 vm_map_entry_t old_entry;
2882 vm_map_entry_t new_entry;
2883 vm_object_t object;
2884 int count;
2886 vm_map_lock(old_map);
2887 old_map->infork = 1;
2890 * XXX Note: upcalls are not copied.
2892 vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
2893 bcopy(&vm1->vm_startcopy, &vm2->vm_startcopy,
2894 (caddr_t)&vm1->vm_endcopy - (caddr_t)&vm1->vm_startcopy);
2895 new_map = &vm2->vm_map; /* XXX */
2896 new_map->timestamp = 1;
2898 count = 0;
2899 old_entry = old_map->header.next;
2900 while (old_entry != &old_map->header) {
2901 ++count;
2902 old_entry = old_entry->next;
2905 count = vm_map_entry_reserve(count + MAP_RESERVE_COUNT);
2907 old_entry = old_map->header.next;
2908 while (old_entry != &old_map->header) {
2909 if (old_entry->maptype == VM_MAPTYPE_SUBMAP)
2910 panic("vm_map_fork: encountered a submap");
2912 switch (old_entry->inheritance) {
2913 case VM_INHERIT_NONE:
2914 break;
2916 case VM_INHERIT_SHARE:
2918 * Clone the entry, creating the shared object if
2919 * necessary.
2921 object = old_entry->object.vm_object;
2922 if (object == NULL) {
2923 vm_map_entry_allocate_object(old_entry);
2924 object = old_entry->object.vm_object;
2928 * Add the reference before calling vm_map_entry_shadow
2929 * to insure that a shadow object is created.
2931 vm_object_reference(object);
2932 if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2933 vm_map_entry_shadow(old_entry);
2934 /* Transfer the second reference too. */
2935 vm_object_reference(
2936 old_entry->object.vm_object);
2937 vm_object_deallocate(object);
2938 object = old_entry->object.vm_object;
2940 vm_object_clear_flag(object, OBJ_ONEMAPPING);
2943 * Clone the entry, referencing the shared object.
2945 new_entry = vm_map_entry_create(new_map, &count);
2946 *new_entry = *old_entry;
2947 new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2948 new_entry->wired_count = 0;
2951 * Insert the entry into the new map -- we know we're
2952 * inserting at the end of the new map.
2955 vm_map_entry_link(new_map, new_map->header.prev,
2956 new_entry);
2959 * Update the physical map
2962 pmap_copy(new_map->pmap, old_map->pmap,
2963 new_entry->start,
2964 (old_entry->end - old_entry->start),
2965 old_entry->start);
2966 break;
2968 case VM_INHERIT_COPY:
2970 * Clone the entry and link into the map.
2972 new_entry = vm_map_entry_create(new_map, &count);
2973 *new_entry = *old_entry;
2974 new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2975 new_entry->wired_count = 0;
2976 new_entry->object.vm_object = NULL;
2977 vm_map_entry_link(new_map, new_map->header.prev,
2978 new_entry);
2979 vm_map_copy_entry(old_map, new_map, old_entry,
2980 new_entry);
2981 break;
2983 old_entry = old_entry->next;
2986 new_map->size = old_map->size;
2987 old_map->infork = 0;
2988 vm_map_unlock(old_map);
2989 vm_map_entry_release(count);
2991 return (vm2);
2995 vm_map_stack (vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
2996 boolean_t fitit, vm_prot_t prot, vm_prot_t max, int cow)
2998 vm_map_entry_t prev_entry;
2999 vm_map_entry_t new_stack_entry;
3000 vm_size_t init_ssize;
3001 int rv;
3002 int count;
3003 vm_offset_t tmpaddr;
3006 * XXX cleanup cruft
3008 if (VM_MIN_USER_ADDRESS > 0 &&
3009 fitit == FALSE &&
3010 addrbos < VM_MIN_USER_ADDRESS) {
3011 return (KERN_NO_SPACE);
3014 if (max_ssize < sgrowsiz)
3015 init_ssize = max_ssize;
3016 else
3017 init_ssize = sgrowsiz;
3019 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
3020 vm_map_lock(map);
3023 * Find space for the mapping
3025 if (fitit) {
3026 if (vm_map_findspace(map, addrbos, max_ssize, 1, &tmpaddr)) {
3027 vm_map_unlock(map);
3028 vm_map_entry_release(count);
3029 return (KERN_NO_SPACE);
3031 addrbos = tmpaddr;
3034 /* If addr is already mapped, no go */
3035 if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
3036 vm_map_unlock(map);
3037 vm_map_entry_release(count);
3038 return (KERN_NO_SPACE);
3041 #if 0
3042 /* XXX already handled by kern_mmap() */
3043 /* If we would blow our VMEM resource limit, no go */
3044 if (map->size + init_ssize >
3045 curproc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
3046 vm_map_unlock(map);
3047 vm_map_entry_release(count);
3048 return (KERN_NO_SPACE);
3050 #endif
3053 * If we can't accomodate max_ssize in the current mapping,
3054 * no go. However, we need to be aware that subsequent user
3055 * mappings might map into the space we have reserved for
3056 * stack, and currently this space is not protected.
3058 * Hopefully we will at least detect this condition
3059 * when we try to grow the stack.
3061 if ((prev_entry->next != &map->header) &&
3062 (prev_entry->next->start < addrbos + max_ssize)) {
3063 vm_map_unlock(map);
3064 vm_map_entry_release(count);
3065 return (KERN_NO_SPACE);
3069 * We initially map a stack of only init_ssize. We will
3070 * grow as needed later. Since this is to be a grow
3071 * down stack, we map at the top of the range.
3073 * Note: we would normally expect prot and max to be
3074 * VM_PROT_ALL, and cow to be 0. Possibly we should
3075 * eliminate these as input parameters, and just
3076 * pass these values here in the insert call.
3078 rv = vm_map_insert(map, &count,
3079 NULL, 0, addrbos + max_ssize - init_ssize,
3080 addrbos + max_ssize,
3081 VM_MAPTYPE_NORMAL,
3082 prot, max,
3083 cow);
3085 /* Now set the avail_ssize amount */
3086 if (rv == KERN_SUCCESS) {
3087 if (prev_entry != &map->header)
3088 vm_map_clip_end(map, prev_entry, addrbos + max_ssize - init_ssize, &count);
3089 new_stack_entry = prev_entry->next;
3090 if (new_stack_entry->end != addrbos + max_ssize ||
3091 new_stack_entry->start != addrbos + max_ssize - init_ssize)
3092 panic ("Bad entry start/end for new stack entry");
3093 else
3094 new_stack_entry->aux.avail_ssize = max_ssize - init_ssize;
3097 vm_map_unlock(map);
3098 vm_map_entry_release(count);
3099 return (rv);
3102 /* Attempts to grow a vm stack entry. Returns KERN_SUCCESS if the
3103 * desired address is already mapped, or if we successfully grow
3104 * the stack. Also returns KERN_SUCCESS if addr is outside the
3105 * stack range (this is strange, but preserves compatibility with
3106 * the grow function in vm_machdep.c).
3109 vm_map_growstack (struct proc *p, vm_offset_t addr)
3111 vm_map_entry_t prev_entry;
3112 vm_map_entry_t stack_entry;
3113 vm_map_entry_t new_stack_entry;
3114 struct vmspace *vm = p->p_vmspace;
3115 vm_map_t map = &vm->vm_map;
3116 vm_offset_t end;
3117 int grow_amount;
3118 int rv = KERN_SUCCESS;
3119 int is_procstack;
3120 int use_read_lock = 1;
3121 int count;
3123 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
3124 Retry:
3125 if (use_read_lock)
3126 vm_map_lock_read(map);
3127 else
3128 vm_map_lock(map);
3130 /* If addr is already in the entry range, no need to grow.*/
3131 if (vm_map_lookup_entry(map, addr, &prev_entry))
3132 goto done;
3134 if ((stack_entry = prev_entry->next) == &map->header)
3135 goto done;
3136 if (prev_entry == &map->header)
3137 end = stack_entry->start - stack_entry->aux.avail_ssize;
3138 else
3139 end = prev_entry->end;
3141 /* This next test mimics the old grow function in vm_machdep.c.
3142 * It really doesn't quite make sense, but we do it anyway
3143 * for compatibility.
3145 * If not growable stack, return success. This signals the
3146 * caller to proceed as he would normally with normal vm.
3148 if (stack_entry->aux.avail_ssize < 1 ||
3149 addr >= stack_entry->start ||
3150 addr < stack_entry->start - stack_entry->aux.avail_ssize) {
3151 goto done;
3154 /* Find the minimum grow amount */
3155 grow_amount = roundup (stack_entry->start - addr, PAGE_SIZE);
3156 if (grow_amount > stack_entry->aux.avail_ssize) {
3157 rv = KERN_NO_SPACE;
3158 goto done;
3161 /* If there is no longer enough space between the entries
3162 * nogo, and adjust the available space. Note: this
3163 * should only happen if the user has mapped into the
3164 * stack area after the stack was created, and is
3165 * probably an error.
3167 * This also effectively destroys any guard page the user
3168 * might have intended by limiting the stack size.
3170 if (grow_amount > stack_entry->start - end) {
3171 if (use_read_lock && vm_map_lock_upgrade(map)) {
3172 use_read_lock = 0;
3173 goto Retry;
3175 use_read_lock = 0;
3176 stack_entry->aux.avail_ssize = stack_entry->start - end;
3177 rv = KERN_NO_SPACE;
3178 goto done;
3181 is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr;
3183 /* If this is the main process stack, see if we're over the
3184 * stack limit.
3186 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
3187 p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
3188 rv = KERN_NO_SPACE;
3189 goto done;
3192 /* Round up the grow amount modulo SGROWSIZ */
3193 grow_amount = roundup (grow_amount, sgrowsiz);
3194 if (grow_amount > stack_entry->aux.avail_ssize) {
3195 grow_amount = stack_entry->aux.avail_ssize;
3197 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
3198 p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
3199 grow_amount = p->p_rlimit[RLIMIT_STACK].rlim_cur -
3200 ctob(vm->vm_ssize);
3203 /* If we would blow our VMEM resource limit, no go */
3204 if (map->size + grow_amount > p->p_rlimit[RLIMIT_VMEM].rlim_cur) {
3205 rv = KERN_NO_SPACE;
3206 goto done;
3209 if (use_read_lock && vm_map_lock_upgrade(map)) {
3210 use_read_lock = 0;
3211 goto Retry;
3213 use_read_lock = 0;
3215 /* Get the preliminary new entry start value */
3216 addr = stack_entry->start - grow_amount;
3218 /* If this puts us into the previous entry, cut back our growth
3219 * to the available space. Also, see the note above.
3221 if (addr < end) {
3222 stack_entry->aux.avail_ssize = stack_entry->start - end;
3223 addr = end;
3226 rv = vm_map_insert(map, &count,
3227 NULL, 0, addr, stack_entry->start,
3228 VM_MAPTYPE_NORMAL,
3229 VM_PROT_ALL, VM_PROT_ALL,
3232 /* Adjust the available stack space by the amount we grew. */
3233 if (rv == KERN_SUCCESS) {
3234 if (prev_entry != &map->header)
3235 vm_map_clip_end(map, prev_entry, addr, &count);
3236 new_stack_entry = prev_entry->next;
3237 if (new_stack_entry->end != stack_entry->start ||
3238 new_stack_entry->start != addr)
3239 panic ("Bad stack grow start/end in new stack entry");
3240 else {
3241 new_stack_entry->aux.avail_ssize =
3242 stack_entry->aux.avail_ssize -
3243 (new_stack_entry->end - new_stack_entry->start);
3244 if (is_procstack)
3245 vm->vm_ssize += btoc(new_stack_entry->end -
3246 new_stack_entry->start);
3250 done:
3251 if (use_read_lock)
3252 vm_map_unlock_read(map);
3253 else
3254 vm_map_unlock(map);
3255 vm_map_entry_release(count);
3256 return (rv);
3260 * Unshare the specified VM space for exec. If other processes are
3261 * mapped to it, then create a new one. The new vmspace is null.
3263 void
3264 vmspace_exec(struct proc *p, struct vmspace *vmcopy)
3266 struct vmspace *oldvmspace = p->p_vmspace;
3267 struct vmspace *newvmspace;
3268 vm_map_t map = &p->p_vmspace->vm_map;
3271 * If we are execing a resident vmspace we fork it, otherwise
3272 * we create a new vmspace. Note that exitingcnt and upcalls
3273 * are not copied to the new vmspace.
3275 if (vmcopy) {
3276 newvmspace = vmspace_fork(vmcopy);
3277 } else {
3278 newvmspace = vmspace_alloc(map->min_offset, map->max_offset);
3279 bcopy(&oldvmspace->vm_startcopy, &newvmspace->vm_startcopy,
3280 (caddr_t)&oldvmspace->vm_endcopy -
3281 (caddr_t)&oldvmspace->vm_startcopy);
3285 * Finish initializing the vmspace before assigning it
3286 * to the process. The vmspace will become the current vmspace
3287 * if p == curproc.
3289 pmap_pinit2(vmspace_pmap(newvmspace));
3290 pmap_replacevm(p, newvmspace, 0);
3291 sysref_put(&oldvmspace->vm_sysref);
3295 * Unshare the specified VM space for forcing COW. This
3296 * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3298 * The exitingcnt test is not strictly necessary but has been
3299 * included for code sanity (to make the code a bit more deterministic).
3302 void
3303 vmspace_unshare(struct proc *p)
3305 struct vmspace *oldvmspace = p->p_vmspace;
3306 struct vmspace *newvmspace;
3308 if (oldvmspace->vm_sysref.refcnt == 1 && oldvmspace->vm_exitingcnt == 0)
3309 return;
3310 newvmspace = vmspace_fork(oldvmspace);
3311 pmap_pinit2(vmspace_pmap(newvmspace));
3312 pmap_replacevm(p, newvmspace, 0);
3313 sysref_put(&oldvmspace->vm_sysref);
3317 * vm_map_lookup:
3319 * Finds the VM object, offset, and
3320 * protection for a given virtual address in the
3321 * specified map, assuming a page fault of the
3322 * type specified.
3324 * Leaves the map in question locked for read; return
3325 * values are guaranteed until a vm_map_lookup_done
3326 * call is performed. Note that the map argument
3327 * is in/out; the returned map must be used in
3328 * the call to vm_map_lookup_done.
3330 * A handle (out_entry) is returned for use in
3331 * vm_map_lookup_done, to make that fast.
3333 * If a lookup is requested with "write protection"
3334 * specified, the map may be changed to perform virtual
3335 * copying operations, although the data referenced will
3336 * remain the same.
3339 vm_map_lookup(vm_map_t *var_map, /* IN/OUT */
3340 vm_offset_t vaddr,
3341 vm_prot_t fault_typea,
3342 vm_map_entry_t *out_entry, /* OUT */
3343 vm_object_t *object, /* OUT */
3344 vm_pindex_t *pindex, /* OUT */
3345 vm_prot_t *out_prot, /* OUT */
3346 boolean_t *wired) /* OUT */
3348 vm_map_entry_t entry;
3349 vm_map_t map = *var_map;
3350 vm_prot_t prot;
3351 vm_prot_t fault_type = fault_typea;
3352 int use_read_lock = 1;
3353 int rv = KERN_SUCCESS;
3355 RetryLookup:
3356 if (use_read_lock)
3357 vm_map_lock_read(map);
3358 else
3359 vm_map_lock(map);
3362 * If the map has an interesting hint, try it before calling full
3363 * blown lookup routine.
3365 entry = map->hint;
3366 *out_entry = entry;
3368 if ((entry == &map->header) ||
3369 (vaddr < entry->start) || (vaddr >= entry->end)) {
3370 vm_map_entry_t tmp_entry;
3373 * Entry was either not a valid hint, or the vaddr was not
3374 * contained in the entry, so do a full lookup.
3376 if (!vm_map_lookup_entry(map, vaddr, &tmp_entry)) {
3377 rv = KERN_INVALID_ADDRESS;
3378 goto done;
3381 entry = tmp_entry;
3382 *out_entry = entry;
3386 * Handle submaps.
3388 if (entry->maptype == VM_MAPTYPE_SUBMAP) {
3389 vm_map_t old_map = map;
3391 *var_map = map = entry->object.sub_map;
3392 if (use_read_lock)
3393 vm_map_unlock_read(old_map);
3394 else
3395 vm_map_unlock(old_map);
3396 use_read_lock = 1;
3397 goto RetryLookup;
3401 * Check whether this task is allowed to have this page.
3402 * Note the special case for MAP_ENTRY_COW
3403 * pages with an override. This is to implement a forced
3404 * COW for debuggers.
3407 if (fault_type & VM_PROT_OVERRIDE_WRITE)
3408 prot = entry->max_protection;
3409 else
3410 prot = entry->protection;
3412 fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3413 if ((fault_type & prot) != fault_type) {
3414 rv = KERN_PROTECTION_FAILURE;
3415 goto done;
3418 if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3419 (entry->eflags & MAP_ENTRY_COW) &&
3420 (fault_type & VM_PROT_WRITE) &&
3421 (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
3422 rv = KERN_PROTECTION_FAILURE;
3423 goto done;
3427 * If this page is not pageable, we have to get it for all possible
3428 * accesses.
3430 *wired = (entry->wired_count != 0);
3431 if (*wired)
3432 prot = fault_type = entry->protection;
3435 * Virtual page tables may need to update the accessed (A) bit
3436 * in a page table entry. Upgrade the fault to a write fault for
3437 * that case if the map will support it. If the map does not support
3438 * it the page table entry simply will not be updated.
3440 if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
3441 if (prot & VM_PROT_WRITE)
3442 fault_type |= VM_PROT_WRITE;
3446 * If the entry was copy-on-write, we either ...
3448 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3450 * If we want to write the page, we may as well handle that
3451 * now since we've got the map locked.
3453 * If we don't need to write the page, we just demote the
3454 * permissions allowed.
3457 if (fault_type & VM_PROT_WRITE) {
3459 * Make a new object, and place it in the object
3460 * chain. Note that no new references have appeared
3461 * -- one just moved from the map to the new
3462 * object.
3465 if (use_read_lock && vm_map_lock_upgrade(map)) {
3466 use_read_lock = 0;
3467 goto RetryLookup;
3469 use_read_lock = 0;
3471 vm_map_entry_shadow(entry);
3472 } else {
3474 * We're attempting to read a copy-on-write page --
3475 * don't allow writes.
3478 prot &= ~VM_PROT_WRITE;
3483 * Create an object if necessary.
3485 if (entry->object.vm_object == NULL &&
3486 !map->system_map) {
3487 if (use_read_lock && vm_map_lock_upgrade(map)) {
3488 use_read_lock = 0;
3489 goto RetryLookup;
3491 use_read_lock = 0;
3492 vm_map_entry_allocate_object(entry);
3496 * Return the object/offset from this entry. If the entry was
3497 * copy-on-write or empty, it has been fixed up.
3500 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3501 *object = entry->object.vm_object;
3504 * Return whether this is the only map sharing this data. On
3505 * success we return with a read lock held on the map. On failure
3506 * we return with the map unlocked.
3508 *out_prot = prot;
3509 done:
3510 if (rv == KERN_SUCCESS) {
3511 if (use_read_lock == 0)
3512 vm_map_lock_downgrade(map);
3513 } else if (use_read_lock) {
3514 vm_map_unlock_read(map);
3515 } else {
3516 vm_map_unlock(map);
3518 return (rv);
3522 * vm_map_lookup_done:
3524 * Releases locks acquired by a vm_map_lookup
3525 * (according to the handle returned by that lookup).
3528 void
3529 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry, int count)
3532 * Unlock the main-level map
3534 vm_map_unlock_read(map);
3535 if (count)
3536 vm_map_entry_release(count);
3539 #include "opt_ddb.h"
3540 #ifdef DDB
3541 #include <sys/kernel.h>
3543 #include <ddb/ddb.h>
3546 * vm_map_print: [ debug ]
3548 DB_SHOW_COMMAND(map, vm_map_print)
3550 static int nlines;
3551 /* XXX convert args. */
3552 vm_map_t map = (vm_map_t)addr;
3553 boolean_t full = have_addr;
3555 vm_map_entry_t entry;
3557 db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
3558 (void *)map,
3559 (void *)map->pmap, map->nentries, map->timestamp);
3560 nlines++;
3562 if (!full && db_indent)
3563 return;
3565 db_indent += 2;
3566 for (entry = map->header.next; entry != &map->header;
3567 entry = entry->next) {
3568 db_iprintf("map entry %p: start=%p, end=%p\n",
3569 (void *)entry, (void *)entry->start, (void *)entry->end);
3570 nlines++;
3572 static char *inheritance_name[4] =
3573 {"share", "copy", "none", "donate_copy"};
3575 db_iprintf(" prot=%x/%x/%s",
3576 entry->protection,
3577 entry->max_protection,
3578 inheritance_name[(int)(unsigned char)entry->inheritance]);
3579 if (entry->wired_count != 0)
3580 db_printf(", wired");
3582 if (entry->maptype == VM_MAPTYPE_SUBMAP) {
3583 /* XXX no %qd in kernel. Truncate entry->offset. */
3584 db_printf(", share=%p, offset=0x%lx\n",
3585 (void *)entry->object.sub_map,
3586 (long)entry->offset);
3587 nlines++;
3588 if ((entry->prev == &map->header) ||
3589 (entry->prev->object.sub_map !=
3590 entry->object.sub_map)) {
3591 db_indent += 2;
3592 vm_map_print((db_expr_t)(intptr_t)
3593 entry->object.sub_map,
3594 full, 0, NULL);
3595 db_indent -= 2;
3597 } else {
3598 /* XXX no %qd in kernel. Truncate entry->offset. */
3599 db_printf(", object=%p, offset=0x%lx",
3600 (void *)entry->object.vm_object,
3601 (long)entry->offset);
3602 if (entry->eflags & MAP_ENTRY_COW)
3603 db_printf(", copy (%s)",
3604 (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
3605 db_printf("\n");
3606 nlines++;
3608 if ((entry->prev == &map->header) ||
3609 (entry->prev->object.vm_object !=
3610 entry->object.vm_object)) {
3611 db_indent += 2;
3612 vm_object_print((db_expr_t)(intptr_t)
3613 entry->object.vm_object,
3614 full, 0, NULL);
3615 nlines += 4;
3616 db_indent -= 2;
3620 db_indent -= 2;
3621 if (db_indent == 0)
3622 nlines = 0;
3626 DB_SHOW_COMMAND(procvm, procvm)
3628 struct proc *p;
3630 if (have_addr) {
3631 p = (struct proc *) addr;
3632 } else {
3633 p = curproc;
3636 db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3637 (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3638 (void *)vmspace_pmap(p->p_vmspace));
3640 vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3643 #endif /* DDB */