]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_map.c
Call swap_pager_freespace() from vm_object_page_remove().
[FreeBSD/FreeBSD.git] / sys / vm / vm_map.c
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      from: @(#)vm_map.c      8.3 (Berkeley) 1/12/94
35  *
36  *
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62
63 /*
64  *      Virtual memory mapping module.
65  */
66
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
69
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/elf.h>
73 #include <sys/kernel.h>
74 #include <sys/ktr.h>
75 #include <sys/lock.h>
76 #include <sys/mutex.h>
77 #include <sys/proc.h>
78 #include <sys/vmmeter.h>
79 #include <sys/mman.h>
80 #include <sys/vnode.h>
81 #include <sys/racct.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/file.h>
85 #include <sys/sysctl.h>
86 #include <sys/sysent.h>
87 #include <sys/shm.h>
88
89 #include <vm/vm.h>
90 #include <vm/vm_param.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pageout.h>
95 #include <vm/vm_object.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vm_kern.h>
98 #include <vm/vm_extern.h>
99 #include <vm/vnode_pager.h>
100 #include <vm/swap_pager.h>
101 #include <vm/uma.h>
102
103 /*
104  *      Virtual memory maps provide for the mapping, protection,
105  *      and sharing of virtual memory objects.  In addition,
106  *      this module provides for an efficient virtual copy of
107  *      memory from one map to another.
108  *
109  *      Synchronization is required prior to most operations.
110  *
111  *      Maps consist of an ordered doubly-linked list of simple
112  *      entries; a self-adjusting binary search tree of these
113  *      entries is used to speed up lookups.
114  *
115  *      Since portions of maps are specified by start/end addresses,
116  *      which may not align with existing map entries, all
117  *      routines merely "clip" entries to these start/end values.
118  *      [That is, an entry is split into two, bordering at a
119  *      start or end value.]  Note that these clippings may not
120  *      always be necessary (as the two resulting entries are then
121  *      not changed); however, the clipping is done for convenience.
122  *
123  *      As mentioned above, virtual copy operations are performed
124  *      by copying VM object references from one map to
125  *      another, and then marking both regions as copy-on-write.
126  */
127
128 static struct mtx map_sleep_mtx;
129 static uma_zone_t mapentzone;
130 static uma_zone_t kmapentzone;
131 static uma_zone_t mapzone;
132 static uma_zone_t vmspace_zone;
133 static int vmspace_zinit(void *mem, int size, int flags);
134 static int vm_map_zinit(void *mem, int ize, int flags);
135 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
136     vm_offset_t max);
137 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
138 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
139 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
140 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
141     vm_map_entry_t gap_entry);
142 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
143     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
144 #ifdef INVARIANTS
145 static void vm_map_zdtor(void *mem, int size, void *arg);
146 static void vmspace_zdtor(void *mem, int size, void *arg);
147 #endif
148 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
149     vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
150     int cow);
151 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
152     vm_offset_t failed_addr);
153
154 #define ENTRY_CHARGED(e) ((e)->cred != NULL || \
155     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
156      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
157
158 /* 
159  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
160  * stable.
161  */
162 #define PROC_VMSPACE_LOCK(p) do { } while (0)
163 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
164
165 /*
166  *      VM_MAP_RANGE_CHECK:     [ internal use only ]
167  *
168  *      Asserts that the starting and ending region
169  *      addresses fall within the valid range of the map.
170  */
171 #define VM_MAP_RANGE_CHECK(map, start, end)             \
172                 {                                       \
173                 if (start < vm_map_min(map))            \
174                         start = vm_map_min(map);        \
175                 if (end > vm_map_max(map))              \
176                         end = vm_map_max(map);          \
177                 if (start > end)                        \
178                         start = end;                    \
179                 }
180
181 /*
182  *      vm_map_startup:
183  *
184  *      Initialize the vm_map module.  Must be called before
185  *      any other vm_map routines.
186  *
187  *      Map and entry structures are allocated from the general
188  *      purpose memory pool with some exceptions:
189  *
190  *      - The kernel map and kmem submap are allocated statically.
191  *      - Kernel map entries are allocated out of a static pool.
192  *
193  *      These restrictions are necessary since malloc() uses the
194  *      maps and requires map entries.
195  */
196
197 void
198 vm_map_startup(void)
199 {
200         mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
201         mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
202 #ifdef INVARIANTS
203             vm_map_zdtor,
204 #else
205             NULL,
206 #endif
207             vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
208         uma_prealloc(mapzone, MAX_KMAP);
209         kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
210             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
211             UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
212         mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
213             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
214         vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
215 #ifdef INVARIANTS
216             vmspace_zdtor,
217 #else
218             NULL,
219 #endif
220             vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
221 }
222
223 static int
224 vmspace_zinit(void *mem, int size, int flags)
225 {
226         struct vmspace *vm;
227
228         vm = (struct vmspace *)mem;
229
230         vm->vm_map.pmap = NULL;
231         (void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
232         PMAP_LOCK_INIT(vmspace_pmap(vm));
233         return (0);
234 }
235
236 static int
237 vm_map_zinit(void *mem, int size, int flags)
238 {
239         vm_map_t map;
240
241         map = (vm_map_t)mem;
242         memset(map, 0, sizeof(*map));
243         mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
244         sx_init(&map->lock, "vm map (user)");
245         return (0);
246 }
247
248 #ifdef INVARIANTS
249 static void
250 vmspace_zdtor(void *mem, int size, void *arg)
251 {
252         struct vmspace *vm;
253
254         vm = (struct vmspace *)mem;
255
256         vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
257 }
258 static void
259 vm_map_zdtor(void *mem, int size, void *arg)
260 {
261         vm_map_t map;
262
263         map = (vm_map_t)mem;
264         KASSERT(map->nentries == 0,
265             ("map %p nentries == %d on free.",
266             map, map->nentries));
267         KASSERT(map->size == 0,
268             ("map %p size == %lu on free.",
269             map, (unsigned long)map->size));
270 }
271 #endif  /* INVARIANTS */
272
273 /*
274  * Allocate a vmspace structure, including a vm_map and pmap,
275  * and initialize those structures.  The refcnt is set to 1.
276  *
277  * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
278  */
279 struct vmspace *
280 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
281 {
282         struct vmspace *vm;
283
284         vm = uma_zalloc(vmspace_zone, M_WAITOK);
285         KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
286         if (!pinit(vmspace_pmap(vm))) {
287                 uma_zfree(vmspace_zone, vm);
288                 return (NULL);
289         }
290         CTR1(KTR_VM, "vmspace_alloc: %p", vm);
291         _vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
292         vm->vm_refcnt = 1;
293         vm->vm_shm = NULL;
294         vm->vm_swrss = 0;
295         vm->vm_tsize = 0;
296         vm->vm_dsize = 0;
297         vm->vm_ssize = 0;
298         vm->vm_taddr = 0;
299         vm->vm_daddr = 0;
300         vm->vm_maxsaddr = 0;
301         return (vm);
302 }
303
304 #ifdef RACCT
305 static void
306 vmspace_container_reset(struct proc *p)
307 {
308
309         PROC_LOCK(p);
310         racct_set(p, RACCT_DATA, 0);
311         racct_set(p, RACCT_STACK, 0);
312         racct_set(p, RACCT_RSS, 0);
313         racct_set(p, RACCT_MEMLOCK, 0);
314         racct_set(p, RACCT_VMEM, 0);
315         PROC_UNLOCK(p);
316 }
317 #endif
318
319 static inline void
320 vmspace_dofree(struct vmspace *vm)
321 {
322
323         CTR1(KTR_VM, "vmspace_free: %p", vm);
324
325         /*
326          * Make sure any SysV shm is freed, it might not have been in
327          * exit1().
328          */
329         shmexit(vm);
330
331         /*
332          * Lock the map, to wait out all other references to it.
333          * Delete all of the mappings and pages they hold, then call
334          * the pmap module to reclaim anything left.
335          */
336         (void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
337             vm_map_max(&vm->vm_map));
338
339         pmap_release(vmspace_pmap(vm));
340         vm->vm_map.pmap = NULL;
341         uma_zfree(vmspace_zone, vm);
342 }
343
344 void
345 vmspace_free(struct vmspace *vm)
346 {
347
348         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
349             "vmspace_free() called");
350
351         if (vm->vm_refcnt == 0)
352                 panic("vmspace_free: attempt to free already freed vmspace");
353
354         if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
355                 vmspace_dofree(vm);
356 }
357
358 void
359 vmspace_exitfree(struct proc *p)
360 {
361         struct vmspace *vm;
362
363         PROC_VMSPACE_LOCK(p);
364         vm = p->p_vmspace;
365         p->p_vmspace = NULL;
366         PROC_VMSPACE_UNLOCK(p);
367         KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
368         vmspace_free(vm);
369 }
370
371 void
372 vmspace_exit(struct thread *td)
373 {
374         int refcnt;
375         struct vmspace *vm;
376         struct proc *p;
377
378         /*
379          * Release user portion of address space.
380          * This releases references to vnodes,
381          * which could cause I/O if the file has been unlinked.
382          * Need to do this early enough that we can still sleep.
383          *
384          * The last exiting process to reach this point releases as
385          * much of the environment as it can. vmspace_dofree() is the
386          * slower fallback in case another process had a temporary
387          * reference to the vmspace.
388          */
389
390         p = td->td_proc;
391         vm = p->p_vmspace;
392         atomic_add_int(&vmspace0.vm_refcnt, 1);
393         refcnt = vm->vm_refcnt;
394         do {
395                 if (refcnt > 1 && p->p_vmspace != &vmspace0) {
396                         /* Switch now since other proc might free vmspace */
397                         PROC_VMSPACE_LOCK(p);
398                         p->p_vmspace = &vmspace0;
399                         PROC_VMSPACE_UNLOCK(p);
400                         pmap_activate(td);
401                 }
402         } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt - 1));
403         if (refcnt == 1) {
404                 if (p->p_vmspace != vm) {
405                         /* vmspace not yet freed, switch back */
406                         PROC_VMSPACE_LOCK(p);
407                         p->p_vmspace = vm;
408                         PROC_VMSPACE_UNLOCK(p);
409                         pmap_activate(td);
410                 }
411                 pmap_remove_pages(vmspace_pmap(vm));
412                 /* Switch now since this proc will free vmspace */
413                 PROC_VMSPACE_LOCK(p);
414                 p->p_vmspace = &vmspace0;
415                 PROC_VMSPACE_UNLOCK(p);
416                 pmap_activate(td);
417                 vmspace_dofree(vm);
418         }
419 #ifdef RACCT
420         if (racct_enable)
421                 vmspace_container_reset(p);
422 #endif
423 }
424
425 /* Acquire reference to vmspace owned by another process. */
426
427 struct vmspace *
428 vmspace_acquire_ref(struct proc *p)
429 {
430         struct vmspace *vm;
431         int refcnt;
432
433         PROC_VMSPACE_LOCK(p);
434         vm = p->p_vmspace;
435         if (vm == NULL) {
436                 PROC_VMSPACE_UNLOCK(p);
437                 return (NULL);
438         }
439         refcnt = vm->vm_refcnt;
440         do {
441                 if (refcnt <= 0) {      /* Avoid 0->1 transition */
442                         PROC_VMSPACE_UNLOCK(p);
443                         return (NULL);
444                 }
445         } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt + 1));
446         if (vm != p->p_vmspace) {
447                 PROC_VMSPACE_UNLOCK(p);
448                 vmspace_free(vm);
449                 return (NULL);
450         }
451         PROC_VMSPACE_UNLOCK(p);
452         return (vm);
453 }
454
455 /*
456  * Switch between vmspaces in an AIO kernel process.
457  *
458  * The new vmspace is either the vmspace of a user process obtained
459  * from an active AIO request or the initial vmspace of the AIO kernel
460  * process (when it is idling).  Because user processes will block to
461  * drain any active AIO requests before proceeding in exit() or
462  * execve(), the reference count for vmspaces from AIO requests can
463  * never be 0.  Similarly, AIO kernel processes hold an extra
464  * reference on their initial vmspace for the life of the process.  As
465  * a result, the 'newvm' vmspace always has a non-zero reference
466  * count.  This permits an additional reference on 'newvm' to be
467  * acquired via a simple atomic increment rather than the loop in
468  * vmspace_acquire_ref() above.
469  */
470 void
471 vmspace_switch_aio(struct vmspace *newvm)
472 {
473         struct vmspace *oldvm;
474
475         /* XXX: Need some way to assert that this is an aio daemon. */
476
477         KASSERT(newvm->vm_refcnt > 0,
478             ("vmspace_switch_aio: newvm unreferenced"));
479
480         oldvm = curproc->p_vmspace;
481         if (oldvm == newvm)
482                 return;
483
484         /*
485          * Point to the new address space and refer to it.
486          */
487         curproc->p_vmspace = newvm;
488         atomic_add_int(&newvm->vm_refcnt, 1);
489
490         /* Activate the new mapping. */
491         pmap_activate(curthread);
492
493         vmspace_free(oldvm);
494 }
495
496 void
497 _vm_map_lock(vm_map_t map, const char *file, int line)
498 {
499
500         if (map->system_map)
501                 mtx_lock_flags_(&map->system_mtx, 0, file, line);
502         else
503                 sx_xlock_(&map->lock, file, line);
504         map->timestamp++;
505 }
506
507 void
508 vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
509 {
510         vm_object_t object;
511         struct vnode *vp;
512         bool vp_held;
513
514         if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
515                 return;
516         KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
517             ("Submap with execs"));
518         object = entry->object.vm_object;
519         KASSERT(object != NULL, ("No object for text, entry %p", entry));
520         if ((object->flags & OBJ_ANON) != 0)
521                 object = object->handle;
522         else
523                 KASSERT(object->backing_object == NULL,
524                     ("non-anon object %p shadows", object));
525         KASSERT(object != NULL, ("No content object for text, entry %p obj %p",
526             entry, entry->object.vm_object));
527
528         /*
529          * Mostly, we do not lock the backing object.  It is
530          * referenced by the entry we are processing, so it cannot go
531          * away.
532          */
533         vp = NULL;
534         vp_held = false;
535         if (object->type == OBJT_DEAD) {
536                 /*
537                  * For OBJT_DEAD objects, v_writecount was handled in
538                  * vnode_pager_dealloc().
539                  */
540         } else if (object->type == OBJT_VNODE) {
541                 vp = object->handle;
542         } else if (object->type == OBJT_SWAP) {
543                 KASSERT((object->flags & OBJ_TMPFS_NODE) != 0,
544                     ("vm_map_entry_set_vnode_text: swap and !TMPFS "
545                     "entry %p, object %p, add %d", entry, object, add));
546                 /*
547                  * Tmpfs VREG node, which was reclaimed, has
548                  * OBJ_TMPFS_NODE flag set, but not OBJ_TMPFS.  In
549                  * this case there is no v_writecount to adjust.
550                  */
551                 VM_OBJECT_RLOCK(object);
552                 if ((object->flags & OBJ_TMPFS) != 0) {
553                         vp = object->un_pager.swp.swp_tmpfs;
554                         if (vp != NULL) {
555                                 vhold(vp);
556                                 vp_held = true;
557                         }
558                 }
559                 VM_OBJECT_RUNLOCK(object);
560         } else {
561                 KASSERT(0,
562                     ("vm_map_entry_set_vnode_text: wrong object type, "
563                     "entry %p, object %p, add %d", entry, object, add));
564         }
565         if (vp != NULL) {
566                 if (add) {
567                         VOP_SET_TEXT_CHECKED(vp);
568                 } else {
569                         vn_lock(vp, LK_SHARED | LK_RETRY);
570                         VOP_UNSET_TEXT_CHECKED(vp);
571                         VOP_UNLOCK(vp);
572                 }
573                 if (vp_held)
574                         vdrop(vp);
575         }
576 }
577
578 /*
579  * Use a different name for this vm_map_entry field when it's use
580  * is not consistent with its use as part of an ordered search tree.
581  */
582 #define defer_next right
583
584 static void
585 vm_map_process_deferred(void)
586 {
587         struct thread *td;
588         vm_map_entry_t entry, next;
589         vm_object_t object;
590
591         td = curthread;
592         entry = td->td_map_def_user;
593         td->td_map_def_user = NULL;
594         while (entry != NULL) {
595                 next = entry->defer_next;
596                 MPASS((entry->eflags & (MAP_ENTRY_WRITECNT |
597                     MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_WRITECNT |
598                     MAP_ENTRY_VN_EXEC));
599                 if ((entry->eflags & MAP_ENTRY_WRITECNT) != 0) {
600                         /*
601                          * Decrement the object's writemappings and
602                          * possibly the vnode's v_writecount.
603                          */
604                         KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
605                             ("Submap with writecount"));
606                         object = entry->object.vm_object;
607                         KASSERT(object != NULL, ("No object for writecount"));
608                         vm_pager_release_writecount(object, entry->start,
609                             entry->end);
610                 }
611                 vm_map_entry_set_vnode_text(entry, false);
612                 vm_map_entry_deallocate(entry, FALSE);
613                 entry = next;
614         }
615 }
616
617 #ifdef INVARIANTS
618 static void
619 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
620 {
621
622         if (map->system_map)
623                 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
624         else
625                 sx_assert_(&map->lock, SA_XLOCKED, file, line);
626 }
627
628 #define VM_MAP_ASSERT_LOCKED(map) \
629     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
630
631 enum { VMMAP_CHECK_NONE, VMMAP_CHECK_UNLOCK, VMMAP_CHECK_ALL };
632 #ifdef DIAGNOSTIC
633 static int enable_vmmap_check = VMMAP_CHECK_UNLOCK;
634 #else
635 static int enable_vmmap_check = VMMAP_CHECK_NONE;
636 #endif
637 SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
638     &enable_vmmap_check, 0, "Enable vm map consistency checking");
639
640 static void _vm_map_assert_consistent(vm_map_t map, int check);
641
642 #define VM_MAP_ASSERT_CONSISTENT(map) \
643     _vm_map_assert_consistent(map, VMMAP_CHECK_ALL)
644 #ifdef DIAGNOSTIC
645 #define VM_MAP_UNLOCK_CONSISTENT(map) do {                              \
646         if (map->nupdates > map->nentries) {                            \
647                 _vm_map_assert_consistent(map, VMMAP_CHECK_UNLOCK);     \
648                 map->nupdates = 0;                                      \
649         }                                                               \
650 } while (0)
651 #else
652 #define VM_MAP_UNLOCK_CONSISTENT(map)
653 #endif
654 #else
655 #define VM_MAP_ASSERT_LOCKED(map)
656 #define VM_MAP_ASSERT_CONSISTENT(map)
657 #define VM_MAP_UNLOCK_CONSISTENT(map)
658 #endif /* INVARIANTS */
659
660 void
661 _vm_map_unlock(vm_map_t map, const char *file, int line)
662 {
663
664         VM_MAP_UNLOCK_CONSISTENT(map);
665         if (map->system_map)
666                 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
667         else {
668                 sx_xunlock_(&map->lock, file, line);
669                 vm_map_process_deferred();
670         }
671 }
672
673 void
674 _vm_map_lock_read(vm_map_t map, const char *file, int line)
675 {
676
677         if (map->system_map)
678                 mtx_lock_flags_(&map->system_mtx, 0, file, line);
679         else
680                 sx_slock_(&map->lock, file, line);
681 }
682
683 void
684 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
685 {
686
687         if (map->system_map)
688                 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
689         else {
690                 sx_sunlock_(&map->lock, file, line);
691                 vm_map_process_deferred();
692         }
693 }
694
695 int
696 _vm_map_trylock(vm_map_t map, const char *file, int line)
697 {
698         int error;
699
700         error = map->system_map ?
701             !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
702             !sx_try_xlock_(&map->lock, file, line);
703         if (error == 0)
704                 map->timestamp++;
705         return (error == 0);
706 }
707
708 int
709 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
710 {
711         int error;
712
713         error = map->system_map ?
714             !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
715             !sx_try_slock_(&map->lock, file, line);
716         return (error == 0);
717 }
718
719 /*
720  *      _vm_map_lock_upgrade:   [ internal use only ]
721  *
722  *      Tries to upgrade a read (shared) lock on the specified map to a write
723  *      (exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
724  *      non-zero value if the upgrade fails.  If the upgrade fails, the map is
725  *      returned without a read or write lock held.
726  *
727  *      Requires that the map be read locked.
728  */
729 int
730 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
731 {
732         unsigned int last_timestamp;
733
734         if (map->system_map) {
735                 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
736         } else {
737                 if (!sx_try_upgrade_(&map->lock, file, line)) {
738                         last_timestamp = map->timestamp;
739                         sx_sunlock_(&map->lock, file, line);
740                         vm_map_process_deferred();
741                         /*
742                          * If the map's timestamp does not change while the
743                          * map is unlocked, then the upgrade succeeds.
744                          */
745                         sx_xlock_(&map->lock, file, line);
746                         if (last_timestamp != map->timestamp) {
747                                 sx_xunlock_(&map->lock, file, line);
748                                 return (1);
749                         }
750                 }
751         }
752         map->timestamp++;
753         return (0);
754 }
755
756 void
757 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
758 {
759
760         if (map->system_map) {
761                 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
762         } else {
763                 VM_MAP_UNLOCK_CONSISTENT(map);
764                 sx_downgrade_(&map->lock, file, line);
765         }
766 }
767
768 /*
769  *      vm_map_locked:
770  *
771  *      Returns a non-zero value if the caller holds a write (exclusive) lock
772  *      on the specified map and the value "0" otherwise.
773  */
774 int
775 vm_map_locked(vm_map_t map)
776 {
777
778         if (map->system_map)
779                 return (mtx_owned(&map->system_mtx));
780         else
781                 return (sx_xlocked(&map->lock));
782 }
783
784 /*
785  *      _vm_map_unlock_and_wait:
786  *
787  *      Atomically releases the lock on the specified map and puts the calling
788  *      thread to sleep.  The calling thread will remain asleep until either
789  *      vm_map_wakeup() is performed on the map or the specified timeout is
790  *      exceeded.
791  *
792  *      WARNING!  This function does not perform deferred deallocations of
793  *      objects and map entries.  Therefore, the calling thread is expected to
794  *      reacquire the map lock after reawakening and later perform an ordinary
795  *      unlock operation, such as vm_map_unlock(), before completing its
796  *      operation on the map.
797  */
798 int
799 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
800 {
801
802         VM_MAP_UNLOCK_CONSISTENT(map);
803         mtx_lock(&map_sleep_mtx);
804         if (map->system_map)
805                 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
806         else
807                 sx_xunlock_(&map->lock, file, line);
808         return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
809             timo));
810 }
811
812 /*
813  *      vm_map_wakeup:
814  *
815  *      Awaken any threads that have slept on the map using
816  *      vm_map_unlock_and_wait().
817  */
818 void
819 vm_map_wakeup(vm_map_t map)
820 {
821
822         /*
823          * Acquire and release map_sleep_mtx to prevent a wakeup()
824          * from being performed (and lost) between the map unlock
825          * and the msleep() in _vm_map_unlock_and_wait().
826          */
827         mtx_lock(&map_sleep_mtx);
828         mtx_unlock(&map_sleep_mtx);
829         wakeup(&map->root);
830 }
831
832 void
833 vm_map_busy(vm_map_t map)
834 {
835
836         VM_MAP_ASSERT_LOCKED(map);
837         map->busy++;
838 }
839
840 void
841 vm_map_unbusy(vm_map_t map)
842 {
843
844         VM_MAP_ASSERT_LOCKED(map);
845         KASSERT(map->busy, ("vm_map_unbusy: not busy"));
846         if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
847                 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
848                 wakeup(&map->busy);
849         }
850 }
851
852 void 
853 vm_map_wait_busy(vm_map_t map)
854 {
855
856         VM_MAP_ASSERT_LOCKED(map);
857         while (map->busy) {
858                 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
859                 if (map->system_map)
860                         msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
861                 else
862                         sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
863         }
864         map->timestamp++;
865 }
866
867 long
868 vmspace_resident_count(struct vmspace *vmspace)
869 {
870         return pmap_resident_count(vmspace_pmap(vmspace));
871 }
872
873 /*
874  *      vm_map_create:
875  *
876  *      Creates and returns a new empty VM map with
877  *      the given physical map structure, and having
878  *      the given lower and upper address bounds.
879  */
880 vm_map_t
881 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
882 {
883         vm_map_t result;
884
885         result = uma_zalloc(mapzone, M_WAITOK);
886         CTR1(KTR_VM, "vm_map_create: %p", result);
887         _vm_map_init(result, pmap, min, max);
888         return (result);
889 }
890
891 /*
892  * Initialize an existing vm_map structure
893  * such as that in the vmspace structure.
894  */
895 static void
896 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
897 {
898
899         map->header.eflags = MAP_ENTRY_HEADER;
900         map->needs_wakeup = FALSE;
901         map->system_map = 0;
902         map->pmap = pmap;
903         map->header.end = min;
904         map->header.start = max;
905         map->flags = 0;
906         map->header.left = map->header.right = &map->header;
907         map->root = NULL;
908         map->timestamp = 0;
909         map->busy = 0;
910         map->anon_loc = 0;
911 #ifdef DIAGNOSTIC
912         map->nupdates = 0;
913 #endif
914 }
915
916 void
917 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
918 {
919
920         _vm_map_init(map, pmap, min, max);
921         mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
922         sx_init(&map->lock, "user map");
923 }
924
925 /*
926  *      vm_map_entry_dispose:   [ internal use only ]
927  *
928  *      Inverse of vm_map_entry_create.
929  */
930 static void
931 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
932 {
933         uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
934 }
935
936 /*
937  *      vm_map_entry_create:    [ internal use only ]
938  *
939  *      Allocates a VM map entry for insertion.
940  *      No entry fields are filled in.
941  */
942 static vm_map_entry_t
943 vm_map_entry_create(vm_map_t map)
944 {
945         vm_map_entry_t new_entry;
946
947         if (map->system_map)
948                 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
949         else
950                 new_entry = uma_zalloc(mapentzone, M_WAITOK);
951         if (new_entry == NULL)
952                 panic("vm_map_entry_create: kernel resources exhausted");
953         return (new_entry);
954 }
955
956 /*
957  *      vm_map_entry_set_behavior:
958  *
959  *      Set the expected access behavior, either normal, random, or
960  *      sequential.
961  */
962 static inline void
963 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
964 {
965         entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
966             (behavior & MAP_ENTRY_BEHAV_MASK);
967 }
968
969 /*
970  *      vm_map_entry_max_free_{left,right}:
971  *
972  *      Compute the size of the largest free gap between two entries,
973  *      one the root of a tree and the other the ancestor of that root
974  *      that is the least or greatest ancestor found on the search path.
975  */
976 static inline vm_size_t
977 vm_map_entry_max_free_left(vm_map_entry_t root, vm_map_entry_t left_ancestor)
978 {
979
980         return (root->left != left_ancestor ?
981             root->left->max_free : root->start - left_ancestor->end);
982 }
983
984 static inline vm_size_t
985 vm_map_entry_max_free_right(vm_map_entry_t root, vm_map_entry_t right_ancestor)
986 {
987
988         return (root->right != right_ancestor ?
989             root->right->max_free : right_ancestor->start - root->end);
990 }
991
992 /*
993  *      vm_map_entry_{pred,succ}:
994  *
995  *      Find the {predecessor, successor} of the entry by taking one step
996  *      in the appropriate direction and backtracking as much as necessary.
997  *      vm_map_entry_succ is defined in vm_map.h.
998  */
999 static inline vm_map_entry_t
1000 vm_map_entry_pred(vm_map_entry_t entry)
1001 {
1002         vm_map_entry_t prior;
1003
1004         prior = entry->left;
1005         if (prior->right->start < entry->start) {
1006                 do
1007                         prior = prior->right;
1008                 while (prior->right != entry);
1009         }
1010         return (prior);
1011 }
1012
1013 static inline vm_size_t
1014 vm_size_max(vm_size_t a, vm_size_t b)
1015 {
1016
1017         return (a > b ? a : b);
1018 }
1019
1020 #define SPLAY_LEFT_STEP(root, y, llist, rlist, test) do {               \
1021         vm_map_entry_t z;                                               \
1022         vm_size_t max_free;                                             \
1023                                                                         \
1024         /*                                                              \
1025          * Infer root->right->max_free == root->max_free when           \
1026          * y->max_free < root->max_free || root->max_free == 0.         \
1027          * Otherwise, look right to find it.                            \
1028          */                                                             \
1029         y = root->left;                                                 \
1030         max_free = root->max_free;                                      \
1031         KASSERT(max_free == vm_size_max(                                \
1032             vm_map_entry_max_free_left(root, llist),                    \
1033             vm_map_entry_max_free_right(root, rlist)),                  \
1034             ("%s: max_free invariant fails", __func__));                \
1035         if (max_free - 1 < vm_map_entry_max_free_left(root, llist))     \
1036                 max_free = vm_map_entry_max_free_right(root, rlist);    \
1037         if (y != llist && (test)) {                                     \
1038                 /* Rotate right and make y root. */                     \
1039                 z = y->right;                                           \
1040                 if (z != root) {                                        \
1041                         root->left = z;                                 \
1042                         y->right = root;                                \
1043                         if (max_free < y->max_free)                     \
1044                             root->max_free = max_free =                 \
1045                             vm_size_max(max_free, z->max_free);         \
1046                 } else if (max_free < y->max_free)                      \
1047                         root->max_free = max_free =                     \
1048                             vm_size_max(max_free, root->start - y->end);\
1049                 root = y;                                               \
1050                 y = root->left;                                         \
1051         }                                                               \
1052         /* Copy right->max_free.  Put root on rlist. */                 \
1053         root->max_free = max_free;                                      \
1054         KASSERT(max_free == vm_map_entry_max_free_right(root, rlist),   \
1055             ("%s: max_free not copied from right", __func__));          \
1056         root->left = rlist;                                             \
1057         rlist = root;                                                   \
1058         root = y != llist ? y : NULL;                                   \
1059 } while (0)
1060
1061 #define SPLAY_RIGHT_STEP(root, y, llist, rlist, test) do {              \
1062         vm_map_entry_t z;                                               \
1063         vm_size_t max_free;                                             \
1064                                                                         \
1065         /*                                                              \
1066          * Infer root->left->max_free == root->max_free when            \
1067          * y->max_free < root->max_free || root->max_free == 0.         \
1068          * Otherwise, look left to find it.                             \
1069          */                                                             \
1070         y = root->right;                                                \
1071         max_free = root->max_free;                                      \
1072         KASSERT(max_free == vm_size_max(                                \
1073             vm_map_entry_max_free_left(root, llist),                    \
1074             vm_map_entry_max_free_right(root, rlist)),                  \
1075             ("%s: max_free invariant fails", __func__));                \
1076         if (max_free - 1 < vm_map_entry_max_free_right(root, rlist))    \
1077                 max_free = vm_map_entry_max_free_left(root, llist);     \
1078         if (y != rlist && (test)) {                                     \
1079                 /* Rotate left and make y root. */                      \
1080                 z = y->left;                                            \
1081                 if (z != root) {                                        \
1082                         root->right = z;                                \
1083                         y->left = root;                                 \
1084                         if (max_free < y->max_free)                     \
1085                             root->max_free = max_free =                 \
1086                             vm_size_max(max_free, z->max_free);         \
1087                 } else if (max_free < y->max_free)                      \
1088                         root->max_free = max_free =                     \
1089                             vm_size_max(max_free, y->start - root->end);\
1090                 root = y;                                               \
1091                 y = root->right;                                        \
1092         }                                                               \
1093         /* Copy left->max_free.  Put root on llist. */                  \
1094         root->max_free = max_free;                                      \
1095         KASSERT(max_free == vm_map_entry_max_free_left(root, llist),    \
1096             ("%s: max_free not copied from left", __func__));           \
1097         root->right = llist;                                            \
1098         llist = root;                                                   \
1099         root = y != rlist ? y : NULL;                                   \
1100 } while (0)
1101
1102 /*
1103  * Walk down the tree until we find addr or a gap where addr would go, breaking
1104  * off left and right subtrees of nodes less than, or greater than addr.  Treat
1105  * subtrees with root->max_free < length as empty trees.  llist and rlist are
1106  * the two sides in reverse order (bottom-up), with llist linked by the right
1107  * pointer and rlist linked by the left pointer in the vm_map_entry, and both
1108  * lists terminated by &map->header.  This function, and the subsequent call to
1109  * vm_map_splay_merge_{left,right,pred,succ}, rely on the start and end address
1110  * values in &map->header.
1111  */
1112 static __always_inline vm_map_entry_t
1113 vm_map_splay_split(vm_map_t map, vm_offset_t addr, vm_size_t length,
1114     vm_map_entry_t *llist, vm_map_entry_t *rlist)
1115 {
1116         vm_map_entry_t left, right, root, y;
1117
1118         left = right = &map->header;
1119         root = map->root;
1120         while (root != NULL && root->max_free >= length) {
1121                 KASSERT(left->end <= root->start &&
1122                     root->end <= right->start,
1123                     ("%s: root not within tree bounds", __func__));
1124                 if (addr < root->start) {
1125                         SPLAY_LEFT_STEP(root, y, left, right,
1126                             y->max_free >= length && addr < y->start);
1127                 } else if (addr >= root->end) {
1128                         SPLAY_RIGHT_STEP(root, y, left, right,
1129                             y->max_free >= length && addr >= y->end);
1130                 } else
1131                         break;
1132         }
1133         *llist = left;
1134         *rlist = right;
1135         return (root);
1136 }
1137
1138 static __always_inline void
1139 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *rlist)
1140 {
1141         vm_map_entry_t hi, right, y;
1142
1143         right = *rlist;
1144         hi = root->right == right ? NULL : root->right;
1145         if (hi == NULL)
1146                 return;
1147         do
1148                 SPLAY_LEFT_STEP(hi, y, root, right, true);
1149         while (hi != NULL);
1150         *rlist = right;
1151 }
1152
1153 static __always_inline void
1154 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *llist)
1155 {
1156         vm_map_entry_t left, lo, y;
1157
1158         left = *llist;
1159         lo = root->left == left ? NULL : root->left;
1160         if (lo == NULL)
1161                 return;
1162         do
1163                 SPLAY_RIGHT_STEP(lo, y, left, root, true);
1164         while (lo != NULL);
1165         *llist = left;
1166 }
1167
1168 static inline void
1169 vm_map_entry_swap(vm_map_entry_t *a, vm_map_entry_t *b)
1170 {
1171         vm_map_entry_t tmp;
1172
1173         tmp = *b;
1174         *b = *a;
1175         *a = tmp;
1176 }
1177
1178 /*
1179  * Walk back up the two spines, flip the pointers and set max_free.  The
1180  * subtrees of the root go at the bottom of llist and rlist.
1181  */
1182 static vm_size_t
1183 vm_map_splay_merge_left_walk(vm_map_entry_t header, vm_map_entry_t root,
1184     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t llist)
1185 {
1186         do {
1187                 /*
1188                  * The max_free values of the children of llist are in
1189                  * llist->max_free and max_free.  Update with the
1190                  * max value.
1191                  */
1192                 llist->max_free = max_free =
1193                     vm_size_max(llist->max_free, max_free);
1194                 vm_map_entry_swap(&llist->right, &tail);
1195                 vm_map_entry_swap(&tail, &llist);
1196         } while (llist != header);
1197         root->left = tail;
1198         return (max_free);
1199 }
1200
1201 /*
1202  * When llist is known to be the predecessor of root.
1203  */
1204 static inline vm_size_t
1205 vm_map_splay_merge_pred(vm_map_entry_t header, vm_map_entry_t root,
1206     vm_map_entry_t llist)
1207 {
1208         vm_size_t max_free;
1209
1210         max_free = root->start - llist->end;
1211         if (llist != header) {
1212                 max_free = vm_map_splay_merge_left_walk(header, root,
1213                     root, max_free, llist);
1214         } else {
1215                 root->left = header;
1216                 header->right = root;
1217         }
1218         return (max_free);
1219 }
1220
1221 /*
1222  * When llist may or may not be the predecessor of root.
1223  */
1224 static inline vm_size_t
1225 vm_map_splay_merge_left(vm_map_entry_t header, vm_map_entry_t root,
1226     vm_map_entry_t llist)
1227 {
1228         vm_size_t max_free;
1229
1230         max_free = vm_map_entry_max_free_left(root, llist);
1231         if (llist != header) {
1232                 max_free = vm_map_splay_merge_left_walk(header, root,
1233                     root->left == llist ? root : root->left,
1234                     max_free, llist);
1235         }
1236         return (max_free);
1237 }
1238
1239 static vm_size_t
1240 vm_map_splay_merge_right_walk(vm_map_entry_t header, vm_map_entry_t root,
1241     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t rlist)
1242 {
1243         do {
1244                 /*
1245                  * The max_free values of the children of rlist are in
1246                  * rlist->max_free and max_free.  Update with the
1247                  * max value.
1248                  */
1249                 rlist->max_free = max_free =
1250                     vm_size_max(rlist->max_free, max_free);
1251                 vm_map_entry_swap(&rlist->left, &tail);
1252                 vm_map_entry_swap(&tail, &rlist);
1253         } while (rlist != header);
1254         root->right = tail;
1255         return (max_free);
1256 }
1257
1258 /*
1259  * When rlist is known to be the succecessor of root.
1260  */
1261 static inline vm_size_t
1262 vm_map_splay_merge_succ(vm_map_entry_t header, vm_map_entry_t root,
1263     vm_map_entry_t rlist)
1264 {
1265         vm_size_t max_free;
1266
1267         max_free = rlist->start - root->end;
1268         if (rlist != header) {
1269                 max_free = vm_map_splay_merge_right_walk(header, root,
1270                     root, max_free, rlist);
1271         } else {
1272                 root->right = header;
1273                 header->left = root;
1274         }
1275         return (max_free);
1276 }
1277
1278 /*
1279  * When rlist may or may not be the succecessor of root.
1280  */
1281 static inline vm_size_t
1282 vm_map_splay_merge_right(vm_map_entry_t header, vm_map_entry_t root,
1283     vm_map_entry_t rlist)
1284 {
1285         vm_size_t max_free;
1286
1287         max_free = vm_map_entry_max_free_right(root, rlist);
1288         if (rlist != header) {
1289                 max_free = vm_map_splay_merge_right_walk(header, root,
1290                     root->right == rlist ? root : root->right,
1291                     max_free, rlist);
1292         }
1293         return (max_free);
1294 }
1295
1296 /*
1297  *      vm_map_splay:
1298  *
1299  *      The Sleator and Tarjan top-down splay algorithm with the
1300  *      following variation.  Max_free must be computed bottom-up, so
1301  *      on the downward pass, maintain the left and right spines in
1302  *      reverse order.  Then, make a second pass up each side to fix
1303  *      the pointers and compute max_free.  The time bound is O(log n)
1304  *      amortized.
1305  *
1306  *      The tree is threaded, which means that there are no null pointers.
1307  *      When a node has no left child, its left pointer points to its
1308  *      predecessor, which the last ancestor on the search path from the root
1309  *      where the search branched right.  Likewise, when a node has no right
1310  *      child, its right pointer points to its successor.  The map header node
1311  *      is the predecessor of the first map entry, and the successor of the
1312  *      last.
1313  *
1314  *      The new root is the vm_map_entry containing "addr", or else an
1315  *      adjacent entry (lower if possible) if addr is not in the tree.
1316  *
1317  *      The map must be locked, and leaves it so.
1318  *
1319  *      Returns: the new root.
1320  */
1321 static vm_map_entry_t
1322 vm_map_splay(vm_map_t map, vm_offset_t addr)
1323 {
1324         vm_map_entry_t header, llist, rlist, root;
1325         vm_size_t max_free_left, max_free_right;
1326
1327         header = &map->header;
1328         root = vm_map_splay_split(map, addr, 0, &llist, &rlist);
1329         if (root != NULL) {
1330                 max_free_left = vm_map_splay_merge_left(header, root, llist);
1331                 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1332         } else if (llist != header) {
1333                 /*
1334                  * Recover the greatest node in the left
1335                  * subtree and make it the root.
1336                  */
1337                 root = llist;
1338                 llist = root->right;
1339                 max_free_left = vm_map_splay_merge_left(header, root, llist);
1340                 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1341         } else if (rlist != header) {
1342                 /*
1343                  * Recover the least node in the right
1344                  * subtree and make it the root.
1345                  */
1346                 root = rlist;
1347                 rlist = root->left;
1348                 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1349                 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1350         } else {
1351                 /* There is no root. */
1352                 return (NULL);
1353         }
1354         root->max_free = vm_size_max(max_free_left, max_free_right);
1355         map->root = root;
1356         VM_MAP_ASSERT_CONSISTENT(map);
1357         return (root);
1358 }
1359
1360 /*
1361  *      vm_map_entry_{un,}link:
1362  *
1363  *      Insert/remove entries from maps.  On linking, if new entry clips
1364  *      existing entry, trim existing entry to avoid overlap, and manage
1365  *      offsets.  On unlinking, merge disappearing entry with neighbor, if
1366  *      called for, and manage offsets.  Callers should not modify fields in
1367  *      entries already mapped.
1368  */
1369 static void
1370 vm_map_entry_link(vm_map_t map, vm_map_entry_t entry)
1371 {
1372         vm_map_entry_t header, llist, rlist, root;
1373         vm_size_t max_free_left, max_free_right;
1374
1375         CTR3(KTR_VM,
1376             "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1377             map->nentries, entry);
1378         VM_MAP_ASSERT_LOCKED(map);
1379         map->nentries++;
1380         header = &map->header;
1381         root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1382         if (root == NULL) {
1383                 /*
1384                  * The new entry does not overlap any existing entry in the
1385                  * map, so it becomes the new root of the map tree.
1386                  */
1387                 max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1388                 max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1389         } else if (entry->start == root->start) {
1390                 /*
1391                  * The new entry is a clone of root, with only the end field
1392                  * changed.  The root entry will be shrunk to abut the new
1393                  * entry, and will be the right child of the new root entry in
1394                  * the modified map.
1395                  */
1396                 KASSERT(entry->end < root->end,
1397                     ("%s: clip_start not within entry", __func__));
1398                 vm_map_splay_findprev(root, &llist);
1399                 root->offset += entry->end - root->start;
1400                 root->start = entry->end;
1401                 max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1402                 max_free_right = root->max_free = vm_size_max(
1403                     vm_map_splay_merge_pred(entry, root, entry),
1404                     vm_map_splay_merge_right(header, root, rlist));
1405         } else {
1406                 /*
1407                  * The new entry is a clone of root, with only the start field
1408                  * changed.  The root entry will be shrunk to abut the new
1409                  * entry, and will be the left child of the new root entry in
1410                  * the modified map.
1411                  */
1412                 KASSERT(entry->end == root->end,
1413                     ("%s: clip_start not within entry", __func__));
1414                 vm_map_splay_findnext(root, &rlist);
1415                 entry->offset += entry->start - root->start;
1416                 root->end = entry->start;
1417                 max_free_left = root->max_free = vm_size_max(
1418                     vm_map_splay_merge_left(header, root, llist),
1419                     vm_map_splay_merge_succ(entry, root, entry));
1420                 max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1421         }
1422         entry->max_free = vm_size_max(max_free_left, max_free_right);
1423         map->root = entry;
1424         VM_MAP_ASSERT_CONSISTENT(map);
1425 }
1426
1427 enum unlink_merge_type {
1428         UNLINK_MERGE_NONE,
1429         UNLINK_MERGE_NEXT
1430 };
1431
1432 static void
1433 vm_map_entry_unlink(vm_map_t map, vm_map_entry_t entry,
1434     enum unlink_merge_type op)
1435 {
1436         vm_map_entry_t header, llist, rlist, root;
1437         vm_size_t max_free_left, max_free_right;
1438
1439         VM_MAP_ASSERT_LOCKED(map);
1440         header = &map->header;
1441         root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1442         KASSERT(root != NULL,
1443             ("vm_map_entry_unlink: unlink object not mapped"));
1444
1445         vm_map_splay_findprev(root, &llist);
1446         vm_map_splay_findnext(root, &rlist);
1447         if (op == UNLINK_MERGE_NEXT) {
1448                 rlist->start = root->start;
1449                 rlist->offset = root->offset;
1450         }
1451         if (llist != header) {
1452                 root = llist;
1453                 llist = root->right;
1454                 max_free_left = vm_map_splay_merge_left(header, root, llist);
1455                 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1456         } else if (rlist != header) {
1457                 root = rlist;
1458                 rlist = root->left;
1459                 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1460                 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1461         } else {
1462                 header->left = header->right = header;
1463                 root = NULL;
1464         }
1465         if (root != NULL)
1466                 root->max_free = vm_size_max(max_free_left, max_free_right);
1467         map->root = root;
1468         VM_MAP_ASSERT_CONSISTENT(map);
1469         map->nentries--;
1470         CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1471             map->nentries, entry);
1472 }
1473
1474 /*
1475  *      vm_map_entry_resize:
1476  *
1477  *      Resize a vm_map_entry, recompute the amount of free space that
1478  *      follows it and propagate that value up the tree.
1479  *
1480  *      The map must be locked, and leaves it so.
1481  */
1482 static void
1483 vm_map_entry_resize(vm_map_t map, vm_map_entry_t entry, vm_size_t grow_amount)
1484 {
1485         vm_map_entry_t header, llist, rlist, root;
1486
1487         VM_MAP_ASSERT_LOCKED(map);
1488         header = &map->header;
1489         root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1490         KASSERT(root != NULL, ("%s: resize object not mapped", __func__));
1491         vm_map_splay_findnext(root, &rlist);
1492         entry->end += grow_amount;
1493         root->max_free = vm_size_max(
1494             vm_map_splay_merge_left(header, root, llist),
1495             vm_map_splay_merge_succ(header, root, rlist));
1496         map->root = root;
1497         VM_MAP_ASSERT_CONSISTENT(map);
1498         CTR4(KTR_VM, "%s: map %p, nentries %d, entry %p",
1499             __func__, map, map->nentries, entry);
1500 }
1501
1502 /*
1503  *      vm_map_lookup_entry:    [ internal use only ]
1504  *
1505  *      Finds the map entry containing (or
1506  *      immediately preceding) the specified address
1507  *      in the given map; the entry is returned
1508  *      in the "entry" parameter.  The boolean
1509  *      result indicates whether the address is
1510  *      actually contained in the map.
1511  */
1512 boolean_t
1513 vm_map_lookup_entry(
1514         vm_map_t map,
1515         vm_offset_t address,
1516         vm_map_entry_t *entry)  /* OUT */
1517 {
1518         vm_map_entry_t cur, header, lbound, ubound;
1519         boolean_t locked;
1520
1521         /*
1522          * If the map is empty, then the map entry immediately preceding
1523          * "address" is the map's header.
1524          */
1525         header = &map->header;
1526         cur = map->root;
1527         if (cur == NULL) {
1528                 *entry = header;
1529                 return (FALSE);
1530         }
1531         if (address >= cur->start && cur->end > address) {
1532                 *entry = cur;
1533                 return (TRUE);
1534         }
1535         if ((locked = vm_map_locked(map)) ||
1536             sx_try_upgrade(&map->lock)) {
1537                 /*
1538                  * Splay requires a write lock on the map.  However, it only
1539                  * restructures the binary search tree; it does not otherwise
1540                  * change the map.  Thus, the map's timestamp need not change
1541                  * on a temporary upgrade.
1542                  */
1543                 cur = vm_map_splay(map, address);
1544                 if (!locked) {
1545                         VM_MAP_UNLOCK_CONSISTENT(map);
1546                         sx_downgrade(&map->lock);
1547                 }
1548
1549                 /*
1550                  * If "address" is contained within a map entry, the new root
1551                  * is that map entry.  Otherwise, the new root is a map entry
1552                  * immediately before or after "address".
1553                  */
1554                 if (address < cur->start) {
1555                         *entry = header;
1556                         return (FALSE);
1557                 }
1558                 *entry = cur;
1559                 return (address < cur->end);
1560         }
1561         /*
1562          * Since the map is only locked for read access, perform a
1563          * standard binary search tree lookup for "address".
1564          */
1565         lbound = ubound = header;
1566         for (;;) {
1567                 if (address < cur->start) {
1568                         ubound = cur;
1569                         cur = cur->left;
1570                         if (cur == lbound)
1571                                 break;
1572                 } else if (cur->end <= address) {
1573                         lbound = cur;
1574                         cur = cur->right;
1575                         if (cur == ubound)
1576                                 break;
1577                 } else {
1578                         *entry = cur;
1579                         return (TRUE);
1580                 }
1581         }
1582         *entry = lbound;
1583         return (FALSE);
1584 }
1585
1586 /*
1587  *      vm_map_insert:
1588  *
1589  *      Inserts the given whole VM object into the target
1590  *      map at the specified address range.  The object's
1591  *      size should match that of the address range.
1592  *
1593  *      Requires that the map be locked, and leaves it so.
1594  *
1595  *      If object is non-NULL, ref count must be bumped by caller
1596  *      prior to making call to account for the new entry.
1597  */
1598 int
1599 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1600     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1601 {
1602         vm_map_entry_t new_entry, next_entry, prev_entry;
1603         struct ucred *cred;
1604         vm_eflags_t protoeflags;
1605         vm_inherit_t inheritance;
1606
1607         VM_MAP_ASSERT_LOCKED(map);
1608         KASSERT(object != kernel_object ||
1609             (cow & MAP_COPY_ON_WRITE) == 0,
1610             ("vm_map_insert: kernel object and COW"));
1611         KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1612             ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1613         KASSERT((prot & ~max) == 0,
1614             ("prot %#x is not subset of max_prot %#x", prot, max));
1615
1616         /*
1617          * Check that the start and end points are not bogus.
1618          */
1619         if (start == end || !vm_map_range_valid(map, start, end))
1620                 return (KERN_INVALID_ADDRESS);
1621
1622         /*
1623          * Find the entry prior to the proposed starting address; if it's part
1624          * of an existing entry, this range is bogus.
1625          */
1626         if (vm_map_lookup_entry(map, start, &prev_entry))
1627                 return (KERN_NO_SPACE);
1628
1629         /*
1630          * Assert that the next entry doesn't overlap the end point.
1631          */
1632         next_entry = vm_map_entry_succ(prev_entry);
1633         if (next_entry->start < end)
1634                 return (KERN_NO_SPACE);
1635
1636         if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1637             max != VM_PROT_NONE))
1638                 return (KERN_INVALID_ARGUMENT);
1639
1640         protoeflags = 0;
1641         if (cow & MAP_COPY_ON_WRITE)
1642                 protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1643         if (cow & MAP_NOFAULT)
1644                 protoeflags |= MAP_ENTRY_NOFAULT;
1645         if (cow & MAP_DISABLE_SYNCER)
1646                 protoeflags |= MAP_ENTRY_NOSYNC;
1647         if (cow & MAP_DISABLE_COREDUMP)
1648                 protoeflags |= MAP_ENTRY_NOCOREDUMP;
1649         if (cow & MAP_STACK_GROWS_DOWN)
1650                 protoeflags |= MAP_ENTRY_GROWS_DOWN;
1651         if (cow & MAP_STACK_GROWS_UP)
1652                 protoeflags |= MAP_ENTRY_GROWS_UP;
1653         if (cow & MAP_WRITECOUNT)
1654                 protoeflags |= MAP_ENTRY_WRITECNT;
1655         if (cow & MAP_VN_EXEC)
1656                 protoeflags |= MAP_ENTRY_VN_EXEC;
1657         if ((cow & MAP_CREATE_GUARD) != 0)
1658                 protoeflags |= MAP_ENTRY_GUARD;
1659         if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1660                 protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1661         if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1662                 protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1663         if (cow & MAP_INHERIT_SHARE)
1664                 inheritance = VM_INHERIT_SHARE;
1665         else
1666                 inheritance = VM_INHERIT_DEFAULT;
1667
1668         cred = NULL;
1669         if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1670                 goto charged;
1671         if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1672             ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1673                 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1674                         return (KERN_RESOURCE_SHORTAGE);
1675                 KASSERT(object == NULL ||
1676                     (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1677                     object->cred == NULL,
1678                     ("overcommit: vm_map_insert o %p", object));
1679                 cred = curthread->td_ucred;
1680         }
1681
1682 charged:
1683         /* Expand the kernel pmap, if necessary. */
1684         if (map == kernel_map && end > kernel_vm_end)
1685                 pmap_growkernel(end);
1686         if (object != NULL) {
1687                 /*
1688                  * OBJ_ONEMAPPING must be cleared unless this mapping
1689                  * is trivially proven to be the only mapping for any
1690                  * of the object's pages.  (Object granularity
1691                  * reference counting is insufficient to recognize
1692                  * aliases with precision.)
1693                  */
1694                 if ((object->flags & OBJ_ANON) != 0) {
1695                         VM_OBJECT_WLOCK(object);
1696                         if (object->ref_count > 1 || object->shadow_count != 0)
1697                                 vm_object_clear_flag(object, OBJ_ONEMAPPING);
1698                         VM_OBJECT_WUNLOCK(object);
1699                 }
1700         } else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1701             protoeflags &&
1702             (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1703             MAP_VN_EXEC)) == 0 &&
1704             prev_entry->end == start && (prev_entry->cred == cred ||
1705             (prev_entry->object.vm_object != NULL &&
1706             prev_entry->object.vm_object->cred == cred)) &&
1707             vm_object_coalesce(prev_entry->object.vm_object,
1708             prev_entry->offset,
1709             (vm_size_t)(prev_entry->end - prev_entry->start),
1710             (vm_size_t)(end - prev_entry->end), cred != NULL &&
1711             (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1712                 /*
1713                  * We were able to extend the object.  Determine if we
1714                  * can extend the previous map entry to include the
1715                  * new range as well.
1716                  */
1717                 if (prev_entry->inheritance == inheritance &&
1718                     prev_entry->protection == prot &&
1719                     prev_entry->max_protection == max &&
1720                     prev_entry->wired_count == 0) {
1721                         KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1722                             0, ("prev_entry %p has incoherent wiring",
1723                             prev_entry));
1724                         if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1725                                 map->size += end - prev_entry->end;
1726                         vm_map_entry_resize(map, prev_entry,
1727                             end - prev_entry->end);
1728                         vm_map_try_merge_entries(map, prev_entry, next_entry);
1729                         return (KERN_SUCCESS);
1730                 }
1731
1732                 /*
1733                  * If we can extend the object but cannot extend the
1734                  * map entry, we have to create a new map entry.  We
1735                  * must bump the ref count on the extended object to
1736                  * account for it.  object may be NULL.
1737                  */
1738                 object = prev_entry->object.vm_object;
1739                 offset = prev_entry->offset +
1740                     (prev_entry->end - prev_entry->start);
1741                 vm_object_reference(object);
1742                 if (cred != NULL && object != NULL && object->cred != NULL &&
1743                     !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1744                         /* Object already accounts for this uid. */
1745                         cred = NULL;
1746                 }
1747         }
1748         if (cred != NULL)
1749                 crhold(cred);
1750
1751         /*
1752          * Create a new entry
1753          */
1754         new_entry = vm_map_entry_create(map);
1755         new_entry->start = start;
1756         new_entry->end = end;
1757         new_entry->cred = NULL;
1758
1759         new_entry->eflags = protoeflags;
1760         new_entry->object.vm_object = object;
1761         new_entry->offset = offset;
1762
1763         new_entry->inheritance = inheritance;
1764         new_entry->protection = prot;
1765         new_entry->max_protection = max;
1766         new_entry->wired_count = 0;
1767         new_entry->wiring_thread = NULL;
1768         new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1769         new_entry->next_read = start;
1770
1771         KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1772             ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1773         new_entry->cred = cred;
1774
1775         /*
1776          * Insert the new entry into the list
1777          */
1778         vm_map_entry_link(map, new_entry);
1779         if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1780                 map->size += new_entry->end - new_entry->start;
1781
1782         /*
1783          * Try to coalesce the new entry with both the previous and next
1784          * entries in the list.  Previously, we only attempted to coalesce
1785          * with the previous entry when object is NULL.  Here, we handle the
1786          * other cases, which are less common.
1787          */
1788         vm_map_try_merge_entries(map, prev_entry, new_entry);
1789         vm_map_try_merge_entries(map, new_entry, next_entry);
1790
1791         if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1792                 vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1793                     end - start, cow & MAP_PREFAULT_PARTIAL);
1794         }
1795
1796         return (KERN_SUCCESS);
1797 }
1798
1799 /*
1800  *      vm_map_findspace:
1801  *
1802  *      Find the first fit (lowest VM address) for "length" free bytes
1803  *      beginning at address >= start in the given map.
1804  *
1805  *      In a vm_map_entry, "max_free" is the maximum amount of
1806  *      contiguous free space between an entry in its subtree and a
1807  *      neighbor of that entry.  This allows finding a free region in
1808  *      one path down the tree, so O(log n) amortized with splay
1809  *      trees.
1810  *
1811  *      The map must be locked, and leaves it so.
1812  *
1813  *      Returns: starting address if sufficient space,
1814  *               vm_map_max(map)-length+1 if insufficient space.
1815  */
1816 vm_offset_t
1817 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1818 {
1819         vm_map_entry_t header, llist, rlist, root, y;
1820         vm_size_t left_length, max_free_left, max_free_right;
1821         vm_offset_t gap_end;
1822
1823         /*
1824          * Request must fit within min/max VM address and must avoid
1825          * address wrap.
1826          */
1827         start = MAX(start, vm_map_min(map));
1828         if (start >= vm_map_max(map) || length > vm_map_max(map) - start)
1829                 return (vm_map_max(map) - length + 1);
1830
1831         /* Empty tree means wide open address space. */
1832         if (map->root == NULL)
1833                 return (start);
1834
1835         /*
1836          * After splay_split, if start is within an entry, push it to the start
1837          * of the following gap.  If rlist is at the end of the gap containing
1838          * start, save the end of that gap in gap_end to see if the gap is big
1839          * enough; otherwise set gap_end to start skip gap-checking and move
1840          * directly to a search of the right subtree.
1841          */
1842         header = &map->header;
1843         root = vm_map_splay_split(map, start, length, &llist, &rlist);
1844         gap_end = rlist->start;
1845         if (root != NULL) {
1846                 start = root->end;
1847                 if (root->right != rlist)
1848                         gap_end = start;
1849                 max_free_left = vm_map_splay_merge_left(header, root, llist);
1850                 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1851         } else if (rlist != header) {
1852                 root = rlist;
1853                 rlist = root->left;
1854                 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1855                 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1856         } else {
1857                 root = llist;
1858                 llist = root->right;
1859                 max_free_left = vm_map_splay_merge_left(header, root, llist);
1860                 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1861         }
1862         root->max_free = vm_size_max(max_free_left, max_free_right);
1863         map->root = root;
1864         VM_MAP_ASSERT_CONSISTENT(map);
1865         if (length <= gap_end - start)
1866                 return (start);
1867
1868         /* With max_free, can immediately tell if no solution. */
1869         if (root->right == header || length > root->right->max_free)
1870                 return (vm_map_max(map) - length + 1);
1871
1872         /*
1873          * Splay for the least large-enough gap in the right subtree.
1874          */
1875         llist = rlist = header;
1876         for (left_length = 0;;
1877             left_length = vm_map_entry_max_free_left(root, llist)) {
1878                 if (length <= left_length)
1879                         SPLAY_LEFT_STEP(root, y, llist, rlist,
1880                             length <= vm_map_entry_max_free_left(y, llist));
1881                 else
1882                         SPLAY_RIGHT_STEP(root, y, llist, rlist,
1883                             length > vm_map_entry_max_free_left(y, root));
1884                 if (root == NULL)
1885                         break;
1886         }
1887         root = llist;
1888         llist = root->right;
1889         max_free_left = vm_map_splay_merge_left(header, root, llist);
1890         if (rlist == header) {
1891                 root->max_free = vm_size_max(max_free_left,
1892                     vm_map_splay_merge_succ(header, root, rlist));
1893         } else {
1894                 y = rlist;
1895                 rlist = y->left;
1896                 y->max_free = vm_size_max(
1897                     vm_map_splay_merge_pred(root, y, root),
1898                     vm_map_splay_merge_right(header, y, rlist));
1899                 root->max_free = vm_size_max(max_free_left, y->max_free);
1900         }
1901         map->root = root;
1902         VM_MAP_ASSERT_CONSISTENT(map);
1903         return (root->end);
1904 }
1905
1906 int
1907 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1908     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1909     vm_prot_t max, int cow)
1910 {
1911         vm_offset_t end;
1912         int result;
1913
1914         end = start + length;
1915         KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1916             object == NULL,
1917             ("vm_map_fixed: non-NULL backing object for stack"));
1918         vm_map_lock(map);
1919         VM_MAP_RANGE_CHECK(map, start, end);
1920         if ((cow & MAP_CHECK_EXCL) == 0)
1921                 vm_map_delete(map, start, end);
1922         if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1923                 result = vm_map_stack_locked(map, start, length, sgrowsiz,
1924                     prot, max, cow);
1925         } else {
1926                 result = vm_map_insert(map, object, offset, start, end,
1927                     prot, max, cow);
1928         }
1929         vm_map_unlock(map);
1930         return (result);
1931 }
1932
1933 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1934 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1935
1936 static int cluster_anon = 1;
1937 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1938     &cluster_anon, 0,
1939     "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1940
1941 static bool
1942 clustering_anon_allowed(vm_offset_t addr)
1943 {
1944
1945         switch (cluster_anon) {
1946         case 0:
1947                 return (false);
1948         case 1:
1949                 return (addr == 0);
1950         case 2:
1951         default:
1952                 return (true);
1953         }
1954 }
1955
1956 static long aslr_restarts;
1957 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
1958     &aslr_restarts, 0,
1959     "Number of aslr failures");
1960
1961 #define MAP_32BIT_MAX_ADDR      ((vm_offset_t)1 << 31)
1962
1963 /*
1964  * Searches for the specified amount of free space in the given map with the
1965  * specified alignment.  Performs an address-ordered, first-fit search from
1966  * the given address "*addr", with an optional upper bound "max_addr".  If the
1967  * parameter "alignment" is zero, then the alignment is computed from the
1968  * given (object, offset) pair so as to enable the greatest possible use of
1969  * superpage mappings.  Returns KERN_SUCCESS and the address of the free space
1970  * in "*addr" if successful.  Otherwise, returns KERN_NO_SPACE.
1971  *
1972  * The map must be locked.  Initially, there must be at least "length" bytes
1973  * of free space at the given address.
1974  */
1975 static int
1976 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1977     vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
1978     vm_offset_t alignment)
1979 {
1980         vm_offset_t aligned_addr, free_addr;
1981
1982         VM_MAP_ASSERT_LOCKED(map);
1983         free_addr = *addr;
1984         KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
1985             ("caller failed to provide space %#jx at address %p",
1986              (uintmax_t)length, (void *)free_addr));
1987         for (;;) {
1988                 /*
1989                  * At the start of every iteration, the free space at address
1990                  * "*addr" is at least "length" bytes.
1991                  */
1992                 if (alignment == 0)
1993                         pmap_align_superpage(object, offset, addr, length);
1994                 else if ((*addr & (alignment - 1)) != 0) {
1995                         *addr &= ~(alignment - 1);
1996                         *addr += alignment;
1997                 }
1998                 aligned_addr = *addr;
1999                 if (aligned_addr == free_addr) {
2000                         /*
2001                          * Alignment did not change "*addr", so "*addr" must
2002                          * still provide sufficient free space.
2003                          */
2004                         return (KERN_SUCCESS);
2005                 }
2006
2007                 /*
2008                  * Test for address wrap on "*addr".  A wrapped "*addr" could
2009                  * be a valid address, in which case vm_map_findspace() cannot
2010                  * be relied upon to fail.
2011                  */
2012                 if (aligned_addr < free_addr)
2013                         return (KERN_NO_SPACE);
2014                 *addr = vm_map_findspace(map, aligned_addr, length);
2015                 if (*addr + length > vm_map_max(map) ||
2016                     (max_addr != 0 && *addr + length > max_addr))
2017                         return (KERN_NO_SPACE);
2018                 free_addr = *addr;
2019                 if (free_addr == aligned_addr) {
2020                         /*
2021                          * If a successful call to vm_map_findspace() did not
2022                          * change "*addr", then "*addr" must still be aligned
2023                          * and provide sufficient free space.
2024                          */
2025                         return (KERN_SUCCESS);
2026                 }
2027         }
2028 }
2029
2030 /*
2031  *      vm_map_find finds an unallocated region in the target address
2032  *      map with the given length.  The search is defined to be
2033  *      first-fit from the specified address; the region found is
2034  *      returned in the same parameter.
2035  *
2036  *      If object is non-NULL, ref count must be bumped by caller
2037  *      prior to making call to account for the new entry.
2038  */
2039 int
2040 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2041             vm_offset_t *addr,  /* IN/OUT */
2042             vm_size_t length, vm_offset_t max_addr, int find_space,
2043             vm_prot_t prot, vm_prot_t max, int cow)
2044 {
2045         vm_offset_t alignment, curr_min_addr, min_addr;
2046         int gap, pidx, rv, try;
2047         bool cluster, en_aslr, update_anon;
2048
2049         KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
2050             object == NULL,
2051             ("vm_map_find: non-NULL backing object for stack"));
2052         MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
2053             (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
2054         if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
2055             (object->flags & OBJ_COLORED) == 0))
2056                 find_space = VMFS_ANY_SPACE;
2057         if (find_space >> 8 != 0) {
2058                 KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
2059                 alignment = (vm_offset_t)1 << (find_space >> 8);
2060         } else
2061                 alignment = 0;
2062         en_aslr = (map->flags & MAP_ASLR) != 0;
2063         update_anon = cluster = clustering_anon_allowed(*addr) &&
2064             (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
2065             find_space != VMFS_NO_SPACE && object == NULL &&
2066             (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
2067             MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
2068         curr_min_addr = min_addr = *addr;
2069         if (en_aslr && min_addr == 0 && !cluster &&
2070             find_space != VMFS_NO_SPACE &&
2071             (map->flags & MAP_ASLR_IGNSTART) != 0)
2072                 curr_min_addr = min_addr = vm_map_min(map);
2073         try = 0;
2074         vm_map_lock(map);
2075         if (cluster) {
2076                 curr_min_addr = map->anon_loc;
2077                 if (curr_min_addr == 0)
2078                         cluster = false;
2079         }
2080         if (find_space != VMFS_NO_SPACE) {
2081                 KASSERT(find_space == VMFS_ANY_SPACE ||
2082                     find_space == VMFS_OPTIMAL_SPACE ||
2083                     find_space == VMFS_SUPER_SPACE ||
2084                     alignment != 0, ("unexpected VMFS flag"));
2085 again:
2086                 /*
2087                  * When creating an anonymous mapping, try clustering
2088                  * with an existing anonymous mapping first.
2089                  *
2090                  * We make up to two attempts to find address space
2091                  * for a given find_space value. The first attempt may
2092                  * apply randomization or may cluster with an existing
2093                  * anonymous mapping. If this first attempt fails,
2094                  * perform a first-fit search of the available address
2095                  * space.
2096                  *
2097                  * If all tries failed, and find_space is
2098                  * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
2099                  * Again enable clustering and randomization.
2100                  */
2101                 try++;
2102                 MPASS(try <= 2);
2103
2104                 if (try == 2) {
2105                         /*
2106                          * Second try: we failed either to find a
2107                          * suitable region for randomizing the
2108                          * allocation, or to cluster with an existing
2109                          * mapping.  Retry with free run.
2110                          */
2111                         curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
2112                             vm_map_min(map) : min_addr;
2113                         atomic_add_long(&aslr_restarts, 1);
2114                 }
2115
2116                 if (try == 1 && en_aslr && !cluster) {
2117                         /*
2118                          * Find space for allocation, including
2119                          * gap needed for later randomization.
2120                          */
2121                         pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
2122                             (find_space == VMFS_SUPER_SPACE || find_space ==
2123                             VMFS_OPTIMAL_SPACE) ? 1 : 0;
2124                         gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
2125                             (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
2126                             aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
2127                         *addr = vm_map_findspace(map, curr_min_addr,
2128                             length + gap * pagesizes[pidx]);
2129                         if (*addr + length + gap * pagesizes[pidx] >
2130                             vm_map_max(map))
2131                                 goto again;
2132                         /* And randomize the start address. */
2133                         *addr += (arc4random() % gap) * pagesizes[pidx];
2134                         if (max_addr != 0 && *addr + length > max_addr)
2135                                 goto again;
2136                 } else {
2137                         *addr = vm_map_findspace(map, curr_min_addr, length);
2138                         if (*addr + length > vm_map_max(map) ||
2139                             (max_addr != 0 && *addr + length > max_addr)) {
2140                                 if (cluster) {
2141                                         cluster = false;
2142                                         MPASS(try == 1);
2143                                         goto again;
2144                                 }
2145                                 rv = KERN_NO_SPACE;
2146                                 goto done;
2147                         }
2148                 }
2149
2150                 if (find_space != VMFS_ANY_SPACE &&
2151                     (rv = vm_map_alignspace(map, object, offset, addr, length,
2152                     max_addr, alignment)) != KERN_SUCCESS) {
2153                         if (find_space == VMFS_OPTIMAL_SPACE) {
2154                                 find_space = VMFS_ANY_SPACE;
2155                                 curr_min_addr = min_addr;
2156                                 cluster = update_anon;
2157                                 try = 0;
2158                                 goto again;
2159                         }
2160                         goto done;
2161                 }
2162         } else if ((cow & MAP_REMAP) != 0) {
2163                 if (!vm_map_range_valid(map, *addr, *addr + length)) {
2164                         rv = KERN_INVALID_ADDRESS;
2165                         goto done;
2166                 }
2167                 vm_map_delete(map, *addr, *addr + length);
2168         }
2169         if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
2170                 rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
2171                     max, cow);
2172         } else {
2173                 rv = vm_map_insert(map, object, offset, *addr, *addr + length,
2174                     prot, max, cow);
2175         }
2176         if (rv == KERN_SUCCESS && update_anon)
2177                 map->anon_loc = *addr + length;
2178 done:
2179         vm_map_unlock(map);
2180         return (rv);
2181 }
2182
2183 /*
2184  *      vm_map_find_min() is a variant of vm_map_find() that takes an
2185  *      additional parameter (min_addr) and treats the given address
2186  *      (*addr) differently.  Specifically, it treats *addr as a hint
2187  *      and not as the minimum address where the mapping is created.
2188  *
2189  *      This function works in two phases.  First, it tries to
2190  *      allocate above the hint.  If that fails and the hint is
2191  *      greater than min_addr, it performs a second pass, replacing
2192  *      the hint with min_addr as the minimum address for the
2193  *      allocation.
2194  */
2195 int
2196 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2197     vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
2198     vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
2199     int cow)
2200 {
2201         vm_offset_t hint;
2202         int rv;
2203
2204         hint = *addr;
2205         for (;;) {
2206                 rv = vm_map_find(map, object, offset, addr, length, max_addr,
2207                     find_space, prot, max, cow);
2208                 if (rv == KERN_SUCCESS || min_addr >= hint)
2209                         return (rv);
2210                 *addr = hint = min_addr;
2211         }
2212 }
2213
2214 /*
2215  * A map entry with any of the following flags set must not be merged with
2216  * another entry.
2217  */
2218 #define MAP_ENTRY_NOMERGE_MASK  (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
2219             MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
2220
2221 static bool
2222 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
2223 {
2224
2225         KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
2226             (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
2227             ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
2228             prev, entry));
2229         return (prev->end == entry->start &&
2230             prev->object.vm_object == entry->object.vm_object &&
2231             (prev->object.vm_object == NULL ||
2232             prev->offset + (prev->end - prev->start) == entry->offset) &&
2233             prev->eflags == entry->eflags &&
2234             prev->protection == entry->protection &&
2235             prev->max_protection == entry->max_protection &&
2236             prev->inheritance == entry->inheritance &&
2237             prev->wired_count == entry->wired_count &&
2238             prev->cred == entry->cred);
2239 }
2240
2241 static void
2242 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2243 {
2244
2245         /*
2246          * If the backing object is a vnode object, vm_object_deallocate()
2247          * calls vrele().  However, vrele() does not lock the vnode because
2248          * the vnode has additional references.  Thus, the map lock can be
2249          * kept without causing a lock-order reversal with the vnode lock.
2250          *
2251          * Since we count the number of virtual page mappings in
2252          * object->un_pager.vnp.writemappings, the writemappings value
2253          * should not be adjusted when the entry is disposed of.
2254          */
2255         if (entry->object.vm_object != NULL)
2256                 vm_object_deallocate(entry->object.vm_object);
2257         if (entry->cred != NULL)
2258                 crfree(entry->cred);
2259         vm_map_entry_dispose(map, entry);
2260 }
2261
2262 /*
2263  *      vm_map_try_merge_entries:
2264  *
2265  *      Compare the given map entry to its predecessor, and merge its precessor
2266  *      into it if possible.  The entry remains valid, and may be extended.
2267  *      The predecessor may be deleted.
2268  *
2269  *      The map must be locked.
2270  */
2271 void
2272 vm_map_try_merge_entries(vm_map_t map, vm_map_entry_t prev_entry,
2273     vm_map_entry_t entry)
2274 {
2275
2276         VM_MAP_ASSERT_LOCKED(map);
2277         if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 &&
2278             vm_map_mergeable_neighbors(prev_entry, entry)) {
2279                 vm_map_entry_unlink(map, prev_entry, UNLINK_MERGE_NEXT);
2280                 vm_map_merged_neighbor_dispose(map, prev_entry);
2281         }
2282 }
2283
2284 /*
2285  *      vm_map_entry_back:
2286  *
2287  *      Allocate an object to back a map entry.
2288  */
2289 static inline void
2290 vm_map_entry_back(vm_map_entry_t entry)
2291 {
2292         vm_object_t object;
2293
2294         KASSERT(entry->object.vm_object == NULL,
2295             ("map entry %p has backing object", entry));
2296         KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2297             ("map entry %p is a submap", entry));
2298         object = vm_object_allocate_anon(atop(entry->end - entry->start), NULL,
2299             entry->cred, entry->end - entry->start);
2300         entry->object.vm_object = object;
2301         entry->offset = 0;
2302         entry->cred = NULL;
2303 }
2304
2305 /*
2306  *      vm_map_entry_charge_object
2307  *
2308  *      If there is no object backing this entry, create one.  Otherwise, if
2309  *      the entry has cred, give it to the backing object.
2310  */
2311 static inline void
2312 vm_map_entry_charge_object(vm_map_t map, vm_map_entry_t entry)
2313 {
2314
2315         VM_MAP_ASSERT_LOCKED(map);
2316         KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2317             ("map entry %p is a submap", entry));
2318         if (entry->object.vm_object == NULL && !map->system_map &&
2319             (entry->eflags & MAP_ENTRY_GUARD) == 0)
2320                 vm_map_entry_back(entry);
2321         else if (entry->object.vm_object != NULL &&
2322             ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2323             entry->cred != NULL) {
2324                 VM_OBJECT_WLOCK(entry->object.vm_object);
2325                 KASSERT(entry->object.vm_object->cred == NULL,
2326                     ("OVERCOMMIT: %s: both cred e %p", __func__, entry));
2327                 entry->object.vm_object->cred = entry->cred;
2328                 entry->object.vm_object->charge = entry->end - entry->start;
2329                 VM_OBJECT_WUNLOCK(entry->object.vm_object);
2330                 entry->cred = NULL;
2331         }
2332 }
2333
2334 /*
2335  *      vm_map_entry_clone
2336  *
2337  *      Create a duplicate map entry for clipping.
2338  */
2339 static vm_map_entry_t
2340 vm_map_entry_clone(vm_map_t map, vm_map_entry_t entry)
2341 {
2342         vm_map_entry_t new_entry;
2343
2344         VM_MAP_ASSERT_LOCKED(map);
2345
2346         /*
2347          * Create a backing object now, if none exists, so that more individual
2348          * objects won't be created after the map entry is split.
2349          */
2350         vm_map_entry_charge_object(map, entry);
2351
2352         /* Clone the entry. */
2353         new_entry = vm_map_entry_create(map);
2354         *new_entry = *entry;
2355         if (new_entry->cred != NULL)
2356                 crhold(entry->cred);
2357         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2358                 vm_object_reference(new_entry->object.vm_object);
2359                 vm_map_entry_set_vnode_text(new_entry, true);
2360                 /*
2361                  * The object->un_pager.vnp.writemappings for the object of
2362                  * MAP_ENTRY_WRITECNT type entry shall be kept as is here.  The
2363                  * virtual pages are re-distributed among the clipped entries,
2364                  * so the sum is left the same.
2365                  */
2366         }
2367         return (new_entry);
2368 }
2369
2370 /*
2371  *      vm_map_clip_start:      [ internal use only ]
2372  *
2373  *      Asserts that the given entry begins at or after
2374  *      the specified address; if necessary,
2375  *      it splits the entry into two.
2376  */
2377 static inline void
2378 vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
2379 {
2380         vm_map_entry_t new_entry;
2381
2382         if (start <= entry->start)
2383                 return;
2384
2385         VM_MAP_ASSERT_LOCKED(map);
2386         KASSERT(entry->end > start && entry->start < start,
2387             ("%s: invalid clip of entry %p", __func__, entry));
2388
2389         new_entry = vm_map_entry_clone(map, entry);
2390
2391         /*
2392          * Split off the front portion.  Insert the new entry BEFORE this one,
2393          * so that this entry has the specified starting address.
2394          */
2395         new_entry->end = start;
2396         vm_map_entry_link(map, new_entry);
2397 }
2398
2399 /*
2400  *      vm_map_lookup_clip_start:
2401  *
2402  *      Find the entry at or just after 'start', and clip it if 'start' is in
2403  *      the interior of the entry.  Return entry after 'start', and in
2404  *      prev_entry set the entry before 'start'.
2405  */
2406 static inline vm_map_entry_t
2407 vm_map_lookup_clip_start(vm_map_t map, vm_offset_t start,
2408     vm_map_entry_t *prev_entry)
2409 {
2410         vm_map_entry_t entry;
2411
2412         if (vm_map_lookup_entry(map, start, prev_entry)) {
2413                 entry = *prev_entry;
2414                 vm_map_clip_start(map, entry, start);
2415                 *prev_entry = vm_map_entry_pred(entry);
2416         } else
2417                 entry = vm_map_entry_succ(*prev_entry);
2418         return (entry);
2419 }
2420
2421 /*
2422  *      vm_map_clip_end:        [ internal use only ]
2423  *
2424  *      Asserts that the given entry ends at or before
2425  *      the specified address; if necessary,
2426  *      it splits the entry into two.
2427  */
2428 static inline void
2429 vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
2430 {
2431         vm_map_entry_t new_entry;
2432
2433         if (end >= entry->end)
2434                 return;
2435
2436         VM_MAP_ASSERT_LOCKED(map);
2437         KASSERT(entry->start < end && entry->end > end,
2438             ("%s: invalid clip of entry %p", __func__, entry));
2439
2440         new_entry = vm_map_entry_clone(map, entry);
2441
2442         /*
2443          * Split off the back portion.  Insert the new entry AFTER this one,
2444          * so that this entry has the specified ending address.
2445          */
2446         new_entry->start = end;
2447         vm_map_entry_link(map, new_entry);
2448 }
2449
2450 /*
2451  *      vm_map_submap:          [ kernel use only ]
2452  *
2453  *      Mark the given range as handled by a subordinate map.
2454  *
2455  *      This range must have been created with vm_map_find,
2456  *      and no other operations may have been performed on this
2457  *      range prior to calling vm_map_submap.
2458  *
2459  *      Only a limited number of operations can be performed
2460  *      within this rage after calling vm_map_submap:
2461  *              vm_fault
2462  *      [Don't try vm_map_copy!]
2463  *
2464  *      To remove a submapping, one must first remove the
2465  *      range from the superior map, and then destroy the
2466  *      submap (if desired).  [Better yet, don't try it.]
2467  */
2468 int
2469 vm_map_submap(
2470         vm_map_t map,
2471         vm_offset_t start,
2472         vm_offset_t end,
2473         vm_map_t submap)
2474 {
2475         vm_map_entry_t entry;
2476         int result;
2477
2478         result = KERN_INVALID_ARGUMENT;
2479
2480         vm_map_lock(submap);
2481         submap->flags |= MAP_IS_SUB_MAP;
2482         vm_map_unlock(submap);
2483
2484         vm_map_lock(map);
2485         VM_MAP_RANGE_CHECK(map, start, end);
2486         if (vm_map_lookup_entry(map, start, &entry) && entry->end >= end &&
2487             (entry->eflags & MAP_ENTRY_COW) == 0 &&
2488             entry->object.vm_object == NULL) {
2489                 vm_map_clip_start(map, entry, start);
2490                 vm_map_clip_end(map, entry, end);
2491                 entry->object.sub_map = submap;
2492                 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2493                 result = KERN_SUCCESS;
2494         }
2495         vm_map_unlock(map);
2496
2497         if (result != KERN_SUCCESS) {
2498                 vm_map_lock(submap);
2499                 submap->flags &= ~MAP_IS_SUB_MAP;
2500                 vm_map_unlock(submap);
2501         }
2502         return (result);
2503 }
2504
2505 /*
2506  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2507  */
2508 #define MAX_INIT_PT     96
2509
2510 /*
2511  *      vm_map_pmap_enter:
2512  *
2513  *      Preload the specified map's pmap with mappings to the specified
2514  *      object's memory-resident pages.  No further physical pages are
2515  *      allocated, and no further virtual pages are retrieved from secondary
2516  *      storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
2517  *      limited number of page mappings are created at the low-end of the
2518  *      specified address range.  (For this purpose, a superpage mapping
2519  *      counts as one page mapping.)  Otherwise, all resident pages within
2520  *      the specified address range are mapped.
2521  */
2522 static void
2523 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2524     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2525 {
2526         vm_offset_t start;
2527         vm_page_t p, p_start;
2528         vm_pindex_t mask, psize, threshold, tmpidx;
2529
2530         if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2531                 return;
2532         if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2533                 VM_OBJECT_WLOCK(object);
2534                 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2535                         pmap_object_init_pt(map->pmap, addr, object, pindex,
2536                             size);
2537                         VM_OBJECT_WUNLOCK(object);
2538                         return;
2539                 }
2540                 VM_OBJECT_LOCK_DOWNGRADE(object);
2541         } else
2542                 VM_OBJECT_RLOCK(object);
2543
2544         psize = atop(size);
2545         if (psize + pindex > object->size) {
2546                 if (pindex >= object->size) {
2547                         VM_OBJECT_RUNLOCK(object);
2548                         return;
2549                 }
2550                 psize = object->size - pindex;
2551         }
2552
2553         start = 0;
2554         p_start = NULL;
2555         threshold = MAX_INIT_PT;
2556
2557         p = vm_page_find_least(object, pindex);
2558         /*
2559          * Assert: the variable p is either (1) the page with the
2560          * least pindex greater than or equal to the parameter pindex
2561          * or (2) NULL.
2562          */
2563         for (;
2564              p != NULL && (tmpidx = p->pindex - pindex) < psize;
2565              p = TAILQ_NEXT(p, listq)) {
2566                 /*
2567                  * don't allow an madvise to blow away our really
2568                  * free pages allocating pv entries.
2569                  */
2570                 if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2571                     vm_page_count_severe()) ||
2572                     ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2573                     tmpidx >= threshold)) {
2574                         psize = tmpidx;
2575                         break;
2576                 }
2577                 if (vm_page_all_valid(p)) {
2578                         if (p_start == NULL) {
2579                                 start = addr + ptoa(tmpidx);
2580                                 p_start = p;
2581                         }
2582                         /* Jump ahead if a superpage mapping is possible. */
2583                         if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2584                             (pagesizes[p->psind] - 1)) == 0) {
2585                                 mask = atop(pagesizes[p->psind]) - 1;
2586                                 if (tmpidx + mask < psize &&
2587                                     vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2588                                         p += mask;
2589                                         threshold += mask;
2590                                 }
2591                         }
2592                 } else if (p_start != NULL) {
2593                         pmap_enter_object(map->pmap, start, addr +
2594                             ptoa(tmpidx), p_start, prot);
2595                         p_start = NULL;
2596                 }
2597         }
2598         if (p_start != NULL)
2599                 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2600                     p_start, prot);
2601         VM_OBJECT_RUNLOCK(object);
2602 }
2603
2604 /*
2605  *      vm_map_protect:
2606  *
2607  *      Sets the protection of the specified address
2608  *      region in the target map.  If "set_max" is
2609  *      specified, the maximum protection is to be set;
2610  *      otherwise, only the current protection is affected.
2611  */
2612 int
2613 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2614                vm_prot_t new_prot, boolean_t set_max)
2615 {
2616         vm_map_entry_t entry, first_entry, in_tran, prev_entry;
2617         vm_object_t obj;
2618         struct ucred *cred;
2619         vm_prot_t old_prot;
2620         int rv;
2621
2622         if (start == end)
2623                 return (KERN_SUCCESS);
2624
2625 again:
2626         in_tran = NULL;
2627         vm_map_lock(map);
2628
2629         /*
2630          * Ensure that we are not concurrently wiring pages.  vm_map_wire() may
2631          * need to fault pages into the map and will drop the map lock while
2632          * doing so, and the VM object may end up in an inconsistent state if we
2633          * update the protection on the map entry in between faults.
2634          */
2635         vm_map_wait_busy(map);
2636
2637         VM_MAP_RANGE_CHECK(map, start, end);
2638
2639         if (!vm_map_lookup_entry(map, start, &first_entry))
2640                 first_entry = vm_map_entry_succ(first_entry);
2641
2642         /*
2643          * Make a first pass to check for protection violations.
2644          */
2645         for (entry = first_entry; entry->start < end;
2646             entry = vm_map_entry_succ(entry)) {
2647                 if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
2648                         continue;
2649                 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
2650                         vm_map_unlock(map);
2651                         return (KERN_INVALID_ARGUMENT);
2652                 }
2653                 if ((new_prot & entry->max_protection) != new_prot) {
2654                         vm_map_unlock(map);
2655                         return (KERN_PROTECTION_FAILURE);
2656                 }
2657                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2658                         in_tran = entry;
2659         }
2660
2661         /*
2662          * Postpone the operation until all in-transition map entries have
2663          * stabilized.  An in-transition entry might already have its pages
2664          * wired and wired_count incremented, but not yet have its
2665          * MAP_ENTRY_USER_WIRED flag set.  In which case, we would fail to call
2666          * vm_fault_copy_entry() in the final loop below.
2667          */
2668         if (in_tran != NULL) {
2669                 in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2670                 vm_map_unlock_and_wait(map, 0);
2671                 goto again;
2672         }
2673
2674         /*
2675          * Before changing the protections, try to reserve swap space for any
2676          * private (i.e., copy-on-write) mappings that are transitioning from
2677          * read-only to read/write access.  If a reservation fails, break out
2678          * of this loop early and let the next loop simplify the entries, since
2679          * some may now be mergeable.
2680          */
2681         rv = KERN_SUCCESS;
2682         vm_map_clip_start(map, first_entry, start);
2683         for (entry = first_entry; entry->start < end;
2684             entry = vm_map_entry_succ(entry)) {
2685                 vm_map_clip_end(map, entry, end);
2686
2687                 if (set_max ||
2688                     ((new_prot & ~entry->protection) & VM_PROT_WRITE) == 0 ||
2689                     ENTRY_CHARGED(entry) ||
2690                     (entry->eflags & MAP_ENTRY_GUARD) != 0) {
2691                         continue;
2692                 }
2693
2694                 cred = curthread->td_ucred;
2695                 obj = entry->object.vm_object;
2696
2697                 if (obj == NULL ||
2698                     (entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0) {
2699                         if (!swap_reserve(entry->end - entry->start)) {
2700                                 rv = KERN_RESOURCE_SHORTAGE;
2701                                 end = entry->end;
2702                                 break;
2703                         }
2704                         crhold(cred);
2705                         entry->cred = cred;
2706                         continue;
2707                 }
2708
2709                 if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP)
2710                         continue;
2711                 VM_OBJECT_WLOCK(obj);
2712                 if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
2713                         VM_OBJECT_WUNLOCK(obj);
2714                         continue;
2715                 }
2716
2717                 /*
2718                  * Charge for the whole object allocation now, since
2719                  * we cannot distinguish between non-charged and
2720                  * charged clipped mapping of the same object later.
2721                  */
2722                 KASSERT(obj->charge == 0,
2723                     ("vm_map_protect: object %p overcharged (entry %p)",
2724                     obj, entry));
2725                 if (!swap_reserve(ptoa(obj->size))) {
2726                         VM_OBJECT_WUNLOCK(obj);
2727                         rv = KERN_RESOURCE_SHORTAGE;
2728                         end = entry->end;
2729                         break;
2730                 }
2731
2732                 crhold(cred);
2733                 obj->cred = cred;
2734                 obj->charge = ptoa(obj->size);
2735                 VM_OBJECT_WUNLOCK(obj);
2736         }
2737
2738         /*
2739          * If enough swap space was available, go back and fix up protections.
2740          * Otherwise, just simplify entries, since some may have been modified.
2741          * [Note that clipping is not necessary the second time.]
2742          */
2743         for (prev_entry = vm_map_entry_pred(first_entry), entry = first_entry;
2744             entry->start < end;
2745             vm_map_try_merge_entries(map, prev_entry, entry),
2746             prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2747                 if (rv != KERN_SUCCESS ||
2748                     (entry->eflags & MAP_ENTRY_GUARD) != 0)
2749                         continue;
2750
2751                 old_prot = entry->protection;
2752
2753                 if (set_max)
2754                         entry->protection =
2755                             (entry->max_protection = new_prot) &
2756                             old_prot;
2757                 else
2758                         entry->protection = new_prot;
2759
2760                 /*
2761                  * For user wired map entries, the normal lazy evaluation of
2762                  * write access upgrades through soft page faults is
2763                  * undesirable.  Instead, immediately copy any pages that are
2764                  * copy-on-write and enable write access in the physical map.
2765                  */
2766                 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2767                     (entry->protection & VM_PROT_WRITE) != 0 &&
2768                     (old_prot & VM_PROT_WRITE) == 0)
2769                         vm_fault_copy_entry(map, map, entry, entry, NULL);
2770
2771                 /*
2772                  * When restricting access, update the physical map.  Worry
2773                  * about copy-on-write here.
2774                  */
2775                 if ((old_prot & ~entry->protection) != 0) {
2776 #define MASK(entry)     (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2777                                                         VM_PROT_ALL)
2778                         pmap_protect(map->pmap, entry->start,
2779                             entry->end,
2780                             entry->protection & MASK(entry));
2781 #undef  MASK
2782                 }
2783         }
2784         vm_map_try_merge_entries(map, prev_entry, entry);
2785         vm_map_unlock(map);
2786         return (rv);
2787 }
2788
2789 /*
2790  *      vm_map_madvise:
2791  *
2792  *      This routine traverses a processes map handling the madvise
2793  *      system call.  Advisories are classified as either those effecting
2794  *      the vm_map_entry structure, or those effecting the underlying
2795  *      objects.
2796  */
2797 int
2798 vm_map_madvise(
2799         vm_map_t map,
2800         vm_offset_t start,
2801         vm_offset_t end,
2802         int behav)
2803 {
2804         vm_map_entry_t entry, prev_entry;
2805         bool modify_map;
2806
2807         /*
2808          * Some madvise calls directly modify the vm_map_entry, in which case
2809          * we need to use an exclusive lock on the map and we need to perform
2810          * various clipping operations.  Otherwise we only need a read-lock
2811          * on the map.
2812          */
2813         switch(behav) {
2814         case MADV_NORMAL:
2815         case MADV_SEQUENTIAL:
2816         case MADV_RANDOM:
2817         case MADV_NOSYNC:
2818         case MADV_AUTOSYNC:
2819         case MADV_NOCORE:
2820         case MADV_CORE:
2821                 if (start == end)
2822                         return (0);
2823                 modify_map = true;
2824                 vm_map_lock(map);
2825                 break;
2826         case MADV_WILLNEED:
2827         case MADV_DONTNEED:
2828         case MADV_FREE:
2829                 if (start == end)
2830                         return (0);
2831                 modify_map = false;
2832                 vm_map_lock_read(map);
2833                 break;
2834         default:
2835                 return (EINVAL);
2836         }
2837
2838         /*
2839          * Locate starting entry and clip if necessary.
2840          */
2841         VM_MAP_RANGE_CHECK(map, start, end);
2842
2843         if (modify_map) {
2844                 /*
2845                  * madvise behaviors that are implemented in the vm_map_entry.
2846                  *
2847                  * We clip the vm_map_entry so that behavioral changes are
2848                  * limited to the specified address range.
2849                  */
2850                 for (entry = vm_map_lookup_clip_start(map, start, &prev_entry);
2851                     entry->start < end;
2852                     prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2853                         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2854                                 continue;
2855
2856                         vm_map_clip_end(map, entry, end);
2857
2858                         switch (behav) {
2859                         case MADV_NORMAL:
2860                                 vm_map_entry_set_behavior(entry,
2861                                     MAP_ENTRY_BEHAV_NORMAL);
2862                                 break;
2863                         case MADV_SEQUENTIAL:
2864                                 vm_map_entry_set_behavior(entry,
2865                                     MAP_ENTRY_BEHAV_SEQUENTIAL);
2866                                 break;
2867                         case MADV_RANDOM:
2868                                 vm_map_entry_set_behavior(entry,
2869                                     MAP_ENTRY_BEHAV_RANDOM);
2870                                 break;
2871                         case MADV_NOSYNC:
2872                                 entry->eflags |= MAP_ENTRY_NOSYNC;
2873                                 break;
2874                         case MADV_AUTOSYNC:
2875                                 entry->eflags &= ~MAP_ENTRY_NOSYNC;
2876                                 break;
2877                         case MADV_NOCORE:
2878                                 entry->eflags |= MAP_ENTRY_NOCOREDUMP;
2879                                 break;
2880                         case MADV_CORE:
2881                                 entry->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2882                                 break;
2883                         default:
2884                                 break;
2885                         }
2886                         vm_map_try_merge_entries(map, prev_entry, entry);
2887                 }
2888                 vm_map_try_merge_entries(map, prev_entry, entry);
2889                 vm_map_unlock(map);
2890         } else {
2891                 vm_pindex_t pstart, pend;
2892
2893                 /*
2894                  * madvise behaviors that are implemented in the underlying
2895                  * vm_object.
2896                  *
2897                  * Since we don't clip the vm_map_entry, we have to clip
2898                  * the vm_object pindex and count.
2899                  */
2900                 if (!vm_map_lookup_entry(map, start, &entry))
2901                         entry = vm_map_entry_succ(entry);
2902                 for (; entry->start < end;
2903                     entry = vm_map_entry_succ(entry)) {
2904                         vm_offset_t useEnd, useStart;
2905
2906                         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2907                                 continue;
2908
2909                         /*
2910                          * MADV_FREE would otherwise rewind time to
2911                          * the creation of the shadow object.  Because
2912                          * we hold the VM map read-locked, neither the
2913                          * entry's object nor the presence of a
2914                          * backing object can change.
2915                          */
2916                         if (behav == MADV_FREE &&
2917                             entry->object.vm_object != NULL &&
2918                             entry->object.vm_object->backing_object != NULL)
2919                                 continue;
2920
2921                         pstart = OFF_TO_IDX(entry->offset);
2922                         pend = pstart + atop(entry->end - entry->start);
2923                         useStart = entry->start;
2924                         useEnd = entry->end;
2925
2926                         if (entry->start < start) {
2927                                 pstart += atop(start - entry->start);
2928                                 useStart = start;
2929                         }
2930                         if (entry->end > end) {
2931                                 pend -= atop(entry->end - end);
2932                                 useEnd = end;
2933                         }
2934
2935                         if (pstart >= pend)
2936                                 continue;
2937
2938                         /*
2939                          * Perform the pmap_advise() before clearing
2940                          * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2941                          * concurrent pmap operation, such as pmap_remove(),
2942                          * could clear a reference in the pmap and set
2943                          * PGA_REFERENCED on the page before the pmap_advise()
2944                          * had completed.  Consequently, the page would appear
2945                          * referenced based upon an old reference that
2946                          * occurred before this pmap_advise() ran.
2947                          */
2948                         if (behav == MADV_DONTNEED || behav == MADV_FREE)
2949                                 pmap_advise(map->pmap, useStart, useEnd,
2950                                     behav);
2951
2952                         vm_object_madvise(entry->object.vm_object, pstart,
2953                             pend, behav);
2954
2955                         /*
2956                          * Pre-populate paging structures in the
2957                          * WILLNEED case.  For wired entries, the
2958                          * paging structures are already populated.
2959                          */
2960                         if (behav == MADV_WILLNEED &&
2961                             entry->wired_count == 0) {
2962                                 vm_map_pmap_enter(map,
2963                                     useStart,
2964                                     entry->protection,
2965                                     entry->object.vm_object,
2966                                     pstart,
2967                                     ptoa(pend - pstart),
2968                                     MAP_PREFAULT_MADVISE
2969                                 );
2970                         }
2971                 }
2972                 vm_map_unlock_read(map);
2973         }
2974         return (0);
2975 }
2976
2977
2978 /*
2979  *      vm_map_inherit:
2980  *
2981  *      Sets the inheritance of the specified address
2982  *      range in the target map.  Inheritance
2983  *      affects how the map will be shared with
2984  *      child maps at the time of vmspace_fork.
2985  */
2986 int
2987 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2988                vm_inherit_t new_inheritance)
2989 {
2990         vm_map_entry_t entry, prev_entry;
2991
2992         switch (new_inheritance) {
2993         case VM_INHERIT_NONE:
2994         case VM_INHERIT_COPY:
2995         case VM_INHERIT_SHARE:
2996         case VM_INHERIT_ZERO:
2997                 break;
2998         default:
2999                 return (KERN_INVALID_ARGUMENT);
3000         }
3001         if (start == end)
3002                 return (KERN_SUCCESS);
3003         vm_map_lock(map);
3004         VM_MAP_RANGE_CHECK(map, start, end);
3005         for (entry = vm_map_lookup_clip_start(map, start, &prev_entry);
3006             entry->start < end;
3007             prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3008                 vm_map_clip_end(map, entry, end);
3009                 if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
3010                     new_inheritance != VM_INHERIT_ZERO)
3011                         entry->inheritance = new_inheritance;
3012                 vm_map_try_merge_entries(map, prev_entry, entry);
3013         }
3014         vm_map_try_merge_entries(map, prev_entry, entry);
3015         vm_map_unlock(map);
3016         return (KERN_SUCCESS);
3017 }
3018
3019 /*
3020  *      vm_map_entry_in_transition:
3021  *
3022  *      Release the map lock, and sleep until the entry is no longer in
3023  *      transition.  Awake and acquire the map lock.  If the map changed while
3024  *      another held the lock, lookup a possibly-changed entry at or after the
3025  *      'start' position of the old entry.
3026  */
3027 static vm_map_entry_t
3028 vm_map_entry_in_transition(vm_map_t map, vm_offset_t in_start,
3029     vm_offset_t *io_end, bool holes_ok, vm_map_entry_t in_entry)
3030 {
3031         vm_map_entry_t entry;
3032         vm_offset_t start;
3033         u_int last_timestamp;
3034
3035         VM_MAP_ASSERT_LOCKED(map);
3036         KASSERT((in_entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3037             ("not in-tranition map entry %p", in_entry));
3038         /*
3039          * We have not yet clipped the entry.
3040          */
3041         start = MAX(in_start, in_entry->start);
3042         in_entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3043         last_timestamp = map->timestamp;
3044         if (vm_map_unlock_and_wait(map, 0)) {
3045                 /*
3046                  * Allow interruption of user wiring/unwiring?
3047                  */
3048         }
3049         vm_map_lock(map);
3050         if (last_timestamp + 1 == map->timestamp)
3051                 return (in_entry);
3052
3053         /*
3054          * Look again for the entry because the map was modified while it was
3055          * unlocked.  Specifically, the entry may have been clipped, merged, or
3056          * deleted.
3057          */
3058         if (!vm_map_lookup_entry(map, start, &entry)) {
3059                 if (!holes_ok) {
3060                         *io_end = start;
3061                         return (NULL);
3062                 }
3063                 entry = vm_map_entry_succ(entry);
3064         }
3065         return (entry);
3066 }
3067
3068 /*
3069  *      vm_map_unwire:
3070  *
3071  *      Implements both kernel and user unwiring.
3072  */
3073 int
3074 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
3075     int flags)
3076 {
3077         vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3078         int rv;
3079         bool holes_ok, need_wakeup, user_unwire;
3080
3081         if (start == end)
3082                 return (KERN_SUCCESS);
3083         holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3084         user_unwire = (flags & VM_MAP_WIRE_USER) != 0;
3085         vm_map_lock(map);
3086         VM_MAP_RANGE_CHECK(map, start, end);
3087         if (!vm_map_lookup_entry(map, start, &first_entry)) {
3088                 if (holes_ok)
3089                         first_entry = vm_map_entry_succ(first_entry);
3090                 else {
3091                         vm_map_unlock(map);
3092                         return (KERN_INVALID_ADDRESS);
3093                 }
3094         }
3095         rv = KERN_SUCCESS;
3096         for (entry = first_entry; entry->start < end; entry = next_entry) {
3097                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3098                         /*
3099                          * We have not yet clipped the entry.
3100                          */
3101                         next_entry = vm_map_entry_in_transition(map, start,
3102                             &end, holes_ok, entry);
3103                         if (next_entry == NULL) {
3104                                 if (entry == first_entry) {
3105                                         vm_map_unlock(map);
3106                                         return (KERN_INVALID_ADDRESS);
3107                                 }
3108                                 rv = KERN_INVALID_ADDRESS;
3109                                 break;
3110                         }
3111                         first_entry = (entry == first_entry) ?
3112                             next_entry : NULL;
3113                         continue;
3114                 }
3115                 vm_map_clip_start(map, entry, start);
3116                 vm_map_clip_end(map, entry, end);
3117                 /*
3118                  * Mark the entry in case the map lock is released.  (See
3119                  * above.)
3120                  */
3121                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3122                     entry->wiring_thread == NULL,
3123                     ("owned map entry %p", entry));
3124                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3125                 entry->wiring_thread = curthread;
3126                 next_entry = vm_map_entry_succ(entry);
3127                 /*
3128                  * Check the map for holes in the specified region.
3129                  * If holes_ok, skip this check.
3130                  */
3131                 if (!holes_ok &&
3132                     entry->end < end && next_entry->start > entry->end) {
3133                         end = entry->end;
3134                         rv = KERN_INVALID_ADDRESS;
3135                         break;
3136                 }
3137                 /*
3138                  * If system unwiring, require that the entry is system wired.
3139                  */
3140                 if (!user_unwire &&
3141                     vm_map_entry_system_wired_count(entry) == 0) {
3142                         end = entry->end;
3143                         rv = KERN_INVALID_ARGUMENT;
3144                         break;
3145                 }
3146         }
3147         need_wakeup = false;
3148         if (first_entry == NULL &&
3149             !vm_map_lookup_entry(map, start, &first_entry)) {
3150                 KASSERT(holes_ok, ("vm_map_unwire: lookup failed"));
3151                 prev_entry = first_entry;
3152                 entry = vm_map_entry_succ(first_entry);
3153         } else {
3154                 prev_entry = vm_map_entry_pred(first_entry);
3155                 entry = first_entry;
3156         }
3157         for (; entry->start < end;
3158             prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3159                 /*
3160                  * If holes_ok was specified, an empty
3161                  * space in the unwired region could have been mapped
3162                  * while the map lock was dropped for draining
3163                  * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
3164                  * could be simultaneously wiring this new mapping
3165                  * entry.  Detect these cases and skip any entries
3166                  * marked as in transition by us.
3167                  */
3168                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3169                     entry->wiring_thread != curthread) {
3170                         KASSERT(holes_ok,
3171                             ("vm_map_unwire: !HOLESOK and new/changed entry"));
3172                         continue;
3173                 }
3174
3175                 if (rv == KERN_SUCCESS && (!user_unwire ||
3176                     (entry->eflags & MAP_ENTRY_USER_WIRED))) {
3177                         if (entry->wired_count == 1)
3178                                 vm_map_entry_unwire(map, entry);
3179                         else
3180                                 entry->wired_count--;
3181                         if (user_unwire)
3182                                 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3183                 }
3184                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3185                     ("vm_map_unwire: in-transition flag missing %p", entry));
3186                 KASSERT(entry->wiring_thread == curthread,
3187                     ("vm_map_unwire: alien wire %p", entry));
3188                 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
3189                 entry->wiring_thread = NULL;
3190                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3191                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3192                         need_wakeup = true;
3193                 }
3194                 vm_map_try_merge_entries(map, prev_entry, entry);
3195         }
3196         vm_map_try_merge_entries(map, prev_entry, entry);
3197         vm_map_unlock(map);
3198         if (need_wakeup)
3199                 vm_map_wakeup(map);
3200         return (rv);
3201 }
3202
3203 static void
3204 vm_map_wire_user_count_sub(u_long npages)
3205 {
3206
3207         atomic_subtract_long(&vm_user_wire_count, npages);
3208 }
3209
3210 static bool
3211 vm_map_wire_user_count_add(u_long npages)
3212 {
3213         u_long wired;
3214
3215         wired = vm_user_wire_count;
3216         do {
3217                 if (npages + wired > vm_page_max_user_wired)
3218                         return (false);
3219         } while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
3220             npages + wired));
3221
3222         return (true);
3223 }
3224
3225 /*
3226  *      vm_map_wire_entry_failure:
3227  *
3228  *      Handle a wiring failure on the given entry.
3229  *
3230  *      The map should be locked.
3231  */
3232 static void
3233 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
3234     vm_offset_t failed_addr)
3235 {
3236
3237         VM_MAP_ASSERT_LOCKED(map);
3238         KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
3239             entry->wired_count == 1,
3240             ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
3241         KASSERT(failed_addr < entry->end,
3242             ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
3243
3244         /*
3245          * If any pages at the start of this entry were successfully wired,
3246          * then unwire them.
3247          */
3248         if (failed_addr > entry->start) {
3249                 pmap_unwire(map->pmap, entry->start, failed_addr);
3250                 vm_object_unwire(entry->object.vm_object, entry->offset,
3251                     failed_addr - entry->start, PQ_ACTIVE);
3252         }
3253
3254         /*
3255          * Assign an out-of-range value to represent the failure to wire this
3256          * entry.
3257          */
3258         entry->wired_count = -1;
3259 }
3260
3261 int
3262 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3263 {
3264         int rv;
3265
3266         vm_map_lock(map);
3267         rv = vm_map_wire_locked(map, start, end, flags);
3268         vm_map_unlock(map);
3269         return (rv);
3270 }
3271
3272
3273 /*
3274  *      vm_map_wire_locked:
3275  *
3276  *      Implements both kernel and user wiring.  Returns with the map locked,
3277  *      the map lock may be dropped.
3278  */
3279 int
3280 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3281 {
3282         vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3283         vm_offset_t faddr, saved_end, saved_start;
3284         u_long npages;
3285         u_int last_timestamp;
3286         int rv;
3287         bool holes_ok, need_wakeup, user_wire;
3288         vm_prot_t prot;
3289
3290         VM_MAP_ASSERT_LOCKED(map);
3291
3292         if (start == end)
3293                 return (KERN_SUCCESS);
3294         prot = 0;
3295         if (flags & VM_MAP_WIRE_WRITE)
3296                 prot |= VM_PROT_WRITE;
3297         holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3298         user_wire = (flags & VM_MAP_WIRE_USER) != 0;
3299         VM_MAP_RANGE_CHECK(map, start, end);
3300         if (!vm_map_lookup_entry(map, start, &first_entry)) {
3301                 if (holes_ok)
3302                         first_entry = vm_map_entry_succ(first_entry);
3303                 else
3304                         return (KERN_INVALID_ADDRESS);
3305         }
3306         for (entry = first_entry; entry->start < end; entry = next_entry) {
3307                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3308                         /*
3309                          * We have not yet clipped the entry.
3310                          */
3311                         next_entry = vm_map_entry_in_transition(map, start,
3312                             &end, holes_ok, entry);
3313                         if (next_entry == NULL) {
3314                                 if (entry == first_entry)
3315                                         return (KERN_INVALID_ADDRESS);
3316                                 rv = KERN_INVALID_ADDRESS;
3317                                 goto done;
3318                         }
3319                         first_entry = (entry == first_entry) ?
3320                             next_entry : NULL;
3321                         continue;
3322                 }
3323                 vm_map_clip_start(map, entry, start);
3324                 vm_map_clip_end(map, entry, end);
3325                 /*
3326                  * Mark the entry in case the map lock is released.  (See
3327                  * above.)
3328                  */
3329                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3330                     entry->wiring_thread == NULL,
3331                     ("owned map entry %p", entry));
3332                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3333                 entry->wiring_thread = curthread;
3334                 if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3335                     || (entry->protection & prot) != prot) {
3336                         entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3337                         if (!holes_ok) {
3338                                 end = entry->end;
3339                                 rv = KERN_INVALID_ADDRESS;
3340                                 goto done;
3341                         }
3342                 } else if (entry->wired_count == 0) {
3343                         entry->wired_count++;
3344
3345                         npages = atop(entry->end - entry->start);
3346                         if (user_wire && !vm_map_wire_user_count_add(npages)) {
3347                                 vm_map_wire_entry_failure(map, entry,
3348                                     entry->start);
3349                                 end = entry->end;
3350                                 rv = KERN_RESOURCE_SHORTAGE;
3351                                 goto done;
3352                         }
3353
3354                         /*
3355                          * Release the map lock, relying on the in-transition
3356                          * mark.  Mark the map busy for fork.
3357                          */
3358                         saved_start = entry->start;
3359                         saved_end = entry->end;
3360                         last_timestamp = map->timestamp;
3361                         vm_map_busy(map);
3362                         vm_map_unlock(map);
3363
3364                         faddr = saved_start;
3365                         do {
3366                                 /*
3367                                  * Simulate a fault to get the page and enter
3368                                  * it into the physical map.
3369                                  */
3370                                 if ((rv = vm_fault(map, faddr,
3371                                     VM_PROT_NONE, VM_FAULT_WIRE, NULL)) !=
3372                                     KERN_SUCCESS)
3373                                         break;
3374                         } while ((faddr += PAGE_SIZE) < saved_end);
3375                         vm_map_lock(map);
3376                         vm_map_unbusy(map);
3377                         if (last_timestamp + 1 != map->timestamp) {
3378                                 /*
3379                                  * Look again for the entry because the map was
3380                                  * modified while it was unlocked.  The entry
3381                                  * may have been clipped, but NOT merged or
3382                                  * deleted.
3383                                  */
3384                                 if (!vm_map_lookup_entry(map, saved_start,
3385                                     &next_entry))
3386                                         KASSERT(false,
3387                                             ("vm_map_wire: lookup failed"));
3388                                 first_entry = (entry == first_entry) ?
3389                                     next_entry : NULL;
3390                                 for (entry = next_entry; entry->end < saved_end;
3391                                     entry = vm_map_entry_succ(entry)) {
3392                                         /*
3393                                          * In case of failure, handle entries
3394                                          * that were not fully wired here;
3395                                          * fully wired entries are handled
3396                                          * later.
3397                                          */
3398                                         if (rv != KERN_SUCCESS &&
3399                                             faddr < entry->end)
3400                                                 vm_map_wire_entry_failure(map,
3401                                                     entry, faddr);
3402                                 }
3403                         }
3404                         if (rv != KERN_SUCCESS) {
3405                                 vm_map_wire_entry_failure(map, entry, faddr);
3406                                 if (user_wire)
3407                                         vm_map_wire_user_count_sub(npages);
3408                                 end = entry->end;
3409                                 goto done;
3410                         }
3411                 } else if (!user_wire ||
3412                            (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3413                         entry->wired_count++;
3414                 }
3415                 /*
3416                  * Check the map for holes in the specified region.
3417                  * If holes_ok was specified, skip this check.
3418                  */
3419                 next_entry = vm_map_entry_succ(entry);
3420                 if (!holes_ok &&
3421                     entry->end < end && next_entry->start > entry->end) {
3422                         end = entry->end;
3423                         rv = KERN_INVALID_ADDRESS;
3424                         goto done;
3425                 }
3426         }
3427         rv = KERN_SUCCESS;
3428 done:
3429         need_wakeup = false;
3430         if (first_entry == NULL &&
3431             !vm_map_lookup_entry(map, start, &first_entry)) {
3432                 KASSERT(holes_ok, ("vm_map_wire: lookup failed"));
3433                 prev_entry = first_entry;
3434                 entry = vm_map_entry_succ(first_entry);
3435         } else {
3436                 prev_entry = vm_map_entry_pred(first_entry);
3437                 entry = first_entry;
3438         }
3439         for (; entry->start < end;
3440             prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3441                 /*
3442                  * If holes_ok was specified, an empty
3443                  * space in the unwired region could have been mapped
3444                  * while the map lock was dropped for faulting in the
3445                  * pages or draining MAP_ENTRY_IN_TRANSITION.
3446                  * Moreover, another thread could be simultaneously
3447                  * wiring this new mapping entry.  Detect these cases
3448                  * and skip any entries marked as in transition not by us.
3449                  */
3450                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3451                     entry->wiring_thread != curthread) {
3452                         KASSERT(holes_ok,
3453                             ("vm_map_wire: !HOLESOK and new/changed entry"));
3454                         continue;
3455                 }
3456
3457                 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0) {
3458                         /* do nothing */
3459                 } else if (rv == KERN_SUCCESS) {
3460                         if (user_wire)
3461                                 entry->eflags |= MAP_ENTRY_USER_WIRED;
3462                 } else if (entry->wired_count == -1) {
3463                         /*
3464                          * Wiring failed on this entry.  Thus, unwiring is
3465                          * unnecessary.
3466                          */
3467                         entry->wired_count = 0;
3468                 } else if (!user_wire ||
3469                     (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3470                         /*
3471                          * Undo the wiring.  Wiring succeeded on this entry
3472                          * but failed on a later entry.  
3473                          */
3474                         if (entry->wired_count == 1) {
3475                                 vm_map_entry_unwire(map, entry);
3476                                 if (user_wire)
3477                                         vm_map_wire_user_count_sub(
3478                                             atop(entry->end - entry->start));
3479                         } else
3480                                 entry->wired_count--;
3481                 }
3482                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3483                     ("vm_map_wire: in-transition flag missing %p", entry));
3484                 KASSERT(entry->wiring_thread == curthread,
3485                     ("vm_map_wire: alien wire %p", entry));
3486                 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3487                     MAP_ENTRY_WIRE_SKIPPED);
3488                 entry->wiring_thread = NULL;
3489                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3490                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3491                         need_wakeup = true;
3492                 }
3493                 vm_map_try_merge_entries(map, prev_entry, entry);
3494         }
3495         vm_map_try_merge_entries(map, prev_entry, entry);
3496         if (need_wakeup)
3497                 vm_map_wakeup(map);
3498         return (rv);
3499 }
3500
3501 /*
3502  * vm_map_sync
3503  *
3504  * Push any dirty cached pages in the address range to their pager.
3505  * If syncio is TRUE, dirty pages are written synchronously.
3506  * If invalidate is TRUE, any cached pages are freed as well.
3507  *
3508  * If the size of the region from start to end is zero, we are
3509  * supposed to flush all modified pages within the region containing
3510  * start.  Unfortunately, a region can be split or coalesced with
3511  * neighboring regions, making it difficult to determine what the
3512  * original region was.  Therefore, we approximate this requirement by
3513  * flushing the current region containing start.
3514  *
3515  * Returns an error if any part of the specified range is not mapped.
3516  */
3517 int
3518 vm_map_sync(
3519         vm_map_t map,
3520         vm_offset_t start,
3521         vm_offset_t end,
3522         boolean_t syncio,
3523         boolean_t invalidate)
3524 {
3525         vm_map_entry_t entry, first_entry, next_entry;
3526         vm_size_t size;
3527         vm_object_t object;
3528         vm_ooffset_t offset;
3529         unsigned int last_timestamp;
3530         boolean_t failed;
3531
3532         vm_map_lock_read(map);
3533         VM_MAP_RANGE_CHECK(map, start, end);
3534         if (!vm_map_lookup_entry(map, start, &first_entry)) {
3535                 vm_map_unlock_read(map);
3536                 return (KERN_INVALID_ADDRESS);
3537         } else if (start == end) {
3538                 start = first_entry->start;
3539                 end = first_entry->end;
3540         }
3541         /*
3542          * Make a first pass to check for user-wired memory and holes.
3543          */
3544         for (entry = first_entry; entry->start < end; entry = next_entry) {
3545                 if (invalidate &&
3546                     (entry->eflags & MAP_ENTRY_USER_WIRED) != 0) {
3547                         vm_map_unlock_read(map);
3548                         return (KERN_INVALID_ARGUMENT);
3549                 }
3550                 next_entry = vm_map_entry_succ(entry);
3551                 if (end > entry->end &&
3552                     entry->end != next_entry->start) {
3553                         vm_map_unlock_read(map);
3554                         return (KERN_INVALID_ADDRESS);
3555                 }
3556         }
3557
3558         if (invalidate)
3559                 pmap_remove(map->pmap, start, end);
3560         failed = FALSE;
3561
3562         /*
3563          * Make a second pass, cleaning/uncaching pages from the indicated
3564          * objects as we go.
3565          */
3566         for (entry = first_entry; entry->start < end;) {
3567                 offset = entry->offset + (start - entry->start);
3568                 size = (end <= entry->end ? end : entry->end) - start;
3569                 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
3570                         vm_map_t smap;
3571                         vm_map_entry_t tentry;
3572                         vm_size_t tsize;
3573
3574                         smap = entry->object.sub_map;
3575                         vm_map_lock_read(smap);
3576                         (void) vm_map_lookup_entry(smap, offset, &tentry);
3577                         tsize = tentry->end - offset;
3578                         if (tsize < size)
3579                                 size = tsize;
3580                         object = tentry->object.vm_object;
3581                         offset = tentry->offset + (offset - tentry->start);
3582                         vm_map_unlock_read(smap);
3583                 } else {
3584                         object = entry->object.vm_object;
3585                 }
3586                 vm_object_reference(object);
3587                 last_timestamp = map->timestamp;
3588                 vm_map_unlock_read(map);
3589                 if (!vm_object_sync(object, offset, size, syncio, invalidate))
3590                         failed = TRUE;
3591                 start += size;
3592                 vm_object_deallocate(object);
3593                 vm_map_lock_read(map);
3594                 if (last_timestamp == map->timestamp ||
3595                     !vm_map_lookup_entry(map, start, &entry))
3596                         entry = vm_map_entry_succ(entry);
3597         }
3598
3599         vm_map_unlock_read(map);
3600         return (failed ? KERN_FAILURE : KERN_SUCCESS);
3601 }
3602
3603 /*
3604  *      vm_map_entry_unwire:    [ internal use only ]
3605  *
3606  *      Make the region specified by this entry pageable.
3607  *
3608  *      The map in question should be locked.
3609  *      [This is the reason for this routine's existence.]
3610  */
3611 static void
3612 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3613 {
3614         vm_size_t size;
3615
3616         VM_MAP_ASSERT_LOCKED(map);
3617         KASSERT(entry->wired_count > 0,
3618             ("vm_map_entry_unwire: entry %p isn't wired", entry));
3619
3620         size = entry->end - entry->start;
3621         if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3622                 vm_map_wire_user_count_sub(atop(size));
3623         pmap_unwire(map->pmap, entry->start, entry->end);
3624         vm_object_unwire(entry->object.vm_object, entry->offset, size,
3625             PQ_ACTIVE);
3626         entry->wired_count = 0;
3627 }
3628
3629 static void
3630 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3631 {
3632
3633         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3634                 vm_object_deallocate(entry->object.vm_object);
3635         uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3636 }
3637
3638 /*
3639  *      vm_map_entry_delete:    [ internal use only ]
3640  *
3641  *      Deallocate the given entry from the target map.
3642  */
3643 static void
3644 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3645 {
3646         vm_object_t object;
3647         vm_pindex_t offidxstart, offidxend, size1;
3648         vm_size_t size;
3649
3650         vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3651         object = entry->object.vm_object;
3652
3653         if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3654                 MPASS(entry->cred == NULL);
3655                 MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3656                 MPASS(object == NULL);
3657                 vm_map_entry_deallocate(entry, map->system_map);
3658                 return;
3659         }
3660
3661         size = entry->end - entry->start;
3662         map->size -= size;
3663
3664         if (entry->cred != NULL) {
3665                 swap_release_by_cred(size, entry->cred);
3666                 crfree(entry->cred);
3667         }
3668
3669         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 || object == NULL) {
3670                 entry->object.vm_object = NULL;
3671         } else if ((object->flags & OBJ_ANON) != 0 ||
3672             object == kernel_object) {
3673                 KASSERT(entry->cred == NULL || object->cred == NULL ||
3674                     (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3675                     ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3676                 offidxstart = OFF_TO_IDX(entry->offset);
3677                 offidxend = offidxstart + atop(size);
3678                 VM_OBJECT_WLOCK(object);
3679                 if (object->ref_count != 1 &&
3680                     ((object->flags & OBJ_ONEMAPPING) != 0 ||
3681                     object == kernel_object)) {
3682                         vm_object_collapse(object);
3683
3684                         /*
3685                          * The option OBJPR_NOTMAPPED can be passed here
3686                          * because vm_map_delete() already performed
3687                          * pmap_remove() on the only mapping to this range
3688                          * of pages. 
3689                          */
3690                         vm_object_page_remove(object, offidxstart, offidxend,
3691                             OBJPR_NOTMAPPED);
3692                         if (offidxend >= object->size &&
3693                             offidxstart < object->size) {
3694                                 size1 = object->size;
3695                                 object->size = offidxstart;
3696                                 if (object->cred != NULL) {
3697                                         size1 -= object->size;
3698                                         KASSERT(object->charge >= ptoa(size1),
3699                                             ("object %p charge < 0", object));
3700                                         swap_release_by_cred(ptoa(size1),
3701                                             object->cred);
3702                                         object->charge -= ptoa(size1);
3703                                 }
3704                         }
3705                 }
3706                 VM_OBJECT_WUNLOCK(object);
3707         }
3708         if (map->system_map)
3709                 vm_map_entry_deallocate(entry, TRUE);
3710         else {
3711                 entry->defer_next = curthread->td_map_def_user;
3712                 curthread->td_map_def_user = entry;
3713         }
3714 }
3715
3716 /*
3717  *      vm_map_delete:  [ internal use only ]
3718  *
3719  *      Deallocates the given address range from the target
3720  *      map.
3721  */
3722 int
3723 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3724 {
3725         vm_map_entry_t entry, next_entry;
3726
3727         VM_MAP_ASSERT_LOCKED(map);
3728         if (start == end)
3729                 return (KERN_SUCCESS);
3730
3731         /*
3732          * Find the start of the region, and clip it.
3733          * Step through all entries in this region.
3734          */
3735         for (entry = vm_map_lookup_clip_start(map, start, &entry);
3736             entry->start < end; entry = next_entry) {
3737                 /*
3738                  * Wait for wiring or unwiring of an entry to complete.
3739                  * Also wait for any system wirings to disappear on
3740                  * user maps.
3741                  */
3742                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3743                     (vm_map_pmap(map) != kernel_pmap &&
3744                     vm_map_entry_system_wired_count(entry) != 0)) {
3745                         unsigned int last_timestamp;
3746                         vm_offset_t saved_start;
3747
3748                         saved_start = entry->start;
3749                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3750                         last_timestamp = map->timestamp;
3751                         (void) vm_map_unlock_and_wait(map, 0);
3752                         vm_map_lock(map);
3753                         if (last_timestamp + 1 != map->timestamp) {
3754                                 /*
3755                                  * Look again for the entry because the map was
3756                                  * modified while it was unlocked.
3757                                  * Specifically, the entry may have been
3758                                  * clipped, merged, or deleted.
3759                                  */
3760                                 next_entry = vm_map_lookup_clip_start(map,
3761                                     saved_start, &next_entry);
3762                         } else
3763                                 next_entry = entry;
3764                         continue;
3765                 }
3766                 vm_map_clip_end(map, entry, end);
3767                 next_entry = vm_map_entry_succ(entry);
3768
3769                 /*
3770                  * Unwire before removing addresses from the pmap; otherwise,
3771                  * unwiring will put the entries back in the pmap.
3772                  */
3773                 if (entry->wired_count != 0)
3774                         vm_map_entry_unwire(map, entry);
3775
3776                 /*
3777                  * Remove mappings for the pages, but only if the
3778                  * mappings could exist.  For instance, it does not
3779                  * make sense to call pmap_remove() for guard entries.
3780                  */
3781                 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3782                     entry->object.vm_object != NULL)
3783                         pmap_remove(map->pmap, entry->start, entry->end);
3784
3785                 if (entry->end == map->anon_loc)
3786                         map->anon_loc = entry->start;
3787
3788                 /*
3789                  * Delete the entry only after removing all pmap
3790                  * entries pointing to its pages.  (Otherwise, its
3791                  * page frames may be reallocated, and any modify bits
3792                  * will be set in the wrong object!)
3793                  */
3794                 vm_map_entry_delete(map, entry);
3795         }
3796         return (KERN_SUCCESS);
3797 }
3798
3799 /*
3800  *      vm_map_remove:
3801  *
3802  *      Remove the given address range from the target map.
3803  *      This is the exported form of vm_map_delete.
3804  */
3805 int
3806 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3807 {
3808         int result;
3809
3810         vm_map_lock(map);
3811         VM_MAP_RANGE_CHECK(map, start, end);
3812         result = vm_map_delete(map, start, end);
3813         vm_map_unlock(map);
3814         return (result);
3815 }
3816
3817 /*
3818  *      vm_map_check_protection:
3819  *
3820  *      Assert that the target map allows the specified privilege on the
3821  *      entire address region given.  The entire region must be allocated.
3822  *
3823  *      WARNING!  This code does not and should not check whether the
3824  *      contents of the region is accessible.  For example a smaller file
3825  *      might be mapped into a larger address space.
3826  *
3827  *      NOTE!  This code is also called by munmap().
3828  *
3829  *      The map must be locked.  A read lock is sufficient.
3830  */
3831 boolean_t
3832 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3833                         vm_prot_t protection)
3834 {
3835         vm_map_entry_t entry;
3836         vm_map_entry_t tmp_entry;
3837
3838         if (!vm_map_lookup_entry(map, start, &tmp_entry))
3839                 return (FALSE);
3840         entry = tmp_entry;
3841
3842         while (start < end) {
3843                 /*
3844                  * No holes allowed!
3845                  */
3846                 if (start < entry->start)
3847                         return (FALSE);
3848                 /*
3849                  * Check protection associated with entry.
3850                  */
3851                 if ((entry->protection & protection) != protection)
3852                         return (FALSE);
3853                 /* go to next entry */
3854                 start = entry->end;
3855                 entry = vm_map_entry_succ(entry);
3856         }
3857         return (TRUE);
3858 }
3859
3860
3861 /*
3862  *
3863  *      vm_map_copy_swap_object:
3864  *
3865  *      Copies a swap-backed object from an existing map entry to a
3866  *      new one.  Carries forward the swap charge.  May change the
3867  *      src object on return.
3868  */
3869 static void
3870 vm_map_copy_swap_object(vm_map_entry_t src_entry, vm_map_entry_t dst_entry,
3871     vm_offset_t size, vm_ooffset_t *fork_charge)
3872 {
3873         vm_object_t src_object;
3874         struct ucred *cred;
3875         int charged;
3876
3877         src_object = src_entry->object.vm_object;
3878         charged = ENTRY_CHARGED(src_entry);
3879         if ((src_object->flags & OBJ_ANON) != 0) {
3880                 VM_OBJECT_WLOCK(src_object);
3881                 vm_object_collapse(src_object);
3882                 if ((src_object->flags & OBJ_ONEMAPPING) != 0) {
3883                         vm_object_split(src_entry);
3884                         src_object = src_entry->object.vm_object;
3885                 }
3886                 vm_object_reference_locked(src_object);
3887                 vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3888                 VM_OBJECT_WUNLOCK(src_object);
3889         } else
3890                 vm_object_reference(src_object);
3891         if (src_entry->cred != NULL &&
3892             !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3893                 KASSERT(src_object->cred == NULL,
3894                     ("OVERCOMMIT: vm_map_copy_anon_entry: cred %p",
3895                      src_object));
3896                 src_object->cred = src_entry->cred;
3897                 src_object->charge = size;
3898         }
3899         dst_entry->object.vm_object = src_object;
3900         if (charged) {
3901                 cred = curthread->td_ucred;
3902                 crhold(cred);
3903                 dst_entry->cred = cred;
3904                 *fork_charge += size;
3905                 if (!(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3906                         crhold(cred);
3907                         src_entry->cred = cred;
3908                         *fork_charge += size;
3909                 }
3910         }
3911 }
3912
3913 /*
3914  *      vm_map_copy_entry:
3915  *
3916  *      Copies the contents of the source entry to the destination
3917  *      entry.  The entries *must* be aligned properly.
3918  */
3919 static void
3920 vm_map_copy_entry(
3921         vm_map_t src_map,
3922         vm_map_t dst_map,
3923         vm_map_entry_t src_entry,
3924         vm_map_entry_t dst_entry,
3925         vm_ooffset_t *fork_charge)
3926 {
3927         vm_object_t src_object;
3928         vm_map_entry_t fake_entry;
3929         vm_offset_t size;
3930
3931         VM_MAP_ASSERT_LOCKED(dst_map);
3932
3933         if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3934                 return;
3935
3936         if (src_entry->wired_count == 0 ||
3937             (src_entry->protection & VM_PROT_WRITE) == 0) {
3938                 /*
3939                  * If the source entry is marked needs_copy, it is already
3940                  * write-protected.
3941                  */
3942                 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3943                     (src_entry->protection & VM_PROT_WRITE) != 0) {
3944                         pmap_protect(src_map->pmap,
3945                             src_entry->start,
3946                             src_entry->end,
3947                             src_entry->protection & ~VM_PROT_WRITE);
3948                 }
3949
3950                 /*
3951                  * Make a copy of the object.
3952                  */
3953                 size = src_entry->end - src_entry->start;
3954                 if ((src_object = src_entry->object.vm_object) != NULL) {
3955                         if (src_object->type == OBJT_DEFAULT ||
3956                             src_object->type == OBJT_SWAP) {
3957                                 vm_map_copy_swap_object(src_entry, dst_entry,
3958                                     size, fork_charge);
3959                                 /* May have split/collapsed, reload obj. */
3960                                 src_object = src_entry->object.vm_object;
3961                         } else {
3962                                 vm_object_reference(src_object);
3963                                 dst_entry->object.vm_object = src_object;
3964                         }
3965                         src_entry->eflags |= MAP_ENTRY_COW |
3966                             MAP_ENTRY_NEEDS_COPY;
3967                         dst_entry->eflags |= MAP_ENTRY_COW |
3968                             MAP_ENTRY_NEEDS_COPY;
3969                         dst_entry->offset = src_entry->offset;
3970                         if (src_entry->eflags & MAP_ENTRY_WRITECNT) {
3971                                 /*
3972                                  * MAP_ENTRY_WRITECNT cannot
3973                                  * indicate write reference from
3974                                  * src_entry, since the entry is
3975                                  * marked as needs copy.  Allocate a
3976                                  * fake entry that is used to
3977                                  * decrement object->un_pager writecount
3978                                  * at the appropriate time.  Attach
3979                                  * fake_entry to the deferred list.
3980                                  */
3981                                 fake_entry = vm_map_entry_create(dst_map);
3982                                 fake_entry->eflags = MAP_ENTRY_WRITECNT;
3983                                 src_entry->eflags &= ~MAP_ENTRY_WRITECNT;
3984                                 vm_object_reference(src_object);
3985                                 fake_entry->object.vm_object = src_object;
3986                                 fake_entry->start = src_entry->start;
3987                                 fake_entry->end = src_entry->end;
3988                                 fake_entry->defer_next =
3989                                     curthread->td_map_def_user;
3990                                 curthread->td_map_def_user = fake_entry;
3991                         }
3992
3993                         pmap_copy(dst_map->pmap, src_map->pmap,
3994                             dst_entry->start, dst_entry->end - dst_entry->start,
3995                             src_entry->start);
3996                 } else {
3997                         dst_entry->object.vm_object = NULL;
3998                         dst_entry->offset = 0;
3999                         if (src_entry->cred != NULL) {
4000                                 dst_entry->cred = curthread->td_ucred;
4001                                 crhold(dst_entry->cred);
4002                                 *fork_charge += size;
4003                         }
4004                 }
4005         } else {
4006                 /*
4007                  * We don't want to make writeable wired pages copy-on-write.
4008                  * Immediately copy these pages into the new map by simulating
4009                  * page faults.  The new pages are pageable.
4010                  */
4011                 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
4012                     fork_charge);
4013         }
4014 }
4015
4016 /*
4017  * vmspace_map_entry_forked:
4018  * Update the newly-forked vmspace each time a map entry is inherited
4019  * or copied.  The values for vm_dsize and vm_tsize are approximate
4020  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
4021  */
4022 static void
4023 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
4024     vm_map_entry_t entry)
4025 {
4026         vm_size_t entrysize;
4027         vm_offset_t newend;
4028
4029         if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
4030                 return;
4031         entrysize = entry->end - entry->start;
4032         vm2->vm_map.size += entrysize;
4033         if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
4034                 vm2->vm_ssize += btoc(entrysize);
4035         } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
4036             entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
4037                 newend = MIN(entry->end,
4038                     (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
4039                 vm2->vm_dsize += btoc(newend - entry->start);
4040         } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
4041             entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
4042                 newend = MIN(entry->end,
4043                     (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
4044                 vm2->vm_tsize += btoc(newend - entry->start);
4045         }
4046 }
4047
4048 /*
4049  * vmspace_fork:
4050  * Create a new process vmspace structure and vm_map
4051  * based on those of an existing process.  The new map
4052  * is based on the old map, according to the inheritance
4053  * values on the regions in that map.
4054  *
4055  * XXX It might be worth coalescing the entries added to the new vmspace.
4056  *
4057  * The source map must not be locked.
4058  */
4059 struct vmspace *
4060 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
4061 {
4062         struct vmspace *vm2;
4063         vm_map_t new_map, old_map;
4064         vm_map_entry_t new_entry, old_entry;
4065         vm_object_t object;
4066         int error, locked;
4067         vm_inherit_t inh;
4068
4069         old_map = &vm1->vm_map;
4070         /* Copy immutable fields of vm1 to vm2. */
4071         vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
4072             pmap_pinit);
4073         if (vm2 == NULL)
4074                 return (NULL);
4075
4076         vm2->vm_taddr = vm1->vm_taddr;
4077         vm2->vm_daddr = vm1->vm_daddr;
4078         vm2->vm_maxsaddr = vm1->vm_maxsaddr;
4079         vm_map_lock(old_map);
4080         if (old_map->busy)
4081                 vm_map_wait_busy(old_map);
4082         new_map = &vm2->vm_map;
4083         locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
4084         KASSERT(locked, ("vmspace_fork: lock failed"));
4085
4086         error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
4087         if (error != 0) {
4088                 sx_xunlock(&old_map->lock);
4089                 sx_xunlock(&new_map->lock);
4090                 vm_map_process_deferred();
4091                 vmspace_free(vm2);
4092                 return (NULL);
4093         }
4094
4095         new_map->anon_loc = old_map->anon_loc;
4096
4097         VM_MAP_ENTRY_FOREACH(old_entry, old_map) {
4098                 if ((old_entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
4099                         panic("vm_map_fork: encountered a submap");
4100
4101                 inh = old_entry->inheritance;
4102                 if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4103                     inh != VM_INHERIT_NONE)
4104                         inh = VM_INHERIT_COPY;
4105
4106                 switch (inh) {
4107                 case VM_INHERIT_NONE:
4108                         break;
4109
4110                 case VM_INHERIT_SHARE:
4111                         /*
4112                          * Clone the entry, creating the shared object if
4113                          * necessary.
4114                          */
4115                         object = old_entry->object.vm_object;
4116                         if (object == NULL) {
4117                                 vm_map_entry_back(old_entry);
4118                                 object = old_entry->object.vm_object;
4119                         }
4120
4121                         /*
4122                          * Add the reference before calling vm_object_shadow
4123                          * to insure that a shadow object is created.
4124                          */
4125                         vm_object_reference(object);
4126                         if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4127                                 vm_object_shadow(&old_entry->object.vm_object,
4128                                     &old_entry->offset,
4129                                     old_entry->end - old_entry->start,
4130                                     old_entry->cred,
4131                                     /* Transfer the second reference too. */
4132                                     true);
4133                                 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4134                                 old_entry->cred = NULL;
4135
4136                                 /*
4137                                  * As in vm_map_merged_neighbor_dispose(),
4138                                  * the vnode lock will not be acquired in
4139                                  * this call to vm_object_deallocate().
4140                                  */
4141                                 vm_object_deallocate(object);
4142                                 object = old_entry->object.vm_object;
4143                         } else {
4144                                 VM_OBJECT_WLOCK(object);
4145                                 vm_object_clear_flag(object, OBJ_ONEMAPPING);
4146                                 if (old_entry->cred != NULL) {
4147                                         KASSERT(object->cred == NULL,
4148                                             ("vmspace_fork both cred"));
4149                                         object->cred = old_entry->cred;
4150                                         object->charge = old_entry->end -
4151                                             old_entry->start;
4152                                         old_entry->cred = NULL;
4153                                 }
4154
4155                                 /*
4156                                  * Assert the correct state of the vnode
4157                                  * v_writecount while the object is locked, to
4158                                  * not relock it later for the assertion
4159                                  * correctness.
4160                                  */
4161                                 if (old_entry->eflags & MAP_ENTRY_WRITECNT &&
4162                                     object->type == OBJT_VNODE) {
4163                                         KASSERT(((struct vnode *)object->
4164                                             handle)->v_writecount > 0,
4165                                             ("vmspace_fork: v_writecount %p",
4166                                             object));
4167                                         KASSERT(object->un_pager.vnp.
4168                                             writemappings > 0,
4169                                             ("vmspace_fork: vnp.writecount %p",
4170                                             object));
4171                                 }
4172                                 VM_OBJECT_WUNLOCK(object);
4173                         }
4174
4175                         /*
4176                          * Clone the entry, referencing the shared object.
4177                          */
4178                         new_entry = vm_map_entry_create(new_map);
4179                         *new_entry = *old_entry;
4180                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4181                             MAP_ENTRY_IN_TRANSITION);
4182                         new_entry->wiring_thread = NULL;
4183                         new_entry->wired_count = 0;
4184                         if (new_entry->eflags & MAP_ENTRY_WRITECNT) {
4185                                 vm_pager_update_writecount(object,
4186                                     new_entry->start, new_entry->end);
4187                         }
4188                         vm_map_entry_set_vnode_text(new_entry, true);
4189
4190                         /*
4191                          * Insert the entry into the new map -- we know we're
4192                          * inserting at the end of the new map.
4193                          */
4194                         vm_map_entry_link(new_map, new_entry);
4195                         vmspace_map_entry_forked(vm1, vm2, new_entry);
4196
4197                         /*
4198                          * Update the physical map
4199                          */
4200                         pmap_copy(new_map->pmap, old_map->pmap,
4201                             new_entry->start,
4202                             (old_entry->end - old_entry->start),
4203                             old_entry->start);
4204                         break;
4205
4206                 case VM_INHERIT_COPY:
4207                         /*
4208                          * Clone the entry and link into the map.
4209                          */
4210                         new_entry = vm_map_entry_create(new_map);
4211                         *new_entry = *old_entry;
4212                         /*
4213                          * Copied entry is COW over the old object.
4214                          */
4215                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4216                             MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_WRITECNT);
4217                         new_entry->wiring_thread = NULL;
4218                         new_entry->wired_count = 0;
4219                         new_entry->object.vm_object = NULL;
4220                         new_entry->cred = NULL;
4221                         vm_map_entry_link(new_map, new_entry);
4222                         vmspace_map_entry_forked(vm1, vm2, new_entry);
4223                         vm_map_copy_entry(old_map, new_map, old_entry,
4224                             new_entry, fork_charge);
4225                         vm_map_entry_set_vnode_text(new_entry, true);
4226                         break;
4227
4228                 case VM_INHERIT_ZERO:
4229                         /*
4230                          * Create a new anonymous mapping entry modelled from
4231                          * the old one.
4232                          */
4233                         new_entry = vm_map_entry_create(new_map);
4234                         memset(new_entry, 0, sizeof(*new_entry));
4235
4236                         new_entry->start = old_entry->start;
4237                         new_entry->end = old_entry->end;
4238                         new_entry->eflags = old_entry->eflags &
4239                             ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4240                             MAP_ENTRY_WRITECNT | MAP_ENTRY_VN_EXEC);
4241                         new_entry->protection = old_entry->protection;
4242                         new_entry->max_protection = old_entry->max_protection;
4243                         new_entry->inheritance = VM_INHERIT_ZERO;
4244
4245                         vm_map_entry_link(new_map, new_entry);
4246                         vmspace_map_entry_forked(vm1, vm2, new_entry);
4247
4248                         new_entry->cred = curthread->td_ucred;
4249                         crhold(new_entry->cred);
4250                         *fork_charge += (new_entry->end - new_entry->start);
4251
4252                         break;
4253                 }
4254         }
4255         /*
4256          * Use inlined vm_map_unlock() to postpone handling the deferred
4257          * map entries, which cannot be done until both old_map and
4258          * new_map locks are released.
4259          */
4260         sx_xunlock(&old_map->lock);
4261         sx_xunlock(&new_map->lock);
4262         vm_map_process_deferred();
4263
4264         return (vm2);
4265 }
4266
4267 /*
4268  * Create a process's stack for exec_new_vmspace().  This function is never
4269  * asked to wire the newly created stack.
4270  */
4271 int
4272 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4273     vm_prot_t prot, vm_prot_t max, int cow)
4274 {
4275         vm_size_t growsize, init_ssize;
4276         rlim_t vmemlim;
4277         int rv;
4278
4279         MPASS((map->flags & MAP_WIREFUTURE) == 0);
4280         growsize = sgrowsiz;
4281         init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4282         vm_map_lock(map);
4283         vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4284         /* If we would blow our VMEM resource limit, no go */
4285         if (map->size + init_ssize > vmemlim) {
4286                 rv = KERN_NO_SPACE;
4287                 goto out;
4288         }
4289         rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4290             max, cow);
4291 out:
4292         vm_map_unlock(map);
4293         return (rv);
4294 }
4295
4296 static int stack_guard_page = 1;
4297 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4298     &stack_guard_page, 0,
4299     "Specifies the number of guard pages for a stack that grows");
4300
4301 static int
4302 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4303     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4304 {
4305         vm_map_entry_t new_entry, prev_entry;
4306         vm_offset_t bot, gap_bot, gap_top, top;
4307         vm_size_t init_ssize, sgp;
4308         int orient, rv;
4309
4310         /*
4311          * The stack orientation is piggybacked with the cow argument.
4312          * Extract it into orient and mask the cow argument so that we
4313          * don't pass it around further.
4314          */
4315         orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4316         KASSERT(orient != 0, ("No stack grow direction"));
4317         KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4318             ("bi-dir stack"));
4319
4320         if (max_ssize == 0 ||
4321             !vm_map_range_valid(map, addrbos, addrbos + max_ssize))
4322                 return (KERN_INVALID_ADDRESS);
4323         sgp = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4324             (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4325             (vm_size_t)stack_guard_page * PAGE_SIZE;
4326         if (sgp >= max_ssize)
4327                 return (KERN_INVALID_ARGUMENT);
4328
4329         init_ssize = growsize;
4330         if (max_ssize < init_ssize + sgp)
4331                 init_ssize = max_ssize - sgp;
4332
4333         /* If addr is already mapped, no go */
4334         if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4335                 return (KERN_NO_SPACE);
4336
4337         /*
4338          * If we can't accommodate max_ssize in the current mapping, no go.
4339          */
4340         if (vm_map_entry_succ(prev_entry)->start < addrbos + max_ssize)
4341                 return (KERN_NO_SPACE);
4342
4343         /*
4344          * We initially map a stack of only init_ssize.  We will grow as
4345          * needed later.  Depending on the orientation of the stack (i.e.
4346          * the grow direction) we either map at the top of the range, the
4347          * bottom of the range or in the middle.
4348          *
4349          * Note: we would normally expect prot and max to be VM_PROT_ALL,
4350          * and cow to be 0.  Possibly we should eliminate these as input
4351          * parameters, and just pass these values here in the insert call.
4352          */
4353         if (orient == MAP_STACK_GROWS_DOWN) {
4354                 bot = addrbos + max_ssize - init_ssize;
4355                 top = bot + init_ssize;
4356                 gap_bot = addrbos;
4357                 gap_top = bot;
4358         } else /* if (orient == MAP_STACK_GROWS_UP) */ {
4359                 bot = addrbos;
4360                 top = bot + init_ssize;
4361                 gap_bot = top;
4362                 gap_top = addrbos + max_ssize;
4363         }
4364         rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
4365         if (rv != KERN_SUCCESS)
4366                 return (rv);
4367         new_entry = vm_map_entry_succ(prev_entry);
4368         KASSERT(new_entry->end == top || new_entry->start == bot,
4369             ("Bad entry start/end for new stack entry"));
4370         KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4371             (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4372             ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4373         KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4374             (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4375             ("new entry lacks MAP_ENTRY_GROWS_UP"));
4376         if (gap_bot == gap_top)
4377                 return (KERN_SUCCESS);
4378         rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4379             VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4380             MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4381         if (rv == KERN_SUCCESS) {
4382                 /*
4383                  * Gap can never successfully handle a fault, so
4384                  * read-ahead logic is never used for it.  Re-use
4385                  * next_read of the gap entry to store
4386                  * stack_guard_page for vm_map_growstack().
4387                  */
4388                 if (orient == MAP_STACK_GROWS_DOWN)
4389                         vm_map_entry_pred(new_entry)->next_read = sgp;
4390                 else
4391                         vm_map_entry_succ(new_entry)->next_read = sgp;
4392         } else {
4393                 (void)vm_map_delete(map, bot, top);
4394         }
4395         return (rv);
4396 }
4397
4398 /*
4399  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if we
4400  * successfully grow the stack.
4401  */
4402 static int
4403 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4404 {
4405         vm_map_entry_t stack_entry;
4406         struct proc *p;
4407         struct vmspace *vm;
4408         struct ucred *cred;
4409         vm_offset_t gap_end, gap_start, grow_start;
4410         vm_size_t grow_amount, guard, max_grow;
4411         rlim_t lmemlim, stacklim, vmemlim;
4412         int rv, rv1;
4413         bool gap_deleted, grow_down, is_procstack;
4414 #ifdef notyet
4415         uint64_t limit;
4416 #endif
4417 #ifdef RACCT
4418         int error;
4419 #endif
4420
4421         p = curproc;
4422         vm = p->p_vmspace;
4423
4424         /*
4425          * Disallow stack growth when the access is performed by a
4426          * debugger or AIO daemon.  The reason is that the wrong
4427          * resource limits are applied.
4428          */
4429         if (p != initproc && (map != &p->p_vmspace->vm_map ||
4430             p->p_textvp == NULL))
4431                 return (KERN_FAILURE);
4432
4433         MPASS(!map->system_map);
4434
4435         lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4436         stacklim = lim_cur(curthread, RLIMIT_STACK);
4437         vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4438 retry:
4439         /* If addr is not in a hole for a stack grow area, no need to grow. */
4440         if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4441                 return (KERN_FAILURE);
4442         if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4443                 return (KERN_SUCCESS);
4444         if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4445                 stack_entry = vm_map_entry_succ(gap_entry);
4446                 if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4447                     stack_entry->start != gap_entry->end)
4448                         return (KERN_FAILURE);
4449                 grow_amount = round_page(stack_entry->start - addr);
4450                 grow_down = true;
4451         } else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4452                 stack_entry = vm_map_entry_pred(gap_entry);
4453                 if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4454                     stack_entry->end != gap_entry->start)
4455                         return (KERN_FAILURE);
4456                 grow_amount = round_page(addr + 1 - stack_entry->end);
4457                 grow_down = false;
4458         } else {
4459                 return (KERN_FAILURE);
4460         }
4461         guard = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4462             (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4463             gap_entry->next_read;
4464         max_grow = gap_entry->end - gap_entry->start;
4465         if (guard > max_grow)
4466                 return (KERN_NO_SPACE);
4467         max_grow -= guard;
4468         if (grow_amount > max_grow)
4469                 return (KERN_NO_SPACE);
4470
4471         /*
4472          * If this is the main process stack, see if we're over the stack
4473          * limit.
4474          */
4475         is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4476             addr < (vm_offset_t)p->p_sysent->sv_usrstack;
4477         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4478                 return (KERN_NO_SPACE);
4479
4480 #ifdef RACCT
4481         if (racct_enable) {
4482                 PROC_LOCK(p);
4483                 if (is_procstack && racct_set(p, RACCT_STACK,
4484                     ctob(vm->vm_ssize) + grow_amount)) {
4485                         PROC_UNLOCK(p);
4486                         return (KERN_NO_SPACE);
4487                 }
4488                 PROC_UNLOCK(p);
4489         }
4490 #endif
4491
4492         grow_amount = roundup(grow_amount, sgrowsiz);
4493         if (grow_amount > max_grow)
4494                 grow_amount = max_grow;
4495         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4496                 grow_amount = trunc_page((vm_size_t)stacklim) -
4497                     ctob(vm->vm_ssize);
4498         }
4499
4500 #ifdef notyet
4501         PROC_LOCK(p);
4502         limit = racct_get_available(p, RACCT_STACK);
4503         PROC_UNLOCK(p);
4504         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4505                 grow_amount = limit - ctob(vm->vm_ssize);
4506 #endif
4507
4508         if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4509                 if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4510                         rv = KERN_NO_SPACE;
4511                         goto out;
4512                 }
4513 #ifdef RACCT
4514                 if (racct_enable) {
4515                         PROC_LOCK(p);
4516                         if (racct_set(p, RACCT_MEMLOCK,
4517                             ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4518                                 PROC_UNLOCK(p);
4519                                 rv = KERN_NO_SPACE;
4520                                 goto out;
4521                         }
4522                         PROC_UNLOCK(p);
4523                 }
4524 #endif
4525         }
4526
4527         /* If we would blow our VMEM resource limit, no go */
4528         if (map->size + grow_amount > vmemlim) {
4529                 rv = KERN_NO_SPACE;
4530                 goto out;
4531         }
4532 #ifdef RACCT
4533         if (racct_enable) {
4534                 PROC_LOCK(p);
4535                 if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4536                         PROC_UNLOCK(p);
4537                         rv = KERN_NO_SPACE;
4538                         goto out;
4539                 }
4540                 PROC_UNLOCK(p);
4541         }
4542 #endif
4543
4544         if (vm_map_lock_upgrade(map)) {
4545                 gap_entry = NULL;
4546                 vm_map_lock_read(map);
4547                 goto retry;
4548         }
4549
4550         if (grow_down) {
4551                 grow_start = gap_entry->end - grow_amount;
4552                 if (gap_entry->start + grow_amount == gap_entry->end) {
4553                         gap_start = gap_entry->start;
4554                         gap_end = gap_entry->end;
4555                         vm_map_entry_delete(map, gap_entry);
4556                         gap_deleted = true;
4557                 } else {
4558                         MPASS(gap_entry->start < gap_entry->end - grow_amount);
4559                         vm_map_entry_resize(map, gap_entry, -grow_amount);
4560                         gap_deleted = false;
4561                 }
4562                 rv = vm_map_insert(map, NULL, 0, grow_start,
4563                     grow_start + grow_amount,
4564                     stack_entry->protection, stack_entry->max_protection,
4565                     MAP_STACK_GROWS_DOWN);
4566                 if (rv != KERN_SUCCESS) {
4567                         if (gap_deleted) {
4568                                 rv1 = vm_map_insert(map, NULL, 0, gap_start,
4569                                     gap_end, VM_PROT_NONE, VM_PROT_NONE,
4570                                     MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4571                                 MPASS(rv1 == KERN_SUCCESS);
4572                         } else
4573                                 vm_map_entry_resize(map, gap_entry,
4574                                     grow_amount);
4575                 }
4576         } else {
4577                 grow_start = stack_entry->end;
4578                 cred = stack_entry->cred;
4579                 if (cred == NULL && stack_entry->object.vm_object != NULL)
4580                         cred = stack_entry->object.vm_object->cred;
4581                 if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4582                         rv = KERN_NO_SPACE;
4583                 /* Grow the underlying object if applicable. */
4584                 else if (stack_entry->object.vm_object == NULL ||
4585                     vm_object_coalesce(stack_entry->object.vm_object,
4586                     stack_entry->offset,
4587                     (vm_size_t)(stack_entry->end - stack_entry->start),
4588                     grow_amount, cred != NULL)) {
4589                         if (gap_entry->start + grow_amount == gap_entry->end) {
4590                                 vm_map_entry_delete(map, gap_entry);
4591                                 vm_map_entry_resize(map, stack_entry,
4592                                     grow_amount);
4593                         } else {
4594                                 gap_entry->start += grow_amount;
4595                                 stack_entry->end += grow_amount;
4596                         }
4597                         map->size += grow_amount;
4598                         rv = KERN_SUCCESS;
4599                 } else
4600                         rv = KERN_FAILURE;
4601         }
4602         if (rv == KERN_SUCCESS && is_procstack)
4603                 vm->vm_ssize += btoc(grow_amount);
4604
4605         /*
4606          * Heed the MAP_WIREFUTURE flag if it was set for this process.
4607          */
4608         if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4609                 rv = vm_map_wire_locked(map, grow_start,
4610                     grow_start + grow_amount,
4611                     VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4612         }
4613         vm_map_lock_downgrade(map);
4614
4615 out:
4616 #ifdef RACCT
4617         if (racct_enable && rv != KERN_SUCCESS) {
4618                 PROC_LOCK(p);
4619                 error = racct_set(p, RACCT_VMEM, map->size);
4620                 KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4621                 if (!old_mlock) {
4622                         error = racct_set(p, RACCT_MEMLOCK,
4623                             ptoa(pmap_wired_count(map->pmap)));
4624                         KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4625                 }
4626                 error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4627                 KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4628                 PROC_UNLOCK(p);
4629         }
4630 #endif
4631
4632         return (rv);
4633 }
4634
4635 /*
4636  * Unshare the specified VM space for exec.  If other processes are
4637  * mapped to it, then create a new one.  The new vmspace is null.
4638  */
4639 int
4640 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4641 {
4642         struct vmspace *oldvmspace = p->p_vmspace;
4643         struct vmspace *newvmspace;
4644
4645         KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4646             ("vmspace_exec recursed"));
4647         newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4648         if (newvmspace == NULL)
4649                 return (ENOMEM);
4650         newvmspace->vm_swrss = oldvmspace->vm_swrss;
4651         /*
4652          * This code is written like this for prototype purposes.  The
4653          * goal is to avoid running down the vmspace here, but let the
4654          * other process's that are still using the vmspace to finally
4655          * run it down.  Even though there is little or no chance of blocking
4656          * here, it is a good idea to keep this form for future mods.
4657          */
4658         PROC_VMSPACE_LOCK(p);
4659         p->p_vmspace = newvmspace;
4660         PROC_VMSPACE_UNLOCK(p);
4661         if (p == curthread->td_proc)
4662                 pmap_activate(curthread);
4663         curthread->td_pflags |= TDP_EXECVMSPC;
4664         return (0);
4665 }
4666
4667 /*
4668  * Unshare the specified VM space for forcing COW.  This
4669  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4670  */
4671 int
4672 vmspace_unshare(struct proc *p)
4673 {
4674         struct vmspace *oldvmspace = p->p_vmspace;
4675         struct vmspace *newvmspace;
4676         vm_ooffset_t fork_charge;
4677
4678         if (oldvmspace->vm_refcnt == 1)
4679                 return (0);
4680         fork_charge = 0;
4681         newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4682         if (newvmspace == NULL)
4683                 return (ENOMEM);
4684         if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4685                 vmspace_free(newvmspace);
4686                 return (ENOMEM);
4687         }
4688         PROC_VMSPACE_LOCK(p);
4689         p->p_vmspace = newvmspace;
4690         PROC_VMSPACE_UNLOCK(p);
4691         if (p == curthread->td_proc)
4692                 pmap_activate(curthread);
4693         vmspace_free(oldvmspace);
4694         return (0);
4695 }
4696
4697 /*
4698  *      vm_map_lookup:
4699  *
4700  *      Finds the VM object, offset, and
4701  *      protection for a given virtual address in the
4702  *      specified map, assuming a page fault of the
4703  *      type specified.
4704  *
4705  *      Leaves the map in question locked for read; return
4706  *      values are guaranteed until a vm_map_lookup_done
4707  *      call is performed.  Note that the map argument
4708  *      is in/out; the returned map must be used in
4709  *      the call to vm_map_lookup_done.
4710  *
4711  *      A handle (out_entry) is returned for use in
4712  *      vm_map_lookup_done, to make that fast.
4713  *
4714  *      If a lookup is requested with "write protection"
4715  *      specified, the map may be changed to perform virtual
4716  *      copying operations, although the data referenced will
4717  *      remain the same.
4718  */
4719 int
4720 vm_map_lookup(vm_map_t *var_map,                /* IN/OUT */
4721               vm_offset_t vaddr,
4722               vm_prot_t fault_typea,
4723               vm_map_entry_t *out_entry,        /* OUT */
4724               vm_object_t *object,              /* OUT */
4725               vm_pindex_t *pindex,              /* OUT */
4726               vm_prot_t *out_prot,              /* OUT */
4727               boolean_t *wired)                 /* OUT */
4728 {
4729         vm_map_entry_t entry;
4730         vm_map_t map = *var_map;
4731         vm_prot_t prot;
4732         vm_prot_t fault_type;
4733         vm_object_t eobject;
4734         vm_size_t size;
4735         struct ucred *cred;
4736
4737 RetryLookup:
4738
4739         vm_map_lock_read(map);
4740
4741 RetryLookupLocked:
4742         /*
4743          * Lookup the faulting address.
4744          */
4745         if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4746                 vm_map_unlock_read(map);
4747                 return (KERN_INVALID_ADDRESS);
4748         }
4749
4750         entry = *out_entry;
4751
4752         /*
4753          * Handle submaps.
4754          */
4755         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4756                 vm_map_t old_map = map;
4757
4758                 *var_map = map = entry->object.sub_map;
4759                 vm_map_unlock_read(old_map);
4760                 goto RetryLookup;
4761         }
4762
4763         /*
4764          * Check whether this task is allowed to have this page.
4765          */
4766         prot = entry->protection;
4767         if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4768                 fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4769                 if (prot == VM_PROT_NONE && map != kernel_map &&
4770                     (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4771                     (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4772                     MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4773                     vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4774                         goto RetryLookupLocked;
4775         }
4776         fault_type = fault_typea & VM_PROT_ALL;
4777         if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4778                 vm_map_unlock_read(map);
4779                 return (KERN_PROTECTION_FAILURE);
4780         }
4781         KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4782             (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4783             (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4784             ("entry %p flags %x", entry, entry->eflags));
4785         if ((fault_typea & VM_PROT_COPY) != 0 &&
4786             (entry->max_protection & VM_PROT_WRITE) == 0 &&
4787             (entry->eflags & MAP_ENTRY_COW) == 0) {
4788                 vm_map_unlock_read(map);
4789                 return (KERN_PROTECTION_FAILURE);
4790         }
4791
4792         /*
4793          * If this page is not pageable, we have to get it for all possible
4794          * accesses.
4795          */
4796         *wired = (entry->wired_count != 0);
4797         if (*wired)
4798                 fault_type = entry->protection;
4799         size = entry->end - entry->start;
4800
4801         /*
4802          * If the entry was copy-on-write, we either ...
4803          */
4804         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4805                 /*
4806                  * If we want to write the page, we may as well handle that
4807                  * now since we've got the map locked.
4808                  *
4809                  * If we don't need to write the page, we just demote the
4810                  * permissions allowed.
4811                  */
4812                 if ((fault_type & VM_PROT_WRITE) != 0 ||
4813                     (fault_typea & VM_PROT_COPY) != 0) {
4814                         /*
4815                          * Make a new object, and place it in the object
4816                          * chain.  Note that no new references have appeared
4817                          * -- one just moved from the map to the new
4818                          * object.
4819                          */
4820                         if (vm_map_lock_upgrade(map))
4821                                 goto RetryLookup;
4822
4823                         if (entry->cred == NULL) {
4824                                 /*
4825                                  * The debugger owner is charged for
4826                                  * the memory.
4827                                  */
4828                                 cred = curthread->td_ucred;
4829                                 crhold(cred);
4830                                 if (!swap_reserve_by_cred(size, cred)) {
4831                                         crfree(cred);
4832                                         vm_map_unlock(map);
4833                                         return (KERN_RESOURCE_SHORTAGE);
4834                                 }
4835                                 entry->cred = cred;
4836                         }
4837                         eobject = entry->object.vm_object;
4838                         vm_object_shadow(&entry->object.vm_object,
4839                             &entry->offset, size, entry->cred, false);
4840                         if (eobject == entry->object.vm_object) {
4841                                 /*
4842                                  * The object was not shadowed.
4843                                  */
4844                                 swap_release_by_cred(size, entry->cred);
4845                                 crfree(entry->cred);
4846                         }
4847                         entry->cred = NULL;
4848                         entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4849
4850                         vm_map_lock_downgrade(map);
4851                 } else {
4852                         /*
4853                          * We're attempting to read a copy-on-write page --
4854                          * don't allow writes.
4855                          */
4856                         prot &= ~VM_PROT_WRITE;
4857                 }
4858         }
4859
4860         /*
4861          * Create an object if necessary.
4862          */
4863         if (entry->object.vm_object == NULL && !map->system_map) {
4864                 if (vm_map_lock_upgrade(map))
4865                         goto RetryLookup;
4866                 entry->object.vm_object = vm_object_allocate_anon(atop(size),
4867                     NULL, entry->cred, entry->cred != NULL ? size : 0);
4868                 entry->offset = 0;
4869                 entry->cred = NULL;
4870                 vm_map_lock_downgrade(map);
4871         }
4872
4873         /*
4874          * Return the object/offset from this entry.  If the entry was
4875          * copy-on-write or empty, it has been fixed up.
4876          */
4877         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4878         *object = entry->object.vm_object;
4879
4880         *out_prot = prot;
4881         return (KERN_SUCCESS);
4882 }
4883
4884 /*
4885  *      vm_map_lookup_locked:
4886  *
4887  *      Lookup the faulting address.  A version of vm_map_lookup that returns 
4888  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4889  */
4890 int
4891 vm_map_lookup_locked(vm_map_t *var_map,         /* IN/OUT */
4892                      vm_offset_t vaddr,
4893                      vm_prot_t fault_typea,
4894                      vm_map_entry_t *out_entry, /* OUT */
4895                      vm_object_t *object,       /* OUT */
4896                      vm_pindex_t *pindex,       /* OUT */
4897                      vm_prot_t *out_prot,       /* OUT */
4898                      boolean_t *wired)          /* OUT */
4899 {
4900         vm_map_entry_t entry;
4901         vm_map_t map = *var_map;
4902         vm_prot_t prot;
4903         vm_prot_t fault_type = fault_typea;
4904
4905         /*
4906          * Lookup the faulting address.
4907          */
4908         if (!vm_map_lookup_entry(map, vaddr, out_entry))
4909                 return (KERN_INVALID_ADDRESS);
4910
4911         entry = *out_entry;
4912
4913         /*
4914          * Fail if the entry refers to a submap.
4915          */
4916         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4917                 return (KERN_FAILURE);
4918
4919         /*
4920          * Check whether this task is allowed to have this page.
4921          */
4922         prot = entry->protection;
4923         fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4924         if ((fault_type & prot) != fault_type)
4925                 return (KERN_PROTECTION_FAILURE);
4926
4927         /*
4928          * If this page is not pageable, we have to get it for all possible
4929          * accesses.
4930          */
4931         *wired = (entry->wired_count != 0);
4932         if (*wired)
4933                 fault_type = entry->protection;
4934
4935         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4936                 /*
4937                  * Fail if the entry was copy-on-write for a write fault.
4938                  */
4939                 if (fault_type & VM_PROT_WRITE)
4940                         return (KERN_FAILURE);
4941                 /*
4942                  * We're attempting to read a copy-on-write page --
4943                  * don't allow writes.
4944                  */
4945                 prot &= ~VM_PROT_WRITE;
4946         }
4947
4948         /*
4949          * Fail if an object should be created.
4950          */
4951         if (entry->object.vm_object == NULL && !map->system_map)
4952                 return (KERN_FAILURE);
4953
4954         /*
4955          * Return the object/offset from this entry.  If the entry was
4956          * copy-on-write or empty, it has been fixed up.
4957          */
4958         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4959         *object = entry->object.vm_object;
4960
4961         *out_prot = prot;
4962         return (KERN_SUCCESS);
4963 }
4964
4965 /*
4966  *      vm_map_lookup_done:
4967  *
4968  *      Releases locks acquired by a vm_map_lookup
4969  *      (according to the handle returned by that lookup).
4970  */
4971 void
4972 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4973 {
4974         /*
4975          * Unlock the main-level map
4976          */
4977         vm_map_unlock_read(map);
4978 }
4979
4980 vm_offset_t
4981 vm_map_max_KBI(const struct vm_map *map)
4982 {
4983
4984         return (vm_map_max(map));
4985 }
4986
4987 vm_offset_t
4988 vm_map_min_KBI(const struct vm_map *map)
4989 {
4990
4991         return (vm_map_min(map));
4992 }
4993
4994 pmap_t
4995 vm_map_pmap_KBI(vm_map_t map)
4996 {
4997
4998         return (map->pmap);
4999 }
5000
5001 #ifdef INVARIANTS
5002 static void
5003 _vm_map_assert_consistent(vm_map_t map, int check)
5004 {
5005         vm_map_entry_t entry, prev;
5006         vm_map_entry_t cur, header, lbound, ubound;
5007         vm_size_t max_left, max_right;
5008
5009 #ifdef DIAGNOSTIC
5010         ++map->nupdates;
5011 #endif
5012         if (enable_vmmap_check != check)
5013                 return;
5014
5015         header = prev = &map->header;
5016         VM_MAP_ENTRY_FOREACH(entry, map) {
5017                 KASSERT(prev->end <= entry->start,
5018                     ("map %p prev->end = %jx, start = %jx", map,
5019                     (uintmax_t)prev->end, (uintmax_t)entry->start));
5020                 KASSERT(entry->start < entry->end,
5021                     ("map %p start = %jx, end = %jx", map,
5022                     (uintmax_t)entry->start, (uintmax_t)entry->end));
5023                 KASSERT(entry->left == header ||
5024                     entry->left->start < entry->start,
5025                     ("map %p left->start = %jx, start = %jx", map,
5026                     (uintmax_t)entry->left->start, (uintmax_t)entry->start));
5027                 KASSERT(entry->right == header ||
5028                     entry->start < entry->right->start,
5029                     ("map %p start = %jx, right->start = %jx", map,
5030                     (uintmax_t)entry->start, (uintmax_t)entry->right->start));
5031                 cur = map->root;
5032                 lbound = ubound = header;
5033                 for (;;) {
5034                         if (entry->start < cur->start) {
5035                                 ubound = cur;
5036                                 cur = cur->left;
5037                                 KASSERT(cur != lbound,
5038                                     ("map %p cannot find %jx",
5039                                     map, (uintmax_t)entry->start));
5040                         } else if (cur->end <= entry->start) {
5041                                 lbound = cur;
5042                                 cur = cur->right;
5043                                 KASSERT(cur != ubound,
5044                                     ("map %p cannot find %jx",
5045                                     map, (uintmax_t)entry->start));
5046                         } else {
5047                                 KASSERT(cur == entry,
5048                                     ("map %p cannot find %jx",
5049                                     map, (uintmax_t)entry->start));
5050                                 break;
5051                         }
5052                 }
5053                 max_left = vm_map_entry_max_free_left(entry, lbound);
5054                 max_right = vm_map_entry_max_free_right(entry, ubound);
5055                 KASSERT(entry->max_free == vm_size_max(max_left, max_right),
5056                     ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
5057                     (uintmax_t)entry->max_free,
5058                     (uintmax_t)max_left, (uintmax_t)max_right));
5059                 prev = entry;
5060         }
5061         KASSERT(prev->end <= entry->start,
5062             ("map %p prev->end = %jx, start = %jx", map,
5063             (uintmax_t)prev->end, (uintmax_t)entry->start));
5064 }
5065 #endif
5066
5067 #include "opt_ddb.h"
5068 #ifdef DDB
5069 #include <sys/kernel.h>
5070
5071 #include <ddb/ddb.h>
5072
5073 static void
5074 vm_map_print(vm_map_t map)
5075 {
5076         vm_map_entry_t entry, prev;
5077
5078         db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
5079             (void *)map,
5080             (void *)map->pmap, map->nentries, map->timestamp);
5081
5082         db_indent += 2;
5083         prev = &map->header;
5084         VM_MAP_ENTRY_FOREACH(entry, map) {
5085                 db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
5086                     (void *)entry, (void *)entry->start, (void *)entry->end,
5087                     entry->eflags);
5088                 {
5089                         static const char * const inheritance_name[4] =
5090                         {"share", "copy", "none", "donate_copy"};
5091
5092                         db_iprintf(" prot=%x/%x/%s",
5093                             entry->protection,
5094                             entry->max_protection,
5095                             inheritance_name[(int)(unsigned char)
5096                             entry->inheritance]);
5097                         if (entry->wired_count != 0)
5098                                 db_printf(", wired");
5099                 }
5100                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
5101                         db_printf(", share=%p, offset=0x%jx\n",
5102                             (void *)entry->object.sub_map,
5103                             (uintmax_t)entry->offset);
5104                         if (prev == &map->header ||
5105                             prev->object.sub_map !=
5106                                 entry->object.sub_map) {
5107                                 db_indent += 2;
5108                                 vm_map_print((vm_map_t)entry->object.sub_map);
5109                                 db_indent -= 2;
5110                         }
5111                 } else {
5112                         if (entry->cred != NULL)
5113                                 db_printf(", ruid %d", entry->cred->cr_ruid);
5114                         db_printf(", object=%p, offset=0x%jx",
5115                             (void *)entry->object.vm_object,
5116                             (uintmax_t)entry->offset);
5117                         if (entry->object.vm_object && entry->object.vm_object->cred)
5118                                 db_printf(", obj ruid %d charge %jx",
5119                                     entry->object.vm_object->cred->cr_ruid,
5120                                     (uintmax_t)entry->object.vm_object->charge);
5121                         if (entry->eflags & MAP_ENTRY_COW)
5122                                 db_printf(", copy (%s)",
5123                                     (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
5124                         db_printf("\n");
5125
5126                         if (prev == &map->header ||
5127                             prev->object.vm_object !=
5128                                 entry->object.vm_object) {
5129                                 db_indent += 2;
5130                                 vm_object_print((db_expr_t)(intptr_t)
5131                                                 entry->object.vm_object,
5132                                                 0, 0, (char *)0);
5133                                 db_indent -= 2;
5134                         }
5135                 }
5136                 prev = entry;
5137         }
5138         db_indent -= 2;
5139 }
5140
5141 DB_SHOW_COMMAND(map, map)
5142 {
5143
5144         if (!have_addr) {
5145                 db_printf("usage: show map <addr>\n");
5146                 return;
5147         }
5148         vm_map_print((vm_map_t)addr);
5149 }
5150
5151 DB_SHOW_COMMAND(procvm, procvm)
5152 {
5153         struct proc *p;
5154
5155         if (have_addr) {
5156                 p = db_lookup_proc(addr);
5157         } else {
5158                 p = curproc;
5159         }
5160
5161         db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
5162             (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
5163             (void *)vmspace_pmap(p->p_vmspace));
5164
5165         vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
5166 }
5167
5168 #endif /* DDB */