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