1/*	$NetBSD: uvm_map.c,v 1.411 2024/02/09 22:08:38 andvar Exp $	*/
2
3/*
4 * Copyright (c) 1997 Charles D. Cranor and Washington University.
5 * Copyright (c) 1991, 1993, The Regents of the University of California.
6 *
7 * All rights reserved.
8 *
9 * This code is derived from software contributed to Berkeley by
10 * The Mach Operating System project at Carnegie-Mellon University.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 *	@(#)vm_map.c    8.3 (Berkeley) 1/12/94
37 * from: Id: uvm_map.c,v 1.1.2.27 1998/02/07 01:16:54 chs Exp
38 *
39 *
40 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
41 * All rights reserved.
42 *
43 * Permission to use, copy, modify and distribute this software and
44 * its documentation is hereby granted, provided that both the copyright
45 * notice and this permission notice appear in all copies of the
46 * software, derivative works or modified versions, and any portions
47 * thereof, and that both notices appear in supporting documentation.
48 *
49 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
50 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
51 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52 *
53 * Carnegie Mellon requests users of this software to return to
54 *
55 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
56 *  School of Computer Science
57 *  Carnegie Mellon University
58 *  Pittsburgh PA 15213-3890
59 *
60 * any improvements or extensions that they make and grant Carnegie the
61 * rights to redistribute these changes.
62 */
63
64/*
65 * uvm_map.c: uvm map operations
66 */
67
68#include <sys/cdefs.h>
69__KERNEL_RCSID(0, "$NetBSD: uvm_map.c,v 1.411 2024/02/09 22:08:38 andvar Exp $");
70
71#include "opt_ddb.h"
72#include "opt_pax.h"
73#include "opt_uvmhist.h"
74#include "opt_uvm.h"
75#include "opt_sysv.h"
76
77#include <sys/param.h>
78#include <sys/systm.h>
79#include <sys/mman.h>
80#include <sys/proc.h>
81#include <sys/pool.h>
82#include <sys/kernel.h>
83#include <sys/mount.h>
84#include <sys/pax.h>
85#include <sys/vnode.h>
86#include <sys/filedesc.h>
87#include <sys/lockdebug.h>
88#include <sys/atomic.h>
89#include <sys/sysctl.h>
90#ifndef __USER_VA0_IS_SAFE
91#include <sys/kauth.h>
92#include "opt_user_va0_disable_default.h"
93#endif
94
95#include <sys/shm.h>
96
97#include <uvm/uvm.h>
98#include <uvm/uvm_readahead.h>
99
100#if defined(DDB) || defined(DEBUGPRINT)
101#include <uvm/uvm_ddb.h>
102#endif
103
104#ifdef UVMHIST
105#ifndef UVMHIST_MAPHIST_SIZE
106#define UVMHIST_MAPHIST_SIZE 100
107#endif
108static struct kern_history_ent maphistbuf[UVMHIST_MAPHIST_SIZE];
109UVMHIST_DEFINE(maphist) = UVMHIST_INITIALIZER(maphist, maphistbuf);
110#endif
111
112#if !defined(UVMMAP_COUNTERS)
113
114#define	UVMMAP_EVCNT_DEFINE(name)	/* nothing */
115#define UVMMAP_EVCNT_INCR(ev)		/* nothing */
116#define UVMMAP_EVCNT_DECR(ev)		/* nothing */
117
118#else /* defined(UVMMAP_NOCOUNTERS) */
119
120#include <sys/evcnt.h>
121#define	UVMMAP_EVCNT_DEFINE(name) \
122struct evcnt uvmmap_evcnt_##name = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, \
123    "uvmmap", #name); \
124EVCNT_ATTACH_STATIC(uvmmap_evcnt_##name);
125#define	UVMMAP_EVCNT_INCR(ev)		uvmmap_evcnt_##ev.ev_count++
126#define	UVMMAP_EVCNT_DECR(ev)		uvmmap_evcnt_##ev.ev_count--
127
128#endif /* defined(UVMMAP_NOCOUNTERS) */
129
130UVMMAP_EVCNT_DEFINE(ubackmerge)
131UVMMAP_EVCNT_DEFINE(uforwmerge)
132UVMMAP_EVCNT_DEFINE(ubimerge)
133UVMMAP_EVCNT_DEFINE(unomerge)
134UVMMAP_EVCNT_DEFINE(kbackmerge)
135UVMMAP_EVCNT_DEFINE(kforwmerge)
136UVMMAP_EVCNT_DEFINE(kbimerge)
137UVMMAP_EVCNT_DEFINE(knomerge)
138UVMMAP_EVCNT_DEFINE(map_call)
139UVMMAP_EVCNT_DEFINE(mlk_call)
140UVMMAP_EVCNT_DEFINE(mlk_hint)
141UVMMAP_EVCNT_DEFINE(mlk_tree)
142UVMMAP_EVCNT_DEFINE(mlk_treeloop)
143
144const char vmmapbsy[] = "vmmapbsy";
145
146/*
147 * cache for dynamically-allocated map entries.
148 */
149
150static struct pool_cache uvm_map_entry_cache;
151
152#ifdef PMAP_GROWKERNEL
153/*
154 * This global represents the end of the kernel virtual address
155 * space.  If we want to exceed this, we must grow the kernel
156 * virtual address space dynamically.
157 *
158 * Note, this variable is locked by kernel_map's lock.
159 */
160vaddr_t uvm_maxkaddr;
161#endif
162
163#ifndef __USER_VA0_IS_SAFE
164#ifndef __USER_VA0_DISABLE_DEFAULT
165#define __USER_VA0_DISABLE_DEFAULT 1
166#endif
167#ifdef USER_VA0_DISABLE_DEFAULT /* kernel config option overrides */
168#undef __USER_VA0_DISABLE_DEFAULT
169#define __USER_VA0_DISABLE_DEFAULT USER_VA0_DISABLE_DEFAULT
170#endif
171int user_va0_disable = __USER_VA0_DISABLE_DEFAULT;
172#endif
173
174/*
175 * macros
176 */
177
178/*
179 * uvm_map_align_va: round down or up virtual address
180 */
181static __inline void
182uvm_map_align_va(vaddr_t *vap, vsize_t align, int topdown)
183{
184
185	KASSERT(powerof2(align));
186
187	if (align != 0 && (*vap & (align - 1)) != 0) {
188		if (topdown)
189			*vap = rounddown2(*vap, align);
190		else
191			*vap = roundup2(*vap, align);
192	}
193}
194
195/*
196 * UVM_ET_ISCOMPATIBLE: check some requirements for map entry merging
197 */
198extern struct vm_map *pager_map;
199
200#define	UVM_ET_ISCOMPATIBLE(ent, type, uobj, meflags, \
201    prot, maxprot, inh, adv, wire) \
202	((ent)->etype == (type) && \
203	(((ent)->flags ^ (meflags)) & (UVM_MAP_NOMERGE)) == 0 && \
204	(ent)->object.uvm_obj == (uobj) && \
205	(ent)->protection == (prot) && \
206	(ent)->max_protection == (maxprot) && \
207	(ent)->inheritance == (inh) && \
208	(ent)->advice == (adv) && \
209	(ent)->wired_count == (wire))
210
211/*
212 * uvm_map_entry_link: insert entry into a map
213 *
214 * => map must be locked
215 */
216#define uvm_map_entry_link(map, after_where, entry) do { \
217	uvm_mapent_check(entry); \
218	(map)->nentries++; \
219	(entry)->prev = (after_where); \
220	(entry)->next = (after_where)->next; \
221	(entry)->prev->next = (entry); \
222	(entry)->next->prev = (entry); \
223	uvm_rb_insert((map), (entry)); \
224} while (/*CONSTCOND*/ 0)
225
226/*
227 * uvm_map_entry_unlink: remove entry from a map
228 *
229 * => map must be locked
230 */
231#define uvm_map_entry_unlink(map, entry) do { \
232	KASSERT((entry) != (map)->first_free); \
233	KASSERT((entry) != (map)->hint); \
234	uvm_mapent_check(entry); \
235	(map)->nentries--; \
236	(entry)->next->prev = (entry)->prev; \
237	(entry)->prev->next = (entry)->next; \
238	uvm_rb_remove((map), (entry)); \
239} while (/*CONSTCOND*/ 0)
240
241/*
242 * SAVE_HINT: saves the specified entry as the hint for future lookups.
243 *
244 * => map need not be locked.
245 */
246#define SAVE_HINT(map, check, value) do { \
247	if ((map)->hint == (check)) \
248		(map)->hint = (value); \
249} while (/*CONSTCOND*/ 0)
250
251/*
252 * clear_hints: ensure that hints don't point to the entry.
253 *
254 * => map must be write-locked.
255 */
256static void
257clear_hints(struct vm_map *map, struct vm_map_entry *ent)
258{
259
260	SAVE_HINT(map, ent, ent->prev);
261	if (map->first_free == ent) {
262		map->first_free = ent->prev;
263	}
264}
265
266/*
267 * VM_MAP_RANGE_CHECK: check and correct range
268 *
269 * => map must at least be read locked
270 */
271
272#define VM_MAP_RANGE_CHECK(map, start, end) do { \
273	if (start < vm_map_min(map))		\
274		start = vm_map_min(map);	\
275	if (end > vm_map_max(map))		\
276		end = vm_map_max(map);		\
277	if (start > end)			\
278		start = end;			\
279} while (/*CONSTCOND*/ 0)
280
281/*
282 * local prototypes
283 */
284
285static struct vm_map_entry *
286		uvm_mapent_alloc(struct vm_map *, int);
287static void	uvm_mapent_copy(struct vm_map_entry *, struct vm_map_entry *);
288static void	uvm_mapent_free(struct vm_map_entry *);
289#if defined(DEBUG)
290static void	_uvm_mapent_check(const struct vm_map_entry *, int);
291#define	uvm_mapent_check(map)	_uvm_mapent_check(map, __LINE__)
292#else /* defined(DEBUG) */
293#define	uvm_mapent_check(e)	/* nothing */
294#endif /* defined(DEBUG) */
295
296static void	uvm_map_entry_unwire(struct vm_map *, struct vm_map_entry *);
297static void	uvm_map_reference_amap(struct vm_map_entry *, int);
298static int	uvm_map_space_avail(vaddr_t *, vsize_t, voff_t, vsize_t, int,
299		    int, struct vm_map_entry *);
300static void	uvm_map_unreference_amap(struct vm_map_entry *, int);
301
302int _uvm_map_sanity(struct vm_map *);
303int _uvm_tree_sanity(struct vm_map *);
304static vsize_t uvm_rb_maxgap(const struct vm_map_entry *);
305
306#define	ROOT_ENTRY(map)		((struct vm_map_entry *)(map)->rb_tree.rbt_root)
307#define	LEFT_ENTRY(entry)	((struct vm_map_entry *)(entry)->rb_node.rb_left)
308#define	RIGHT_ENTRY(entry)	((struct vm_map_entry *)(entry)->rb_node.rb_right)
309#define	PARENT_ENTRY(map, entry) \
310	(ROOT_ENTRY(map) == (entry) \
311	    ? NULL : (struct vm_map_entry *)RB_FATHER(&(entry)->rb_node))
312
313/*
314 * These get filled in if/when SYSVSHM shared memory code is loaded
315 *
316 * We do this with function pointers rather the #ifdef SYSVSHM so the
317 * SYSVSHM code can be loaded and unloaded
318 */
319void (*uvm_shmexit)(struct vmspace *) = NULL;
320void (*uvm_shmfork)(struct vmspace *, struct vmspace *) = NULL;
321
322static int
323uvm_map_compare_nodes(void *ctx, const void *nparent, const void *nkey)
324{
325	const struct vm_map_entry *eparent = nparent;
326	const struct vm_map_entry *ekey = nkey;
327
328	KASSERT(eparent->start < ekey->start || eparent->start >= ekey->end);
329	KASSERT(ekey->start < eparent->start || ekey->start >= eparent->end);
330
331	if (eparent->start < ekey->start)
332		return -1;
333	if (eparent->end >= ekey->start)
334		return 1;
335	return 0;
336}
337
338static int
339uvm_map_compare_key(void *ctx, const void *nparent, const void *vkey)
340{
341	const struct vm_map_entry *eparent = nparent;
342	const vaddr_t va = *(const vaddr_t *) vkey;
343
344	if (eparent->start < va)
345		return -1;
346	if (eparent->end >= va)
347		return 1;
348	return 0;
349}
350
351static const rb_tree_ops_t uvm_map_tree_ops = {
352	.rbto_compare_nodes = uvm_map_compare_nodes,
353	.rbto_compare_key = uvm_map_compare_key,
354	.rbto_node_offset = offsetof(struct vm_map_entry, rb_node),
355	.rbto_context = NULL
356};
357
358/*
359 * uvm_rb_gap: return the gap size between our entry and next entry.
360 */
361static inline vsize_t
362uvm_rb_gap(const struct vm_map_entry *entry)
363{
364
365	KASSERT(entry->next != NULL);
366	return entry->next->start - entry->end;
367}
368
369static vsize_t
370uvm_rb_maxgap(const struct vm_map_entry *entry)
371{
372	struct vm_map_entry *child;
373	vsize_t maxgap = entry->gap;
374
375	/*
376	 * We need maxgap to be the largest gap of us or any of our
377	 * descendents.  Since each of our children's maxgap is the
378	 * cached value of their largest gap of themselves or their
379	 * descendents, we can just use that value and avoid recursing
380	 * down the tree to calculate it.
381	 */
382	if ((child = LEFT_ENTRY(entry)) != NULL && maxgap < child->maxgap)
383		maxgap = child->maxgap;
384
385	if ((child = RIGHT_ENTRY(entry)) != NULL && maxgap < child->maxgap)
386		maxgap = child->maxgap;
387
388	return maxgap;
389}
390
391static void
392uvm_rb_fixup(struct vm_map *map, struct vm_map_entry *entry)
393{
394	struct vm_map_entry *parent;
395
396	KASSERT(entry->gap == uvm_rb_gap(entry));
397	entry->maxgap = uvm_rb_maxgap(entry);
398
399	while ((parent = PARENT_ENTRY(map, entry)) != NULL) {
400		struct vm_map_entry *brother;
401		vsize_t maxgap = parent->gap;
402		unsigned int which;
403
404		KDASSERT(parent->gap == uvm_rb_gap(parent));
405		if (maxgap < entry->maxgap)
406			maxgap = entry->maxgap;
407		/*
408		 * Since we work towards the root, we know entry's maxgap
409		 * value is OK, but its brothers may now be out-of-date due
410		 * to rebalancing.  So refresh it.
411		 */
412		which = RB_POSITION(&entry->rb_node) ^ RB_DIR_OTHER;
413		brother = (struct vm_map_entry *)parent->rb_node.rb_nodes[which];
414		if (brother != NULL) {
415			KDASSERT(brother->gap == uvm_rb_gap(brother));
416			brother->maxgap = uvm_rb_maxgap(brother);
417			if (maxgap < brother->maxgap)
418				maxgap = brother->maxgap;
419		}
420
421		parent->maxgap = maxgap;
422		entry = parent;
423	}
424}
425
426static void
427uvm_rb_insert(struct vm_map *map, struct vm_map_entry *entry)
428{
429	struct vm_map_entry *ret __diagused;
430
431	entry->gap = entry->maxgap = uvm_rb_gap(entry);
432	if (entry->prev != &map->header)
433		entry->prev->gap = uvm_rb_gap(entry->prev);
434
435	ret = rb_tree_insert_node(&map->rb_tree, entry);
436	KASSERTMSG(ret == entry,
437	    "uvm_rb_insert: map %p: duplicate entry %p", map, ret);
438
439	/*
440	 * If the previous entry is not our immediate left child, then it's an
441	 * ancestor and will be fixed up on the way to the root.  We don't
442	 * have to check entry->prev against &map->header since &map->header
443	 * will never be in the tree.
444	 */
445	uvm_rb_fixup(map,
446	    LEFT_ENTRY(entry) == entry->prev ? entry->prev : entry);
447}
448
449static void
450uvm_rb_remove(struct vm_map *map, struct vm_map_entry *entry)
451{
452	struct vm_map_entry *prev_parent = NULL, *next_parent = NULL;
453
454	/*
455	 * If we are removing an interior node, then an adjacent node will
456	 * be used to replace its position in the tree.  Therefore we will
457	 * need to fixup the tree starting at the parent of the replacement
458	 * node.  So record their parents for later use.
459	 */
460	if (entry->prev != &map->header)
461		prev_parent = PARENT_ENTRY(map, entry->prev);
462	if (entry->next != &map->header)
463		next_parent = PARENT_ENTRY(map, entry->next);
464
465	rb_tree_remove_node(&map->rb_tree, entry);
466
467	/*
468	 * If the previous node has a new parent, fixup the tree starting
469	 * at the previous node's old parent.
470	 */
471	if (entry->prev != &map->header) {
472		/*
473		 * Update the previous entry's gap due to our absence.
474		 */
475		entry->prev->gap = uvm_rb_gap(entry->prev);
476		uvm_rb_fixup(map, entry->prev);
477		if (prev_parent != NULL
478		    && prev_parent != entry
479		    && prev_parent != PARENT_ENTRY(map, entry->prev))
480			uvm_rb_fixup(map, prev_parent);
481	}
482
483	/*
484	 * If the next node has a new parent, fixup the tree starting
485	 * at the next node's old parent.
486	 */
487	if (entry->next != &map->header) {
488		uvm_rb_fixup(map, entry->next);
489		if (next_parent != NULL
490		    && next_parent != entry
491		    && next_parent != PARENT_ENTRY(map, entry->next))
492			uvm_rb_fixup(map, next_parent);
493	}
494}
495
496#if defined(DEBUG)
497int uvm_debug_check_map = 0;
498int uvm_debug_check_rbtree = 0;
499#define uvm_map_check(map, name) \
500	_uvm_map_check((map), (name), __FILE__, __LINE__)
501static void
502_uvm_map_check(struct vm_map *map, const char *name,
503    const char *file, int line)
504{
505
506	if ((uvm_debug_check_map && _uvm_map_sanity(map)) ||
507	    (uvm_debug_check_rbtree && _uvm_tree_sanity(map))) {
508		panic("uvm_map_check failed: \"%s\" map=%p (%s:%d)",
509		    name, map, file, line);
510	}
511}
512#else /* defined(DEBUG) */
513#define uvm_map_check(map, name)	/* nothing */
514#endif /* defined(DEBUG) */
515
516#if defined(DEBUG) || defined(DDB)
517int
518_uvm_map_sanity(struct vm_map *map)
519{
520	bool first_free_found = false;
521	bool hint_found = false;
522	const struct vm_map_entry *e;
523	struct vm_map_entry *hint = map->hint;
524
525	e = &map->header;
526	for (;;) {
527		if (map->first_free == e) {
528			first_free_found = true;
529		} else if (!first_free_found && e->next->start > e->end) {
530			printf("first_free %p should be %p\n",
531			    map->first_free, e);
532			return -1;
533		}
534		if (hint == e) {
535			hint_found = true;
536		}
537
538		e = e->next;
539		if (e == &map->header) {
540			break;
541		}
542	}
543	if (!first_free_found) {
544		printf("stale first_free\n");
545		return -1;
546	}
547	if (!hint_found) {
548		printf("stale hint\n");
549		return -1;
550	}
551	return 0;
552}
553
554int
555_uvm_tree_sanity(struct vm_map *map)
556{
557	struct vm_map_entry *tmp, *trtmp;
558	int n = 0, i = 1;
559
560	for (tmp = map->header.next; tmp != &map->header; tmp = tmp->next) {
561		if (tmp->gap != uvm_rb_gap(tmp)) {
562			printf("%d/%d gap %#lx != %#lx %s\n",
563			    n + 1, map->nentries,
564			    (ulong)tmp->gap, (ulong)uvm_rb_gap(tmp),
565			    tmp->next == &map->header ? "(last)" : "");
566			goto error;
567		}
568		/*
569		 * If any entries are out of order, tmp->gap will be unsigned
570		 * and will likely exceed the size of the map.
571		 */
572		if (tmp->gap >= vm_map_max(map) - vm_map_min(map)) {
573			printf("too large gap %zu\n", (size_t)tmp->gap);
574			goto error;
575		}
576		n++;
577	}
578
579	if (n != map->nentries) {
580		printf("nentries: %d vs %d\n", n, map->nentries);
581		goto error;
582	}
583
584	trtmp = NULL;
585	for (tmp = map->header.next; tmp != &map->header; tmp = tmp->next) {
586		if (tmp->maxgap != uvm_rb_maxgap(tmp)) {
587			printf("maxgap %#lx != %#lx\n",
588			    (ulong)tmp->maxgap,
589			    (ulong)uvm_rb_maxgap(tmp));
590			goto error;
591		}
592		if (trtmp != NULL && trtmp->start >= tmp->start) {
593			printf("corrupt: 0x%"PRIxVADDR"x >= 0x%"PRIxVADDR"x\n",
594			    trtmp->start, tmp->start);
595			goto error;
596		}
597
598		trtmp = tmp;
599	}
600
601	for (tmp = map->header.next; tmp != &map->header;
602	    tmp = tmp->next, i++) {
603		trtmp = rb_tree_iterate(&map->rb_tree, tmp, RB_DIR_LEFT);
604		if (trtmp == NULL)
605			trtmp = &map->header;
606		if (tmp->prev != trtmp) {
607			printf("lookup: %d: %p->prev=%p: %p\n",
608			    i, tmp, tmp->prev, trtmp);
609			goto error;
610		}
611		trtmp = rb_tree_iterate(&map->rb_tree, tmp, RB_DIR_RIGHT);
612		if (trtmp == NULL)
613			trtmp = &map->header;
614		if (tmp->next != trtmp) {
615			printf("lookup: %d: %p->next=%p: %p\n",
616			    i, tmp, tmp->next, trtmp);
617			goto error;
618		}
619		trtmp = rb_tree_find_node(&map->rb_tree, &tmp->start);
620		if (trtmp != tmp) {
621			printf("lookup: %d: %p - %p: %p\n", i, tmp, trtmp,
622			    PARENT_ENTRY(map, tmp));
623			goto error;
624		}
625	}
626
627	return (0);
628 error:
629	return (-1);
630}
631#endif /* defined(DEBUG) || defined(DDB) */
632
633/*
634 * vm_map_lock: acquire an exclusive (write) lock on a map.
635 *
636 * => The locking protocol provides for guaranteed upgrade from shared ->
637 *    exclusive by whichever thread currently has the map marked busy.
638 *    See "LOCKING PROTOCOL NOTES" in uvm_map.h.  This is horrible; among
639 *    other problems, it defeats any fairness guarantees provided by RW
640 *    locks.
641 */
642
643void
644vm_map_lock(struct vm_map *map)
645{
646
647	for (;;) {
648		rw_enter(&map->lock, RW_WRITER);
649		if (map->busy == NULL || map->busy == curlwp) {
650			break;
651		}
652		mutex_enter(&map->misc_lock);
653		rw_exit(&map->lock);
654		if (map->busy != NULL) {
655			cv_wait(&map->cv, &map->misc_lock);
656		}
657		mutex_exit(&map->misc_lock);
658	}
659	map->timestamp++;
660}
661
662/*
663 * vm_map_lock_try: try to lock a map, failing if it is already locked.
664 */
665
666bool
667vm_map_lock_try(struct vm_map *map)
668{
669
670	if (!rw_tryenter(&map->lock, RW_WRITER)) {
671		return false;
672	}
673	if (map->busy != NULL) {
674		rw_exit(&map->lock);
675		return false;
676	}
677	map->timestamp++;
678	return true;
679}
680
681/*
682 * vm_map_unlock: release an exclusive lock on a map.
683 */
684
685void
686vm_map_unlock(struct vm_map *map)
687{
688
689	KASSERT(rw_write_held(&map->lock));
690	KASSERT(map->busy == NULL || map->busy == curlwp);
691	rw_exit(&map->lock);
692}
693
694/*
695 * vm_map_unbusy: mark the map as unbusy, and wake any waiters that
696 *     want an exclusive lock.
697 */
698
699void
700vm_map_unbusy(struct vm_map *map)
701{
702
703	KASSERT(map->busy == curlwp);
704
705	/*
706	 * Safe to clear 'busy' and 'waiters' with only a read lock held:
707	 *
708	 * o they can only be set with a write lock held
709	 * o writers are blocked out with a read or write hold
710	 * o at any time, only one thread owns the set of values
711	 */
712	mutex_enter(&map->misc_lock);
713	map->busy = NULL;
714	cv_broadcast(&map->cv);
715	mutex_exit(&map->misc_lock);
716}
717
718/*
719 * vm_map_lock_read: acquire a shared (read) lock on a map.
720 */
721
722void
723vm_map_lock_read(struct vm_map *map)
724{
725
726	rw_enter(&map->lock, RW_READER);
727}
728
729/*
730 * vm_map_unlock_read: release a shared lock on a map.
731 */
732
733void
734vm_map_unlock_read(struct vm_map *map)
735{
736
737	rw_exit(&map->lock);
738}
739
740/*
741 * vm_map_busy: mark a map as busy.
742 *
743 * => the caller must hold the map write locked
744 */
745
746void
747vm_map_busy(struct vm_map *map)
748{
749
750	KASSERT(rw_write_held(&map->lock));
751	KASSERT(map->busy == NULL);
752
753	map->busy = curlwp;
754}
755
756/*
757 * vm_map_locked_p: return true if the map is write locked.
758 *
759 * => only for debug purposes like KASSERTs.
760 * => should not be used to verify that a map is not locked.
761 */
762
763bool
764vm_map_locked_p(struct vm_map *map)
765{
766
767	return rw_write_held(&map->lock);
768}
769
770/*
771 * uvm_mapent_alloc: allocate a map entry
772 */
773
774static struct vm_map_entry *
775uvm_mapent_alloc(struct vm_map *map, int flags)
776{
777	struct vm_map_entry *me;
778	int pflags = (flags & UVM_FLAG_NOWAIT) ? PR_NOWAIT : PR_WAITOK;
779	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
780
781	me = pool_cache_get(&uvm_map_entry_cache, pflags);
782	if (__predict_false(me == NULL)) {
783		return NULL;
784	}
785	me->flags = 0;
786
787	UVMHIST_LOG(maphist, "<- new entry=%#jx [kentry=%jd]", (uintptr_t)me,
788	    (map == kernel_map), 0, 0);
789	return me;
790}
791
792/*
793 * uvm_mapent_free: free map entry
794 */
795
796static void
797uvm_mapent_free(struct vm_map_entry *me)
798{
799	UVMHIST_FUNC(__func__);
800	UVMHIST_CALLARGS(maphist,"<- freeing map entry=%#jx [flags=%#jx]",
801		(uintptr_t)me, me->flags, 0, 0);
802	pool_cache_put(&uvm_map_entry_cache, me);
803}
804
805/*
806 * uvm_mapent_copy: copy a map entry, preserving flags
807 */
808
809static inline void
810uvm_mapent_copy(struct vm_map_entry *src, struct vm_map_entry *dst)
811{
812
813	memcpy(dst, src, sizeof(*dst));
814	dst->flags = 0;
815}
816
817#if defined(DEBUG)
818static void
819_uvm_mapent_check(const struct vm_map_entry *entry, int line)
820{
821
822	if (entry->start >= entry->end) {
823		goto bad;
824	}
825	if (UVM_ET_ISOBJ(entry)) {
826		if (entry->object.uvm_obj == NULL) {
827			goto bad;
828		}
829	} else if (UVM_ET_ISSUBMAP(entry)) {
830		if (entry->object.sub_map == NULL) {
831			goto bad;
832		}
833	} else {
834		if (entry->object.uvm_obj != NULL ||
835		    entry->object.sub_map != NULL) {
836			goto bad;
837		}
838	}
839	if (!UVM_ET_ISOBJ(entry)) {
840		if (entry->offset != 0) {
841			goto bad;
842		}
843	}
844
845	return;
846
847bad:
848	panic("%s: bad entry %p, line %d", __func__, entry, line);
849}
850#endif /* defined(DEBUG) */
851
852/*
853 * uvm_map_entry_unwire: unwire a map entry
854 *
855 * => map should be locked by caller
856 */
857
858static inline void
859uvm_map_entry_unwire(struct vm_map *map, struct vm_map_entry *entry)
860{
861
862	entry->wired_count = 0;
863	uvm_fault_unwire_locked(map, entry->start, entry->end);
864}
865
866
867/*
868 * wrapper for calling amap_ref()
869 */
870static inline void
871uvm_map_reference_amap(struct vm_map_entry *entry, int flags)
872{
873
874	amap_ref(entry->aref.ar_amap, entry->aref.ar_pageoff,
875	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
876}
877
878
879/*
880 * wrapper for calling amap_unref()
881 */
882static inline void
883uvm_map_unreference_amap(struct vm_map_entry *entry, int flags)
884{
885
886	amap_unref(entry->aref.ar_amap, entry->aref.ar_pageoff,
887	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
888}
889
890
891/*
892 * uvm_map_init: init mapping system at boot time.
893 */
894
895void
896uvm_map_init(void)
897{
898	/*
899	 * first, init logging system.
900	 */
901
902	UVMHIST_FUNC(__func__);
903	UVMHIST_LINK_STATIC(maphist);
904	UVMHIST_LINK_STATIC(pdhist);
905	UVMHIST_CALLED(maphist);
906	UVMHIST_LOG(maphist,"<starting uvm map system>", 0, 0, 0, 0);
907
908	/*
909	 * initialize the global lock for kernel map entry.
910	 */
911
912	mutex_init(&uvm_kentry_lock, MUTEX_DRIVER, IPL_VM);
913}
914
915/*
916 * uvm_map_init_caches: init mapping system caches.
917 */
918void
919uvm_map_init_caches(void)
920{
921	/*
922	 * initialize caches.
923	 */
924
925	pool_cache_bootstrap(&uvm_map_entry_cache, sizeof(struct vm_map_entry),
926	    coherency_unit, 0, PR_LARGECACHE, "vmmpepl", NULL, IPL_NONE, NULL,
927	    NULL, NULL);
928}
929
930/*
931 * clippers
932 */
933
934/*
935 * uvm_mapent_splitadj: adjust map entries for splitting, after uvm_mapent_copy.
936 */
937
938static void
939uvm_mapent_splitadj(struct vm_map_entry *entry1, struct vm_map_entry *entry2,
940    vaddr_t splitat)
941{
942	vaddr_t adj;
943
944	KASSERT(entry1->start < splitat);
945	KASSERT(splitat < entry1->end);
946
947	adj = splitat - entry1->start;
948	entry1->end = entry2->start = splitat;
949
950	if (entry1->aref.ar_amap) {
951		amap_splitref(&entry1->aref, &entry2->aref, adj);
952	}
953	if (UVM_ET_ISSUBMAP(entry1)) {
954		/* ... unlikely to happen, but play it safe */
955		 uvm_map_reference(entry1->object.sub_map);
956	} else if (UVM_ET_ISOBJ(entry1)) {
957		KASSERT(entry1->object.uvm_obj != NULL); /* suppress coverity */
958		entry2->offset += adj;
959		if (entry1->object.uvm_obj->pgops &&
960		    entry1->object.uvm_obj->pgops->pgo_reference)
961			entry1->object.uvm_obj->pgops->pgo_reference(
962			    entry1->object.uvm_obj);
963	}
964}
965
966/*
967 * uvm_map_clip_start: ensure that the entry begins at or after
968 *	the starting address, if it doesn't we split the entry.
969 *
970 * => caller should use UVM_MAP_CLIP_START macro rather than calling
971 *    this directly
972 * => map must be locked by caller
973 */
974
975void
976uvm_map_clip_start(struct vm_map *map, struct vm_map_entry *entry,
977    vaddr_t start)
978{
979	struct vm_map_entry *new_entry;
980
981	/* uvm_map_simplify_entry(map, entry); */ /* XXX */
982
983	uvm_map_check(map, "clip_start entry");
984	uvm_mapent_check(entry);
985
986	/*
987	 * Split off the front portion.  note that we must insert the new
988	 * entry BEFORE this one, so that this entry has the specified
989	 * starting address.
990	 */
991	new_entry = uvm_mapent_alloc(map, 0);
992	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
993	uvm_mapent_splitadj(new_entry, entry, start);
994	uvm_map_entry_link(map, entry->prev, new_entry);
995
996	uvm_map_check(map, "clip_start leave");
997}
998
999/*
1000 * uvm_map_clip_end: ensure that the entry ends at or before
1001 *	the ending address, if it does't we split the reference
1002 *
1003 * => caller should use UVM_MAP_CLIP_END macro rather than calling
1004 *    this directly
1005 * => map must be locked by caller
1006 */
1007
1008void
1009uvm_map_clip_end(struct vm_map *map, struct vm_map_entry *entry, vaddr_t end)
1010{
1011	struct vm_map_entry *new_entry;
1012
1013	uvm_map_check(map, "clip_end entry");
1014	uvm_mapent_check(entry);
1015
1016	/*
1017	 *	Create a new entry and insert it
1018	 *	AFTER the specified entry
1019	 */
1020	new_entry = uvm_mapent_alloc(map, 0);
1021	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
1022	uvm_mapent_splitadj(entry, new_entry, end);
1023	uvm_map_entry_link(map, entry, new_entry);
1024
1025	uvm_map_check(map, "clip_end leave");
1026}
1027
1028/*
1029 *   M A P   -   m a i n   e n t r y   p o i n t
1030 */
1031/*
1032 * uvm_map: establish a valid mapping in a map
1033 *
1034 * => assume startp is page aligned.
1035 * => assume size is a multiple of PAGE_SIZE.
1036 * => assume sys_mmap provides enough of a "hint" to have us skip
1037 *	over text/data/bss area.
1038 * => map must be unlocked (we will lock it)
1039 * => <uobj,uoffset> value meanings (4 cases):
1040 *	 [1] <NULL,uoffset>		== uoffset is a hint for PMAP_PREFER
1041 *	 [2] <NULL,UVM_UNKNOWN_OFFSET>	== don't PMAP_PREFER
1042 *	 [3] <uobj,uoffset>		== normal mapping
1043 *	 [4] <uobj,UVM_UNKNOWN_OFFSET>	== uvm_map finds offset based on VA
1044 *
1045 *    case [4] is for kernel mappings where we don't know the offset until
1046 *    we've found a virtual address.   note that kernel object offsets are
1047 *    always relative to vm_map_min(kernel_map).
1048 *
1049 * => if `align' is non-zero, we align the virtual address to the specified
1050 *	alignment.
1051 *	this is provided as a mechanism for large pages.
1052 *
1053 * => XXXCDC: need way to map in external amap?
1054 */
1055
1056int
1057uvm_map(struct vm_map *map, vaddr_t *startp /* IN/OUT */, vsize_t size,
1058    struct uvm_object *uobj, voff_t uoffset, vsize_t align, uvm_flag_t flags)
1059{
1060	struct uvm_map_args args;
1061	struct vm_map_entry *new_entry;
1062	int error;
1063
1064	KASSERT((size & PAGE_MASK) == 0);
1065	KASSERT((flags & UVM_FLAG_FIXED) == 0 || align == 0);
1066
1067	/*
1068	 * for pager_map, allocate the new entry first to avoid sleeping
1069	 * for memory while we have the map locked.
1070	 */
1071
1072	new_entry = NULL;
1073	if (map == pager_map) {
1074		new_entry = uvm_mapent_alloc(map, (flags & UVM_FLAG_NOWAIT));
1075		if (__predict_false(new_entry == NULL))
1076			return ENOMEM;
1077	}
1078	if (map == pager_map)
1079		flags |= UVM_FLAG_NOMERGE;
1080
1081	error = uvm_map_prepare(map, *startp, size, uobj, uoffset, align,
1082	    flags, &args);
1083	if (!error) {
1084		error = uvm_map_enter(map, &args, new_entry);
1085		*startp = args.uma_start;
1086	} else if (new_entry) {
1087		uvm_mapent_free(new_entry);
1088	}
1089
1090#if defined(DEBUG)
1091	if (!error && VM_MAP_IS_KERNEL(map) && (flags & UVM_FLAG_NOWAIT) == 0) {
1092		uvm_km_check_empty(map, *startp, *startp + size);
1093	}
1094#endif /* defined(DEBUG) */
1095
1096	return error;
1097}
1098
1099/*
1100 * uvm_map_prepare:
1101 *
1102 * called with map unlocked.
1103 * on success, returns the map locked.
1104 */
1105
1106int
1107uvm_map_prepare(struct vm_map *map, vaddr_t start, vsize_t size,
1108    struct uvm_object *uobj, voff_t uoffset, vsize_t align, uvm_flag_t flags,
1109    struct uvm_map_args *args)
1110{
1111	struct vm_map_entry *prev_entry;
1112	vm_prot_t prot = UVM_PROTECTION(flags);
1113	vm_prot_t maxprot = UVM_MAXPROTECTION(flags);
1114
1115	UVMHIST_FUNC(__func__);
1116	UVMHIST_CALLARGS(maphist, "(map=%#jx, start=%#jx, size=%jx, flags=%#jx)",
1117	    (uintptr_t)map, start, size, flags);
1118	UVMHIST_LOG(maphist, "  uobj/offset %#jx/%jd", (uintptr_t)uobj,
1119	    uoffset,0,0);
1120
1121	/*
1122	 * detect a popular device driver bug.
1123	 */
1124
1125	KASSERT(doing_shutdown || curlwp != NULL);
1126
1127	/*
1128	 * zero-sized mapping doesn't make any sense.
1129	 */
1130	KASSERT(size > 0);
1131
1132	KASSERT((~flags & (UVM_FLAG_NOWAIT | UVM_FLAG_WAITVA)) != 0);
1133
1134	uvm_map_check(map, "map entry");
1135
1136	/*
1137	 * check sanity of protection code
1138	 */
1139
1140	if ((prot & maxprot) != prot) {
1141		UVMHIST_LOG(maphist, "<- prot. failure:  prot=%#jx, max=%#jx",
1142		prot, maxprot,0,0);
1143		return EACCES;
1144	}
1145
1146	/*
1147	 * figure out where to put new VM range
1148	 */
1149retry:
1150	if (vm_map_lock_try(map) == false) {
1151		if ((flags & UVM_FLAG_TRYLOCK) != 0) {
1152			return EAGAIN;
1153		}
1154		vm_map_lock(map); /* could sleep here */
1155	}
1156	if (flags & UVM_FLAG_UNMAP) {
1157		KASSERT(flags & UVM_FLAG_FIXED);
1158		KASSERT((flags & UVM_FLAG_NOWAIT) == 0);
1159
1160		/*
1161		 * Set prev_entry to what it will need to be after any existing
1162		 * entries are removed later in uvm_map_enter().
1163		 */
1164
1165		if (uvm_map_lookup_entry(map, start, &prev_entry)) {
1166			if (start == prev_entry->start)
1167				prev_entry = prev_entry->prev;
1168			else
1169				UVM_MAP_CLIP_END(map, prev_entry, start);
1170			SAVE_HINT(map, map->hint, prev_entry);
1171		}
1172	} else {
1173		prev_entry = uvm_map_findspace(map, start, size, &start,
1174		    uobj, uoffset, align, flags);
1175	}
1176	if (prev_entry == NULL) {
1177		unsigned int timestamp;
1178
1179		timestamp = map->timestamp;
1180		UVMHIST_LOG(maphist,"waiting va timestamp=%#jx",
1181			    timestamp,0,0,0);
1182		map->flags |= VM_MAP_WANTVA;
1183		vm_map_unlock(map);
1184
1185		/*
1186		 * try to reclaim kva and wait until someone does unmap.
1187		 * fragile locking here, so we awaken every second to
1188		 * recheck the condition.
1189		 */
1190
1191		mutex_enter(&map->misc_lock);
1192		while ((map->flags & VM_MAP_WANTVA) != 0 &&
1193		   map->timestamp == timestamp) {
1194			if ((flags & UVM_FLAG_WAITVA) == 0) {
1195				mutex_exit(&map->misc_lock);
1196				UVMHIST_LOG(maphist,
1197				    "<- uvm_map_findspace failed!", 0,0,0,0);
1198				return ENOMEM;
1199			} else {
1200				cv_timedwait(&map->cv, &map->misc_lock, hz);
1201			}
1202		}
1203		mutex_exit(&map->misc_lock);
1204		goto retry;
1205	}
1206
1207#ifdef PMAP_GROWKERNEL
1208	/*
1209	 * If the kernel pmap can't map the requested space,
1210	 * then allocate more resources for it.
1211	 */
1212	if (map == kernel_map && uvm_maxkaddr < (start + size))
1213		uvm_maxkaddr = pmap_growkernel(start + size);
1214#endif
1215
1216	UVMMAP_EVCNT_INCR(map_call);
1217
1218	/*
1219	 * if uobj is null, then uoffset is either a VAC hint for PMAP_PREFER
1220	 * [typically from uvm_map_reserve] or it is UVM_UNKNOWN_OFFSET.   in
1221	 * either case we want to zero it  before storing it in the map entry
1222	 * (because it looks strange and confusing when debugging...)
1223	 *
1224	 * if uobj is not null
1225	 *   if uoffset is not UVM_UNKNOWN_OFFSET then we have a normal mapping
1226	 *      and we do not need to change uoffset.
1227	 *   if uoffset is UVM_UNKNOWN_OFFSET then we need to find the offset
1228	 *      now (based on the starting address of the map).   this case is
1229	 *      for kernel object mappings where we don't know the offset until
1230	 *      the virtual address is found (with uvm_map_findspace).   the
1231	 *      offset is the distance we are from the start of the map.
1232	 */
1233
1234	if (uobj == NULL) {
1235		uoffset = 0;
1236	} else {
1237		if (uoffset == UVM_UNKNOWN_OFFSET) {
1238			KASSERT(UVM_OBJ_IS_KERN_OBJECT(uobj));
1239			uoffset = start - vm_map_min(kernel_map);
1240		}
1241	}
1242
1243	args->uma_flags = flags;
1244	args->uma_prev = prev_entry;
1245	args->uma_start = start;
1246	args->uma_size = size;
1247	args->uma_uobj = uobj;
1248	args->uma_uoffset = uoffset;
1249
1250	UVMHIST_LOG(maphist, "<- done!", 0,0,0,0);
1251	return 0;
1252}
1253
1254/*
1255 * uvm_map_enter:
1256 *
1257 * called with map locked.
1258 * unlock the map before returning.
1259 */
1260
1261int
1262uvm_map_enter(struct vm_map *map, const struct uvm_map_args *args,
1263    struct vm_map_entry *new_entry)
1264{
1265	struct vm_map_entry *prev_entry = args->uma_prev;
1266	struct vm_map_entry *dead = NULL, *dead_entries = NULL;
1267
1268	const uvm_flag_t flags = args->uma_flags;
1269	const vm_prot_t prot = UVM_PROTECTION(flags);
1270	const vm_prot_t maxprot = UVM_MAXPROTECTION(flags);
1271	const vm_inherit_t inherit = UVM_INHERIT(flags);
1272	const int amapwaitflag = (flags & UVM_FLAG_NOWAIT) ?
1273	    AMAP_EXTEND_NOWAIT : 0;
1274	const int advice = UVM_ADVICE(flags);
1275
1276	vaddr_t start = args->uma_start;
1277	vsize_t size = args->uma_size;
1278	struct uvm_object *uobj = args->uma_uobj;
1279	voff_t uoffset = args->uma_uoffset;
1280
1281	const int kmap = (vm_map_pmap(map) == pmap_kernel());
1282	int merged = 0;
1283	int error;
1284	int newetype;
1285
1286	UVMHIST_FUNC(__func__);
1287	UVMHIST_CALLARGS(maphist, "(map=%#jx, start=%#jx, size=%ju, flags=%#jx)",
1288	    (uintptr_t)map, start, size, flags);
1289	UVMHIST_LOG(maphist, "  uobj/offset %#jx/%jd", (uintptr_t)uobj,
1290	    uoffset,0,0);
1291
1292	KASSERT(map->hint == prev_entry); /* bimerge case assumes this */
1293	KASSERT(vm_map_locked_p(map));
1294	KASSERT((flags & (UVM_FLAG_NOWAIT | UVM_FLAG_UNMAP)) !=
1295		(UVM_FLAG_NOWAIT | UVM_FLAG_UNMAP));
1296
1297	if (uobj)
1298		newetype = UVM_ET_OBJ;
1299	else
1300		newetype = 0;
1301
1302	if (flags & UVM_FLAG_COPYONW) {
1303		newetype |= UVM_ET_COPYONWRITE;
1304		if ((flags & UVM_FLAG_OVERLAY) == 0)
1305			newetype |= UVM_ET_NEEDSCOPY;
1306	}
1307
1308	/*
1309	 * For mappings with unmap, remove any old entries now.  Adding the new
1310	 * entry cannot fail because that can only happen if UVM_FLAG_NOWAIT
1311	 * is set, and we do not support nowait and unmap together.
1312	 */
1313
1314	if (flags & UVM_FLAG_UNMAP) {
1315		KASSERT(flags & UVM_FLAG_FIXED);
1316		uvm_unmap_remove(map, start, start + size, &dead_entries, 0);
1317#ifdef DEBUG
1318		struct vm_map_entry *tmp_entry __diagused;
1319		bool rv __diagused;
1320
1321		rv = uvm_map_lookup_entry(map, start, &tmp_entry);
1322		KASSERT(!rv);
1323		KASSERTMSG(prev_entry == tmp_entry,
1324			   "args %p prev_entry %p tmp_entry %p",
1325			   args, prev_entry, tmp_entry);
1326#endif
1327		SAVE_HINT(map, map->hint, prev_entry);
1328	}
1329
1330	/*
1331	 * try and insert in map by extending previous entry, if possible.
1332	 * XXX: we don't try and pull back the next entry.   might be useful
1333	 * for a stack, but we are currently allocating our stack in advance.
1334	 */
1335
1336	if (flags & UVM_FLAG_NOMERGE)
1337		goto nomerge;
1338
1339	if (prev_entry->end == start &&
1340	    prev_entry != &map->header &&
1341	    UVM_ET_ISCOMPATIBLE(prev_entry, newetype, uobj, 0,
1342	    prot, maxprot, inherit, advice, 0)) {
1343
1344		if (uobj && prev_entry->offset +
1345		    (prev_entry->end - prev_entry->start) != uoffset)
1346			goto forwardmerge;
1347
1348		/*
1349		 * can't extend a shared amap.  note: no need to lock amap to
1350		 * look at refs since we don't care about its exact value.
1351		 * if it is one (i.e. we have only reference) it will stay there
1352		 */
1353
1354		if (prev_entry->aref.ar_amap &&
1355		    amap_refs(prev_entry->aref.ar_amap) != 1) {
1356			goto forwardmerge;
1357		}
1358
1359		if (prev_entry->aref.ar_amap) {
1360			error = amap_extend(prev_entry, size,
1361			    amapwaitflag | AMAP_EXTEND_FORWARDS);
1362			if (error)
1363				goto nomerge;
1364		}
1365
1366		if (kmap) {
1367			UVMMAP_EVCNT_INCR(kbackmerge);
1368		} else {
1369			UVMMAP_EVCNT_INCR(ubackmerge);
1370		}
1371		UVMHIST_LOG(maphist,"  starting back merge", 0, 0, 0, 0);
1372
1373		/*
1374		 * drop our reference to uobj since we are extending a reference
1375		 * that we already have (the ref count can not drop to zero).
1376		 */
1377
1378		if (uobj && uobj->pgops->pgo_detach)
1379			uobj->pgops->pgo_detach(uobj);
1380
1381		/*
1382		 * Now that we've merged the entries, note that we've grown
1383		 * and our gap has shrunk.  Then fix the tree.
1384		 */
1385		prev_entry->end += size;
1386		prev_entry->gap -= size;
1387		uvm_rb_fixup(map, prev_entry);
1388
1389		uvm_map_check(map, "map backmerged");
1390
1391		UVMHIST_LOG(maphist,"<- done (via backmerge)!", 0, 0, 0, 0);
1392		merged++;
1393	}
1394
1395forwardmerge:
1396	if (prev_entry->next->start == (start + size) &&
1397	    prev_entry->next != &map->header &&
1398	    UVM_ET_ISCOMPATIBLE(prev_entry->next, newetype, uobj, 0,
1399	    prot, maxprot, inherit, advice, 0)) {
1400
1401		if (uobj && prev_entry->next->offset != uoffset + size)
1402			goto nomerge;
1403
1404		/*
1405		 * can't extend a shared amap.  note: no need to lock amap to
1406		 * look at refs since we don't care about its exact value.
1407		 * if it is one (i.e. we have only reference) it will stay there.
1408		 *
1409		 * note that we also can't merge two amaps, so if we
1410		 * merged with the previous entry which has an amap,
1411		 * and the next entry also has an amap, we give up.
1412		 *
1413		 * Interesting cases:
1414		 * amap, new, amap -> give up second merge (single fwd extend)
1415		 * amap, new, none -> double forward extend (extend again here)
1416		 * none, new, amap -> double backward extend (done here)
1417		 * uobj, new, amap -> single backward extend (done here)
1418		 *
1419		 * XXX should we attempt to deal with someone refilling
1420		 * the deallocated region between two entries that are
1421		 * backed by the same amap (ie, arefs is 2, "prev" and
1422		 * "next" refer to it, and adding this allocation will
1423		 * close the hole, thus restoring arefs to 1 and
1424		 * deallocating the "next" vm_map_entry)?  -- @@@
1425		 */
1426
1427		if (prev_entry->next->aref.ar_amap &&
1428		    (amap_refs(prev_entry->next->aref.ar_amap) != 1 ||
1429		     (merged && prev_entry->aref.ar_amap))) {
1430			goto nomerge;
1431		}
1432
1433		if (merged) {
1434			/*
1435			 * Try to extend the amap of the previous entry to
1436			 * cover the next entry as well.  If it doesn't work
1437			 * just skip on, don't actually give up, since we've
1438			 * already completed the back merge.
1439			 */
1440			if (prev_entry->aref.ar_amap) {
1441				if (amap_extend(prev_entry,
1442				    prev_entry->next->end -
1443				    prev_entry->next->start,
1444				    amapwaitflag | AMAP_EXTEND_FORWARDS))
1445					goto nomerge;
1446			}
1447
1448			/*
1449			 * Try to extend the amap of the *next* entry
1450			 * back to cover the new allocation *and* the
1451			 * previous entry as well (the previous merge
1452			 * didn't have an amap already otherwise we
1453			 * wouldn't be checking here for an amap).  If
1454			 * it doesn't work just skip on, again, don't
1455			 * actually give up, since we've already
1456			 * completed the back merge.
1457			 */
1458			else if (prev_entry->next->aref.ar_amap) {
1459				if (amap_extend(prev_entry->next,
1460				    prev_entry->end -
1461				    prev_entry->start,
1462				    amapwaitflag | AMAP_EXTEND_BACKWARDS))
1463					goto nomerge;
1464			}
1465		} else {
1466			/*
1467			 * Pull the next entry's amap backwards to cover this
1468			 * new allocation.
1469			 */
1470			if (prev_entry->next->aref.ar_amap) {
1471				error = amap_extend(prev_entry->next, size,
1472				    amapwaitflag | AMAP_EXTEND_BACKWARDS);
1473				if (error)
1474					goto nomerge;
1475			}
1476		}
1477
1478		if (merged) {
1479			if (kmap) {
1480				UVMMAP_EVCNT_DECR(kbackmerge);
1481				UVMMAP_EVCNT_INCR(kbimerge);
1482			} else {
1483				UVMMAP_EVCNT_DECR(ubackmerge);
1484				UVMMAP_EVCNT_INCR(ubimerge);
1485			}
1486		} else {
1487			if (kmap) {
1488				UVMMAP_EVCNT_INCR(kforwmerge);
1489			} else {
1490				UVMMAP_EVCNT_INCR(uforwmerge);
1491			}
1492		}
1493		UVMHIST_LOG(maphist,"  starting forward merge", 0, 0, 0, 0);
1494
1495		/*
1496		 * drop our reference to uobj since we are extending a reference
1497		 * that we already have (the ref count can not drop to zero).
1498		 */
1499		if (uobj && uobj->pgops->pgo_detach)
1500			uobj->pgops->pgo_detach(uobj);
1501
1502		if (merged) {
1503			dead = prev_entry->next;
1504			prev_entry->end = dead->end;
1505			uvm_map_entry_unlink(map, dead);
1506			if (dead->aref.ar_amap != NULL) {
1507				prev_entry->aref = dead->aref;
1508				dead->aref.ar_amap = NULL;
1509			}
1510		} else {
1511			prev_entry->next->start -= size;
1512			if (prev_entry != &map->header) {
1513				prev_entry->gap -= size;
1514				KASSERT(prev_entry->gap == uvm_rb_gap(prev_entry));
1515				uvm_rb_fixup(map, prev_entry);
1516			}
1517			if (uobj)
1518				prev_entry->next->offset = uoffset;
1519		}
1520
1521		uvm_map_check(map, "map forwardmerged");
1522
1523		UVMHIST_LOG(maphist,"<- done forwardmerge", 0, 0, 0, 0);
1524		merged++;
1525	}
1526
1527nomerge:
1528	if (!merged) {
1529		UVMHIST_LOG(maphist,"  allocating new map entry", 0, 0, 0, 0);
1530		if (kmap) {
1531			UVMMAP_EVCNT_INCR(knomerge);
1532		} else {
1533			UVMMAP_EVCNT_INCR(unomerge);
1534		}
1535
1536		/*
1537		 * allocate new entry and link it in.
1538		 */
1539
1540		if (new_entry == NULL) {
1541			new_entry = uvm_mapent_alloc(map,
1542				(flags & UVM_FLAG_NOWAIT));
1543			if (__predict_false(new_entry == NULL)) {
1544				error = ENOMEM;
1545				goto done;
1546			}
1547		}
1548		new_entry->start = start;
1549		new_entry->end = new_entry->start + size;
1550		new_entry->object.uvm_obj = uobj;
1551		new_entry->offset = uoffset;
1552
1553		new_entry->etype = newetype;
1554
1555		if (flags & UVM_FLAG_NOMERGE) {
1556			new_entry->flags |= UVM_MAP_NOMERGE;
1557		}
1558
1559		new_entry->protection = prot;
1560		new_entry->max_protection = maxprot;
1561		new_entry->inheritance = inherit;
1562		new_entry->wired_count = 0;
1563		new_entry->advice = advice;
1564		if (flags & UVM_FLAG_OVERLAY) {
1565
1566			/*
1567			 * to_add: for BSS we overallocate a little since we
1568			 * are likely to extend
1569			 */
1570
1571			vaddr_t to_add = (flags & UVM_FLAG_AMAPPAD) ?
1572				UVM_AMAP_CHUNK << PAGE_SHIFT : 0;
1573			struct vm_amap *amap = amap_alloc(size, to_add,
1574			    (flags & UVM_FLAG_NOWAIT));
1575			if (__predict_false(amap == NULL)) {
1576				error = ENOMEM;
1577				goto done;
1578			}
1579			new_entry->aref.ar_pageoff = 0;
1580			new_entry->aref.ar_amap = amap;
1581		} else {
1582			new_entry->aref.ar_pageoff = 0;
1583			new_entry->aref.ar_amap = NULL;
1584		}
1585		uvm_map_entry_link(map, prev_entry, new_entry);
1586
1587		/*
1588		 * Update the free space hint
1589		 */
1590
1591		if ((map->first_free == prev_entry) &&
1592		    (prev_entry->end >= new_entry->start))
1593			map->first_free = new_entry;
1594
1595		new_entry = NULL;
1596	}
1597
1598	map->size += size;
1599
1600	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
1601
1602	error = 0;
1603
1604done:
1605	vm_map_unlock(map);
1606
1607	if (new_entry) {
1608		uvm_mapent_free(new_entry);
1609	}
1610	if (dead) {
1611		KDASSERT(merged);
1612		uvm_mapent_free(dead);
1613	}
1614	if (dead_entries)
1615		uvm_unmap_detach(dead_entries, 0);
1616
1617	return error;
1618}
1619
1620/*
1621 * uvm_map_lookup_entry_bytree: lookup an entry in tree
1622 */
1623
1624static inline bool
1625uvm_map_lookup_entry_bytree(struct vm_map *map, vaddr_t address,
1626    struct vm_map_entry **entry	/* OUT */)
1627{
1628	struct vm_map_entry *prev = &map->header;
1629	struct vm_map_entry *cur = ROOT_ENTRY(map);
1630
1631	while (cur) {
1632		UVMMAP_EVCNT_INCR(mlk_treeloop);
1633		if (address >= cur->start) {
1634			if (address < cur->end) {
1635				*entry = cur;
1636				return true;
1637			}
1638			prev = cur;
1639			cur = RIGHT_ENTRY(cur);
1640		} else
1641			cur = LEFT_ENTRY(cur);
1642	}
1643	*entry = prev;
1644	return false;
1645}
1646
1647/*
1648 * uvm_map_lookup_entry: find map entry at or before an address
1649 *
1650 * => map must at least be read-locked by caller
1651 * => entry is returned in "entry"
1652 * => return value is true if address is in the returned entry
1653 */
1654
1655bool
1656uvm_map_lookup_entry(struct vm_map *map, vaddr_t address,
1657    struct vm_map_entry **entry	/* OUT */)
1658{
1659	struct vm_map_entry *cur;
1660	UVMHIST_FUNC(__func__);
1661	UVMHIST_CALLARGS(maphist,"(map=%#jx,addr=%#jx,ent=%#jx)",
1662	    (uintptr_t)map, address, (uintptr_t)entry, 0);
1663
1664	/*
1665	 * make a quick check to see if we are already looking at
1666	 * the entry we want (which is usually the case).  note also
1667	 * that we don't need to save the hint here...  it is the
1668	 * same hint (unless we are at the header, in which case the
1669	 * hint didn't buy us anything anyway).
1670	 */
1671
1672	cur = map->hint;
1673	UVMMAP_EVCNT_INCR(mlk_call);
1674	if (cur != &map->header &&
1675	    address >= cur->start && cur->end > address) {
1676		UVMMAP_EVCNT_INCR(mlk_hint);
1677		*entry = cur;
1678		UVMHIST_LOG(maphist,"<- got it via hint (%#jx)",
1679		    (uintptr_t)cur, 0, 0, 0);
1680		uvm_mapent_check(*entry);
1681		return (true);
1682	}
1683	uvm_map_check(map, __func__);
1684
1685	/*
1686	 * lookup in the tree.
1687	 */
1688
1689	UVMMAP_EVCNT_INCR(mlk_tree);
1690	if (__predict_true(uvm_map_lookup_entry_bytree(map, address, entry))) {
1691		SAVE_HINT(map, map->hint, *entry);
1692		UVMHIST_LOG(maphist,"<- search got it (%#jx)",
1693		    (uintptr_t)cur, 0, 0, 0);
1694		KDASSERT((*entry)->start <= address);
1695		KDASSERT(address < (*entry)->end);
1696		uvm_mapent_check(*entry);
1697		return (true);
1698	}
1699
1700	SAVE_HINT(map, map->hint, *entry);
1701	UVMHIST_LOG(maphist,"<- failed!",0,0,0,0);
1702	KDASSERT((*entry) == &map->header || (*entry)->end <= address);
1703	KDASSERT((*entry)->next == &map->header ||
1704	    address < (*entry)->next->start);
1705	return (false);
1706}
1707
1708/*
1709 * See if the range between start and start + length fits in the gap
1710 * entry->next->start and entry->end.  Returns 1 if fits, 0 if doesn't
1711 * fit, and -1 address wraps around.
1712 */
1713static int
1714uvm_map_space_avail(vaddr_t *start, vsize_t length, voff_t uoffset,
1715    vsize_t align, int flags, int topdown, struct vm_map_entry *entry)
1716{
1717	vaddr_t end;
1718
1719#ifdef PMAP_PREFER
1720	/*
1721	 * push start address forward as needed to avoid VAC alias problems.
1722	 * we only do this if a valid offset is specified.
1723	 */
1724
1725	if (uoffset != UVM_UNKNOWN_OFFSET)
1726		PMAP_PREFER(uoffset, start, length, topdown);
1727#endif
1728	if ((flags & UVM_FLAG_COLORMATCH) != 0) {
1729		KASSERT(align < uvmexp.ncolors);
1730		if (uvmexp.ncolors > 1) {
1731			const u_int colormask = uvmexp.colormask;
1732			const u_int colorsize = colormask + 1;
1733			vaddr_t hint = atop(*start);
1734			const u_int color = hint & colormask;
1735			if (color != align) {
1736				hint -= color;	/* adjust to color boundary */
1737				KASSERT((hint & colormask) == 0);
1738				if (topdown) {
1739					if (align > color)
1740						hint -= colorsize;
1741				} else {
1742					if (align < color)
1743						hint += colorsize;
1744				}
1745				*start = ptoa(hint + align); /* adjust to color */
1746			}
1747		}
1748	} else {
1749		KASSERT(powerof2(align));
1750		uvm_map_align_va(start, align, topdown);
1751		/*
1752		 * XXX Should we PMAP_PREFER() here again?
1753		 * eh...i think we're okay
1754		 */
1755	}
1756
1757	/*
1758	 * Find the end of the proposed new region.  Be sure we didn't
1759	 * wrap around the address; if so, we lose.  Otherwise, if the
1760	 * proposed new region fits before the next entry, we win.
1761	 */
1762
1763	end = *start + length;
1764	if (end < *start)
1765		return (-1);
1766
1767	if (entry->next->start >= end && *start >= entry->end)
1768		return (1);
1769
1770	return (0);
1771}
1772
1773static void
1774uvm_findspace_invariants(struct vm_map *map, vaddr_t orig_hint, vaddr_t length,
1775    struct uvm_object *uobj, voff_t uoffset, vsize_t align, int flags,
1776    vaddr_t hint, struct vm_map_entry *entry, int line)
1777{
1778	const int topdown = map->flags & VM_MAP_TOPDOWN;
1779
1780	KASSERTMSG( topdown || hint >= orig_hint,
1781	    "map=%p hint=%#"PRIxVADDR" orig_hint=%#"PRIxVADDR
1782	    " length=%#"PRIxVSIZE" uobj=%p uoffset=%#llx align=%"PRIxVSIZE
1783	    " flags=%#x entry=%p (uvm_map_findspace line %d)",
1784	    map, hint, orig_hint,
1785	    length, uobj, (unsigned long long)uoffset, align,
1786	    flags, entry, line);
1787#ifndef __sh3__ /* XXXRO: kern/51254 */
1788	KASSERTMSG(!topdown || hint <= orig_hint,
1789#else
1790	if (__predict_false(!(!topdown || hint <= orig_hint)))
1791		printf(
1792#endif
1793	    "map=%p hint=%#"PRIxVADDR" orig_hint=%#"PRIxVADDR
1794	    " length=%#"PRIxVSIZE" uobj=%p uoffset=%#llx align=%"PRIxVSIZE
1795	    " flags=%#x entry=%p (uvm_map_findspace line %d)",
1796	    map, hint, orig_hint,
1797	    length, uobj, (unsigned long long)uoffset, align,
1798	    flags, entry, line);
1799}
1800
1801/*
1802 * uvm_map_findspace: find "length" sized space in "map".
1803 *
1804 * => "hint" is a hint about where we want it, unless UVM_FLAG_FIXED is
1805 *	set in "flags" (in which case we insist on using "hint").
1806 * => "result" is VA returned
1807 * => uobj/uoffset are to be used to handle VAC alignment, if required
1808 * => if "align" is non-zero, we attempt to align to that value.
1809 * => caller must at least have read-locked map
1810 * => returns NULL on failure, or pointer to prev. map entry if success
1811 * => note this is a cross between the old vm_map_findspace and vm_map_find
1812 */
1813
1814struct vm_map_entry *
1815uvm_map_findspace(struct vm_map *map, vaddr_t hint, vsize_t length,
1816    vaddr_t *result /* OUT */, struct uvm_object *uobj, voff_t uoffset,
1817    vsize_t align, int flags)
1818{
1819#define	INVARIANTS()							      \
1820	uvm_findspace_invariants(map, orig_hint, length, uobj, uoffset, align,\
1821	    flags, hint, entry, __LINE__)
1822	struct vm_map_entry *entry = NULL;
1823	struct vm_map_entry *child, *prev, *tmp;
1824	vaddr_t orig_hint __diagused;
1825	const int topdown = map->flags & VM_MAP_TOPDOWN;
1826	int avail;
1827	UVMHIST_FUNC(__func__);
1828	UVMHIST_CALLARGS(maphist, "(map=%#jx, hint=%#jx, len=%ju, flags=%#jx...",
1829	    (uintptr_t)map, hint, length, flags);
1830	UVMHIST_LOG(maphist, " uobj=%#jx, uoffset=%#jx, align=%#jx)",
1831	    (uintptr_t)uobj, uoffset, align, 0);
1832
1833	KASSERT((flags & UVM_FLAG_COLORMATCH) != 0 || powerof2(align));
1834	KASSERT((flags & UVM_FLAG_COLORMATCH) == 0 || align < uvmexp.ncolors);
1835	KASSERT((flags & UVM_FLAG_FIXED) == 0 || align == 0);
1836
1837	uvm_map_check(map, "map_findspace entry");
1838
1839	/*
1840	 * Clamp the hint to the VM map's min/max address, and remmeber
1841	 * the clamped original hint.  Remember the original hint,
1842	 * clamped to the min/max address.  If we are aligning, then we
1843	 * may have to try again with no alignment constraint if we
1844	 * fail the first time.
1845	 *
1846	 * We use the original hint to verify later that the search has
1847	 * been monotonic -- that is, nonincreasing or nondecreasing,
1848	 * according to topdown or !topdown respectively.  But the
1849	 * clamping is not monotonic.
1850	 */
1851	if (hint < vm_map_min(map)) {	/* check ranges ... */
1852		if (flags & UVM_FLAG_FIXED) {
1853			UVMHIST_LOG(maphist,"<- VA below map range",0,0,0,0);
1854			return (NULL);
1855		}
1856		hint = vm_map_min(map);
1857	}
1858	if (hint > vm_map_max(map)) {
1859		UVMHIST_LOG(maphist,"<- VA %#jx > range [%#jx->%#jx]",
1860		    hint, vm_map_min(map), vm_map_max(map), 0);
1861		return (NULL);
1862	}
1863	orig_hint = hint;
1864	INVARIANTS();
1865
1866	UVMHIST_LOG(maphist,"<- VA %#jx vs range [%#jx->%#jx]",
1867	    hint, vm_map_min(map), vm_map_max(map), 0);
1868
1869	/*
1870	 * hint may not be aligned properly; we need round up or down it
1871	 * before proceeding further.
1872	 */
1873	if ((flags & UVM_FLAG_COLORMATCH) == 0) {
1874		uvm_map_align_va(&hint, align, topdown);
1875		INVARIANTS();
1876	}
1877
1878	UVMHIST_LOG(maphist,"<- VA %#jx vs range [%#jx->%#jx]",
1879	    hint, vm_map_min(map), vm_map_max(map), 0);
1880	/*
1881	 * Look for the first possible address; if there's already
1882	 * something at this address, we have to start after it.
1883	 */
1884
1885	/*
1886	 * @@@: there are four, no, eight cases to consider.
1887	 *
1888	 * 0: found,     fixed,     bottom up -> fail
1889	 * 1: found,     fixed,     top down  -> fail
1890	 * 2: found,     not fixed, bottom up -> start after entry->end,
1891	 *                                       loop up
1892	 * 3: found,     not fixed, top down  -> start before entry->start,
1893	 *                                       loop down
1894	 * 4: not found, fixed,     bottom up -> check entry->next->start, fail
1895	 * 5: not found, fixed,     top down  -> check entry->next->start, fail
1896	 * 6: not found, not fixed, bottom up -> check entry->next->start,
1897	 *                                       loop up
1898	 * 7: not found, not fixed, top down  -> check entry->next->start,
1899	 *                                       loop down
1900	 *
1901	 * as you can see, it reduces to roughly five cases, and that
1902	 * adding top down mapping only adds one unique case (without
1903	 * it, there would be four cases).
1904	 */
1905
1906	if ((flags & UVM_FLAG_FIXED) == 0 &&
1907	    hint == (topdown ? vm_map_max(map) : vm_map_min(map))) {
1908		/*
1909		 * The uvm_map_findspace algorithm is monotonic -- for
1910		 * topdown VM it starts with a high hint and returns a
1911		 * lower free address; for !topdown VM it starts with a
1912		 * low hint and returns a higher free address.  As an
1913		 * optimization, start with the first (highest for
1914		 * topdown, lowest for !topdown) free address.
1915		 *
1916		 * XXX This `optimization' probably doesn't actually do
1917		 * much in practice unless userland explicitly passes
1918		 * the VM map's minimum or maximum address, which
1919		 * varies from machine to machine (VM_MAX/MIN_ADDRESS,
1920		 * e.g. 0x7fbfdfeff000 on amd64 but 0xfffffffff000 on
1921		 * aarch64) and may vary according to other factors
1922		 * like sysctl vm.user_va0_disable.  In particular, if
1923		 * the user specifies 0 as a hint to mmap, then mmap
1924		 * will choose a default address which is usually _not_
1925		 * VM_MAX/MIN_ADDRESS but something else instead like
1926		 * VM_MAX_ADDRESS - stack size - guard page overhead,
1927		 * in which case this branch is never hit.
1928		 *
1929		 * In fact, this branch appears to have been broken for
1930		 * two decades between when topdown was introduced in
1931		 * ~2003 and when it was adapted to handle the topdown
1932		 * case without violating the monotonicity assertion in
1933		 * 2022.  Maybe Someone^TM should either ditch the
1934		 * optimization or find a better way to do it.
1935		 */
1936		entry = map->first_free;
1937	} else {
1938		if (uvm_map_lookup_entry(map, hint, &entry)) {
1939			/* "hint" address already in use ... */
1940			if (flags & UVM_FLAG_FIXED) {
1941				UVMHIST_LOG(maphist, "<- fixed & VA in use",
1942				    0, 0, 0, 0);
1943				return (NULL);
1944			}
1945			if (topdown)
1946				/* Start from lower gap. */
1947				entry = entry->prev;
1948		} else if (flags & UVM_FLAG_FIXED) {
1949			if (entry->next->start >= hint + length &&
1950			    hint + length > hint)
1951				goto found;
1952
1953			/* "hint" address is gap but too small */
1954			UVMHIST_LOG(maphist, "<- fixed mapping failed",
1955			    0, 0, 0, 0);
1956			return (NULL); /* only one shot at it ... */
1957		} else {
1958			/*
1959			 * See if given hint fits in this gap.
1960			 */
1961			avail = uvm_map_space_avail(&hint, length,
1962			    uoffset, align, flags, topdown, entry);
1963			INVARIANTS();
1964			switch (avail) {
1965			case 1:
1966				goto found;
1967			case -1:
1968				goto wraparound;
1969			}
1970
1971			if (topdown) {
1972				/*
1973				 * Still there is a chance to fit
1974				 * if hint > entry->end.
1975				 */
1976			} else {
1977				/* Start from higher gap. */
1978				entry = entry->next;
1979				if (entry == &map->header)
1980					goto notfound;
1981				goto nextgap;
1982			}
1983		}
1984	}
1985
1986	/*
1987	 * Note that all UVM_FLAGS_FIXED case is already handled.
1988	 */
1989	KDASSERT((flags & UVM_FLAG_FIXED) == 0);
1990
1991	/* Try to find the space in the red-black tree */
1992
1993	/* Check slot before any entry */
1994	if (topdown) {
1995		KASSERTMSG(entry->next->start >= vm_map_min(map),
1996		    "map=%p entry=%p entry->next=%p"
1997		    " entry->next->start=0x%"PRIxVADDR" min=0x%"PRIxVADDR,
1998		    map, entry, entry->next,
1999		    entry->next->start, vm_map_min(map));
2000		if (length > entry->next->start - vm_map_min(map))
2001			hint = vm_map_min(map); /* XXX goto wraparound? */
2002		else
2003			hint = entry->next->start - length;
2004		KASSERT(hint >= vm_map_min(map));
2005	} else {
2006		hint = entry->end;
2007	}
2008	INVARIANTS();
2009	avail = uvm_map_space_avail(&hint, length, uoffset, align, flags,
2010	    topdown, entry);
2011	INVARIANTS();
2012	switch (avail) {
2013	case 1:
2014		goto found;
2015	case -1:
2016		goto wraparound;
2017	}
2018
2019nextgap:
2020	KDASSERT((flags & UVM_FLAG_FIXED) == 0);
2021	/* If there is not enough space in the whole tree, we fail */
2022	tmp = ROOT_ENTRY(map);
2023	if (tmp == NULL || tmp->maxgap < length)
2024		goto notfound;
2025
2026	prev = NULL; /* previous candidate */
2027
2028	/* Find an entry close to hint that has enough space */
2029	for (; tmp;) {
2030		KASSERT(tmp->next->start == tmp->end + tmp->gap);
2031		if (topdown) {
2032			if (tmp->next->start < hint + length &&
2033			    (prev == NULL || tmp->end > prev->end)) {
2034				if (tmp->gap >= length)
2035					prev = tmp;
2036				else if ((child = LEFT_ENTRY(tmp)) != NULL
2037				    && child->maxgap >= length)
2038					prev = tmp;
2039			}
2040		} else {
2041			if (tmp->end >= hint &&
2042			    (prev == NULL || tmp->end < prev->end)) {
2043				if (tmp->gap >= length)
2044					prev = tmp;
2045				else if ((child = RIGHT_ENTRY(tmp)) != NULL
2046				    && child->maxgap >= length)
2047					prev = tmp;
2048			}
2049		}
2050		if (tmp->next->start < hint + length)
2051			child = RIGHT_ENTRY(tmp);
2052		else if (tmp->end > hint)
2053			child = LEFT_ENTRY(tmp);
2054		else {
2055			if (tmp->gap >= length)
2056				break;
2057			if (topdown)
2058				child = LEFT_ENTRY(tmp);
2059			else
2060				child = RIGHT_ENTRY(tmp);
2061		}
2062		if (child == NULL || child->maxgap < length)
2063			break;
2064		tmp = child;
2065	}
2066
2067	if (tmp != NULL && tmp->start < hint && hint < tmp->next->start) {
2068		/*
2069		 * Check if the entry that we found satifies the
2070		 * space requirement
2071		 */
2072		if (topdown) {
2073			if (hint > tmp->next->start - length)
2074				hint = tmp->next->start - length;
2075		} else {
2076			if (hint < tmp->end)
2077				hint = tmp->end;
2078		}
2079		INVARIANTS();
2080		avail = uvm_map_space_avail(&hint, length, uoffset, align,
2081		    flags, topdown, tmp);
2082		INVARIANTS();
2083		switch (avail) {
2084		case 1:
2085			entry = tmp;
2086			goto found;
2087		case -1:
2088			goto wraparound;
2089		}
2090		if (tmp->gap >= length)
2091			goto listsearch;
2092	}
2093	if (prev == NULL)
2094		goto notfound;
2095
2096	if (topdown) {
2097		KASSERT(orig_hint >= prev->next->start - length ||
2098		    prev->next->start - length > prev->next->start);
2099		hint = prev->next->start - length;
2100	} else {
2101		KASSERT(orig_hint <= prev->end);
2102		hint = prev->end;
2103	}
2104	INVARIANTS();
2105	avail = uvm_map_space_avail(&hint, length, uoffset, align,
2106	    flags, topdown, prev);
2107	INVARIANTS();
2108	switch (avail) {
2109	case 1:
2110		entry = prev;
2111		goto found;
2112	case -1:
2113		goto wraparound;
2114	}
2115	if (prev->gap >= length)
2116		goto listsearch;
2117
2118	if (topdown)
2119		tmp = LEFT_ENTRY(prev);
2120	else
2121		tmp = RIGHT_ENTRY(prev);
2122	for (;;) {
2123		KASSERT(tmp);
2124		KASSERTMSG(tmp->maxgap >= length,
2125		    "tmp->maxgap=0x%"PRIxVSIZE" length=0x%"PRIxVSIZE,
2126		    tmp->maxgap, length);
2127		if (topdown)
2128			child = RIGHT_ENTRY(tmp);
2129		else
2130			child = LEFT_ENTRY(tmp);
2131		if (child && child->maxgap >= length) {
2132			tmp = child;
2133			continue;
2134		}
2135		if (tmp->gap >= length)
2136			break;
2137		if (topdown)
2138			tmp = LEFT_ENTRY(tmp);
2139		else
2140			tmp = RIGHT_ENTRY(tmp);
2141	}
2142
2143	if (topdown) {
2144		KASSERT(orig_hint >= tmp->next->start - length ||
2145		    tmp->next->start - length > tmp->next->start);
2146		hint = tmp->next->start - length;
2147	} else {
2148		KASSERT(orig_hint <= tmp->end);
2149		hint = tmp->end;
2150	}
2151	INVARIANTS();
2152	avail = uvm_map_space_avail(&hint, length, uoffset, align,
2153	    flags, topdown, tmp);
2154	INVARIANTS();
2155	switch (avail) {
2156	case 1:
2157		entry = tmp;
2158		goto found;
2159	case -1:
2160		goto wraparound;
2161	}
2162
2163	/*
2164	 * The tree fails to find an entry because of offset or alignment
2165	 * restrictions.  Search the list instead.
2166	 */
2167 listsearch:
2168	/*
2169	 * Look through the rest of the map, trying to fit a new region in
2170	 * the gap between existing regions, or after the very last region.
2171	 * note: entry->end = base VA of current gap,
2172	 *	 entry->next->start = VA of end of current gap
2173	 */
2174
2175	INVARIANTS();
2176	for (;;) {
2177		/* Update hint for current gap. */
2178		hint = topdown ? entry->next->start - length : entry->end;
2179		INVARIANTS();
2180
2181		/* See if it fits. */
2182		avail = uvm_map_space_avail(&hint, length, uoffset, align,
2183		    flags, topdown, entry);
2184		INVARIANTS();
2185		switch (avail) {
2186		case 1:
2187			goto found;
2188		case -1:
2189			goto wraparound;
2190		}
2191
2192		/* Advance to next/previous gap */
2193		if (topdown) {
2194			if (entry == &map->header) {
2195				UVMHIST_LOG(maphist, "<- failed (off start)",
2196				    0,0,0,0);
2197				goto notfound;
2198			}
2199			entry = entry->prev;
2200		} else {
2201			entry = entry->next;
2202			if (entry == &map->header) {
2203				UVMHIST_LOG(maphist, "<- failed (off end)",
2204				    0,0,0,0);
2205				goto notfound;
2206			}
2207		}
2208	}
2209
2210 found:
2211	SAVE_HINT(map, map->hint, entry);
2212	*result = hint;
2213	UVMHIST_LOG(maphist,"<- got it!  (result=%#jx)", hint, 0,0,0);
2214	INVARIANTS();
2215	KASSERT(entry->end <= hint);
2216	KASSERT(hint + length <= entry->next->start);
2217	return (entry);
2218
2219 wraparound:
2220	UVMHIST_LOG(maphist, "<- failed (wrap around)", 0,0,0,0);
2221
2222	return (NULL);
2223
2224 notfound:
2225	UVMHIST_LOG(maphist, "<- failed (notfound)", 0,0,0,0);
2226
2227	return (NULL);
2228#undef INVARIANTS
2229}
2230
2231/*
2232 *   U N M A P   -   m a i n   h e l p e r   f u n c t i o n s
2233 */
2234
2235/*
2236 * uvm_unmap_remove: remove mappings from a vm_map (from "start" up to "stop")
2237 *
2238 * => caller must check alignment and size
2239 * => map must be locked by caller
2240 * => we return a list of map entries that we've remove from the map
2241 *    in "entry_list"
2242 */
2243
2244void
2245uvm_unmap_remove(struct vm_map *map, vaddr_t start, vaddr_t end,
2246    struct vm_map_entry **entry_list /* OUT */, int flags)
2247{
2248	struct vm_map_entry *entry, *first_entry, *next;
2249	vaddr_t len;
2250	UVMHIST_FUNC(__func__);
2251	UVMHIST_CALLARGS(maphist,"(map=%#jx, start=%#jx, end=%#jx)",
2252	    (uintptr_t)map, start, end, 0);
2253	VM_MAP_RANGE_CHECK(map, start, end);
2254
2255	uvm_map_check(map, "unmap_remove entry");
2256
2257	/*
2258	 * find first entry
2259	 */
2260
2261	if (uvm_map_lookup_entry(map, start, &first_entry) == true) {
2262		/* clip and go... */
2263		entry = first_entry;
2264		UVM_MAP_CLIP_START(map, entry, start);
2265		/* critical!  prevents stale hint */
2266		SAVE_HINT(map, entry, entry->prev);
2267	} else {
2268		entry = first_entry->next;
2269	}
2270
2271	/*
2272	 * save the free space hint
2273	 */
2274
2275	if (map->first_free != &map->header && map->first_free->start >= start)
2276		map->first_free = entry->prev;
2277
2278	/*
2279	 * note: we now re-use first_entry for a different task.  we remove
2280	 * a number of map entries from the map and save them in a linked
2281	 * list headed by "first_entry".  once we remove them from the map
2282	 * the caller should unlock the map and drop the references to the
2283	 * backing objects [c.f. uvm_unmap_detach].  the object is to
2284	 * separate unmapping from reference dropping.  why?
2285	 *   [1] the map has to be locked for unmapping
2286	 *   [2] the map need not be locked for reference dropping
2287	 *   [3] dropping references may trigger pager I/O, and if we hit
2288	 *       a pager that does synchronous I/O we may have to wait for it.
2289	 *   [4] we would like all waiting for I/O to occur with maps unlocked
2290	 *       so that we don't block other threads.
2291	 */
2292
2293	first_entry = NULL;
2294	*entry_list = NULL;
2295
2296	/*
2297	 * break up the area into map entry sized regions and unmap.  note
2298	 * that all mappings have to be removed before we can even consider
2299	 * dropping references to amaps or VM objects (otherwise we could end
2300	 * up with a mapping to a page on the free list which would be very bad)
2301	 */
2302
2303	while ((entry != &map->header) && (entry->start < end)) {
2304		KASSERT((entry->flags & UVM_MAP_STATIC) == 0);
2305
2306		UVM_MAP_CLIP_END(map, entry, end);
2307		next = entry->next;
2308		len = entry->end - entry->start;
2309
2310		/*
2311		 * unwire before removing addresses from the pmap; otherwise
2312		 * unwiring will put the entries back into the pmap (XXX).
2313		 */
2314
2315		if (VM_MAPENT_ISWIRED(entry)) {
2316			uvm_map_entry_unwire(map, entry);
2317		}
2318		if (flags & UVM_FLAG_VAONLY) {
2319
2320			/* nothing */
2321
2322		} else if ((map->flags & VM_MAP_PAGEABLE) == 0) {
2323
2324			/*
2325			 * if the map is non-pageable, any pages mapped there
2326			 * must be wired and entered with pmap_kenter_pa(),
2327			 * and we should free any such pages immediately.
2328			 * this is mostly used for kmem_map.
2329			 */
2330			KASSERT(vm_map_pmap(map) == pmap_kernel());
2331
2332			uvm_km_pgremove_intrsafe(map, entry->start, entry->end);
2333		} else if (UVM_ET_ISOBJ(entry) &&
2334			   UVM_OBJ_IS_KERN_OBJECT(entry->object.uvm_obj)) {
2335			panic("%s: kernel object %p %p\n",
2336			    __func__, map, entry);
2337		} else if (UVM_ET_ISOBJ(entry) || entry->aref.ar_amap) {
2338			/*
2339			 * remove mappings the standard way.  lock object
2340			 * and/or amap to ensure vm_page state does not
2341			 * change while in pmap_remove().
2342			 */
2343
2344#ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
2345			uvm_map_lock_entry(entry, RW_WRITER);
2346#else
2347			uvm_map_lock_entry(entry, RW_READER);
2348#endif
2349			pmap_remove(map->pmap, entry->start, entry->end);
2350
2351			/*
2352			 * note: if map is dying, leave pmap_update() for
2353			 * later.  if the map is to be reused (exec) then
2354			 * pmap_update() will be called.  if the map is
2355			 * being disposed of (exit) then pmap_destroy()
2356			 * will be called.
2357			 */
2358
2359			if ((map->flags & VM_MAP_DYING) == 0) {
2360				pmap_update(vm_map_pmap(map));
2361			} else {
2362				KASSERT(vm_map_pmap(map) != pmap_kernel());
2363			}
2364
2365			uvm_map_unlock_entry(entry);
2366		}
2367
2368#if defined(UVMDEBUG)
2369		/*
2370		 * check if there's remaining mapping,
2371		 * which is a bug in caller.
2372		 */
2373
2374		vaddr_t va;
2375		for (va = entry->start; va < entry->end;
2376		    va += PAGE_SIZE) {
2377			if (pmap_extract(vm_map_pmap(map), va, NULL)) {
2378				panic("%s: %#"PRIxVADDR" has mapping",
2379				    __func__, va);
2380			}
2381		}
2382
2383		if (VM_MAP_IS_KERNEL(map) && (flags & UVM_FLAG_NOWAIT) == 0) {
2384			uvm_km_check_empty(map, entry->start, entry->end);
2385		}
2386#endif /* defined(UVMDEBUG) */
2387
2388		/*
2389		 * remove entry from map and put it on our list of entries
2390		 * that we've nuked.  then go to next entry.
2391		 */
2392
2393		UVMHIST_LOG(maphist, "  removed map entry %#jx",
2394		    (uintptr_t)entry, 0, 0, 0);
2395
2396		/* critical!  prevents stale hint */
2397		SAVE_HINT(map, entry, entry->prev);
2398
2399		uvm_map_entry_unlink(map, entry);
2400		KASSERT(map->size >= len);
2401		map->size -= len;
2402		entry->prev = NULL;
2403		entry->next = first_entry;
2404		first_entry = entry;
2405		entry = next;
2406	}
2407
2408	uvm_map_check(map, "unmap_remove leave");
2409
2410	/*
2411	 * now we've cleaned up the map and are ready for the caller to drop
2412	 * references to the mapped objects.
2413	 */
2414
2415	*entry_list = first_entry;
2416	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
2417
2418	if (map->flags & VM_MAP_WANTVA) {
2419		mutex_enter(&map->misc_lock);
2420		map->flags &= ~VM_MAP_WANTVA;
2421		cv_broadcast(&map->cv);
2422		mutex_exit(&map->misc_lock);
2423	}
2424}
2425
2426/*
2427 * uvm_unmap_detach: drop references in a chain of map entries
2428 *
2429 * => we will free the map entries as we traverse the list.
2430 */
2431
2432void
2433uvm_unmap_detach(struct vm_map_entry *first_entry, int flags)
2434{
2435	struct vm_map_entry *next_entry;
2436	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
2437
2438	while (first_entry) {
2439		KASSERT(!VM_MAPENT_ISWIRED(first_entry));
2440		UVMHIST_LOG(maphist,
2441		    "  detach %#jx: amap=%#jx, obj=%#jx, submap?=%jd",
2442		    (uintptr_t)first_entry,
2443		    (uintptr_t)first_entry->aref.ar_amap,
2444		    (uintptr_t)first_entry->object.uvm_obj,
2445		    UVM_ET_ISSUBMAP(first_entry));
2446
2447		/*
2448		 * drop reference to amap, if we've got one
2449		 */
2450
2451		if (first_entry->aref.ar_amap)
2452			uvm_map_unreference_amap(first_entry, flags);
2453
2454		/*
2455		 * drop reference to our backing object, if we've got one
2456		 */
2457
2458		KASSERT(!UVM_ET_ISSUBMAP(first_entry));
2459		if (UVM_ET_ISOBJ(first_entry) &&
2460		    first_entry->object.uvm_obj->pgops->pgo_detach) {
2461			(*first_entry->object.uvm_obj->pgops->pgo_detach)
2462				(first_entry->object.uvm_obj);
2463		}
2464		next_entry = first_entry->next;
2465		uvm_mapent_free(first_entry);
2466		first_entry = next_entry;
2467	}
2468	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
2469}
2470
2471/*
2472 *   E X T R A C T I O N   F U N C T I O N S
2473 */
2474
2475/*
2476 * uvm_map_reserve: reserve space in a vm_map for future use.
2477 *
2478 * => we reserve space in a map by putting a dummy map entry in the
2479 *    map (dummy means obj=NULL, amap=NULL, prot=VM_PROT_NONE)
2480 * => map should be unlocked (we will write lock it)
2481 * => we return true if we were able to reserve space
2482 * => XXXCDC: should be inline?
2483 */
2484
2485int
2486uvm_map_reserve(struct vm_map *map, vsize_t size,
2487    vaddr_t offset	/* hint for pmap_prefer */,
2488    vsize_t align	/* alignment */,
2489    vaddr_t *raddr	/* IN:hint, OUT: reserved VA */,
2490    uvm_flag_t flags	/* UVM_FLAG_FIXED or UVM_FLAG_COLORMATCH or 0 */)
2491{
2492	UVMHIST_FUNC(__func__);
2493	UVMHIST_CALLARGS(maphist, "(map=%#jx, size=%#jx, offset=%#jx, addr=%#jx)",
2494	    (uintptr_t)map, size, offset, (uintptr_t)raddr);
2495
2496	size = round_page(size);
2497
2498	/*
2499	 * reserve some virtual space.
2500	 */
2501
2502	if (uvm_map(map, raddr, size, NULL, offset, align,
2503	    UVM_MAPFLAG(UVM_PROT_NONE, UVM_PROT_NONE, UVM_INH_NONE,
2504	    UVM_ADV_RANDOM, UVM_FLAG_NOMERGE|flags)) != 0) {
2505	    UVMHIST_LOG(maphist, "<- done (no VM)", 0,0,0,0);
2506		return (false);
2507	}
2508
2509	UVMHIST_LOG(maphist, "<- done (*raddr=%#jx)", *raddr,0,0,0);
2510	return (true);
2511}
2512
2513/*
2514 * uvm_map_replace: replace a reserved (blank) area of memory with
2515 * real mappings.
2516 *
2517 * => caller must WRITE-LOCK the map
2518 * => we return true if replacement was a success
2519 * => we expect the newents chain to have nnewents entrys on it and
2520 *    we expect newents->prev to point to the last entry on the list
2521 * => note newents is allowed to be NULL
2522 */
2523
2524static int
2525uvm_map_replace(struct vm_map *map, vaddr_t start, vaddr_t end,
2526    struct vm_map_entry *newents, int nnewents, vsize_t nsize,
2527    struct vm_map_entry **oldentryp)
2528{
2529	struct vm_map_entry *oldent, *last;
2530
2531	uvm_map_check(map, "map_replace entry");
2532
2533	/*
2534	 * first find the blank map entry at the specified address
2535	 */
2536
2537	if (!uvm_map_lookup_entry(map, start, &oldent)) {
2538		return (false);
2539	}
2540
2541	/*
2542	 * check to make sure we have a proper blank entry
2543	 */
2544
2545	if (end < oldent->end) {
2546		UVM_MAP_CLIP_END(map, oldent, end);
2547	}
2548	if (oldent->start != start || oldent->end != end ||
2549	    oldent->object.uvm_obj != NULL || oldent->aref.ar_amap != NULL) {
2550		return (false);
2551	}
2552
2553#ifdef DIAGNOSTIC
2554
2555	/*
2556	 * sanity check the newents chain
2557	 */
2558
2559	{
2560		struct vm_map_entry *tmpent = newents;
2561		int nent = 0;
2562		vsize_t sz = 0;
2563		vaddr_t cur = start;
2564
2565		while (tmpent) {
2566			nent++;
2567			sz += tmpent->end - tmpent->start;
2568			if (tmpent->start < cur)
2569				panic("uvm_map_replace1");
2570			if (tmpent->start >= tmpent->end || tmpent->end > end) {
2571				panic("uvm_map_replace2: "
2572				    "tmpent->start=%#"PRIxVADDR
2573				    ", tmpent->end=%#"PRIxVADDR
2574				    ", end=%#"PRIxVADDR,
2575				    tmpent->start, tmpent->end, end);
2576			}
2577			cur = tmpent->end;
2578			if (tmpent->next) {
2579				if (tmpent->next->prev != tmpent)
2580					panic("uvm_map_replace3");
2581			} else {
2582				if (newents->prev != tmpent)
2583					panic("uvm_map_replace4");
2584			}
2585			tmpent = tmpent->next;
2586		}
2587		if (nent != nnewents)
2588			panic("uvm_map_replace5");
2589		if (sz != nsize)
2590			panic("uvm_map_replace6");
2591	}
2592#endif
2593
2594	/*
2595	 * map entry is a valid blank!   replace it.   (this does all the
2596	 * work of map entry link/unlink...).
2597	 */
2598
2599	if (newents) {
2600		last = newents->prev;
2601
2602		/* critical: flush stale hints out of map */
2603		SAVE_HINT(map, map->hint, newents);
2604		if (map->first_free == oldent)
2605			map->first_free = last;
2606
2607		last->next = oldent->next;
2608		last->next->prev = last;
2609
2610		/* Fix RB tree */
2611		uvm_rb_remove(map, oldent);
2612
2613		newents->prev = oldent->prev;
2614		newents->prev->next = newents;
2615		map->nentries = map->nentries + (nnewents - 1);
2616
2617		/* Fixup the RB tree */
2618		{
2619			int i;
2620			struct vm_map_entry *tmp;
2621
2622			tmp = newents;
2623			for (i = 0; i < nnewents && tmp; i++) {
2624				uvm_rb_insert(map, tmp);
2625				tmp = tmp->next;
2626			}
2627		}
2628	} else {
2629		/* NULL list of new entries: just remove the old one */
2630		clear_hints(map, oldent);
2631		uvm_map_entry_unlink(map, oldent);
2632	}
2633	map->size -= end - start - nsize;
2634
2635	uvm_map_check(map, "map_replace leave");
2636
2637	/*
2638	 * now we can free the old blank entry and return.
2639	 */
2640
2641	*oldentryp = oldent;
2642	return (true);
2643}
2644
2645/*
2646 * uvm_map_extract: extract a mapping from a map and put it somewhere
2647 *	(maybe removing the old mapping)
2648 *
2649 * => maps should be unlocked (we will write lock them)
2650 * => returns 0 on success, error code otherwise
2651 * => start must be page aligned
2652 * => len must be page sized
2653 * => flags:
2654 *      UVM_EXTRACT_REMOVE: remove mappings from srcmap
2655 *      UVM_EXTRACT_CONTIG: abort if unmapped area (advisory only)
2656 *      UVM_EXTRACT_QREF: for a temporary extraction do quick obj refs
2657 *      UVM_EXTRACT_FIXPROT: set prot to maxprot as we go
2658 *      UVM_EXTRACT_PROT_ALL: set prot to UVM_PROT_ALL as we go
2659 *    >>>NOTE: if you set REMOVE, you are not allowed to use CONTIG or QREF!<<<
2660 *    >>>NOTE: QREF's must be unmapped via the QREF path, thus should only
2661 *             be used from within the kernel in a kernel level map <<<
2662 */
2663
2664int
2665uvm_map_extract(struct vm_map *srcmap, vaddr_t start, vsize_t len,
2666    struct vm_map *dstmap, vaddr_t *dstaddrp, int flags)
2667{
2668	vaddr_t dstaddr, end, newend, oldoffset, fudge, orig_fudge;
2669	struct vm_map_entry *chain, *endchain, *entry, *orig_entry, *newentry,
2670	    *deadentry, *oldentry;
2671	struct vm_map_entry *resentry = NULL; /* a dummy reservation entry */
2672	vsize_t elen __unused;
2673	int nchain, error, copy_ok;
2674	vsize_t nsize;
2675	UVMHIST_FUNC(__func__);
2676	UVMHIST_CALLARGS(maphist,"(srcmap=%#jx,start=%#jx, len=%#jx",
2677	    (uintptr_t)srcmap, start, len, 0);
2678	UVMHIST_LOG(maphist," ...,dstmap=%#jx, flags=%#jx)",
2679	    (uintptr_t)dstmap, flags, 0, 0);
2680
2681	/*
2682	 * step 0: sanity check: start must be on a page boundary, length
2683	 * must be page sized.  can't ask for CONTIG/QREF if you asked for
2684	 * REMOVE.
2685	 */
2686
2687	KASSERTMSG((start & PAGE_MASK) == 0, "start=0x%"PRIxVADDR, start);
2688	KASSERTMSG((len & PAGE_MASK) == 0, "len=0x%"PRIxVADDR, len);
2689	KASSERT((flags & UVM_EXTRACT_REMOVE) == 0 ||
2690		(flags & (UVM_EXTRACT_CONTIG|UVM_EXTRACT_QREF)) == 0);
2691
2692	/*
2693	 * step 1: reserve space in the target map for the extracted area
2694	 */
2695
2696	if ((flags & UVM_EXTRACT_RESERVED) == 0) {
2697		dstaddr = vm_map_min(dstmap);
2698		if (!uvm_map_reserve(dstmap, len, start,
2699		    atop(start) & uvmexp.colormask, &dstaddr,
2700		    UVM_FLAG_COLORMATCH))
2701			return (ENOMEM);
2702		KASSERT((atop(start ^ dstaddr) & uvmexp.colormask) == 0);
2703		*dstaddrp = dstaddr;	/* pass address back to caller */
2704		UVMHIST_LOG(maphist, "  dstaddr=%#jx", dstaddr,0,0,0);
2705	} else {
2706		dstaddr = *dstaddrp;
2707	}
2708
2709	/*
2710	 * step 2: setup for the extraction process loop by init'ing the
2711	 * map entry chain, locking src map, and looking up the first useful
2712	 * entry in the map.
2713	 */
2714
2715	end = start + len;
2716	newend = dstaddr + len;
2717	chain = endchain = NULL;
2718	nchain = 0;
2719	nsize = 0;
2720	vm_map_lock(srcmap);
2721
2722	if (uvm_map_lookup_entry(srcmap, start, &entry)) {
2723
2724		/* "start" is within an entry */
2725		if (flags & UVM_EXTRACT_QREF) {
2726
2727			/*
2728			 * for quick references we don't clip the entry, so
2729			 * the entry may map space "before" the starting
2730			 * virtual address... this is the "fudge" factor
2731			 * (which can be non-zero only the first time
2732			 * through the "while" loop in step 3).
2733			 */
2734
2735			fudge = start - entry->start;
2736		} else {
2737
2738			/*
2739			 * normal reference: we clip the map to fit (thus
2740			 * fudge is zero)
2741			 */
2742
2743			UVM_MAP_CLIP_START(srcmap, entry, start);
2744			SAVE_HINT(srcmap, srcmap->hint, entry->prev);
2745			fudge = 0;
2746		}
2747	} else {
2748
2749		/* "start" is not within an entry ... skip to next entry */
2750		if (flags & UVM_EXTRACT_CONTIG) {
2751			error = EINVAL;
2752			goto bad;    /* definite hole here ... */
2753		}
2754
2755		entry = entry->next;
2756		fudge = 0;
2757	}
2758
2759	/* save values from srcmap for step 6 */
2760	orig_entry = entry;
2761	orig_fudge = fudge;
2762
2763	/*
2764	 * step 3: now start looping through the map entries, extracting
2765	 * as we go.
2766	 */
2767
2768	while (entry->start < end && entry != &srcmap->header) {
2769
2770		/* if we are not doing a quick reference, clip it */
2771		if ((flags & UVM_EXTRACT_QREF) == 0)
2772			UVM_MAP_CLIP_END(srcmap, entry, end);
2773
2774		/* clear needs_copy (allow chunking) */
2775		if (UVM_ET_ISNEEDSCOPY(entry)) {
2776			amap_copy(srcmap, entry,
2777			    AMAP_COPY_NOWAIT|AMAP_COPY_NOMERGE, start, end);
2778			if (UVM_ET_ISNEEDSCOPY(entry)) {  /* failed? */
2779				error = ENOMEM;
2780				goto bad;
2781			}
2782
2783			/* amap_copy could clip (during chunk)!  update fudge */
2784			if (fudge) {
2785				fudge = start - entry->start;
2786				orig_fudge = fudge;
2787			}
2788		}
2789
2790		/* calculate the offset of this from "start" */
2791		oldoffset = (entry->start + fudge) - start;
2792
2793		/* allocate a new map entry */
2794		newentry = uvm_mapent_alloc(dstmap, 0);
2795		if (newentry == NULL) {
2796			error = ENOMEM;
2797			goto bad;
2798		}
2799
2800		/* set up new map entry */
2801		newentry->next = NULL;
2802		newentry->prev = endchain;
2803		newentry->start = dstaddr + oldoffset;
2804		newentry->end =
2805		    newentry->start + (entry->end - (entry->start + fudge));
2806		if (newentry->end > newend || newentry->end < newentry->start)
2807			newentry->end = newend;
2808		newentry->object.uvm_obj = entry->object.uvm_obj;
2809		if (newentry->object.uvm_obj) {
2810			if (newentry->object.uvm_obj->pgops->pgo_reference)
2811				newentry->object.uvm_obj->pgops->
2812				    pgo_reference(newentry->object.uvm_obj);
2813			newentry->offset = entry->offset + fudge;
2814		} else {
2815			newentry->offset = 0;
2816		}
2817		newentry->etype = entry->etype;
2818		if (flags & UVM_EXTRACT_PROT_ALL) {
2819			newentry->protection = newentry->max_protection =
2820			    UVM_PROT_ALL;
2821		} else {
2822			newentry->protection = (flags & UVM_EXTRACT_FIXPROT) ?
2823			    entry->max_protection : entry->protection;
2824			newentry->max_protection = entry->max_protection;
2825		}
2826		newentry->inheritance = entry->inheritance;
2827		newentry->wired_count = 0;
2828		newentry->aref.ar_amap = entry->aref.ar_amap;
2829		if (newentry->aref.ar_amap) {
2830			newentry->aref.ar_pageoff =
2831			    entry->aref.ar_pageoff + (fudge >> PAGE_SHIFT);
2832			uvm_map_reference_amap(newentry, AMAP_SHARED |
2833			    ((flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0));
2834		} else {
2835			newentry->aref.ar_pageoff = 0;
2836		}
2837		newentry->advice = entry->advice;
2838		if ((flags & UVM_EXTRACT_QREF) != 0) {
2839			newentry->flags |= UVM_MAP_NOMERGE;
2840		}
2841
2842		/* now link it on the chain */
2843		nchain++;
2844		nsize += newentry->end - newentry->start;
2845		if (endchain == NULL) {
2846			chain = endchain = newentry;
2847		} else {
2848			endchain->next = newentry;
2849			endchain = newentry;
2850		}
2851
2852		/* end of 'while' loop! */
2853		if ((flags & UVM_EXTRACT_CONTIG) && entry->end < end &&
2854		    (entry->next == &srcmap->header ||
2855		    entry->next->start != entry->end)) {
2856			error = EINVAL;
2857			goto bad;
2858		}
2859		entry = entry->next;
2860		fudge = 0;
2861	}
2862
2863	/*
2864	 * step 4: close off chain (in format expected by uvm_map_replace)
2865	 */
2866
2867	if (chain)
2868		chain->prev = endchain;
2869
2870	/*
2871	 * step 5: attempt to lock the dest map so we can pmap_copy.
2872	 * note usage of copy_ok:
2873	 *   1 => dstmap locked, pmap_copy ok, and we "replace" here (step 5)
2874	 *   0 => dstmap unlocked, NO pmap_copy, and we will "replace" in step 7
2875	 */
2876
2877	if (srcmap == dstmap || vm_map_lock_try(dstmap) == true) {
2878		copy_ok = 1;
2879		if (!uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
2880		    nchain, nsize, &resentry)) {
2881			if (srcmap != dstmap)
2882				vm_map_unlock(dstmap);
2883			error = EIO;
2884			goto bad;
2885		}
2886	} else {
2887		copy_ok = 0;
2888		/* replace deferred until step 7 */
2889	}
2890
2891	/*
2892	 * step 6: traverse the srcmap a second time to do the following:
2893	 *  - if we got a lock on the dstmap do pmap_copy
2894	 *  - if UVM_EXTRACT_REMOVE remove the entries
2895	 * we make use of orig_entry and orig_fudge (saved in step 2)
2896	 */
2897
2898	if (copy_ok || (flags & UVM_EXTRACT_REMOVE)) {
2899
2900		/* purge possible stale hints from srcmap */
2901		if (flags & UVM_EXTRACT_REMOVE) {
2902			SAVE_HINT(srcmap, srcmap->hint, orig_entry->prev);
2903			if (srcmap->first_free != &srcmap->header &&
2904			    srcmap->first_free->start >= start)
2905				srcmap->first_free = orig_entry->prev;
2906		}
2907
2908		entry = orig_entry;
2909		fudge = orig_fudge;
2910		deadentry = NULL;	/* for UVM_EXTRACT_REMOVE */
2911
2912		while (entry->start < end && entry != &srcmap->header) {
2913			if (copy_ok) {
2914				oldoffset = (entry->start + fudge) - start;
2915				elen = MIN(end, entry->end) -
2916				    (entry->start + fudge);
2917				pmap_copy(dstmap->pmap, srcmap->pmap,
2918				    dstaddr + oldoffset, elen,
2919				    entry->start + fudge);
2920			}
2921
2922			/* we advance "entry" in the following if statement */
2923			if (flags & UVM_EXTRACT_REMOVE) {
2924#ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
2925				uvm_map_lock_entry(entry, RW_WRITER);
2926#else
2927				uvm_map_lock_entry(entry, RW_READER);
2928#endif
2929				pmap_remove(srcmap->pmap, entry->start,
2930						entry->end);
2931				uvm_map_unlock_entry(entry);
2932				oldentry = entry;	/* save entry */
2933				entry = entry->next;	/* advance */
2934				uvm_map_entry_unlink(srcmap, oldentry);
2935							/* add to dead list */
2936				oldentry->next = deadentry;
2937				deadentry = oldentry;
2938			} else {
2939				entry = entry->next;		/* advance */
2940			}
2941
2942			/* end of 'while' loop */
2943			fudge = 0;
2944		}
2945		pmap_update(srcmap->pmap);
2946
2947		/*
2948		 * unlock dstmap.  we will dispose of deadentry in
2949		 * step 7 if needed
2950		 */
2951
2952		if (copy_ok && srcmap != dstmap)
2953			vm_map_unlock(dstmap);
2954
2955	} else {
2956		deadentry = NULL;
2957	}
2958
2959	/*
2960	 * step 7: we are done with the source map, unlock.   if copy_ok
2961	 * is 0 then we have not replaced the dummy mapping in dstmap yet
2962	 * and we need to do so now.
2963	 */
2964
2965	vm_map_unlock(srcmap);
2966	if ((flags & UVM_EXTRACT_REMOVE) && deadentry)
2967		uvm_unmap_detach(deadentry, 0);   /* dispose of old entries */
2968
2969	/* now do the replacement if we didn't do it in step 5 */
2970	if (copy_ok == 0) {
2971		vm_map_lock(dstmap);
2972		error = uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
2973		    nchain, nsize, &resentry);
2974		vm_map_unlock(dstmap);
2975
2976		if (error == false) {
2977			error = EIO;
2978			goto bad2;
2979		}
2980	}
2981
2982	if (resentry != NULL)
2983		uvm_mapent_free(resentry);
2984
2985	return (0);
2986
2987	/*
2988	 * bad: failure recovery
2989	 */
2990bad:
2991	vm_map_unlock(srcmap);
2992bad2:			/* src already unlocked */
2993	if (chain)
2994		uvm_unmap_detach(chain,
2995		    (flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0);
2996
2997	if (resentry != NULL)
2998		uvm_mapent_free(resentry);
2999
3000	if ((flags & UVM_EXTRACT_RESERVED) == 0) {
3001		uvm_unmap(dstmap, dstaddr, dstaddr+len);   /* ??? */
3002	}
3003	return (error);
3004}
3005
3006/* end of extraction functions */
3007
3008/*
3009 * uvm_map_submap: punch down part of a map into a submap
3010 *
3011 * => only the kernel_map is allowed to be submapped
3012 * => the purpose of submapping is to break up the locking granularity
3013 *	of a larger map
3014 * => the range specified must have been mapped previously with a uvm_map()
3015 *	call [with uobj==NULL] to create a blank map entry in the main map.
3016 *	[And it had better still be blank!]
3017 * => maps which contain submaps should never be copied or forked.
3018 * => to remove a submap, use uvm_unmap() on the main map
3019 *	and then uvm_map_deallocate() the submap.
3020 * => main map must be unlocked.
3021 * => submap must have been init'd and have a zero reference count.
3022 *	[need not be locked as we don't actually reference it]
3023 */
3024
3025int
3026uvm_map_submap(struct vm_map *map, vaddr_t start, vaddr_t end,
3027    struct vm_map *submap)
3028{
3029	struct vm_map_entry *entry;
3030	int error;
3031
3032	vm_map_lock(map);
3033	VM_MAP_RANGE_CHECK(map, start, end);
3034
3035	if (uvm_map_lookup_entry(map, start, &entry)) {
3036		UVM_MAP_CLIP_START(map, entry, start);
3037		UVM_MAP_CLIP_END(map, entry, end);	/* to be safe */
3038	} else {
3039		entry = NULL;
3040	}
3041
3042	if (entry != NULL &&
3043	    entry->start == start && entry->end == end &&
3044	    entry->object.uvm_obj == NULL && entry->aref.ar_amap == NULL &&
3045	    !UVM_ET_ISCOPYONWRITE(entry) && !UVM_ET_ISNEEDSCOPY(entry)) {
3046		entry->etype |= UVM_ET_SUBMAP;
3047		entry->object.sub_map = submap;
3048		entry->offset = 0;
3049		uvm_map_reference(submap);
3050		error = 0;
3051	} else {
3052		error = EINVAL;
3053	}
3054	vm_map_unlock(map);
3055
3056	return error;
3057}
3058
3059/*
3060 * uvm_map_protect_user: change map protection on behalf of the user.
3061 * Enforces PAX settings as necessary.
3062 */
3063int
3064uvm_map_protect_user(struct lwp *l, vaddr_t start, vaddr_t end,
3065    vm_prot_t new_prot)
3066{
3067	int error;
3068
3069	if ((error = PAX_MPROTECT_VALIDATE(l, new_prot)))
3070		return error;
3071
3072	return uvm_map_protect(&l->l_proc->p_vmspace->vm_map, start, end,
3073	    new_prot, false);
3074}
3075
3076
3077/*
3078 * uvm_map_protect: change map protection
3079 *
3080 * => set_max means set max_protection.
3081 * => map must be unlocked.
3082 */
3083
3084#define MASK(entry)	(UVM_ET_ISCOPYONWRITE(entry) ? \
3085			 ~VM_PROT_WRITE : VM_PROT_ALL)
3086
3087int
3088uvm_map_protect(struct vm_map *map, vaddr_t start, vaddr_t end,
3089    vm_prot_t new_prot, bool set_max)
3090{
3091	struct vm_map_entry *current, *entry;
3092	int error = 0;
3093	UVMHIST_FUNC(__func__);
3094	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_prot=%#jx)",
3095	    (uintptr_t)map, start, end, new_prot);
3096
3097	vm_map_lock(map);
3098	VM_MAP_RANGE_CHECK(map, start, end);
3099	if (uvm_map_lookup_entry(map, start, &entry)) {
3100		UVM_MAP_CLIP_START(map, entry, start);
3101	} else {
3102		entry = entry->next;
3103	}
3104
3105	/*
3106	 * make a first pass to check for protection violations.
3107	 */
3108
3109	current = entry;
3110	while ((current != &map->header) && (current->start < end)) {
3111		if (UVM_ET_ISSUBMAP(current)) {
3112			error = EINVAL;
3113			goto out;
3114		}
3115		if ((new_prot & current->max_protection) != new_prot) {
3116			error = EACCES;
3117			goto out;
3118		}
3119		/*
3120		 * Don't allow VM_PROT_EXECUTE to be set on entries that
3121		 * point to vnodes that are associated with a NOEXEC file
3122		 * system.
3123		 */
3124		if (UVM_ET_ISOBJ(current) &&
3125		    UVM_OBJ_IS_VNODE(current->object.uvm_obj)) {
3126			struct vnode *vp =
3127			    (struct vnode *) current->object.uvm_obj;
3128
3129			if ((new_prot & VM_PROT_EXECUTE) != 0 &&
3130			    (vp->v_mount->mnt_flag & MNT_NOEXEC) != 0) {
3131				error = EACCES;
3132				goto out;
3133			}
3134		}
3135
3136		current = current->next;
3137	}
3138
3139	/* go back and fix up protections (no need to clip this time). */
3140
3141	current = entry;
3142	while ((current != &map->header) && (current->start < end)) {
3143		vm_prot_t old_prot;
3144
3145		UVM_MAP_CLIP_END(map, current, end);
3146		old_prot = current->protection;
3147		if (set_max)
3148			current->protection =
3149			    (current->max_protection = new_prot) & old_prot;
3150		else
3151			current->protection = new_prot;
3152
3153		/*
3154		 * update physical map if necessary.  worry about copy-on-write
3155		 * here -- CHECK THIS XXX
3156		 */
3157
3158		if (current->protection != old_prot) {
3159			/* update pmap! */
3160#ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
3161			uvm_map_lock_entry(current, RW_WRITER);
3162#else
3163			uvm_map_lock_entry(current, RW_READER);
3164#endif
3165			pmap_protect(map->pmap, current->start, current->end,
3166			    current->protection & MASK(current));
3167			uvm_map_unlock_entry(current);
3168
3169			/*
3170			 * If this entry points at a vnode, and the
3171			 * protection includes VM_PROT_EXECUTE, mark
3172			 * the vnode as VEXECMAP.
3173			 */
3174			if (UVM_ET_ISOBJ(current)) {
3175				struct uvm_object *uobj =
3176				    current->object.uvm_obj;
3177
3178				if (UVM_OBJ_IS_VNODE(uobj) &&
3179				    (current->protection & VM_PROT_EXECUTE)) {
3180					vn_markexec((struct vnode *) uobj);
3181				}
3182			}
3183		}
3184
3185		/*
3186		 * If the map is configured to lock any future mappings,
3187		 * wire this entry now if the old protection was VM_PROT_NONE
3188		 * and the new protection is not VM_PROT_NONE.
3189		 */
3190
3191		if ((map->flags & VM_MAP_WIREFUTURE) != 0 &&
3192		    VM_MAPENT_ISWIRED(current) == 0 &&
3193		    old_prot == VM_PROT_NONE &&
3194		    new_prot != VM_PROT_NONE) {
3195
3196			/*
3197			 * We must call pmap_update() here because the
3198			 * pmap_protect() call above might have removed some
3199			 * pmap entries and uvm_map_pageable() might create
3200			 * some new pmap entries that rely on the prior
3201			 * removals being completely finished.
3202			 */
3203
3204			pmap_update(map->pmap);
3205
3206			if (uvm_map_pageable(map, current->start,
3207			    current->end, false,
3208			    UVM_LK_ENTER|UVM_LK_EXIT) != 0) {
3209
3210				/*
3211				 * If locking the entry fails, remember the
3212				 * error if it's the first one.  Note we
3213				 * still continue setting the protection in
3214				 * the map, but will return the error
3215				 * condition regardless.
3216				 *
3217				 * XXX Ignore what the actual error is,
3218				 * XXX just call it a resource shortage
3219				 * XXX so that it doesn't get confused
3220				 * XXX what uvm_map_protect() itself would
3221				 * XXX normally return.
3222				 */
3223
3224				error = ENOMEM;
3225			}
3226		}
3227		current = current->next;
3228	}
3229	pmap_update(map->pmap);
3230
3231 out:
3232	vm_map_unlock(map);
3233
3234	UVMHIST_LOG(maphist, "<- done, error=%jd",error,0,0,0);
3235	return error;
3236}
3237
3238#undef  MASK
3239
3240/*
3241 * uvm_map_inherit: set inheritance code for range of addrs in map.
3242 *
3243 * => map must be unlocked
3244 * => note that the inherit code is used during a "fork".  see fork
3245 *	code for details.
3246 */
3247
3248int
3249uvm_map_inherit(struct vm_map *map, vaddr_t start, vaddr_t end,
3250    vm_inherit_t new_inheritance)
3251{
3252	struct vm_map_entry *entry, *temp_entry;
3253	UVMHIST_FUNC(__func__);
3254	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_inh=%#jx)",
3255	    (uintptr_t)map, start, end, new_inheritance);
3256
3257	switch (new_inheritance) {
3258	case MAP_INHERIT_NONE:
3259	case MAP_INHERIT_COPY:
3260	case MAP_INHERIT_SHARE:
3261	case MAP_INHERIT_ZERO:
3262		break;
3263	default:
3264		UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
3265		return EINVAL;
3266	}
3267
3268	vm_map_lock(map);
3269	VM_MAP_RANGE_CHECK(map, start, end);
3270	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
3271		entry = temp_entry;
3272		UVM_MAP_CLIP_START(map, entry, start);
3273	}  else {
3274		entry = temp_entry->next;
3275	}
3276	while ((entry != &map->header) && (entry->start < end)) {
3277		UVM_MAP_CLIP_END(map, entry, end);
3278		entry->inheritance = new_inheritance;
3279		entry = entry->next;
3280	}
3281	vm_map_unlock(map);
3282	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
3283	return 0;
3284}
3285
3286/*
3287 * uvm_map_advice: set advice code for range of addrs in map.
3288 *
3289 * => map must be unlocked
3290 */
3291
3292int
3293uvm_map_advice(struct vm_map *map, vaddr_t start, vaddr_t end, int new_advice)
3294{
3295	struct vm_map_entry *entry, *temp_entry;
3296	UVMHIST_FUNC(__func__);
3297	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_adv=%#jx)",
3298	    (uintptr_t)map, start, end, new_advice);
3299
3300	vm_map_lock(map);
3301	VM_MAP_RANGE_CHECK(map, start, end);
3302	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
3303		entry = temp_entry;
3304		UVM_MAP_CLIP_START(map, entry, start);
3305	} else {
3306		entry = temp_entry->next;
3307	}
3308
3309	/*
3310	 * XXXJRT: disallow holes?
3311	 */
3312
3313	while ((entry != &map->header) && (entry->start < end)) {
3314		UVM_MAP_CLIP_END(map, entry, end);
3315
3316		switch (new_advice) {
3317		case MADV_NORMAL:
3318		case MADV_RANDOM:
3319		case MADV_SEQUENTIAL:
3320			/* nothing special here */
3321			break;
3322
3323		default:
3324			vm_map_unlock(map);
3325			UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
3326			return EINVAL;
3327		}
3328		entry->advice = new_advice;
3329		entry = entry->next;
3330	}
3331
3332	vm_map_unlock(map);
3333	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
3334	return 0;
3335}
3336
3337/*
3338 * uvm_map_willneed: apply MADV_WILLNEED
3339 */
3340
3341int
3342uvm_map_willneed(struct vm_map *map, vaddr_t start, vaddr_t end)
3343{
3344	struct vm_map_entry *entry;
3345	UVMHIST_FUNC(__func__);
3346	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx)",
3347	    (uintptr_t)map, start, end, 0);
3348
3349	vm_map_lock_read(map);
3350	VM_MAP_RANGE_CHECK(map, start, end);
3351	if (!uvm_map_lookup_entry(map, start, &entry)) {
3352		entry = entry->next;
3353	}
3354	while (entry->start < end) {
3355		struct vm_amap * const amap = entry->aref.ar_amap;
3356		struct uvm_object * const uobj = entry->object.uvm_obj;
3357
3358		KASSERT(entry != &map->header);
3359		KASSERT(start < entry->end);
3360		/*
3361		 * For now, we handle only the easy but commonly-requested case.
3362		 * ie. start prefetching of backing uobj pages.
3363		 *
3364		 * XXX It might be useful to pmap_enter() the already-in-core
3365		 * pages by inventing a "weak" mode for uvm_fault() which would
3366		 * only do the PGO_LOCKED pgo_get().
3367		 */
3368		if (UVM_ET_ISOBJ(entry) && amap == NULL && uobj != NULL) {
3369			off_t offset;
3370			off_t size;
3371
3372			offset = entry->offset;
3373			if (start < entry->start) {
3374				offset += entry->start - start;
3375			}
3376			size = entry->offset + (entry->end - entry->start);
3377			if (entry->end < end) {
3378				size -= end - entry->end;
3379			}
3380			uvm_readahead(uobj, offset, size);
3381		}
3382		entry = entry->next;
3383	}
3384	vm_map_unlock_read(map);
3385	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
3386	return 0;
3387}
3388
3389/*
3390 * uvm_map_pageable: sets the pageability of a range in a map.
3391 *
3392 * => wires map entries.  should not be used for transient page locking.
3393 *	for that, use uvm_fault_wire()/uvm_fault_unwire() (see uvm_vslock()).
3394 * => regions specified as not pageable require lock-down (wired) memory
3395 *	and page tables.
3396 * => map must never be read-locked
3397 * => if islocked is true, map is already write-locked
3398 * => we always unlock the map, since we must downgrade to a read-lock
3399 *	to call uvm_fault_wire()
3400 * => XXXCDC: check this and try and clean it up.
3401 */
3402
3403int
3404uvm_map_pageable(struct vm_map *map, vaddr_t start, vaddr_t end,
3405    bool new_pageable, int lockflags)
3406{
3407	struct vm_map_entry *entry, *start_entry, *failed_entry;
3408	int rv;
3409#ifdef DIAGNOSTIC
3410	u_int timestamp_save;
3411#endif
3412	UVMHIST_FUNC(__func__);
3413	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_pageable=%ju)",
3414	    (uintptr_t)map, start, end, new_pageable);
3415	KASSERT(map->flags & VM_MAP_PAGEABLE);
3416
3417	if ((lockflags & UVM_LK_ENTER) == 0)
3418		vm_map_lock(map);
3419	VM_MAP_RANGE_CHECK(map, start, end);
3420
3421	/*
3422	 * only one pageability change may take place at one time, since
3423	 * uvm_fault_wire assumes it will be called only once for each
3424	 * wiring/unwiring.  therefore, we have to make sure we're actually
3425	 * changing the pageability for the entire region.  we do so before
3426	 * making any changes.
3427	 */
3428
3429	if (uvm_map_lookup_entry(map, start, &start_entry) == false) {
3430		if ((lockflags & UVM_LK_EXIT) == 0)
3431			vm_map_unlock(map);
3432
3433		UVMHIST_LOG(maphist,"<- done (fault)",0,0,0,0);
3434		return EFAULT;
3435	}
3436	entry = start_entry;
3437
3438	if (start == end) {		/* nothing required */
3439		if ((lockflags & UVM_LK_EXIT) == 0)
3440			vm_map_unlock(map);
3441
3442		UVMHIST_LOG(maphist,"<- done (nothing)",0,0,0,0);
3443		return 0;
3444	}
3445
3446	/*
3447	 * handle wiring and unwiring separately.
3448	 */
3449
3450	if (new_pageable) {		/* unwire */
3451		UVM_MAP_CLIP_START(map, entry, start);
3452
3453		/*
3454		 * unwiring.  first ensure that the range to be unwired is
3455		 * really wired down and that there are no holes.
3456		 */
3457
3458		while ((entry != &map->header) && (entry->start < end)) {
3459			if (entry->wired_count == 0 ||
3460			    (entry->end < end &&
3461			     (entry->next == &map->header ||
3462			      entry->next->start > entry->end))) {
3463				if ((lockflags & UVM_LK_EXIT) == 0)
3464					vm_map_unlock(map);
3465				UVMHIST_LOG(maphist, "<- done (INVAL)",0,0,0,0);
3466				return EINVAL;
3467			}
3468			entry = entry->next;
3469		}
3470
3471		/*
3472		 * POSIX 1003.1b - a single munlock call unlocks a region,
3473		 * regardless of the number of mlock calls made on that
3474		 * region.
3475		 */
3476
3477		entry = start_entry;
3478		while ((entry != &map->header) && (entry->start < end)) {
3479			UVM_MAP_CLIP_END(map, entry, end);
3480			if (VM_MAPENT_ISWIRED(entry))
3481				uvm_map_entry_unwire(map, entry);
3482			entry = entry->next;
3483		}
3484		if ((lockflags & UVM_LK_EXIT) == 0)
3485			vm_map_unlock(map);
3486		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
3487		return 0;
3488	}
3489
3490	/*
3491	 * wire case: in two passes [XXXCDC: ugly block of code here]
3492	 *
3493	 * 1: holding the write lock, we create any anonymous maps that need
3494	 *    to be created.  then we clip each map entry to the region to
3495	 *    be wired and increment its wiring count.
3496	 *
3497	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
3498	 *    in the pages for any newly wired area (wired_count == 1).
3499	 *
3500	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
3501	 *    deadlock with another thread that may have faulted on one of
3502	 *    the pages to be wired (it would mark the page busy, blocking
3503	 *    us, then in turn block on the map lock that we hold).  because
3504	 *    of problems in the recursive lock package, we cannot upgrade
3505	 *    to a write lock in vm_map_lookup.  thus, any actions that
3506	 *    require the write lock must be done beforehand.  because we
3507	 *    keep the read lock on the map, the copy-on-write status of the
3508	 *    entries we modify here cannot change.
3509	 */
3510
3511	while ((entry != &map->header) && (entry->start < end)) {
3512		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
3513
3514			/*
3515			 * perform actions of vm_map_lookup that need the
3516			 * write lock on the map: create an anonymous map
3517			 * for a copy-on-write region, or an anonymous map
3518			 * for a zero-fill region.  (XXXCDC: submap case
3519			 * ok?)
3520			 */
3521
3522			if (!UVM_ET_ISSUBMAP(entry)) {  /* not submap */
3523				if (UVM_ET_ISNEEDSCOPY(entry) &&
3524				    ((entry->max_protection & VM_PROT_WRITE) ||
3525				     (entry->object.uvm_obj == NULL))) {
3526					amap_copy(map, entry, 0, start, end);
3527					/* XXXCDC: wait OK? */
3528				}
3529			}
3530		}
3531		UVM_MAP_CLIP_START(map, entry, start);
3532		UVM_MAP_CLIP_END(map, entry, end);
3533		entry->wired_count++;
3534
3535		/*
3536		 * Check for holes
3537		 */
3538
3539		if (entry->protection == VM_PROT_NONE ||
3540		    (entry->end < end &&
3541		     (entry->next == &map->header ||
3542		      entry->next->start > entry->end))) {
3543
3544			/*
3545			 * found one.  amap creation actions do not need to
3546			 * be undone, but the wired counts need to be restored.
3547			 */
3548
3549			while (entry != &map->header && entry->end > start) {
3550				entry->wired_count--;
3551				entry = entry->prev;
3552			}
3553			if ((lockflags & UVM_LK_EXIT) == 0)
3554				vm_map_unlock(map);
3555			UVMHIST_LOG(maphist,"<- done (INVALID WIRE)",0,0,0,0);
3556			return EINVAL;
3557		}
3558		entry = entry->next;
3559	}
3560
3561	/*
3562	 * Pass 2.
3563	 */
3564
3565#ifdef DIAGNOSTIC
3566	timestamp_save = map->timestamp;
3567#endif
3568	vm_map_busy(map);
3569	vm_map_unlock(map);
3570
3571	rv = 0;
3572	entry = start_entry;
3573	while (entry != &map->header && entry->start < end) {
3574		if (entry->wired_count == 1) {
3575			rv = uvm_fault_wire(map, entry->start, entry->end,
3576			    entry->max_protection, 1);
3577			if (rv) {
3578
3579				/*
3580				 * wiring failed.  break out of the loop.
3581				 * we'll clean up the map below, once we
3582				 * have a write lock again.
3583				 */
3584
3585				break;
3586			}
3587		}
3588		entry = entry->next;
3589	}
3590
3591	if (rv) {	/* failed? */
3592
3593		/*
3594		 * Get back to an exclusive (write) lock.
3595		 */
3596
3597		vm_map_lock(map);
3598		vm_map_unbusy(map);
3599
3600#ifdef DIAGNOSTIC
3601		if (timestamp_save + 1 != map->timestamp)
3602			panic("uvm_map_pageable: stale map");
3603#endif
3604
3605		/*
3606		 * first drop the wiring count on all the entries
3607		 * which haven't actually been wired yet.
3608		 */
3609
3610		failed_entry = entry;
3611		while (entry != &map->header && entry->start < end) {
3612			entry->wired_count--;
3613			entry = entry->next;
3614		}
3615
3616		/*
3617		 * now, unwire all the entries that were successfully
3618		 * wired above.
3619		 */
3620
3621		entry = start_entry;
3622		while (entry != failed_entry) {
3623			entry->wired_count--;
3624			if (VM_MAPENT_ISWIRED(entry) == 0)
3625				uvm_map_entry_unwire(map, entry);
3626			entry = entry->next;
3627		}
3628		if ((lockflags & UVM_LK_EXIT) == 0)
3629			vm_map_unlock(map);
3630		UVMHIST_LOG(maphist, "<- done (RV=%jd)", rv,0,0,0);
3631		return (rv);
3632	}
3633
3634	if ((lockflags & UVM_LK_EXIT) == 0) {
3635		vm_map_unbusy(map);
3636	} else {
3637
3638		/*
3639		 * Get back to an exclusive (write) lock.
3640		 */
3641
3642		vm_map_lock(map);
3643		vm_map_unbusy(map);
3644	}
3645
3646	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
3647	return 0;
3648}
3649
3650/*
3651 * uvm_map_pageable_all: special case of uvm_map_pageable - affects
3652 * all mapped regions.
3653 *
3654 * => map must not be locked.
3655 * => if no flags are specified, all regions are unwired.
3656 * => XXXJRT: has some of the same problems as uvm_map_pageable() above.
3657 */
3658
3659int
3660uvm_map_pageable_all(struct vm_map *map, int flags, vsize_t limit)
3661{
3662	struct vm_map_entry *entry, *failed_entry;
3663	vsize_t size;
3664	int rv;
3665#ifdef DIAGNOSTIC
3666	u_int timestamp_save;
3667#endif
3668	UVMHIST_FUNC(__func__);
3669	UVMHIST_CALLARGS(maphist,"(map=%#jx,flags=%#jx)", (uintptr_t)map, flags,
3670	    0, 0);
3671
3672	KASSERT(map->flags & VM_MAP_PAGEABLE);
3673
3674	vm_map_lock(map);
3675
3676	/*
3677	 * handle wiring and unwiring separately.
3678	 */
3679
3680	if (flags == 0) {			/* unwire */
3681
3682		/*
3683		 * POSIX 1003.1b -- munlockall unlocks all regions,
3684		 * regardless of how many times mlockall has been called.
3685		 */
3686
3687		for (entry = map->header.next; entry != &map->header;
3688		     entry = entry->next) {
3689			if (VM_MAPENT_ISWIRED(entry))
3690				uvm_map_entry_unwire(map, entry);
3691		}
3692		map->flags &= ~VM_MAP_WIREFUTURE;
3693		vm_map_unlock(map);
3694		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
3695		return 0;
3696	}
3697
3698	if (flags & MCL_FUTURE) {
3699
3700		/*
3701		 * must wire all future mappings; remember this.
3702		 */
3703
3704		map->flags |= VM_MAP_WIREFUTURE;
3705	}
3706
3707	if ((flags & MCL_CURRENT) == 0) {
3708
3709		/*
3710		 * no more work to do!
3711		 */
3712
3713		UVMHIST_LOG(maphist,"<- done (OK no wire)",0,0,0,0);
3714		vm_map_unlock(map);
3715		return 0;
3716	}
3717
3718	/*
3719	 * wire case: in three passes [XXXCDC: ugly block of code here]
3720	 *
3721	 * 1: holding the write lock, count all pages mapped by non-wired
3722	 *    entries.  if this would cause us to go over our limit, we fail.
3723	 *
3724	 * 2: still holding the write lock, we create any anonymous maps that
3725	 *    need to be created.  then we increment its wiring count.
3726	 *
3727	 * 3: we downgrade to a read lock, and call uvm_fault_wire to fault
3728	 *    in the pages for any newly wired area (wired_count == 1).
3729	 *
3730	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
3731	 *    deadlock with another thread that may have faulted on one of
3732	 *    the pages to be wired (it would mark the page busy, blocking
3733	 *    us, then in turn block on the map lock that we hold).  because
3734	 *    of problems in the recursive lock package, we cannot upgrade
3735	 *    to a write lock in vm_map_lookup.  thus, any actions that
3736	 *    require the write lock must be done beforehand.  because we
3737	 *    keep the read lock on the map, the copy-on-write status of the
3738	 *    entries we modify here cannot change.
3739	 */
3740
3741	for (size = 0, entry = map->header.next; entry != &map->header;
3742	     entry = entry->next) {
3743		if (entry->protection != VM_PROT_NONE &&
3744		    VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
3745			size += entry->end - entry->start;
3746		}
3747	}
3748
3749	if (atop(size) + uvmexp.wired > uvmexp.wiredmax) {
3750		vm_map_unlock(map);
3751		return ENOMEM;
3752	}
3753
3754	if (limit != 0 &&
3755	    (size + ptoa(pmap_wired_count(vm_map_pmap(map))) > limit)) {
3756		vm_map_unlock(map);
3757		return ENOMEM;
3758	}
3759
3760	/*
3761	 * Pass 2.
3762	 */
3763
3764	for (entry = map->header.next; entry != &map->header;
3765	     entry = entry->next) {
3766		if (entry->protection == VM_PROT_NONE)
3767			continue;
3768		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
3769
3770			/*
3771			 * perform actions of vm_map_lookup that need the
3772			 * write lock on the map: create an anonymous map
3773			 * for a copy-on-write region, or an anonymous map
3774			 * for a zero-fill region.  (XXXCDC: submap case
3775			 * ok?)
3776			 */
3777
3778			if (!UVM_ET_ISSUBMAP(entry)) {	/* not submap */
3779				if (UVM_ET_ISNEEDSCOPY(entry) &&
3780				    ((entry->max_protection & VM_PROT_WRITE) ||
3781				     (entry->object.uvm_obj == NULL))) {
3782					amap_copy(map, entry, 0, entry->start,
3783					    entry->end);
3784					/* XXXCDC: wait OK? */
3785				}
3786			}
3787		}
3788		entry->wired_count++;
3789	}
3790
3791	/*
3792	 * Pass 3.
3793	 */
3794
3795#ifdef DIAGNOSTIC
3796	timestamp_save = map->timestamp;
3797#endif
3798	vm_map_busy(map);
3799	vm_map_unlock(map);
3800
3801	rv = 0;
3802	for (entry = map->header.next; entry != &map->header;
3803	     entry = entry->next) {
3804		if (entry->wired_count == 1) {
3805			rv = uvm_fault_wire(map, entry->start, entry->end,
3806			    entry->max_protection, 1);
3807			if (rv) {
3808
3809				/*
3810				 * wiring failed.  break out of the loop.
3811				 * we'll clean up the map below, once we
3812				 * have a write lock again.
3813				 */
3814
3815				break;
3816			}
3817		}
3818	}
3819
3820	if (rv) {
3821
3822		/*
3823		 * Get back an exclusive (write) lock.
3824		 */
3825
3826		vm_map_lock(map);
3827		vm_map_unbusy(map);
3828
3829#ifdef DIAGNOSTIC
3830		if (timestamp_save + 1 != map->timestamp)
3831			panic("uvm_map_pageable_all: stale map");
3832#endif
3833
3834		/*
3835		 * first drop the wiring count on all the entries
3836		 * which haven't actually been wired yet.
3837		 *
3838		 * Skip VM_PROT_NONE entries like we did above.
3839		 */
3840
3841		failed_entry = entry;
3842		for (/* nothing */; entry != &map->header;
3843		     entry = entry->next) {
3844			if (entry->protection == VM_PROT_NONE)
3845				continue;
3846			entry->wired_count--;
3847		}
3848
3849		/*
3850		 * now, unwire all the entries that were successfully
3851		 * wired above.
3852		 *
3853		 * Skip VM_PROT_NONE entries like we did above.
3854		 */
3855
3856		for (entry = map->header.next; entry != failed_entry;
3857		     entry = entry->next) {
3858			if (entry->protection == VM_PROT_NONE)
3859				continue;
3860			entry->wired_count--;
3861			if (VM_MAPENT_ISWIRED(entry))
3862				uvm_map_entry_unwire(map, entry);
3863		}
3864		vm_map_unlock(map);
3865		UVMHIST_LOG(maphist,"<- done (RV=%jd)", rv,0,0,0);
3866		return (rv);
3867	}
3868
3869	vm_map_unbusy(map);
3870
3871	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
3872	return 0;
3873}
3874
3875/*
3876 * uvm_map_clean: clean out a map range
3877 *
3878 * => valid flags:
3879 *   if (flags & PGO_CLEANIT): dirty pages are cleaned first
3880 *   if (flags & PGO_SYNCIO): dirty pages are written synchronously
3881 *   if (flags & PGO_DEACTIVATE): any cached pages are deactivated after clean
3882 *   if (flags & PGO_FREE): any cached pages are freed after clean
3883 * => returns an error if any part of the specified range isn't mapped
3884 * => never a need to flush amap layer since the anonymous memory has
3885 *	no permanent home, but may deactivate pages there
3886 * => called from sys_msync() and sys_madvise()
3887 * => caller must not have map locked
3888 */
3889
3890int
3891uvm_map_clean(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
3892{
3893	struct vm_map_entry *current, *entry;
3894	struct uvm_object *uobj;
3895	struct vm_amap *amap;
3896	struct vm_anon *anon;
3897	struct vm_page *pg;
3898	vaddr_t offset;
3899	vsize_t size;
3900	voff_t uoff;
3901	int error, refs;
3902	UVMHIST_FUNC(__func__);
3903	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,flags=%#jx)",
3904	    (uintptr_t)map, start, end, flags);
3905
3906	KASSERT((flags & (PGO_FREE|PGO_DEACTIVATE)) !=
3907		(PGO_FREE|PGO_DEACTIVATE));
3908
3909	vm_map_lock(map);
3910	VM_MAP_RANGE_CHECK(map, start, end);
3911	if (!uvm_map_lookup_entry(map, start, &entry)) {
3912		vm_map_unlock(map);
3913		return EFAULT;
3914	}
3915
3916	/*
3917	 * Make a first pass to check for holes and wiring problems.
3918	 */
3919
3920	for (current = entry; current->start < end; current = current->next) {
3921		if (UVM_ET_ISSUBMAP(current)) {
3922			vm_map_unlock(map);
3923			return EINVAL;
3924		}
3925		if ((flags & PGO_FREE) != 0 && VM_MAPENT_ISWIRED(entry)) {
3926			vm_map_unlock(map);
3927			return EBUSY;
3928		}
3929		if (end <= current->end) {
3930			break;
3931		}
3932		if (current->end != current->next->start) {
3933			vm_map_unlock(map);
3934			return EFAULT;
3935		}
3936	}
3937
3938	vm_map_busy(map);
3939	vm_map_unlock(map);
3940	error = 0;
3941	for (current = entry; start < end; current = current->next) {
3942		amap = current->aref.ar_amap;	/* upper layer */
3943		uobj = current->object.uvm_obj;	/* lower layer */
3944		KASSERT(start >= current->start);
3945
3946		/*
3947		 * No amap cleaning necessary if:
3948		 *
3949		 *	(1) There's no amap.
3950		 *
3951		 *	(2) We're not deactivating or freeing pages.
3952		 */
3953
3954		if (amap == NULL || (flags & (PGO_DEACTIVATE|PGO_FREE)) == 0)
3955			goto flush_object;
3956
3957		offset = start - current->start;
3958		size = MIN(end, current->end) - start;
3959
3960		amap_lock(amap, RW_WRITER);
3961		for ( ; size != 0; size -= PAGE_SIZE, offset += PAGE_SIZE) {
3962			anon = amap_lookup(&current->aref, offset);
3963			if (anon == NULL)
3964				continue;
3965
3966			KASSERT(anon->an_lock == amap->am_lock);
3967			pg = anon->an_page;
3968			if (pg == NULL) {
3969				continue;
3970			}
3971			if (pg->flags & PG_BUSY) {
3972				continue;
3973			}
3974
3975			switch (flags & (PGO_CLEANIT|PGO_FREE|PGO_DEACTIVATE)) {
3976
3977			/*
3978			 * In these first 3 cases, we just deactivate the page.
3979			 */
3980
3981			case PGO_CLEANIT|PGO_FREE:
3982			case PGO_CLEANIT|PGO_DEACTIVATE:
3983			case PGO_DEACTIVATE:
3984 deactivate_it:
3985				/*
3986				 * skip the page if it's loaned or wired,
3987				 * since it shouldn't be on a paging queue
3988				 * at all in these cases.
3989				 */
3990
3991				if (pg->loan_count != 0 ||
3992				    pg->wire_count != 0) {
3993					continue;
3994				}
3995				KASSERT(pg->uanon == anon);
3996				uvm_pagelock(pg);
3997				uvm_pagedeactivate(pg);
3998				uvm_pageunlock(pg);
3999				continue;
4000
4001			case PGO_FREE:
4002
4003				/*
4004				 * If there are multiple references to
4005				 * the amap, just deactivate the page.
4006				 */
4007
4008				if (amap_refs(amap) > 1)
4009					goto deactivate_it;
4010
4011				/* skip the page if it's wired */
4012				if (pg->wire_count != 0) {
4013					continue;
4014				}
4015				amap_unadd(&current->aref, offset);
4016				refs = --anon->an_ref;
4017				if (refs == 0) {
4018					uvm_anfree(anon);
4019				}
4020				continue;
4021			}
4022		}
4023		amap_unlock(amap);
4024
4025 flush_object:
4026		/*
4027		 * flush pages if we've got a valid backing object.
4028		 * note that we must always clean object pages before
4029		 * freeing them since otherwise we could reveal stale
4030		 * data from files.
4031		 */
4032
4033		uoff = current->offset + (start - current->start);
4034		size = MIN(end, current->end) - start;
4035		if (uobj != NULL) {
4036			rw_enter(uobj->vmobjlock, RW_WRITER);
4037			if (uobj->pgops->pgo_put != NULL)
4038				error = (uobj->pgops->pgo_put)(uobj, uoff,
4039				    uoff + size, flags | PGO_CLEANIT);
4040			else
4041				error = 0;
4042		}
4043		start += size;
4044	}
4045	vm_map_unbusy(map);
4046	return error;
4047}
4048
4049
4050/*
4051 * uvm_map_checkprot: check protection in map
4052 *
4053 * => must allow specified protection in a fully allocated region.
4054 * => map must be read or write locked by caller.
4055 */
4056
4057bool
4058uvm_map_checkprot(struct vm_map *map, vaddr_t start, vaddr_t end,
4059    vm_prot_t protection)
4060{
4061	struct vm_map_entry *entry;
4062	struct vm_map_entry *tmp_entry;
4063
4064	if (!uvm_map_lookup_entry(map, start, &tmp_entry)) {
4065		return (false);
4066	}
4067	entry = tmp_entry;
4068	while (start < end) {
4069		if (entry == &map->header) {
4070			return (false);
4071		}
4072
4073		/*
4074		 * no holes allowed
4075		 */
4076
4077		if (start < entry->start) {
4078			return (false);
4079		}
4080
4081		/*
4082		 * check protection associated with entry
4083		 */
4084
4085		if ((entry->protection & protection) != protection) {
4086			return (false);
4087		}
4088		start = entry->end;
4089		entry = entry->next;
4090	}
4091	return (true);
4092}
4093
4094/*
4095 * uvmspace_alloc: allocate a vmspace structure.
4096 *
4097 * - structure includes vm_map and pmap
4098 * - XXX: no locking on this structure
4099 * - refcnt set to 1, rest must be init'd by caller
4100 */
4101struct vmspace *
4102uvmspace_alloc(vaddr_t vmin, vaddr_t vmax, bool topdown)
4103{
4104	struct vmspace *vm;
4105	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
4106
4107	vm = kmem_alloc(sizeof(*vm), KM_SLEEP);
4108	uvmspace_init(vm, NULL, vmin, vmax, topdown);
4109	UVMHIST_LOG(maphist,"<- done (vm=%#jx)", (uintptr_t)vm, 0, 0, 0);
4110	return (vm);
4111}
4112
4113/*
4114 * uvmspace_init: initialize a vmspace structure.
4115 *
4116 * - XXX: no locking on this structure
4117 * - refcnt set to 1, rest must be init'd by caller
4118 */
4119void
4120uvmspace_init(struct vmspace *vm, struct pmap *pmap, vaddr_t vmin,
4121    vaddr_t vmax, bool topdown)
4122{
4123	UVMHIST_FUNC(__func__);
4124	UVMHIST_CALLARGS(maphist, "(vm=%#jx, pmap=%#jx, vmin=%#jx, vmax=%#jx",
4125	    (uintptr_t)vm, (uintptr_t)pmap, vmin, vmax);
4126	UVMHIST_LOG(maphist, "   topdown=%ju)", topdown, 0, 0, 0);
4127
4128	memset(vm, 0, sizeof(*vm));
4129	uvm_map_setup(&vm->vm_map, vmin, vmax, VM_MAP_PAGEABLE
4130	    | (topdown ? VM_MAP_TOPDOWN : 0)
4131	    );
4132	if (pmap)
4133		pmap_reference(pmap);
4134	else
4135		pmap = pmap_create();
4136	vm->vm_map.pmap = pmap;
4137	vm->vm_refcnt = 1;
4138	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
4139}
4140
4141/*
4142 * uvmspace_share: share a vmspace between two processes
4143 *
4144 * - used for vfork, threads(?)
4145 */
4146
4147void
4148uvmspace_share(struct proc *p1, struct proc *p2)
4149{
4150
4151	uvmspace_addref(p1->p_vmspace);
4152	p2->p_vmspace = p1->p_vmspace;
4153}
4154
4155#if 0
4156
4157/*
4158 * uvmspace_unshare: ensure that process "p" has its own, unshared, vmspace
4159 *
4160 * - XXX: no locking on vmspace
4161 */
4162
4163void
4164uvmspace_unshare(struct lwp *l)
4165{
4166	struct proc *p = l->l_proc;
4167	struct vmspace *nvm, *ovm = p->p_vmspace;
4168
4169	if (ovm->vm_refcnt == 1)
4170		/* nothing to do: vmspace isn't shared in the first place */
4171		return;
4172
4173	/* make a new vmspace, still holding old one */
4174	nvm = uvmspace_fork(ovm);
4175
4176	kpreempt_disable();
4177	pmap_deactivate(l);		/* unbind old vmspace */
4178	p->p_vmspace = nvm;
4179	pmap_activate(l);		/* switch to new vmspace */
4180	kpreempt_enable();
4181
4182	uvmspace_free(ovm);		/* drop reference to old vmspace */
4183}
4184
4185#endif
4186
4187
4188/*
4189 * uvmspace_spawn: a new process has been spawned and needs a vmspace
4190 */
4191
4192void
4193uvmspace_spawn(struct lwp *l, vaddr_t start, vaddr_t end, bool topdown)
4194{
4195	struct proc *p = l->l_proc;
4196	struct vmspace *nvm;
4197
4198#ifdef __HAVE_CPU_VMSPACE_EXEC
4199	cpu_vmspace_exec(l, start, end);
4200#endif
4201
4202	nvm = uvmspace_alloc(start, end, topdown);
4203	kpreempt_disable();
4204	p->p_vmspace = nvm;
4205	pmap_activate(l);
4206	kpreempt_enable();
4207}
4208
4209/*
4210 * uvmspace_exec: the process wants to exec a new program
4211 */
4212
4213void
4214uvmspace_exec(struct lwp *l, vaddr_t start, vaddr_t end, bool topdown)
4215{
4216	struct proc *p = l->l_proc;
4217	struct vmspace *nvm, *ovm = p->p_vmspace;
4218	struct vm_map *map;
4219	int flags;
4220
4221	KASSERT(ovm != NULL);
4222#ifdef __HAVE_CPU_VMSPACE_EXEC
4223	cpu_vmspace_exec(l, start, end);
4224#endif
4225
4226	map = &ovm->vm_map;
4227	/*
4228	 * see if more than one process is using this vmspace...
4229	 */
4230
4231	if (ovm->vm_refcnt == 1
4232	    && topdown == ((ovm->vm_map.flags & VM_MAP_TOPDOWN) != 0)) {
4233
4234		/*
4235		 * if p is the only process using its vmspace then we can safely
4236		 * recycle that vmspace for the program that is being exec'd.
4237		 * But only if TOPDOWN matches the requested value for the new
4238		 * vm space!
4239		 */
4240
4241		/*
4242		 * SYSV SHM semantics require us to kill all segments on an exec
4243		 */
4244		if (uvm_shmexit && ovm->vm_shm)
4245			(*uvm_shmexit)(ovm);
4246
4247		/*
4248		 * POSIX 1003.1b -- "lock future mappings" is revoked
4249		 * when a process execs another program image.
4250		 */
4251
4252		map->flags &= ~VM_MAP_WIREFUTURE;
4253
4254		/*
4255		 * now unmap the old program.
4256		 *
4257		 * XXX set VM_MAP_DYING for the duration, so pmap_update()
4258		 * is not called until the pmap has been totally cleared out
4259		 * after pmap_remove_all(), or it can confuse some pmap
4260		 * implementations.  it would be nice to handle this by
4261		 * deferring the pmap_update() while it is known the address
4262		 * space is not visible to any user LWP other than curlwp,
4263		 * but there isn't an elegant way of inferring that right
4264		 * now.
4265		 */
4266
4267		flags = pmap_remove_all(map->pmap) ? UVM_FLAG_VAONLY : 0;
4268		map->flags |= VM_MAP_DYING;
4269		uvm_unmap1(map, vm_map_min(map), vm_map_max(map), flags);
4270		map->flags &= ~VM_MAP_DYING;
4271		pmap_update(map->pmap);
4272		KASSERT(map->header.prev == &map->header);
4273		KASSERT(map->nentries == 0);
4274
4275		/*
4276		 * resize the map
4277		 */
4278
4279		vm_map_setmin(map, start);
4280		vm_map_setmax(map, end);
4281	} else {
4282
4283		/*
4284		 * p's vmspace is being shared, so we can't reuse it for p since
4285		 * it is still being used for others.   allocate a new vmspace
4286		 * for p
4287		 */
4288
4289		nvm = uvmspace_alloc(start, end, topdown);
4290
4291		/*
4292		 * install new vmspace and drop our ref to the old one.
4293		 */
4294
4295		kpreempt_disable();
4296		pmap_deactivate(l);
4297		p->p_vmspace = nvm;
4298		pmap_activate(l);
4299		kpreempt_enable();
4300
4301		uvmspace_free(ovm);
4302	}
4303}
4304
4305/*
4306 * uvmspace_addref: add a reference to a vmspace.
4307 */
4308
4309void
4310uvmspace_addref(struct vmspace *vm)
4311{
4312
4313	KASSERT((vm->vm_map.flags & VM_MAP_DYING) == 0);
4314	KASSERT(vm->vm_refcnt > 0);
4315	atomic_inc_uint(&vm->vm_refcnt);
4316}
4317
4318/*
4319 * uvmspace_free: free a vmspace data structure
4320 */
4321
4322void
4323uvmspace_free(struct vmspace *vm)
4324{
4325	struct vm_map_entry *dead_entries;
4326	struct vm_map *map = &vm->vm_map;
4327	int flags;
4328
4329	UVMHIST_FUNC(__func__);
4330	UVMHIST_CALLARGS(maphist,"(vm=%#jx) ref=%jd", (uintptr_t)vm,
4331	    vm->vm_refcnt, 0, 0);
4332
4333	membar_release();
4334	if (atomic_dec_uint_nv(&vm->vm_refcnt) > 0)
4335		return;
4336	membar_acquire();
4337
4338	/*
4339	 * at this point, there should be no other references to the map.
4340	 * delete all of the mappings, then destroy the pmap.
4341	 */
4342
4343	map->flags |= VM_MAP_DYING;
4344	flags = pmap_remove_all(map->pmap) ? UVM_FLAG_VAONLY : 0;
4345
4346	/* Get rid of any SYSV shared memory segments. */
4347	if (uvm_shmexit && vm->vm_shm != NULL)
4348		(*uvm_shmexit)(vm);
4349
4350	if (map->nentries) {
4351		uvm_unmap_remove(map, vm_map_min(map), vm_map_max(map),
4352		    &dead_entries, flags);
4353		if (dead_entries != NULL)
4354			uvm_unmap_detach(dead_entries, 0);
4355	}
4356	KASSERT(map->nentries == 0);
4357	KASSERT(map->size == 0);
4358
4359	mutex_destroy(&map->misc_lock);
4360	rw_destroy(&map->lock);
4361	cv_destroy(&map->cv);
4362	pmap_destroy(map->pmap);
4363	kmem_free(vm, sizeof(*vm));
4364}
4365
4366static struct vm_map_entry *
4367uvm_mapent_clone(struct vm_map *new_map, struct vm_map_entry *old_entry,
4368    int flags)
4369{
4370	struct vm_map_entry *new_entry;
4371
4372	new_entry = uvm_mapent_alloc(new_map, 0);
4373	/* old_entry -> new_entry */
4374	uvm_mapent_copy(old_entry, new_entry);
4375
4376	/* new pmap has nothing wired in it */
4377	new_entry->wired_count = 0;
4378
4379	/*
4380	 * gain reference to object backing the map (can't
4381	 * be a submap, already checked this case).
4382	 */
4383
4384	if (new_entry->aref.ar_amap)
4385		uvm_map_reference_amap(new_entry, flags);
4386
4387	if (new_entry->object.uvm_obj &&
4388	    new_entry->object.uvm_obj->pgops->pgo_reference)
4389		new_entry->object.uvm_obj->pgops->pgo_reference(
4390			new_entry->object.uvm_obj);
4391
4392	/* insert entry at end of new_map's entry list */
4393	uvm_map_entry_link(new_map, new_map->header.prev,
4394	    new_entry);
4395
4396	return new_entry;
4397}
4398
4399/*
4400 * share the mapping: this means we want the old and
4401 * new entries to share amaps and backing objects.
4402 */
4403static void
4404uvm_mapent_forkshared(struct vm_map *new_map, struct vm_map *old_map,
4405    struct vm_map_entry *old_entry)
4406{
4407	/*
4408	 * if the old_entry needs a new amap (due to prev fork)
4409	 * then we need to allocate it now so that we have
4410	 * something we own to share with the new_entry.   [in
4411	 * other words, we need to clear needs_copy]
4412	 */
4413
4414	if (UVM_ET_ISNEEDSCOPY(old_entry)) {
4415		/* get our own amap, clears needs_copy */
4416		amap_copy(old_map, old_entry, AMAP_COPY_NOCHUNK,
4417		    0, 0);
4418		/* XXXCDC: WAITOK??? */
4419	}
4420
4421	uvm_mapent_clone(new_map, old_entry, AMAP_SHARED);
4422}
4423
4424
4425static void
4426uvm_mapent_forkcopy(struct vm_map *new_map, struct vm_map *old_map,
4427    struct vm_map_entry *old_entry)
4428{
4429	struct vm_map_entry *new_entry;
4430
4431	/*
4432	 * copy-on-write the mapping (using mmap's
4433	 * MAP_PRIVATE semantics)
4434	 *
4435	 * allocate new_entry, adjust reference counts.
4436	 * (note that new references are read-only).
4437	 */
4438
4439	new_entry = uvm_mapent_clone(new_map, old_entry, 0);
4440
4441	new_entry->etype |=
4442	    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
4443
4444	/*
4445	 * the new entry will need an amap.  it will either
4446	 * need to be copied from the old entry or created
4447	 * from scratch (if the old entry does not have an
4448	 * amap).  can we defer this process until later
4449	 * (by setting "needs_copy") or do we need to copy
4450	 * the amap now?
4451	 *
4452	 * we must copy the amap now if any of the following
4453	 * conditions hold:
4454	 * 1. the old entry has an amap and that amap is
4455	 *    being shared.  this means that the old (parent)
4456	 *    process is sharing the amap with another
4457	 *    process.  if we do not clear needs_copy here
4458	 *    we will end up in a situation where both the
4459	 *    parent and child process are referring to the
4460	 *    same amap with "needs_copy" set.  if the
4461	 *    parent write-faults, the fault routine will
4462	 *    clear "needs_copy" in the parent by allocating
4463	 *    a new amap.   this is wrong because the
4464	 *    parent is supposed to be sharing the old amap
4465	 *    and the new amap will break that.
4466	 *
4467	 * 2. if the old entry has an amap and a non-zero
4468	 *    wire count then we are going to have to call
4469	 *    amap_cow_now to avoid page faults in the
4470	 *    parent process.   since amap_cow_now requires
4471	 *    "needs_copy" to be clear we might as well
4472	 *    clear it here as well.
4473	 *
4474	 */
4475
4476	if (old_entry->aref.ar_amap != NULL) {
4477		if ((amap_flags(old_entry->aref.ar_amap) & AMAP_SHARED) != 0 ||
4478		    VM_MAPENT_ISWIRED(old_entry)) {
4479
4480			amap_copy(new_map, new_entry,
4481			    AMAP_COPY_NOCHUNK, 0, 0);
4482			/* XXXCDC: M_WAITOK ... ok? */
4483		}
4484	}
4485
4486	/*
4487	 * if the parent's entry is wired down, then the
4488	 * parent process does not want page faults on
4489	 * access to that memory.  this means that we
4490	 * cannot do copy-on-write because we can't write
4491	 * protect the old entry.   in this case we
4492	 * resolve all copy-on-write faults now, using
4493	 * amap_cow_now.   note that we have already
4494	 * allocated any needed amap (above).
4495	 */
4496
4497	if (VM_MAPENT_ISWIRED(old_entry)) {
4498
4499		/*
4500		 * resolve all copy-on-write faults now
4501		 * (note that there is nothing to do if
4502		 * the old mapping does not have an amap).
4503		 */
4504		if (old_entry->aref.ar_amap)
4505			amap_cow_now(new_map, new_entry);
4506
4507	} else {
4508		/*
4509		 * setup mappings to trigger copy-on-write faults
4510		 * we must write-protect the parent if it has
4511		 * an amap and it is not already "needs_copy"...
4512		 * if it is already "needs_copy" then the parent
4513		 * has already been write-protected by a previous
4514		 * fork operation.
4515		 */
4516		if (old_entry->aref.ar_amap &&
4517		    !UVM_ET_ISNEEDSCOPY(old_entry)) {
4518			if (old_entry->max_protection & VM_PROT_WRITE) {
4519#ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
4520				uvm_map_lock_entry(old_entry, RW_WRITER);
4521#else
4522				uvm_map_lock_entry(old_entry, RW_READER);
4523#endif
4524				pmap_protect(old_map->pmap,
4525				    old_entry->start, old_entry->end,
4526				    old_entry->protection & ~VM_PROT_WRITE);
4527				uvm_map_unlock_entry(old_entry);
4528			}
4529			old_entry->etype |= UVM_ET_NEEDSCOPY;
4530		}
4531	}
4532}
4533
4534/*
4535 * zero the mapping: the new entry will be zero initialized
4536 */
4537static void
4538uvm_mapent_forkzero(struct vm_map *new_map, struct vm_map *old_map,
4539    struct vm_map_entry *old_entry)
4540{
4541	struct vm_map_entry *new_entry;
4542
4543	new_entry = uvm_mapent_clone(new_map, old_entry, 0);
4544
4545	new_entry->etype |=
4546	    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
4547
4548	if (new_entry->aref.ar_amap) {
4549		uvm_map_unreference_amap(new_entry, 0);
4550		new_entry->aref.ar_pageoff = 0;
4551		new_entry->aref.ar_amap = NULL;
4552	}
4553
4554	if (UVM_ET_ISOBJ(new_entry)) {
4555		if (new_entry->object.uvm_obj->pgops->pgo_detach)
4556			new_entry->object.uvm_obj->pgops->pgo_detach(
4557			    new_entry->object.uvm_obj);
4558		new_entry->object.uvm_obj = NULL;
4559		new_entry->offset = 0;
4560		new_entry->etype &= ~UVM_ET_OBJ;
4561	}
4562}
4563
4564/*
4565 *   F O R K   -   m a i n   e n t r y   p o i n t
4566 */
4567/*
4568 * uvmspace_fork: fork a process' main map
4569 *
4570 * => create a new vmspace for child process from parent.
4571 * => parent's map must not be locked.
4572 */
4573
4574struct vmspace *
4575uvmspace_fork(struct vmspace *vm1)
4576{
4577	struct vmspace *vm2;
4578	struct vm_map *old_map = &vm1->vm_map;
4579	struct vm_map *new_map;
4580	struct vm_map_entry *old_entry;
4581	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
4582
4583	vm_map_lock(old_map);
4584
4585	vm2 = uvmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
4586	    vm1->vm_map.flags & VM_MAP_TOPDOWN);
4587	memcpy(&vm2->vm_startcopy, &vm1->vm_startcopy,
4588	    (char *) (vm1 + 1) - (char *) &vm1->vm_startcopy);
4589	new_map = &vm2->vm_map;		  /* XXX */
4590
4591	old_entry = old_map->header.next;
4592	new_map->size = old_map->size;
4593
4594	/*
4595	 * go entry-by-entry
4596	 */
4597
4598	while (old_entry != &old_map->header) {
4599
4600		/*
4601		 * first, some sanity checks on the old entry
4602		 */
4603
4604		KASSERT(!UVM_ET_ISSUBMAP(old_entry));
4605		KASSERT(UVM_ET_ISCOPYONWRITE(old_entry) ||
4606			!UVM_ET_ISNEEDSCOPY(old_entry));
4607
4608		switch (old_entry->inheritance) {
4609		case MAP_INHERIT_NONE:
4610			/*
4611			 * drop the mapping, modify size
4612			 */
4613			new_map->size -= old_entry->end - old_entry->start;
4614			break;
4615
4616		case MAP_INHERIT_SHARE:
4617			uvm_mapent_forkshared(new_map, old_map, old_entry);
4618			break;
4619
4620		case MAP_INHERIT_COPY:
4621			uvm_mapent_forkcopy(new_map, old_map, old_entry);
4622			break;
4623
4624		case MAP_INHERIT_ZERO:
4625			uvm_mapent_forkzero(new_map, old_map, old_entry);
4626			break;
4627		default:
4628			KASSERT(0);
4629			break;
4630		}
4631		old_entry = old_entry->next;
4632	}
4633
4634	pmap_update(old_map->pmap);
4635	vm_map_unlock(old_map);
4636
4637	if (uvm_shmfork && vm1->vm_shm)
4638		(*uvm_shmfork)(vm1, vm2);
4639
4640#ifdef PMAP_FORK
4641	pmap_fork(vm1->vm_map.pmap, vm2->vm_map.pmap);
4642#endif
4643
4644	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
4645	return (vm2);
4646}
4647
4648
4649/*
4650 * uvm_mapent_trymerge: try to merge an entry with its neighbors.
4651 *
4652 * => called with map locked.
4653 * => return non zero if successfully merged.
4654 */
4655
4656int
4657uvm_mapent_trymerge(struct vm_map *map, struct vm_map_entry *entry, int flags)
4658{
4659	struct uvm_object *uobj;
4660	struct vm_map_entry *next;
4661	struct vm_map_entry *prev;
4662	vsize_t size;
4663	int merged = 0;
4664	bool copying;
4665	int newetype;
4666
4667	if (entry->aref.ar_amap != NULL) {
4668		return 0;
4669	}
4670	if ((entry->flags & UVM_MAP_NOMERGE) != 0) {
4671		return 0;
4672	}
4673
4674	uobj = entry->object.uvm_obj;
4675	size = entry->end - entry->start;
4676	copying = (flags & UVM_MERGE_COPYING) != 0;
4677	newetype = copying ? (entry->etype & ~UVM_ET_NEEDSCOPY) : entry->etype;
4678
4679	next = entry->next;
4680	if (next != &map->header &&
4681	    next->start == entry->end &&
4682	    ((copying && next->aref.ar_amap != NULL &&
4683	    amap_refs(next->aref.ar_amap) == 1) ||
4684	    (!copying && next->aref.ar_amap == NULL)) &&
4685	    UVM_ET_ISCOMPATIBLE(next, newetype,
4686	    uobj, entry->flags, entry->protection,
4687	    entry->max_protection, entry->inheritance, entry->advice,
4688	    entry->wired_count) &&
4689	    (uobj == NULL || entry->offset + size == next->offset)) {
4690		int error;
4691
4692		if (copying) {
4693			error = amap_extend(next, size,
4694			    AMAP_EXTEND_NOWAIT|AMAP_EXTEND_BACKWARDS);
4695		} else {
4696			error = 0;
4697		}
4698		if (error == 0) {
4699			if (uobj) {
4700				if (uobj->pgops->pgo_detach) {
4701					uobj->pgops->pgo_detach(uobj);
4702				}
4703			}
4704
4705			entry->end = next->end;
4706			clear_hints(map, next);
4707			uvm_map_entry_unlink(map, next);
4708			if (copying) {
4709				entry->aref = next->aref;
4710				entry->etype &= ~UVM_ET_NEEDSCOPY;
4711			}
4712			uvm_map_check(map, "trymerge forwardmerge");
4713			uvm_mapent_free(next);
4714			merged++;
4715		}
4716	}
4717
4718	prev = entry->prev;
4719	if (prev != &map->header &&
4720	    prev->end == entry->start &&
4721	    ((copying && !merged && prev->aref.ar_amap != NULL &&
4722	    amap_refs(prev->aref.ar_amap) == 1) ||
4723	    (!copying && prev->aref.ar_amap == NULL)) &&
4724	    UVM_ET_ISCOMPATIBLE(prev, newetype,
4725	    uobj, entry->flags, entry->protection,
4726	    entry->max_protection, entry->inheritance, entry->advice,
4727	    entry->wired_count) &&
4728	    (uobj == NULL ||
4729	    prev->offset + prev->end - prev->start == entry->offset)) {
4730		int error;
4731
4732		if (copying) {
4733			error = amap_extend(prev, size,
4734			    AMAP_EXTEND_NOWAIT|AMAP_EXTEND_FORWARDS);
4735		} else {
4736			error = 0;
4737		}
4738		if (error == 0) {
4739			if (uobj) {
4740				if (uobj->pgops->pgo_detach) {
4741					uobj->pgops->pgo_detach(uobj);
4742				}
4743				entry->offset = prev->offset;
4744			}
4745
4746			entry->start = prev->start;
4747			clear_hints(map, prev);
4748			uvm_map_entry_unlink(map, prev);
4749			if (copying) {
4750				entry->aref = prev->aref;
4751				entry->etype &= ~UVM_ET_NEEDSCOPY;
4752			}
4753			uvm_map_check(map, "trymerge backmerge");
4754			uvm_mapent_free(prev);
4755			merged++;
4756		}
4757	}
4758
4759	return merged;
4760}
4761
4762/*
4763 * uvm_map_setup: init map
4764 *
4765 * => map must not be in service yet.
4766 */
4767
4768void
4769uvm_map_setup(struct vm_map *map, vaddr_t vmin, vaddr_t vmax, int flags)
4770{
4771
4772	rb_tree_init(&map->rb_tree, &uvm_map_tree_ops);
4773	map->header.next = map->header.prev = &map->header;
4774	map->nentries = 0;
4775	map->size = 0;
4776	map->ref_count = 1;
4777	vm_map_setmin(map, vmin);
4778	vm_map_setmax(map, vmax);
4779	map->flags = flags;
4780	map->first_free = &map->header;
4781	map->hint = &map->header;
4782	map->timestamp = 0;
4783	map->busy = NULL;
4784
4785	rw_init(&map->lock);
4786	cv_init(&map->cv, "vm_map");
4787	mutex_init(&map->misc_lock, MUTEX_DRIVER, IPL_NONE);
4788}
4789
4790/*
4791 *   U N M A P   -   m a i n   e n t r y   p o i n t
4792 */
4793
4794/*
4795 * uvm_unmap1: remove mappings from a vm_map (from "start" up to "stop")
4796 *
4797 * => caller must check alignment and size
4798 * => map must be unlocked (we will lock it)
4799 * => flags is UVM_FLAG_QUANTUM or 0.
4800 */
4801
4802void
4803uvm_unmap1(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
4804{
4805	struct vm_map_entry *dead_entries;
4806	UVMHIST_FUNC(__func__);
4807	UVMHIST_CALLARGS(maphist, "  (map=%#jx, start=%#jx, end=%#jx)",
4808	    (uintptr_t)map, start, end, 0);
4809
4810	KASSERTMSG(start < end,
4811	    "%s: map %p: start %#jx < end %#jx", __func__, map,
4812	    (uintmax_t)start, (uintmax_t)end);
4813	if (map == kernel_map) {
4814		LOCKDEBUG_MEM_CHECK((void *)start, end - start);
4815	}
4816
4817	/*
4818	 * work now done by helper functions.   wipe the pmap's and then
4819	 * detach from the dead entries...
4820	 */
4821	vm_map_lock(map);
4822	uvm_unmap_remove(map, start, end, &dead_entries, flags);
4823	vm_map_unlock(map);
4824
4825	if (dead_entries != NULL)
4826		uvm_unmap_detach(dead_entries, 0);
4827
4828	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
4829}
4830
4831
4832/*
4833 * uvm_map_reference: add reference to a map
4834 *
4835 * => map need not be locked
4836 */
4837
4838void
4839uvm_map_reference(struct vm_map *map)
4840{
4841
4842	atomic_inc_uint(&map->ref_count);
4843}
4844
4845void
4846uvm_map_lock_entry(struct vm_map_entry *entry, krw_t op)
4847{
4848
4849	if (entry->aref.ar_amap != NULL) {
4850		amap_lock(entry->aref.ar_amap, op);
4851	}
4852	if (UVM_ET_ISOBJ(entry)) {
4853		rw_enter(entry->object.uvm_obj->vmobjlock, op);
4854	}
4855}
4856
4857void
4858uvm_map_unlock_entry(struct vm_map_entry *entry)
4859{
4860
4861	if (UVM_ET_ISOBJ(entry)) {
4862		rw_exit(entry->object.uvm_obj->vmobjlock);
4863	}
4864	if (entry->aref.ar_amap != NULL) {
4865		amap_unlock(entry->aref.ar_amap);
4866	}
4867}
4868
4869#define	UVM_VOADDR_TYPE_MASK	0x3UL
4870#define	UVM_VOADDR_TYPE_UOBJ	0x1UL
4871#define	UVM_VOADDR_TYPE_ANON	0x2UL
4872#define	UVM_VOADDR_OBJECT_MASK	~UVM_VOADDR_TYPE_MASK
4873
4874#define	UVM_VOADDR_GET_TYPE(voa)					\
4875	((voa)->object & UVM_VOADDR_TYPE_MASK)
4876#define	UVM_VOADDR_GET_OBJECT(voa)					\
4877	((voa)->object & UVM_VOADDR_OBJECT_MASK)
4878#define	UVM_VOADDR_SET_OBJECT(voa, obj, type)				\
4879do {									\
4880	KASSERT(((uintptr_t)(obj) & UVM_VOADDR_TYPE_MASK) == 0);	\
4881	(voa)->object = ((uintptr_t)(obj)) | (type);			\
4882} while (/*CONSTCOND*/0)
4883
4884#define	UVM_VOADDR_GET_UOBJ(voa)					\
4885	((struct uvm_object *)UVM_VOADDR_GET_OBJECT(voa))
4886#define	UVM_VOADDR_SET_UOBJ(voa, uobj)					\
4887	UVM_VOADDR_SET_OBJECT(voa, uobj, UVM_VOADDR_TYPE_UOBJ)
4888
4889#define	UVM_VOADDR_GET_ANON(voa)					\
4890	((struct vm_anon *)UVM_VOADDR_GET_OBJECT(voa))
4891#define	UVM_VOADDR_SET_ANON(voa, anon)					\
4892	UVM_VOADDR_SET_OBJECT(voa, anon, UVM_VOADDR_TYPE_ANON)
4893
4894/*
4895 * uvm_voaddr_acquire: returns the virtual object address corresponding
4896 * to the specified virtual address.
4897 *
4898 * => resolves COW so the true page identity is tracked.
4899 *
4900 * => acquires a reference on the page's owner (uvm_object or vm_anon)
4901 */
4902bool
4903uvm_voaddr_acquire(struct vm_map * const map, vaddr_t const va,
4904    struct uvm_voaddr * const voaddr)
4905{
4906	struct vm_map_entry *entry;
4907	struct vm_anon *anon = NULL;
4908	bool result = false;
4909	bool exclusive = false;
4910	void (*unlock_fn)(struct vm_map *);
4911
4912	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
4913	UVMHIST_LOG(maphist,"(map=%#jx,va=%#jx)", (uintptr_t)map, va, 0, 0);
4914
4915	const vaddr_t start = trunc_page(va);
4916	const vaddr_t end = round_page(va+1);
4917
4918 lookup_again:
4919	if (__predict_false(exclusive)) {
4920		vm_map_lock(map);
4921		unlock_fn = vm_map_unlock;
4922	} else {
4923		vm_map_lock_read(map);
4924		unlock_fn = vm_map_unlock_read;
4925	}
4926
4927	if (__predict_false(!uvm_map_lookup_entry(map, start, &entry))) {
4928		unlock_fn(map);
4929		UVMHIST_LOG(maphist,"<- done (no entry)",0,0,0,0);
4930		return false;
4931	}
4932
4933	if (__predict_false(entry->protection == VM_PROT_NONE)) {
4934		unlock_fn(map);
4935		UVMHIST_LOG(maphist,"<- done (PROT_NONE)",0,0,0,0);
4936		return false;
4937	}
4938
4939	/*
4940	 * We have a fast path for the common case of "no COW resolution
4941	 * needed" whereby we have taken a read lock on the map and if
4942	 * we don't encounter any need to create a vm_anon then great!
4943	 * But if we do, we loop around again, instead taking an exclusive
4944	 * lock so that we can perform the fault.
4945	 *
4946	 * In the event that we have to resolve the fault, we do nearly the
4947	 * same work as uvm_map_pageable() does:
4948	 *
4949	 * 1: holding the write lock, we create any anonymous maps that need
4950	 *    to be created.  however, we do NOT need to clip the map entries
4951	 *    in this case.
4952	 *
4953	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
4954	 *    in the page (assuming the entry is not already wired).  this
4955	 *    is done because we need the vm_anon to be present.
4956	 */
4957	if (__predict_true(!VM_MAPENT_ISWIRED(entry))) {
4958
4959		bool need_fault = false;
4960
4961		/*
4962		 * perform the action of vm_map_lookup that need the
4963		 * write lock on the map: create an anonymous map for
4964		 * a copy-on-write region, or an anonymous map for
4965		 * a zero-fill region.
4966		 */
4967		if (__predict_false(UVM_ET_ISSUBMAP(entry))) {
4968			unlock_fn(map);
4969			UVMHIST_LOG(maphist,"<- done (submap)",0,0,0,0);
4970			return false;
4971		}
4972		if (__predict_false(UVM_ET_ISNEEDSCOPY(entry) &&
4973		    ((entry->max_protection & VM_PROT_WRITE) ||
4974		     (entry->object.uvm_obj == NULL)))) {
4975			if (!exclusive) {
4976				/* need to take the slow path */
4977				KASSERT(unlock_fn == vm_map_unlock_read);
4978				vm_map_unlock_read(map);
4979				exclusive = true;
4980				goto lookup_again;
4981			}
4982			need_fault = true;
4983			amap_copy(map, entry, 0, start, end);
4984			/* XXXCDC: wait OK? */
4985		}
4986
4987		/*
4988		 * do a quick check to see if the fault has already
4989		 * been resolved to the upper layer.
4990		 */
4991		if (__predict_true(entry->aref.ar_amap != NULL &&
4992				   need_fault == false)) {
4993			amap_lock(entry->aref.ar_amap, RW_WRITER);
4994			anon = amap_lookup(&entry->aref, start - entry->start);
4995			if (__predict_true(anon != NULL)) {
4996				/* amap unlocked below */
4997				goto found_anon;
4998			}
4999			amap_unlock(entry->aref.ar_amap);
5000			need_fault = true;
5001		}
5002
5003		/*
5004		 * we predict this test as false because if we reach
5005		 * this point, then we are likely dealing with a
5006		 * shared memory region backed by a uvm_object, in
5007		 * which case a fault to create the vm_anon is not
5008		 * necessary.
5009		 */
5010		if (__predict_false(need_fault)) {
5011			if (exclusive) {
5012				vm_map_busy(map);
5013				vm_map_unlock(map);
5014				unlock_fn = vm_map_unbusy;
5015			}
5016
5017			if (uvm_fault_wire(map, start, end,
5018					   entry->max_protection, 1)) {
5019				/* wiring failed */
5020				unlock_fn(map);
5021				UVMHIST_LOG(maphist,"<- done (wire failed)",
5022					    0,0,0,0);
5023				return false;
5024			}
5025
5026			/*
5027			 * now that we have resolved the fault, we can unwire
5028			 * the page.
5029			 */
5030			if (exclusive) {
5031				vm_map_lock(map);
5032				vm_map_unbusy(map);
5033				unlock_fn = vm_map_unlock;
5034			}
5035
5036			uvm_fault_unwire_locked(map, start, end);
5037		}
5038	}
5039
5040	/* check the upper layer */
5041	if (entry->aref.ar_amap) {
5042		amap_lock(entry->aref.ar_amap, RW_WRITER);
5043		anon = amap_lookup(&entry->aref, start - entry->start);
5044		if (anon) {
5045 found_anon:		KASSERT(anon->an_lock == entry->aref.ar_amap->am_lock);
5046			anon->an_ref++;
5047			rw_obj_hold(anon->an_lock);
5048			KASSERT(anon->an_ref != 0);
5049			UVM_VOADDR_SET_ANON(voaddr, anon);
5050			voaddr->offset = va & PAGE_MASK;
5051			result = true;
5052		}
5053		amap_unlock(entry->aref.ar_amap);
5054	}
5055
5056	/* check the lower layer */
5057	if (!result && UVM_ET_ISOBJ(entry)) {
5058		struct uvm_object *uobj = entry->object.uvm_obj;
5059
5060		KASSERT(uobj != NULL);
5061		(*uobj->pgops->pgo_reference)(uobj);
5062		UVM_VOADDR_SET_UOBJ(voaddr, uobj);
5063		voaddr->offset = entry->offset + (va - entry->start);
5064		result = true;
5065	}
5066
5067	unlock_fn(map);
5068
5069	if (result) {
5070		UVMHIST_LOG(maphist,
5071		    "<- done OK (type=%jd,owner=%#jx,offset=%#jx)",
5072		    UVM_VOADDR_GET_TYPE(voaddr),
5073		    UVM_VOADDR_GET_OBJECT(voaddr),
5074		    voaddr->offset, 0);
5075	} else {
5076		UVMHIST_LOG(maphist,"<- done (failed)",0,0,0,0);
5077	}
5078
5079	return result;
5080}
5081
5082/*
5083 * uvm_voaddr_release: release the references held by the
5084 * vitual object address.
5085 */
5086void
5087uvm_voaddr_release(struct uvm_voaddr * const voaddr)
5088{
5089
5090	switch (UVM_VOADDR_GET_TYPE(voaddr)) {
5091	case UVM_VOADDR_TYPE_UOBJ: {
5092		struct uvm_object * const uobj = UVM_VOADDR_GET_UOBJ(voaddr);
5093
5094		KASSERT(uobj != NULL);
5095		KASSERT(uobj->pgops->pgo_detach != NULL);
5096		(*uobj->pgops->pgo_detach)(uobj);
5097		break;
5098	    }
5099	case UVM_VOADDR_TYPE_ANON: {
5100		struct vm_anon * const anon = UVM_VOADDR_GET_ANON(voaddr);
5101		krwlock_t *lock;
5102
5103		KASSERT(anon != NULL);
5104		rw_enter((lock = anon->an_lock), RW_WRITER);
5105	    	KASSERT(anon->an_ref > 0);
5106		if (--anon->an_ref == 0) {
5107			uvm_anfree(anon);
5108		}
5109		rw_exit(lock);
5110		rw_obj_free(lock);
5111	    	break;
5112	    }
5113	default:
5114		panic("uvm_voaddr_release: bad type");
5115	}
5116	memset(voaddr, 0, sizeof(*voaddr));
5117}
5118
5119/*
5120 * uvm_voaddr_compare: compare two uvm_voaddr objects.
5121 *
5122 * => memcmp() semantics
5123 */
5124int
5125uvm_voaddr_compare(const struct uvm_voaddr * const voaddr1,
5126    const struct uvm_voaddr * const voaddr2)
5127{
5128	const uintptr_t type1 = UVM_VOADDR_GET_TYPE(voaddr1);
5129	const uintptr_t type2 = UVM_VOADDR_GET_TYPE(voaddr2);
5130
5131	KASSERT(type1 == UVM_VOADDR_TYPE_UOBJ ||
5132		type1 == UVM_VOADDR_TYPE_ANON);
5133
5134	KASSERT(type2 == UVM_VOADDR_TYPE_UOBJ ||
5135		type2 == UVM_VOADDR_TYPE_ANON);
5136
5137	if (type1 < type2)
5138		return -1;
5139	if (type1 > type2)
5140		return 1;
5141
5142	const uintptr_t addr1 = UVM_VOADDR_GET_OBJECT(voaddr1);
5143	const uintptr_t addr2 = UVM_VOADDR_GET_OBJECT(voaddr2);
5144
5145	if (addr1 < addr2)
5146		return -1;
5147	if (addr1 > addr2)
5148		return 1;
5149
5150	if (voaddr1->offset < voaddr2->offset)
5151		return -1;
5152	if (voaddr1->offset > voaddr2->offset)
5153		return 1;
5154
5155	return 0;
5156}
5157
5158#if defined(DDB) || defined(DEBUGPRINT)
5159
5160/*
5161 * uvm_map_printit: actually prints the map
5162 */
5163
5164void
5165uvm_map_printit(struct vm_map *map, bool full,
5166    void (*pr)(const char *, ...))
5167{
5168	struct vm_map_entry *entry;
5169
5170	(*pr)("MAP %p: [%#lx->%#lx]\n", map, vm_map_min(map),
5171	    vm_map_max(map));
5172	(*pr)("\t#ent=%d, sz=%d, ref=%d, version=%d, flags=%#x\n",
5173	    map->nentries, map->size, map->ref_count, map->timestamp,
5174	    map->flags);
5175	(*pr)("\tpmap=%p(resident=%ld, wired=%ld)\n", map->pmap,
5176	    pmap_resident_count(map->pmap), pmap_wired_count(map->pmap));
5177	if (!full)
5178		return;
5179	for (entry = map->header.next; entry != &map->header;
5180	    entry = entry->next) {
5181		(*pr)(" - %p: %#lx->%#lx: obj=%p/%#llx, amap=%p/%d\n",
5182		    entry, entry->start, entry->end, entry->object.uvm_obj,
5183		    (long long)entry->offset, entry->aref.ar_amap,
5184		    entry->aref.ar_pageoff);
5185		(*pr)(
5186		    "\tsubmap=%c, cow=%c, nc=%c, prot(max)=%d/%d, inh=%d, "
5187		    "wc=%d, adv=%d%s\n",
5188		    (entry->etype & UVM_ET_SUBMAP) ? 'T' : 'F',
5189		    (entry->etype & UVM_ET_COPYONWRITE) ? 'T' : 'F',
5190		    (entry->etype & UVM_ET_NEEDSCOPY) ? 'T' : 'F',
5191		    entry->protection, entry->max_protection,
5192		    entry->inheritance, entry->wired_count, entry->advice,
5193		    entry == map->first_free ? " (first_free)" : "");
5194	}
5195}
5196
5197void
5198uvm_whatis(uintptr_t addr, void (*pr)(const char *, ...))
5199{
5200	struct vm_map *map;
5201
5202	for (map = kernel_map;;) {
5203		struct vm_map_entry *entry;
5204
5205		if (!uvm_map_lookup_entry_bytree(map, (vaddr_t)addr, &entry)) {
5206			break;
5207		}
5208		(*pr)("%p is %p+%zu from VMMAP %p\n",
5209		    (void *)addr, (void *)entry->start,
5210		    (size_t)(addr - (uintptr_t)entry->start), map);
5211		if (!UVM_ET_ISSUBMAP(entry)) {
5212			break;
5213		}
5214		map = entry->object.sub_map;
5215	}
5216}
5217
5218#endif /* DDB || DEBUGPRINT */
5219
5220#ifndef __USER_VA0_IS_SAFE
5221static int
5222sysctl_user_va0_disable(SYSCTLFN_ARGS)
5223{
5224	struct sysctlnode node;
5225	int t, error;
5226
5227	node = *rnode;
5228	node.sysctl_data = &t;
5229	t = user_va0_disable;
5230	error = sysctl_lookup(SYSCTLFN_CALL(&node));
5231	if (error || newp == NULL)
5232		return (error);
5233
5234	if (!t && user_va0_disable &&
5235	    kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_MAP_VA_ZERO, 0,
5236	    NULL, NULL, NULL))
5237		return EPERM;
5238
5239	user_va0_disable = !!t;
5240	return 0;
5241}
5242#endif
5243
5244static int
5245fill_vmentry(struct lwp *l, struct proc *p, struct kinfo_vmentry *kve,
5246    struct vm_map *m, struct vm_map_entry *e)
5247{
5248#ifndef _RUMPKERNEL
5249	int error;
5250
5251	memset(kve, 0, sizeof(*kve));
5252	KASSERT(e != NULL);
5253	if (UVM_ET_ISOBJ(e)) {
5254		struct uvm_object *uobj = e->object.uvm_obj;
5255		KASSERT(uobj != NULL);
5256		kve->kve_ref_count = uobj->uo_refs;
5257		kve->kve_count = uobj->uo_npages;
5258		if (UVM_OBJ_IS_VNODE(uobj)) {
5259			struct vattr va;
5260			struct vnode *vp = (struct vnode *)uobj;
5261			vn_lock(vp, LK_SHARED | LK_RETRY);
5262			error = VOP_GETATTR(vp, &va, l->l_cred);
5263			VOP_UNLOCK(vp);
5264			kve->kve_type = KVME_TYPE_VNODE;
5265			if (error == 0) {
5266				kve->kve_vn_size = vp->v_size;
5267				kve->kve_vn_type = (int)vp->v_type;
5268				kve->kve_vn_mode = va.va_mode;
5269				kve->kve_vn_rdev = va.va_rdev;
5270				kve->kve_vn_fileid = va.va_fileid;
5271				kve->kve_vn_fsid = va.va_fsid;
5272				error = vnode_to_path(kve->kve_path,
5273				    sizeof(kve->kve_path) / 2, vp, l, p);
5274			}
5275		} else if (UVM_OBJ_IS_KERN_OBJECT(uobj)) {
5276			kve->kve_type = KVME_TYPE_KERN;
5277		} else if (UVM_OBJ_IS_DEVICE(uobj)) {
5278			kve->kve_type = KVME_TYPE_DEVICE;
5279		} else if (UVM_OBJ_IS_AOBJ(uobj)) {
5280			kve->kve_type = KVME_TYPE_ANON;
5281		} else {
5282			kve->kve_type = KVME_TYPE_OBJECT;
5283		}
5284	} else if (UVM_ET_ISSUBMAP(e)) {
5285		struct vm_map *map = e->object.sub_map;
5286		KASSERT(map != NULL);
5287		kve->kve_ref_count = map->ref_count;
5288		kve->kve_count = map->nentries;
5289		kve->kve_type = KVME_TYPE_SUBMAP;
5290	} else
5291		kve->kve_type = KVME_TYPE_UNKNOWN;
5292
5293	kve->kve_start = e->start;
5294	kve->kve_end = e->end;
5295	kve->kve_offset = e->offset;
5296	kve->kve_wired_count = e->wired_count;
5297	kve->kve_inheritance = e->inheritance;
5298	kve->kve_attributes = 0; /* unused */
5299	kve->kve_advice = e->advice;
5300#define PROT(p) (((p) & VM_PROT_READ) ? KVME_PROT_READ : 0) | \
5301	(((p) & VM_PROT_WRITE) ? KVME_PROT_WRITE : 0) | \
5302	(((p) & VM_PROT_EXECUTE) ? KVME_PROT_EXEC : 0)
5303	kve->kve_protection = PROT(e->protection);
5304	kve->kve_max_protection = PROT(e->max_protection);
5305	kve->kve_flags |= (e->etype & UVM_ET_COPYONWRITE)
5306	    ? KVME_FLAG_COW : 0;
5307	kve->kve_flags |= (e->etype & UVM_ET_NEEDSCOPY)
5308	    ? KVME_FLAG_NEEDS_COPY : 0;
5309	kve->kve_flags |= (m->flags & VM_MAP_TOPDOWN)
5310	    ? KVME_FLAG_GROWS_DOWN : KVME_FLAG_GROWS_UP;
5311	kve->kve_flags |= (m->flags & VM_MAP_PAGEABLE)
5312	    ? KVME_FLAG_PAGEABLE : 0;
5313#endif
5314	return 0;
5315}
5316
5317static int
5318fill_vmentries(struct lwp *l, pid_t pid, u_int elem_size, void *oldp,
5319    size_t *oldlenp)
5320{
5321	int error;
5322	struct proc *p;
5323	struct kinfo_vmentry *vme;
5324	struct vmspace *vm;
5325	struct vm_map *map;
5326	struct vm_map_entry *entry;
5327	char *dp;
5328	size_t count, vmesize;
5329
5330	if (elem_size == 0 || elem_size > 2 * sizeof(*vme))
5331		return EINVAL;
5332
5333	if (oldp) {
5334		if (*oldlenp > 10UL * 1024UL * 1024UL)
5335			return E2BIG;
5336		count = *oldlenp / elem_size;
5337		if (count == 0)
5338			return ENOMEM;
5339		vmesize = count * sizeof(*vme);
5340	} else
5341		vmesize = 0;
5342
5343	if ((error = proc_find_locked(l, &p, pid)) != 0)
5344		return error;
5345
5346	vme = NULL;
5347	count = 0;
5348
5349	if ((error = proc_vmspace_getref(p, &vm)) != 0)
5350		goto out;
5351
5352	map = &vm->vm_map;
5353	vm_map_lock_read(map);
5354
5355	dp = oldp;
5356	if (oldp)
5357		vme = kmem_alloc(vmesize, KM_SLEEP);
5358	for (entry = map->header.next; entry != &map->header;
5359	    entry = entry->next) {
5360		if (oldp && (dp - (char *)oldp) < vmesize) {
5361			error = fill_vmentry(l, p, &vme[count], map, entry);
5362			if (error)
5363				goto out;
5364			dp += elem_size;
5365		}
5366		count++;
5367	}
5368	vm_map_unlock_read(map);
5369	uvmspace_free(vm);
5370
5371out:
5372	if (pid != -1)
5373		mutex_exit(p->p_lock);
5374	if (error == 0) {
5375		const u_int esize = uimin(sizeof(*vme), elem_size);
5376		dp = oldp;
5377		for (size_t i = 0; i < count; i++) {
5378			if (oldp && (dp - (char *)oldp) < vmesize) {
5379				error = sysctl_copyout(l, &vme[i], dp, esize);
5380				if (error)
5381					break;
5382				dp += elem_size;
5383			} else
5384				break;
5385		}
5386		count *= elem_size;
5387		if (oldp != NULL && *oldlenp < count)
5388			error = ENOSPC;
5389		*oldlenp = count;
5390	}
5391	if (vme)
5392		kmem_free(vme, vmesize);
5393	return error;
5394}
5395
5396static int
5397sysctl_vmproc(SYSCTLFN_ARGS)
5398{
5399	int error;
5400
5401	if (namelen == 1 && name[0] == CTL_QUERY)
5402		return (sysctl_query(SYSCTLFN_CALL(rnode)));
5403
5404	if (namelen == 0)
5405		return EINVAL;
5406
5407	switch (name[0]) {
5408	case VM_PROC_MAP:
5409		if (namelen != 3)
5410			return EINVAL;
5411		sysctl_unlock();
5412		error = fill_vmentries(l, name[1], name[2], oldp, oldlenp);
5413		sysctl_relock();
5414		return error;
5415	default:
5416		return EINVAL;
5417	}
5418}
5419
5420SYSCTL_SETUP(sysctl_uvmmap_setup, "sysctl uvmmap setup")
5421{
5422
5423	sysctl_createv(clog, 0, NULL, NULL,
5424		       CTLFLAG_PERMANENT,
5425		       CTLTYPE_STRUCT, "proc",
5426		       SYSCTL_DESCR("Process vm information"),
5427		       sysctl_vmproc, 0, NULL, 0,
5428		       CTL_VM, VM_PROC, CTL_EOL);
5429#ifndef __USER_VA0_IS_SAFE
5430        sysctl_createv(clog, 0, NULL, NULL,
5431                       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5432                       CTLTYPE_INT, "user_va0_disable",
5433                       SYSCTL_DESCR("Disable VA 0"),
5434                       sysctl_user_va0_disable, 0, &user_va0_disable, 0,
5435                       CTL_VM, CTL_CREATE, CTL_EOL);
5436#endif
5437}
5438