xref: /freebsd-14-stable/sys/kern/subr_physmem.c (revision 3756a1c62af2f326419572d6fc5789c52567e32e)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2014 Ian Lepore <ian@freebsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #ifdef _KERNEL
31 #include "opt_acpi.h"
32 #include "opt_ddb.h"
33 #endif
34 
35 /*
36  * Routines for describing and initializing anything related to physical memory.
37  */
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/bus.h>
42 #include <sys/kernel.h>
43 #include <sys/module.h>
44 #include <sys/physmem.h>
45 
46 #ifdef _KERNEL
47 #include <vm/vm.h>
48 #include <vm/vm_param.h>
49 #include <vm/vm_page.h>
50 #include <vm/vm_phys.h>
51 #include <vm/vm_dumpset.h>
52 
53 #include <machine/md_var.h>
54 #include <machine/resource.h>
55 #else
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <string.h>
59 #endif
60 
61 /*
62  * These structures are used internally to keep track of regions of physical
63  * ram, and regions within the physical ram that need to be excluded.  An
64  * exclusion region can be excluded from crash dumps, from the vm pool of pages
65  * that can be allocated, or both, depending on the exclusion flags associated
66  * with the region.
67  */
68 #ifdef DEV_ACPI
69 #define	MAX_HWCNT	32	/* ACPI needs more regions */
70 #define	MAX_EXCNT	32
71 #else
72 #define	MAX_HWCNT	16
73 #define	MAX_EXCNT	16
74 #endif
75 
76 #if defined(__arm__)
77 #define	MAX_PHYS_ADDR	0xFFFFFFFFull
78 #elif defined(__aarch64__) || defined(__amd64__) || defined(__riscv)
79 #define	MAX_PHYS_ADDR	0xFFFFFFFFFFFFFFFFull
80 #endif
81 
82 struct region {
83 	vm_paddr_t	addr;
84 	vm_size_t	size;
85 	uint32_t	flags;
86 };
87 
88 static struct region hwregions[MAX_HWCNT];
89 static struct region exregions[MAX_EXCNT];
90 
91 static size_t hwcnt;
92 static size_t excnt;
93 
94 /*
95  * realmem is the total number of hardware pages, excluded or not.
96  * Maxmem is one greater than the last physical page number.
97  */
98 long realmem;
99 long Maxmem;
100 
101 #ifndef _KERNEL
102 static void
panic(const char * fmt,...)103 panic(const char *fmt, ...)
104 {
105 	va_list va;
106 
107 	va_start(va, fmt);
108 	vfprintf(stderr, fmt, va);
109 	fprintf(stderr, "\n");
110 	va_end(va);
111 	__builtin_trap();
112 }
113 #endif
114 
115 /*
116  * Print the contents of the physical and excluded region tables using the
117  * provided printf-like output function (which will be either printf or
118  * db_printf).
119  */
120 static void
121 physmem_dump_tables(int (*prfunc)(const char *, ...) __printflike(1, 2))
122 {
123 	size_t i;
124 	int flags;
125 	uintmax_t addr, size;
126 	const unsigned int mbyte = 1024 * 1024;
127 
128 	prfunc("Physical memory chunk(s):\n");
129 	for (i = 0; i < hwcnt; ++i) {
130 		addr = hwregions[i].addr;
131 		size = hwregions[i].size;
132 		prfunc("  0x%08jx - 0x%08jx, %5ju MB (%7ju pages)\n", addr,
133 		    addr + size - 1, size / mbyte, size / PAGE_SIZE);
134 	}
135 
136 	prfunc("Excluded memory regions:\n");
137 	for (i = 0; i < excnt; ++i) {
138 		addr  = exregions[i].addr;
139 		size  = exregions[i].size;
140 		flags = exregions[i].flags;
141 		prfunc("  0x%08jx - 0x%08jx, %5ju MB (%7ju pages) %s %s\n",
142 		    addr, addr + size - 1, size / mbyte, size / PAGE_SIZE,
143 		    (flags & EXFLAG_NOALLOC) ? "NoAlloc" : "",
144 		    (flags & EXFLAG_NODUMP)  ? "NoDump" : "");
145 	}
146 
147 #ifdef DEBUG
148 	prfunc("Avail lists:\n");
149 	for (i = 0; phys_avail[i] != 0; ++i) {
150 		prfunc("  phys_avail[%zu] 0x%08jx\n", i,
151 		    (uintmax_t)phys_avail[i]);
152 	}
153 	for (i = 0; dump_avail[i] != 0; ++i) {
154 		prfunc("  dump_avail[%zu] 0x%08jx\n", i,
155 		    (uintmax_t)dump_avail[i]);
156 	}
157 #endif
158 }
159 
160 /*
161  * Print the contents of the static mapping table.  Used for bootverbose.
162  */
163 void
physmem_print_tables(void)164 physmem_print_tables(void)
165 {
166 
167 	physmem_dump_tables(printf);
168 }
169 
170 /*
171  * Walk the list of hardware regions, processing it against the list of
172  * exclusions that contain the given exflags, and generating an "avail list".
173  *
174  * If maxphyssz is not zero it sets upper limit, in bytes, for the total
175  * "avail list" size. Walk stops once the limit is reached and the last region
176  * is cut short if necessary.
177  *
178  * Updates the value at *pavail with the sum of all pages in all hw regions.
179  *
180  * Returns the number of entries in the avail list, which is twice the number
181  * of returned regions.
182  */
183 static size_t
regions_to_avail(vm_paddr_t * avail,uint32_t exflags,size_t maxavail,uint64_t maxphyssz,long * pavail,long * prealmem)184 regions_to_avail(vm_paddr_t *avail, uint32_t exflags, size_t maxavail,
185     uint64_t maxphyssz, long *pavail, long *prealmem)
186 {
187 	size_t acnt, exi, hwi;
188 	uint64_t adj, end, start, xend, xstart;
189 	long availmem, totalmem;
190 	const struct region *exp, *hwp;
191 	uint64_t availsz;
192 
193 	totalmem = 0;
194 	availmem = 0;
195 	availsz = 0;
196 	acnt = 0;
197 	for (hwi = 0, hwp = hwregions; hwi < hwcnt; ++hwi, ++hwp) {
198 		adj   = round_page(hwp->addr) - hwp->addr;
199 		start = round_page(hwp->addr);
200 		end   = trunc_page(hwp->size + adj) + start;
201 		totalmem += atop((vm_offset_t)(end - start));
202 		for (exi = 0, exp = exregions; exi < excnt; ++exi, ++exp) {
203 			/*
204 			 * If the excluded region does not match given flags,
205 			 * continue checking with the next excluded region.
206 			 */
207 			if ((exp->flags & exflags) == 0)
208 				continue;
209 			xstart = exp->addr;
210 			xend   = exp->size + xstart;
211 			/*
212 			 * If the excluded region ends before this hw region,
213 			 * continue checking with the next excluded region.
214 			 */
215 			if (xend <= start)
216 				continue;
217 			/*
218 			 * If the excluded region begins after this hw region
219 			 * we're done because both lists are sorted.
220 			 */
221 			if (xstart >= end)
222 				break;
223 			/*
224 			 * If the excluded region completely covers this hw
225 			 * region, shrink this hw region to zero size.
226 			 */
227 			if ((start >= xstart) && (end <= xend)) {
228 				start = xend;
229 				end = xend;
230 				break;
231 			}
232 			/*
233 			 * If the excluded region falls wholly within this hw
234 			 * region without abutting or overlapping the beginning
235 			 * or end, create an available entry from the leading
236 			 * fragment, then adjust the start of this hw region to
237 			 * the end of the excluded region, and continue checking
238 			 * the next excluded region because another exclusion
239 			 * could affect the remainder of this hw region.
240 			 */
241 			if ((xstart > start) && (xend < end)) {
242 
243 				if ((maxphyssz != 0) &&
244 				    (availsz + xstart - start > maxphyssz)) {
245 					xstart = maxphyssz + start - availsz;
246 				}
247 				if (xstart <= start)
248 					continue;
249 				if (acnt > 0 &&
250 				    avail[acnt - 1] == (vm_paddr_t)start) {
251 					avail[acnt - 1] = (vm_paddr_t)xstart;
252 				} else {
253 					avail[acnt++] = (vm_paddr_t)start;
254 					avail[acnt++] = (vm_paddr_t)xstart;
255 				}
256 				availsz += (xstart - start);
257 				availmem += atop((vm_offset_t)(xstart - start));
258 				start = xend;
259 				continue;
260 			}
261 			/*
262 			 * We know the excluded region overlaps either the start
263 			 * or end of this hardware region (but not both), trim
264 			 * the excluded portion off the appropriate end.
265 			 */
266 			if (xstart <= start)
267 				start = xend;
268 			else
269 				end = xstart;
270 		}
271 		/*
272 		 * If the trimming actions above left a non-zero size, create an
273 		 * available entry for it.
274 		 */
275 		if (end > start) {
276 			if ((maxphyssz != 0) &&
277 			    (availsz + end - start > maxphyssz)) {
278 				end = maxphyssz + start - availsz;
279 			}
280 			if (end <= start)
281 				break;
282 
283 			if (acnt > 0 && avail[acnt - 1] == (vm_paddr_t)start) {
284 				avail[acnt - 1] = (vm_paddr_t)end;
285 			} else {
286 				avail[acnt++] = (vm_paddr_t)start;
287 				avail[acnt++] = (vm_paddr_t)end;
288 			}
289 			availsz += end - start;
290 			availmem += atop((vm_offset_t)(end - start));
291 		}
292 		if (acnt >= maxavail)
293 			panic("Not enough space in the dump/phys_avail arrays");
294 	}
295 
296 	if (pavail != NULL)
297 		*pavail = availmem;
298 	if (prealmem != NULL)
299 		*prealmem = totalmem;
300 	return (acnt);
301 }
302 
303 /*
304  * Check if the region at idx can be merged with the region above it.
305  */
306 static size_t
merge_upper_regions(struct region * regions,size_t rcnt,size_t idx)307 merge_upper_regions(struct region *regions, size_t rcnt, size_t idx)
308 {
309 	struct region *lower, *upper;
310 	vm_paddr_t lend, uend;
311 	size_t i, mergecnt, movecnt;
312 
313 	lower = &regions[idx];
314 	lend = lower->addr + lower->size;
315 
316 	/*
317 	 * Continue merging in upper entries as long as we have entries to
318 	 * merge; the new block could have spanned more than one, although one
319 	 * is likely the common case.
320 	 */
321 	for (i = idx + 1; i < rcnt; i++) {
322 		upper = &regions[i];
323 		if (lend < upper->addr || lower->flags != upper->flags)
324 			break;
325 
326 		uend = upper->addr + upper->size;
327 		if (uend > lend) {
328 			lower->size += uend - lend;
329 			lend = lower->addr + lower->size;
330 		}
331 
332 		if (uend >= lend) {
333 			/*
334 			 * If we didn't move past the end of the upper region,
335 			 * then we don't need to bother checking for another
336 			 * merge because it would have been done already.  Just
337 			 * increment i once more to maintain the invariant that
338 			 * i is one past the last entry merged.
339 			 */
340 			i++;
341 			break;
342 		}
343 	}
344 
345 	/*
346 	 * We merged in the entries from [idx + 1, i); physically move the tail
347 	 * end at [i, rcnt) if we need to.
348 	 */
349 	mergecnt = i - (idx + 1);
350 	if (mergecnt > 0) {
351 		movecnt = rcnt - i;
352 		if (movecnt == 0) {
353 			/* Merged all the way to the end, just decrease rcnt. */
354 			rcnt = idx + 1;
355 		} else {
356 			memmove(&regions[idx + 1], &regions[idx + mergecnt + 1],
357 			    movecnt * sizeof(*regions));
358 			rcnt -= mergecnt;
359 		}
360 	}
361 	return (rcnt);
362 }
363 
364 /*
365  * Insertion-sort a new entry into a regions list; sorted by start address.
366  */
367 static size_t
insert_region(struct region * regions,size_t rcnt,vm_paddr_t addr,vm_size_t size,uint32_t flags)368 insert_region(struct region *regions, size_t rcnt, vm_paddr_t addr,
369     vm_size_t size, uint32_t flags)
370 {
371 	size_t i;
372 	vm_paddr_t nend, rend;
373 	struct region *ep, *rp;
374 
375 	nend = addr + size;
376 	ep = regions + rcnt;
377 	for (i = 0, rp = regions; i < rcnt; ++i, ++rp) {
378 		rend = rp->addr + rp->size;
379 		if (flags == rp->flags) {
380 			if (addr <= rp->addr && nend >= rp->addr) {
381 				/*
382 				 * New mapping overlaps at the beginning, shift
383 				 * for any difference in the beginning then
384 				 * shift if the new mapping extends past.
385 				 */
386 				rp->size += rp->addr - addr;
387 				rp->addr = addr;
388 				if (nend > rend) {
389 					rp->size += nend - rend;
390 					rcnt = merge_upper_regions(regions,
391 					    rcnt, i);
392 				}
393 				return (rcnt);
394 			} else if (addr <= rend && nend > rp->addr) {
395 				/*
396 				 * New mapping is either entirely contained
397 				 * within or it's overlapping at the end.
398 				 */
399 				if (nend > rend) {
400 					rp->size += nend - rend;
401 					rcnt = merge_upper_regions(regions,
402 					    rcnt, i);
403 				}
404 				return (rcnt);
405 			}
406 		} else if ((flags != 0) && (rp->flags != 0)) {
407 			/*
408 			 * If we're duplicating an entry that already exists
409 			 * exactly, just upgrade its flags as needed.  We could
410 			 * do more if we find that we have differently specified
411 			 * flags clipping existing excluding regions, but that's
412 			 * probably rare.
413 			 */
414 			if (addr == rp->addr && nend == rend) {
415 				rp->flags |= flags;
416 				return (rcnt);
417 			}
418 		}
419 
420 		if (addr < rp->addr) {
421 			bcopy(rp, rp + 1, (ep - rp) * sizeof(*rp));
422 			break;
423 		}
424 	}
425 	rp->addr  = addr;
426 	rp->size  = size;
427 	rp->flags = flags;
428 	rcnt++;
429 
430 	return (rcnt);
431 }
432 
433 /*
434  * Add a hardware memory region.
435  */
436 void
physmem_hardware_region(uint64_t pa,uint64_t sz)437 physmem_hardware_region(uint64_t pa, uint64_t sz)
438 {
439 	/*
440 	 * Filter out the page at PA 0x00000000.  The VM can't handle it, as
441 	 * pmap_extract() == 0 means failure.
442 	 */
443 	if (pa == 0) {
444 		if (sz <= PAGE_SIZE)
445 			return;
446 		pa  = PAGE_SIZE;
447 		sz -= PAGE_SIZE;
448 	} else if (pa > MAX_PHYS_ADDR) {
449 		/* This range is past usable memory, ignore it */
450 		return;
451 	}
452 
453 	/*
454 	 * Also filter out the page at the end of the physical address space --
455 	 * if addr is non-zero and addr+size is zero we wrapped to the next byte
456 	 * beyond what vm_paddr_t can express.  That leads to a NULL pointer
457 	 * deref early in startup; work around it by leaving the last page out.
458 	 *
459 	 * XXX This just in:  subtract out a whole megabyte, not just 1 page.
460 	 * Reducing the size by anything less than 1MB results in the NULL
461 	 * pointer deref in _vm_map_lock_read().  Better to give up a megabyte
462 	 * than leave some folks with an unusable system while we investigate.
463 	 */
464 	if ((pa + sz) > (MAX_PHYS_ADDR - 1024 * 1024)) {
465 		sz = MAX_PHYS_ADDR - pa + 1;
466 		if (sz <= 1024 * 1024)
467 			return;
468 		sz -= 1024 * 1024;
469 	}
470 
471 	if (sz > 0 && hwcnt < nitems(hwregions))
472 		hwcnt = insert_region(hwregions, hwcnt, pa, sz, 0);
473 }
474 
475 /*
476  * Add an exclusion region.
477  */
478 void
physmem_exclude_region(vm_paddr_t pa,vm_size_t sz,uint32_t exflags)479 physmem_exclude_region(vm_paddr_t pa, vm_size_t sz, uint32_t exflags)
480 {
481 	vm_offset_t adj;
482 
483 	/*
484 	 * Truncate the starting address down to a page boundary, and round the
485 	 * ending page up to a page boundary.
486 	 */
487 	adj = pa - trunc_page(pa);
488 	pa  = trunc_page(pa);
489 	sz  = round_page(sz + adj);
490 
491 	if (excnt >= nitems(exregions))
492 		panic("failed to exclude region %#jx-%#jx", (uintmax_t)pa,
493 		    (uintmax_t)(pa + sz));
494 	excnt = insert_region(exregions, excnt, pa, sz, exflags);
495 }
496 
497 size_t
physmem_avail(vm_paddr_t * avail,size_t maxavail)498 physmem_avail(vm_paddr_t *avail, size_t maxavail)
499 {
500 
501 	return (regions_to_avail(avail, EXFLAG_NOALLOC, maxavail, 0, NULL, NULL));
502 }
503 
504 bool
physmem_excluded(vm_paddr_t pa,vm_size_t sz)505 physmem_excluded(vm_paddr_t pa, vm_size_t sz)
506 {
507 	const struct region *exp;
508 	size_t exi;
509 
510 	for (exi = 0, exp = exregions; exi < excnt; ++exi, ++exp) {
511 		if (pa < exp->addr || pa + sz > exp->addr + exp->size)
512 			continue;
513 		return (true);
514 	}
515 	return (false);
516 }
517 
518 #ifdef _KERNEL
519 /*
520  * Process all the regions added earlier into the global avail lists.
521  *
522  * Updates the kernel global 'physmem' with the number of physical pages
523  * available for use (all pages not in any exclusion region).
524  *
525  * Updates the kernel global 'Maxmem' with the page number one greater then the
526  * last page of physical memory in the system.
527  */
528 void
physmem_init_kernel_globals(void)529 physmem_init_kernel_globals(void)
530 {
531 	size_t nextidx;
532 	u_long hwphyssz;
533 
534 	hwphyssz = 0;
535 	TUNABLE_ULONG_FETCH("hw.physmem", &hwphyssz);
536 
537 	regions_to_avail(dump_avail, EXFLAG_NODUMP, PHYS_AVAIL_ENTRIES,
538 	    hwphyssz, NULL, NULL);
539 	nextidx = regions_to_avail(phys_avail, EXFLAG_NOALLOC,
540 	    PHYS_AVAIL_ENTRIES, hwphyssz, &physmem, &realmem);
541 	if (nextidx == 0)
542 		panic("No memory entries in phys_avail");
543 	Maxmem = atop(phys_avail[nextidx - 1]);
544 }
545 
546 #ifdef DDB
547 #include <ddb/ddb.h>
548 
DB_SHOW_COMMAND_FLAGS(physmem,db_show_physmem,DB_CMD_MEMSAFE)549 DB_SHOW_COMMAND_FLAGS(physmem, db_show_physmem, DB_CMD_MEMSAFE)
550 {
551 
552 	physmem_dump_tables(db_printf);
553 }
554 
555 #endif /* DDB */
556 
557 /*
558  * ram pseudo driver - this reserves I/O space resources corresponding to physical
559  * memory regions.
560  */
561 
562 static void
ram_identify(driver_t * driver,device_t parent)563 ram_identify(driver_t *driver, device_t parent)
564 {
565 
566 	if (resource_disabled("ram", 0))
567 		return;
568 	if (BUS_ADD_CHILD(parent, 0, "ram", 0) == NULL)
569 		panic("ram_identify");
570 }
571 
572 static int
ram_probe(device_t dev)573 ram_probe(device_t dev)
574 {
575 
576 	device_quiet(dev);
577 	device_set_desc(dev, "System RAM");
578 	return (BUS_PROBE_SPECIFIC);
579 }
580 
581 static int
ram_attach(device_t dev)582 ram_attach(device_t dev)
583 {
584 	vm_paddr_t avail_list[PHYS_AVAIL_COUNT];
585 	rman_res_t start, end;
586 	int rid, i;
587 
588 	rid = 0;
589 
590 	/* Get the avail list. */
591 	bzero(avail_list, sizeof(avail_list));
592 	regions_to_avail(avail_list, EXFLAG_NOALLOC | EXFLAG_NODUMP,
593 	    PHYS_AVAIL_COUNT, 0, NULL, NULL);
594 
595 	/* Reserve all memory regions. */
596 	for (i = 0; avail_list[i + 1] != 0; i += 2) {
597 		start = avail_list[i];
598 		end = avail_list[i + 1];
599 
600 		if (bootverbose)
601 			device_printf(dev,
602 			    "reserving memory region:   %jx-%jx\n",
603 			    (uintmax_t)start, (uintmax_t)end);
604 
605 		if (bus_alloc_resource(dev, SYS_RES_MEMORY, &rid, start, end,
606 		    end - start, 0) == NULL)
607 			panic("ram_attach: resource %d failed to attach", rid);
608 		rid++;
609 	}
610 
611 	return (0);
612 }
613 
614 static device_method_t ram_methods[] = {
615 	/* Device interface */
616 	DEVMETHOD(device_identify,	ram_identify),
617 	DEVMETHOD(device_probe,		ram_probe),
618 	DEVMETHOD(device_attach,	ram_attach),
619 
620 	DEVMETHOD_END
621 };
622 
623 DEFINE_CLASS_0(ram, ram_driver, ram_methods, /* no softc */ 1);
624 DRIVER_MODULE(ram, nexus, ram_driver, 0, 0);
625 #endif /* _KERNEL */
626