xref: /freebsd/sys/vm/vm_kern.c (revision a521f2116473fbd8c09db395518f060a27d02334)
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 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		(1 << 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;
181 
182 	VM_OBJECT_ASSERT_WLOCKED(object);
183 
184 	wait = (pflags & VM_ALLOC_WAITOK) != 0;
185 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
186 	pflags |= VM_ALLOC_NOWAIT;
187 	for (tries = wait ? 3 : 1;; tries--) {
188 		m = vm_page_alloc_contig_domain(object, pindex, domain, pflags,
189 		    npages, low, high, alignment, boundary, memattr);
190 		if (m != NULL || tries == 0)
191 			break;
192 
193 		VM_OBJECT_WUNLOCK(object);
194 		if (!vm_page_reclaim_contig_domain(domain, pflags, npages,
195 		    low, high, alignment, boundary) && wait)
196 			vm_wait_domain(domain);
197 		VM_OBJECT_WLOCK(object);
198 	}
199 	return (m);
200 }
201 
202 /*
203  *	Allocates a region from the kernel address map and physical pages
204  *	within the specified address range to the kernel object.  Creates a
205  *	wired mapping from this region to these pages, and returns the
206  *	region's starting virtual address.  The allocated pages are not
207  *	necessarily physically contiguous.  If M_ZERO is specified through the
208  *	given flags, then the pages are zeroed before they are mapped.
209  */
210 static vm_offset_t
211 kmem_alloc_attr_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
212     vm_paddr_t high, vm_memattr_t memattr)
213 {
214 	vmem_t *vmem;
215 	vm_object_t object;
216 	vm_offset_t addr, i, offset;
217 	vm_page_t m;
218 	int pflags;
219 	vm_prot_t prot;
220 
221 	object = kernel_object;
222 	size = round_page(size);
223 	vmem = vm_dom[domain].vmd_kernel_arena;
224 	if (vmem_alloc(vmem, size, M_BESTFIT | flags, &addr))
225 		return (0);
226 	offset = addr - VM_MIN_KERNEL_ADDRESS;
227 	pflags = malloc2vm_flags(flags) | VM_ALLOC_WIRED;
228 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
229 	VM_OBJECT_WLOCK(object);
230 	for (i = 0; i < size; i += PAGE_SIZE) {
231 		m = kmem_alloc_contig_pages(object, atop(offset + i),
232 		    domain, pflags, 1, low, high, PAGE_SIZE, 0, memattr);
233 		if (m == NULL) {
234 			VM_OBJECT_WUNLOCK(object);
235 			kmem_unback(object, addr, i);
236 			vmem_free(vmem, addr, size);
237 			return (0);
238 		}
239 		KASSERT(vm_phys_domain(m) == domain,
240 		    ("kmem_alloc_attr_domain: Domain mismatch %d != %d",
241 		    vm_phys_domain(m), domain));
242 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
243 			pmap_zero_page(m);
244 		vm_page_valid(m);
245 		pmap_enter(kernel_pmap, addr + i, m, prot,
246 		    prot | PMAP_ENTER_WIRED, 0);
247 	}
248 	VM_OBJECT_WUNLOCK(object);
249 	return (addr);
250 }
251 
252 vm_offset_t
253 kmem_alloc_attr(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
254     vm_memattr_t memattr)
255 {
256 
257 	return (kmem_alloc_attr_domainset(DOMAINSET_RR(), size, flags, low,
258 	    high, memattr));
259 }
260 
261 vm_offset_t
262 kmem_alloc_attr_domainset(struct domainset *ds, vm_size_t size, int flags,
263     vm_paddr_t low, vm_paddr_t high, vm_memattr_t memattr)
264 {
265 	struct vm_domainset_iter di;
266 	vm_offset_t addr;
267 	int domain;
268 
269 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
270 	do {
271 		addr = kmem_alloc_attr_domain(domain, size, flags, low, high,
272 		    memattr);
273 		if (addr != 0)
274 			break;
275 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
276 
277 	return (addr);
278 }
279 
280 /*
281  *	Allocates a region from the kernel address map and physically
282  *	contiguous pages within the specified address range to the kernel
283  *	object.  Creates a wired mapping from this region to these pages, and
284  *	returns the region's starting virtual address.  If M_ZERO is specified
285  *	through the given flags, then the pages are zeroed before they are
286  *	mapped.
287  */
288 static vm_offset_t
289 kmem_alloc_contig_domain(int domain, vm_size_t size, int flags, vm_paddr_t low,
290     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
291     vm_memattr_t memattr)
292 {
293 	vmem_t *vmem;
294 	vm_object_t object;
295 	vm_offset_t addr, offset, tmp;
296 	vm_page_t end_m, m;
297 	u_long npages;
298 	int pflags;
299 
300 	object = kernel_object;
301 	size = round_page(size);
302 	vmem = vm_dom[domain].vmd_kernel_arena;
303 	if (vmem_alloc(vmem, size, flags | M_BESTFIT, &addr))
304 		return (0);
305 	offset = addr - VM_MIN_KERNEL_ADDRESS;
306 	pflags = malloc2vm_flags(flags) | VM_ALLOC_WIRED;
307 	npages = atop(size);
308 	VM_OBJECT_WLOCK(object);
309 	m = kmem_alloc_contig_pages(object, atop(offset), domain,
310 	    pflags, npages, low, high, alignment, boundary, memattr);
311 	if (m == NULL) {
312 		VM_OBJECT_WUNLOCK(object);
313 		vmem_free(vmem, addr, size);
314 		return (0);
315 	}
316 	KASSERT(vm_phys_domain(m) == domain,
317 	    ("kmem_alloc_contig_domain: Domain mismatch %d != %d",
318 	    vm_phys_domain(m), domain));
319 	end_m = m + npages;
320 	tmp = addr;
321 	for (; m < end_m; m++) {
322 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
323 			pmap_zero_page(m);
324 		vm_page_valid(m);
325 		pmap_enter(kernel_pmap, tmp, m, VM_PROT_RW,
326 		    VM_PROT_RW | PMAP_ENTER_WIRED, 0);
327 		tmp += PAGE_SIZE;
328 	}
329 	VM_OBJECT_WUNLOCK(object);
330 	return (addr);
331 }
332 
333 vm_offset_t
334 kmem_alloc_contig(vm_size_t size, int flags, vm_paddr_t low, vm_paddr_t high,
335     u_long alignment, vm_paddr_t boundary, vm_memattr_t memattr)
336 {
337 
338 	return (kmem_alloc_contig_domainset(DOMAINSET_RR(), size, flags, low,
339 	    high, alignment, boundary, memattr));
340 }
341 
342 vm_offset_t
343 kmem_alloc_contig_domainset(struct domainset *ds, vm_size_t size, int flags,
344     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
345     vm_memattr_t memattr)
346 {
347 	struct vm_domainset_iter di;
348 	vm_offset_t addr;
349 	int domain;
350 
351 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
352 	do {
353 		addr = kmem_alloc_contig_domain(domain, size, flags, low, high,
354 		    alignment, boundary, memattr);
355 		if (addr != 0)
356 			break;
357 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
358 
359 	return (addr);
360 }
361 
362 /*
363  *	kmem_subinit:
364  *
365  *	Initializes a map to manage a subrange
366  *	of the kernel virtual address space.
367  *
368  *	Arguments are as follows:
369  *
370  *	parent		Map to take range from
371  *	min, max	Returned endpoints of map
372  *	size		Size of range to find
373  *	superpage_align	Request that min is superpage aligned
374  */
375 void
376 kmem_subinit(vm_map_t map, vm_map_t parent, vm_offset_t *min, vm_offset_t *max,
377     vm_size_t size, bool superpage_align)
378 {
379 	int ret;
380 
381 	size = round_page(size);
382 
383 	*min = vm_map_min(parent);
384 	ret = vm_map_find(parent, NULL, 0, min, size, 0, superpage_align ?
385 	    VMFS_SUPER_SPACE : VMFS_ANY_SPACE, VM_PROT_ALL, VM_PROT_ALL,
386 	    MAP_ACC_NO_CHARGE);
387 	if (ret != KERN_SUCCESS)
388 		panic("kmem_subinit: bad status return of %d", ret);
389 	*max = *min + size;
390 	vm_map_init(map, vm_map_pmap(parent), *min, *max);
391 	if (vm_map_submap(parent, *min, *max, map) != KERN_SUCCESS)
392 		panic("kmem_subinit: unable to change range to submap");
393 }
394 
395 /*
396  *	kmem_malloc_domain:
397  *
398  *	Allocate wired-down pages in the kernel's address space.
399  */
400 static vm_offset_t
401 kmem_malloc_domain(int domain, vm_size_t size, int flags)
402 {
403 	vmem_t *arena;
404 	vm_offset_t addr;
405 	int rv;
406 
407 	if (__predict_true((flags & M_EXEC) == 0))
408 		arena = vm_dom[domain].vmd_kernel_arena;
409 	else
410 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
411 	size = round_page(size);
412 	if (vmem_alloc(arena, size, flags | M_BESTFIT, &addr))
413 		return (0);
414 
415 	rv = kmem_back_domain(domain, kernel_object, addr, size, flags);
416 	if (rv != KERN_SUCCESS) {
417 		vmem_free(arena, addr, size);
418 		return (0);
419 	}
420 	return (addr);
421 }
422 
423 vm_offset_t
424 kmem_malloc(vm_size_t size, int flags)
425 {
426 
427 	return (kmem_malloc_domainset(DOMAINSET_RR(), size, flags));
428 }
429 
430 vm_offset_t
431 kmem_malloc_domainset(struct domainset *ds, vm_size_t size, int flags)
432 {
433 	struct vm_domainset_iter di;
434 	vm_offset_t addr;
435 	int domain;
436 
437 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
438 	do {
439 		addr = kmem_malloc_domain(domain, size, flags);
440 		if (addr != 0)
441 			break;
442 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
443 
444 	return (addr);
445 }
446 
447 /*
448  *	kmem_back_domain:
449  *
450  *	Allocate physical pages from the specified domain for the specified
451  *	virtual address range.
452  */
453 int
454 kmem_back_domain(int domain, vm_object_t object, vm_offset_t addr,
455     vm_size_t size, int flags)
456 {
457 	vm_offset_t offset, i;
458 	vm_page_t m, mpred;
459 	vm_prot_t prot;
460 	int pflags;
461 
462 	KASSERT(object == kernel_object,
463 	    ("kmem_back_domain: only supports kernel object."));
464 
465 	offset = addr - VM_MIN_KERNEL_ADDRESS;
466 	pflags = malloc2vm_flags(flags) | VM_ALLOC_WIRED;
467 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
468 	if (flags & M_WAITOK)
469 		pflags |= VM_ALLOC_WAITFAIL;
470 	prot = (flags & M_EXEC) != 0 ? VM_PROT_ALL : VM_PROT_RW;
471 
472 	i = 0;
473 	VM_OBJECT_WLOCK(object);
474 retry:
475 	mpred = vm_radix_lookup_le(&object->rtree, atop(offset + i));
476 	for (; i < size; i += PAGE_SIZE, mpred = m) {
477 		m = vm_page_alloc_domain_after(object, atop(offset + i),
478 		    domain, pflags, mpred);
479 
480 		/*
481 		 * Ran out of space, free everything up and return. Don't need
482 		 * to lock page queues here as we know that the pages we got
483 		 * aren't on any queues.
484 		 */
485 		if (m == NULL) {
486 			if ((flags & M_NOWAIT) == 0)
487 				goto retry;
488 			VM_OBJECT_WUNLOCK(object);
489 			kmem_unback(object, addr, i);
490 			return (KERN_NO_SPACE);
491 		}
492 		KASSERT(vm_phys_domain(m) == domain,
493 		    ("kmem_back_domain: Domain mismatch %d != %d",
494 		    vm_phys_domain(m), domain));
495 		if (flags & M_ZERO && (m->flags & PG_ZERO) == 0)
496 			pmap_zero_page(m);
497 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
498 		    ("kmem_malloc: page %p is managed", m));
499 		vm_page_valid(m);
500 		pmap_enter(kernel_pmap, addr + i, m, prot,
501 		    prot | PMAP_ENTER_WIRED, 0);
502 		if (__predict_false((prot & VM_PROT_EXECUTE) != 0))
503 			m->oflags |= VPO_KMEM_EXEC;
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 (__predict_true((m->oflags & VPO_KMEM_EXEC) == 0))
578 		arena = vm_dom[domain].vmd_kernel_arena;
579 	else
580 		arena = vm_dom[domain].vmd_kernel_rwx_arena;
581 	for (; offset < end; offset += PAGE_SIZE, m = next) {
582 		next = vm_page_next(m);
583 		vm_page_xbusy_claim(m);
584 		vm_page_unwire_noq(m);
585 		vm_page_free(m);
586 	}
587 	VM_OBJECT_WUNLOCK(object);
588 
589 	return (arena);
590 }
591 
592 void
593 kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
594 {
595 
596 	(void)_kmem_unback(object, addr, size);
597 }
598 
599 /*
600  *	kmem_free:
601  *
602  *	Free memory allocated with kmem_malloc.  The size must match the
603  *	original allocation.
604  */
605 void
606 kmem_free(vm_offset_t addr, vm_size_t size)
607 {
608 	struct vmem *arena;
609 
610 	size = round_page(size);
611 	arena = _kmem_unback(kernel_object, addr, size);
612 	if (arena != NULL)
613 		vmem_free(arena, addr, size);
614 }
615 
616 /*
617  *	kmap_alloc_wait:
618  *
619  *	Allocates pageable memory from a sub-map of the kernel.  If the submap
620  *	has no room, the caller sleeps waiting for more memory in the submap.
621  *
622  *	This routine may block.
623  */
624 vm_offset_t
625 kmap_alloc_wait(vm_map_t map, vm_size_t size)
626 {
627 	vm_offset_t addr;
628 
629 	size = round_page(size);
630 	if (!swap_reserve(size))
631 		return (0);
632 
633 	for (;;) {
634 		/*
635 		 * To make this work for more than one map, use the map's lock
636 		 * to lock out sleepers/wakers.
637 		 */
638 		vm_map_lock(map);
639 		addr = vm_map_findspace(map, vm_map_min(map), size);
640 		if (addr + size <= vm_map_max(map))
641 			break;
642 		/* no space now; see if we can ever get space */
643 		if (vm_map_max(map) - vm_map_min(map) < size) {
644 			vm_map_unlock(map);
645 			swap_release(size);
646 			return (0);
647 		}
648 		map->needs_wakeup = TRUE;
649 		vm_map_unlock_and_wait(map, 0);
650 	}
651 	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_RW, VM_PROT_RW,
652 	    MAP_ACC_CHARGED);
653 	vm_map_unlock(map);
654 	return (addr);
655 }
656 
657 /*
658  *	kmap_free_wakeup:
659  *
660  *	Returns memory to a submap of the kernel, and wakes up any processes
661  *	waiting for memory in that map.
662  */
663 void
664 kmap_free_wakeup(vm_map_t map, vm_offset_t addr, vm_size_t size)
665 {
666 
667 	vm_map_lock(map);
668 	(void) vm_map_delete(map, trunc_page(addr), round_page(addr + size));
669 	if (map->needs_wakeup) {
670 		map->needs_wakeup = FALSE;
671 		vm_map_wakeup(map);
672 	}
673 	vm_map_unlock(map);
674 }
675 
676 void
677 kmem_init_zero_region(void)
678 {
679 	vm_offset_t addr, i;
680 	vm_page_t m;
681 
682 	/*
683 	 * Map a single physical page of zeros to a larger virtual range.
684 	 * This requires less looping in places that want large amounts of
685 	 * zeros, while not using much more physical resources.
686 	 */
687 	addr = kva_alloc(ZERO_REGION_SIZE);
688 	m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
689 	    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
690 	if ((m->flags & PG_ZERO) == 0)
691 		pmap_zero_page(m);
692 	for (i = 0; i < ZERO_REGION_SIZE; i += PAGE_SIZE)
693 		pmap_qenter(addr + i, &m, 1);
694 	pmap_protect(kernel_pmap, addr, addr + ZERO_REGION_SIZE, VM_PROT_READ);
695 
696 	zero_region = (const void *)addr;
697 }
698 
699 /*
700  * Import KVA from the kernel map into the kernel arena.
701  */
702 static int
703 kva_import(void *unused, vmem_size_t size, int flags, vmem_addr_t *addrp)
704 {
705 	vm_offset_t addr;
706 	int result;
707 
708 	KASSERT((size % KVA_QUANTUM) == 0,
709 	    ("kva_import: Size %jd is not a multiple of %d",
710 	    (intmax_t)size, (int)KVA_QUANTUM));
711 	addr = vm_map_min(kernel_map);
712 	result = vm_map_find(kernel_map, NULL, 0, &addr, size, 0,
713 	    VMFS_SUPER_SPACE, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
714 	if (result != KERN_SUCCESS)
715                 return (ENOMEM);
716 
717 	*addrp = addr;
718 
719 	return (0);
720 }
721 
722 /*
723  * Import KVA from a parent arena into a per-domain arena.  Imports must be
724  * KVA_QUANTUM-aligned and a multiple of KVA_QUANTUM in size.
725  */
726 static int
727 kva_import_domain(void *arena, vmem_size_t size, int flags, vmem_addr_t *addrp)
728 {
729 
730 	KASSERT((size % KVA_QUANTUM) == 0,
731 	    ("kva_import_domain: Size %jd is not a multiple of %d",
732 	    (intmax_t)size, (int)KVA_QUANTUM));
733 	return (vmem_xalloc(arena, size, KVA_QUANTUM, 0, 0, VMEM_ADDR_MIN,
734 	    VMEM_ADDR_MAX, flags, addrp));
735 }
736 
737 /*
738  * 	kmem_init:
739  *
740  *	Create the kernel map; insert a mapping covering kernel text,
741  *	data, bss, and all space allocated thus far (`boostrap' data).  The
742  *	new map will thus map the range between VM_MIN_KERNEL_ADDRESS and
743  *	`start' as allocated, and the range between `start' and `end' as free.
744  *	Create the kernel vmem arena and its per-domain children.
745  */
746 void
747 kmem_init(vm_offset_t start, vm_offset_t end)
748 {
749 	vm_size_t quantum;
750 	int domain;
751 
752 	vm_map_init(kernel_map, kernel_pmap, VM_MIN_KERNEL_ADDRESS, end);
753 	kernel_map->system_map = 1;
754 	vm_map_lock(kernel_map);
755 	/* N.B.: cannot use kgdb to debug, starting with this assignment ... */
756 	(void)vm_map_insert(kernel_map, NULL, 0,
757 #ifdef __amd64__
758 	    KERNBASE,
759 #else
760 	    VM_MIN_KERNEL_ADDRESS,
761 #endif
762 	    start, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
763 	/* ... and ending with the completion of the above `insert' */
764 
765 #ifdef __amd64__
766 	/*
767 	 * Mark KVA used for the page array as allocated.  Other platforms
768 	 * that handle vm_page_array allocation can simply adjust virtual_avail
769 	 * instead.
770 	 */
771 	(void)vm_map_insert(kernel_map, NULL, 0, (vm_offset_t)vm_page_array,
772 	    (vm_offset_t)vm_page_array + round_2mpage(vm_page_array_size *
773 	    sizeof(struct vm_page)),
774 	    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
775 #endif
776 	vm_map_unlock(kernel_map);
777 
778 	/*
779 	 * Use a large import quantum on NUMA systems.  This helps minimize
780 	 * interleaving of superpages, reducing internal fragmentation within
781 	 * the per-domain arenas.
782 	 */
783 	if (vm_ndomains > 1 && PMAP_HAS_DMAP)
784 		quantum = KVA_NUMA_IMPORT_QUANTUM;
785 	else
786 		quantum = KVA_QUANTUM;
787 
788 	/*
789 	 * Initialize the kernel_arena.  This can grow on demand.
790 	 */
791 	vmem_init(kernel_arena, "kernel arena", 0, 0, PAGE_SIZE, 0, 0);
792 	vmem_set_import(kernel_arena, kva_import, NULL, NULL, quantum);
793 
794 	for (domain = 0; domain < vm_ndomains; domain++) {
795 		/*
796 		 * Initialize the per-domain arenas.  These are used to color
797 		 * the KVA space in a way that ensures that virtual large pages
798 		 * are backed by memory from the same physical domain,
799 		 * maximizing the potential for superpage promotion.
800 		 */
801 		vm_dom[domain].vmd_kernel_arena = vmem_create(
802 		    "kernel arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
803 		vmem_set_import(vm_dom[domain].vmd_kernel_arena,
804 		    kva_import_domain, NULL, kernel_arena, quantum);
805 
806 		/*
807 		 * In architectures with superpages, maintain separate arenas
808 		 * for allocations with permissions that differ from the
809 		 * "standard" read/write permissions used for kernel memory,
810 		 * so as not to inhibit superpage promotion.
811 		 *
812 		 * Use the base import quantum since this arena is rarely used.
813 		 */
814 #if VM_NRESERVLEVEL > 0
815 		vm_dom[domain].vmd_kernel_rwx_arena = vmem_create(
816 		    "kernel rwx arena domain", 0, 0, PAGE_SIZE, 0, M_WAITOK);
817 		vmem_set_import(vm_dom[domain].vmd_kernel_rwx_arena,
818 		    kva_import_domain, (vmem_release_t *)vmem_xfree,
819 		    kernel_arena, KVA_QUANTUM);
820 #else
821 		vm_dom[domain].vmd_kernel_rwx_arena =
822 		    vm_dom[domain].vmd_kernel_arena;
823 #endif
824 	}
825 
826 	/*
827 	 * This must be the very first call so that the virtual address
828 	 * space used for early allocations is properly marked used in
829 	 * the map.
830 	 */
831 	uma_startup2();
832 }
833 
834 /*
835  *	kmem_bootstrap_free:
836  *
837  *	Free pages backing preloaded data (e.g., kernel modules) to the
838  *	system.  Currently only supported on platforms that create a
839  *	vm_phys segment for preloaded data.
840  */
841 void
842 kmem_bootstrap_free(vm_offset_t start, vm_size_t size)
843 {
844 #if defined(__i386__) || defined(__amd64__)
845 	struct vm_domain *vmd;
846 	vm_offset_t end, va;
847 	vm_paddr_t pa;
848 	vm_page_t m;
849 
850 	end = trunc_page(start + size);
851 	start = round_page(start);
852 
853 #ifdef __amd64__
854 	/*
855 	 * Preloaded files do not have execute permissions by default on amd64.
856 	 * Restore the default permissions to ensure that the direct map alias
857 	 * is updated.
858 	 */
859 	pmap_change_prot(start, end - start, VM_PROT_RW);
860 #endif
861 	for (va = start; va < end; va += PAGE_SIZE) {
862 		pa = pmap_kextract(va);
863 		m = PHYS_TO_VM_PAGE(pa);
864 
865 		vmd = vm_pagequeue_domain(m);
866 		vm_domain_free_lock(vmd);
867 		vm_phys_free_pages(m, 0);
868 		vm_domain_free_unlock(vmd);
869 
870 		vm_domain_freecnt_inc(vmd, 1);
871 		vm_cnt.v_page_count++;
872 	}
873 	pmap_remove(kernel_pmap, start, end);
874 	(void)vmem_add(kernel_arena, start, end - start, M_WAITOK);
875 #endif
876 }
877 
878 /*
879  * Allow userspace to directly trigger the VM drain routine for testing
880  * purposes.
881  */
882 static int
883 debug_vm_lowmem(SYSCTL_HANDLER_ARGS)
884 {
885 	int error, i;
886 
887 	i = 0;
888 	error = sysctl_handle_int(oidp, &i, 0, req);
889 	if (error)
890 		return (error);
891 	if ((i & ~(VM_LOW_KMEM | VM_LOW_PAGES)) != 0)
892 		return (EINVAL);
893 	if (i != 0)
894 		EVENTHANDLER_INVOKE(vm_lowmem, i);
895 	return (0);
896 }
897 
898 SYSCTL_PROC(_debug, OID_AUTO, vm_lowmem, CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, 0,
899     debug_vm_lowmem, "I", "set to trigger vm_lowmem event with given flags");
900