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