xref: /freebsd/sys/vm/vm_kern.c (revision 7899f917b1c0ea178f1d2be0cfb452086d079d23)
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 vmem *arena;
638 	vm_page_t m, next;
639 	vm_offset_t end, offset;
640 	int domain;
641 
642 	KASSERT(object == kernel_object,
643 	    ("kmem_unback: only supports kernel object."));
644 
645 	if (size == 0)
646 		return (NULL);
647 	pmap_remove(kernel_pmap, addr, addr + size);
648 	offset = addr - VM_MIN_KERNEL_ADDRESS;
649 	end = offset + size;
650 	VM_OBJECT_WLOCK(object);
651 	m = vm_page_lookup(object, atop(offset));
652 	domain = vm_page_domain(m);
653 	if (__predict_true((m->oflags & VPO_KMEM_EXEC) == 0))
654 		arena = vm_dom[domain].vmd_kernel_arena;
655 	else
656 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
657 	for (; offset < end; offset += PAGE_SIZE, m = next) {
658 		next = vm_page_next(m);
659 		vm_page_xbusy_claim(m);
660 		vm_page_unwire_noq(m);
661 		vm_page_free(m);
662 	}
663 	VM_OBJECT_WUNLOCK(object);
664 
665 	return (arena);
666 }
667 
668 void
669 kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
670 {
671 
672 	(void)_kmem_unback(object, addr, size);
673 }
674 
675 /*
676  *	kmem_free:
677  *
678  *	Free memory allocated with kmem_malloc.  The size must match the
679  *	original allocation.
680  */
681 void
682 kmem_free(void *addr, vm_size_t size)
683 {
684 	struct vmem *arena;
685 
686 	size = round_page(size);
687 	kasan_mark(addr, size, size, 0);
688 	arena = _kmem_unback(kernel_object, (uintptr_t)addr, size);
689 	if (arena != NULL)
690 		vmem_free(arena, (uintptr_t)addr, size);
691 }
692 
693 /*
694  *	kmap_alloc_wait:
695  *
696  *	Allocates pageable memory from a sub-map of the kernel.  If the submap
697  *	has no room, the caller sleeps waiting for more memory in the submap.
698  *
699  *	This routine may block.
700  */
701 vm_offset_t
702 kmap_alloc_wait(vm_map_t map, vm_size_t size)
703 {
704 	vm_offset_t addr;
705 
706 	size = round_page(size);
707 	if (!swap_reserve(size))
708 		return (0);
709 
710 	for (;;) {
711 		/*
712 		 * To make this work for more than one map, use the map's lock
713 		 * to lock out sleepers/wakers.
714 		 */
715 		vm_map_lock(map);
716 		addr = vm_map_findspace(map, vm_map_min(map), size);
717 		if (addr + size <= vm_map_max(map))
718 			break;
719 		/* no space now; see if we can ever get space */
720 		if (vm_map_max(map) - vm_map_min(map) < size) {
721 			vm_map_unlock(map);
722 			swap_release(size);
723 			return (0);
724 		}
725 		map->needs_wakeup = TRUE;
726 		vm_map_unlock_and_wait(map, 0);
727 	}
728 	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_RW, VM_PROT_RW,
729 	    MAP_ACC_CHARGED);
730 	vm_map_unlock(map);
731 	return (addr);
732 }
733 
734 /*
735  *	kmap_free_wakeup:
736  *
737  *	Returns memory to a submap of the kernel, and wakes up any processes
738  *	waiting for memory in that map.
739  */
740 void
741 kmap_free_wakeup(vm_map_t map, vm_offset_t addr, vm_size_t size)
742 {
743 
744 	vm_map_lock(map);
745 	(void) vm_map_delete(map, trunc_page(addr), round_page(addr + size));
746 	if (map->needs_wakeup) {
747 		map->needs_wakeup = FALSE;
748 		vm_map_wakeup(map);
749 	}
750 	vm_map_unlock(map);
751 }
752 
753 void
754 kmem_init_zero_region(void)
755 {
756 	vm_offset_t addr, i;
757 	vm_page_t m;
758 
759 	/*
760 	 * Map a single physical page of zeros to a larger virtual range.
761 	 * This requires less looping in places that want large amounts of
762 	 * zeros, while not using much more physical resources.
763 	 */
764 	addr = kva_alloc(ZERO_REGION_SIZE);
765 	m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO);
766 	for (i = 0; i < ZERO_REGION_SIZE; i += PAGE_SIZE)
767 		pmap_qenter(addr + i, &m, 1);
768 	pmap_protect(kernel_pmap, addr, addr + ZERO_REGION_SIZE, VM_PROT_READ);
769 
770 	zero_region = (const void *)addr;
771 }
772 
773 /*
774  * Import KVA from the kernel map into the kernel arena.
775  */
776 static int
777 kva_import(void *unused, vmem_size_t size, int flags, vmem_addr_t *addrp)
778 {
779 	vm_offset_t addr;
780 	int result;
781 
782 	TSENTER();
783 	KASSERT((size % KVA_QUANTUM) == 0,
784 	    ("kva_import: Size %jd is not a multiple of %d",
785 	    (intmax_t)size, (int)KVA_QUANTUM));
786 	addr = vm_map_min(kernel_map);
787 	result = vm_map_find(kernel_map, NULL, 0, &addr, size, 0,
788 	    VMFS_SUPER_SPACE, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
789 	if (result != KERN_SUCCESS) {
790 		TSEXIT();
791                 return (ENOMEM);
792 	}
793 
794 	*addrp = addr;
795 
796 	TSEXIT();
797 	return (0);
798 }
799 
800 /*
801  * Import KVA from a parent arena into a per-domain arena.  Imports must be
802  * KVA_QUANTUM-aligned and a multiple of KVA_QUANTUM in size.
803  */
804 static int
805 kva_import_domain(void *arena, vmem_size_t size, int flags, vmem_addr_t *addrp)
806 {
807 
808 	KASSERT((size % KVA_QUANTUM) == 0,
809 	    ("kva_import_domain: Size %jd is not a multiple of %d",
810 	    (intmax_t)size, (int)KVA_QUANTUM));
811 	return (vmem_xalloc(arena, size, KVA_QUANTUM, 0, 0, VMEM_ADDR_MIN,
812 	    VMEM_ADDR_MAX, flags, addrp));
813 }
814 
815 /*
816  * 	kmem_init:
817  *
818  *	Create the kernel map; insert a mapping covering kernel text,
819  *	data, bss, and all space allocated thus far (`boostrap' data).  The
820  *	new map will thus map the range between VM_MIN_KERNEL_ADDRESS and
821  *	`start' as allocated, and the range between `start' and `end' as free.
822  *	Create the kernel vmem arena and its per-domain children.
823  */
824 void
825 kmem_init(vm_offset_t start, vm_offset_t end)
826 {
827 	vm_size_t quantum;
828 	int domain;
829 
830 	vm_map_init(kernel_map, kernel_pmap, VM_MIN_KERNEL_ADDRESS, end);
831 	kernel_map->system_map = 1;
832 	vm_map_lock(kernel_map);
833 	/* N.B.: cannot use kgdb to debug, starting with this assignment ... */
834 	(void)vm_map_insert(kernel_map, NULL, 0,
835 #ifdef __amd64__
836 	    KERNBASE,
837 #else
838 	    VM_MIN_KERNEL_ADDRESS,
839 #endif
840 	    start, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
841 	/* ... and ending with the completion of the above `insert' */
842 
843 #ifdef __amd64__
844 	/*
845 	 * Mark KVA used for the page array as allocated.  Other platforms
846 	 * that handle vm_page_array allocation can simply adjust virtual_avail
847 	 * instead.
848 	 */
849 	(void)vm_map_insert(kernel_map, NULL, 0, (vm_offset_t)vm_page_array,
850 	    (vm_offset_t)vm_page_array + round_2mpage(vm_page_array_size *
851 	    sizeof(struct vm_page)),
852 	    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
853 #endif
854 	vm_map_unlock(kernel_map);
855 
856 	/*
857 	 * Use a large import quantum on NUMA systems.  This helps minimize
858 	 * interleaving of superpages, reducing internal fragmentation within
859 	 * the per-domain arenas.
860 	 */
861 	if (vm_ndomains > 1 && PMAP_HAS_DMAP)
862 		quantum = KVA_NUMA_IMPORT_QUANTUM;
863 	else
864 		quantum = KVA_QUANTUM;
865 
866 	/*
867 	 * Initialize the kernel_arena.  This can grow on demand.
868 	 */
869 	vmem_init(kernel_arena, "kernel arena", 0, 0, PAGE_SIZE, 0, 0);
870 	vmem_set_import(kernel_arena, kva_import, NULL, NULL, quantum);
871 
872 	for (domain = 0; domain < vm_ndomains; domain++) {
873 		/*
874 		 * Initialize the per-domain arenas.  These are used to color
875 		 * the KVA space in a way that ensures that virtual large pages
876 		 * are backed by memory from the same physical domain,
877 		 * maximizing the potential for superpage promotion.
878 		 */
879 		vm_dom[domain].vmd_kernel_arena = vmem_create(
880 		    "kernel arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
881 		vmem_set_import(vm_dom[domain].vmd_kernel_arena,
882 		    kva_import_domain, NULL, kernel_arena, quantum);
883 
884 		/*
885 		 * In architectures with superpages, maintain separate arenas
886 		 * for allocations with permissions that differ from the
887 		 * "standard" read/write permissions used for kernel memory
888 		 * and pages that are never released, so as not to inhibit
889 		 * superpage promotion.
890 		 *
891 		 * Use the base import quantum since these arenas are rarely
892 		 * used.
893 		 */
894 #if VM_NRESERVLEVEL > 0
895 		vm_dom[domain].vmd_kernel_rwx_arena = vmem_create(
896 		    "kernel rwx arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
897 		vm_dom[domain].vmd_kernel_nofree_arena = vmem_create(
898 		    "kernel NOFREE arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
899 		vmem_set_import(vm_dom[domain].vmd_kernel_rwx_arena,
900 		    kva_import_domain, (vmem_release_t *)vmem_xfree,
901 		    kernel_arena, KVA_QUANTUM);
902 		vmem_set_import(vm_dom[domain].vmd_kernel_nofree_arena,
903 		    kva_import_domain, (vmem_release_t *)vmem_xfree,
904 		    kernel_arena, KVA_QUANTUM);
905 #else
906 		vm_dom[domain].vmd_kernel_rwx_arena =
907 		    vm_dom[domain].vmd_kernel_arena;
908 		vm_dom[domain].vmd_kernel_nofree_arena =
909 		    vm_dom[domain].vmd_kernel_arena;
910 #endif
911 	}
912 
913 	/*
914 	 * This must be the very first call so that the virtual address
915 	 * space used for early allocations is properly marked used in
916 	 * the map.
917 	 */
918 	uma_startup2();
919 }
920 
921 /*
922  *	kmem_bootstrap_free:
923  *
924  *	Free pages backing preloaded data (e.g., kernel modules) to the
925  *	system.  Currently only supported on platforms that create a
926  *	vm_phys segment for preloaded data.
927  */
928 void
929 kmem_bootstrap_free(vm_offset_t start, vm_size_t size)
930 {
931 #if defined(__i386__) || defined(__amd64__)
932 	struct vm_domain *vmd;
933 	vm_offset_t end, va;
934 	vm_paddr_t pa;
935 	vm_page_t m;
936 
937 	end = trunc_page(start + size);
938 	start = round_page(start);
939 
940 #ifdef __amd64__
941 	/*
942 	 * Preloaded files do not have execute permissions by default on amd64.
943 	 * Restore the default permissions to ensure that the direct map alias
944 	 * is updated.
945 	 */
946 	pmap_change_prot(start, end - start, VM_PROT_RW);
947 #endif
948 	for (va = start; va < end; va += PAGE_SIZE) {
949 		pa = pmap_kextract(va);
950 		m = PHYS_TO_VM_PAGE(pa);
951 
952 		vmd = vm_pagequeue_domain(m);
953 		vm_domain_free_lock(vmd);
954 		vm_phys_free_pages(m, 0);
955 		vm_domain_free_unlock(vmd);
956 
957 		vm_domain_freecnt_inc(vmd, 1);
958 		vm_cnt.v_page_count++;
959 	}
960 	pmap_remove(kernel_pmap, start, end);
961 	(void)vmem_add(kernel_arena, start, end - start, M_WAITOK);
962 #endif
963 }
964 
965 #ifdef PMAP_WANT_ACTIVE_CPUS_NAIVE
966 void
967 pmap_active_cpus(pmap_t pmap, cpuset_t *res)
968 {
969 	struct thread *td;
970 	struct proc *p;
971 	struct vmspace *vm;
972 	int c;
973 
974 	CPU_ZERO(res);
975 	CPU_FOREACH(c) {
976 		td = cpuid_to_pcpu[c]->pc_curthread;
977 		p = td->td_proc;
978 		if (p == NULL)
979 			continue;
980 		vm = vmspace_acquire_ref(p);
981 		if (vm == NULL)
982 			continue;
983 		if (pmap == vmspace_pmap(vm))
984 			CPU_SET(c, res);
985 		vmspace_free(vm);
986 	}
987 }
988 #endif
989 
990 /*
991  * Allow userspace to directly trigger the VM drain routine for testing
992  * purposes.
993  */
994 static int
995 debug_vm_lowmem(SYSCTL_HANDLER_ARGS)
996 {
997 	int error, i;
998 
999 	i = 0;
1000 	error = sysctl_handle_int(oidp, &i, 0, req);
1001 	if (error != 0)
1002 		return (error);
1003 	if ((i & ~(VM_LOW_KMEM | VM_LOW_PAGES)) != 0)
1004 		return (EINVAL);
1005 	if (i != 0)
1006 		EVENTHANDLER_INVOKE(vm_lowmem, i);
1007 	return (0);
1008 }
1009 SYSCTL_PROC(_debug, OID_AUTO, vm_lowmem,
1010     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0, debug_vm_lowmem, "I",
1011     "set to trigger vm_lowmem event with given flags");
1012 
1013 static int
1014 debug_uma_reclaim(SYSCTL_HANDLER_ARGS)
1015 {
1016 	int error, i;
1017 
1018 	i = 0;
1019 	error = sysctl_handle_int(oidp, &i, 0, req);
1020 	if (error != 0 || req->newptr == NULL)
1021 		return (error);
1022 	if (i != UMA_RECLAIM_TRIM && i != UMA_RECLAIM_DRAIN &&
1023 	    i != UMA_RECLAIM_DRAIN_CPU)
1024 		return (EINVAL);
1025 	uma_reclaim(i);
1026 	return (0);
1027 }
1028 SYSCTL_PROC(_debug, OID_AUTO, uma_reclaim,
1029     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0, debug_uma_reclaim, "I",
1030     "set to generate request to reclaim uma caches");
1031 
1032 static int
1033 debug_uma_reclaim_domain(SYSCTL_HANDLER_ARGS)
1034 {
1035 	int domain, error, request;
1036 
1037 	request = 0;
1038 	error = sysctl_handle_int(oidp, &request, 0, req);
1039 	if (error != 0 || req->newptr == NULL)
1040 		return (error);
1041 
1042 	domain = request >> 4;
1043 	request &= 0xf;
1044 	if (request != UMA_RECLAIM_TRIM && request != UMA_RECLAIM_DRAIN &&
1045 	    request != UMA_RECLAIM_DRAIN_CPU)
1046 		return (EINVAL);
1047 	if (domain < 0 || domain >= vm_ndomains)
1048 		return (EINVAL);
1049 	uma_reclaim_domain(request, domain);
1050 	return (0);
1051 }
1052 SYSCTL_PROC(_debug, OID_AUTO, uma_reclaim_domain,
1053     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0,
1054     debug_uma_reclaim_domain, "I",
1055     "");
1056