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