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