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