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