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