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