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