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