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