xref: /freebsd/sys/vm/vm_kern.c (revision bc5304a006238115291e7568583632889dffbab9)
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/asan.h>
75 #include <sys/domainset.h>
76 #include <sys/eventhandler.h>
77 #include <sys/kernel.h>
78 #include <sys/lock.h>
79 #include <sys/malloc.h>
80 #include <sys/proc.h>
81 #include <sys/rwlock.h>
82 #include <sys/sysctl.h>
83 #include <sys/vmem.h>
84 #include <sys/vmmeter.h>
85 
86 #include <vm/vm.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_domainset.h>
89 #include <vm/vm_kern.h>
90 #include <vm/pmap.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pageout.h>
95 #include <vm/vm_pagequeue.h>
96 #include <vm/vm_phys.h>
97 #include <vm/vm_radix.h>
98 #include <vm/vm_extern.h>
99 #include <vm/uma.h>
100 
101 struct vm_map kernel_map_store;
102 struct vm_map exec_map_store;
103 struct vm_map pipe_map_store;
104 
105 const void *zero_region;
106 CTASSERT((ZERO_REGION_SIZE & PAGE_MASK) == 0);
107 
108 /* NB: Used by kernel debuggers. */
109 const u_long vm_maxuser_address = VM_MAXUSER_ADDRESS;
110 
111 u_int exec_map_entry_size;
112 u_int exec_map_entries;
113 
114 SYSCTL_ULONG(_vm, OID_AUTO, min_kernel_address, CTLFLAG_RD,
115     SYSCTL_NULL_ULONG_PTR, VM_MIN_KERNEL_ADDRESS, "Min kernel address");
116 
117 SYSCTL_ULONG(_vm, OID_AUTO, max_kernel_address, CTLFLAG_RD,
118 #if defined(__arm__)
119     &vm_max_kernel_address, 0,
120 #else
121     SYSCTL_NULL_ULONG_PTR, VM_MAX_KERNEL_ADDRESS,
122 #endif
123     "Max kernel address");
124 
125 #if VM_NRESERVLEVEL > 0
126 #define	KVA_QUANTUM_SHIFT	(VM_LEVEL_0_ORDER + PAGE_SHIFT)
127 #else
128 /* On non-superpage architectures we want large import sizes. */
129 #define	KVA_QUANTUM_SHIFT	(8 + PAGE_SHIFT)
130 #endif
131 #define	KVA_QUANTUM		(1ul << KVA_QUANTUM_SHIFT)
132 #define	KVA_NUMA_IMPORT_QUANTUM	(KVA_QUANTUM * 128)
133 
134 extern void     uma_startup2(void);
135 
136 /*
137  *	kva_alloc:
138  *
139  *	Allocate a virtual address range with no underlying object and
140  *	no initial mapping to physical memory.  Any mapping from this
141  *	range to physical memory must be explicitly created prior to
142  *	its use, typically with pmap_qenter().  Any attempt to create
143  *	a mapping on demand through vm_fault() will result in a panic.
144  */
145 vm_offset_t
146 kva_alloc(vm_size_t size)
147 {
148 	vm_offset_t addr;
149 
150 	size = round_page(size);
151 	if (vmem_alloc(kernel_arena, size, M_BESTFIT | M_NOWAIT, &addr))
152 		return (0);
153 
154 	return (addr);
155 }
156 
157 /*
158  *	kva_free:
159  *
160  *	Release a region of kernel virtual memory allocated
161  *	with kva_alloc, and return the physical pages
162  *	associated with that region.
163  *
164  *	This routine may not block on kernel maps.
165  */
166 void
167 kva_free(vm_offset_t addr, vm_size_t size)
168 {
169 
170 	size = round_page(size);
171 	vmem_free(kernel_arena, addr, size);
172 }
173 
174 static vm_page_t
175 kmem_alloc_contig_pages(vm_object_t object, vm_pindex_t pindex, int domain,
176     int pflags, u_long npages, vm_paddr_t low, vm_paddr_t high,
177     u_long alignment, vm_paddr_t boundary, vm_memattr_t memattr)
178 {
179 	vm_page_t m;
180 	int tries;
181 	bool wait, reclaim;
182 
183 	VM_OBJECT_ASSERT_WLOCKED(object);
184 
185 	/* Disallow an invalid combination of flags. */
186 	MPASS((pflags & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
187 	    (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM));
188 
189 	wait = (pflags & VM_ALLOC_WAITOK) != 0;
190 	reclaim = (pflags & VM_ALLOC_NORECLAIM) == 0;
191 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
192 	pflags |= VM_ALLOC_NOWAIT;
193 	for (tries = wait ? 3 : 1;; tries--) {
194 		m = vm_page_alloc_contig_domain(object, pindex, domain, pflags,
195 		    npages, low, high, alignment, boundary, memattr);
196 		if (m != NULL || tries == 0 || !reclaim)
197 			break;
198 
199 		VM_OBJECT_WUNLOCK(object);
200 		if (!vm_page_reclaim_contig_domain(domain, pflags, npages,
201 		    low, high, alignment, boundary) && wait)
202 			vm_wait_domain(domain);
203 		VM_OBJECT_WLOCK(object);
204 	}
205 	return (m);
206 }
207 
208 /*
209  *	Allocates a region from the kernel address map and physical pages
210  *	within the specified address range to the kernel object.  Creates a
211  *	wired mapping from this region to these pages, and returns the
212  *	region's starting virtual address.  The allocated pages are not
213  *	necessarily physically contiguous.  If M_ZERO is specified through the
214  *	given flags, then the pages are zeroed before they are mapped.
215  */
216 static vm_offset_t
217 kmem_alloc_attr_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
218     vm_paddr_t high, vm_memattr_t memattr)
219 {
220 	vmem_t *vmem;
221 	vm_object_t object;
222 	vm_offset_t addr, i, offset;
223 	vm_page_t m;
224 	vm_size_t asize;
225 	int pflags;
226 	vm_prot_t prot;
227 
228 	object = kernel_object;
229 	asize = round_page(size);
230 	vmem = vm_dom[domain].vmd_kernel_arena;
231 	if (vmem_alloc(vmem, asize, M_BESTFIT | flags, &addr))
232 		return (0);
233 	offset = addr - VM_MIN_KERNEL_ADDRESS;
234 	pflags = malloc2vm_flags(flags) | VM_ALLOC_WIRED;
235 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
236 	VM_OBJECT_WLOCK(object);
237 	for (i = 0; i < asize; i += PAGE_SIZE) {
238 		m = kmem_alloc_contig_pages(object, atop(offset + i),
239 		    domain, pflags, 1, low, high, PAGE_SIZE, 0, memattr);
240 		if (m == NULL) {
241 			VM_OBJECT_WUNLOCK(object);
242 			kmem_unback(object, addr, i);
243 			vmem_free(vmem, addr, asize);
244 			return (0);
245 		}
246 		KASSERT(vm_page_domain(m) == domain,
247 		    ("kmem_alloc_attr_domain: Domain mismatch %d != %d",
248 		    vm_page_domain(m), domain));
249 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
250 			pmap_zero_page(m);
251 		vm_page_valid(m);
252 		pmap_enter(kernel_pmap, addr + i, m, prot,
253 		    prot | PMAP_ENTER_WIRED, 0);
254 	}
255 	VM_OBJECT_WUNLOCK(object);
256 	kasan_mark((void *)addr, size, asize, KASAN_KMEM_REDZONE);
257 	return (addr);
258 }
259 
260 vm_offset_t
261 kmem_alloc_attr(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
262     vm_memattr_t memattr)
263 {
264 
265 	return (kmem_alloc_attr_domainset(DOMAINSET_RR(), size, flags, low,
266 	    high, memattr));
267 }
268 
269 vm_offset_t
270 kmem_alloc_attr_domainset(struct domainset *ds, vm_size_t size, int flags,
271     vm_paddr_t low, vm_paddr_t high, vm_memattr_t memattr)
272 {
273 	struct vm_domainset_iter di;
274 	vm_offset_t addr;
275 	int domain;
276 
277 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
278 	do {
279 		addr = kmem_alloc_attr_domain(domain, size, flags, low, high,
280 		    memattr);
281 		if (addr != 0)
282 			break;
283 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
284 
285 	return (addr);
286 }
287 
288 /*
289  *	Allocates a region from the kernel address map and physically
290  *	contiguous pages within the specified address range to the kernel
291  *	object.  Creates a wired mapping from this region to these pages, and
292  *	returns the region's starting virtual address.  If M_ZERO is specified
293  *	through the given flags, then the pages are zeroed before they are
294  *	mapped.
295  */
296 static vm_offset_t
297 kmem_alloc_contig_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
298     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
299     vm_memattr_t memattr)
300 {
301 	vmem_t *vmem;
302 	vm_object_t object;
303 	vm_offset_t addr, offset, tmp;
304 	vm_page_t end_m, m;
305 	vm_size_t asize;
306 	u_long npages;
307 	int pflags;
308 
309 	object = kernel_object;
310 	asize = round_page(size);
311 	vmem = vm_dom[domain].vmd_kernel_arena;
312 	if (vmem_alloc(vmem, asize, flags | M_BESTFIT, &addr))
313 		return (0);
314 	offset = addr - VM_MIN_KERNEL_ADDRESS;
315 	pflags = malloc2vm_flags(flags) | VM_ALLOC_WIRED;
316 	npages = atop(asize);
317 	VM_OBJECT_WLOCK(object);
318 	m = kmem_alloc_contig_pages(object, atop(offset), domain,
319 	    pflags, npages, low, high, alignment, boundary, memattr);
320 	if (m == NULL) {
321 		VM_OBJECT_WUNLOCK(object);
322 		vmem_free(vmem, addr, asize);
323 		return (0);
324 	}
325 	KASSERT(vm_page_domain(m) == domain,
326 	    ("kmem_alloc_contig_domain: Domain mismatch %d != %d",
327 	    vm_page_domain(m), domain));
328 	end_m = m + npages;
329 	tmp = addr;
330 	for (; m < end_m; m++) {
331 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
332 			pmap_zero_page(m);
333 		vm_page_valid(m);
334 		pmap_enter(kernel_pmap, tmp, m, VM_PROT_RW,
335 		    VM_PROT_RW | PMAP_ENTER_WIRED, 0);
336 		tmp += PAGE_SIZE;
337 	}
338 	VM_OBJECT_WUNLOCK(object);
339 	kasan_mark((void *)addr, size, asize, KASAN_KMEM_REDZONE);
340 	return (addr);
341 }
342 
343 vm_offset_t
344 kmem_alloc_contig(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
345     u_long alignment, vm_paddr_t boundary, vm_memattr_t memattr)
346 {
347 
348 	return (kmem_alloc_contig_domainset(DOMAINSET_RR(), size, flags, low,
349 	    high, alignment, boundary, memattr));
350 }
351 
352 vm_offset_t
353 kmem_alloc_contig_domainset(struct domainset *ds, vm_size_t size, int flags,
354     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
355     vm_memattr_t memattr)
356 {
357 	struct vm_domainset_iter di;
358 	vm_offset_t addr;
359 	int domain;
360 
361 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
362 	do {
363 		addr = kmem_alloc_contig_domain(domain, size, flags, low, high,
364 		    alignment, boundary, memattr);
365 		if (addr != 0)
366 			break;
367 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
368 
369 	return (addr);
370 }
371 
372 /*
373  *	kmem_subinit:
374  *
375  *	Initializes a map to manage a subrange
376  *	of the kernel virtual address space.
377  *
378  *	Arguments are as follows:
379  *
380  *	parent		Map to take range from
381  *	min, max	Returned endpoints of map
382  *	size		Size of range to find
383  *	superpage_align	Request that min is superpage aligned
384  */
385 void
386 kmem_subinit(vm_map_t map, vm_map_t parent, vm_offset_t *min, vm_offset_t *max,
387     vm_size_t size, bool superpage_align)
388 {
389 	int ret;
390 
391 	size = round_page(size);
392 
393 	*min = vm_map_min(parent);
394 	ret = vm_map_find(parent, NULL, 0, min, size, 0, superpage_align ?
395 	    VMFS_SUPER_SPACE : VMFS_ANY_SPACE, VM_PROT_ALL, VM_PROT_ALL,
396 	    MAP_ACC_NO_CHARGE);
397 	if (ret != KERN_SUCCESS)
398 		panic("kmem_subinit: bad status return of %d", ret);
399 	*max = *min + size;
400 	vm_map_init(map, vm_map_pmap(parent), *min, *max);
401 	if (vm_map_submap(parent, *min, *max, map) != KERN_SUCCESS)
402 		panic("kmem_subinit: unable to change range to submap");
403 }
404 
405 /*
406  *	kmem_malloc_domain:
407  *
408  *	Allocate wired-down pages in the kernel's address space.
409  */
410 static vm_offset_t
411 kmem_malloc_domain(int domain, vm_size_t size, int flags)
412 {
413 	vmem_t *arena;
414 	vm_offset_t addr;
415 	vm_size_t asize;
416 	int rv;
417 
418 	if (__predict_true((flags & M_EXEC) == 0))
419 		arena = vm_dom[domain].vmd_kernel_arena;
420 	else
421 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
422 	asize = round_page(size);
423 	if (vmem_alloc(arena, asize, flags | M_BESTFIT, &addr))
424 		return (0);
425 
426 	rv = kmem_back_domain(domain, kernel_object, addr, asize, flags);
427 	if (rv != KERN_SUCCESS) {
428 		vmem_free(arena, addr, asize);
429 		return (0);
430 	}
431 	kasan_mark((void *)addr, size, asize, KASAN_KMEM_REDZONE);
432 	return (addr);
433 }
434 
435 vm_offset_t
436 kmem_malloc(vm_size_t size, int flags)
437 {
438 
439 	return (kmem_malloc_domainset(DOMAINSET_RR(), size, flags));
440 }
441 
442 vm_offset_t
443 kmem_malloc_domainset(struct domainset *ds, vm_size_t size, int flags)
444 {
445 	struct vm_domainset_iter di;
446 	vm_offset_t addr;
447 	int domain;
448 
449 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
450 	do {
451 		addr = kmem_malloc_domain(domain, size, flags);
452 		if (addr != 0)
453 			break;
454 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
455 
456 	return (addr);
457 }
458 
459 /*
460  *	kmem_back_domain:
461  *
462  *	Allocate physical pages from the specified domain for the specified
463  *	virtual address range.
464  */
465 int
466 kmem_back_domain(int domain, vm_object_t object, vm_offset_t addr,
467     vm_size_t size, int flags)
468 {
469 	vm_offset_t offset, i;
470 	vm_page_t m, mpred;
471 	vm_prot_t prot;
472 	int pflags;
473 
474 	KASSERT(object == kernel_object,
475 	    ("kmem_back_domain: only supports kernel object."));
476 
477 	offset = addr - VM_MIN_KERNEL_ADDRESS;
478 	pflags = malloc2vm_flags(flags) | VM_ALLOC_WIRED;
479 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
480 	if (flags & M_WAITOK)
481 		pflags |= VM_ALLOC_WAITFAIL;
482 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
483 
484 	i = 0;
485 	VM_OBJECT_WLOCK(object);
486 retry:
487 	mpred = vm_radix_lookup_le(&object->rtree, atop(offset + i));
488 	for (; i < size; i += PAGE_SIZE, mpred = m) {
489 		m = vm_page_alloc_domain_after(object, atop(offset + i),
490 		    domain, pflags, mpred);
491 
492 		/*
493 		 * Ran out of space, free everything up and return. Don't need
494 		 * to lock page queues here as we know that the pages we got
495 		 * aren't on any queues.
496 		 */
497 		if (m == NULL) {
498 			if ((flags & M_NOWAIT) == 0)
499 				goto retry;
500 			VM_OBJECT_WUNLOCK(object);
501 			kmem_unback(object, addr, i);
502 			return (KERN_NO_SPACE);
503 		}
504 		KASSERT(vm_page_domain(m) == domain,
505 		    ("kmem_back_domain: Domain mismatch %d != %d",
506 		    vm_page_domain(m), domain));
507 		if (flags & M_ZERO && (m->flags & PG_ZERO) == 0)
508 			pmap_zero_page(m);
509 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
510 		    ("kmem_malloc: page %p is managed", m));
511 		vm_page_valid(m);
512 		pmap_enter(kernel_pmap, addr + i, m, prot,
513 		    prot | PMAP_ENTER_WIRED, 0);
514 		if (__predict_false((prot & VM_PROT_EXECUTE) != 0))
515 			m->oflags |= VPO_KMEM_EXEC;
516 	}
517 	VM_OBJECT_WUNLOCK(object);
518 
519 	return (KERN_SUCCESS);
520 }
521 
522 /*
523  *	kmem_back:
524  *
525  *	Allocate physical pages for the specified virtual address range.
526  */
527 int
528 kmem_back(vm_object_t object, vm_offset_t addr, vm_size_t size, int flags)
529 {
530 	vm_offset_t end, next, start;
531 	int domain, rv;
532 
533 	KASSERT(object == kernel_object,
534 	    ("kmem_back: only supports kernel object."));
535 
536 	for (start = addr, end = addr + size; addr < end; addr = next) {
537 		/*
538 		 * We must ensure that pages backing a given large virtual page
539 		 * all come from the same physical domain.
540 		 */
541 		if (vm_ndomains > 1) {
542 			domain = (addr >> KVA_QUANTUM_SHIFT) % vm_ndomains;
543 			while (VM_DOMAIN_EMPTY(domain))
544 				domain++;
545 			next = roundup2(addr + 1, KVA_QUANTUM);
546 			if (next > end || next < start)
547 				next = end;
548 		} else {
549 			domain = 0;
550 			next = end;
551 		}
552 		rv = kmem_back_domain(domain, object, addr, next - addr, flags);
553 		if (rv != KERN_SUCCESS) {
554 			kmem_unback(object, start, addr - start);
555 			break;
556 		}
557 	}
558 	return (rv);
559 }
560 
561 /*
562  *	kmem_unback:
563  *
564  *	Unmap and free the physical pages underlying the specified virtual
565  *	address range.
566  *
567  *	A physical page must exist within the specified object at each index
568  *	that is being unmapped.
569  */
570 static struct vmem *
571 _kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
572 {
573 	struct vmem *arena;
574 	vm_page_t m, next;
575 	vm_offset_t end, offset;
576 	int domain;
577 
578 	KASSERT(object == kernel_object,
579 	    ("kmem_unback: only supports kernel object."));
580 
581 	if (size == 0)
582 		return (NULL);
583 	pmap_remove(kernel_pmap, addr, addr + size);
584 	offset = addr - VM_MIN_KERNEL_ADDRESS;
585 	end = offset + size;
586 	VM_OBJECT_WLOCK(object);
587 	m = vm_page_lookup(object, atop(offset));
588 	domain = vm_page_domain(m);
589 	if (__predict_true((m->oflags & VPO_KMEM_EXEC) == 0))
590 		arena = vm_dom[domain].vmd_kernel_arena;
591 	else
592 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
593 	for (; offset < end; offset += PAGE_SIZE, m = next) {
594 		next = vm_page_next(m);
595 		vm_page_xbusy_claim(m);
596 		vm_page_unwire_noq(m);
597 		vm_page_free(m);
598 	}
599 	VM_OBJECT_WUNLOCK(object);
600 
601 	return (arena);
602 }
603 
604 void
605 kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
606 {
607 
608 	(void)_kmem_unback(object, addr, size);
609 }
610 
611 /*
612  *	kmem_free:
613  *
614  *	Free memory allocated with kmem_malloc.  The size must match the
615  *	original allocation.
616  */
617 void
618 kmem_free(vm_offset_t addr, vm_size_t size)
619 {
620 	struct vmem *arena;
621 
622 	size = round_page(size);
623 	kasan_mark((void *)addr, size, size, 0);
624 	arena = _kmem_unback(kernel_object, addr, size);
625 	if (arena != NULL)
626 		vmem_free(arena, addr, size);
627 }
628 
629 /*
630  *	kmap_alloc_wait:
631  *
632  *	Allocates pageable memory from a sub-map of the kernel.  If the submap
633  *	has no room, the caller sleeps waiting for more memory in the submap.
634  *
635  *	This routine may block.
636  */
637 vm_offset_t
638 kmap_alloc_wait(vm_map_t map, vm_size_t size)
639 {
640 	vm_offset_t addr;
641 
642 	size = round_page(size);
643 	if (!swap_reserve(size))
644 		return (0);
645 
646 	for (;;) {
647 		/*
648 		 * To make this work for more than one map, use the map's lock
649 		 * to lock out sleepers/wakers.
650 		 */
651 		vm_map_lock(map);
652 		addr = vm_map_findspace(map, vm_map_min(map), size);
653 		if (addr + size <= vm_map_max(map))
654 			break;
655 		/* no space now; see if we can ever get space */
656 		if (vm_map_max(map) - vm_map_min(map) < size) {
657 			vm_map_unlock(map);
658 			swap_release(size);
659 			return (0);
660 		}
661 		map->needs_wakeup = TRUE;
662 		vm_map_unlock_and_wait(map, 0);
663 	}
664 	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_RW, VM_PROT_RW,
665 	    MAP_ACC_CHARGED);
666 	vm_map_unlock(map);
667 	return (addr);
668 }
669 
670 /*
671  *	kmap_free_wakeup:
672  *
673  *	Returns memory to a submap of the kernel, and wakes up any processes
674  *	waiting for memory in that map.
675  */
676 void
677 kmap_free_wakeup(vm_map_t map, vm_offset_t addr, vm_size_t size)
678 {
679 
680 	vm_map_lock(map);
681 	(void) vm_map_delete(map, trunc_page(addr), round_page(addr + size));
682 	if (map->needs_wakeup) {
683 		map->needs_wakeup = FALSE;
684 		vm_map_wakeup(map);
685 	}
686 	vm_map_unlock(map);
687 }
688 
689 void
690 kmem_init_zero_region(void)
691 {
692 	vm_offset_t addr, i;
693 	vm_page_t m;
694 
695 	/*
696 	 * Map a single physical page of zeros to a larger virtual range.
697 	 * This requires less looping in places that want large amounts of
698 	 * zeros, while not using much more physical resources.
699 	 */
700 	addr = kva_alloc(ZERO_REGION_SIZE);
701 	m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
702 	    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
703 	if ((m->flags & PG_ZERO) == 0)
704 		pmap_zero_page(m);
705 	for (i = 0; i < ZERO_REGION_SIZE; i += PAGE_SIZE)
706 		pmap_qenter(addr + i, &m, 1);
707 	pmap_protect(kernel_pmap, addr, addr + ZERO_REGION_SIZE, VM_PROT_READ);
708 
709 	zero_region = (const void *)addr;
710 }
711 
712 /*
713  * Import KVA from the kernel map into the kernel arena.
714  */
715 static int
716 kva_import(void *unused, vmem_size_t size, int flags, vmem_addr_t *addrp)
717 {
718 	vm_offset_t addr;
719 	int result;
720 
721 	KASSERT((size % KVA_QUANTUM) == 0,
722 	    ("kva_import: Size %jd is not a multiple of %d",
723 	    (intmax_t)size, (int)KVA_QUANTUM));
724 	addr = vm_map_min(kernel_map);
725 	result = vm_map_find(kernel_map, NULL, 0, &addr, size, 0,
726 	    VMFS_SUPER_SPACE, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
727 	if (result != KERN_SUCCESS)
728                 return (ENOMEM);
729 
730 	*addrp = addr;
731 
732 	return (0);
733 }
734 
735 /*
736  * Import KVA from a parent arena into a per-domain arena.  Imports must be
737  * KVA_QUANTUM-aligned and a multiple of KVA_QUANTUM in size.
738  */
739 static int
740 kva_import_domain(void *arena, vmem_size_t size, int flags, vmem_addr_t *addrp)
741 {
742 
743 	KASSERT((size % KVA_QUANTUM) == 0,
744 	    ("kva_import_domain: Size %jd is not a multiple of %d",
745 	    (intmax_t)size, (int)KVA_QUANTUM));
746 	return (vmem_xalloc(arena, size, KVA_QUANTUM, 0, 0, VMEM_ADDR_MIN,
747 	    VMEM_ADDR_MAX, flags, addrp));
748 }
749 
750 /*
751  * 	kmem_init:
752  *
753  *	Create the kernel map; insert a mapping covering kernel text,
754  *	data, bss, and all space allocated thus far (`boostrap' data).  The
755  *	new map will thus map the range between VM_MIN_KERNEL_ADDRESS and
756  *	`start' as allocated, and the range between `start' and `end' as free.
757  *	Create the kernel vmem arena and its per-domain children.
758  */
759 void
760 kmem_init(vm_offset_t start, vm_offset_t end)
761 {
762 	vm_size_t quantum;
763 	int domain;
764 
765 	vm_map_init(kernel_map, kernel_pmap, VM_MIN_KERNEL_ADDRESS, end);
766 	kernel_map->system_map = 1;
767 	vm_map_lock(kernel_map);
768 	/* N.B.: cannot use kgdb to debug, starting with this assignment ... */
769 	(void)vm_map_insert(kernel_map, NULL, 0,
770 #ifdef __amd64__
771 	    KERNBASE,
772 #else
773 	    VM_MIN_KERNEL_ADDRESS,
774 #endif
775 	    start, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
776 	/* ... and ending with the completion of the above `insert' */
777 
778 #ifdef __amd64__
779 	/*
780 	 * Mark KVA used for the page array as allocated.  Other platforms
781 	 * that handle vm_page_array allocation can simply adjust virtual_avail
782 	 * instead.
783 	 */
784 	(void)vm_map_insert(kernel_map, NULL, 0, (vm_offset_t)vm_page_array,
785 	    (vm_offset_t)vm_page_array + round_2mpage(vm_page_array_size *
786 	    sizeof(struct vm_page)),
787 	    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
788 #endif
789 	vm_map_unlock(kernel_map);
790 
791 	/*
792 	 * Use a large import quantum on NUMA systems.  This helps minimize
793 	 * interleaving of superpages, reducing internal fragmentation within
794 	 * the per-domain arenas.
795 	 */
796 	if (vm_ndomains > 1 && PMAP_HAS_DMAP)
797 		quantum = KVA_NUMA_IMPORT_QUANTUM;
798 	else
799 		quantum = KVA_QUANTUM;
800 
801 	/*
802 	 * Initialize the kernel_arena.  This can grow on demand.
803 	 */
804 	vmem_init(kernel_arena, "kernel arena", 0, 0, PAGE_SIZE, 0, 0);
805 	vmem_set_import(kernel_arena, kva_import, NULL, NULL, quantum);
806 
807 	for (domain = 0; domain < vm_ndomains; domain++) {
808 		/*
809 		 * Initialize the per-domain arenas.  These are used to color
810 		 * the KVA space in a way that ensures that virtual large pages
811 		 * are backed by memory from the same physical domain,
812 		 * maximizing the potential for superpage promotion.
813 		 */
814 		vm_dom[domain].vmd_kernel_arena = vmem_create(
815 		    "kernel arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
816 		vmem_set_import(vm_dom[domain].vmd_kernel_arena,
817 		    kva_import_domain, NULL, kernel_arena, quantum);
818 
819 		/*
820 		 * In architectures with superpages, maintain separate arenas
821 		 * for allocations with permissions that differ from the
822 		 * "standard" read/write permissions used for kernel memory,
823 		 * so as not to inhibit superpage promotion.
824 		 *
825 		 * Use the base import quantum since this arena is rarely used.
826 		 */
827 #if VM_NRESERVLEVEL > 0
828 		vm_dom[domain].vmd_kernel_rwx_arena = vmem_create(
829 		    "kernel rwx arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
830 		vmem_set_import(vm_dom[domain].vmd_kernel_rwx_arena,
831 		    kva_import_domain, (vmem_release_t *)vmem_xfree,
832 		    kernel_arena, KVA_QUANTUM);
833 #else
834 		vm_dom[domain].vmd_kernel_rwx_arena =
835 		    vm_dom[domain].vmd_kernel_arena;
836 #endif
837 	}
838 
839 	/*
840 	 * This must be the very first call so that the virtual address
841 	 * space used for early allocations is properly marked used in
842 	 * the map.
843 	 */
844 	uma_startup2();
845 }
846 
847 /*
848  *	kmem_bootstrap_free:
849  *
850  *	Free pages backing preloaded data (e.g., kernel modules) to the
851  *	system.  Currently only supported on platforms that create a
852  *	vm_phys segment for preloaded data.
853  */
854 void
855 kmem_bootstrap_free(vm_offset_t start, vm_size_t size)
856 {
857 #if defined(__i386__) || defined(__amd64__)
858 	struct vm_domain *vmd;
859 	vm_offset_t end, va;
860 	vm_paddr_t pa;
861 	vm_page_t m;
862 
863 	end = trunc_page(start + size);
864 	start = round_page(start);
865 
866 #ifdef __amd64__
867 	/*
868 	 * Preloaded files do not have execute permissions by default on amd64.
869 	 * Restore the default permissions to ensure that the direct map alias
870 	 * is updated.
871 	 */
872 	pmap_change_prot(start, end - start, VM_PROT_RW);
873 #endif
874 	for (va = start; va < end; va += PAGE_SIZE) {
875 		pa = pmap_kextract(va);
876 		m = PHYS_TO_VM_PAGE(pa);
877 
878 		vmd = vm_pagequeue_domain(m);
879 		vm_domain_free_lock(vmd);
880 		vm_phys_free_pages(m, 0);
881 		vm_domain_free_unlock(vmd);
882 
883 		vm_domain_freecnt_inc(vmd, 1);
884 		vm_cnt.v_page_count++;
885 	}
886 	pmap_remove(kernel_pmap, start, end);
887 	(void)vmem_add(kernel_arena, start, end - start, M_WAITOK);
888 #endif
889 }
890 
891 /*
892  * Allow userspace to directly trigger the VM drain routine for testing
893  * purposes.
894  */
895 static int
896 debug_vm_lowmem(SYSCTL_HANDLER_ARGS)
897 {
898 	int error, i;
899 
900 	i = 0;
901 	error = sysctl_handle_int(oidp, &i, 0, req);
902 	if (error != 0)
903 		return (error);
904 	if ((i & ~(VM_LOW_KMEM | VM_LOW_PAGES)) != 0)
905 		return (EINVAL);
906 	if (i != 0)
907 		EVENTHANDLER_INVOKE(vm_lowmem, i);
908 	return (0);
909 }
910 SYSCTL_PROC(_debug, OID_AUTO, vm_lowmem,
911     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0, debug_vm_lowmem, "I",
912     "set to trigger vm_lowmem event with given flags");
913 
914 static int
915 debug_uma_reclaim(SYSCTL_HANDLER_ARGS)
916 {
917 	int error, i;
918 
919 	i = 0;
920 	error = sysctl_handle_int(oidp, &i, 0, req);
921 	if (error != 0 || req->newptr == NULL)
922 		return (error);
923 	if (i != UMA_RECLAIM_TRIM && i != UMA_RECLAIM_DRAIN &&
924 	    i != UMA_RECLAIM_DRAIN_CPU)
925 		return (EINVAL);
926 	uma_reclaim(i);
927 	return (0);
928 }
929 SYSCTL_PROC(_debug, OID_AUTO, uma_reclaim,
930     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0, debug_uma_reclaim, "I",
931     "set to generate request to reclaim uma caches");
932 
933 static int
934 debug_uma_reclaim_domain(SYSCTL_HANDLER_ARGS)
935 {
936 	int domain, error, request;
937 
938 	request = 0;
939 	error = sysctl_handle_int(oidp, &request, 0, req);
940 	if (error != 0 || req->newptr == NULL)
941 		return (error);
942 
943 	domain = request >> 4;
944 	request &= 0xf;
945 	if (request != UMA_RECLAIM_TRIM && request != UMA_RECLAIM_DRAIN &&
946 	    request != UMA_RECLAIM_DRAIN_CPU)
947 		return (EINVAL);
948 	if (domain < 0 || domain >= vm_ndomains)
949 		return (EINVAL);
950 	uma_reclaim_domain(request, domain);
951 	return (0);
952 }
953 SYSCTL_PROC(_debug, OID_AUTO, uma_reclaim_domain,
954     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0,
955     debug_uma_reclaim_domain, "I",
956     "");
957