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