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