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