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