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