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