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