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