xref: /freebsd/sys/vm/vm_kern.c (revision 752d135e0dacd9a463d24ffb89779b67ce0a7ea0)
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_phys.h>
95 #include <vm/vm_pagequeue.h>
96 #include <vm/vm_radix.h>
97 #include <vm/vm_extern.h>
98 #include <vm/uma.h>
99 
100 vm_map_t kernel_map;
101 vm_map_t exec_map;
102 vm_map_t pipe_map;
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__) || defined(__sparc64__)
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 want large import sizes. */
128 #define	KVA_QUANTUM_SHIFT	(10 + PAGE_SHIFT)
129 #endif
130 #define	KVA_QUANTUM		(1 << KVA_QUANTUM_SHIFT)
131 
132 /*
133  *	kva_alloc:
134  *
135  *	Allocate a virtual address range with no underlying object and
136  *	no initial mapping to physical memory.  Any mapping from this
137  *	range to physical memory must be explicitly created prior to
138  *	its use, typically with pmap_qenter().  Any attempt to create
139  *	a mapping on demand through vm_fault() will result in a panic.
140  */
141 vm_offset_t
142 kva_alloc(vm_size_t size)
143 {
144 	vm_offset_t addr;
145 
146 	size = round_page(size);
147 	if (vmem_alloc(kernel_arena, size, M_BESTFIT | M_NOWAIT, &addr))
148 		return (0);
149 
150 	return (addr);
151 }
152 
153 /*
154  *	kva_free:
155  *
156  *	Release a region of kernel virtual memory allocated
157  *	with kva_alloc, and return the physical pages
158  *	associated with that region.
159  *
160  *	This routine may not block on kernel maps.
161  */
162 void
163 kva_free(vm_offset_t addr, vm_size_t size)
164 {
165 
166 	size = round_page(size);
167 	vmem_free(kernel_arena, addr, size);
168 }
169 
170 /*
171  *	Allocates a region from the kernel address map and physical pages
172  *	within the specified address range to the kernel object.  Creates a
173  *	wired mapping from this region to these pages, and returns the
174  *	region's starting virtual address.  The allocated pages are not
175  *	necessarily physically contiguous.  If M_ZERO is specified through the
176  *	given flags, then the pages are zeroed before they are mapped.
177  */
178 static vm_offset_t
179 kmem_alloc_attr_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
180     vm_paddr_t high, vm_memattr_t memattr)
181 {
182 	vmem_t *vmem;
183 	vm_object_t object = kernel_object;
184 	vm_offset_t addr, i, offset;
185 	vm_page_t m;
186 	int pflags, tries;
187 
188 	size = round_page(size);
189 	vmem = vm_dom[domain].vmd_kernel_arena;
190 	if (vmem_alloc(vmem, size, M_BESTFIT | flags, &addr))
191 		return (0);
192 	offset = addr - VM_MIN_KERNEL_ADDRESS;
193 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
194 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
195 	pflags |= VM_ALLOC_NOWAIT;
196 	VM_OBJECT_WLOCK(object);
197 	for (i = 0; i < size; i += PAGE_SIZE) {
198 		tries = 0;
199 retry:
200 		m = vm_page_alloc_contig_domain(object, atop(offset + i),
201 		    domain, pflags, 1, low, high, PAGE_SIZE, 0, memattr);
202 		if (m == NULL) {
203 			VM_OBJECT_WUNLOCK(object);
204 			if (tries < ((flags & M_NOWAIT) != 0 ? 1 : 3)) {
205 				if (!vm_page_reclaim_contig_domain(domain,
206 				    pflags, 1, low, high, PAGE_SIZE, 0) &&
207 				    (flags & M_WAITOK) != 0)
208 					vm_wait_domain(domain);
209 				VM_OBJECT_WLOCK(object);
210 				tries++;
211 				goto retry;
212 			}
213 			kmem_unback(object, addr, i);
214 			vmem_free(vmem, addr, size);
215 			return (0);
216 		}
217 		KASSERT(vm_phys_domain(m) == domain,
218 		    ("kmem_alloc_attr_domain: Domain mismatch %d != %d",
219 		    vm_phys_domain(m), domain));
220 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
221 			pmap_zero_page(m);
222 		m->valid = VM_PAGE_BITS_ALL;
223 		pmap_enter(kernel_pmap, addr + i, m, VM_PROT_RW,
224 		    VM_PROT_RW | PMAP_ENTER_WIRED, 0);
225 	}
226 	VM_OBJECT_WUNLOCK(object);
227 	return (addr);
228 }
229 
230 vm_offset_t
231 kmem_alloc_attr(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
232     vm_memattr_t memattr)
233 {
234 
235 	return (kmem_alloc_attr_domainset(DOMAINSET_RR(), size, flags, low,
236 	    high, memattr));
237 }
238 
239 vm_offset_t
240 kmem_alloc_attr_domainset(struct domainset *ds, vm_size_t size, int flags,
241     vm_paddr_t low, vm_paddr_t high, vm_memattr_t memattr)
242 {
243 	struct vm_domainset_iter di;
244 	vm_offset_t addr;
245 	int domain;
246 
247 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
248 	do {
249 		addr = kmem_alloc_attr_domain(domain, size, flags, low, high,
250 		    memattr);
251 		if (addr != 0)
252 			break;
253 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
254 
255 	return (addr);
256 }
257 
258 /*
259  *	Allocates a region from the kernel address map and physically
260  *	contiguous pages within the specified address range to the kernel
261  *	object.  Creates a wired mapping from this region to these pages, and
262  *	returns the region's starting virtual address.  If M_ZERO is specified
263  *	through the given flags, then the pages are zeroed before they are
264  *	mapped.
265  */
266 static vm_offset_t
267 kmem_alloc_contig_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
268     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
269     vm_memattr_t memattr)
270 {
271 	vmem_t *vmem;
272 	vm_object_t object = kernel_object;
273 	vm_offset_t addr, offset, tmp;
274 	vm_page_t end_m, m;
275 	u_long npages;
276 	int pflags, tries;
277 
278 	size = round_page(size);
279 	vmem = vm_dom[domain].vmd_kernel_arena;
280 	if (vmem_alloc(vmem, size, flags | M_BESTFIT, &addr))
281 		return (0);
282 	offset = addr - VM_MIN_KERNEL_ADDRESS;
283 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
284 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
285 	pflags |= VM_ALLOC_NOWAIT;
286 	npages = atop(size);
287 	VM_OBJECT_WLOCK(object);
288 	tries = 0;
289 retry:
290 	m = vm_page_alloc_contig_domain(object, atop(offset), domain, pflags,
291 	    npages, low, high, alignment, boundary, memattr);
292 	if (m == NULL) {
293 		VM_OBJECT_WUNLOCK(object);
294 		if (tries < ((flags & M_NOWAIT) != 0 ? 1 : 3)) {
295 			if (!vm_page_reclaim_contig_domain(domain, pflags,
296 			    npages, low, high, alignment, boundary) &&
297 			    (flags & M_WAITOK) != 0)
298 				vm_wait_domain(domain);
299 			VM_OBJECT_WLOCK(object);
300 			tries++;
301 			goto retry;
302 		}
303 		vmem_free(vmem, addr, size);
304 		return (0);
305 	}
306 	KASSERT(vm_phys_domain(m) == domain,
307 	    ("kmem_alloc_contig_domain: Domain mismatch %d != %d",
308 	    vm_phys_domain(m), domain));
309 	end_m = m + npages;
310 	tmp = addr;
311 	for (; m < end_m; m++) {
312 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
313 			pmap_zero_page(m);
314 		m->valid = VM_PAGE_BITS_ALL;
315 		pmap_enter(kernel_pmap, tmp, m, VM_PROT_RW,
316 		    VM_PROT_RW | PMAP_ENTER_WIRED, 0);
317 		tmp += PAGE_SIZE;
318 	}
319 	VM_OBJECT_WUNLOCK(object);
320 	return (addr);
321 }
322 
323 vm_offset_t
324 kmem_alloc_contig(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
325     u_long alignment, vm_paddr_t boundary, vm_memattr_t memattr)
326 {
327 
328 	return (kmem_alloc_contig_domainset(DOMAINSET_RR(), size, flags, low,
329 	    high, alignment, boundary, memattr));
330 }
331 
332 vm_offset_t
333 kmem_alloc_contig_domainset(struct domainset *ds, vm_size_t size, int flags,
334     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
335     vm_memattr_t memattr)
336 {
337 	struct vm_domainset_iter di;
338 	vm_offset_t addr;
339 	int domain;
340 
341 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
342 	do {
343 		addr = kmem_alloc_contig_domain(domain, size, flags, low, high,
344 		    alignment, boundary, memattr);
345 		if (addr != 0)
346 			break;
347 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
348 
349 	return (addr);
350 }
351 
352 /*
353  *	kmem_suballoc:
354  *
355  *	Allocates a map to manage a subrange
356  *	of the kernel virtual address space.
357  *
358  *	Arguments are as follows:
359  *
360  *	parent		Map to take range from
361  *	min, max	Returned endpoints of map
362  *	size		Size of range to find
363  *	superpage_align	Request that min is superpage aligned
364  */
365 vm_map_t
366 kmem_suballoc(vm_map_t parent, vm_offset_t *min, vm_offset_t *max,
367     vm_size_t size, boolean_t superpage_align)
368 {
369 	int ret;
370 	vm_map_t result;
371 
372 	size = round_page(size);
373 
374 	*min = vm_map_min(parent);
375 	ret = vm_map_find(parent, NULL, 0, min, size, 0, superpage_align ?
376 	    VMFS_SUPER_SPACE : VMFS_ANY_SPACE, VM_PROT_ALL, VM_PROT_ALL,
377 	    MAP_ACC_NO_CHARGE);
378 	if (ret != KERN_SUCCESS)
379 		panic("kmem_suballoc: bad status return of %d", ret);
380 	*max = *min + size;
381 	result = vm_map_create(vm_map_pmap(parent), *min, *max);
382 	if (result == NULL)
383 		panic("kmem_suballoc: cannot create submap");
384 	if (vm_map_submap(parent, *min, *max, result) != KERN_SUCCESS)
385 		panic("kmem_suballoc: unable to change range to submap");
386 	return (result);
387 }
388 
389 /*
390  *	kmem_malloc_domain:
391  *
392  *	Allocate wired-down pages in the kernel's address space.
393  */
394 static vm_offset_t
395 kmem_malloc_domain(int domain, vm_size_t size, int flags)
396 {
397 	vmem_t *arena;
398 	vm_offset_t addr;
399 	int rv;
400 
401 #if VM_NRESERVLEVEL > 0
402 	if (__predict_true((flags & M_EXEC) == 0))
403 		arena = vm_dom[domain].vmd_kernel_arena;
404 	else
405 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
406 #else
407 	arena = vm_dom[domain].vmd_kernel_arena;
408 #endif
409 	size = round_page(size);
410 	if (vmem_alloc(arena, size, flags | M_BESTFIT, &addr))
411 		return (0);
412 
413 	rv = kmem_back_domain(domain, kernel_object, addr, size, flags);
414 	if (rv != KERN_SUCCESS) {
415 		vmem_free(arena, addr, size);
416 		return (0);
417 	}
418 	return (addr);
419 }
420 
421 vm_offset_t
422 kmem_malloc(vm_size_t size, int flags)
423 {
424 
425 	return (kmem_malloc_domainset(DOMAINSET_RR(), size, flags));
426 }
427 
428 vm_offset_t
429 kmem_malloc_domainset(struct domainset *ds, vm_size_t size, int flags)
430 {
431 	struct vm_domainset_iter di;
432 	vm_offset_t addr;
433 	int domain;
434 
435 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
436 	do {
437 		addr = kmem_malloc_domain(domain, size, flags);
438 		if (addr != 0)
439 			break;
440 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
441 
442 	return (addr);
443 }
444 
445 /*
446  *	kmem_back_domain:
447  *
448  *	Allocate physical pages from the specified domain for the specified
449  *	virtual address range.
450  */
451 int
452 kmem_back_domain(int domain, vm_object_t object, vm_offset_t addr,
453     vm_size_t size, int flags)
454 {
455 	vm_offset_t offset, i;
456 	vm_page_t m, mpred;
457 	vm_prot_t prot;
458 	int pflags;
459 
460 	KASSERT(object == kernel_object,
461 	    ("kmem_back_domain: only supports kernel object."));
462 
463 	offset = addr - VM_MIN_KERNEL_ADDRESS;
464 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
465 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
466 	if (flags & M_WAITOK)
467 		pflags |= VM_ALLOC_WAITFAIL;
468 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
469 
470 	i = 0;
471 	VM_OBJECT_WLOCK(object);
472 retry:
473 	mpred = vm_radix_lookup_le(&object->rtree, atop(offset + i));
474 	for (; i < size; i += PAGE_SIZE, mpred = m) {
475 		m = vm_page_alloc_domain_after(object, atop(offset + i),
476 		    domain, pflags, mpred);
477 
478 		/*
479 		 * Ran out of space, free everything up and return. Don't need
480 		 * to lock page queues here as we know that the pages we got
481 		 * aren't on any queues.
482 		 */
483 		if (m == NULL) {
484 			if ((flags & M_NOWAIT) == 0)
485 				goto retry;
486 			VM_OBJECT_WUNLOCK(object);
487 			kmem_unback(object, addr, i);
488 			return (KERN_NO_SPACE);
489 		}
490 		KASSERT(vm_phys_domain(m) == domain,
491 		    ("kmem_back_domain: Domain mismatch %d != %d",
492 		    vm_phys_domain(m), domain));
493 		if (flags & M_ZERO && (m->flags & PG_ZERO) == 0)
494 			pmap_zero_page(m);
495 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
496 		    ("kmem_malloc: page %p is managed", m));
497 		m->valid = VM_PAGE_BITS_ALL;
498 		pmap_enter(kernel_pmap, addr + i, m, prot,
499 		    prot | PMAP_ENTER_WIRED, 0);
500 #if VM_NRESERVLEVEL > 0
501 		if (__predict_false((prot & VM_PROT_EXECUTE) != 0))
502 			m->oflags |= VPO_KMEM_EXEC;
503 #endif
504 	}
505 	VM_OBJECT_WUNLOCK(object);
506 
507 	return (KERN_SUCCESS);
508 }
509 
510 /*
511  *	kmem_back:
512  *
513  *	Allocate physical pages for the specified virtual address range.
514  */
515 int
516 kmem_back(vm_object_t object, vm_offset_t addr, vm_size_t size, int flags)
517 {
518 	vm_offset_t end, next, start;
519 	int domain, rv;
520 
521 	KASSERT(object == kernel_object,
522 	    ("kmem_back: only supports kernel object."));
523 
524 	for (start = addr, end = addr + size; addr < end; addr = next) {
525 		/*
526 		 * We must ensure that pages backing a given large virtual page
527 		 * all come from the same physical domain.
528 		 */
529 		if (vm_ndomains > 1) {
530 			domain = (addr >> KVA_QUANTUM_SHIFT) % vm_ndomains;
531 			while (VM_DOMAIN_EMPTY(domain))
532 				domain++;
533 			next = roundup2(addr + 1, KVA_QUANTUM);
534 			if (next > end || next < start)
535 				next = end;
536 		} else {
537 			domain = 0;
538 			next = end;
539 		}
540 		rv = kmem_back_domain(domain, object, addr, next - addr, flags);
541 		if (rv != KERN_SUCCESS) {
542 			kmem_unback(object, start, addr - start);
543 			break;
544 		}
545 	}
546 	return (rv);
547 }
548 
549 /*
550  *	kmem_unback:
551  *
552  *	Unmap and free the physical pages underlying the specified virtual
553  *	address range.
554  *
555  *	A physical page must exist within the specified object at each index
556  *	that is being unmapped.
557  */
558 static struct vmem *
559 _kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
560 {
561 	struct vmem *arena;
562 	vm_page_t m, next;
563 	vm_offset_t end, offset;
564 	int domain;
565 
566 	KASSERT(object == kernel_object,
567 	    ("kmem_unback: only supports kernel object."));
568 
569 	if (size == 0)
570 		return (NULL);
571 	pmap_remove(kernel_pmap, addr, addr + size);
572 	offset = addr - VM_MIN_KERNEL_ADDRESS;
573 	end = offset + size;
574 	VM_OBJECT_WLOCK(object);
575 	m = vm_page_lookup(object, atop(offset));
576 	domain = vm_phys_domain(m);
577 #if VM_NRESERVLEVEL > 0
578 	if (__predict_true((m->oflags & VPO_KMEM_EXEC) == 0))
579 		arena = vm_dom[domain].vmd_kernel_arena;
580 	else
581 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
582 #else
583 	arena = vm_dom[domain].vmd_kernel_arena;
584 #endif
585 	for (; offset < end; offset += PAGE_SIZE, m = next) {
586 		next = vm_page_next(m);
587 		vm_page_unwire(m, PQ_NONE);
588 		vm_page_free(m);
589 	}
590 	VM_OBJECT_WUNLOCK(object);
591 
592 	return (arena);
593 }
594 
595 void
596 kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
597 {
598 
599 	(void)_kmem_unback(object, addr, size);
600 }
601 
602 /*
603  *	kmem_free:
604  *
605  *	Free memory allocated with kmem_malloc.  The size must match the
606  *	original allocation.
607  */
608 void
609 kmem_free(vm_offset_t addr, vm_size_t size)
610 {
611 	struct vmem *arena;
612 
613 	size = round_page(size);
614 	arena = _kmem_unback(kernel_object, addr, size);
615 	if (arena != NULL)
616 		vmem_free(arena, addr, size);
617 }
618 
619 /*
620  *	kmap_alloc_wait:
621  *
622  *	Allocates pageable memory from a sub-map of the kernel.  If the submap
623  *	has no room, the caller sleeps waiting for more memory in the submap.
624  *
625  *	This routine may block.
626  */
627 vm_offset_t
628 kmap_alloc_wait(vm_map_t map, vm_size_t size)
629 {
630 	vm_offset_t addr;
631 
632 	size = round_page(size);
633 	if (!swap_reserve(size))
634 		return (0);
635 
636 	for (;;) {
637 		/*
638 		 * To make this work for more than one map, use the map's lock
639 		 * to lock out sleepers/wakers.
640 		 */
641 		vm_map_lock(map);
642 		if (vm_map_findspace(map, vm_map_min(map), size, &addr) == 0)
643 			break;
644 		/* no space now; see if we can ever get space */
645 		if (vm_map_max(map) - vm_map_min(map) < size) {
646 			vm_map_unlock(map);
647 			swap_release(size);
648 			return (0);
649 		}
650 		map->needs_wakeup = TRUE;
651 		vm_map_unlock_and_wait(map, 0);
652 	}
653 	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_RW, VM_PROT_RW,
654 	    MAP_ACC_CHARGED);
655 	vm_map_unlock(map);
656 	return (addr);
657 }
658 
659 /*
660  *	kmap_free_wakeup:
661  *
662  *	Returns memory to a submap of the kernel, and wakes up any processes
663  *	waiting for memory in that map.
664  */
665 void
666 kmap_free_wakeup(vm_map_t map, vm_offset_t addr, vm_size_t size)
667 {
668 
669 	vm_map_lock(map);
670 	(void) vm_map_delete(map, trunc_page(addr), round_page(addr + size));
671 	if (map->needs_wakeup) {
672 		map->needs_wakeup = FALSE;
673 		vm_map_wakeup(map);
674 	}
675 	vm_map_unlock(map);
676 }
677 
678 void
679 kmem_init_zero_region(void)
680 {
681 	vm_offset_t addr, i;
682 	vm_page_t m;
683 
684 	/*
685 	 * Map a single physical page of zeros to a larger virtual range.
686 	 * This requires less looping in places that want large amounts of
687 	 * zeros, while not using much more physical resources.
688 	 */
689 	addr = kva_alloc(ZERO_REGION_SIZE);
690 	m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
691 	    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
692 	if ((m->flags & PG_ZERO) == 0)
693 		pmap_zero_page(m);
694 	for (i = 0; i < ZERO_REGION_SIZE; i += PAGE_SIZE)
695 		pmap_qenter(addr + i, &m, 1);
696 	pmap_protect(kernel_pmap, addr, addr + ZERO_REGION_SIZE, VM_PROT_READ);
697 
698 	zero_region = (const void *)addr;
699 }
700 
701 /*
702  * Import KVA from the kernel map into the kernel arena.
703  */
704 static int
705 kva_import(void *unused, vmem_size_t size, int flags, vmem_addr_t *addrp)
706 {
707 	vm_offset_t addr;
708 	int result;
709 
710 	KASSERT((size % KVA_QUANTUM) == 0,
711 	    ("kva_import: Size %jd is not a multiple of %d",
712 	    (intmax_t)size, (int)KVA_QUANTUM));
713 	addr = vm_map_min(kernel_map);
714 	result = vm_map_find(kernel_map, NULL, 0, &addr, size, 0,
715 	    VMFS_SUPER_SPACE, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
716 	if (result != KERN_SUCCESS)
717                 return (ENOMEM);
718 
719 	*addrp = addr;
720 
721 	return (0);
722 }
723 
724 /*
725  * Import KVA from a parent arena into a per-domain arena.  Imports must be
726  * KVA_QUANTUM-aligned and a multiple of KVA_QUANTUM in size.
727  */
728 static int
729 kva_import_domain(void *arena, vmem_size_t size, int flags, vmem_addr_t *addrp)
730 {
731 
732 	KASSERT((size % KVA_QUANTUM) == 0,
733 	    ("kva_import_domain: Size %jd is not a multiple of %d",
734 	    (intmax_t)size, (int)KVA_QUANTUM));
735 	return (vmem_xalloc(arena, size, KVA_QUANTUM, 0, 0, VMEM_ADDR_MIN,
736 	    VMEM_ADDR_MAX, flags, addrp));
737 }
738 
739 /*
740  * 	kmem_init:
741  *
742  *	Create the kernel map; insert a mapping covering kernel text,
743  *	data, bss, and all space allocated thus far (`boostrap' data).  The
744  *	new map will thus map the range between VM_MIN_KERNEL_ADDRESS and
745  *	`start' as allocated, and the range between `start' and `end' as free.
746  *	Create the kernel vmem arena and its per-domain children.
747  */
748 void
749 kmem_init(vm_offset_t start, vm_offset_t end)
750 {
751 	vm_map_t m;
752 	int domain;
753 
754 	m = vm_map_create(kernel_pmap, VM_MIN_KERNEL_ADDRESS, end);
755 	m->system_map = 1;
756 	vm_map_lock(m);
757 	/* N.B.: cannot use kgdb to debug, starting with this assignment ... */
758 	kernel_map = m;
759 	(void) vm_map_insert(m, NULL, (vm_ooffset_t) 0,
760 #ifdef __amd64__
761 	    KERNBASE,
762 #else
763 	    VM_MIN_KERNEL_ADDRESS,
764 #endif
765 	    start, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
766 	/* ... and ending with the completion of the above `insert' */
767 	vm_map_unlock(m);
768 
769 	/*
770 	 * Initialize the kernel_arena.  This can grow on demand.
771 	 */
772 	vmem_init(kernel_arena, "kernel arena", 0, 0, PAGE_SIZE, 0, 0);
773 	vmem_set_import(kernel_arena, kva_import, NULL, NULL, KVA_QUANTUM);
774 
775 	for (domain = 0; domain < vm_ndomains; domain++) {
776 		/*
777 		 * Initialize the per-domain arenas.  These are used to color
778 		 * the KVA space in a way that ensures that virtual large pages
779 		 * are backed by memory from the same physical domain,
780 		 * maximizing the potential for superpage promotion.
781 		 */
782 		vm_dom[domain].vmd_kernel_arena = vmem_create(
783 		    "kernel arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
784 		vmem_set_import(vm_dom[domain].vmd_kernel_arena,
785 		    kva_import_domain, NULL, kernel_arena, KVA_QUANTUM);
786 
787 		/*
788 		 * In architectures with superpages, maintain separate arenas
789 		 * for allocations with permissions that differ from the
790 		 * "standard" read/write permissions used for kernel memory,
791 		 * so as not to inhibit superpage promotion.
792 		 */
793 #if VM_NRESERVLEVEL > 0
794 		vm_dom[domain].vmd_kernel_rwx_arena = vmem_create(
795 		    "kernel rwx arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
796 		vmem_set_import(vm_dom[domain].vmd_kernel_rwx_arena,
797 		    kva_import_domain, (vmem_release_t *)vmem_xfree,
798 		    kernel_arena, KVA_QUANTUM);
799 #endif
800 	}
801 }
802 
803 /*
804  *	kmem_bootstrap_free:
805  *
806  *	Free pages backing preloaded data (e.g., kernel modules) to the
807  *	system.  Currently only supported on platforms that create a
808  *	vm_phys segment for preloaded data.
809  */
810 void
811 kmem_bootstrap_free(vm_offset_t start, vm_size_t size)
812 {
813 #if defined(__i386__) || defined(__amd64__)
814 	struct vm_domain *vmd;
815 	vm_offset_t end, va;
816 	vm_paddr_t pa;
817 	vm_page_t m;
818 
819 	end = trunc_page(start + size);
820 	start = round_page(start);
821 
822 	for (va = start; va < end; va += PAGE_SIZE) {
823 		pa = pmap_kextract(va);
824 		m = PHYS_TO_VM_PAGE(pa);
825 
826 		vmd = vm_pagequeue_domain(m);
827 		vm_domain_free_lock(vmd);
828 		vm_phys_free_pages(m, 0);
829 		vm_domain_free_unlock(vmd);
830 
831 		vm_domain_freecnt_inc(vmd, 1);
832 		vm_cnt.v_page_count++;
833 	}
834 	pmap_remove(kernel_pmap, start, end);
835 	(void)vmem_add(kernel_arena, start, end - start, M_WAITOK);
836 #endif
837 }
838 
839 #ifdef DIAGNOSTIC
840 /*
841  * Allow userspace to directly trigger the VM drain routine for testing
842  * purposes.
843  */
844 static int
845 debug_vm_lowmem(SYSCTL_HANDLER_ARGS)
846 {
847 	int error, i;
848 
849 	i = 0;
850 	error = sysctl_handle_int(oidp, &i, 0, req);
851 	if (error)
852 		return (error);
853 	if ((i & ~(VM_LOW_KMEM | VM_LOW_PAGES)) != 0)
854 		return (EINVAL);
855 	if (i != 0)
856 		EVENTHANDLER_INVOKE(vm_lowmem, i);
857 	return (0);
858 }
859 
860 SYSCTL_PROC(_debug, OID_AUTO, vm_lowmem, CTLTYPE_INT | CTLFLAG_RW, 0, 0,
861     debug_vm_lowmem, "I", "set to trigger vm_lowmem event with given flags");
862 #endif
863