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