Merge branch 'vendor/OPENSSL'
[dragonfly.git] / sys / vm / vm_map.c
1 /*
2  * (MPSAFE)
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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)vm_map.c      8.3 (Berkeley) 1/12/94
39  *
40  *
41  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42  * All rights reserved.
43  *
44  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
45  *
46  * Permission to use, copy, modify and distribute this software and
47  * its documentation is hereby granted, provided that both the copyright
48  * notice and this permission notice appear in all copies of the
49  * software, derivative works or modified versions, and any portions
50  * thereof, and that both notices appear in supporting documentation.
51  *
52  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
53  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
54  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
55  *
56  * Carnegie Mellon requests users of this software to return to
57  *
58  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
59  *  School of Computer Science
60  *  Carnegie Mellon University
61  *  Pittsburgh PA 15213-3890
62  *
63  * any improvements or extensions that they make and grant Carnegie the
64  * rights to redistribute these changes.
65  *
66  * $FreeBSD: src/sys/vm/vm_map.c,v 1.187.2.19 2003/05/27 00:47:02 alc Exp $
67  * $DragonFly: src/sys/vm/vm_map.c,v 1.56 2007/04/29 18:25:41 dillon Exp $
68  */
69
70 /*
71  *      Virtual memory mapping module.
72  */
73
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/kernel.h>
77 #include <sys/proc.h>
78 #include <sys/lock.h>
79 #include <sys/vmmeter.h>
80 #include <sys/mman.h>
81 #include <sys/vnode.h>
82 #include <sys/resourcevar.h>
83 #include <sys/shm.h>
84 #include <sys/tree.h>
85 #include <sys/malloc.h>
86
87 #include <vm/vm.h>
88 #include <vm/vm_param.h>
89 #include <vm/pmap.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_page.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_pager.h>
94 #include <vm/vm_kern.h>
95 #include <vm/vm_extern.h>
96 #include <vm/swap_pager.h>
97 #include <vm/vm_zone.h>
98
99 #include <sys/thread2.h>
100 #include <sys/sysref2.h>
101
102 /*
103  * Virtual memory maps provide for the mapping, protection, and sharing
104  * of virtual memory objects.  In addition, this module provides for an
105  * efficient virtual copy of 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 entries.
110  * A hint and a RB tree is used to speed-up lookups.
111  *
112  * Callers looking to modify maps specify start/end addresses which cause
113  * the related map entry to be clipped if necessary, and then later
114  * recombined if the pieces remained compatible.
115  *
116  * Virtual copy operations are performed by copying VM object references
117  * from one map to another, and then marking both regions as copy-on-write.
118  */
119 static void vmspace_terminate(struct vmspace *vm);
120 static void vmspace_lock(struct vmspace *vm);
121 static void vmspace_unlock(struct vmspace *vm);
122 static void vmspace_dtor(void *obj, void *private);
123
124 MALLOC_DEFINE(M_VMSPACE, "vmspace", "vmspace objcache backingstore");
125
126 struct sysref_class vmspace_sysref_class = {
127         .name =         "vmspace",
128         .mtype =        M_VMSPACE,
129         .proto =        SYSREF_PROTO_VMSPACE,
130         .offset =       offsetof(struct vmspace, vm_sysref),
131         .objsize =      sizeof(struct vmspace),
132         .mag_capacity = 32,
133         .flags = SRC_MANAGEDINIT,
134         .dtor = vmspace_dtor,
135         .ops = {
136                 .terminate = (sysref_terminate_func_t)vmspace_terminate,
137                 .lock = (sysref_lock_func_t)vmspace_lock,
138                 .unlock = (sysref_lock_func_t)vmspace_unlock
139         }
140 };
141
142 #define VMEPERCPU       2
143
144 static struct vm_zone mapentzone_store, mapzone_store;
145 static vm_zone_t mapentzone, mapzone;
146 static struct vm_object mapentobj, mapobj;
147
148 static struct vm_map_entry map_entry_init[MAX_MAPENT];
149 static struct vm_map_entry cpu_map_entry_init[MAXCPU][VMEPERCPU];
150 static struct vm_map map_init[MAX_KMAP];
151
152 static void vm_map_entry_shadow(vm_map_entry_t entry);
153 static vm_map_entry_t vm_map_entry_create(vm_map_t map, int *);
154 static void vm_map_entry_dispose (vm_map_t map, vm_map_entry_t entry, int *);
155 static void _vm_map_clip_end (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
156 static void _vm_map_clip_start (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
157 static void vm_map_entry_delete (vm_map_t, vm_map_entry_t, int *);
158 static void vm_map_entry_unwire (vm_map_t, vm_map_entry_t);
159 static void vm_map_copy_entry (vm_map_t, vm_map_t, vm_map_entry_t,
160                 vm_map_entry_t);
161 static void vm_map_split (vm_map_entry_t);
162 static void vm_map_unclip_range (vm_map_t map, vm_map_entry_t start_entry, vm_offset_t start, vm_offset_t end, int *count, int flags);
163
164 /*
165  * Initialize the vm_map module.  Must be called before any other vm_map
166  * routines.
167  *
168  * Map and entry structures are allocated from the general purpose
169  * memory pool with some exceptions:
170  *
171  *      - The kernel map is allocated statically.
172  *      - Initial kernel map entries are allocated out of a static pool.
173  *
174  *      These restrictions are necessary since malloc() uses the
175  *      maps and requires map entries.
176  *
177  * Called from the low level boot code only.
178  */
179 void
180 vm_map_startup(void)
181 {
182         mapzone = &mapzone_store;
183         zbootinit(mapzone, "MAP", sizeof (struct vm_map),
184                 map_init, MAX_KMAP);
185         mapentzone = &mapentzone_store;
186         zbootinit(mapentzone, "MAP ENTRY", sizeof (struct vm_map_entry),
187                 map_entry_init, MAX_MAPENT);
188 }
189
190 /*
191  * Called prior to any vmspace allocations.
192  *
193  * Called from the low level boot code only.
194  */
195 void
196 vm_init2(void) 
197 {
198         zinitna(mapentzone, &mapentobj, NULL, 0, 0, 
199                 ZONE_USE_RESERVE | ZONE_SPECIAL, 1);
200         zinitna(mapzone, &mapobj, NULL, 0, 0, 0, 1);
201         pmap_init2();
202         vm_object_init2();
203 }
204
205
206 /*
207  * Red black tree functions
208  *
209  * The caller must hold the related map lock.
210  */
211 static int rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b);
212 RB_GENERATE(vm_map_rb_tree, vm_map_entry, rb_entry, rb_vm_map_compare);
213
214 /* a->start is address, and the only field has to be initialized */
215 static int
216 rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b)
217 {
218         if (a->start < b->start)
219                 return(-1);
220         else if (a->start > b->start)
221                 return(1);
222         return(0);
223 }
224
225 /*
226  * Allocate a vmspace structure, including a vm_map and pmap.
227  * Initialize numerous fields.  While the initial allocation is zerod,
228  * subsequence reuse from the objcache leaves elements of the structure
229  * intact (particularly the pmap), so portions must be zerod.
230  *
231  * The structure is not considered activated until we call sysref_activate().
232  *
233  * No requirements.
234  */
235 struct vmspace *
236 vmspace_alloc(vm_offset_t min, vm_offset_t max)
237 {
238         struct vmspace *vm;
239
240         lwkt_gettoken(&vmspace_token);
241         vm = sysref_alloc(&vmspace_sysref_class);
242         bzero(&vm->vm_startcopy,
243               (char *)&vm->vm_endcopy - (char *)&vm->vm_startcopy);
244         vm_map_init(&vm->vm_map, min, max, NULL);
245         pmap_pinit(vmspace_pmap(vm));           /* (some fields reused) */
246         vm->vm_map.pmap = vmspace_pmap(vm);             /* XXX */
247         vm->vm_shm = NULL;
248         vm->vm_exitingcnt = 0;
249         cpu_vmspace_alloc(vm);
250         sysref_activate(&vm->vm_sysref);
251         lwkt_reltoken(&vmspace_token);
252
253         return (vm);
254 }
255
256 /*
257  * dtor function - Some elements of the pmap are retained in the
258  * free-cached vmspaces to improve performance.  We have to clean them up
259  * here before returning the vmspace to the memory pool.
260  *
261  * No requirements.
262  */
263 static void
264 vmspace_dtor(void *obj, void *private)
265 {
266         struct vmspace *vm = obj;
267
268         pmap_puninit(vmspace_pmap(vm));
269 }
270
271 /*
272  * Called in two cases: 
273  *
274  * (1) When the last sysref is dropped, but exitingcnt might still be
275  *     non-zero.
276  *
277  * (2) When there are no sysrefs (i.e. refcnt is negative) left and the
278  *     exitingcnt becomes zero
279  *
280  * sysref will not scrap the object until we call sysref_put() once more
281  * after the last ref has been dropped.
282  *
283  * Interlocked by the sysref API.
284  */
285 static void
286 vmspace_terminate(struct vmspace *vm)
287 {
288         int count;
289
290         /*
291          * If exitingcnt is non-zero we can't get rid of the entire vmspace
292          * yet, but we can scrap user memory.
293          */
294         lwkt_gettoken(&vmspace_token);
295         if (vm->vm_exitingcnt) {
296                 shmexit(vm);
297                 pmap_remove_pages(vmspace_pmap(vm), VM_MIN_USER_ADDRESS,
298                                   VM_MAX_USER_ADDRESS);
299                 vm_map_remove(&vm->vm_map, VM_MIN_USER_ADDRESS,
300                               VM_MAX_USER_ADDRESS);
301                 lwkt_reltoken(&vmspace_token);
302                 return;
303         }
304         cpu_vmspace_free(vm);
305
306         /*
307          * Make sure any SysV shm is freed, it might not have in
308          * exit1()
309          */
310         shmexit(vm);
311
312         KKASSERT(vm->vm_upcalls == NULL);
313
314         /*
315          * Lock the map, to wait out all other references to it.
316          * Delete all of the mappings and pages they hold, then call
317          * the pmap module to reclaim anything left.
318          */
319         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
320         vm_map_lock(&vm->vm_map);
321         vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
322                 vm->vm_map.max_offset, &count);
323         vm_map_unlock(&vm->vm_map);
324         vm_map_entry_release(count);
325
326         pmap_release(vmspace_pmap(vm));
327         sysref_put(&vm->vm_sysref);
328         lwkt_reltoken(&vmspace_token);
329 }
330
331 /*
332  * vmspaces are not currently locked.
333  */
334 static void
335 vmspace_lock(struct vmspace *vm __unused)
336 {
337 }
338
339 static void
340 vmspace_unlock(struct vmspace *vm __unused)
341 {
342 }
343
344 /*
345  * This is called during exit indicating that the vmspace is no
346  * longer in used by an exiting process, but the process has not yet
347  * been cleaned up.
348  *
349  * No requirements.
350  */
351 void
352 vmspace_exitbump(struct vmspace *vm)
353 {
354         lwkt_gettoken(&vmspace_token);
355         ++vm->vm_exitingcnt;
356         lwkt_reltoken(&vmspace_token);
357 }
358
359 /*
360  * This is called in the wait*() handling code.  The vmspace can be terminated
361  * after the last wait is finished using it.
362  *
363  * No requirements.
364  */
365 void
366 vmspace_exitfree(struct proc *p)
367 {
368         struct vmspace *vm;
369
370         lwkt_gettoken(&vmspace_token);
371         vm = p->p_vmspace;
372         p->p_vmspace = NULL;
373
374         if (--vm->vm_exitingcnt == 0 && sysref_isinactive(&vm->vm_sysref))
375                 vmspace_terminate(vm);
376         lwkt_reltoken(&vmspace_token);
377 }
378
379 /*
380  * Swap useage is determined by taking the proportional swap used by
381  * VM objects backing the VM map.  To make up for fractional losses,
382  * if the VM object has any swap use at all the associated map entries
383  * count for at least 1 swap page.
384  *
385  * No requirements.
386  */
387 int
388 vmspace_swap_count(struct vmspace *vmspace)
389 {
390         vm_map_t map = &vmspace->vm_map;
391         vm_map_entry_t cur;
392         vm_object_t object;
393         int count = 0;
394         int n;
395
396         lwkt_gettoken(&vmspace_token);
397         for (cur = map->header.next; cur != &map->header; cur = cur->next) {
398                 switch(cur->maptype) {
399                 case VM_MAPTYPE_NORMAL:
400                 case VM_MAPTYPE_VPAGETABLE:
401                         if ((object = cur->object.vm_object) == NULL)
402                                 break;
403                         if (object->swblock_count) {
404                                 n = (cur->end - cur->start) / PAGE_SIZE;
405                                 count += object->swblock_count *
406                                     SWAP_META_PAGES * n / object->size + 1;
407                         }
408                         break;
409                 default:
410                         break;
411                 }
412         }
413         lwkt_reltoken(&vmspace_token);
414         return(count);
415 }
416
417 /*
418  * Calculate the approximate number of anonymous pages in use by
419  * this vmspace.  To make up for fractional losses, we count each
420  * VM object as having at least 1 anonymous page.
421  *
422  * No requirements.
423  */
424 int
425 vmspace_anonymous_count(struct vmspace *vmspace)
426 {
427         vm_map_t map = &vmspace->vm_map;
428         vm_map_entry_t cur;
429         vm_object_t object;
430         int count = 0;
431
432         lwkt_gettoken(&vmspace_token);
433         for (cur = map->header.next; cur != &map->header; cur = cur->next) {
434                 switch(cur->maptype) {
435                 case VM_MAPTYPE_NORMAL:
436                 case VM_MAPTYPE_VPAGETABLE:
437                         if ((object = cur->object.vm_object) == NULL)
438                                 break;
439                         if (object->type != OBJT_DEFAULT &&
440                             object->type != OBJT_SWAP) {
441                                 break;
442                         }
443                         count += object->resident_page_count;
444                         break;
445                 default:
446                         break;
447                 }
448         }
449         lwkt_reltoken(&vmspace_token);
450         return(count);
451 }
452
453 /*
454  * Creates and returns a new empty VM map with the given physical map
455  * structure, and having the given lower and upper address bounds.
456  *
457  * No requirements.
458  */
459 vm_map_t
460 vm_map_create(vm_map_t result, pmap_t pmap, vm_offset_t min, vm_offset_t max)
461 {
462         if (result == NULL)
463                 result = zalloc(mapzone);
464         vm_map_init(result, min, max, pmap);
465         return (result);
466 }
467
468 /*
469  * Initialize an existing vm_map structure such as that in the vmspace
470  * structure.  The pmap is initialized elsewhere.
471  *
472  * No requirements.
473  */
474 void
475 vm_map_init(struct vm_map *map, vm_offset_t min, vm_offset_t max, pmap_t pmap)
476 {
477         map->header.next = map->header.prev = &map->header;
478         RB_INIT(&map->rb_root);
479         map->nentries = 0;
480         map->size = 0;
481         map->system_map = 0;
482         map->infork = 0;
483         map->min_offset = min;
484         map->max_offset = max;
485         map->pmap = pmap;
486         map->first_free = &map->header;
487         map->hint = &map->header;
488         map->timestamp = 0;
489         lockinit(&map->lock, "thrd_sleep", 0, 0);
490 }
491
492 /*
493  * Shadow the vm_map_entry's object.  This typically needs to be done when
494  * a write fault is taken on an entry which had previously been cloned by
495  * fork().  The shared object (which might be NULL) must become private so
496  * we add a shadow layer above it.
497  *
498  * Object allocation for anonymous mappings is defered as long as possible.
499  * When creating a shadow, however, the underlying object must be instantiated
500  * so it can be shared.
501  *
502  * If the map segment is governed by a virtual page table then it is
503  * possible to address offsets beyond the mapped area.  Just allocate
504  * a maximally sized object for this case.
505  *
506  * The vm_map must be exclusively locked.
507  * No other requirements.
508  */
509 static
510 void
511 vm_map_entry_shadow(vm_map_entry_t entry)
512 {
513         if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
514                 vm_object_shadow(&entry->object.vm_object, &entry->offset,
515                                  0x7FFFFFFF);   /* XXX */
516         } else {
517                 vm_object_shadow(&entry->object.vm_object, &entry->offset,
518                                  atop(entry->end - entry->start));
519         }
520         entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
521 }
522
523 /*
524  * Allocate an object for a vm_map_entry.
525  *
526  * Object allocation for anonymous mappings is defered as long as possible.
527  * This function is called when we can defer no longer, generally when a map
528  * entry might be split or forked or takes a page fault.
529  *
530  * If the map segment is governed by a virtual page table then it is
531  * possible to address offsets beyond the mapped area.  Just allocate
532  * a maximally sized object for this case.
533  *
534  * The vm_map must be exclusively locked.
535  * No other requirements.
536  */
537 void 
538 vm_map_entry_allocate_object(vm_map_entry_t entry)
539 {
540         vm_object_t obj;
541
542         if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
543                 obj = vm_object_allocate(OBJT_DEFAULT, 0x7FFFFFFF); /* XXX */
544         } else {
545                 obj = vm_object_allocate(OBJT_DEFAULT,
546                                          atop(entry->end - entry->start));
547         }
548         entry->object.vm_object = obj;
549         entry->offset = 0;
550 }
551
552 /*
553  * Set an initial negative count so the first attempt to reserve
554  * space preloads a bunch of vm_map_entry's for this cpu.  Also
555  * pre-allocate 2 vm_map_entries which will be needed by zalloc() to
556  * map a new page for vm_map_entry structures.  SMP systems are
557  * particularly sensitive.
558  *
559  * This routine is called in early boot so we cannot just call
560  * vm_map_entry_reserve().
561  *
562  * Called from the low level boot code only (for each cpu)
563  */
564 void
565 vm_map_entry_reserve_cpu_init(globaldata_t gd)
566 {
567         vm_map_entry_t entry;
568         int i;
569
570         gd->gd_vme_avail -= MAP_RESERVE_COUNT * 2;
571         entry = &cpu_map_entry_init[gd->gd_cpuid][0];
572         for (i = 0; i < VMEPERCPU; ++i, ++entry) {
573                 entry->next = gd->gd_vme_base;
574                 gd->gd_vme_base = entry;
575         }
576 }
577
578 /*
579  * Reserves vm_map_entry structures so code later on can manipulate
580  * map_entry structures within a locked map without blocking trying
581  * to allocate a new vm_map_entry.
582  *
583  * No requirements.
584  */
585 int
586 vm_map_entry_reserve(int count)
587 {
588         struct globaldata *gd = mycpu;
589         vm_map_entry_t entry;
590
591         /*
592          * Make sure we have enough structures in gd_vme_base to handle
593          * the reservation request.
594          */
595         crit_enter();
596         while (gd->gd_vme_avail < count) {
597                 entry = zalloc(mapentzone);
598                 entry->next = gd->gd_vme_base;
599                 gd->gd_vme_base = entry;
600                 ++gd->gd_vme_avail;
601         }
602         gd->gd_vme_avail -= count;
603         crit_exit();
604
605         return(count);
606 }
607
608 /*
609  * Releases previously reserved vm_map_entry structures that were not
610  * used.  If we have too much junk in our per-cpu cache clean some of
611  * it out.
612  *
613  * No requirements.
614  */
615 void
616 vm_map_entry_release(int count)
617 {
618         struct globaldata *gd = mycpu;
619         vm_map_entry_t entry;
620
621         crit_enter();
622         gd->gd_vme_avail += count;
623         while (gd->gd_vme_avail > MAP_RESERVE_SLOP) {
624                 entry = gd->gd_vme_base;
625                 KKASSERT(entry != NULL);
626                 gd->gd_vme_base = entry->next;
627                 --gd->gd_vme_avail;
628                 crit_exit();
629                 zfree(mapentzone, entry);
630                 crit_enter();
631         }
632         crit_exit();
633 }
634
635 /*
636  * Reserve map entry structures for use in kernel_map itself.  These
637  * entries have *ALREADY* been reserved on a per-cpu basis when the map
638  * was inited.  This function is used by zalloc() to avoid a recursion
639  * when zalloc() itself needs to allocate additional kernel memory.
640  *
641  * This function works like the normal reserve but does not load the
642  * vm_map_entry cache (because that would result in an infinite
643  * recursion).  Note that gd_vme_avail may go negative.  This is expected.
644  *
645  * Any caller of this function must be sure to renormalize after
646  * potentially eating entries to ensure that the reserve supply
647  * remains intact.
648  *
649  * No requirements.
650  */
651 int
652 vm_map_entry_kreserve(int count)
653 {
654         struct globaldata *gd = mycpu;
655
656         crit_enter();
657         gd->gd_vme_avail -= count;
658         crit_exit();
659         KASSERT(gd->gd_vme_base != NULL,
660                 ("no reserved entries left, gd_vme_avail = %d\n",
661                 gd->gd_vme_avail));
662         return(count);
663 }
664
665 /*
666  * Release previously reserved map entries for kernel_map.  We do not
667  * attempt to clean up like the normal release function as this would
668  * cause an unnecessary (but probably not fatal) deep procedure call.
669  *
670  * No requirements.
671  */
672 void
673 vm_map_entry_krelease(int count)
674 {
675         struct globaldata *gd = mycpu;
676
677         crit_enter();
678         gd->gd_vme_avail += count;
679         crit_exit();
680 }
681
682 /*
683  * Allocates a VM map entry for insertion.  No entry fields are filled in.
684  *
685  * The entries should have previously been reserved.  The reservation count
686  * is tracked in (*countp).
687  *
688  * No requirements.
689  */
690 static vm_map_entry_t
691 vm_map_entry_create(vm_map_t map, int *countp)
692 {
693         struct globaldata *gd = mycpu;
694         vm_map_entry_t entry;
695
696         KKASSERT(*countp > 0);
697         --*countp;
698         crit_enter();
699         entry = gd->gd_vme_base;
700         KASSERT(entry != NULL, ("gd_vme_base NULL! count %d", *countp));
701         gd->gd_vme_base = entry->next;
702         crit_exit();
703
704         return(entry);
705 }
706
707 /*
708  * Dispose of a vm_map_entry that is no longer being referenced.
709  *
710  * No requirements.
711  */
712 static void
713 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry, int *countp)
714 {
715         struct globaldata *gd = mycpu;
716
717         KKASSERT(map->hint != entry);
718         KKASSERT(map->first_free != entry);
719
720         ++*countp;
721         crit_enter();
722         entry->next = gd->gd_vme_base;
723         gd->gd_vme_base = entry;
724         crit_exit();
725 }
726
727
728 /*
729  * Insert/remove entries from maps.
730  *
731  * The related map must be exclusively locked.
732  * No other requirements.
733  *
734  * NOTE! We currently acquire the vmspace_token only to avoid races
735  *       against the pageout daemon's calls to vmspace_*_count(), which
736  *       are unable to safely lock the vm_map without potentially
737  *       deadlocking.
738  */
739 static __inline void
740 vm_map_entry_link(vm_map_t map,
741                   vm_map_entry_t after_where,
742                   vm_map_entry_t entry)
743 {
744         ASSERT_VM_MAP_LOCKED(map);
745
746         lwkt_gettoken(&vmspace_token);
747         map->nentries++;
748         entry->prev = after_where;
749         entry->next = after_where->next;
750         entry->next->prev = entry;
751         after_where->next = entry;
752         if (vm_map_rb_tree_RB_INSERT(&map->rb_root, entry))
753                 panic("vm_map_entry_link: dup addr map %p ent %p", map, entry);
754         lwkt_reltoken(&vmspace_token);
755 }
756
757 static __inline void
758 vm_map_entry_unlink(vm_map_t map,
759                     vm_map_entry_t entry)
760 {
761         vm_map_entry_t prev;
762         vm_map_entry_t next;
763
764         ASSERT_VM_MAP_LOCKED(map);
765
766         if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
767                 panic("vm_map_entry_unlink: attempt to mess with "
768                       "locked entry! %p", entry);
769         }
770         lwkt_gettoken(&vmspace_token);
771         prev = entry->prev;
772         next = entry->next;
773         next->prev = prev;
774         prev->next = next;
775         vm_map_rb_tree_RB_REMOVE(&map->rb_root, entry);
776         map->nentries--;
777         lwkt_reltoken(&vmspace_token);
778 }
779
780 /*
781  * Finds the map entry containing (or immediately preceding) the specified
782  * address in the given map.  The entry is returned in (*entry).
783  *
784  * The boolean result indicates whether the address is actually contained
785  * in the map.
786  *
787  * The related map must be locked.
788  * No other requirements.
789  */
790 boolean_t
791 vm_map_lookup_entry(vm_map_t map, vm_offset_t address, vm_map_entry_t *entry)
792 {
793         vm_map_entry_t tmp;
794         vm_map_entry_t last;
795
796         ASSERT_VM_MAP_LOCKED(map);
797 #if 0
798         /*
799          * XXX TEMPORARILY DISABLED.  For some reason our attempt to revive
800          * the hint code with the red-black lookup meets with system crashes
801          * and lockups.  We do not yet know why.
802          *
803          * It is possible that the problem is related to the setting
804          * of the hint during map_entry deletion, in the code specified
805          * at the GGG comment later on in this file.
806          */
807         /*
808          * Quickly check the cached hint, there's a good chance of a match.
809          */
810         if (map->hint != &map->header) {
811                 tmp = map->hint;
812                 if (address >= tmp->start && address < tmp->end) {
813                         *entry = tmp;
814                         return(TRUE);
815                 }
816         }
817 #endif
818
819         /*
820          * Locate the record from the top of the tree.  'last' tracks the
821          * closest prior record and is returned if no match is found, which
822          * in binary tree terms means tracking the most recent right-branch
823          * taken.  If there is no prior record, &map->header is returned.
824          */
825         last = &map->header;
826         tmp = RB_ROOT(&map->rb_root);
827
828         while (tmp) {
829                 if (address >= tmp->start) {
830                         if (address < tmp->end) {
831                                 *entry = tmp;
832                                 map->hint = tmp;
833                                 return(TRUE);
834                         }
835                         last = tmp;
836                         tmp = RB_RIGHT(tmp, rb_entry);
837                 } else {
838                         tmp = RB_LEFT(tmp, rb_entry);
839                 }
840         }
841         *entry = last;
842         return (FALSE);
843 }
844
845 /*
846  * Inserts the given whole VM object into the target map at the specified
847  * address range.  The object's size should match that of the address range.
848  *
849  * The map must be exclusively locked.
850  * The caller must have reserved sufficient vm_map_entry structures.
851  *
852  * If object is non-NULL, ref count must be bumped by caller
853  * prior to making call to account for the new entry.
854  */
855 int
856 vm_map_insert(vm_map_t map, int *countp,
857               vm_object_t object, vm_ooffset_t offset,
858               vm_offset_t start, vm_offset_t end,
859               vm_maptype_t maptype,
860               vm_prot_t prot, vm_prot_t max,
861               int cow)
862 {
863         vm_map_entry_t new_entry;
864         vm_map_entry_t prev_entry;
865         vm_map_entry_t temp_entry;
866         vm_eflags_t protoeflags;
867
868         ASSERT_VM_MAP_LOCKED(map);
869
870         /*
871          * Check that the start and end points are not bogus.
872          */
873         if ((start < map->min_offset) || (end > map->max_offset) ||
874             (start >= end))
875                 return (KERN_INVALID_ADDRESS);
876
877         /*
878          * Find the entry prior to the proposed starting address; if it's part
879          * of an existing entry, this range is bogus.
880          */
881         if (vm_map_lookup_entry(map, start, &temp_entry))
882                 return (KERN_NO_SPACE);
883
884         prev_entry = temp_entry;
885
886         /*
887          * Assert that the next entry doesn't overlap the end point.
888          */
889
890         if ((prev_entry->next != &map->header) &&
891             (prev_entry->next->start < end))
892                 return (KERN_NO_SPACE);
893
894         protoeflags = 0;
895
896         if (cow & MAP_COPY_ON_WRITE)
897                 protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
898
899         if (cow & MAP_NOFAULT) {
900                 protoeflags |= MAP_ENTRY_NOFAULT;
901
902                 KASSERT(object == NULL,
903                         ("vm_map_insert: paradoxical MAP_NOFAULT request"));
904         }
905         if (cow & MAP_DISABLE_SYNCER)
906                 protoeflags |= MAP_ENTRY_NOSYNC;
907         if (cow & MAP_DISABLE_COREDUMP)
908                 protoeflags |= MAP_ENTRY_NOCOREDUMP;
909         if (cow & MAP_IS_STACK)
910                 protoeflags |= MAP_ENTRY_STACK;
911         if (cow & MAP_IS_KSTACK)
912                 protoeflags |= MAP_ENTRY_KSTACK;
913
914         lwkt_gettoken(&vm_token);
915         lwkt_gettoken(&vmobj_token);
916
917         if (object) {
918                 /*
919                  * When object is non-NULL, it could be shared with another
920                  * process.  We have to set or clear OBJ_ONEMAPPING 
921                  * appropriately.
922                  */
923                 if ((object->ref_count > 1) || (object->shadow_count != 0)) {
924                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
925                 }
926         }
927         else if ((prev_entry != &map->header) &&
928                  (prev_entry->eflags == protoeflags) &&
929                  (prev_entry->end == start) &&
930                  (prev_entry->wired_count == 0) &&
931                  prev_entry->maptype == maptype &&
932                  ((prev_entry->object.vm_object == NULL) ||
933                   vm_object_coalesce(prev_entry->object.vm_object,
934                                      OFF_TO_IDX(prev_entry->offset),
935                                      (vm_size_t)(prev_entry->end - prev_entry->start),
936                                      (vm_size_t)(end - prev_entry->end)))) {
937                 /*
938                  * We were able to extend the object.  Determine if we
939                  * can extend the previous map entry to include the 
940                  * new range as well.
941                  */
942                 if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
943                     (prev_entry->protection == prot) &&
944                     (prev_entry->max_protection == max)) {
945                         lwkt_reltoken(&vmobj_token);
946                         lwkt_reltoken(&vm_token);
947                         map->size += (end - prev_entry->end);
948                         prev_entry->end = end;
949                         vm_map_simplify_entry(map, prev_entry, countp);
950                         return (KERN_SUCCESS);
951                 }
952
953                 /*
954                  * If we can extend the object but cannot extend the
955                  * map entry, we have to create a new map entry.  We
956                  * must bump the ref count on the extended object to
957                  * account for it.  object may be NULL.
958                  */
959                 object = prev_entry->object.vm_object;
960                 offset = prev_entry->offset +
961                         (prev_entry->end - prev_entry->start);
962                 vm_object_reference_locked(object);
963         }
964
965         lwkt_reltoken(&vmobj_token);
966         lwkt_reltoken(&vm_token);
967
968         /*
969          * NOTE: if conditionals fail, object can be NULL here.  This occurs
970          * in things like the buffer map where we manage kva but do not manage
971          * backing objects.
972          */
973
974         /*
975          * Create a new entry
976          */
977
978         new_entry = vm_map_entry_create(map, countp);
979         new_entry->start = start;
980         new_entry->end = end;
981
982         new_entry->maptype = maptype;
983         new_entry->eflags = protoeflags;
984         new_entry->object.vm_object = object;
985         new_entry->offset = offset;
986         new_entry->aux.master_pde = 0;
987
988         new_entry->inheritance = VM_INHERIT_DEFAULT;
989         new_entry->protection = prot;
990         new_entry->max_protection = max;
991         new_entry->wired_count = 0;
992
993         /*
994          * Insert the new entry into the list
995          */
996
997         vm_map_entry_link(map, prev_entry, new_entry);
998         map->size += new_entry->end - new_entry->start;
999
1000         /*
1001          * Update the free space hint.  Entries cannot overlap.
1002          * An exact comparison is needed to avoid matching
1003          * against the map->header.
1004          */
1005         if ((map->first_free == prev_entry) &&
1006             (prev_entry->end == new_entry->start)) {
1007                 map->first_free = new_entry;
1008         }
1009
1010 #if 0
1011         /*
1012          * Temporarily removed to avoid MAP_STACK panic, due to
1013          * MAP_STACK being a huge hack.  Will be added back in
1014          * when MAP_STACK (and the user stack mapping) is fixed.
1015          */
1016         /*
1017          * It may be possible to simplify the entry
1018          */
1019         vm_map_simplify_entry(map, new_entry, countp);
1020 #endif
1021
1022         /*
1023          * Try to pre-populate the page table.  Mappings governed by virtual
1024          * page tables cannot be prepopulated without a lot of work, so
1025          * don't try.
1026          */
1027         if ((cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) &&
1028             maptype != VM_MAPTYPE_VPAGETABLE) {
1029                 pmap_object_init_pt(map->pmap, start, prot,
1030                                     object, OFF_TO_IDX(offset), end - start,
1031                                     cow & MAP_PREFAULT_PARTIAL);
1032         }
1033
1034         return (KERN_SUCCESS);
1035 }
1036
1037 /*
1038  * Find sufficient space for `length' bytes in the given map, starting at
1039  * `start'.  Returns 0 on success, 1 on no space.
1040  *
1041  * This function will returned an arbitrarily aligned pointer.  If no
1042  * particular alignment is required you should pass align as 1.  Note that
1043  * the map may return PAGE_SIZE aligned pointers if all the lengths used in
1044  * the map are a multiple of PAGE_SIZE, even if you pass a smaller align
1045  * argument.
1046  *
1047  * 'align' should be a power of 2 but is not required to be.
1048  *
1049  * The map must be exclusively locked.
1050  * No other requirements.
1051  */
1052 int
1053 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
1054                  vm_size_t align, int flags, vm_offset_t *addr)
1055 {
1056         vm_map_entry_t entry, next;
1057         vm_offset_t end;
1058         vm_offset_t align_mask;
1059
1060         if (start < map->min_offset)
1061                 start = map->min_offset;
1062         if (start > map->max_offset)
1063                 return (1);
1064
1065         /*
1066          * If the alignment is not a power of 2 we will have to use
1067          * a mod/division, set align_mask to a special value.
1068          */
1069         if ((align | (align - 1)) + 1 != (align << 1))
1070                 align_mask = (vm_offset_t)-1;
1071         else
1072                 align_mask = align - 1;
1073
1074         /*
1075          * Look for the first possible address; if there's already something
1076          * at this address, we have to start after it.
1077          */
1078         if (start == map->min_offset) {
1079                 if ((entry = map->first_free) != &map->header)
1080                         start = entry->end;
1081         } else {
1082                 vm_map_entry_t tmp;
1083
1084                 if (vm_map_lookup_entry(map, start, &tmp))
1085                         start = tmp->end;
1086                 entry = tmp;
1087         }
1088
1089         /*
1090          * Look through the rest of the map, trying to fit a new region in the
1091          * gap between existing regions, or after the very last region.
1092          */
1093         for (;; start = (entry = next)->end) {
1094                 /*
1095                  * Adjust the proposed start by the requested alignment,
1096                  * be sure that we didn't wrap the address.
1097                  */
1098                 if (align_mask == (vm_offset_t)-1)
1099                         end = ((start + align - 1) / align) * align;
1100                 else
1101                         end = (start + align_mask) & ~align_mask;
1102                 if (end < start)
1103                         return (1);
1104                 start = end;
1105                 /*
1106                  * Find the end of the proposed new region.  Be sure we didn't
1107                  * go beyond the end of the map, or wrap around the address.
1108                  * Then check to see if this is the last entry or if the 
1109                  * proposed end fits in the gap between this and the next
1110                  * entry.
1111                  */
1112                 end = start + length;
1113                 if (end > map->max_offset || end < start)
1114                         return (1);
1115                 next = entry->next;
1116
1117                 /*
1118                  * If the next entry's start address is beyond the desired
1119                  * end address we may have found a good entry.
1120                  *
1121                  * If the next entry is a stack mapping we do not map into
1122                  * the stack's reserved space.
1123                  *
1124                  * XXX continue to allow mapping into the stack's reserved
1125                  * space if doing a MAP_STACK mapping inside a MAP_STACK
1126                  * mapping, for backwards compatibility.  But the caller
1127                  * really should use MAP_STACK | MAP_TRYFIXED if they
1128                  * want to do that.
1129                  */
1130                 if (next == &map->header)
1131                         break;
1132                 if (next->start >= end) {
1133                         if ((next->eflags & MAP_ENTRY_STACK) == 0)
1134                                 break;
1135                         if (flags & MAP_STACK)
1136                                 break;
1137                         if (next->start - next->aux.avail_ssize >= end)
1138                                 break;
1139                 }
1140         }
1141         map->hint = entry;
1142
1143         /*
1144          * Grow the kernel_map if necessary.  pmap_growkernel() will panic
1145          * if it fails.  The kernel_map is locked and nothing can steal
1146          * our address space if pmap_growkernel() blocks.
1147          *
1148          * NOTE: This may be unconditionally called for kldload areas on
1149          *       x86_64 because these do not bump kernel_vm_end (which would
1150          *       fill 128G worth of page tables!).  Therefore we must not
1151          *       retry.
1152          */
1153         if (map == &kernel_map) {
1154                 vm_offset_t kstop;
1155
1156                 kstop = round_page(start + length);
1157                 if (kstop > kernel_vm_end)
1158                         pmap_growkernel(start, kstop);
1159         }
1160         *addr = start;
1161         return (0);
1162 }
1163
1164 /*
1165  * vm_map_find finds an unallocated region in the target address map with
1166  * the given length.  The search is defined to be first-fit from the
1167  * specified address; the region found is returned in the same parameter.
1168  *
1169  * If object is non-NULL, ref count must be bumped by caller
1170  * prior to making call to account for the new entry.
1171  *
1172  * No requirements.  This function will lock the map temporarily.
1173  */
1174 int
1175 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1176             vm_offset_t *addr,  vm_size_t length, vm_size_t align,
1177             boolean_t fitit,
1178             vm_maptype_t maptype,
1179             vm_prot_t prot, vm_prot_t max,
1180             int cow)
1181 {
1182         vm_offset_t start;
1183         int result;
1184         int count;
1185
1186         start = *addr;
1187
1188         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1189         vm_map_lock(map);
1190         if (fitit) {
1191                 if (vm_map_findspace(map, start, length, align, 0, addr)) {
1192                         vm_map_unlock(map);
1193                         vm_map_entry_release(count);
1194                         return (KERN_NO_SPACE);
1195                 }
1196                 start = *addr;
1197         }
1198         result = vm_map_insert(map, &count, object, offset,
1199                                start, start + length,
1200                                maptype,
1201                                prot, max,
1202                                cow);
1203         vm_map_unlock(map);
1204         vm_map_entry_release(count);
1205
1206         return (result);
1207 }
1208
1209 /*
1210  * Simplify the given map entry by merging with either neighbor.  This
1211  * routine also has the ability to merge with both neighbors.
1212  *
1213  * This routine guarentees that the passed entry remains valid (though
1214  * possibly extended).  When merging, this routine may delete one or
1215  * both neighbors.  No action is taken on entries which have their
1216  * in-transition flag set.
1217  *
1218  * The map must be exclusively locked.
1219  */
1220 void
1221 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry, int *countp)
1222 {
1223         vm_map_entry_t next, prev;
1224         vm_size_t prevsize, esize;
1225
1226         if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1227                 ++mycpu->gd_cnt.v_intrans_coll;
1228                 return;
1229         }
1230
1231         if (entry->maptype == VM_MAPTYPE_SUBMAP)
1232                 return;
1233
1234         prev = entry->prev;
1235         if (prev != &map->header) {
1236                 prevsize = prev->end - prev->start;
1237                 if ( (prev->end == entry->start) &&
1238                      (prev->maptype == entry->maptype) &&
1239                      (prev->object.vm_object == entry->object.vm_object) &&
1240                      (!prev->object.vm_object ||
1241                         (prev->offset + prevsize == entry->offset)) &&
1242                      (prev->eflags == entry->eflags) &&
1243                      (prev->protection == entry->protection) &&
1244                      (prev->max_protection == entry->max_protection) &&
1245                      (prev->inheritance == entry->inheritance) &&
1246                      (prev->wired_count == entry->wired_count)) {
1247                         if (map->first_free == prev)
1248                                 map->first_free = entry;
1249                         if (map->hint == prev)
1250                                 map->hint = entry;
1251                         vm_map_entry_unlink(map, prev);
1252                         entry->start = prev->start;
1253                         entry->offset = prev->offset;
1254                         if (prev->object.vm_object)
1255                                 vm_object_deallocate(prev->object.vm_object);
1256                         vm_map_entry_dispose(map, prev, countp);
1257                 }
1258         }
1259
1260         next = entry->next;
1261         if (next != &map->header) {
1262                 esize = entry->end - entry->start;
1263                 if ((entry->end == next->start) &&
1264                     (next->maptype == entry->maptype) &&
1265                     (next->object.vm_object == entry->object.vm_object) &&
1266                      (!entry->object.vm_object ||
1267                         (entry->offset + esize == next->offset)) &&
1268                     (next->eflags == entry->eflags) &&
1269                     (next->protection == entry->protection) &&
1270                     (next->max_protection == entry->max_protection) &&
1271                     (next->inheritance == entry->inheritance) &&
1272                     (next->wired_count == entry->wired_count)) {
1273                         if (map->first_free == next)
1274                                 map->first_free = entry;
1275                         if (map->hint == next)
1276                                 map->hint = entry;
1277                         vm_map_entry_unlink(map, next);
1278                         entry->end = next->end;
1279                         if (next->object.vm_object)
1280                                 vm_object_deallocate(next->object.vm_object);
1281                         vm_map_entry_dispose(map, next, countp);
1282                 }
1283         }
1284 }
1285
1286 /*
1287  * Asserts that the given entry begins at or after the specified address.
1288  * If necessary, it splits the entry into two.
1289  */
1290 #define vm_map_clip_start(map, entry, startaddr, countp)                \
1291 {                                                                       \
1292         if (startaddr > entry->start)                                   \
1293                 _vm_map_clip_start(map, entry, startaddr, countp);      \
1294 }
1295
1296 /*
1297  * This routine is called only when it is known that the entry must be split.
1298  *
1299  * The map must be exclusively locked.
1300  */
1301 static void
1302 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start,
1303                    int *countp)
1304 {
1305         vm_map_entry_t new_entry;
1306
1307         /*
1308          * Split off the front portion -- note that we must insert the new
1309          * entry BEFORE this one, so that this entry has the specified
1310          * starting address.
1311          */
1312
1313         vm_map_simplify_entry(map, entry, countp);
1314
1315         /*
1316          * If there is no object backing this entry, we might as well create
1317          * one now.  If we defer it, an object can get created after the map
1318          * is clipped, and individual objects will be created for the split-up
1319          * map.  This is a bit of a hack, but is also about the best place to
1320          * put this improvement.
1321          */
1322         if (entry->object.vm_object == NULL && !map->system_map) {
1323                 vm_map_entry_allocate_object(entry);
1324         }
1325
1326         new_entry = vm_map_entry_create(map, countp);
1327         *new_entry = *entry;
1328
1329         new_entry->end = start;
1330         entry->offset += (start - entry->start);
1331         entry->start = start;
1332
1333         vm_map_entry_link(map, entry->prev, new_entry);
1334
1335         switch(entry->maptype) {
1336         case VM_MAPTYPE_NORMAL:
1337         case VM_MAPTYPE_VPAGETABLE:
1338                 vm_object_reference(new_entry->object.vm_object);
1339                 break;
1340         default:
1341                 break;
1342         }
1343 }
1344
1345 /*
1346  * Asserts that the given entry ends at or before the specified address.
1347  * If necessary, it splits the entry into two.
1348  *
1349  * The map must be exclusively locked.
1350  */
1351 #define vm_map_clip_end(map, entry, endaddr, countp)            \
1352 {                                                               \
1353         if (endaddr < entry->end)                               \
1354                 _vm_map_clip_end(map, entry, endaddr, countp);  \
1355 }
1356
1357 /*
1358  * This routine is called only when it is known that the entry must be split.
1359  *
1360  * The map must be exclusively locked.
1361  */
1362 static void
1363 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end,
1364                  int *countp)
1365 {
1366         vm_map_entry_t new_entry;
1367
1368         /*
1369          * If there is no object backing this entry, we might as well create
1370          * one now.  If we defer it, an object can get created after the map
1371          * is clipped, and individual objects will be created for the split-up
1372          * map.  This is a bit of a hack, but is also about the best place to
1373          * put this improvement.
1374          */
1375
1376         if (entry->object.vm_object == NULL && !map->system_map) {
1377                 vm_map_entry_allocate_object(entry);
1378         }
1379
1380         /*
1381          * Create a new entry and insert it AFTER the specified entry
1382          */
1383
1384         new_entry = vm_map_entry_create(map, countp);
1385         *new_entry = *entry;
1386
1387         new_entry->start = entry->end = end;
1388         new_entry->offset += (end - entry->start);
1389
1390         vm_map_entry_link(map, entry, new_entry);
1391
1392         switch(entry->maptype) {
1393         case VM_MAPTYPE_NORMAL:
1394         case VM_MAPTYPE_VPAGETABLE:
1395                 vm_object_reference(new_entry->object.vm_object);
1396                 break;
1397         default:
1398                 break;
1399         }
1400 }
1401
1402 /*
1403  * Asserts that the starting and ending region addresses fall within the
1404  * valid range for the map.
1405  */
1406 #define VM_MAP_RANGE_CHECK(map, start, end)     \
1407 {                                               \
1408         if (start < vm_map_min(map))            \
1409                 start = vm_map_min(map);        \
1410         if (end > vm_map_max(map))              \
1411                 end = vm_map_max(map);          \
1412         if (start > end)                        \
1413                 start = end;                    \
1414 }
1415
1416 /*
1417  * Used to block when an in-transition collison occurs.  The map
1418  * is unlocked for the sleep and relocked before the return.
1419  */
1420 static
1421 void
1422 vm_map_transition_wait(vm_map_t map)
1423 {
1424         vm_map_unlock(map);
1425         tsleep(map, 0, "vment", 0);
1426         vm_map_lock(map);
1427 }
1428
1429 /*
1430  * When we do blocking operations with the map lock held it is
1431  * possible that a clip might have occured on our in-transit entry,
1432  * requiring an adjustment to the entry in our loop.  These macros
1433  * help the pageable and clip_range code deal with the case.  The
1434  * conditional costs virtually nothing if no clipping has occured.
1435  */
1436
1437 #define CLIP_CHECK_BACK(entry, save_start)              \
1438     do {                                                \
1439             while (entry->start != save_start) {        \
1440                     entry = entry->prev;                \
1441                     KASSERT(entry != &map->header, ("bad entry clip")); \
1442             }                                           \
1443     } while(0)
1444
1445 #define CLIP_CHECK_FWD(entry, save_end)                 \
1446     do {                                                \
1447             while (entry->end != save_end) {            \
1448                     entry = entry->next;                \
1449                     KASSERT(entry != &map->header, ("bad entry clip")); \
1450             }                                           \
1451     } while(0)
1452
1453
1454 /*
1455  * Clip the specified range and return the base entry.  The
1456  * range may cover several entries starting at the returned base
1457  * and the first and last entry in the covering sequence will be
1458  * properly clipped to the requested start and end address.
1459  *
1460  * If no holes are allowed you should pass the MAP_CLIP_NO_HOLES
1461  * flag.
1462  *
1463  * The MAP_ENTRY_IN_TRANSITION flag will be set for the entries
1464  * covered by the requested range.
1465  *
1466  * The map must be exclusively locked on entry and will remain locked
1467  * on return. If no range exists or the range contains holes and you
1468  * specified that no holes were allowed, NULL will be returned.  This
1469  * routine may temporarily unlock the map in order avoid a deadlock when
1470  * sleeping.
1471  */
1472 static
1473 vm_map_entry_t
1474 vm_map_clip_range(vm_map_t map, vm_offset_t start, vm_offset_t end, 
1475                   int *countp, int flags)
1476 {
1477         vm_map_entry_t start_entry;
1478         vm_map_entry_t entry;
1479
1480         /*
1481          * Locate the entry and effect initial clipping.  The in-transition
1482          * case does not occur very often so do not try to optimize it.
1483          */
1484 again:
1485         if (vm_map_lookup_entry(map, start, &start_entry) == FALSE)
1486                 return (NULL);
1487         entry = start_entry;
1488         if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1489                 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1490                 ++mycpu->gd_cnt.v_intrans_coll;
1491                 ++mycpu->gd_cnt.v_intrans_wait;
1492                 vm_map_transition_wait(map);
1493                 /*
1494                  * entry and/or start_entry may have been clipped while
1495                  * we slept, or may have gone away entirely.  We have
1496                  * to restart from the lookup.
1497                  */
1498                 goto again;
1499         }
1500
1501         /*
1502          * Since we hold an exclusive map lock we do not have to restart
1503          * after clipping, even though clipping may block in zalloc.
1504          */
1505         vm_map_clip_start(map, entry, start, countp);
1506         vm_map_clip_end(map, entry, end, countp);
1507         entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1508
1509         /*
1510          * Scan entries covered by the range.  When working on the next
1511          * entry a restart need only re-loop on the current entry which
1512          * we have already locked, since 'next' may have changed.  Also,
1513          * even though entry is safe, it may have been clipped so we
1514          * have to iterate forwards through the clip after sleeping.
1515          */
1516         while (entry->next != &map->header && entry->next->start < end) {
1517                 vm_map_entry_t next = entry->next;
1518
1519                 if (flags & MAP_CLIP_NO_HOLES) {
1520                         if (next->start > entry->end) {
1521                                 vm_map_unclip_range(map, start_entry,
1522                                         start, entry->end, countp, flags);
1523                                 return(NULL);
1524                         }
1525                 }
1526
1527                 if (next->eflags & MAP_ENTRY_IN_TRANSITION) {
1528                         vm_offset_t save_end = entry->end;
1529                         next->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1530                         ++mycpu->gd_cnt.v_intrans_coll;
1531                         ++mycpu->gd_cnt.v_intrans_wait;
1532                         vm_map_transition_wait(map);
1533
1534                         /*
1535                          * clips might have occured while we blocked.
1536                          */
1537                         CLIP_CHECK_FWD(entry, save_end);
1538                         CLIP_CHECK_BACK(start_entry, start);
1539                         continue;
1540                 }
1541                 /*
1542                  * No restart necessary even though clip_end may block, we
1543                  * are holding the map lock.
1544                  */
1545                 vm_map_clip_end(map, next, end, countp);
1546                 next->eflags |= MAP_ENTRY_IN_TRANSITION;
1547                 entry = next;
1548         }
1549         if (flags & MAP_CLIP_NO_HOLES) {
1550                 if (entry->end != end) {
1551                         vm_map_unclip_range(map, start_entry,
1552                                 start, entry->end, countp, flags);
1553                         return(NULL);
1554                 }
1555         }
1556         return(start_entry);
1557 }
1558
1559 /*
1560  * Undo the effect of vm_map_clip_range().  You should pass the same
1561  * flags and the same range that you passed to vm_map_clip_range().
1562  * This code will clear the in-transition flag on the entries and
1563  * wake up anyone waiting.  This code will also simplify the sequence
1564  * and attempt to merge it with entries before and after the sequence.
1565  *
1566  * The map must be locked on entry and will remain locked on return.
1567  *
1568  * Note that you should also pass the start_entry returned by
1569  * vm_map_clip_range().  However, if you block between the two calls
1570  * with the map unlocked please be aware that the start_entry may
1571  * have been clipped and you may need to scan it backwards to find
1572  * the entry corresponding with the original start address.  You are
1573  * responsible for this, vm_map_unclip_range() expects the correct
1574  * start_entry to be passed to it and will KASSERT otherwise.
1575  */
1576 static
1577 void
1578 vm_map_unclip_range(vm_map_t map, vm_map_entry_t start_entry,
1579                     vm_offset_t start, vm_offset_t end,
1580                     int *countp, int flags)
1581 {
1582         vm_map_entry_t entry;
1583
1584         entry = start_entry;
1585
1586         KASSERT(entry->start == start, ("unclip_range: illegal base entry"));
1587         while (entry != &map->header && entry->start < end) {
1588                 KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
1589                         ("in-transition flag not set during unclip on: %p",
1590                         entry));
1591                 KASSERT(entry->end <= end,
1592                         ("unclip_range: tail wasn't clipped"));
1593                 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1594                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1595                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1596                         wakeup(map);
1597                 }
1598                 entry = entry->next;
1599         }
1600
1601         /*
1602          * Simplification does not block so there is no restart case.
1603          */
1604         entry = start_entry;
1605         while (entry != &map->header && entry->start < end) {
1606                 vm_map_simplify_entry(map, entry, countp);
1607                 entry = entry->next;
1608         }
1609 }
1610
1611 /*
1612  * Mark the given range as handled by a subordinate map.
1613  *
1614  * This range must have been created with vm_map_find(), and no other
1615  * operations may have been performed on this range prior to calling
1616  * vm_map_submap().
1617  *
1618  * Submappings cannot be removed.
1619  *
1620  * No requirements.
1621  */
1622 int
1623 vm_map_submap(vm_map_t map, vm_offset_t start, vm_offset_t end, vm_map_t submap)
1624 {
1625         vm_map_entry_t entry;
1626         int result = KERN_INVALID_ARGUMENT;
1627         int count;
1628
1629         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1630         vm_map_lock(map);
1631
1632         VM_MAP_RANGE_CHECK(map, start, end);
1633
1634         if (vm_map_lookup_entry(map, start, &entry)) {
1635                 vm_map_clip_start(map, entry, start, &count);
1636         } else {
1637                 entry = entry->next;
1638         }
1639
1640         vm_map_clip_end(map, entry, end, &count);
1641
1642         if ((entry->start == start) && (entry->end == end) &&
1643             ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1644             (entry->object.vm_object == NULL)) {
1645                 entry->object.sub_map = submap;
1646                 entry->maptype = VM_MAPTYPE_SUBMAP;
1647                 result = KERN_SUCCESS;
1648         }
1649         vm_map_unlock(map);
1650         vm_map_entry_release(count);
1651
1652         return (result);
1653 }
1654
1655 /*
1656  * Sets the protection of the specified address region in the target map. 
1657  * If "set_max" is specified, the maximum protection is to be set;
1658  * otherwise, only the current protection is affected.
1659  *
1660  * The protection is not applicable to submaps, but is applicable to normal
1661  * maps and maps governed by virtual page tables.  For example, when operating
1662  * on a virtual page table our protection basically controls how COW occurs
1663  * on the backing object, whereas the virtual page table abstraction itself
1664  * is an abstraction for userland.
1665  *
1666  * No requirements.
1667  */
1668 int
1669 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1670                vm_prot_t new_prot, boolean_t set_max)
1671 {
1672         vm_map_entry_t current;
1673         vm_map_entry_t entry;
1674         int count;
1675
1676         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1677         vm_map_lock(map);
1678
1679         VM_MAP_RANGE_CHECK(map, start, end);
1680
1681         if (vm_map_lookup_entry(map, start, &entry)) {
1682                 vm_map_clip_start(map, entry, start, &count);
1683         } else {
1684                 entry = entry->next;
1685         }
1686
1687         /*
1688          * Make a first pass to check for protection violations.
1689          */
1690         current = entry;
1691         while ((current != &map->header) && (current->start < end)) {
1692                 if (current->maptype == VM_MAPTYPE_SUBMAP) {
1693                         vm_map_unlock(map);
1694                         vm_map_entry_release(count);
1695                         return (KERN_INVALID_ARGUMENT);
1696                 }
1697                 if ((new_prot & current->max_protection) != new_prot) {
1698                         vm_map_unlock(map);
1699                         vm_map_entry_release(count);
1700                         return (KERN_PROTECTION_FAILURE);
1701                 }
1702                 current = current->next;
1703         }
1704
1705         /*
1706          * Go back and fix up protections. [Note that clipping is not
1707          * necessary the second time.]
1708          */
1709         current = entry;
1710
1711         while ((current != &map->header) && (current->start < end)) {
1712                 vm_prot_t old_prot;
1713
1714                 vm_map_clip_end(map, current, end, &count);
1715
1716                 old_prot = current->protection;
1717                 if (set_max) {
1718                         current->protection =
1719                             (current->max_protection = new_prot) &
1720                             old_prot;
1721                 } else {
1722                         current->protection = new_prot;
1723                 }
1724
1725                 /*
1726                  * Update physical map if necessary. Worry about copy-on-write
1727                  * here -- CHECK THIS XXX
1728                  */
1729
1730                 if (current->protection != old_prot) {
1731 #define MASK(entry)     (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1732                                                         VM_PROT_ALL)
1733
1734                         pmap_protect(map->pmap, current->start,
1735                             current->end,
1736                             current->protection & MASK(current));
1737 #undef  MASK
1738                 }
1739
1740                 vm_map_simplify_entry(map, current, &count);
1741
1742                 current = current->next;
1743         }
1744
1745         vm_map_unlock(map);
1746         vm_map_entry_release(count);
1747         return (KERN_SUCCESS);
1748 }
1749
1750 /*
1751  * This routine traverses a processes map handling the madvise
1752  * system call.  Advisories are classified as either those effecting
1753  * the vm_map_entry structure, or those effecting the underlying
1754  * objects.
1755  *
1756  * The <value> argument is used for extended madvise calls.
1757  *
1758  * No requirements.
1759  */
1760 int
1761 vm_map_madvise(vm_map_t map, vm_offset_t start, vm_offset_t end,
1762                int behav, off_t value)
1763 {
1764         vm_map_entry_t current, entry;
1765         int modify_map = 0;
1766         int error = 0;
1767         int count;
1768
1769         /*
1770          * Some madvise calls directly modify the vm_map_entry, in which case
1771          * we need to use an exclusive lock on the map and we need to perform 
1772          * various clipping operations.  Otherwise we only need a read-lock
1773          * on the map.
1774          */
1775
1776         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1777
1778         switch(behav) {
1779         case MADV_NORMAL:
1780         case MADV_SEQUENTIAL:
1781         case MADV_RANDOM:
1782         case MADV_NOSYNC:
1783         case MADV_AUTOSYNC:
1784         case MADV_NOCORE:
1785         case MADV_CORE:
1786         case MADV_SETMAP:
1787         case MADV_INVAL:
1788                 modify_map = 1;
1789                 vm_map_lock(map);
1790                 break;
1791         case MADV_WILLNEED:
1792         case MADV_DONTNEED:
1793         case MADV_FREE:
1794                 vm_map_lock_read(map);
1795                 break;
1796         default:
1797                 vm_map_entry_release(count);
1798                 return (EINVAL);
1799         }
1800
1801         /*
1802          * Locate starting entry and clip if necessary.
1803          */
1804
1805         VM_MAP_RANGE_CHECK(map, start, end);
1806
1807         if (vm_map_lookup_entry(map, start, &entry)) {
1808                 if (modify_map)
1809                         vm_map_clip_start(map, entry, start, &count);
1810         } else {
1811                 entry = entry->next;
1812         }
1813
1814         if (modify_map) {
1815                 /*
1816                  * madvise behaviors that are implemented in the vm_map_entry.
1817                  *
1818                  * We clip the vm_map_entry so that behavioral changes are
1819                  * limited to the specified address range.
1820                  */
1821                 for (current = entry;
1822                      (current != &map->header) && (current->start < end);
1823                      current = current->next
1824                 ) {
1825                         if (current->maptype == VM_MAPTYPE_SUBMAP)
1826                                 continue;
1827
1828                         vm_map_clip_end(map, current, end, &count);
1829
1830                         switch (behav) {
1831                         case MADV_NORMAL:
1832                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1833                                 break;
1834                         case MADV_SEQUENTIAL:
1835                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1836                                 break;
1837                         case MADV_RANDOM:
1838                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1839                                 break;
1840                         case MADV_NOSYNC:
1841                                 current->eflags |= MAP_ENTRY_NOSYNC;
1842                                 break;
1843                         case MADV_AUTOSYNC:
1844                                 current->eflags &= ~MAP_ENTRY_NOSYNC;
1845                                 break;
1846                         case MADV_NOCORE:
1847                                 current->eflags |= MAP_ENTRY_NOCOREDUMP;
1848                                 break;
1849                         case MADV_CORE:
1850                                 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
1851                                 break;
1852                         case MADV_INVAL:
1853                                 /*
1854                                  * Invalidate the related pmap entries, used
1855                                  * to flush portions of the real kernel's
1856                                  * pmap when the caller has removed or
1857                                  * modified existing mappings in a virtual
1858                                  * page table.
1859                                  */
1860                                 pmap_remove(map->pmap,
1861                                             current->start, current->end);
1862                                 break;
1863                         case MADV_SETMAP:
1864                                 /*
1865                                  * Set the page directory page for a map
1866                                  * governed by a virtual page table.  Mark
1867                                  * the entry as being governed by a virtual
1868                                  * page table if it is not.
1869                                  *
1870                                  * XXX the page directory page is stored
1871                                  * in the avail_ssize field if the map_entry.
1872                                  *
1873                                  * XXX the map simplification code does not
1874                                  * compare this field so weird things may
1875                                  * happen if you do not apply this function
1876                                  * to the entire mapping governed by the
1877                                  * virtual page table.
1878                                  */
1879                                 if (current->maptype != VM_MAPTYPE_VPAGETABLE) {
1880                                         error = EINVAL;
1881                                         break;
1882                                 }
1883                                 current->aux.master_pde = value;
1884                                 pmap_remove(map->pmap,
1885                                             current->start, current->end);
1886                                 break;
1887                         default:
1888                                 error = EINVAL;
1889                                 break;
1890                         }
1891                         vm_map_simplify_entry(map, current, &count);
1892                 }
1893                 vm_map_unlock(map);
1894         } else {
1895                 vm_pindex_t pindex;
1896                 int count;
1897
1898                 /*
1899                  * madvise behaviors that are implemented in the underlying
1900                  * vm_object.
1901                  *
1902                  * Since we don't clip the vm_map_entry, we have to clip
1903                  * the vm_object pindex and count.
1904                  *
1905                  * NOTE!  We currently do not support these functions on
1906                  * virtual page tables.
1907                  */
1908                 for (current = entry;
1909                      (current != &map->header) && (current->start < end);
1910                      current = current->next
1911                 ) {
1912                         vm_offset_t useStart;
1913
1914                         if (current->maptype != VM_MAPTYPE_NORMAL)
1915                                 continue;
1916
1917                         pindex = OFF_TO_IDX(current->offset);
1918                         count = atop(current->end - current->start);
1919                         useStart = current->start;
1920
1921                         if (current->start < start) {
1922                                 pindex += atop(start - current->start);
1923                                 count -= atop(start - current->start);
1924                                 useStart = start;
1925                         }
1926                         if (current->end > end)
1927                                 count -= atop(current->end - end);
1928
1929                         if (count <= 0)
1930                                 continue;
1931
1932                         vm_object_madvise(current->object.vm_object,
1933                                           pindex, count, behav);
1934
1935                         /*
1936                          * Try to populate the page table.  Mappings governed
1937                          * by virtual page tables cannot be pre-populated
1938                          * without a lot of work so don't try.
1939                          */
1940                         if (behav == MADV_WILLNEED &&
1941                             current->maptype != VM_MAPTYPE_VPAGETABLE) {
1942                                 pmap_object_init_pt(
1943                                     map->pmap, 
1944                                     useStart,
1945                                     current->protection,
1946                                     current->object.vm_object,
1947                                     pindex, 
1948                                     (count << PAGE_SHIFT),
1949                                     MAP_PREFAULT_MADVISE
1950                                 );
1951                         }
1952                 }
1953                 vm_map_unlock_read(map);
1954         }
1955         vm_map_entry_release(count);
1956         return(error);
1957 }       
1958
1959
1960 /*
1961  * Sets the inheritance of the specified address range in the target map.
1962  * Inheritance affects how the map will be shared with child maps at the
1963  * time of vm_map_fork.
1964  */
1965 int
1966 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
1967                vm_inherit_t new_inheritance)
1968 {
1969         vm_map_entry_t entry;
1970         vm_map_entry_t temp_entry;
1971         int count;
1972
1973         switch (new_inheritance) {
1974         case VM_INHERIT_NONE:
1975         case VM_INHERIT_COPY:
1976         case VM_INHERIT_SHARE:
1977                 break;
1978         default:
1979                 return (KERN_INVALID_ARGUMENT);
1980         }
1981
1982         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1983         vm_map_lock(map);
1984
1985         VM_MAP_RANGE_CHECK(map, start, end);
1986
1987         if (vm_map_lookup_entry(map, start, &temp_entry)) {
1988                 entry = temp_entry;
1989                 vm_map_clip_start(map, entry, start, &count);
1990         } else
1991                 entry = temp_entry->next;
1992
1993         while ((entry != &map->header) && (entry->start < end)) {
1994                 vm_map_clip_end(map, entry, end, &count);
1995
1996                 entry->inheritance = new_inheritance;
1997
1998                 vm_map_simplify_entry(map, entry, &count);
1999
2000                 entry = entry->next;
2001         }
2002         vm_map_unlock(map);
2003         vm_map_entry_release(count);
2004         return (KERN_SUCCESS);
2005 }
2006
2007 /*
2008  * Implement the semantics of mlock
2009  */
2010 int
2011 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t real_end,
2012               boolean_t new_pageable)
2013 {
2014         vm_map_entry_t entry;
2015         vm_map_entry_t start_entry;
2016         vm_offset_t end;
2017         int rv = KERN_SUCCESS;
2018         int count;
2019
2020         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2021         vm_map_lock(map);
2022         VM_MAP_RANGE_CHECK(map, start, real_end);
2023         end = real_end;
2024
2025         start_entry = vm_map_clip_range(map, start, end, &count,
2026                                         MAP_CLIP_NO_HOLES);
2027         if (start_entry == NULL) {
2028                 vm_map_unlock(map);
2029                 vm_map_entry_release(count);
2030                 return (KERN_INVALID_ADDRESS);
2031         }
2032
2033         if (new_pageable == 0) {
2034                 entry = start_entry;
2035                 while ((entry != &map->header) && (entry->start < end)) {
2036                         vm_offset_t save_start;
2037                         vm_offset_t save_end;
2038
2039                         /*
2040                          * Already user wired or hard wired (trivial cases)
2041                          */
2042                         if (entry->eflags & MAP_ENTRY_USER_WIRED) {
2043                                 entry = entry->next;
2044                                 continue;
2045                         }
2046                         if (entry->wired_count != 0) {
2047                                 entry->wired_count++;
2048                                 entry->eflags |= MAP_ENTRY_USER_WIRED;
2049                                 entry = entry->next;
2050                                 continue;
2051                         }
2052
2053                         /*
2054                          * A new wiring requires instantiation of appropriate
2055                          * management structures and the faulting in of the
2056                          * page.
2057                          */
2058                         if (entry->maptype != VM_MAPTYPE_SUBMAP) {
2059                                 int copyflag = entry->eflags &
2060                                                MAP_ENTRY_NEEDS_COPY;
2061                                 if (copyflag && ((entry->protection &
2062                                                   VM_PROT_WRITE) != 0)) {
2063                                         vm_map_entry_shadow(entry);
2064                                 } else if (entry->object.vm_object == NULL &&
2065                                            !map->system_map) {
2066                                         vm_map_entry_allocate_object(entry);
2067                                 }
2068                         }
2069                         entry->wired_count++;
2070                         entry->eflags |= MAP_ENTRY_USER_WIRED;
2071
2072                         /*
2073                          * Now fault in the area.  Note that vm_fault_wire()
2074                          * may release the map lock temporarily, it will be
2075                          * relocked on return.  The in-transition
2076                          * flag protects the entries. 
2077                          */
2078                         save_start = entry->start;
2079                         save_end = entry->end;
2080                         rv = vm_fault_wire(map, entry, TRUE);
2081                         if (rv) {
2082                                 CLIP_CHECK_BACK(entry, save_start);
2083                                 for (;;) {
2084                                         KASSERT(entry->wired_count == 1, ("bad wired_count on entry"));
2085                                         entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2086                                         entry->wired_count = 0;
2087                                         if (entry->end == save_end)
2088                                                 break;
2089                                         entry = entry->next;
2090                                         KASSERT(entry != &map->header, ("bad entry clip during backout"));
2091                                 }
2092                                 end = save_start;       /* unwire the rest */
2093                                 break;
2094                         }
2095                         /*
2096                          * note that even though the entry might have been
2097                          * clipped, the USER_WIRED flag we set prevents
2098                          * duplication so we do not have to do a 
2099                          * clip check.
2100                          */
2101                         entry = entry->next;
2102                 }
2103
2104                 /*
2105                  * If we failed fall through to the unwiring section to
2106                  * unwire what we had wired so far.  'end' has already
2107                  * been adjusted.
2108                  */
2109                 if (rv)
2110                         new_pageable = 1;
2111
2112                 /*
2113                  * start_entry might have been clipped if we unlocked the
2114                  * map and blocked.  No matter how clipped it has gotten
2115                  * there should be a fragment that is on our start boundary.
2116                  */
2117                 CLIP_CHECK_BACK(start_entry, start);
2118         }
2119
2120         /*
2121          * Deal with the unwiring case.
2122          */
2123         if (new_pageable) {
2124                 /*
2125                  * This is the unwiring case.  We must first ensure that the
2126                  * range to be unwired is really wired down.  We know there
2127                  * are no holes.
2128                  */
2129                 entry = start_entry;
2130                 while ((entry != &map->header) && (entry->start < end)) {
2131                         if ((entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2132                                 rv = KERN_INVALID_ARGUMENT;
2133                                 goto done;
2134                         }
2135                         KASSERT(entry->wired_count != 0, ("wired count was 0 with USER_WIRED set! %p", entry));
2136                         entry = entry->next;
2137                 }
2138
2139                 /*
2140                  * Now decrement the wiring count for each region. If a region
2141                  * becomes completely unwired, unwire its physical pages and
2142                  * mappings.
2143                  */
2144                 /*
2145                  * The map entries are processed in a loop, checking to
2146                  * make sure the entry is wired and asserting it has a wired
2147                  * count. However, another loop was inserted more-or-less in
2148                  * the middle of the unwiring path. This loop picks up the
2149                  * "entry" loop variable from the first loop without first
2150                  * setting it to start_entry. Naturally, the secound loop
2151                  * is never entered and the pages backing the entries are
2152                  * never unwired. This can lead to a leak of wired pages.
2153                  */
2154                 entry = start_entry;
2155                 while ((entry != &map->header) && (entry->start < end)) {
2156                         KASSERT(entry->eflags & MAP_ENTRY_USER_WIRED,
2157                                 ("expected USER_WIRED on entry %p", entry));
2158                         entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2159                         entry->wired_count--;
2160                         if (entry->wired_count == 0)
2161                                 vm_fault_unwire(map, entry);
2162                         entry = entry->next;
2163                 }
2164         }
2165 done:
2166         vm_map_unclip_range(map, start_entry, start, real_end, &count,
2167                 MAP_CLIP_NO_HOLES);
2168         map->timestamp++;
2169         vm_map_unlock(map);
2170         vm_map_entry_release(count);
2171         return (rv);
2172 }
2173
2174 /*
2175  * Sets the pageability of the specified address range in the target map.
2176  * Regions specified as not pageable require locked-down physical
2177  * memory and physical page maps.
2178  *
2179  * The map must not be locked, but a reference must remain to the map
2180  * throughout the call.
2181  *
2182  * This function may be called via the zalloc path and must properly
2183  * reserve map entries for kernel_map.
2184  *
2185  * No requirements.
2186  */
2187 int
2188 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t real_end, int kmflags)
2189 {
2190         vm_map_entry_t entry;
2191         vm_map_entry_t start_entry;
2192         vm_offset_t end;
2193         int rv = KERN_SUCCESS;
2194         int count;
2195
2196         if (kmflags & KM_KRESERVE)
2197                 count = vm_map_entry_kreserve(MAP_RESERVE_COUNT);
2198         else
2199                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2200         vm_map_lock(map);
2201         VM_MAP_RANGE_CHECK(map, start, real_end);
2202         end = real_end;
2203
2204         start_entry = vm_map_clip_range(map, start, end, &count,
2205                                         MAP_CLIP_NO_HOLES);
2206         if (start_entry == NULL) {
2207                 vm_map_unlock(map);
2208                 rv = KERN_INVALID_ADDRESS;
2209                 goto failure;
2210         }
2211         if ((kmflags & KM_PAGEABLE) == 0) {
2212                 /*
2213                  * Wiring.  
2214                  *
2215                  * 1.  Holding the write lock, we create any shadow or zero-fill
2216                  * objects that need to be created. Then we clip each map
2217                  * entry to the region to be wired and increment its wiring
2218                  * count.  We create objects before clipping the map entries
2219                  * to avoid object proliferation.
2220                  *
2221                  * 2.  We downgrade to a read lock, and call vm_fault_wire to
2222                  * fault in the pages for any newly wired area (wired_count is
2223                  * 1).
2224                  *
2225                  * Downgrading to a read lock for vm_fault_wire avoids a 
2226                  * possible deadlock with another process that may have faulted
2227                  * on one of the pages to be wired (it would mark the page busy,
2228                  * blocking us, then in turn block on the map lock that we
2229                  * hold).  Because of problems in the recursive lock package,
2230                  * we cannot upgrade to a write lock in vm_map_lookup.  Thus,
2231                  * any actions that require the write lock must be done
2232                  * beforehand.  Because we keep the read lock on the map, the
2233                  * copy-on-write status of the entries we modify here cannot
2234                  * change.
2235                  */
2236                 entry = start_entry;
2237                 while ((entry != &map->header) && (entry->start < end)) {
2238                         /*
2239                          * Trivial case if the entry is already wired
2240                          */
2241                         if (entry->wired_count) {
2242                                 entry->wired_count++;
2243                                 entry = entry->next;
2244                                 continue;
2245                         }
2246
2247                         /*
2248                          * The entry is being newly wired, we have to setup
2249                          * appropriate management structures.  A shadow 
2250                          * object is required for a copy-on-write region,
2251                          * or a normal object for a zero-fill region.  We
2252                          * do not have to do this for entries that point to sub
2253                          * maps because we won't hold the lock on the sub map.
2254                          */
2255                         if (entry->maptype != VM_MAPTYPE_SUBMAP) {
2256                                 int copyflag = entry->eflags &
2257                                                MAP_ENTRY_NEEDS_COPY;
2258                                 if (copyflag && ((entry->protection &
2259                                                   VM_PROT_WRITE) != 0)) {
2260                                         vm_map_entry_shadow(entry);
2261                                 } else if (entry->object.vm_object == NULL &&
2262                                            !map->system_map) {
2263                                         vm_map_entry_allocate_object(entry);
2264                                 }
2265                         }
2266
2267                         entry->wired_count++;
2268                         entry = entry->next;
2269                 }
2270
2271                 /*
2272                  * Pass 2.
2273                  */
2274
2275                 /*
2276                  * HACK HACK HACK HACK
2277                  *
2278                  * vm_fault_wire() temporarily unlocks the map to avoid
2279                  * deadlocks.  The in-transition flag from vm_map_clip_range
2280                  * call should protect us from changes while the map is
2281                  * unlocked.  T
2282                  *
2283                  * NOTE: Previously this comment stated that clipping might
2284                  *       still occur while the entry is unlocked, but from
2285                  *       what I can tell it actually cannot.
2286                  *
2287                  *       It is unclear whether the CLIP_CHECK_*() calls
2288                  *       are still needed but we keep them in anyway.
2289                  *
2290                  * HACK HACK HACK HACK
2291                  */
2292
2293                 entry = start_entry;
2294                 while (entry != &map->header && entry->start < end) {
2295                         /*
2296                          * If vm_fault_wire fails for any page we need to undo
2297                          * what has been done.  We decrement the wiring count
2298                          * for those pages which have not yet been wired (now)
2299                          * and unwire those that have (later).
2300                          */
2301                         vm_offset_t save_start = entry->start;
2302                         vm_offset_t save_end = entry->end;
2303
2304                         if (entry->wired_count == 1)
2305                                 rv = vm_fault_wire(map, entry, FALSE);
2306                         if (rv) {
2307                                 CLIP_CHECK_BACK(entry, save_start);
2308                                 for (;;) {
2309                                         KASSERT(entry->wired_count == 1, ("wired_count changed unexpectedly"));
2310                                         entry->wired_count = 0;
2311                                         if (entry->end == save_end)
2312                                                 break;
2313                                         entry = entry->next;
2314                                         KASSERT(entry != &map->header, ("bad entry clip during backout"));
2315                                 }
2316                                 end = save_start;
2317                                 break;
2318                         }
2319                         CLIP_CHECK_FWD(entry, save_end);
2320                         entry = entry->next;
2321                 }
2322
2323                 /*
2324                  * If a failure occured undo everything by falling through
2325                  * to the unwiring code.  'end' has already been adjusted
2326                  * appropriately.
2327                  */
2328                 if (rv)
2329                         kmflags |= KM_PAGEABLE;
2330
2331                 /*
2332                  * start_entry is still IN_TRANSITION but may have been 
2333                  * clipped since vm_fault_wire() unlocks and relocks the
2334                  * map.  No matter how clipped it has gotten there should
2335                  * be a fragment that is on our start boundary.
2336                  */
2337                 CLIP_CHECK_BACK(start_entry, start);
2338         }
2339
2340         if (kmflags & KM_PAGEABLE) {
2341                 /*
2342                  * This is the unwiring case.  We must first ensure that the
2343                  * range to be unwired is really wired down.  We know there
2344                  * are no holes.
2345                  */
2346                 entry = start_entry;
2347                 while ((entry != &map->header) && (entry->start < end)) {
2348                         if (entry->wired_count == 0) {
2349                                 rv = KERN_INVALID_ARGUMENT;
2350                                 goto done;
2351                         }
2352                         entry = entry->next;
2353                 }
2354
2355                 /*
2356                  * Now decrement the wiring count for each region. If a region
2357                  * becomes completely unwired, unwire its physical pages and
2358                  * mappings.
2359                  */
2360                 entry = start_entry;
2361                 while ((entry != &map->header) && (entry->start < end)) {
2362                         entry->wired_count--;
2363                         if (entry->wired_count == 0)
2364                                 vm_fault_unwire(map, entry);
2365                         entry = entry->next;
2366                 }
2367         }
2368 done:
2369         vm_map_unclip_range(map, start_entry, start, real_end,
2370                             &count, MAP_CLIP_NO_HOLES);
2371         map->timestamp++;
2372         vm_map_unlock(map);
2373 failure:
2374         if (kmflags & KM_KRESERVE)
2375                 vm_map_entry_krelease(count);
2376         else
2377                 vm_map_entry_release(count);
2378         return (rv);
2379 }
2380
2381 /*
2382  * Mark a newly allocated address range as wired but do not fault in
2383  * the pages.  The caller is expected to load the pages into the object.
2384  *
2385  * The map must be locked on entry and will remain locked on return.
2386  * No other requirements.
2387  */
2388 void
2389 vm_map_set_wired_quick(vm_map_t map, vm_offset_t addr, vm_size_t size,
2390                        int *countp)
2391 {
2392         vm_map_entry_t scan;
2393         vm_map_entry_t entry;
2394
2395         entry = vm_map_clip_range(map, addr, addr + size,
2396                                   countp, MAP_CLIP_NO_HOLES);
2397         for (scan = entry;
2398              scan != &map->header && scan->start < addr + size;
2399              scan = scan->next) {
2400             KKASSERT(entry->wired_count == 0);
2401             entry->wired_count = 1;                                              
2402         }
2403         vm_map_unclip_range(map, entry, addr, addr + size,
2404                             countp, MAP_CLIP_NO_HOLES);
2405 }
2406
2407 /*
2408  * Push any dirty cached pages in the address range to their pager.
2409  * If syncio is TRUE, dirty pages are written synchronously.
2410  * If invalidate is TRUE, any cached pages are freed as well.
2411  *
2412  * This routine is called by sys_msync()
2413  *
2414  * Returns an error if any part of the specified range is not mapped.
2415  *
2416  * No requirements.
2417  */
2418 int
2419 vm_map_clean(vm_map_t map, vm_offset_t start, vm_offset_t end,
2420              boolean_t syncio, boolean_t invalidate)
2421 {
2422         vm_map_entry_t current;
2423         vm_map_entry_t entry;
2424         vm_size_t size;
2425         vm_object_t object;
2426         vm_ooffset_t offset;
2427
2428         vm_map_lock_read(map);
2429         VM_MAP_RANGE_CHECK(map, start, end);
2430         if (!vm_map_lookup_entry(map, start, &entry)) {
2431                 vm_map_unlock_read(map);
2432                 return (KERN_INVALID_ADDRESS);
2433         }
2434         /*
2435          * Make a first pass to check for holes.
2436          */
2437         for (current = entry; current->start < end; current = current->next) {
2438                 if (current->maptype == VM_MAPTYPE_SUBMAP) {
2439                         vm_map_unlock_read(map);
2440                         return (KERN_INVALID_ARGUMENT);
2441                 }
2442                 if (end > current->end &&
2443                     (current->next == &map->header ||
2444                         current->end != current->next->start)) {
2445                         vm_map_unlock_read(map);
2446                         return (KERN_INVALID_ADDRESS);
2447                 }
2448         }
2449
2450         if (invalidate)
2451                 pmap_remove(vm_map_pmap(map), start, end);
2452
2453         /*
2454          * Make a second pass, cleaning/uncaching pages from the indicated
2455          * objects as we go.
2456          *
2457          * Hold vm_token to avoid blocking in vm_object_reference()
2458          */
2459         lwkt_gettoken(&vm_token);
2460         lwkt_gettoken(&vmobj_token);
2461
2462         for (current = entry; current->start < end; current = current->next) {
2463                 offset = current->offset + (start - current->start);
2464                 size = (end <= current->end ? end : current->end) - start;
2465                 if (current->maptype == VM_MAPTYPE_SUBMAP) {
2466                         vm_map_t smap;
2467                         vm_map_entry_t tentry;
2468                         vm_size_t tsize;
2469
2470                         smap = current->object.sub_map;
2471                         vm_map_lock_read(smap);
2472                         vm_map_lookup_entry(smap, offset, &tentry);
2473                         tsize = tentry->end - offset;
2474                         if (tsize < size)
2475                                 size = tsize;
2476                         object = tentry->object.vm_object;
2477                         offset = tentry->offset + (offset - tentry->start);
2478                         vm_map_unlock_read(smap);
2479                 } else {
2480                         object = current->object.vm_object;
2481                 }
2482                 /*
2483                  * Note that there is absolutely no sense in writing out
2484                  * anonymous objects, so we track down the vnode object
2485                  * to write out.
2486                  * We invalidate (remove) all pages from the address space
2487                  * anyway, for semantic correctness.
2488                  *
2489                  * note: certain anonymous maps, such as MAP_NOSYNC maps,
2490                  * may start out with a NULL object.
2491                  */
2492                 while (object && object->backing_object) {
2493                         offset += object->backing_object_offset;
2494                         object = object->backing_object;
2495                         if (object->size < OFF_TO_IDX( offset + size))
2496                                 size = IDX_TO_OFF(object->size) - offset;
2497                 }
2498                 if (object && (object->type == OBJT_VNODE) && 
2499                     (current->protection & VM_PROT_WRITE) &&
2500                     (object->flags & OBJ_NOMSYNC) == 0) {
2501                         /*
2502                          * Flush pages if writing is allowed, invalidate them
2503                          * if invalidation requested.  Pages undergoing I/O
2504                          * will be ignored by vm_object_page_remove().
2505                          *
2506                          * We cannot lock the vnode and then wait for paging
2507                          * to complete without deadlocking against vm_fault.
2508                          * Instead we simply call vm_object_page_remove() and
2509                          * allow it to block internally on a page-by-page 
2510                          * basis when it encounters pages undergoing async 
2511                          * I/O.
2512                          */
2513                         int flags;
2514
2515                         vm_object_reference_locked(object);
2516                         vn_lock(object->handle, LK_EXCLUSIVE | LK_RETRY);
2517                         flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
2518                         flags |= invalidate ? OBJPC_INVAL : 0;
2519
2520                         /*
2521                          * When operating on a virtual page table just
2522                          * flush the whole object.  XXX we probably ought
2523                          * to 
2524                          */
2525                         switch(current->maptype) {
2526                         case VM_MAPTYPE_NORMAL:
2527                                 vm_object_page_clean(object,
2528                                     OFF_TO_IDX(offset),
2529                                     OFF_TO_IDX(offset + size + PAGE_MASK),
2530                                     flags);
2531                                 break;
2532                         case VM_MAPTYPE_VPAGETABLE:
2533                                 vm_object_page_clean(object, 0, 0, flags);
2534                                 break;
2535                         }
2536                         vn_unlock(((struct vnode *)object->handle));
2537                         vm_object_deallocate_locked(object);
2538                 }
2539                 if (object && invalidate &&
2540                    ((object->type == OBJT_VNODE) ||
2541                     (object->type == OBJT_DEVICE))) {
2542                         int clean_only = 
2543                                 (object->type == OBJT_DEVICE) ? FALSE : TRUE;
2544                         vm_object_reference_locked(object);
2545                         switch(current->maptype) {
2546                         case VM_MAPTYPE_NORMAL:
2547                                 vm_object_page_remove(object,
2548                                     OFF_TO_IDX(offset),
2549                                     OFF_TO_IDX(offset + size + PAGE_MASK),
2550                                     clean_only);
2551                                 break;
2552                         case VM_MAPTYPE_VPAGETABLE:
2553                                 vm_object_page_remove(object, 0, 0, clean_only);
2554                                 break;
2555                         }
2556                         vm_object_deallocate_locked(object);
2557                 }
2558                 start += size;
2559         }
2560
2561         lwkt_reltoken(&vmobj_token);
2562         lwkt_reltoken(&vm_token);
2563         vm_map_unlock_read(map);
2564
2565         return (KERN_SUCCESS);
2566 }
2567
2568 /*
2569  * Make the region specified by this entry pageable.
2570  *
2571  * The vm_map must be exclusively locked.
2572  */
2573 static void 
2574 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2575 {
2576         entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2577         entry->wired_count = 0;
2578         vm_fault_unwire(map, entry);
2579 }
2580
2581 /*
2582  * Deallocate the given entry from the target map.
2583  *
2584  * The vm_map must be exclusively locked.
2585  */
2586 static void
2587 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry, int *countp)
2588 {
2589         vm_map_entry_unlink(map, entry);
2590         map->size -= entry->end - entry->start;
2591
2592         switch(entry->maptype) {
2593         case VM_MAPTYPE_NORMAL:
2594         case VM_MAPTYPE_VPAGETABLE:
2595                 vm_object_deallocate(entry->object.vm_object);
2596                 break;
2597         default:
2598                 break;
2599         }
2600
2601         vm_map_entry_dispose(map, entry, countp);
2602 }
2603
2604 /*
2605  * Deallocates the given address range from the target map.
2606  *
2607  * The vm_map must be exclusively locked.
2608  */
2609 int
2610 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end, int *countp)
2611 {
2612         vm_object_t object;
2613         vm_map_entry_t entry;
2614         vm_map_entry_t first_entry;
2615
2616         ASSERT_VM_MAP_LOCKED(map);
2617 again:
2618         /*
2619          * Find the start of the region, and clip it.  Set entry to point
2620          * at the first record containing the requested address or, if no
2621          * such record exists, the next record with a greater address.  The
2622          * loop will run from this point until a record beyond the termination
2623          * address is encountered.
2624          *
2625          * map->hint must be adjusted to not point to anything we delete,
2626          * so set it to the entry prior to the one being deleted.
2627          *
2628          * GGG see other GGG comment.
2629          */
2630         if (vm_map_lookup_entry(map, start, &first_entry)) {
2631                 entry = first_entry;
2632                 vm_map_clip_start(map, entry, start, countp);
2633                 map->hint = entry->prev;        /* possible problem XXX */
2634         } else {
2635                 map->hint = first_entry;        /* possible problem XXX */
2636                 entry = first_entry->next;
2637         }
2638
2639         /*
2640          * If a hole opens up prior to the current first_free then
2641          * adjust first_free.  As with map->hint, map->first_free
2642          * cannot be left set to anything we might delete.
2643          */
2644         if (entry == &map->header) {
2645                 map->first_free = &map->header;
2646         } else if (map->first_free->start >= start) {
2647                 map->first_free = entry->prev;
2648         }
2649
2650         /*
2651          * Step through all entries in this region
2652          */
2653         while ((entry != &map->header) && (entry->start < end)) {
2654                 vm_map_entry_t next;
2655                 vm_offset_t s, e;
2656                 vm_pindex_t offidxstart, offidxend, count;
2657
2658                 /*
2659                  * If we hit an in-transition entry we have to sleep and
2660                  * retry.  It's easier (and not really slower) to just retry
2661                  * since this case occurs so rarely and the hint is already
2662                  * pointing at the right place.  We have to reset the
2663                  * start offset so as not to accidently delete an entry
2664                  * another process just created in vacated space.
2665                  */
2666                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2667                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2668                         start = entry->start;
2669                         ++mycpu->gd_cnt.v_intrans_coll;
2670                         ++mycpu->gd_cnt.v_intrans_wait;
2671                         vm_map_transition_wait(map);
2672                         goto again;
2673                 }
2674                 vm_map_clip_end(map, entry, end, countp);
2675
2676                 s = entry->start;
2677                 e = entry->end;
2678                 next = entry->next;
2679
2680                 offidxstart = OFF_TO_IDX(entry->offset);
2681                 count = OFF_TO_IDX(e - s);
2682                 object = entry->object.vm_object;
2683
2684                 /*
2685                  * Unwire before removing addresses from the pmap; otherwise,
2686                  * unwiring will put the entries back in the pmap.
2687                  */
2688                 if (entry->wired_count != 0)
2689                         vm_map_entry_unwire(map, entry);
2690
2691                 offidxend = offidxstart + count;
2692
2693                 /*
2694                  * Hold vm_token when manipulating vm_objects,
2695                  *
2696                  * Hold vmobj_token when potentially adding or removing
2697                  * objects (collapse requires both).
2698                  */
2699                 lwkt_gettoken(&vm_token);
2700                 lwkt_gettoken(&vmobj_token);
2701
2702                 if (object == &kernel_object) {
2703                         vm_object_page_remove(object, offidxstart,
2704                                               offidxend, FALSE);
2705                 } else {
2706                         pmap_remove(map->pmap, s, e);
2707
2708                         if (object != NULL &&
2709                             object->ref_count != 1 &&
2710                             (object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) ==
2711                              OBJ_ONEMAPPING &&
2712                             (object->type == OBJT_DEFAULT ||
2713                              object->type == OBJT_SWAP)) {
2714                                 vm_object_collapse(object);
2715                                 vm_object_page_remove(object, offidxstart,
2716                                                       offidxend, FALSE);
2717                                 if (object->type == OBJT_SWAP) {
2718                                         swap_pager_freespace(object,
2719                                                              offidxstart,
2720                                                              count);
2721                                 }
2722                                 if (offidxend >= object->size &&
2723                                     offidxstart < object->size) {
2724                                         object->size = offidxstart;
2725                                 }
2726                         }
2727                 }
2728                 lwkt_reltoken(&vmobj_token);
2729                 lwkt_reltoken(&vm_token);
2730
2731                 /*
2732                  * Delete the entry (which may delete the object) only after
2733                  * removing all pmap entries pointing to its pages.
2734                  * (Otherwise, its page frames may be reallocated, and any
2735                  * modify bits will be set in the wrong object!)
2736                  */
2737                 vm_map_entry_delete(map, entry, countp);
2738                 entry = next;
2739         }
2740         return (KERN_SUCCESS);
2741 }
2742
2743 /*
2744  * Remove the given address range from the target map.
2745  * This is the exported form of vm_map_delete.
2746  *
2747  * No requirements.
2748  */
2749 int
2750 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2751 {
2752         int result;
2753         int count;
2754
2755         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2756         vm_map_lock(map);
2757         VM_MAP_RANGE_CHECK(map, start, end);
2758         result = vm_map_delete(map, start, end, &count);
2759         vm_map_unlock(map);
2760         vm_map_entry_release(count);
2761
2762         return (result);
2763 }
2764
2765 /*
2766  * Assert that the target map allows the specified privilege on the
2767  * entire address region given.  The entire region must be allocated.
2768  *
2769  * The caller must specify whether the vm_map is already locked or not.
2770  */
2771 boolean_t
2772 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2773                         vm_prot_t protection, boolean_t have_lock)
2774 {
2775         vm_map_entry_t entry;
2776         vm_map_entry_t tmp_entry;
2777         boolean_t result;
2778
2779         if (have_lock == FALSE)
2780                 vm_map_lock_read(map);
2781
2782         if (!vm_map_lookup_entry(map, start, &tmp_entry)) {
2783                 if (have_lock == FALSE)
2784                         vm_map_unlock_read(map);
2785                 return (FALSE);
2786         }
2787         entry = tmp_entry;
2788
2789         result = TRUE;
2790         while (start < end) {
2791                 if (entry == &map->header) {
2792                         result = FALSE;
2793                         break;
2794                 }
2795                 /*
2796                  * No holes allowed!
2797                  */
2798
2799                 if (start < entry->start) {
2800                         result = FALSE;
2801                         break;
2802                 }
2803                 /*
2804                  * Check protection associated with entry.
2805                  */
2806
2807                 if ((entry->protection & protection) != protection) {
2808                         result = FALSE;
2809                         break;
2810                 }
2811                 /* go to next entry */
2812
2813                 start = entry->end;
2814                 entry = entry->next;
2815         }
2816         if (have_lock == FALSE)
2817                 vm_map_unlock_read(map);
2818         return (result);
2819 }
2820
2821 /*
2822  * Split the pages in a map entry into a new object.  This affords
2823  * easier removal of unused pages, and keeps object inheritance from
2824  * being a negative impact on memory usage.
2825  *
2826  * The vm_map must be exclusively locked.
2827  */
2828 static void
2829 vm_map_split(vm_map_entry_t entry)
2830 {
2831         vm_page_t m;
2832         vm_object_t orig_object, new_object, source;
2833         vm_offset_t s, e;
2834         vm_pindex_t offidxstart, offidxend, idx;
2835         vm_size_t size;
2836         vm_ooffset_t offset;
2837
2838         orig_object = entry->object.vm_object;
2839         if (orig_object->type != OBJT_DEFAULT && orig_object->type != OBJT_SWAP)
2840                 return;
2841         if (orig_object->ref_count <= 1)
2842                 return;
2843
2844         offset = entry->offset;
2845         s = entry->start;
2846         e = entry->end;
2847
2848         offidxstart = OFF_TO_IDX(offset);
2849         offidxend = offidxstart + OFF_TO_IDX(e - s);
2850         size = offidxend - offidxstart;
2851
2852         switch(orig_object->type) {
2853         case OBJT_DEFAULT:
2854                 new_object = default_pager_alloc(NULL, IDX_TO_OFF(size),
2855                                                  VM_PROT_ALL, 0);
2856                 break;
2857         case OBJT_SWAP:
2858                 new_object = swap_pager_alloc(NULL, IDX_TO_OFF(size),
2859                                               VM_PROT_ALL, 0);
2860                 break;
2861         default:
2862                 /* not reached */
2863                 new_object = NULL;
2864                 KKASSERT(0);
2865         }
2866         if (new_object == NULL)
2867                 return;
2868
2869         /*
2870          * vm_token required when manipulating vm_objects.
2871          */
2872         lwkt_gettoken(&vm_token);
2873         lwkt_gettoken(&vmobj_token);
2874
2875         source = orig_object->backing_object;
2876         if (source != NULL) {
2877                 /* Referenced by new_object */
2878                 vm_object_reference_locked(source);
2879                 LIST_INSERT_HEAD(&source->shadow_head,
2880                                  new_object, shadow_list);
2881                 vm_object_clear_flag(source, OBJ_ONEMAPPING);
2882                 new_object->backing_object_offset = 
2883                         orig_object->backing_object_offset +
2884                         IDX_TO_OFF(offidxstart);
2885                 new_object->backing_object = source;
2886                 source->shadow_count++;
2887                 source->generation++;
2888         }
2889
2890         for (idx = 0; idx < size; idx++) {
2891                 vm_page_t m;
2892
2893         retry:
2894                 m = vm_page_lookup(orig_object, offidxstart + idx);
2895                 if (m == NULL)
2896                         continue;
2897
2898                 /*
2899                  * We must wait for pending I/O to complete before we can
2900                  * rename the page.
2901                  *
2902                  * We do not have to VM_PROT_NONE the page as mappings should
2903                  * not be changed by this operation.
2904                  */
2905                 if (vm_page_sleep_busy(m, TRUE, "spltwt"))
2906                         goto retry;
2907                 vm_page_busy(m);
2908                 vm_page_rename(m, new_object, idx);
2909                 /* page automatically made dirty by rename and cache handled */
2910                 vm_page_busy(m);
2911         }
2912
2913         if (orig_object->type == OBJT_SWAP) {
2914                 vm_object_pip_add(orig_object, 1);
2915                 /*
2916                  * copy orig_object pages into new_object
2917                  * and destroy unneeded pages in
2918                  * shadow object.
2919                  */
2920                 swap_pager_copy(orig_object, new_object, offidxstart, 0);
2921                 vm_object_pip_wakeup(orig_object);
2922         }
2923
2924         /*
2925          * Wakeup the pages we played with.  No spl protection is needed
2926          * for a simple wakeup.
2927          */
2928         for (idx = 0; idx < size; idx++) {
2929                 m = vm_page_lookup(new_object, idx);
2930                 if (m)
2931                         vm_page_wakeup(m);
2932         }
2933
2934         entry->object.vm_object = new_object;
2935         entry->offset = 0LL;
2936         vm_object_deallocate_locked(orig_object);
2937         lwkt_reltoken(&vmobj_token);
2938         lwkt_reltoken(&vm_token);
2939 }
2940
2941 /*
2942  * Copies the contents of the source entry to the destination
2943  * entry.  The entries *must* be aligned properly.
2944  *
2945  * The vm_map must be exclusively locked.
2946  * vm_token must be held
2947  */
2948 static void
2949 vm_map_copy_entry(vm_map_t src_map, vm_map_t dst_map,
2950         vm_map_entry_t src_entry, vm_map_entry_t dst_entry)
2951 {
2952         vm_object_t src_object;
2953
2954         if (dst_entry->maptype == VM_MAPTYPE_SUBMAP)
2955                 return;
2956         if (src_entry->maptype == VM_MAPTYPE_SUBMAP)
2957                 return;
2958
2959         ASSERT_LWKT_TOKEN_HELD(&vm_token);
2960         lwkt_gettoken(&vmobj_token);            /* required for collapse */
2961
2962         if (src_entry->wired_count == 0) {
2963                 /*
2964                  * If the source entry is marked needs_copy, it is already
2965                  * write-protected.
2966                  */
2967                 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2968                         pmap_protect(src_map->pmap,
2969                             src_entry->start,
2970                             src_entry->end,
2971                             src_entry->protection & ~VM_PROT_WRITE);
2972                 }
2973
2974                 /*
2975                  * Make a copy of the object.
2976                  */
2977                 if ((src_object = src_entry->object.vm_object) != NULL) {
2978                         if ((src_object->handle == NULL) &&
2979                                 (src_object->type == OBJT_DEFAULT ||
2980                                  src_object->type == OBJT_SWAP)) {
2981                                 vm_object_collapse(src_object);
2982                                 if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
2983                                         vm_map_split(src_entry);
2984                                         src_object = src_entry->object.vm_object;
2985                                 }
2986                         }
2987
2988                         vm_object_reference_locked(src_object);
2989                         vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2990                         dst_entry->object.vm_object = src_object;
2991                         src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2992                         dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2993                         dst_entry->offset = src_entry->offset;
2994                 } else {
2995                         dst_entry->object.vm_object = NULL;
2996                         dst_entry->offset = 0;
2997                 }
2998
2999                 pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
3000                     dst_entry->end - dst_entry->start, src_entry->start);
3001         } else {
3002                 /*
3003                  * Of course, wired down pages can't be set copy-on-write.
3004                  * Cause wired pages to be copied into the new map by
3005                  * simulating faults (the new pages are pageable)
3006                  */
3007                 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
3008         }
3009         lwkt_reltoken(&vmobj_token);
3010 }
3011
3012 /*
3013  * vmspace_fork:
3014  * Create a new process vmspace structure and vm_map
3015  * based on those of an existing process.  The new map
3016  * is based on the old map, according to the inheritance
3017  * values on the regions in that map.
3018  *
3019  * The source map must not be locked.
3020  * No requirements.
3021  */
3022 struct vmspace *
3023 vmspace_fork(struct vmspace *vm1)
3024 {
3025         struct vmspace *vm2;
3026         vm_map_t old_map = &vm1->vm_map;
3027         vm_map_t new_map;
3028         vm_map_entry_t old_entry;
3029         vm_map_entry_t new_entry;
3030         vm_object_t object;
3031         int count;
3032
3033         lwkt_gettoken(&vm_token);
3034         lwkt_gettoken(&vmspace_token);
3035         lwkt_gettoken(&vmobj_token);
3036         vm_map_lock(old_map);
3037         old_map->infork = 1;
3038
3039         /*
3040          * XXX Note: upcalls are not copied.
3041          */
3042         vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
3043         bcopy(&vm1->vm_startcopy, &vm2->vm_startcopy,
3044             (caddr_t)&vm1->vm_endcopy - (caddr_t)&vm1->vm_startcopy);
3045         new_map = &vm2->vm_map; /* XXX */
3046         new_map->timestamp = 1;
3047
3048         vm_map_lock(new_map);
3049
3050         count = 0;
3051         old_entry = old_map->header.next;
3052         while (old_entry != &old_map->header) {
3053                 ++count;
3054                 old_entry = old_entry->next;
3055         }
3056
3057         count = vm_map_entry_reserve(count + MAP_RESERVE_COUNT);
3058
3059         old_entry = old_map->header.next;
3060         while (old_entry != &old_map->header) {
3061                 if (old_entry->maptype == VM_MAPTYPE_SUBMAP)
3062                         panic("vm_map_fork: encountered a submap");
3063
3064                 switch (old_entry->inheritance) {
3065                 case VM_INHERIT_NONE:
3066                         break;
3067                 case VM_INHERIT_SHARE:
3068                         /*
3069                          * Clone the entry, creating the shared object if
3070                          * necessary.
3071                          */
3072                         object = old_entry->object.vm_object;
3073                         if (object == NULL) {
3074                                 vm_map_entry_allocate_object(old_entry);
3075                                 object = old_entry->object.vm_object;
3076                         }
3077
3078                         /*
3079                          * Add the reference before calling vm_map_entry_shadow
3080                          * to insure that a shadow object is created.
3081                          */
3082                         vm_object_reference_locked(object);
3083                         if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3084                                 vm_map_entry_shadow(old_entry);
3085                                 /* Transfer the second reference too. */
3086                                 vm_object_reference_locked(
3087                                     old_entry->object.vm_object);
3088                                 vm_object_deallocate_locked(object);
3089                                 object = old_entry->object.vm_object;
3090                         }
3091                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
3092
3093                         /*
3094                          * Clone the entry, referencing the shared object.
3095                          */
3096                         new_entry = vm_map_entry_create(new_map, &count);
3097                         *new_entry = *old_entry;
3098                         new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3099                         new_entry->wired_count = 0;
3100
3101                         /*
3102                          * Insert the entry into the new map -- we know we're
3103                          * inserting at the end of the new map.
3104                          */
3105
3106                         vm_map_entry_link(new_map, new_map->header.prev,
3107                                           new_entry);
3108
3109                         /*
3110                          * Update the physical map
3111                          */
3112                         pmap_copy(new_map->pmap, old_map->pmap,
3113                             new_entry->start,
3114                             (old_entry->end - old_entry->start),
3115                             old_entry->start);
3116                         break;
3117                 case VM_INHERIT_COPY:
3118                         /*
3119                          * Clone the entry and link into the map.
3120                          */
3121                         new_entry = vm_map_entry_create(new_map, &count);
3122                         *new_entry = *old_entry;
3123                         new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3124                         new_entry->wired_count = 0;
3125                         new_entry->object.vm_object = NULL;
3126                         vm_map_entry_link(new_map, new_map->header.prev,
3127                                           new_entry);
3128                         vm_map_copy_entry(old_map, new_map, old_entry,
3129                                           new_entry);
3130                         break;
3131                 }
3132                 old_entry = old_entry->next;
3133         }
3134
3135         new_map->size = old_map->size;
3136         old_map->infork = 0;
3137         vm_map_unlock(old_map);
3138         vm_map_unlock(new_map);
3139         vm_map_entry_release(count);
3140
3141         lwkt_reltoken(&vmobj_token);
3142         lwkt_reltoken(&vmspace_token);
3143         lwkt_reltoken(&vm_token);
3144
3145         return (vm2);
3146 }
3147
3148 /*
3149  * Create an auto-grow stack entry
3150  *
3151  * No requirements.
3152  */
3153 int
3154 vm_map_stack (vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3155               int flags, vm_prot_t prot, vm_prot_t max, int cow)
3156 {
3157         vm_map_entry_t  prev_entry;
3158         vm_map_entry_t  new_stack_entry;
3159         vm_size_t       init_ssize;
3160         int             rv;
3161         int             count;
3162         vm_offset_t     tmpaddr;
3163
3164         cow |= MAP_IS_STACK;
3165
3166         if (max_ssize < sgrowsiz)
3167                 init_ssize = max_ssize;
3168         else
3169                 init_ssize = sgrowsiz;
3170
3171         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
3172         vm_map_lock(map);
3173
3174         /*
3175          * Find space for the mapping
3176          */
3177         if ((flags & (MAP_FIXED | MAP_TRYFIXED)) == 0) {
3178                 if (vm_map_findspace(map, addrbos, max_ssize, 1,
3179                                      flags, &tmpaddr)) {
3180                         vm_map_unlock(map);
3181                         vm_map_entry_release(count);
3182                         return (KERN_NO_SPACE);
3183                 }
3184                 addrbos = tmpaddr;
3185         }
3186
3187         /* If addr is already mapped, no go */
3188         if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
3189                 vm_map_unlock(map);
3190                 vm_map_entry_release(count);
3191                 return (KERN_NO_SPACE);
3192         }
3193
3194 #if 0
3195         /* XXX already handled by kern_mmap() */
3196         /* If we would blow our VMEM resource limit, no go */
3197         if (map->size + init_ssize >
3198             curproc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
3199                 vm_map_unlock(map);
3200                 vm_map_entry_release(count);
3201                 return (KERN_NO_SPACE);
3202         }
3203 #endif
3204
3205         /*
3206          * If we can't accomodate max_ssize in the current mapping,
3207          * no go.  However, we need to be aware that subsequent user
3208          * mappings might map into the space we have reserved for
3209          * stack, and currently this space is not protected.  
3210          * 
3211          * Hopefully we will at least detect this condition 
3212          * when we try to grow the stack.
3213          */
3214         if ((prev_entry->next != &map->header) &&
3215             (prev_entry->next->start < addrbos + max_ssize)) {
3216                 vm_map_unlock(map);
3217                 vm_map_entry_release(count);
3218                 return (KERN_NO_SPACE);
3219         }
3220
3221         /*
3222          * We initially map a stack of only init_ssize.  We will
3223          * grow as needed later.  Since this is to be a grow 
3224          * down stack, we map at the top of the range.
3225          *
3226          * Note: we would normally expect prot and max to be
3227          * VM_PROT_ALL, and cow to be 0.  Possibly we should
3228          * eliminate these as input parameters, and just
3229          * pass these values here in the insert call.
3230          */
3231         rv = vm_map_insert(map, &count,
3232                            NULL, 0, addrbos + max_ssize - init_ssize,
3233                            addrbos + max_ssize,
3234                            VM_MAPTYPE_NORMAL,
3235                            prot, max,
3236                            cow);
3237
3238         /* Now set the avail_ssize amount */
3239         if (rv == KERN_SUCCESS) {
3240                 if (prev_entry != &map->header)
3241                         vm_map_clip_end(map, prev_entry, addrbos + max_ssize - init_ssize, &count);
3242                 new_stack_entry = prev_entry->next;
3243                 if (new_stack_entry->end   != addrbos + max_ssize ||
3244                     new_stack_entry->start != addrbos + max_ssize - init_ssize)
3245                         panic ("Bad entry start/end for new stack entry");
3246                 else 
3247                         new_stack_entry->aux.avail_ssize = max_ssize - init_ssize;
3248         }
3249
3250         vm_map_unlock(map);
3251         vm_map_entry_release(count);
3252         return (rv);
3253 }
3254
3255 /*
3256  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
3257  * desired address is already mapped, or if we successfully grow
3258  * the stack.  Also returns KERN_SUCCESS if addr is outside the
3259  * stack range (this is strange, but preserves compatibility with
3260  * the grow function in vm_machdep.c).
3261  *
3262  * No requirements.
3263  */
3264 int
3265 vm_map_growstack (struct proc *p, vm_offset_t addr)
3266 {
3267         vm_map_entry_t prev_entry;
3268         vm_map_entry_t stack_entry;
3269         vm_map_entry_t new_stack_entry;
3270         struct vmspace *vm = p->p_vmspace;
3271         vm_map_t map = &vm->vm_map;
3272         vm_offset_t    end;
3273         int grow_amount;
3274         int rv = KERN_SUCCESS;
3275         int is_procstack;
3276         int use_read_lock = 1;
3277         int count;
3278
3279         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
3280 Retry:
3281         if (use_read_lock)
3282                 vm_map_lock_read(map);
3283         else
3284                 vm_map_lock(map);
3285
3286         /* If addr is already in the entry range, no need to grow.*/
3287         if (vm_map_lookup_entry(map, addr, &prev_entry))
3288                 goto done;
3289
3290         if ((stack_entry = prev_entry->next) == &map->header)
3291                 goto done;
3292         if (prev_entry == &map->header) 
3293                 end = stack_entry->start - stack_entry->aux.avail_ssize;
3294         else
3295                 end = prev_entry->end;
3296
3297         /*
3298          * This next test mimics the old grow function in vm_machdep.c.
3299          * It really doesn't quite make sense, but we do it anyway
3300          * for compatibility.
3301          *
3302          * If not growable stack, return success.  This signals the
3303          * caller to proceed as he would normally with normal vm.
3304          */
3305         if (stack_entry->aux.avail_ssize < 1 ||
3306             addr >= stack_entry->start ||
3307             addr <  stack_entry->start - stack_entry->aux.avail_ssize) {
3308                 goto done;
3309         } 
3310         
3311         /* Find the minimum grow amount */
3312         grow_amount = roundup (stack_entry->start - addr, PAGE_SIZE);
3313         if (grow_amount > stack_entry->aux.avail_ssize) {
3314                 rv = KERN_NO_SPACE;
3315                 goto done;
3316         }
3317
3318         /*
3319          * If there is no longer enough space between the entries
3320          * nogo, and adjust the available space.  Note: this 
3321          * should only happen if the user has mapped into the
3322          * stack area after the stack was created, and is
3323          * probably an error.
3324          *
3325          * This also effectively destroys any guard page the user
3326          * might have intended by limiting the stack size.
3327          */
3328         if (grow_amount > stack_entry->start - end) {
3329                 if (use_read_lock && vm_map_lock_upgrade(map)) {
3330                         use_read_lock = 0;
3331                         goto Retry;
3332                 }
3333                 use_read_lock = 0;
3334                 stack_entry->aux.avail_ssize = stack_entry->start - end;
3335                 rv = KERN_NO_SPACE;
3336                 goto done;
3337         }
3338
3339         is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr;
3340
3341         /* If this is the main process stack, see if we're over the 
3342          * stack limit.
3343          */
3344         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
3345                              p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
3346                 rv = KERN_NO_SPACE;
3347                 goto done;
3348         }
3349
3350         /* Round up the grow amount modulo SGROWSIZ */
3351         grow_amount = roundup (grow_amount, sgrowsiz);
3352         if (grow_amount > stack_entry->aux.avail_ssize) {
3353                 grow_amount = stack_entry->aux.avail_ssize;
3354         }
3355         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
3356                              p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
3357                 grow_amount = p->p_rlimit[RLIMIT_STACK].rlim_cur -
3358                               ctob(vm->vm_ssize);
3359         }
3360
3361         /* If we would blow our VMEM resource limit, no go */
3362         if (map->size + grow_amount > p->p_rlimit[RLIMIT_VMEM].rlim_cur) {
3363                 rv = KERN_NO_SPACE;
3364                 goto done;
3365         }
3366
3367         if (use_read_lock && vm_map_lock_upgrade(map)) {
3368                 use_read_lock = 0;
3369                 goto Retry;
3370         }
3371         use_read_lock = 0;
3372
3373         /* Get the preliminary new entry start value */
3374         addr = stack_entry->start - grow_amount;
3375
3376         /* If this puts us into the previous entry, cut back our growth
3377          * to the available space.  Also, see the note above.
3378          */
3379         if (addr < end) {
3380                 stack_entry->aux.avail_ssize = stack_entry->start - end;
3381                 addr = end;
3382         }
3383
3384         rv = vm_map_insert(map, &count,
3385                            NULL, 0, addr, stack_entry->start,
3386                            VM_MAPTYPE_NORMAL,
3387                            VM_PROT_ALL, VM_PROT_ALL,
3388                            0);
3389
3390         /* Adjust the available stack space by the amount we grew. */
3391         if (rv == KERN_SUCCESS) {
3392                 if (prev_entry != &map->header)
3393                         vm_map_clip_end(map, prev_entry, addr, &count);
3394                 new_stack_entry = prev_entry->next;
3395                 if (new_stack_entry->end   != stack_entry->start  ||
3396                     new_stack_entry->start != addr)
3397                         panic ("Bad stack grow start/end in new stack entry");
3398                 else {
3399                         new_stack_entry->aux.avail_ssize =
3400                                 stack_entry->aux.avail_ssize -
3401                                 (new_stack_entry->end - new_stack_entry->start);
3402                         if (is_procstack)
3403                                 vm->vm_ssize += btoc(new_stack_entry->end -
3404                                                      new_stack_entry->start);
3405                 }
3406         }
3407
3408 done:
3409         if (use_read_lock)
3410                 vm_map_unlock_read(map);
3411         else
3412                 vm_map_unlock(map);
3413         vm_map_entry_release(count);
3414         return (rv);
3415 }
3416
3417 /*
3418  * Unshare the specified VM space for exec.  If other processes are
3419  * mapped to it, then create a new one.  The new vmspace is null.
3420  *
3421  * No requirements.
3422  */
3423 void
3424 vmspace_exec(struct proc *p, struct vmspace *vmcopy) 
3425 {
3426         struct vmspace *oldvmspace = p->p_vmspace;
3427         struct vmspace *newvmspace;
3428         vm_map_t map = &p->p_vmspace->vm_map;
3429
3430         /*
3431          * If we are execing a resident vmspace we fork it, otherwise
3432          * we create a new vmspace.  Note that exitingcnt and upcalls
3433          * are not copied to the new vmspace.
3434          */
3435         lwkt_gettoken(&vmspace_token);
3436         if (vmcopy)  {
3437                 newvmspace = vmspace_fork(vmcopy);
3438         } else {
3439                 newvmspace = vmspace_alloc(map->min_offset, map->max_offset);
3440                 bcopy(&oldvmspace->vm_startcopy, &newvmspace->vm_startcopy,
3441                       (caddr_t)&oldvmspace->vm_endcopy -
3442                        (caddr_t)&oldvmspace->vm_startcopy);
3443         }
3444
3445         /*
3446          * Finish initializing the vmspace before assigning it
3447          * to the process.  The vmspace will become the current vmspace
3448          * if p == curproc.
3449          */
3450         pmap_pinit2(vmspace_pmap(newvmspace));
3451         pmap_replacevm(p, newvmspace, 0);
3452         sysref_put(&oldvmspace->vm_sysref);
3453         lwkt_reltoken(&vmspace_token);
3454 }
3455
3456 /*
3457  * Unshare the specified VM space for forcing COW.  This
3458  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3459  *
3460  * The exitingcnt test is not strictly necessary but has been
3461  * included for code sanity (to make the code a bit more deterministic).
3462  */
3463 void
3464 vmspace_unshare(struct proc *p) 
3465 {
3466         struct vmspace *oldvmspace = p->p_vmspace;
3467         struct vmspace *newvmspace;
3468
3469         lwkt_gettoken(&vmspace_token);
3470         if (oldvmspace->vm_sysref.refcnt == 1 && oldvmspace->vm_exitingcnt == 0)
3471                 return;
3472         newvmspace = vmspace_fork(oldvmspace);
3473         pmap_pinit2(vmspace_pmap(newvmspace));
3474         pmap_replacevm(p, newvmspace, 0);
3475         sysref_put(&oldvmspace->vm_sysref);
3476         lwkt_reltoken(&vmspace_token);
3477 }
3478
3479 /*
3480  * Finds the VM object, offset, and protection for a given virtual address
3481  * in the specified map, assuming a page fault of the type specified.
3482  *
3483  * Leaves the map in question locked for read; return values are guaranteed
3484  * until a vm_map_lookup_done call is performed.  Note that the map argument
3485  * is in/out; the returned map must be used in the call to vm_map_lookup_done.
3486  *
3487  * A handle (out_entry) is returned for use in vm_map_lookup_done, to make
3488  * that fast.
3489  *
3490  * If a lookup is requested with "write protection" specified, the map may
3491  * be changed to perform virtual copying operations, although the data
3492  * referenced will remain the same.
3493  *
3494  * No requirements.
3495  */
3496 int
3497 vm_map_lookup(vm_map_t *var_map,                /* IN/OUT */
3498               vm_offset_t vaddr,
3499               vm_prot_t fault_typea,
3500               vm_map_entry_t *out_entry,        /* OUT */
3501               vm_object_t *object,              /* OUT */
3502               vm_pindex_t *pindex,              /* OUT */
3503               vm_prot_t *out_prot,              /* OUT */
3504               boolean_t *wired)                 /* OUT */
3505 {
3506         vm_map_entry_t entry;
3507         vm_map_t map = *var_map;
3508         vm_prot_t prot;
3509         vm_prot_t fault_type = fault_typea;
3510         int use_read_lock = 1;
3511         int rv = KERN_SUCCESS;
3512
3513 RetryLookup:
3514         if (use_read_lock)
3515                 vm_map_lock_read(map);
3516         else
3517                 vm_map_lock(map);
3518
3519         /*
3520          * If the map has an interesting hint, try it before calling full
3521          * blown lookup routine.
3522          */
3523         entry = map->hint;
3524         *out_entry = entry;
3525
3526         if ((entry == &map->header) ||
3527             (vaddr < entry->start) || (vaddr >= entry->end)) {
3528                 vm_map_entry_t tmp_entry;
3529
3530                 /*
3531                  * Entry was either not a valid hint, or the vaddr was not
3532                  * contained in the entry, so do a full lookup.
3533                  */
3534                 if (!vm_map_lookup_entry(map, vaddr, &tmp_entry)) {
3535                         rv = KERN_INVALID_ADDRESS;
3536                         goto done;
3537                 }
3538
3539                 entry = tmp_entry;
3540                 *out_entry = entry;
3541         }
3542         
3543         /*
3544          * Handle submaps.
3545          */
3546         if (entry->maptype == VM_MAPTYPE_SUBMAP) {
3547                 vm_map_t old_map = map;
3548
3549                 *var_map = map = entry->object.sub_map;
3550                 if (use_read_lock)
3551                         vm_map_unlock_read(old_map);
3552                 else
3553                         vm_map_unlock(old_map);
3554                 use_read_lock = 1;
3555                 goto RetryLookup;
3556         }
3557
3558         /*
3559          * Check whether this task is allowed to have this page.
3560          * Note the special case for MAP_ENTRY_COW
3561          * pages with an override.  This is to implement a forced
3562          * COW for debuggers.
3563          */
3564
3565         if (fault_type & VM_PROT_OVERRIDE_WRITE)
3566                 prot = entry->max_protection;
3567         else
3568                 prot = entry->protection;
3569
3570         fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3571         if ((fault_type & prot) != fault_type) {
3572                 rv = KERN_PROTECTION_FAILURE;
3573                 goto done;
3574         }
3575
3576         if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3577             (entry->eflags & MAP_ENTRY_COW) &&
3578             (fault_type & VM_PROT_WRITE) &&
3579             (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
3580                 rv = KERN_PROTECTION_FAILURE;
3581                 goto done;
3582         }
3583
3584         /*
3585          * If this page is not pageable, we have to get it for all possible
3586          * accesses.
3587          */
3588         *wired = (entry->wired_count != 0);
3589         if (*wired)
3590                 prot = fault_type = entry->protection;
3591
3592         /*
3593          * Virtual page tables may need to update the accessed (A) bit
3594          * in a page table entry.  Upgrade the fault to a write fault for
3595          * that case if the map will support it.  If the map does not support
3596          * it the page table entry simply will not be updated.
3597          */
3598         if (entry->maptype == VM_MAPTYPE_VPAGETABLE) {
3599                 if (prot & VM_PROT_WRITE)
3600                         fault_type |= VM_PROT_WRITE;
3601         }
3602
3603         /*
3604          * If the entry was copy-on-write, we either ...
3605          */
3606         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3607                 /*
3608                  * If we want to write the page, we may as well handle that
3609                  * now since we've got the map locked.
3610                  *
3611                  * If we don't need to write the page, we just demote the
3612                  * permissions allowed.
3613                  */
3614
3615                 if (fault_type & VM_PROT_WRITE) {
3616                         /*
3617                          * Make a new object, and place it in the object
3618                          * chain.  Note that no new references have appeared
3619                          * -- one just moved from the map to the new
3620                          * object.
3621                          */
3622
3623                         if (use_read_lock && vm_map_lock_upgrade(map)) {
3624                                 use_read_lock = 0;
3625                                 goto RetryLookup;
3626                         }
3627                         use_read_lock = 0;
3628
3629                         vm_map_entry_shadow(entry);
3630                 } else {
3631                         /*
3632                          * We're attempting to read a copy-on-write page --
3633                          * don't allow writes.
3634                          */
3635
3636                         prot &= ~VM_PROT_WRITE;
3637                 }
3638         }
3639
3640         /*
3641          * Create an object if necessary.
3642          */
3643         if (entry->object.vm_object == NULL &&
3644             !map->system_map) {
3645                 if (use_read_lock && vm_map_lock_upgrade(map))  {
3646                         use_read_lock = 0;
3647                         goto RetryLookup;
3648                 }
3649                 use_read_lock = 0;
3650                 vm_map_entry_allocate_object(entry);
3651         }
3652
3653         /*
3654          * Return the object/offset from this entry.  If the entry was
3655          * copy-on-write or empty, it has been fixed up.
3656          */
3657
3658         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3659         *object = entry->object.vm_object;
3660
3661         /*
3662          * Return whether this is the only map sharing this data.  On
3663          * success we return with a read lock held on the map.  On failure
3664          * we return with the map unlocked.
3665          */
3666         *out_prot = prot;
3667 done:
3668         if (rv == KERN_SUCCESS) {
3669                 if (use_read_lock == 0)
3670                         vm_map_lock_downgrade(map);
3671         } else if (use_read_lock) {
3672                 vm_map_unlock_read(map);
3673         } else {
3674                 vm_map_unlock(map);
3675         }
3676         return (rv);
3677 }
3678
3679 /*
3680  * Releases locks acquired by a vm_map_lookup()
3681  * (according to the handle returned by that lookup).
3682  *
3683  * No other requirements.
3684  */
3685 void
3686 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry, int count)
3687 {
3688         /*
3689          * Unlock the main-level map
3690          */
3691         vm_map_unlock_read(map);
3692         if (count)
3693                 vm_map_entry_release(count);
3694 }
3695
3696 #include "opt_ddb.h"
3697 #ifdef DDB
3698 #include <sys/kernel.h>
3699
3700 #include <ddb/ddb.h>
3701
3702 /*
3703  * Debugging only
3704  */
3705 DB_SHOW_COMMAND(map, vm_map_print)
3706 {
3707         static int nlines;
3708         /* XXX convert args. */
3709         vm_map_t map = (vm_map_t)addr;
3710         boolean_t full = have_addr;
3711
3712         vm_map_entry_t entry;
3713
3714         db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
3715             (void *)map,
3716             (void *)map->pmap, map->nentries, map->timestamp);
3717         nlines++;
3718
3719         if (!full && db_indent)
3720                 return;
3721
3722         db_indent += 2;
3723         for (entry = map->header.next; entry != &map->header;
3724             entry = entry->next) {
3725                 db_iprintf("map entry %p: start=%p, end=%p\n",
3726                     (void *)entry, (void *)entry->start, (void *)entry->end);
3727                 nlines++;
3728                 {
3729                         static char *inheritance_name[4] =
3730                         {"share", "copy", "none", "donate_copy"};
3731
3732                         db_iprintf(" prot=%x/%x/%s",
3733                             entry->protection,
3734                             entry->max_protection,
3735                             inheritance_name[(int)(unsigned char)entry->inheritance]);
3736                         if (entry->wired_count != 0)
3737                                 db_printf(", wired");
3738                 }
3739                 if (entry->maptype == VM_MAPTYPE_SUBMAP) {
3740                         /* XXX no %qd in kernel.  Truncate entry->offset. */
3741                         db_printf(", share=%p, offset=0x%lx\n",
3742                             (void *)entry->object.sub_map,
3743                             (long)entry->offset);
3744                         nlines++;
3745                         if ((entry->prev == &map->header) ||
3746                             (entry->prev->object.sub_map !=
3747                                 entry->object.sub_map)) {
3748                                 db_indent += 2;
3749                                 vm_map_print((db_expr_t)(intptr_t)
3750                                              entry->object.sub_map,
3751                                              full, 0, NULL);
3752                                 db_indent -= 2;
3753                         }
3754                 } else {
3755                         /* XXX no %qd in kernel.  Truncate entry->offset. */
3756                         db_printf(", object=%p, offset=0x%lx",
3757                             (void *)entry->object.vm_object,
3758                             (long)entry->offset);
3759                         if (entry->eflags & MAP_ENTRY_COW)
3760                                 db_printf(", copy (%s)",
3761                                     (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
3762                         db_printf("\n");
3763                         nlines++;
3764
3765                         if ((entry->prev == &map->header) ||
3766                             (entry->prev->object.vm_object !=
3767                                 entry->object.vm_object)) {
3768                                 db_indent += 2;
3769                                 vm_object_print((db_expr_t)(intptr_t)
3770                                                 entry->object.vm_object,
3771                                                 full, 0, NULL);
3772                                 nlines += 4;
3773                                 db_indent -= 2;
3774                         }
3775                 }
3776         }
3777         db_indent -= 2;
3778         if (db_indent == 0)
3779                 nlines = 0;
3780 }
3781
3782 /*
3783  * Debugging only
3784  */
3785 DB_SHOW_COMMAND(procvm, procvm)
3786 {
3787         struct proc *p;
3788
3789         if (have_addr) {
3790                 p = (struct proc *) addr;
3791         } else {
3792                 p = curproc;
3793         }
3794
3795         db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3796             (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3797             (void *)vmspace_pmap(p->p_vmspace));
3798
3799         vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3800 }
3801
3802 #endif /* DDB */