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