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