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