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