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