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