xref: /freebsd/sys/vm/vm_kern.c (revision d8a0fe102c0cfdfcd5b818f850eff09d8536c9bc)
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 <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>		/* for ticks and hz */
73 #include <sys/eventhandler.h>
74 #include <sys/lock.h>
75 #include <sys/proc.h>
76 #include <sys/malloc.h>
77 #include <sys/rwlock.h>
78 #include <sys/sysctl.h>
79 #include <sys/vmem.h>
80 
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/vm_kern.h>
84 #include <vm/pmap.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_pageout.h>
89 #include <vm/vm_radix.h>
90 #include <vm/vm_extern.h>
91 #include <vm/uma.h>
92 
93 vm_map_t kernel_map;
94 vm_map_t exec_map;
95 vm_map_t pipe_map;
96 
97 const void *zero_region;
98 CTASSERT((ZERO_REGION_SIZE & PAGE_MASK) == 0);
99 
100 /* NB: Used by kernel debuggers. */
101 const u_long vm_maxuser_address = VM_MAXUSER_ADDRESS;
102 
103 u_int exec_map_entry_size;
104 u_int exec_map_entries;
105 
106 SYSCTL_ULONG(_vm, OID_AUTO, min_kernel_address, CTLFLAG_RD,
107     SYSCTL_NULL_ULONG_PTR, VM_MIN_KERNEL_ADDRESS, "Min kernel address");
108 
109 SYSCTL_ULONG(_vm, OID_AUTO, max_kernel_address, CTLFLAG_RD,
110 #if defined(__arm__) || defined(__sparc64__)
111     &vm_max_kernel_address, 0,
112 #else
113     SYSCTL_NULL_ULONG_PTR, VM_MAX_KERNEL_ADDRESS,
114 #endif
115     "Max kernel address");
116 
117 /*
118  *	kva_alloc:
119  *
120  *	Allocate a virtual address range with no underlying object and
121  *	no initial mapping to physical memory.  Any mapping from this
122  *	range to physical memory must be explicitly created prior to
123  *	its use, typically with pmap_qenter().  Any attempt to create
124  *	a mapping on demand through vm_fault() will result in a panic.
125  */
126 vm_offset_t
127 kva_alloc(vm_size_t size)
128 {
129 	vm_offset_t addr;
130 
131 	size = round_page(size);
132 	if (vmem_alloc(kernel_arena, size, M_BESTFIT | M_NOWAIT, &addr))
133 		return (0);
134 
135 	return (addr);
136 }
137 
138 /*
139  *	kva_free:
140  *
141  *	Release a region of kernel virtual memory allocated
142  *	with kva_alloc, and return the physical pages
143  *	associated with that region.
144  *
145  *	This routine may not block on kernel maps.
146  */
147 void
148 kva_free(vm_offset_t addr, vm_size_t size)
149 {
150 
151 	size = round_page(size);
152 	vmem_free(kernel_arena, addr, size);
153 }
154 
155 /*
156  *	Allocates a region from the kernel address map and physical pages
157  *	within the specified address range to the kernel object.  Creates a
158  *	wired mapping from this region to these pages, and returns the
159  *	region's starting virtual address.  The allocated pages are not
160  *	necessarily physically contiguous.  If M_ZERO is specified through the
161  *	given flags, then the pages are zeroed before they are mapped.
162  */
163 vm_offset_t
164 kmem_alloc_attr(vmem_t *vmem, vm_size_t size, int flags, vm_paddr_t low,
165     vm_paddr_t high, vm_memattr_t memattr)
166 {
167 	vm_object_t object = kernel_object;
168 	vm_offset_t addr, i, offset;
169 	vm_page_t m;
170 	int pflags, tries;
171 
172 	KASSERT(vmem == kernel_arena,
173 	    ("kmem_alloc_attr: Only kernel_arena is supported."));
174 	size = round_page(size);
175 	if (vmem_alloc(vmem, size, M_BESTFIT | flags, &addr))
176 		return (0);
177 	offset = addr - VM_MIN_KERNEL_ADDRESS;
178 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
179 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
180 	pflags |= VM_ALLOC_NOWAIT;
181 	VM_OBJECT_WLOCK(object);
182 	for (i = 0; i < size; i += PAGE_SIZE) {
183 		tries = 0;
184 retry:
185 		m = vm_page_alloc_contig(object, atop(offset + i),
186 		    pflags, 1, low, high, PAGE_SIZE, 0, memattr);
187 		if (m == NULL) {
188 			VM_OBJECT_WUNLOCK(object);
189 			if (tries < ((flags & M_NOWAIT) != 0 ? 1 : 3)) {
190 				if (!vm_page_reclaim_contig(pflags, 1,
191 				    low, high, PAGE_SIZE, 0) &&
192 				    (flags & M_WAITOK) != 0)
193 					VM_WAIT;
194 				VM_OBJECT_WLOCK(object);
195 				tries++;
196 				goto retry;
197 			}
198 			kmem_unback(object, addr, i);
199 			vmem_free(vmem, addr, size);
200 			return (0);
201 		}
202 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
203 			pmap_zero_page(m);
204 		m->valid = VM_PAGE_BITS_ALL;
205 		pmap_enter(kernel_pmap, addr + i, m, VM_PROT_ALL,
206 		    VM_PROT_ALL | PMAP_ENTER_WIRED, 0);
207 	}
208 	VM_OBJECT_WUNLOCK(object);
209 	return (addr);
210 }
211 
212 /*
213  *	Allocates a region from the kernel address map and physically
214  *	contiguous pages within the specified address range to the kernel
215  *	object.  Creates a wired mapping from this region to these pages, and
216  *	returns the region's starting virtual address.  If M_ZERO is specified
217  *	through the given flags, then the pages are zeroed before they are
218  *	mapped.
219  */
220 vm_offset_t
221 kmem_alloc_contig(struct vmem *vmem, vm_size_t size, int flags, vm_paddr_t low,
222     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
223     vm_memattr_t memattr)
224 {
225 	vm_object_t object = kernel_object;
226 	vm_offset_t addr, offset, tmp;
227 	vm_page_t end_m, m;
228 	u_long npages;
229 	int pflags, tries;
230 
231 	KASSERT(vmem == kernel_arena,
232 	    ("kmem_alloc_contig: Only kernel_arena is supported."));
233 	size = round_page(size);
234 	if (vmem_alloc(vmem, size, flags | M_BESTFIT, &addr))
235 		return (0);
236 	offset = addr - VM_MIN_KERNEL_ADDRESS;
237 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
238 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
239 	pflags |= VM_ALLOC_NOWAIT;
240 	npages = atop(size);
241 	VM_OBJECT_WLOCK(object);
242 	tries = 0;
243 retry:
244 	m = vm_page_alloc_contig(object, atop(offset), pflags,
245 	    npages, low, high, alignment, boundary, memattr);
246 	if (m == NULL) {
247 		VM_OBJECT_WUNLOCK(object);
248 		if (tries < ((flags & M_NOWAIT) != 0 ? 1 : 3)) {
249 			if (!vm_page_reclaim_contig(pflags, npages, low, high,
250 			    alignment, boundary) && (flags & M_WAITOK) != 0)
251 				VM_WAIT;
252 			VM_OBJECT_WLOCK(object);
253 			tries++;
254 			goto retry;
255 		}
256 		vmem_free(vmem, addr, size);
257 		return (0);
258 	}
259 	end_m = m + npages;
260 	tmp = addr;
261 	for (; m < end_m; m++) {
262 		if ((flags & M_ZERO) && (m->flags & PG_ZERO) == 0)
263 			pmap_zero_page(m);
264 		m->valid = VM_PAGE_BITS_ALL;
265 		pmap_enter(kernel_pmap, tmp, m, VM_PROT_ALL,
266 		    VM_PROT_ALL | PMAP_ENTER_WIRED, 0);
267 		tmp += PAGE_SIZE;
268 	}
269 	VM_OBJECT_WUNLOCK(object);
270 	return (addr);
271 }
272 
273 /*
274  *	kmem_suballoc:
275  *
276  *	Allocates a map to manage a subrange
277  *	of the kernel virtual address space.
278  *
279  *	Arguments are as follows:
280  *
281  *	parent		Map to take range from
282  *	min, max	Returned endpoints of map
283  *	size		Size of range to find
284  *	superpage_align	Request that min is superpage aligned
285  */
286 vm_map_t
287 kmem_suballoc(vm_map_t parent, vm_offset_t *min, vm_offset_t *max,
288     vm_size_t size, boolean_t superpage_align)
289 {
290 	int ret;
291 	vm_map_t result;
292 
293 	size = round_page(size);
294 
295 	*min = vm_map_min(parent);
296 	ret = vm_map_find(parent, NULL, 0, min, size, 0, superpage_align ?
297 	    VMFS_SUPER_SPACE : VMFS_ANY_SPACE, VM_PROT_ALL, VM_PROT_ALL,
298 	    MAP_ACC_NO_CHARGE);
299 	if (ret != KERN_SUCCESS)
300 		panic("kmem_suballoc: bad status return of %d", ret);
301 	*max = *min + size;
302 	result = vm_map_create(vm_map_pmap(parent), *min, *max);
303 	if (result == NULL)
304 		panic("kmem_suballoc: cannot create submap");
305 	if (vm_map_submap(parent, *min, *max, result) != KERN_SUCCESS)
306 		panic("kmem_suballoc: unable to change range to submap");
307 	return (result);
308 }
309 
310 /*
311  *	kmem_malloc:
312  *
313  *	Allocate wired-down pages in the kernel's address space.
314  */
315 vm_offset_t
316 kmem_malloc(struct vmem *vmem, vm_size_t size, int flags)
317 {
318 	vm_offset_t addr;
319 	int rv;
320 
321 	KASSERT(vmem == kernel_arena,
322 	    ("kmem_malloc: Only kernel_arena is supported."));
323 	size = round_page(size);
324 	if (vmem_alloc(vmem, size, flags | M_BESTFIT, &addr))
325 		return (0);
326 
327 	rv = kmem_back(kernel_object, addr, size, flags);
328 	if (rv != KERN_SUCCESS) {
329 		vmem_free(vmem, addr, size);
330 		return (0);
331 	}
332 	return (addr);
333 }
334 
335 /*
336  *	kmem_back:
337  *
338  *	Allocate physical pages for the specified virtual address range.
339  */
340 int
341 kmem_back(vm_object_t object, vm_offset_t addr, vm_size_t size, int flags)
342 {
343 	vm_offset_t offset, i;
344 	vm_page_t m, mpred;
345 	int pflags;
346 
347 	KASSERT(object == kernel_object,
348 	    ("kmem_back: only supports kernel object."));
349 
350 	offset = addr - VM_MIN_KERNEL_ADDRESS;
351 	pflags = malloc2vm_flags(flags) | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED;
352 	pflags &= ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
353 	if (flags & M_WAITOK)
354 		pflags |= VM_ALLOC_WAITFAIL;
355 
356 	i = 0;
357 	VM_OBJECT_WLOCK(object);
358 retry:
359 	mpred = vm_radix_lookup_le(&object->rtree, atop(offset + i));
360 	for (; i < size; i += PAGE_SIZE, mpred = m) {
361 		m = vm_page_alloc_after(object, atop(offset + i), pflags,
362 		    mpred);
363 
364 		/*
365 		 * Ran out of space, free everything up and return. Don't need
366 		 * to lock page queues here as we know that the pages we got
367 		 * aren't on any queues.
368 		 */
369 		if (m == NULL) {
370 			if ((flags & M_NOWAIT) == 0)
371 				goto retry;
372 			VM_OBJECT_WUNLOCK(object);
373 			kmem_unback(object, addr, i);
374 			return (KERN_NO_SPACE);
375 		}
376 		if (flags & M_ZERO && (m->flags & PG_ZERO) == 0)
377 			pmap_zero_page(m);
378 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
379 		    ("kmem_malloc: page %p is managed", m));
380 		m->valid = VM_PAGE_BITS_ALL;
381 		pmap_enter(kernel_pmap, addr + i, m, VM_PROT_ALL,
382 		    VM_PROT_ALL | PMAP_ENTER_WIRED, 0);
383 	}
384 	VM_OBJECT_WUNLOCK(object);
385 
386 	return (KERN_SUCCESS);
387 }
388 
389 /*
390  *	kmem_unback:
391  *
392  *	Unmap and free the physical pages underlying the specified virtual
393  *	address range.
394  *
395  *	A physical page must exist within the specified object at each index
396  *	that is being unmapped.
397  */
398 void
399 kmem_unback(vm_object_t object, vm_offset_t addr, vm_size_t size)
400 {
401 	vm_page_t m, next;
402 	vm_offset_t end, offset;
403 
404 	KASSERT(object == kernel_object,
405 	    ("kmem_unback: only supports kernel object."));
406 
407 	pmap_remove(kernel_pmap, addr, addr + size);
408 	offset = addr - VM_MIN_KERNEL_ADDRESS;
409 	end = offset + size;
410 	VM_OBJECT_WLOCK(object);
411 	for (m = vm_page_lookup(object, atop(offset)); offset < end;
412 	    offset += PAGE_SIZE, m = next) {
413 		next = vm_page_next(m);
414 		vm_page_unwire(m, PQ_NONE);
415 		vm_page_free(m);
416 	}
417 	VM_OBJECT_WUNLOCK(object);
418 }
419 
420 /*
421  *	kmem_free:
422  *
423  *	Free memory allocated with kmem_malloc.  The size must match the
424  *	original allocation.
425  */
426 void
427 kmem_free(struct vmem *vmem, vm_offset_t addr, vm_size_t size)
428 {
429 
430 	KASSERT(vmem == kernel_arena,
431 	    ("kmem_free: Only kernel_arena is supported."));
432 	size = round_page(size);
433 	kmem_unback(kernel_object, addr, size);
434 	vmem_free(vmem, addr, size);
435 }
436 
437 /*
438  *	kmap_alloc_wait:
439  *
440  *	Allocates pageable memory from a sub-map of the kernel.  If the submap
441  *	has no room, the caller sleeps waiting for more memory in the submap.
442  *
443  *	This routine may block.
444  */
445 vm_offset_t
446 kmap_alloc_wait(vm_map_t map, vm_size_t size)
447 {
448 	vm_offset_t addr;
449 
450 	size = round_page(size);
451 	if (!swap_reserve(size))
452 		return (0);
453 
454 	for (;;) {
455 		/*
456 		 * To make this work for more than one map, use the map's lock
457 		 * to lock out sleepers/wakers.
458 		 */
459 		vm_map_lock(map);
460 		if (vm_map_findspace(map, vm_map_min(map), size, &addr) == 0)
461 			break;
462 		/* no space now; see if we can ever get space */
463 		if (vm_map_max(map) - vm_map_min(map) < size) {
464 			vm_map_unlock(map);
465 			swap_release(size);
466 			return (0);
467 		}
468 		map->needs_wakeup = TRUE;
469 		vm_map_unlock_and_wait(map, 0);
470 	}
471 	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_ALL,
472 	    VM_PROT_ALL, MAP_ACC_CHARGED);
473 	vm_map_unlock(map);
474 	return (addr);
475 }
476 
477 /*
478  *	kmap_free_wakeup:
479  *
480  *	Returns memory to a submap of the kernel, and wakes up any processes
481  *	waiting for memory in that map.
482  */
483 void
484 kmap_free_wakeup(vm_map_t map, vm_offset_t addr, vm_size_t size)
485 {
486 
487 	vm_map_lock(map);
488 	(void) vm_map_delete(map, trunc_page(addr), round_page(addr + size));
489 	if (map->needs_wakeup) {
490 		map->needs_wakeup = FALSE;
491 		vm_map_wakeup(map);
492 	}
493 	vm_map_unlock(map);
494 }
495 
496 void
497 kmem_init_zero_region(void)
498 {
499 	vm_offset_t addr, i;
500 	vm_page_t m;
501 
502 	/*
503 	 * Map a single physical page of zeros to a larger virtual range.
504 	 * This requires less looping in places that want large amounts of
505 	 * zeros, while not using much more physical resources.
506 	 */
507 	addr = kva_alloc(ZERO_REGION_SIZE);
508 	m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
509 	    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
510 	if ((m->flags & PG_ZERO) == 0)
511 		pmap_zero_page(m);
512 	for (i = 0; i < ZERO_REGION_SIZE; i += PAGE_SIZE)
513 		pmap_qenter(addr + i, &m, 1);
514 	pmap_protect(kernel_pmap, addr, addr + ZERO_REGION_SIZE, VM_PROT_READ);
515 
516 	zero_region = (const void *)addr;
517 }
518 
519 /*
520  * 	kmem_init:
521  *
522  *	Create the kernel map; insert a mapping covering kernel text,
523  *	data, bss, and all space allocated thus far (`boostrap' data).  The
524  *	new map will thus map the range between VM_MIN_KERNEL_ADDRESS and
525  *	`start' as allocated, and the range between `start' and `end' as free.
526  */
527 void
528 kmem_init(vm_offset_t start, vm_offset_t end)
529 {
530 	vm_map_t m;
531 
532 	m = vm_map_create(kernel_pmap, VM_MIN_KERNEL_ADDRESS, end);
533 	m->system_map = 1;
534 	vm_map_lock(m);
535 	/* N.B.: cannot use kgdb to debug, starting with this assignment ... */
536 	kernel_map = m;
537 	(void) vm_map_insert(m, NULL, (vm_ooffset_t) 0,
538 #ifdef __amd64__
539 	    KERNBASE,
540 #else
541 	    VM_MIN_KERNEL_ADDRESS,
542 #endif
543 	    start, VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
544 	/* ... and ending with the completion of the above `insert' */
545 	vm_map_unlock(m);
546 }
547 
548 #ifdef DIAGNOSTIC
549 /*
550  * Allow userspace to directly trigger the VM drain routine for testing
551  * purposes.
552  */
553 static int
554 debug_vm_lowmem(SYSCTL_HANDLER_ARGS)
555 {
556 	int error, i;
557 
558 	i = 0;
559 	error = sysctl_handle_int(oidp, &i, 0, req);
560 	if (error)
561 		return (error);
562 	if ((i & ~(VM_LOW_KMEM | VM_LOW_PAGES)) != 0)
563 		return (EINVAL);
564 	if (i != 0)
565 		EVENTHANDLER_INVOKE(vm_lowmem, i);
566 	return (0);
567 }
568 
569 SYSCTL_PROC(_debug, OID_AUTO, vm_lowmem, CTLTYPE_INT | CTLFLAG_RW, 0, 0,
570     debug_vm_lowmem, "I", "set to trigger vm_lowmem event with given flags");
571 #endif
572