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