xref: /freebsd/sys/vm/vm_kern.c (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
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 
455 	return (kmem_malloc_domainset(DOMAINSET_RR(), size, flags));
456 }
457 
458 void *
459 kmem_malloc_domainset(struct domainset *ds, vm_size_t size, int flags)
460 {
461 	struct vm_domainset_iter di;
462 	void *addr;
463 	int domain;
464 
465 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
466 	do {
467 		addr = kmem_malloc_domain(domain, size, flags);
468 		if (addr != NULL)
469 			break;
470 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
471 
472 	return (addr);
473 }
474 
475 /*
476  *	kmem_back_domain:
477  *
478  *	Allocate physical pages from the specified domain for the specified
479  *	virtual address range.
480  */
481 int
482 kmem_back_domain(int domain, vm_object_t object, vm_offset_t addr,
483     vm_size_t size, int flags)
484 {
485 	vm_offset_t offset, i;
486 	vm_page_t m, mpred;
487 	vm_prot_t prot;
488 	int pflags;
489 
490 	KASSERT(object == kernel_object,
491 	    ("kmem_back_domain: only supports kernel object."));
492 
493 	offset = addr - VM_MIN_KERNEL_ADDRESS;
494 	pflags = malloc2vm_flags(flags) | VM_ALLOC_WIRED;
495 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
496 	if (flags & M_WAITOK)
497 		pflags |= VM_ALLOC_WAITFAIL;
498 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
499 
500 	i = 0;
501 	VM_OBJECT_WLOCK(object);
502 retry:
503 	mpred = vm_radix_lookup_le(&object->rtree, atop(offset + i));
504 	for (; i < size; i += PAGE_SIZE, mpred = m) {
505 		m = vm_page_alloc_domain_after(object, atop(offset + i),
506 		    domain, pflags, mpred);
507 
508 		/*
509 		 * Ran out of space, free everything up and return. Don't need
510 		 * to lock page queues here as we know that the pages we got
511 		 * aren't on any queues.
512 		 */
513 		if (m == NULL) {
514 			if ((flags & M_NOWAIT) == 0)
515 				goto retry;
516 			VM_OBJECT_WUNLOCK(object);
517 			kmem_unback(object, addr, i);
518 			return (KERN_NO_SPACE);
519 		}
520 		KASSERT(vm_page_domain(m) == domain,
521 		    ("kmem_back_domain: Domain mismatch %d != %d",
522 		    vm_page_domain(m), domain));
523 		if (flags & M_ZERO && (m->flags & PG_ZERO) == 0)
524 			pmap_zero_page(m);
525 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
526 		    ("kmem_malloc: page %p is managed", m));
527 		vm_page_valid(m);
528 		pmap_enter(kernel_pmap, addr + i, m, prot,
529 		    prot | PMAP_ENTER_WIRED, 0);
530 		if (__predict_false((prot & VM_PROT_EXECUTE) != 0))
531 			m->oflags |= VPO_KMEM_EXEC;
532 	}
533 	VM_OBJECT_WUNLOCK(object);
534 	kmem_alloc_san(addr, size, size, flags);
535 	return (KERN_SUCCESS);
536 }
537 
538 /*
539  *	kmem_back:
540  *
541  *	Allocate physical pages for the specified virtual address range.
542  */
543 int
544 kmem_back(vm_object_t object, vm_offset_t addr, vm_size_t size, int flags)
545 {
546 	vm_offset_t end, next, start;
547 	int domain, rv;
548 
549 	KASSERT(object == kernel_object,
550 	    ("kmem_back: only supports kernel object."));
551 
552 	for (start = addr, end = addr + size; addr < end; addr = next) {
553 		/*
554 		 * We must ensure that pages backing a given large virtual page
555 		 * all come from the same physical domain.
556 		 */
557 		if (vm_ndomains > 1) {
558 			domain = (addr >> KVA_QUANTUM_SHIFT) % vm_ndomains;
559 			while (VM_DOMAIN_EMPTY(domain))
560 				domain++;
561 			next = roundup2(addr + 1, KVA_QUANTUM);
562 			if (next > end || next < start)
563 				next = end;
564 		} else {
565 			domain = 0;
566 			next = end;
567 		}
568 		rv = kmem_back_domain(domain, object, addr, next - addr, flags);
569 		if (rv != KERN_SUCCESS) {
570 			kmem_unback(object, start, addr - start);
571 			break;
572 		}
573 	}
574 	return (rv);
575 }
576 
577 /*
578  *	kmem_unback:
579  *
580  *	Unmap and free the physical pages underlying the specified virtual
581  *	address range.
582  *
583  *	A physical page must exist within the specified object at each index
584  *	that is being unmapped.
585  */
586 static struct vmem *
587 _kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
588 {
589 	struct vmem *arena;
590 	vm_page_t m, next;
591 	vm_offset_t end, offset;
592 	int domain;
593 
594 	KASSERT(object == kernel_object,
595 	    ("kmem_unback: only supports kernel object."));
596 
597 	if (size == 0)
598 		return (NULL);
599 	pmap_remove(kernel_pmap, addr, addr + size);
600 	offset = addr - VM_MIN_KERNEL_ADDRESS;
601 	end = offset + size;
602 	VM_OBJECT_WLOCK(object);
603 	m = vm_page_lookup(object, atop(offset));
604 	domain = vm_page_domain(m);
605 	if (__predict_true((m->oflags & VPO_KMEM_EXEC) == 0))
606 		arena = vm_dom[domain].vmd_kernel_arena;
607 	else
608 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
609 	for (; offset < end; offset += PAGE_SIZE, m = next) {
610 		next = vm_page_next(m);
611 		vm_page_xbusy_claim(m);
612 		vm_page_unwire_noq(m);
613 		vm_page_free(m);
614 	}
615 	VM_OBJECT_WUNLOCK(object);
616 
617 	return (arena);
618 }
619 
620 void
621 kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
622 {
623 
624 	(void)_kmem_unback(object, addr, size);
625 }
626 
627 /*
628  *	kmem_free:
629  *
630  *	Free memory allocated with kmem_malloc.  The size must match the
631  *	original allocation.
632  */
633 void
634 kmem_free(void *addr, vm_size_t size)
635 {
636 	struct vmem *arena;
637 
638 	size = round_page(size);
639 	kasan_mark(addr, size, size, 0);
640 	arena = _kmem_unback(kernel_object, (uintptr_t)addr, size);
641 	if (arena != NULL)
642 		vmem_free(arena, (uintptr_t)addr, size);
643 }
644 
645 /*
646  *	kmap_alloc_wait:
647  *
648  *	Allocates pageable memory from a sub-map of the kernel.  If the submap
649  *	has no room, the caller sleeps waiting for more memory in the submap.
650  *
651  *	This routine may block.
652  */
653 vm_offset_t
654 kmap_alloc_wait(vm_map_t map, vm_size_t size)
655 {
656 	vm_offset_t addr;
657 
658 	size = round_page(size);
659 	if (!swap_reserve(size))
660 		return (0);
661 
662 	for (;;) {
663 		/*
664 		 * To make this work for more than one map, use the map's lock
665 		 * to lock out sleepers/wakers.
666 		 */
667 		vm_map_lock(map);
668 		addr = vm_map_findspace(map, vm_map_min(map), size);
669 		if (addr + size <= vm_map_max(map))
670 			break;
671 		/* no space now; see if we can ever get space */
672 		if (vm_map_max(map) - vm_map_min(map) < size) {
673 			vm_map_unlock(map);
674 			swap_release(size);
675 			return (0);
676 		}
677 		map->needs_wakeup = TRUE;
678 		vm_map_unlock_and_wait(map, 0);
679 	}
680 	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_RW, VM_PROT_RW,
681 	    MAP_ACC_CHARGED);
682 	vm_map_unlock(map);
683 	return (addr);
684 }
685 
686 /*
687  *	kmap_free_wakeup:
688  *
689  *	Returns memory to a submap of the kernel, and wakes up any processes
690  *	waiting for memory in that map.
691  */
692 void
693 kmap_free_wakeup(vm_map_t map, vm_offset_t addr, vm_size_t size)
694 {
695 
696 	vm_map_lock(map);
697 	(void) vm_map_delete(map, trunc_page(addr), round_page(addr + size));
698 	if (map->needs_wakeup) {
699 		map->needs_wakeup = FALSE;
700 		vm_map_wakeup(map);
701 	}
702 	vm_map_unlock(map);
703 }
704 
705 void
706 kmem_init_zero_region(void)
707 {
708 	vm_offset_t addr, i;
709 	vm_page_t m;
710 
711 	/*
712 	 * Map a single physical page of zeros to a larger virtual range.
713 	 * This requires less looping in places that want large amounts of
714 	 * zeros, while not using much more physical resources.
715 	 */
716 	addr = kva_alloc(ZERO_REGION_SIZE);
717 	m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO);
718 	for (i = 0; i < ZERO_REGION_SIZE; i += PAGE_SIZE)
719 		pmap_qenter(addr + i, &m, 1);
720 	pmap_protect(kernel_pmap, addr, addr + ZERO_REGION_SIZE, VM_PROT_READ);
721 
722 	zero_region = (const void *)addr;
723 }
724 
725 /*
726  * Import KVA from the kernel map into the kernel arena.
727  */
728 static int
729 kva_import(void *unused, vmem_size_t size, int flags, vmem_addr_t *addrp)
730 {
731 	vm_offset_t addr;
732 	int result;
733 
734 	KASSERT((size % KVA_QUANTUM) == 0,
735 	    ("kva_import: Size %jd is not a multiple of %d",
736 	    (intmax_t)size, (int)KVA_QUANTUM));
737 	addr = vm_map_min(kernel_map);
738 	result = vm_map_find(kernel_map, NULL, 0, &addr, size, 0,
739 	    VMFS_SUPER_SPACE, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
740 	if (result != KERN_SUCCESS)
741                 return (ENOMEM);
742 
743 	*addrp = addr;
744 
745 	return (0);
746 }
747 
748 /*
749  * Import KVA from a parent arena into a per-domain arena.  Imports must be
750  * KVA_QUANTUM-aligned and a multiple of KVA_QUANTUM in size.
751  */
752 static int
753 kva_import_domain(void *arena, vmem_size_t size, int flags, vmem_addr_t *addrp)
754 {
755 
756 	KASSERT((size % KVA_QUANTUM) == 0,
757 	    ("kva_import_domain: Size %jd is not a multiple of %d",
758 	    (intmax_t)size, (int)KVA_QUANTUM));
759 	return (vmem_xalloc(arena, size, KVA_QUANTUM, 0, 0, VMEM_ADDR_MIN,
760 	    VMEM_ADDR_MAX, flags, addrp));
761 }
762 
763 /*
764  * 	kmem_init:
765  *
766  *	Create the kernel map; insert a mapping covering kernel text,
767  *	data, bss, and all space allocated thus far (`boostrap' data).  The
768  *	new map will thus map the range between VM_MIN_KERNEL_ADDRESS and
769  *	`start' as allocated, and the range between `start' and `end' as free.
770  *	Create the kernel vmem arena and its per-domain children.
771  */
772 void
773 kmem_init(vm_offset_t start, vm_offset_t end)
774 {
775 	vm_size_t quantum;
776 	int domain;
777 
778 	vm_map_init(kernel_map, kernel_pmap, VM_MIN_KERNEL_ADDRESS, end);
779 	kernel_map->system_map = 1;
780 	vm_map_lock(kernel_map);
781 	/* N.B.: cannot use kgdb to debug, starting with this assignment ... */
782 	(void)vm_map_insert(kernel_map, NULL, 0,
783 #ifdef __amd64__
784 	    KERNBASE,
785 #else
786 	    VM_MIN_KERNEL_ADDRESS,
787 #endif
788 	    start, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
789 	/* ... and ending with the completion of the above `insert' */
790 
791 #ifdef __amd64__
792 	/*
793 	 * Mark KVA used for the page array as allocated.  Other platforms
794 	 * that handle vm_page_array allocation can simply adjust virtual_avail
795 	 * instead.
796 	 */
797 	(void)vm_map_insert(kernel_map, NULL, 0, (vm_offset_t)vm_page_array,
798 	    (vm_offset_t)vm_page_array + round_2mpage(vm_page_array_size *
799 	    sizeof(struct vm_page)),
800 	    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
801 #endif
802 	vm_map_unlock(kernel_map);
803 
804 	/*
805 	 * Use a large import quantum on NUMA systems.  This helps minimize
806 	 * interleaving of superpages, reducing internal fragmentation within
807 	 * the per-domain arenas.
808 	 */
809 	if (vm_ndomains > 1 && PMAP_HAS_DMAP)
810 		quantum = KVA_NUMA_IMPORT_QUANTUM;
811 	else
812 		quantum = KVA_QUANTUM;
813 
814 	/*
815 	 * Initialize the kernel_arena.  This can grow on demand.
816 	 */
817 	vmem_init(kernel_arena, "kernel arena", 0, 0, PAGE_SIZE, 0, 0);
818 	vmem_set_import(kernel_arena, kva_import, NULL, NULL, quantum);
819 
820 	for (domain = 0; domain < vm_ndomains; domain++) {
821 		/*
822 		 * Initialize the per-domain arenas.  These are used to color
823 		 * the KVA space in a way that ensures that virtual large pages
824 		 * are backed by memory from the same physical domain,
825 		 * maximizing the potential for superpage promotion.
826 		 */
827 		vm_dom[domain].vmd_kernel_arena = vmem_create(
828 		    "kernel arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
829 		vmem_set_import(vm_dom[domain].vmd_kernel_arena,
830 		    kva_import_domain, NULL, kernel_arena, quantum);
831 
832 		/*
833 		 * In architectures with superpages, maintain separate arenas
834 		 * for allocations with permissions that differ from the
835 		 * "standard" read/write permissions used for kernel memory,
836 		 * so as not to inhibit superpage promotion.
837 		 *
838 		 * Use the base import quantum since this arena is rarely used.
839 		 */
840 #if VM_NRESERVLEVEL > 0
841 		vm_dom[domain].vmd_kernel_rwx_arena = vmem_create(
842 		    "kernel rwx arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
843 		vmem_set_import(vm_dom[domain].vmd_kernel_rwx_arena,
844 		    kva_import_domain, (vmem_release_t *)vmem_xfree,
845 		    kernel_arena, KVA_QUANTUM);
846 #else
847 		vm_dom[domain].vmd_kernel_rwx_arena =
848 		    vm_dom[domain].vmd_kernel_arena;
849 #endif
850 	}
851 
852 	/*
853 	 * This must be the very first call so that the virtual address
854 	 * space used for early allocations is properly marked used in
855 	 * the map.
856 	 */
857 	uma_startup2();
858 }
859 
860 /*
861  *	kmem_bootstrap_free:
862  *
863  *	Free pages backing preloaded data (e.g., kernel modules) to the
864  *	system.  Currently only supported on platforms that create a
865  *	vm_phys segment for preloaded data.
866  */
867 void
868 kmem_bootstrap_free(vm_offset_t start, vm_size_t size)
869 {
870 #if defined(__i386__) || defined(__amd64__)
871 	struct vm_domain *vmd;
872 	vm_offset_t end, va;
873 	vm_paddr_t pa;
874 	vm_page_t m;
875 
876 	end = trunc_page(start + size);
877 	start = round_page(start);
878 
879 #ifdef __amd64__
880 	/*
881 	 * Preloaded files do not have execute permissions by default on amd64.
882 	 * Restore the default permissions to ensure that the direct map alias
883 	 * is updated.
884 	 */
885 	pmap_change_prot(start, end - start, VM_PROT_RW);
886 #endif
887 	for (va = start; va < end; va += PAGE_SIZE) {
888 		pa = pmap_kextract(va);
889 		m = PHYS_TO_VM_PAGE(pa);
890 
891 		vmd = vm_pagequeue_domain(m);
892 		vm_domain_free_lock(vmd);
893 		vm_phys_free_pages(m, 0);
894 		vm_domain_free_unlock(vmd);
895 
896 		vm_domain_freecnt_inc(vmd, 1);
897 		vm_cnt.v_page_count++;
898 	}
899 	pmap_remove(kernel_pmap, start, end);
900 	(void)vmem_add(kernel_arena, start, end - start, M_WAITOK);
901 #endif
902 }
903 
904 /*
905  * Allow userspace to directly trigger the VM drain routine for testing
906  * purposes.
907  */
908 static int
909 debug_vm_lowmem(SYSCTL_HANDLER_ARGS)
910 {
911 	int error, i;
912 
913 	i = 0;
914 	error = sysctl_handle_int(oidp, &i, 0, req);
915 	if (error != 0)
916 		return (error);
917 	if ((i & ~(VM_LOW_KMEM | VM_LOW_PAGES)) != 0)
918 		return (EINVAL);
919 	if (i != 0)
920 		EVENTHANDLER_INVOKE(vm_lowmem, i);
921 	return (0);
922 }
923 SYSCTL_PROC(_debug, OID_AUTO, vm_lowmem,
924     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0, debug_vm_lowmem, "I",
925     "set to trigger vm_lowmem event with given flags");
926 
927 static int
928 debug_uma_reclaim(SYSCTL_HANDLER_ARGS)
929 {
930 	int error, i;
931 
932 	i = 0;
933 	error = sysctl_handle_int(oidp, &i, 0, req);
934 	if (error != 0 || req->newptr == NULL)
935 		return (error);
936 	if (i != UMA_RECLAIM_TRIM && i != UMA_RECLAIM_DRAIN &&
937 	    i != UMA_RECLAIM_DRAIN_CPU)
938 		return (EINVAL);
939 	uma_reclaim(i);
940 	return (0);
941 }
942 SYSCTL_PROC(_debug, OID_AUTO, uma_reclaim,
943     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0, debug_uma_reclaim, "I",
944     "set to generate request to reclaim uma caches");
945 
946 static int
947 debug_uma_reclaim_domain(SYSCTL_HANDLER_ARGS)
948 {
949 	int domain, error, request;
950 
951 	request = 0;
952 	error = sysctl_handle_int(oidp, &request, 0, req);
953 	if (error != 0 || req->newptr == NULL)
954 		return (error);
955 
956 	domain = request >> 4;
957 	request &= 0xf;
958 	if (request != UMA_RECLAIM_TRIM && request != UMA_RECLAIM_DRAIN &&
959 	    request != UMA_RECLAIM_DRAIN_CPU)
960 		return (EINVAL);
961 	if (domain < 0 || domain >= vm_ndomains)
962 		return (EINVAL);
963 	uma_reclaim_domain(request, domain);
964 	return (0);
965 }
966 SYSCTL_PROC(_debug, OID_AUTO, uma_reclaim_domain,
967     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0,
968     debug_uma_reclaim_domain, "I",
969     "");
970