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