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