xref: /freebsd/sys/vm/vm_kern.c (revision 8bcb0991864975618c09697b1aca10683346d9f0)
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	from: @(#)vm_kern.c	8.3 (Berkeley) 1/12/94
35  *
36  *
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62 
63 /*
64  *	Kernel memory management.
65  */
66 
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
69 
70 #include "opt_vm.h"
71 
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>		/* for ticks and hz */
75 #include <sys/domainset.h>
76 #include <sys/eventhandler.h>
77 #include <sys/lock.h>
78 #include <sys/proc.h>
79 #include <sys/malloc.h>
80 #include <sys/rwlock.h>
81 #include <sys/sysctl.h>
82 #include <sys/vmem.h>
83 #include <sys/vmmeter.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_param.h>
87 #include <vm/vm_domainset.h>
88 #include <vm/vm_kern.h>
89 #include <vm/pmap.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_object.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_pageout.h>
94 #include <vm/vm_phys.h>
95 #include <vm/vm_pagequeue.h>
96 #include <vm/vm_radix.h>
97 #include <vm/vm_extern.h>
98 #include <vm/uma.h>
99 
100 vm_map_t kernel_map;
101 vm_map_t exec_map;
102 vm_map_t pipe_map;
103 
104 const void *zero_region;
105 CTASSERT((ZERO_REGION_SIZE & PAGE_MASK) == 0);
106 
107 /* NB: Used by kernel debuggers. */
108 const u_long vm_maxuser_address = VM_MAXUSER_ADDRESS;
109 
110 u_int exec_map_entry_size;
111 u_int exec_map_entries;
112 
113 SYSCTL_ULONG(_vm, OID_AUTO, min_kernel_address, CTLFLAG_RD,
114     SYSCTL_NULL_ULONG_PTR, VM_MIN_KERNEL_ADDRESS, "Min kernel address");
115 
116 SYSCTL_ULONG(_vm, OID_AUTO, max_kernel_address, CTLFLAG_RD,
117 #if defined(__arm__) || defined(__sparc64__)
118     &vm_max_kernel_address, 0,
119 #else
120     SYSCTL_NULL_ULONG_PTR, VM_MAX_KERNEL_ADDRESS,
121 #endif
122     "Max kernel address");
123 
124 #if VM_NRESERVLEVEL > 0
125 #define	KVA_QUANTUM_SHIFT	(VM_LEVEL_0_ORDER + PAGE_SHIFT)
126 #else
127 /* On non-superpage architectures we want large import sizes. */
128 #define	KVA_QUANTUM_SHIFT	(8 + PAGE_SHIFT)
129 #endif
130 #define	KVA_QUANTUM		(1 << KVA_QUANTUM_SHIFT)
131 
132 extern void     uma_startup2(void);
133 
134 /*
135  *	kva_alloc:
136  *
137  *	Allocate a virtual address range with no underlying object and
138  *	no initial mapping to physical memory.  Any mapping from this
139  *	range to physical memory must be explicitly created prior to
140  *	its use, typically with pmap_qenter().  Any attempt to create
141  *	a mapping on demand through vm_fault() will result in a panic.
142  */
143 vm_offset_t
144 kva_alloc(vm_size_t size)
145 {
146 	vm_offset_t addr;
147 
148 	size = round_page(size);
149 	if (vmem_alloc(kernel_arena, size, M_BESTFIT | M_NOWAIT, &addr))
150 		return (0);
151 
152 	return (addr);
153 }
154 
155 /*
156  *	kva_free:
157  *
158  *	Release a region of kernel virtual memory allocated
159  *	with kva_alloc, and return the physical pages
160  *	associated with that region.
161  *
162  *	This routine may not block on kernel maps.
163  */
164 void
165 kva_free(vm_offset_t addr, vm_size_t size)
166 {
167 
168 	size = round_page(size);
169 	vmem_free(kernel_arena, addr, size);
170 }
171 
172 /*
173  *	Allocates a region from the kernel address map and physical pages
174  *	within the specified address range to the kernel object.  Creates a
175  *	wired mapping from this region to these pages, and returns the
176  *	region's starting virtual address.  The allocated pages are not
177  *	necessarily physically contiguous.  If M_ZERO is specified through the
178  *	given flags, then the pages are zeroed before they are mapped.
179  */
180 static vm_offset_t
181 kmem_alloc_attr_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
182     vm_paddr_t high, vm_memattr_t memattr)
183 {
184 	vmem_t *vmem;
185 	vm_object_t object = kernel_object;
186 	vm_offset_t addr, i, offset;
187 	vm_page_t m;
188 	int pflags, tries;
189 	vm_prot_t prot;
190 
191 	size = round_page(size);
192 	vmem = vm_dom[domain].vmd_kernel_arena;
193 	if (vmem_alloc(vmem, size, M_BESTFIT | flags, &addr))
194 		return (0);
195 	offset = addr - VM_MIN_KERNEL_ADDRESS;
196 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
197 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
198 	pflags |= VM_ALLOC_NOWAIT;
199 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
200 	VM_OBJECT_WLOCK(object);
201 	for (i = 0; i < size; i += PAGE_SIZE) {
202 		tries = 0;
203 retry:
204 		m = vm_page_alloc_contig_domain(object, atop(offset + i),
205 		    domain, pflags, 1, low, high, PAGE_SIZE, 0, memattr);
206 		if (m == NULL) {
207 			VM_OBJECT_WUNLOCK(object);
208 			if (tries < ((flags & M_NOWAIT) != 0 ? 1 : 3)) {
209 				if (!vm_page_reclaim_contig_domain(domain,
210 				    pflags, 1, low, high, PAGE_SIZE, 0) &&
211 				    (flags & M_WAITOK) != 0)
212 					vm_wait_domain(domain);
213 				VM_OBJECT_WLOCK(object);
214 				tries++;
215 				goto retry;
216 			}
217 			kmem_unback(object, addr, i);
218 			vmem_free(vmem, addr, size);
219 			return (0);
220 		}
221 		KASSERT(vm_phys_domain(m) == domain,
222 		    ("kmem_alloc_attr_domain: Domain mismatch %d != %d",
223 		    vm_phys_domain(m), domain));
224 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
225 			pmap_zero_page(m);
226 		m->valid = VM_PAGE_BITS_ALL;
227 		pmap_enter(kernel_pmap, addr + i, m, prot,
228 		    prot | PMAP_ENTER_WIRED, 0);
229 	}
230 	VM_OBJECT_WUNLOCK(object);
231 	return (addr);
232 }
233 
234 vm_offset_t
235 kmem_alloc_attr(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
236     vm_memattr_t memattr)
237 {
238 
239 	return (kmem_alloc_attr_domainset(DOMAINSET_RR(), size, flags, low,
240 	    high, memattr));
241 }
242 
243 vm_offset_t
244 kmem_alloc_attr_domainset(struct domainset *ds, vm_size_t size, int flags,
245     vm_paddr_t low, vm_paddr_t high, vm_memattr_t memattr)
246 {
247 	struct vm_domainset_iter di;
248 	vm_offset_t addr;
249 	int domain;
250 
251 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
252 	do {
253 		addr = kmem_alloc_attr_domain(domain, size, flags, low, high,
254 		    memattr);
255 		if (addr != 0)
256 			break;
257 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
258 
259 	return (addr);
260 }
261 
262 /*
263  *	Allocates a region from the kernel address map and physically
264  *	contiguous pages within the specified address range to the kernel
265  *	object.  Creates a wired mapping from this region to these pages, and
266  *	returns the region's starting virtual address.  If M_ZERO is specified
267  *	through the given flags, then the pages are zeroed before they are
268  *	mapped.
269  */
270 static vm_offset_t
271 kmem_alloc_contig_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
272     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
273     vm_memattr_t memattr)
274 {
275 	vmem_t *vmem;
276 	vm_object_t object = kernel_object;
277 	vm_offset_t addr, offset, tmp;
278 	vm_page_t end_m, m;
279 	u_long npages;
280 	int pflags, tries;
281 
282 	size = round_page(size);
283 	vmem = vm_dom[domain].vmd_kernel_arena;
284 	if (vmem_alloc(vmem, size, flags | M_BESTFIT, &addr))
285 		return (0);
286 	offset = addr - VM_MIN_KERNEL_ADDRESS;
287 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
288 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
289 	pflags |= VM_ALLOC_NOWAIT;
290 	npages = atop(size);
291 	VM_OBJECT_WLOCK(object);
292 	tries = 0;
293 retry:
294 	m = vm_page_alloc_contig_domain(object, atop(offset), domain, pflags,
295 	    npages, low, high, alignment, boundary, memattr);
296 	if (m == NULL) {
297 		VM_OBJECT_WUNLOCK(object);
298 		if (tries < ((flags & M_NOWAIT) != 0 ? 1 : 3)) {
299 			if (!vm_page_reclaim_contig_domain(domain, pflags,
300 			    npages, low, high, alignment, boundary) &&
301 			    (flags & M_WAITOK) != 0)
302 				vm_wait_domain(domain);
303 			VM_OBJECT_WLOCK(object);
304 			tries++;
305 			goto retry;
306 		}
307 		vmem_free(vmem, addr, size);
308 		return (0);
309 	}
310 	KASSERT(vm_phys_domain(m) == domain,
311 	    ("kmem_alloc_contig_domain: Domain mismatch %d != %d",
312 	    vm_phys_domain(m), domain));
313 	end_m = m + npages;
314 	tmp = addr;
315 	for (; m < end_m; m++) {
316 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
317 			pmap_zero_page(m);
318 		m->valid = VM_PAGE_BITS_ALL;
319 		pmap_enter(kernel_pmap, tmp, m, VM_PROT_RW,
320 		    VM_PROT_RW | PMAP_ENTER_WIRED, 0);
321 		tmp += PAGE_SIZE;
322 	}
323 	VM_OBJECT_WUNLOCK(object);
324 	return (addr);
325 }
326 
327 vm_offset_t
328 kmem_alloc_contig(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
329     u_long alignment, vm_paddr_t boundary, vm_memattr_t memattr)
330 {
331 
332 	return (kmem_alloc_contig_domainset(DOMAINSET_RR(), size, flags, low,
333 	    high, alignment, boundary, memattr));
334 }
335 
336 vm_offset_t
337 kmem_alloc_contig_domainset(struct domainset *ds, vm_size_t size, int flags,
338     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
339     vm_memattr_t memattr)
340 {
341 	struct vm_domainset_iter di;
342 	vm_offset_t addr;
343 	int domain;
344 
345 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
346 	do {
347 		addr = kmem_alloc_contig_domain(domain, size, flags, low, high,
348 		    alignment, boundary, memattr);
349 		if (addr != 0)
350 			break;
351 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
352 
353 	return (addr);
354 }
355 
356 /*
357  *	kmem_suballoc:
358  *
359  *	Allocates a map to manage a subrange
360  *	of the kernel virtual address space.
361  *
362  *	Arguments are as follows:
363  *
364  *	parent		Map to take range from
365  *	min, max	Returned endpoints of map
366  *	size		Size of range to find
367  *	superpage_align	Request that min is superpage aligned
368  */
369 vm_map_t
370 kmem_suballoc(vm_map_t parent, vm_offset_t *min, vm_offset_t *max,
371     vm_size_t size, boolean_t superpage_align)
372 {
373 	int ret;
374 	vm_map_t result;
375 
376 	size = round_page(size);
377 
378 	*min = vm_map_min(parent);
379 	ret = vm_map_find(parent, NULL, 0, min, size, 0, superpage_align ?
380 	    VMFS_SUPER_SPACE : VMFS_ANY_SPACE, VM_PROT_ALL, VM_PROT_ALL,
381 	    MAP_ACC_NO_CHARGE);
382 	if (ret != KERN_SUCCESS)
383 		panic("kmem_suballoc: bad status return of %d", ret);
384 	*max = *min + size;
385 	result = vm_map_create(vm_map_pmap(parent), *min, *max);
386 	if (result == NULL)
387 		panic("kmem_suballoc: cannot create submap");
388 	if (vm_map_submap(parent, *min, *max, result) != KERN_SUCCESS)
389 		panic("kmem_suballoc: unable to change range to submap");
390 	return (result);
391 }
392 
393 /*
394  *	kmem_malloc_domain:
395  *
396  *	Allocate wired-down pages in the kernel's address space.
397  */
398 static vm_offset_t
399 kmem_malloc_domain(int domain, vm_size_t size, int flags)
400 {
401 	vmem_t *arena;
402 	vm_offset_t addr;
403 	int rv;
404 
405 #if VM_NRESERVLEVEL > 0
406 	if (__predict_true((flags & M_EXEC) == 0))
407 		arena = vm_dom[domain].vmd_kernel_arena;
408 	else
409 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
410 #else
411 	arena = vm_dom[domain].vmd_kernel_arena;
412 #endif
413 	size = round_page(size);
414 	if (vmem_alloc(arena, size, flags | M_BESTFIT, &addr))
415 		return (0);
416 
417 	rv = kmem_back_domain(domain, kernel_object, addr, size, flags);
418 	if (rv != KERN_SUCCESS) {
419 		vmem_free(arena, addr, size);
420 		return (0);
421 	}
422 	return (addr);
423 }
424 
425 vm_offset_t
426 kmem_malloc(vm_size_t size, int flags)
427 {
428 
429 	return (kmem_malloc_domainset(DOMAINSET_RR(), size, flags));
430 }
431 
432 vm_offset_t
433 kmem_malloc_domainset(struct domainset *ds, vm_size_t size, int flags)
434 {
435 	struct vm_domainset_iter di;
436 	vm_offset_t addr;
437 	int domain;
438 
439 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
440 	do {
441 		addr = kmem_malloc_domain(domain, size, flags);
442 		if (addr != 0)
443 			break;
444 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
445 
446 	return (addr);
447 }
448 
449 /*
450  *	kmem_back_domain:
451  *
452  *	Allocate physical pages from the specified domain for the specified
453  *	virtual address range.
454  */
455 int
456 kmem_back_domain(int domain, vm_object_t object, vm_offset_t addr,
457     vm_size_t size, int flags)
458 {
459 	vm_offset_t offset, i;
460 	vm_page_t m, mpred;
461 	vm_prot_t prot;
462 	int pflags;
463 
464 	KASSERT(object == kernel_object,
465 	    ("kmem_back_domain: only supports kernel object."));
466 
467 	offset = addr - VM_MIN_KERNEL_ADDRESS;
468 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
469 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
470 	if (flags & M_WAITOK)
471 		pflags |= VM_ALLOC_WAITFAIL;
472 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
473 
474 	i = 0;
475 	VM_OBJECT_WLOCK(object);
476 retry:
477 	mpred = vm_radix_lookup_le(&object->rtree, atop(offset + i));
478 	for (; i < size; i += PAGE_SIZE, mpred = m) {
479 		m = vm_page_alloc_domain_after(object, atop(offset + i),
480 		    domain, pflags, mpred);
481 
482 		/*
483 		 * Ran out of space, free everything up and return. Don't need
484 		 * to lock page queues here as we know that the pages we got
485 		 * aren't on any queues.
486 		 */
487 		if (m == NULL) {
488 			if ((flags & M_NOWAIT) == 0)
489 				goto retry;
490 			VM_OBJECT_WUNLOCK(object);
491 			kmem_unback(object, addr, i);
492 			return (KERN_NO_SPACE);
493 		}
494 		KASSERT(vm_phys_domain(m) == domain,
495 		    ("kmem_back_domain: Domain mismatch %d != %d",
496 		    vm_phys_domain(m), domain));
497 		if (flags & M_ZERO && (m->flags & PG_ZERO) == 0)
498 			pmap_zero_page(m);
499 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
500 		    ("kmem_malloc: page %p is managed", m));
501 		m->valid = VM_PAGE_BITS_ALL;
502 		pmap_enter(kernel_pmap, addr + i, m, prot,
503 		    prot | PMAP_ENTER_WIRED, 0);
504 #if VM_NRESERVLEVEL > 0
505 		if (__predict_false((prot & VM_PROT_EXECUTE) != 0))
506 			m->oflags |= VPO_KMEM_EXEC;
507 #endif
508 	}
509 	VM_OBJECT_WUNLOCK(object);
510 
511 	return (KERN_SUCCESS);
512 }
513 
514 /*
515  *	kmem_back:
516  *
517  *	Allocate physical pages for the specified virtual address range.
518  */
519 int
520 kmem_back(vm_object_t object, vm_offset_t addr, vm_size_t size, int flags)
521 {
522 	vm_offset_t end, next, start;
523 	int domain, rv;
524 
525 	KASSERT(object == kernel_object,
526 	    ("kmem_back: only supports kernel object."));
527 
528 	for (start = addr, end = addr + size; addr < end; addr = next) {
529 		/*
530 		 * We must ensure that pages backing a given large virtual page
531 		 * all come from the same physical domain.
532 		 */
533 		if (vm_ndomains > 1) {
534 			domain = (addr >> KVA_QUANTUM_SHIFT) % vm_ndomains;
535 			while (VM_DOMAIN_EMPTY(domain))
536 				domain++;
537 			next = roundup2(addr + 1, KVA_QUANTUM);
538 			if (next > end || next < start)
539 				next = end;
540 		} else {
541 			domain = 0;
542 			next = end;
543 		}
544 		rv = kmem_back_domain(domain, object, addr, next - addr, flags);
545 		if (rv != KERN_SUCCESS) {
546 			kmem_unback(object, start, addr - start);
547 			break;
548 		}
549 	}
550 	return (rv);
551 }
552 
553 /*
554  *	kmem_unback:
555  *
556  *	Unmap and free the physical pages underlying the specified virtual
557  *	address range.
558  *
559  *	A physical page must exist within the specified object at each index
560  *	that is being unmapped.
561  */
562 static struct vmem *
563 _kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
564 {
565 	struct vmem *arena;
566 	vm_page_t m, next;
567 	vm_offset_t end, offset;
568 	int domain;
569 
570 	KASSERT(object == kernel_object,
571 	    ("kmem_unback: only supports kernel object."));
572 
573 	if (size == 0)
574 		return (NULL);
575 	pmap_remove(kernel_pmap, addr, addr + size);
576 	offset = addr - VM_MIN_KERNEL_ADDRESS;
577 	end = offset + size;
578 	VM_OBJECT_WLOCK(object);
579 	m = vm_page_lookup(object, atop(offset));
580 	domain = vm_phys_domain(m);
581 #if VM_NRESERVLEVEL > 0
582 	if (__predict_true((m->oflags & VPO_KMEM_EXEC) == 0))
583 		arena = vm_dom[domain].vmd_kernel_arena;
584 	else
585 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
586 #else
587 	arena = vm_dom[domain].vmd_kernel_arena;
588 #endif
589 	for (; offset < end; offset += PAGE_SIZE, m = next) {
590 		next = vm_page_next(m);
591 		vm_page_busy_acquire(m, 0);
592 		vm_page_unwire_noq(m);
593 		vm_page_free(m);
594 	}
595 	VM_OBJECT_WUNLOCK(object);
596 
597 	return (arena);
598 }
599 
600 void
601 kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
602 {
603 
604 	(void)_kmem_unback(object, addr, size);
605 }
606 
607 /*
608  *	kmem_free:
609  *
610  *	Free memory allocated with kmem_malloc.  The size must match the
611  *	original allocation.
612  */
613 void
614 kmem_free(vm_offset_t addr, vm_size_t size)
615 {
616 	struct vmem *arena;
617 
618 	size = round_page(size);
619 	arena = _kmem_unback(kernel_object, addr, size);
620 	if (arena != NULL)
621 		vmem_free(arena, addr, size);
622 }
623 
624 /*
625  *	kmap_alloc_wait:
626  *
627  *	Allocates pageable memory from a sub-map of the kernel.  If the submap
628  *	has no room, the caller sleeps waiting for more memory in the submap.
629  *
630  *	This routine may block.
631  */
632 vm_offset_t
633 kmap_alloc_wait(vm_map_t map, vm_size_t size)
634 {
635 	vm_offset_t addr;
636 
637 	size = round_page(size);
638 	if (!swap_reserve(size))
639 		return (0);
640 
641 	for (;;) {
642 		/*
643 		 * To make this work for more than one map, use the map's lock
644 		 * to lock out sleepers/wakers.
645 		 */
646 		vm_map_lock(map);
647 		addr = vm_map_findspace(map, vm_map_min(map), size);
648 		if (addr + size <= vm_map_max(map))
649 			break;
650 		/* no space now; see if we can ever get space */
651 		if (vm_map_max(map) - vm_map_min(map) < size) {
652 			vm_map_unlock(map);
653 			swap_release(size);
654 			return (0);
655 		}
656 		map->needs_wakeup = TRUE;
657 		vm_map_unlock_and_wait(map, 0);
658 	}
659 	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_RW, VM_PROT_RW,
660 	    MAP_ACC_CHARGED);
661 	vm_map_unlock(map);
662 	return (addr);
663 }
664 
665 /*
666  *	kmap_free_wakeup:
667  *
668  *	Returns memory to a submap of the kernel, and wakes up any processes
669  *	waiting for memory in that map.
670  */
671 void
672 kmap_free_wakeup(vm_map_t map, vm_offset_t addr, vm_size_t size)
673 {
674 
675 	vm_map_lock(map);
676 	(void) vm_map_delete(map, trunc_page(addr), round_page(addr + size));
677 	if (map->needs_wakeup) {
678 		map->needs_wakeup = FALSE;
679 		vm_map_wakeup(map);
680 	}
681 	vm_map_unlock(map);
682 }
683 
684 void
685 kmem_init_zero_region(void)
686 {
687 	vm_offset_t addr, i;
688 	vm_page_t m;
689 
690 	/*
691 	 * Map a single physical page of zeros to a larger virtual range.
692 	 * This requires less looping in places that want large amounts of
693 	 * zeros, while not using much more physical resources.
694 	 */
695 	addr = kva_alloc(ZERO_REGION_SIZE);
696 	m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
697 	    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
698 	if ((m->flags & PG_ZERO) == 0)
699 		pmap_zero_page(m);
700 	for (i = 0; i < ZERO_REGION_SIZE; i += PAGE_SIZE)
701 		pmap_qenter(addr + i, &m, 1);
702 	pmap_protect(kernel_pmap, addr, addr + ZERO_REGION_SIZE, VM_PROT_READ);
703 
704 	zero_region = (const void *)addr;
705 }
706 
707 /*
708  * Import KVA from the kernel map into the kernel arena.
709  */
710 static int
711 kva_import(void *unused, vmem_size_t size, int flags, vmem_addr_t *addrp)
712 {
713 	vm_offset_t addr;
714 	int result;
715 
716 	KASSERT((size % KVA_QUANTUM) == 0,
717 	    ("kva_import: Size %jd is not a multiple of %d",
718 	    (intmax_t)size, (int)KVA_QUANTUM));
719 	addr = vm_map_min(kernel_map);
720 	result = vm_map_find(kernel_map, NULL, 0, &addr, size, 0,
721 	    VMFS_SUPER_SPACE, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
722 	if (result != KERN_SUCCESS)
723                 return (ENOMEM);
724 
725 	*addrp = addr;
726 
727 	return (0);
728 }
729 
730 /*
731  * Import KVA from a parent arena into a per-domain arena.  Imports must be
732  * KVA_QUANTUM-aligned and a multiple of KVA_QUANTUM in size.
733  */
734 static int
735 kva_import_domain(void *arena, vmem_size_t size, int flags, vmem_addr_t *addrp)
736 {
737 
738 	KASSERT((size % KVA_QUANTUM) == 0,
739 	    ("kva_import_domain: Size %jd is not a multiple of %d",
740 	    (intmax_t)size, (int)KVA_QUANTUM));
741 	return (vmem_xalloc(arena, size, KVA_QUANTUM, 0, 0, VMEM_ADDR_MIN,
742 	    VMEM_ADDR_MAX, flags, addrp));
743 }
744 
745 /*
746  * 	kmem_init:
747  *
748  *	Create the kernel map; insert a mapping covering kernel text,
749  *	data, bss, and all space allocated thus far (`boostrap' data).  The
750  *	new map will thus map the range between VM_MIN_KERNEL_ADDRESS and
751  *	`start' as allocated, and the range between `start' and `end' as free.
752  *	Create the kernel vmem arena and its per-domain children.
753  */
754 void
755 kmem_init(vm_offset_t start, vm_offset_t end)
756 {
757 	vm_map_t m;
758 	int domain;
759 
760 	m = vm_map_create(kernel_pmap, VM_MIN_KERNEL_ADDRESS, end);
761 	m->system_map = 1;
762 	vm_map_lock(m);
763 	/* N.B.: cannot use kgdb to debug, starting with this assignment ... */
764 	kernel_map = m;
765 	(void)vm_map_insert(m, NULL, 0,
766 #ifdef __amd64__
767 	    KERNBASE,
768 #else
769 	    VM_MIN_KERNEL_ADDRESS,
770 #endif
771 	    start, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
772 	/* ... and ending with the completion of the above `insert' */
773 
774 #ifdef __amd64__
775 	/*
776 	 * Mark KVA used for the page array as allocated.  Other platforms
777 	 * that handle vm_page_array allocation can simply adjust virtual_avail
778 	 * instead.
779 	 */
780 	(void)vm_map_insert(m, NULL, 0, (vm_offset_t)vm_page_array,
781 	    (vm_offset_t)vm_page_array + round_2mpage(vm_page_array_size *
782 	    sizeof(struct vm_page)),
783 	    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
784 #endif
785 	vm_map_unlock(m);
786 
787 	/*
788 	 * Initialize the kernel_arena.  This can grow on demand.
789 	 */
790 	vmem_init(kernel_arena, "kernel arena", 0, 0, PAGE_SIZE, 0, 0);
791 	vmem_set_import(kernel_arena, kva_import, NULL, NULL, KVA_QUANTUM);
792 
793 	for (domain = 0; domain < vm_ndomains; domain++) {
794 		/*
795 		 * Initialize the per-domain arenas.  These are used to color
796 		 * the KVA space in a way that ensures that virtual large pages
797 		 * are backed by memory from the same physical domain,
798 		 * maximizing the potential for superpage promotion.
799 		 */
800 		vm_dom[domain].vmd_kernel_arena = vmem_create(
801 		    "kernel arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
802 		vmem_set_import(vm_dom[domain].vmd_kernel_arena,
803 		    kva_import_domain, NULL, kernel_arena, KVA_QUANTUM);
804 
805 		/*
806 		 * In architectures with superpages, maintain separate arenas
807 		 * for allocations with permissions that differ from the
808 		 * "standard" read/write permissions used for kernel memory,
809 		 * so as not to inhibit superpage promotion.
810 		 */
811 #if VM_NRESERVLEVEL > 0
812 		vm_dom[domain].vmd_kernel_rwx_arena = vmem_create(
813 		    "kernel rwx arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
814 		vmem_set_import(vm_dom[domain].vmd_kernel_rwx_arena,
815 		    kva_import_domain, (vmem_release_t *)vmem_xfree,
816 		    kernel_arena, KVA_QUANTUM);
817 #endif
818 	}
819 
820 	/*
821 	 * This must be the very first call so that the virtual address
822 	 * space used for early allocations is properly marked used in
823 	 * the map.
824 	 */
825 	uma_startup2();
826 }
827 
828 /*
829  *	kmem_bootstrap_free:
830  *
831  *	Free pages backing preloaded data (e.g., kernel modules) to the
832  *	system.  Currently only supported on platforms that create a
833  *	vm_phys segment for preloaded data.
834  */
835 void
836 kmem_bootstrap_free(vm_offset_t start, vm_size_t size)
837 {
838 #if defined(__i386__) || defined(__amd64__)
839 	struct vm_domain *vmd;
840 	vm_offset_t end, va;
841 	vm_paddr_t pa;
842 	vm_page_t m;
843 
844 	end = trunc_page(start + size);
845 	start = round_page(start);
846 
847 #ifdef __amd64__
848 	/*
849 	 * Preloaded files do not have execute permissions by default on amd64.
850 	 * Restore the default permissions to ensure that the direct map alias
851 	 * is updated.
852 	 */
853 	pmap_change_prot(start, end - start, VM_PROT_RW);
854 #endif
855 	for (va = start; va < end; va += PAGE_SIZE) {
856 		pa = pmap_kextract(va);
857 		m = PHYS_TO_VM_PAGE(pa);
858 
859 		vmd = vm_pagequeue_domain(m);
860 		vm_domain_free_lock(vmd);
861 		vm_phys_free_pages(m, 0);
862 		vm_domain_free_unlock(vmd);
863 
864 		vm_domain_freecnt_inc(vmd, 1);
865 		vm_cnt.v_page_count++;
866 	}
867 	pmap_remove(kernel_pmap, start, end);
868 	(void)vmem_add(kernel_arena, start, end - start, M_WAITOK);
869 #endif
870 }
871 
872 /*
873  * Allow userspace to directly trigger the VM drain routine for testing
874  * purposes.
875  */
876 static int
877 debug_vm_lowmem(SYSCTL_HANDLER_ARGS)
878 {
879 	int error, i;
880 
881 	i = 0;
882 	error = sysctl_handle_int(oidp, &i, 0, req);
883 	if (error)
884 		return (error);
885 	if ((i & ~(VM_LOW_KMEM | VM_LOW_PAGES)) != 0)
886 		return (EINVAL);
887 	if (i != 0)
888 		EVENTHANDLER_INVOKE(vm_lowmem, i);
889 	return (0);
890 }
891 
892 SYSCTL_PROC(_debug, OID_AUTO, vm_lowmem, CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0,
893     debug_vm_lowmem, "I", "set to trigger vm_lowmem event with given flags");
894