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