xref: /freebsd-14-stable/sys/vm/vm_phys.c (revision 6230945b8819f51d2f46ea16a3437fdc91665f90)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002-2006 Rice University
5  * Copyright (c) 2007 Alan L. Cox <alc@cs.rice.edu>
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Alan L. Cox,
9  * Olivier Crameri, Peter Druschel, Sitaram Iyer, and Juan Navarro.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
24  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
30  * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  *	Physical memory system implementation
36  *
37  * Any external functions defined by this module are only to be used by the
38  * virtual memory system.
39  */
40 
41 #include <sys/cdefs.h>
42 #include "opt_ddb.h"
43 #include "opt_vm.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/domainset.h>
48 #include <sys/lock.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/queue.h>
54 #include <sys/rwlock.h>
55 #include <sys/sbuf.h>
56 #include <sys/sysctl.h>
57 #include <sys/tree.h>
58 #include <sys/vmmeter.h>
59 
60 #include <ddb/ddb.h>
61 
62 #include <vm/vm.h>
63 #include <vm/vm_extern.h>
64 #include <vm/vm_param.h>
65 #include <vm/vm_kern.h>
66 #include <vm/vm_object.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_phys.h>
69 #include <vm/vm_pagequeue.h>
70 
71 _Static_assert(sizeof(long) * NBBY >= VM_PHYSSEG_MAX,
72     "Too many physsegs.");
73 _Static_assert(sizeof(long long) >= sizeof(vm_paddr_t),
74     "vm_paddr_t too big for ffsll, flsll.");
75 
76 #ifdef NUMA
77 struct mem_affinity __read_mostly *mem_affinity;
78 int __read_mostly *mem_locality;
79 
80 static int numa_disabled;
81 static SYSCTL_NODE(_vm, OID_AUTO, numa, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
82     "NUMA options");
83 SYSCTL_INT(_vm_numa, OID_AUTO, disabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
84     &numa_disabled, 0, "NUMA-awareness in the allocators is disabled");
85 #endif
86 
87 int __read_mostly vm_ndomains = 1;
88 domainset_t __read_mostly all_domains = DOMAINSET_T_INITIALIZER(0x1);
89 
90 struct vm_phys_seg __read_mostly vm_phys_segs[VM_PHYSSEG_MAX];
91 int __read_mostly vm_phys_nsegs;
92 static struct vm_phys_seg vm_phys_early_segs[8];
93 static int vm_phys_early_nsegs;
94 
95 struct vm_phys_fictitious_seg;
96 static int vm_phys_fictitious_cmp(struct vm_phys_fictitious_seg *,
97     struct vm_phys_fictitious_seg *);
98 
99 RB_HEAD(fict_tree, vm_phys_fictitious_seg) vm_phys_fictitious_tree =
100     RB_INITIALIZER(&vm_phys_fictitious_tree);
101 
102 struct vm_phys_fictitious_seg {
103 	RB_ENTRY(vm_phys_fictitious_seg) node;
104 	/* Memory region data */
105 	vm_paddr_t	start;
106 	vm_paddr_t	end;
107 	vm_page_t	first_page;
108 };
109 
110 RB_GENERATE_STATIC(fict_tree, vm_phys_fictitious_seg, node,
111     vm_phys_fictitious_cmp);
112 
113 static struct rwlock_padalign vm_phys_fictitious_reg_lock;
114 MALLOC_DEFINE(M_FICT_PAGES, "vm_fictitious", "Fictitious VM pages");
115 
116 static struct vm_freelist __aligned(CACHE_LINE_SIZE)
117     vm_phys_free_queues[MAXMEMDOM][VM_NFREELIST][VM_NFREEPOOL]
118     [VM_NFREEORDER_MAX];
119 
120 static int __read_mostly vm_nfreelists;
121 
122 /*
123  * These "avail lists" are globals used to communicate boot-time physical
124  * memory layout to other parts of the kernel.  Each physically contiguous
125  * region of memory is defined by a start address at an even index and an
126  * end address at the following odd index.  Each list is terminated by a
127  * pair of zero entries.
128  *
129  * dump_avail tells the dump code what regions to include in a crash dump, and
130  * phys_avail is all of the remaining physical memory that is available for
131  * the vm system.
132  *
133  * Initially dump_avail and phys_avail are identical.  Boot time memory
134  * allocations remove extents from phys_avail that may still be included
135  * in dumps.
136  */
137 vm_paddr_t phys_avail[PHYS_AVAIL_COUNT];
138 vm_paddr_t dump_avail[PHYS_AVAIL_COUNT];
139 
140 /*
141  * Provides the mapping from VM_FREELIST_* to free list indices (flind).
142  */
143 static int __read_mostly vm_freelist_to_flind[VM_NFREELIST];
144 
145 CTASSERT(VM_FREELIST_DEFAULT == 0);
146 
147 #ifdef VM_FREELIST_DMA32
148 #define	VM_DMA32_BOUNDARY	((vm_paddr_t)1 << 32)
149 #endif
150 
151 /*
152  * Enforce the assumptions made by vm_phys_add_seg() and vm_phys_init() about
153  * the ordering of the free list boundaries.
154  */
155 #if defined(VM_LOWMEM_BOUNDARY) && defined(VM_DMA32_BOUNDARY)
156 CTASSERT(VM_LOWMEM_BOUNDARY < VM_DMA32_BOUNDARY);
157 #endif
158 
159 static int sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS);
160 SYSCTL_OID(_vm, OID_AUTO, phys_free,
161     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
162     sysctl_vm_phys_free, "A",
163     "Phys Free Info");
164 
165 static int sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS);
166 SYSCTL_OID(_vm, OID_AUTO, phys_segs,
167     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
168     sysctl_vm_phys_segs, "A",
169     "Phys Seg Info");
170 
171 #ifdef NUMA
172 static int sysctl_vm_phys_locality(SYSCTL_HANDLER_ARGS);
173 SYSCTL_OID(_vm, OID_AUTO, phys_locality,
174     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
175     sysctl_vm_phys_locality, "A",
176     "Phys Locality Info");
177 #endif
178 
179 SYSCTL_INT(_vm, OID_AUTO, ndomains, CTLFLAG_RD,
180     &vm_ndomains, 0, "Number of physical memory domains available.");
181 
182 static void _vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int domain);
183 static void vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end);
184 static void vm_phys_split_pages(vm_page_t m, int oind, struct vm_freelist *fl,
185     int order, int tail);
186 
187 /*
188  * Red-black tree helpers for vm fictitious range management.
189  */
190 static inline int
vm_phys_fictitious_in_range(struct vm_phys_fictitious_seg * p,struct vm_phys_fictitious_seg * range)191 vm_phys_fictitious_in_range(struct vm_phys_fictitious_seg *p,
192     struct vm_phys_fictitious_seg *range)
193 {
194 
195 	KASSERT(range->start != 0 && range->end != 0,
196 	    ("Invalid range passed on search for vm_fictitious page"));
197 	if (p->start >= range->end)
198 		return (1);
199 	if (p->start < range->start)
200 		return (-1);
201 
202 	return (0);
203 }
204 
205 static int
vm_phys_fictitious_cmp(struct vm_phys_fictitious_seg * p1,struct vm_phys_fictitious_seg * p2)206 vm_phys_fictitious_cmp(struct vm_phys_fictitious_seg *p1,
207     struct vm_phys_fictitious_seg *p2)
208 {
209 
210 	/* Check if this is a search for a page */
211 	if (p1->end == 0)
212 		return (vm_phys_fictitious_in_range(p1, p2));
213 
214 	KASSERT(p2->end != 0,
215     ("Invalid range passed as second parameter to vm fictitious comparison"));
216 
217 	/* Searching to add a new range */
218 	if (p1->end <= p2->start)
219 		return (-1);
220 	if (p1->start >= p2->end)
221 		return (1);
222 
223 	panic("Trying to add overlapping vm fictitious ranges:\n"
224 	    "[%#jx:%#jx] and [%#jx:%#jx]", (uintmax_t)p1->start,
225 	    (uintmax_t)p1->end, (uintmax_t)p2->start, (uintmax_t)p2->end);
226 }
227 
228 int
vm_phys_domain_match(int prefer,vm_paddr_t low,vm_paddr_t high)229 vm_phys_domain_match(int prefer, vm_paddr_t low, vm_paddr_t high)
230 {
231 #ifdef NUMA
232 	domainset_t mask;
233 	int i;
234 
235 	if (vm_ndomains == 1 || mem_affinity == NULL)
236 		return (0);
237 
238 	DOMAINSET_ZERO(&mask);
239 	/*
240 	 * Check for any memory that overlaps low, high.
241 	 */
242 	for (i = 0; mem_affinity[i].end != 0; i++)
243 		if (mem_affinity[i].start <= high &&
244 		    mem_affinity[i].end >= low)
245 			DOMAINSET_SET(mem_affinity[i].domain, &mask);
246 	if (prefer != -1 && DOMAINSET_ISSET(prefer, &mask))
247 		return (prefer);
248 	if (DOMAINSET_EMPTY(&mask))
249 		panic("vm_phys_domain_match:  Impossible constraint");
250 	return (DOMAINSET_FFS(&mask) - 1);
251 #else
252 	return (0);
253 #endif
254 }
255 
256 /*
257  * Outputs the state of the physical memory allocator, specifically,
258  * the amount of physical memory in each free list.
259  */
260 static int
sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)261 sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
262 {
263 	struct sbuf sbuf;
264 	struct vm_freelist *fl;
265 	int dom, error, flind, oind, pind;
266 
267 	error = sysctl_wire_old_buffer(req, 0);
268 	if (error != 0)
269 		return (error);
270 	sbuf_new_for_sysctl(&sbuf, NULL, 128 * vm_ndomains, req);
271 	for (dom = 0; dom < vm_ndomains; dom++) {
272 		sbuf_printf(&sbuf,"\nDOMAIN %d:\n", dom);
273 		for (flind = 0; flind < vm_nfreelists; flind++) {
274 			sbuf_printf(&sbuf, "\nFREE LIST %d:\n"
275 			    "\n  ORDER (SIZE)  |  NUMBER"
276 			    "\n              ", flind);
277 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
278 				sbuf_printf(&sbuf, "  |  POOL %d", pind);
279 			sbuf_printf(&sbuf, "\n--            ");
280 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
281 				sbuf_printf(&sbuf, "-- --      ");
282 			sbuf_printf(&sbuf, "--\n");
283 			for (oind = VM_NFREEORDER - 1; oind >= 0; oind--) {
284 				sbuf_printf(&sbuf, "  %2d (%6dK)", oind,
285 				    1 << (PAGE_SHIFT - 10 + oind));
286 				for (pind = 0; pind < VM_NFREEPOOL; pind++) {
287 				fl = vm_phys_free_queues[dom][flind][pind];
288 					sbuf_printf(&sbuf, "  |  %6d",
289 					    fl[oind].lcnt);
290 				}
291 				sbuf_printf(&sbuf, "\n");
292 			}
293 		}
294 	}
295 	error = sbuf_finish(&sbuf);
296 	sbuf_delete(&sbuf);
297 	return (error);
298 }
299 
300 /*
301  * Outputs the set of physical memory segments.
302  */
303 static int
sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)304 sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
305 {
306 	struct sbuf sbuf;
307 	struct vm_phys_seg *seg;
308 	int error, segind;
309 
310 	error = sysctl_wire_old_buffer(req, 0);
311 	if (error != 0)
312 		return (error);
313 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
314 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
315 		sbuf_printf(&sbuf, "\nSEGMENT %d:\n\n", segind);
316 		seg = &vm_phys_segs[segind];
317 		sbuf_printf(&sbuf, "start:     %#jx\n",
318 		    (uintmax_t)seg->start);
319 		sbuf_printf(&sbuf, "end:       %#jx\n",
320 		    (uintmax_t)seg->end);
321 		sbuf_printf(&sbuf, "domain:    %d\n", seg->domain);
322 		sbuf_printf(&sbuf, "free list: %p\n", seg->free_queues);
323 	}
324 	error = sbuf_finish(&sbuf);
325 	sbuf_delete(&sbuf);
326 	return (error);
327 }
328 
329 /*
330  * Return affinity, or -1 if there's no affinity information.
331  */
332 int
vm_phys_mem_affinity(int f,int t)333 vm_phys_mem_affinity(int f, int t)
334 {
335 
336 #ifdef NUMA
337 	if (mem_locality == NULL)
338 		return (-1);
339 	if (f >= vm_ndomains || t >= vm_ndomains)
340 		return (-1);
341 	return (mem_locality[f * vm_ndomains + t]);
342 #else
343 	return (-1);
344 #endif
345 }
346 
347 #ifdef NUMA
348 /*
349  * Outputs the VM locality table.
350  */
351 static int
sysctl_vm_phys_locality(SYSCTL_HANDLER_ARGS)352 sysctl_vm_phys_locality(SYSCTL_HANDLER_ARGS)
353 {
354 	struct sbuf sbuf;
355 	int error, i, j;
356 
357 	error = sysctl_wire_old_buffer(req, 0);
358 	if (error != 0)
359 		return (error);
360 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
361 
362 	sbuf_printf(&sbuf, "\n");
363 
364 	for (i = 0; i < vm_ndomains; i++) {
365 		sbuf_printf(&sbuf, "%d: ", i);
366 		for (j = 0; j < vm_ndomains; j++) {
367 			sbuf_printf(&sbuf, "%d ", vm_phys_mem_affinity(i, j));
368 		}
369 		sbuf_printf(&sbuf, "\n");
370 	}
371 	error = sbuf_finish(&sbuf);
372 	sbuf_delete(&sbuf);
373 	return (error);
374 }
375 #endif
376 
377 static void
vm_freelist_add(struct vm_freelist * fl,vm_page_t m,int order,int tail)378 vm_freelist_add(struct vm_freelist *fl, vm_page_t m, int order, int tail)
379 {
380 
381 	m->order = order;
382 	if (tail)
383 		TAILQ_INSERT_TAIL(&fl[order].pl, m, listq);
384 	else
385 		TAILQ_INSERT_HEAD(&fl[order].pl, m, listq);
386 	fl[order].lcnt++;
387 }
388 
389 static void
vm_freelist_rem(struct vm_freelist * fl,vm_page_t m,int order)390 vm_freelist_rem(struct vm_freelist *fl, vm_page_t m, int order)
391 {
392 
393 	TAILQ_REMOVE(&fl[order].pl, m, listq);
394 	fl[order].lcnt--;
395 	m->order = VM_NFREEORDER;
396 }
397 
398 /*
399  * Create a physical memory segment.
400  */
401 static void
_vm_phys_create_seg(vm_paddr_t start,vm_paddr_t end,int domain)402 _vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int domain)
403 {
404 	struct vm_phys_seg *seg;
405 
406 	if (!(0 <= domain && domain < vm_ndomains))
407 		panic("%s: Invalid domain %d ('vm_ndomains' is %d)",
408 		    __func__, domain, vm_ndomains);
409 	if (vm_phys_nsegs >= VM_PHYSSEG_MAX)
410 		panic("Not enough storage for physical segments, "
411 		    "increase VM_PHYSSEG_MAX");
412 
413 	seg = &vm_phys_segs[vm_phys_nsegs++];
414 	while (seg > vm_phys_segs && seg[-1].start >= end) {
415 		*seg = *(seg - 1);
416 		seg--;
417 	}
418 	seg->start = start;
419 	seg->end = end;
420 	seg->domain = domain;
421 	if (seg != vm_phys_segs && seg[-1].end > start)
422 		panic("Overlapping physical segments: Current [%#jx,%#jx) "
423 		    "at index %zu, previous [%#jx,%#jx)",
424 		    (uintmax_t)start, (uintmax_t)end, seg - vm_phys_segs,
425 		    (uintmax_t)seg[-1].start, (uintmax_t)seg[-1].end);
426 }
427 
428 static void
vm_phys_create_seg(vm_paddr_t start,vm_paddr_t end)429 vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end)
430 {
431 #ifdef NUMA
432 	int i;
433 
434 	if (mem_affinity == NULL) {
435 		_vm_phys_create_seg(start, end, 0);
436 		return;
437 	}
438 
439 	for (i = 0;; i++) {
440 		if (mem_affinity[i].end == 0)
441 			panic("Reached end of affinity info");
442 		if (mem_affinity[i].end <= start)
443 			continue;
444 		if (mem_affinity[i].start > start)
445 			panic("No affinity info for start %jx",
446 			    (uintmax_t)start);
447 		if (mem_affinity[i].end >= end) {
448 			_vm_phys_create_seg(start, end,
449 			    mem_affinity[i].domain);
450 			break;
451 		}
452 		_vm_phys_create_seg(start, mem_affinity[i].end,
453 		    mem_affinity[i].domain);
454 		start = mem_affinity[i].end;
455 	}
456 #else
457 	_vm_phys_create_seg(start, end, 0);
458 #endif
459 }
460 
461 /*
462  * Add a physical memory segment.
463  */
464 void
vm_phys_add_seg(vm_paddr_t start,vm_paddr_t end)465 vm_phys_add_seg(vm_paddr_t start, vm_paddr_t end)
466 {
467 	vm_paddr_t paddr;
468 
469 	if ((start & PAGE_MASK) != 0)
470 		panic("%s: start (%jx) is not page aligned", __func__,
471 		    (uintmax_t)start);
472 	if ((end & PAGE_MASK) != 0)
473 		panic("%s: end (%jx) is not page aligned", __func__,
474 		    (uintmax_t)end);
475 	if (start > end)
476 		panic("%s: start (%jx) > end (%jx)!", __func__,
477 		    (uintmax_t)start, (uintmax_t)end);
478 
479 	if (start == end)
480 		return;
481 
482 	/*
483 	 * Split the physical memory segment if it spans two or more free
484 	 * list boundaries.
485 	 */
486 	paddr = start;
487 #ifdef	VM_FREELIST_LOWMEM
488 	if (paddr < VM_LOWMEM_BOUNDARY && end > VM_LOWMEM_BOUNDARY) {
489 		vm_phys_create_seg(paddr, VM_LOWMEM_BOUNDARY);
490 		paddr = VM_LOWMEM_BOUNDARY;
491 	}
492 #endif
493 #ifdef	VM_FREELIST_DMA32
494 	if (paddr < VM_DMA32_BOUNDARY && end > VM_DMA32_BOUNDARY) {
495 		vm_phys_create_seg(paddr, VM_DMA32_BOUNDARY);
496 		paddr = VM_DMA32_BOUNDARY;
497 	}
498 #endif
499 	vm_phys_create_seg(paddr, end);
500 }
501 
502 /*
503  * Initialize the physical memory allocator.
504  *
505  * Requires that vm_page_array is initialized!
506  */
507 void
vm_phys_init(void)508 vm_phys_init(void)
509 {
510 	struct vm_freelist *fl;
511 	struct vm_phys_seg *end_seg, *prev_seg, *seg, *tmp_seg;
512 #if defined(VM_DMA32_NPAGES_THRESHOLD) || defined(VM_PHYSSEG_SPARSE)
513 	u_long npages;
514 #endif
515 	int dom, flind, freelist, oind, pind, segind;
516 
517 	/*
518 	 * Compute the number of free lists, and generate the mapping from the
519 	 * manifest constants VM_FREELIST_* to the free list indices.
520 	 *
521 	 * Initially, the entries of vm_freelist_to_flind[] are set to either
522 	 * 0 or 1 to indicate which free lists should be created.
523 	 */
524 #ifdef	VM_DMA32_NPAGES_THRESHOLD
525 	npages = 0;
526 #endif
527 	for (segind = vm_phys_nsegs - 1; segind >= 0; segind--) {
528 		seg = &vm_phys_segs[segind];
529 #ifdef	VM_FREELIST_LOWMEM
530 		if (seg->end <= VM_LOWMEM_BOUNDARY)
531 			vm_freelist_to_flind[VM_FREELIST_LOWMEM] = 1;
532 		else
533 #endif
534 #ifdef	VM_FREELIST_DMA32
535 		if (
536 #ifdef	VM_DMA32_NPAGES_THRESHOLD
537 		    /*
538 		     * Create the DMA32 free list only if the amount of
539 		     * physical memory above physical address 4G exceeds the
540 		     * given threshold.
541 		     */
542 		    npages > VM_DMA32_NPAGES_THRESHOLD &&
543 #endif
544 		    seg->end <= VM_DMA32_BOUNDARY)
545 			vm_freelist_to_flind[VM_FREELIST_DMA32] = 1;
546 		else
547 #endif
548 		{
549 #ifdef	VM_DMA32_NPAGES_THRESHOLD
550 			npages += atop(seg->end - seg->start);
551 #endif
552 			vm_freelist_to_flind[VM_FREELIST_DEFAULT] = 1;
553 		}
554 	}
555 	/* Change each entry into a running total of the free lists. */
556 	for (freelist = 1; freelist < VM_NFREELIST; freelist++) {
557 		vm_freelist_to_flind[freelist] +=
558 		    vm_freelist_to_flind[freelist - 1];
559 	}
560 	vm_nfreelists = vm_freelist_to_flind[VM_NFREELIST - 1];
561 	KASSERT(vm_nfreelists > 0, ("vm_phys_init: no free lists"));
562 	/* Change each entry into a free list index. */
563 	for (freelist = 0; freelist < VM_NFREELIST; freelist++)
564 		vm_freelist_to_flind[freelist]--;
565 
566 	/*
567 	 * Initialize the first_page and free_queues fields of each physical
568 	 * memory segment.
569 	 */
570 #ifdef VM_PHYSSEG_SPARSE
571 	npages = 0;
572 #endif
573 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
574 		seg = &vm_phys_segs[segind];
575 #ifdef VM_PHYSSEG_SPARSE
576 		seg->first_page = &vm_page_array[npages];
577 		npages += atop(seg->end - seg->start);
578 #else
579 		seg->first_page = PHYS_TO_VM_PAGE(seg->start);
580 #endif
581 #ifdef	VM_FREELIST_LOWMEM
582 		if (seg->end <= VM_LOWMEM_BOUNDARY) {
583 			flind = vm_freelist_to_flind[VM_FREELIST_LOWMEM];
584 			KASSERT(flind >= 0,
585 			    ("vm_phys_init: LOWMEM flind < 0"));
586 		} else
587 #endif
588 #ifdef	VM_FREELIST_DMA32
589 		if (seg->end <= VM_DMA32_BOUNDARY) {
590 			flind = vm_freelist_to_flind[VM_FREELIST_DMA32];
591 			KASSERT(flind >= 0,
592 			    ("vm_phys_init: DMA32 flind < 0"));
593 		} else
594 #endif
595 		{
596 			flind = vm_freelist_to_flind[VM_FREELIST_DEFAULT];
597 			KASSERT(flind >= 0,
598 			    ("vm_phys_init: DEFAULT flind < 0"));
599 		}
600 		seg->free_queues = &vm_phys_free_queues[seg->domain][flind];
601 	}
602 
603 	/*
604 	 * Coalesce physical memory segments that are contiguous and share the
605 	 * same per-domain free queues.
606 	 */
607 	prev_seg = vm_phys_segs;
608 	seg = &vm_phys_segs[1];
609 	end_seg = &vm_phys_segs[vm_phys_nsegs];
610 	while (seg < end_seg) {
611 		if (prev_seg->end == seg->start &&
612 		    prev_seg->free_queues == seg->free_queues) {
613 			prev_seg->end = seg->end;
614 			KASSERT(prev_seg->domain == seg->domain,
615 			    ("vm_phys_init: free queues cannot span domains"));
616 			vm_phys_nsegs--;
617 			end_seg--;
618 			for (tmp_seg = seg; tmp_seg < end_seg; tmp_seg++)
619 				*tmp_seg = *(tmp_seg + 1);
620 		} else {
621 			prev_seg = seg;
622 			seg++;
623 		}
624 	}
625 
626 	/*
627 	 * Initialize the free queues.
628 	 */
629 	for (dom = 0; dom < vm_ndomains; dom++) {
630 		for (flind = 0; flind < vm_nfreelists; flind++) {
631 			for (pind = 0; pind < VM_NFREEPOOL; pind++) {
632 				fl = vm_phys_free_queues[dom][flind][pind];
633 				for (oind = 0; oind < VM_NFREEORDER; oind++)
634 					TAILQ_INIT(&fl[oind].pl);
635 			}
636 		}
637 	}
638 
639 	rw_init(&vm_phys_fictitious_reg_lock, "vmfctr");
640 }
641 
642 /*
643  * Register info about the NUMA topology of the system.
644  *
645  * Invoked by platform-dependent code prior to vm_phys_init().
646  */
647 void
vm_phys_register_domains(int ndomains,struct mem_affinity * affinity,int * locality)648 vm_phys_register_domains(int ndomains, struct mem_affinity *affinity,
649     int *locality)
650 {
651 #ifdef NUMA
652 	int i;
653 
654 	/*
655 	 * For now the only override value that we support is 1, which
656 	 * effectively disables NUMA-awareness in the allocators.
657 	 */
658 	TUNABLE_INT_FETCH("vm.numa.disabled", &numa_disabled);
659 	if (numa_disabled)
660 		ndomains = 1;
661 
662 	if (ndomains > 1) {
663 		vm_ndomains = ndomains;
664 		mem_affinity = affinity;
665 		mem_locality = locality;
666 	}
667 
668 	for (i = 0; i < vm_ndomains; i++)
669 		DOMAINSET_SET(i, &all_domains);
670 #else
671 	(void)ndomains;
672 	(void)affinity;
673 	(void)locality;
674 #endif
675 }
676 
677 /*
678  * Split a contiguous, power of two-sized set of physical pages.
679  *
680  * When this function is called by a page allocation function, the caller
681  * should request insertion at the head unless the order [order, oind) queues
682  * are known to be empty.  The objective being to reduce the likelihood of
683  * long-term fragmentation by promoting contemporaneous allocation and
684  * (hopefully) deallocation.
685  */
686 static __inline void
vm_phys_split_pages(vm_page_t m,int oind,struct vm_freelist * fl,int order,int tail)687 vm_phys_split_pages(vm_page_t m, int oind, struct vm_freelist *fl, int order,
688     int tail)
689 {
690 	vm_page_t m_buddy;
691 
692 	while (oind > order) {
693 		oind--;
694 		m_buddy = &m[1 << oind];
695 		KASSERT(m_buddy->order == VM_NFREEORDER,
696 		    ("vm_phys_split_pages: page %p has unexpected order %d",
697 		    m_buddy, m_buddy->order));
698 		vm_freelist_add(fl, m_buddy, oind, tail);
699         }
700 }
701 
702 /*
703  * Add the physical pages [m, m + npages) at the beginning of a power-of-two
704  * aligned and sized set to the specified free list.
705  *
706  * When this function is called by a page allocation function, the caller
707  * should request insertion at the head unless the lower-order queues are
708  * known to be empty.  The objective being to reduce the likelihood of long-
709  * term fragmentation by promoting contemporaneous allocation and (hopefully)
710  * deallocation.
711  *
712  * The physical page m's buddy must not be free.
713  */
714 static void
vm_phys_enq_beg(vm_page_t m,u_int npages,struct vm_freelist * fl,int tail)715 vm_phys_enq_beg(vm_page_t m, u_int npages, struct vm_freelist *fl, int tail)
716 {
717         int order;
718 
719 	KASSERT(npages == 0 ||
720 	    (VM_PAGE_TO_PHYS(m) &
721 	    ((PAGE_SIZE << (fls(npages) - 1)) - 1)) == 0,
722 	    ("%s: page %p and npages %u are misaligned",
723 	    __func__, m, npages));
724         while (npages > 0) {
725 		KASSERT(m->order == VM_NFREEORDER,
726 		    ("%s: page %p has unexpected order %d",
727 		    __func__, m, m->order));
728                 order = fls(npages) - 1;
729 		KASSERT(order < VM_NFREEORDER,
730 		    ("%s: order %d is out of range", __func__, order));
731                 vm_freelist_add(fl, m, order, tail);
732 		m += 1 << order;
733                 npages -= 1 << order;
734         }
735 }
736 
737 /*
738  * Add the physical pages [m, m + npages) at the end of a power-of-two aligned
739  * and sized set to the specified free list.
740  *
741  * When this function is called by a page allocation function, the caller
742  * should request insertion at the head unless the lower-order queues are
743  * known to be empty.  The objective being to reduce the likelihood of long-
744  * term fragmentation by promoting contemporaneous allocation and (hopefully)
745  * deallocation.
746  *
747  * If npages is zero, this function does nothing and ignores the physical page
748  * parameter m.  Otherwise, the physical page m's buddy must not be free.
749  */
750 static vm_page_t
vm_phys_enq_range(vm_page_t m,u_int npages,struct vm_freelist * fl,int tail)751 vm_phys_enq_range(vm_page_t m, u_int npages, struct vm_freelist *fl, int tail)
752 {
753 	int order;
754 
755 	KASSERT(npages == 0 ||
756 	    ((VM_PAGE_TO_PHYS(m) + npages * PAGE_SIZE) &
757 	    ((PAGE_SIZE << (fls(npages) - 1)) - 1)) == 0,
758 	    ("vm_phys_enq_range: page %p and npages %u are misaligned",
759 	    m, npages));
760 	while (npages > 0) {
761 		KASSERT(m->order == VM_NFREEORDER,
762 		    ("vm_phys_enq_range: page %p has unexpected order %d",
763 		    m, m->order));
764 		order = ffs(npages) - 1;
765 		KASSERT(order < VM_NFREEORDER,
766 		    ("vm_phys_enq_range: order %d is out of range", order));
767 		vm_freelist_add(fl, m, order, tail);
768 		m += 1 << order;
769 		npages -= 1 << order;
770 	}
771 	return (m);
772 }
773 
774 /*
775  * Set the pool for a contiguous, power of two-sized set of physical pages.
776  */
777 static void
vm_phys_set_pool(int pool,vm_page_t m,int order)778 vm_phys_set_pool(int pool, vm_page_t m, int order)
779 {
780 	vm_page_t m_tmp;
781 
782 	for (m_tmp = m; m_tmp < &m[1 << order]; m_tmp++)
783 		m_tmp->pool = pool;
784 }
785 
786 /*
787  * Tries to allocate the specified number of pages from the specified pool
788  * within the specified domain.  Returns the actual number of allocated pages
789  * and a pointer to each page through the array ma[].
790  *
791  * The returned pages may not be physically contiguous.  However, in contrast
792  * to performing multiple, back-to-back calls to vm_phys_alloc_pages(..., 0),
793  * calling this function once to allocate the desired number of pages will
794  * avoid wasted time in vm_phys_split_pages().
795  *
796  * The free page queues for the specified domain must be locked.
797  */
798 int
vm_phys_alloc_npages(int domain,int pool,int npages,vm_page_t ma[])799 vm_phys_alloc_npages(int domain, int pool, int npages, vm_page_t ma[])
800 {
801 	struct vm_freelist *alt, *fl;
802 	vm_page_t m;
803 	int avail, end, flind, freelist, i, oind, pind;
804 
805 	KASSERT(domain >= 0 && domain < vm_ndomains,
806 	    ("vm_phys_alloc_npages: domain %d is out of range", domain));
807 	KASSERT(pool < VM_NFREEPOOL,
808 	    ("vm_phys_alloc_npages: pool %d is out of range", pool));
809 	KASSERT(npages <= 1 << (VM_NFREEORDER - 1),
810 	    ("vm_phys_alloc_npages: npages %d is out of range", npages));
811 	vm_domain_free_assert_locked(VM_DOMAIN(domain));
812 	i = 0;
813 	for (freelist = 0; freelist < VM_NFREELIST; freelist++) {
814 		flind = vm_freelist_to_flind[freelist];
815 		if (flind < 0)
816 			continue;
817 		fl = vm_phys_free_queues[domain][flind][pool];
818 		for (oind = 0; oind < VM_NFREEORDER; oind++) {
819 			while ((m = TAILQ_FIRST(&fl[oind].pl)) != NULL) {
820 				vm_freelist_rem(fl, m, oind);
821 				avail = i + (1 << oind);
822 				end = imin(npages, avail);
823 				while (i < end)
824 					ma[i++] = m++;
825 				if (i == npages) {
826 					/*
827 					 * Return excess pages to fl.  Its order
828 					 * [0, oind) queues are empty.
829 					 */
830 					vm_phys_enq_range(m, avail - i, fl, 1);
831 					return (npages);
832 				}
833 			}
834 		}
835 		for (oind = VM_NFREEORDER - 1; oind >= 0; oind--) {
836 			for (pind = 0; pind < VM_NFREEPOOL; pind++) {
837 				alt = vm_phys_free_queues[domain][flind][pind];
838 				while ((m = TAILQ_FIRST(&alt[oind].pl)) !=
839 				    NULL) {
840 					vm_freelist_rem(alt, m, oind);
841 					vm_phys_set_pool(pool, m, oind);
842 					avail = i + (1 << oind);
843 					end = imin(npages, avail);
844 					while (i < end)
845 						ma[i++] = m++;
846 					if (i == npages) {
847 						/*
848 						 * Return excess pages to fl.
849 						 * Its order [0, oind) queues
850 						 * are empty.
851 						 */
852 						vm_phys_enq_range(m, avail - i,
853 						    fl, 1);
854 						return (npages);
855 					}
856 				}
857 			}
858 		}
859 	}
860 	return (i);
861 }
862 
863 /*
864  * Allocate a contiguous, power of two-sized set of physical pages
865  * from the free lists.
866  *
867  * The free page queues must be locked.
868  */
869 vm_page_t
vm_phys_alloc_pages(int domain,int pool,int order)870 vm_phys_alloc_pages(int domain, int pool, int order)
871 {
872 	vm_page_t m;
873 	int freelist;
874 
875 	for (freelist = 0; freelist < VM_NFREELIST; freelist++) {
876 		m = vm_phys_alloc_freelist_pages(domain, freelist, pool, order);
877 		if (m != NULL)
878 			return (m);
879 	}
880 	return (NULL);
881 }
882 
883 /*
884  * Allocate a contiguous, power of two-sized set of physical pages from the
885  * specified free list.  The free list must be specified using one of the
886  * manifest constants VM_FREELIST_*.
887  *
888  * The free page queues must be locked.
889  */
890 vm_page_t
vm_phys_alloc_freelist_pages(int domain,int freelist,int pool,int order)891 vm_phys_alloc_freelist_pages(int domain, int freelist, int pool, int order)
892 {
893 	struct vm_freelist *alt, *fl;
894 	vm_page_t m;
895 	int oind, pind, flind;
896 
897 	KASSERT(domain >= 0 && domain < vm_ndomains,
898 	    ("vm_phys_alloc_freelist_pages: domain %d is out of range",
899 	    domain));
900 	KASSERT(freelist < VM_NFREELIST,
901 	    ("vm_phys_alloc_freelist_pages: freelist %d is out of range",
902 	    freelist));
903 	KASSERT(pool < VM_NFREEPOOL,
904 	    ("vm_phys_alloc_freelist_pages: pool %d is out of range", pool));
905 	KASSERT(order < VM_NFREEORDER,
906 	    ("vm_phys_alloc_freelist_pages: order %d is out of range", order));
907 
908 	flind = vm_freelist_to_flind[freelist];
909 	/* Check if freelist is present */
910 	if (flind < 0)
911 		return (NULL);
912 
913 	vm_domain_free_assert_locked(VM_DOMAIN(domain));
914 	fl = &vm_phys_free_queues[domain][flind][pool][0];
915 	for (oind = order; oind < VM_NFREEORDER; oind++) {
916 		m = TAILQ_FIRST(&fl[oind].pl);
917 		if (m != NULL) {
918 			vm_freelist_rem(fl, m, oind);
919 			/* The order [order, oind) queues are empty. */
920 			vm_phys_split_pages(m, oind, fl, order, 1);
921 			return (m);
922 		}
923 	}
924 
925 	/*
926 	 * The given pool was empty.  Find the largest
927 	 * contiguous, power-of-two-sized set of pages in any
928 	 * pool.  Transfer these pages to the given pool, and
929 	 * use them to satisfy the allocation.
930 	 */
931 	for (oind = VM_NFREEORDER - 1; oind >= order; oind--) {
932 		for (pind = 0; pind < VM_NFREEPOOL; pind++) {
933 			alt = &vm_phys_free_queues[domain][flind][pind][0];
934 			m = TAILQ_FIRST(&alt[oind].pl);
935 			if (m != NULL) {
936 				vm_freelist_rem(alt, m, oind);
937 				vm_phys_set_pool(pool, m, oind);
938 				/* The order [order, oind) queues are empty. */
939 				vm_phys_split_pages(m, oind, fl, order, 1);
940 				return (m);
941 			}
942 		}
943 	}
944 	return (NULL);
945 }
946 
947 /*
948  * Find the vm_page corresponding to the given physical address.
949  */
950 vm_page_t
vm_phys_paddr_to_vm_page(vm_paddr_t pa)951 vm_phys_paddr_to_vm_page(vm_paddr_t pa)
952 {
953 	struct vm_phys_seg *seg;
954 
955 	if ((seg = vm_phys_paddr_to_seg(pa)) != NULL)
956 		return (&seg->first_page[atop(pa - seg->start)]);
957 	return (NULL);
958 }
959 
960 vm_page_t
vm_phys_fictitious_to_vm_page(vm_paddr_t pa)961 vm_phys_fictitious_to_vm_page(vm_paddr_t pa)
962 {
963 	struct vm_phys_fictitious_seg tmp, *seg;
964 	vm_page_t m;
965 
966 	m = NULL;
967 	tmp.start = pa;
968 	tmp.end = 0;
969 
970 	rw_rlock(&vm_phys_fictitious_reg_lock);
971 	seg = RB_FIND(fict_tree, &vm_phys_fictitious_tree, &tmp);
972 	rw_runlock(&vm_phys_fictitious_reg_lock);
973 	if (seg == NULL)
974 		return (NULL);
975 
976 	m = &seg->first_page[atop(pa - seg->start)];
977 	KASSERT((m->flags & PG_FICTITIOUS) != 0, ("%p not fictitious", m));
978 
979 	return (m);
980 }
981 
982 static inline void
vm_phys_fictitious_init_range(vm_page_t range,vm_paddr_t start,long page_count,vm_memattr_t memattr)983 vm_phys_fictitious_init_range(vm_page_t range, vm_paddr_t start,
984     long page_count, vm_memattr_t memattr)
985 {
986 	long i;
987 
988 	bzero(range, page_count * sizeof(*range));
989 	for (i = 0; i < page_count; i++) {
990 		vm_page_initfake(&range[i], start + PAGE_SIZE * i, memattr);
991 		range[i].oflags &= ~VPO_UNMANAGED;
992 		range[i].busy_lock = VPB_UNBUSIED;
993 	}
994 }
995 
996 int
vm_phys_fictitious_reg_range(vm_paddr_t start,vm_paddr_t end,vm_memattr_t memattr)997 vm_phys_fictitious_reg_range(vm_paddr_t start, vm_paddr_t end,
998     vm_memattr_t memattr)
999 {
1000 	struct vm_phys_fictitious_seg *seg;
1001 	vm_page_t fp;
1002 	long page_count;
1003 #ifdef VM_PHYSSEG_DENSE
1004 	long pi, pe;
1005 	long dpage_count;
1006 #endif
1007 
1008 	KASSERT(start < end,
1009 	    ("Start of segment isn't less than end (start: %jx end: %jx)",
1010 	    (uintmax_t)start, (uintmax_t)end));
1011 
1012 	page_count = (end - start) / PAGE_SIZE;
1013 
1014 #ifdef VM_PHYSSEG_DENSE
1015 	pi = atop(start);
1016 	pe = atop(end);
1017 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1018 		fp = &vm_page_array[pi - first_page];
1019 		if ((pe - first_page) > vm_page_array_size) {
1020 			/*
1021 			 * We have a segment that starts inside
1022 			 * of vm_page_array, but ends outside of it.
1023 			 *
1024 			 * Use vm_page_array pages for those that are
1025 			 * inside of the vm_page_array range, and
1026 			 * allocate the remaining ones.
1027 			 */
1028 			dpage_count = vm_page_array_size - (pi - first_page);
1029 			vm_phys_fictitious_init_range(fp, start, dpage_count,
1030 			    memattr);
1031 			page_count -= dpage_count;
1032 			start += ptoa(dpage_count);
1033 			goto alloc;
1034 		}
1035 		/*
1036 		 * We can allocate the full range from vm_page_array,
1037 		 * so there's no need to register the range in the tree.
1038 		 */
1039 		vm_phys_fictitious_init_range(fp, start, page_count, memattr);
1040 		return (0);
1041 	} else if (pe > first_page && (pe - first_page) < vm_page_array_size) {
1042 		/*
1043 		 * We have a segment that ends inside of vm_page_array,
1044 		 * but starts outside of it.
1045 		 */
1046 		fp = &vm_page_array[0];
1047 		dpage_count = pe - first_page;
1048 		vm_phys_fictitious_init_range(fp, ptoa(first_page), dpage_count,
1049 		    memattr);
1050 		end -= ptoa(dpage_count);
1051 		page_count -= dpage_count;
1052 		goto alloc;
1053 	} else if (pi < first_page && pe > (first_page + vm_page_array_size)) {
1054 		/*
1055 		 * Trying to register a fictitious range that expands before
1056 		 * and after vm_page_array.
1057 		 */
1058 		return (EINVAL);
1059 	} else {
1060 alloc:
1061 #endif
1062 		fp = malloc(page_count * sizeof(struct vm_page), M_FICT_PAGES,
1063 		    M_WAITOK);
1064 #ifdef VM_PHYSSEG_DENSE
1065 	}
1066 #endif
1067 	vm_phys_fictitious_init_range(fp, start, page_count, memattr);
1068 
1069 	seg = malloc(sizeof(*seg), M_FICT_PAGES, M_WAITOK | M_ZERO);
1070 	seg->start = start;
1071 	seg->end = end;
1072 	seg->first_page = fp;
1073 
1074 	rw_wlock(&vm_phys_fictitious_reg_lock);
1075 	RB_INSERT(fict_tree, &vm_phys_fictitious_tree, seg);
1076 	rw_wunlock(&vm_phys_fictitious_reg_lock);
1077 
1078 	return (0);
1079 }
1080 
1081 void
vm_phys_fictitious_unreg_range(vm_paddr_t start,vm_paddr_t end)1082 vm_phys_fictitious_unreg_range(vm_paddr_t start, vm_paddr_t end)
1083 {
1084 	struct vm_phys_fictitious_seg *seg, tmp;
1085 #ifdef VM_PHYSSEG_DENSE
1086 	long pi, pe;
1087 #endif
1088 
1089 	KASSERT(start < end,
1090 	    ("Start of segment isn't less than end (start: %jx end: %jx)",
1091 	    (uintmax_t)start, (uintmax_t)end));
1092 
1093 #ifdef VM_PHYSSEG_DENSE
1094 	pi = atop(start);
1095 	pe = atop(end);
1096 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1097 		if ((pe - first_page) <= vm_page_array_size) {
1098 			/*
1099 			 * This segment was allocated using vm_page_array
1100 			 * only, there's nothing to do since those pages
1101 			 * were never added to the tree.
1102 			 */
1103 			return;
1104 		}
1105 		/*
1106 		 * We have a segment that starts inside
1107 		 * of vm_page_array, but ends outside of it.
1108 		 *
1109 		 * Calculate how many pages were added to the
1110 		 * tree and free them.
1111 		 */
1112 		start = ptoa(first_page + vm_page_array_size);
1113 	} else if (pe > first_page && (pe - first_page) < vm_page_array_size) {
1114 		/*
1115 		 * We have a segment that ends inside of vm_page_array,
1116 		 * but starts outside of it.
1117 		 */
1118 		end = ptoa(first_page);
1119 	} else if (pi < first_page && pe > (first_page + vm_page_array_size)) {
1120 		/* Since it's not possible to register such a range, panic. */
1121 		panic(
1122 		    "Unregistering not registered fictitious range [%#jx:%#jx]",
1123 		    (uintmax_t)start, (uintmax_t)end);
1124 	}
1125 #endif
1126 	tmp.start = start;
1127 	tmp.end = 0;
1128 
1129 	rw_wlock(&vm_phys_fictitious_reg_lock);
1130 	seg = RB_FIND(fict_tree, &vm_phys_fictitious_tree, &tmp);
1131 	if (seg->start != start || seg->end != end) {
1132 		rw_wunlock(&vm_phys_fictitious_reg_lock);
1133 		panic(
1134 		    "Unregistering not registered fictitious range [%#jx:%#jx]",
1135 		    (uintmax_t)start, (uintmax_t)end);
1136 	}
1137 	RB_REMOVE(fict_tree, &vm_phys_fictitious_tree, seg);
1138 	rw_wunlock(&vm_phys_fictitious_reg_lock);
1139 	free(seg->first_page, M_FICT_PAGES);
1140 	free(seg, M_FICT_PAGES);
1141 }
1142 
1143 /*
1144  * Free a contiguous, power of two-sized set of physical pages.
1145  *
1146  * The free page queues must be locked.
1147  */
1148 void
vm_phys_free_pages(vm_page_t m,int order)1149 vm_phys_free_pages(vm_page_t m, int order)
1150 {
1151 	struct vm_freelist *fl;
1152 	struct vm_phys_seg *seg;
1153 	vm_paddr_t pa;
1154 	vm_page_t m_buddy;
1155 
1156 	KASSERT(m->order == VM_NFREEORDER,
1157 	    ("vm_phys_free_pages: page %p has unexpected order %d",
1158 	    m, m->order));
1159 	KASSERT(m->pool < VM_NFREEPOOL,
1160 	    ("vm_phys_free_pages: page %p has unexpected pool %d",
1161 	    m, m->pool));
1162 	KASSERT(order < VM_NFREEORDER,
1163 	    ("vm_phys_free_pages: order %d is out of range", order));
1164 	seg = &vm_phys_segs[m->segind];
1165 	vm_domain_free_assert_locked(VM_DOMAIN(seg->domain));
1166 	if (order < VM_NFREEORDER - 1) {
1167 		pa = VM_PAGE_TO_PHYS(m);
1168 		do {
1169 			pa ^= ((vm_paddr_t)1 << (PAGE_SHIFT + order));
1170 			if (pa < seg->start || pa >= seg->end)
1171 				break;
1172 			m_buddy = &seg->first_page[atop(pa - seg->start)];
1173 			if (m_buddy->order != order)
1174 				break;
1175 			fl = (*seg->free_queues)[m_buddy->pool];
1176 			vm_freelist_rem(fl, m_buddy, order);
1177 			if (m_buddy->pool != m->pool)
1178 				vm_phys_set_pool(m->pool, m_buddy, order);
1179 			order++;
1180 			pa &= ~(((vm_paddr_t)1 << (PAGE_SHIFT + order)) - 1);
1181 			m = &seg->first_page[atop(pa - seg->start)];
1182 		} while (order < VM_NFREEORDER - 1);
1183 	}
1184 	fl = (*seg->free_queues)[m->pool];
1185 	vm_freelist_add(fl, m, order, 1);
1186 }
1187 
1188 /*
1189  * Return the largest possible order of a set of pages starting at m.
1190  */
1191 static int
max_order(vm_page_t m)1192 max_order(vm_page_t m)
1193 {
1194 
1195 	/*
1196 	 * Unsigned "min" is used here so that "order" is assigned
1197 	 * "VM_NFREEORDER - 1" when "m"'s physical address is zero
1198 	 * or the low-order bits of its physical address are zero
1199 	 * because the size of a physical address exceeds the size of
1200 	 * a long.
1201 	 */
1202 	return (min(ffsll(VM_PAGE_TO_PHYS(m) >> PAGE_SHIFT) - 1,
1203 	    VM_NFREEORDER - 1));
1204 }
1205 
1206 /*
1207  * Free a contiguous, arbitrarily sized set of physical pages, without
1208  * merging across set boundaries.
1209  *
1210  * The free page queues must be locked.
1211  */
1212 void
vm_phys_enqueue_contig(vm_page_t m,u_long npages)1213 vm_phys_enqueue_contig(vm_page_t m, u_long npages)
1214 {
1215 	struct vm_freelist *fl;
1216 	struct vm_phys_seg *seg;
1217 	vm_page_t m_end;
1218 	vm_paddr_t diff, lo;
1219 	int order;
1220 
1221 	/*
1222 	 * Avoid unnecessary coalescing by freeing the pages in the largest
1223 	 * possible power-of-two-sized subsets.
1224 	 */
1225 	vm_domain_free_assert_locked(vm_pagequeue_domain(m));
1226 	seg = &vm_phys_segs[m->segind];
1227 	fl = (*seg->free_queues)[m->pool];
1228 	m_end = m + npages;
1229 	/* Free blocks of increasing size. */
1230 	lo = VM_PAGE_TO_PHYS(m) >> PAGE_SHIFT;
1231 	if (m < m_end &&
1232 	    (diff = lo ^ (lo + npages - 1)) != 0) {
1233 		order = min(flsll(diff) - 1, VM_NFREEORDER - 1);
1234 		m = vm_phys_enq_range(m, roundup2(lo, 1 << order) - lo, fl, 1);
1235 	}
1236 
1237 	/* Free blocks of maximum size. */
1238 	order = VM_NFREEORDER - 1;
1239 	while (m + (1 << order) <= m_end) {
1240 		KASSERT(seg == &vm_phys_segs[m->segind],
1241 		    ("%s: page range [%p,%p) spans multiple segments",
1242 		    __func__, m_end - npages, m));
1243 		vm_freelist_add(fl, m, order, 1);
1244 		m += 1 << order;
1245 	}
1246 	/* Free blocks of diminishing size. */
1247 	vm_phys_enq_beg(m, m_end - m, fl, 1);
1248 }
1249 
1250 /*
1251  * Free a contiguous, arbitrarily sized set of physical pages.
1252  *
1253  * The free page queues must be locked.
1254  */
1255 void
vm_phys_free_contig(vm_page_t m,u_long npages)1256 vm_phys_free_contig(vm_page_t m, u_long npages)
1257 {
1258 	int order_start, order_end;
1259 	vm_page_t m_start, m_end;
1260 
1261 	vm_domain_free_assert_locked(vm_pagequeue_domain(m));
1262 
1263 	m_start = m;
1264 	order_start = max_order(m_start);
1265 	if (order_start < VM_NFREEORDER - 1)
1266 		m_start += 1 << order_start;
1267 	m_end = m + npages;
1268 	order_end = max_order(m_end);
1269 	if (order_end < VM_NFREEORDER - 1)
1270 		m_end -= 1 << order_end;
1271 	/*
1272 	 * Avoid unnecessary coalescing by freeing the pages at the start and
1273 	 * end of the range last.
1274 	 */
1275 	if (m_start < m_end)
1276 		vm_phys_enqueue_contig(m_start, m_end - m_start);
1277 	if (order_start < VM_NFREEORDER - 1)
1278 		vm_phys_free_pages(m, order_start);
1279 	if (order_end < VM_NFREEORDER - 1)
1280 		vm_phys_free_pages(m_end, order_end);
1281 }
1282 
1283 /*
1284  * Identify the first address range within segment segind or greater
1285  * that matches the domain, lies within the low/high range, and has
1286  * enough pages.  Return -1 if there is none.
1287  */
1288 int
vm_phys_find_range(vm_page_t bounds[],int segind,int domain,u_long npages,vm_paddr_t low,vm_paddr_t high)1289 vm_phys_find_range(vm_page_t bounds[], int segind, int domain,
1290     u_long npages, vm_paddr_t low, vm_paddr_t high)
1291 {
1292 	vm_paddr_t pa_end, pa_start;
1293 	struct vm_phys_seg *end_seg, *seg;
1294 
1295 	KASSERT(npages > 0, ("npages is zero"));
1296 	KASSERT(domain >= 0 && domain < vm_ndomains, ("domain out of range"));
1297 	end_seg = &vm_phys_segs[vm_phys_nsegs];
1298 	for (seg = &vm_phys_segs[segind]; seg < end_seg; seg++) {
1299 		if (seg->domain != domain)
1300 			continue;
1301 		if (seg->start >= high)
1302 			return (-1);
1303 		pa_start = MAX(low, seg->start);
1304 		pa_end = MIN(high, seg->end);
1305 		if (pa_end - pa_start < ptoa(npages))
1306 			continue;
1307 		bounds[0] = &seg->first_page[atop(pa_start - seg->start)];
1308 		bounds[1] = &seg->first_page[atop(pa_end - seg->start)];
1309 		return (seg - vm_phys_segs);
1310 	}
1311 	return (-1);
1312 }
1313 
1314 /*
1315  * Search for the given physical page "m" in the free lists.  If the search
1316  * succeeds, remove "m" from the free lists and return true.  Otherwise, return
1317  * false, indicating that "m" is not in the free lists.
1318  *
1319  * The free page queues must be locked.
1320  */
1321 bool
vm_phys_unfree_page(vm_page_t m)1322 vm_phys_unfree_page(vm_page_t m)
1323 {
1324 	struct vm_freelist *fl;
1325 	struct vm_phys_seg *seg;
1326 	vm_paddr_t pa, pa_half;
1327 	vm_page_t m_set, m_tmp;
1328 	int order;
1329 
1330 	/*
1331 	 * First, find the contiguous, power of two-sized set of free
1332 	 * physical pages containing the given physical page "m" and
1333 	 * assign it to "m_set".
1334 	 */
1335 	seg = &vm_phys_segs[m->segind];
1336 	vm_domain_free_assert_locked(VM_DOMAIN(seg->domain));
1337 	for (m_set = m, order = 0; m_set->order == VM_NFREEORDER &&
1338 	    order < VM_NFREEORDER - 1; ) {
1339 		order++;
1340 		pa = m->phys_addr & (~(vm_paddr_t)0 << (PAGE_SHIFT + order));
1341 		if (pa >= seg->start)
1342 			m_set = &seg->first_page[atop(pa - seg->start)];
1343 		else
1344 			return (false);
1345 	}
1346 	if (m_set->order < order)
1347 		return (false);
1348 	if (m_set->order == VM_NFREEORDER)
1349 		return (false);
1350 	KASSERT(m_set->order < VM_NFREEORDER,
1351 	    ("vm_phys_unfree_page: page %p has unexpected order %d",
1352 	    m_set, m_set->order));
1353 
1354 	/*
1355 	 * Next, remove "m_set" from the free lists.  Finally, extract
1356 	 * "m" from "m_set" using an iterative algorithm: While "m_set"
1357 	 * is larger than a page, shrink "m_set" by returning the half
1358 	 * of "m_set" that does not contain "m" to the free lists.
1359 	 */
1360 	fl = (*seg->free_queues)[m_set->pool];
1361 	order = m_set->order;
1362 	vm_freelist_rem(fl, m_set, order);
1363 	while (order > 0) {
1364 		order--;
1365 		pa_half = m_set->phys_addr ^ (1 << (PAGE_SHIFT + order));
1366 		if (m->phys_addr < pa_half)
1367 			m_tmp = &seg->first_page[atop(pa_half - seg->start)];
1368 		else {
1369 			m_tmp = m_set;
1370 			m_set = &seg->first_page[atop(pa_half - seg->start)];
1371 		}
1372 		vm_freelist_add(fl, m_tmp, order, 0);
1373 	}
1374 	KASSERT(m_set == m, ("vm_phys_unfree_page: fatal inconsistency"));
1375 	return (true);
1376 }
1377 
1378 /*
1379  * Find a run of contiguous physical pages, meeting alignment requirements, from
1380  * a list of max-sized page blocks, where we need at least two consecutive
1381  * blocks to satisfy the (large) page request.
1382  */
1383 static vm_page_t
vm_phys_find_freelist_contig(struct vm_freelist * fl,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)1384 vm_phys_find_freelist_contig(struct vm_freelist *fl, u_long npages,
1385     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
1386 {
1387 	struct vm_phys_seg *seg;
1388 	vm_page_t m, m_iter, m_ret;
1389 	vm_paddr_t max_size, size;
1390 	int max_order;
1391 
1392 	max_order = VM_NFREEORDER - 1;
1393 	size = npages << PAGE_SHIFT;
1394 	max_size = (vm_paddr_t)1 << (PAGE_SHIFT + max_order);
1395 	KASSERT(size > max_size, ("size is too small"));
1396 
1397 	/*
1398 	 * In order to avoid examining any free max-sized page block more than
1399 	 * twice, identify the ones that are first in a physically-contiguous
1400 	 * sequence of such blocks, and only for those walk the sequence to
1401 	 * check if there are enough free blocks starting at a properly aligned
1402 	 * block.  Thus, no block is checked for free-ness more than twice.
1403 	 */
1404 	TAILQ_FOREACH(m, &fl[max_order].pl, listq) {
1405 		/*
1406 		 * Skip m unless it is first in a sequence of free max page
1407 		 * blocks >= low in its segment.
1408 		 */
1409 		seg = &vm_phys_segs[m->segind];
1410 		if (VM_PAGE_TO_PHYS(m) < MAX(low, seg->start))
1411 			continue;
1412 		if (VM_PAGE_TO_PHYS(m) >= max_size &&
1413 		    VM_PAGE_TO_PHYS(m) - max_size >= MAX(low, seg->start) &&
1414 		    max_order == m[-1 << max_order].order)
1415 			continue;
1416 
1417 		/*
1418 		 * Advance m_ret from m to the first of the sequence, if any,
1419 		 * that satisfies alignment conditions and might leave enough
1420 		 * space.
1421 		 */
1422 		m_ret = m;
1423 		while (!vm_addr_ok(VM_PAGE_TO_PHYS(m_ret),
1424 		    size, alignment, boundary) &&
1425 		    VM_PAGE_TO_PHYS(m_ret) + size <= MIN(high, seg->end) &&
1426 		    max_order == m_ret[1 << max_order].order)
1427 			m_ret += 1 << max_order;
1428 
1429 		/*
1430 		 * Skip m unless some block m_ret in the sequence is properly
1431 		 * aligned, and begins a sequence of enough pages less than
1432 		 * high, and in the same segment.
1433 		 */
1434 		if (VM_PAGE_TO_PHYS(m_ret) + size > MIN(high, seg->end))
1435 			continue;
1436 
1437 		/*
1438 		 * Skip m unless the blocks to allocate starting at m_ret are
1439 		 * all free.
1440 		 */
1441 		for (m_iter = m_ret;
1442 		    m_iter < m_ret + npages && max_order == m_iter->order;
1443 		    m_iter += 1 << max_order) {
1444 		}
1445 		if (m_iter < m_ret + npages)
1446 			continue;
1447 		return (m_ret);
1448 	}
1449 	return (NULL);
1450 }
1451 
1452 /*
1453  * Find a run of contiguous physical pages from the specified free list
1454  * table.
1455  */
1456 static vm_page_t
vm_phys_find_queues_contig(struct vm_freelist (* queues)[VM_NFREEPOOL][VM_NFREEORDER_MAX],u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)1457 vm_phys_find_queues_contig(
1458     struct vm_freelist (*queues)[VM_NFREEPOOL][VM_NFREEORDER_MAX],
1459     u_long npages, vm_paddr_t low, vm_paddr_t high,
1460     u_long alignment, vm_paddr_t boundary)
1461 {
1462 	struct vm_freelist *fl;
1463 	vm_page_t m_ret;
1464 	vm_paddr_t pa, pa_end, size;
1465 	int oind, order, pind;
1466 
1467 	KASSERT(npages > 0, ("npages is 0"));
1468 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
1469 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
1470 	/* Compute the queue that is the best fit for npages. */
1471 	order = flsl(npages - 1);
1472 	/* Search for a large enough free block. */
1473 	size = npages << PAGE_SHIFT;
1474 	for (oind = order; oind < VM_NFREEORDER; oind++) {
1475 		for (pind = 0; pind < VM_NFREEPOOL; pind++) {
1476 			fl = (*queues)[pind];
1477 			TAILQ_FOREACH(m_ret, &fl[oind].pl, listq) {
1478 				/*
1479 				 * Determine if the address range starting at pa
1480 				 * is within the given range, satisfies the
1481 				 * given alignment, and does not cross the given
1482 				 * boundary.
1483 				 */
1484 				pa = VM_PAGE_TO_PHYS(m_ret);
1485 				pa_end = pa + size;
1486 				if (low <= pa && pa_end <= high &&
1487 				    vm_addr_ok(pa, size, alignment, boundary))
1488 					return (m_ret);
1489 			}
1490 		}
1491 	}
1492 	if (order < VM_NFREEORDER)
1493 		return (NULL);
1494 	/* Search for a long-enough sequence of max-order blocks. */
1495 	for (pind = 0; pind < VM_NFREEPOOL; pind++) {
1496 		fl = (*queues)[pind];
1497 		m_ret = vm_phys_find_freelist_contig(fl, npages,
1498 		    low, high, alignment, boundary);
1499 		if (m_ret != NULL)
1500 			return (m_ret);
1501 	}
1502 	return (NULL);
1503 }
1504 
1505 /*
1506  * Allocate a contiguous set of physical pages of the given size
1507  * "npages" from the free lists.  All of the physical pages must be at
1508  * or above the given physical address "low" and below the given
1509  * physical address "high".  The given value "alignment" determines the
1510  * alignment of the first physical page in the set.  If the given value
1511  * "boundary" is non-zero, then the set of physical pages cannot cross
1512  * any physical address boundary that is a multiple of that value.  Both
1513  * "alignment" and "boundary" must be a power of two.
1514  */
1515 vm_page_t
vm_phys_alloc_contig(int domain,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)1516 vm_phys_alloc_contig(int domain, u_long npages, vm_paddr_t low, vm_paddr_t high,
1517     u_long alignment, vm_paddr_t boundary)
1518 {
1519 	vm_paddr_t pa_end, pa_start;
1520 	struct vm_freelist *fl;
1521 	vm_page_t m, m_run;
1522 	struct vm_phys_seg *seg;
1523 	struct vm_freelist (*queues)[VM_NFREEPOOL][VM_NFREEORDER_MAX];
1524 	int oind, segind;
1525 
1526 	KASSERT(npages > 0, ("npages is 0"));
1527 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
1528 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
1529 	vm_domain_free_assert_locked(VM_DOMAIN(domain));
1530 	if (low >= high)
1531 		return (NULL);
1532 	queues = NULL;
1533 	m_run = NULL;
1534 	for (segind = vm_phys_nsegs - 1; segind >= 0; segind--) {
1535 		seg = &vm_phys_segs[segind];
1536 		if (seg->start >= high || seg->domain != domain)
1537 			continue;
1538 		if (low >= seg->end)
1539 			break;
1540 		if (low <= seg->start)
1541 			pa_start = seg->start;
1542 		else
1543 			pa_start = low;
1544 		if (high < seg->end)
1545 			pa_end = high;
1546 		else
1547 			pa_end = seg->end;
1548 		if (pa_end - pa_start < ptoa(npages))
1549 			continue;
1550 		/*
1551 		 * If a previous segment led to a search using
1552 		 * the same free lists as would this segment, then
1553 		 * we've actually already searched within this
1554 		 * too.  So skip it.
1555 		 */
1556 		if (seg->free_queues == queues)
1557 			continue;
1558 		queues = seg->free_queues;
1559 		m_run = vm_phys_find_queues_contig(queues, npages,
1560 		    low, high, alignment, boundary);
1561 		if (m_run != NULL)
1562 			break;
1563 	}
1564 	if (m_run == NULL)
1565 		return (NULL);
1566 
1567 	/* Allocate pages from the page-range found. */
1568 	for (m = m_run; m < &m_run[npages]; m = &m[1 << oind]) {
1569 		fl = (*queues)[m->pool];
1570 		oind = m->order;
1571 		vm_freelist_rem(fl, m, oind);
1572 		if (m->pool != VM_FREEPOOL_DEFAULT)
1573 			vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, oind);
1574 	}
1575 	/* Return excess pages to the free lists. */
1576 	fl = (*queues)[VM_FREEPOOL_DEFAULT];
1577 	vm_phys_enq_range(&m_run[npages], m - &m_run[npages], fl, 0);
1578 
1579 	/* Return page verified to satisfy conditions of request. */
1580 	pa_start = VM_PAGE_TO_PHYS(m_run);
1581 	KASSERT(low <= pa_start,
1582 	    ("memory allocated below minimum requested range"));
1583 	KASSERT(pa_start + ptoa(npages) <= high,
1584 	    ("memory allocated above maximum requested range"));
1585 	seg = &vm_phys_segs[m_run->segind];
1586 	KASSERT(seg->domain == domain,
1587 	    ("memory not allocated from specified domain"));
1588 	KASSERT(vm_addr_ok(pa_start, ptoa(npages), alignment, boundary),
1589 	    ("memory alignment/boundary constraints not satisfied"));
1590 	return (m_run);
1591 }
1592 
1593 /*
1594  * Return the index of the first unused slot which may be the terminating
1595  * entry.
1596  */
1597 static int
vm_phys_avail_count(void)1598 vm_phys_avail_count(void)
1599 {
1600 	int i;
1601 
1602 	for (i = 0; i < PHYS_AVAIL_COUNT; i += 2)
1603 		if (phys_avail[i] == 0 && phys_avail[i + 1] == 0)
1604 			return (i);
1605 	panic("Improperly terminated phys_avail[]");
1606 }
1607 
1608 /*
1609  * Assert that a phys_avail entry is valid.
1610  */
1611 static void
vm_phys_avail_check(int i)1612 vm_phys_avail_check(int i)
1613 {
1614 	if (i % 2 != 0)
1615 		panic("Chunk start index %d is not even.", i);
1616 	if (phys_avail[i] & PAGE_MASK)
1617 		panic("Unaligned phys_avail[%d]: %#jx", i,
1618 		    (intmax_t)phys_avail[i]);
1619 	if (phys_avail[i + 1] & PAGE_MASK)
1620 		panic("Unaligned phys_avail[%d + 1]: %#jx", i,
1621 		    (intmax_t)phys_avail[i + 1]);
1622 	if (phys_avail[i + 1] < phys_avail[i])
1623 		panic("phys_avail[%d]: start %#jx > end %#jx", i,
1624 		    (intmax_t)phys_avail[i], (intmax_t)phys_avail[i + 1]);
1625 }
1626 
1627 /*
1628  * Return the index of an overlapping phys_avail entry or -1.
1629  */
1630 #ifdef NUMA
1631 static int
vm_phys_avail_find(vm_paddr_t pa)1632 vm_phys_avail_find(vm_paddr_t pa)
1633 {
1634 	int i;
1635 
1636 	for (i = 0; phys_avail[i + 1]; i += 2)
1637 		if (phys_avail[i] <= pa && phys_avail[i + 1] > pa)
1638 			return (i);
1639 	return (-1);
1640 }
1641 #endif
1642 
1643 /*
1644  * Return the index of the largest entry.
1645  */
1646 int
vm_phys_avail_largest(void)1647 vm_phys_avail_largest(void)
1648 {
1649 	vm_paddr_t sz, largesz;
1650 	int largest;
1651 	int i;
1652 
1653 	largest = 0;
1654 	largesz = 0;
1655 	for (i = 0; phys_avail[i + 1]; i += 2) {
1656 		sz = vm_phys_avail_size(i);
1657 		if (sz > largesz) {
1658 			largesz = sz;
1659 			largest = i;
1660 		}
1661 	}
1662 
1663 	return (largest);
1664 }
1665 
1666 vm_paddr_t
vm_phys_avail_size(int i)1667 vm_phys_avail_size(int i)
1668 {
1669 
1670 	return (phys_avail[i + 1] - phys_avail[i]);
1671 }
1672 
1673 /*
1674  * Split a chunk in phys_avail[] at the address 'pa'.
1675  *
1676  * 'pa' must be within a chunk (slots i and i + 1) or one of its boundaries.
1677  * Returns zero on actual split, in which case the two new chunks occupy slots
1678  * i to i + 3, else EJUSTRETURN if 'pa' was one of the boundaries (and no split
1679  * actually occurred) else ENOSPC if there are not enough slots in phys_avail[]
1680  * to represent the additional chunk caused by the split.
1681  */
1682 static int
vm_phys_avail_split(vm_paddr_t pa,int i)1683 vm_phys_avail_split(vm_paddr_t pa, int i)
1684 {
1685 	int cnt;
1686 
1687 	vm_phys_avail_check(i);
1688 	if (pa < phys_avail[i] || pa > phys_avail[i + 1])
1689 		panic("%s: Address %#jx not in range at slot %d [%#jx;%#jx].",
1690 		    __func__, (uintmax_t)pa, i,
1691 		    (uintmax_t)phys_avail[i], (uintmax_t)phys_avail[i + 1]);
1692 	if (pa == phys_avail[i] || pa == phys_avail[i + 1])
1693 		return (EJUSTRETURN);
1694 	cnt = vm_phys_avail_count();
1695 	if (cnt >= PHYS_AVAIL_ENTRIES)
1696 		return (ENOSPC);
1697 	memmove(&phys_avail[i + 2], &phys_avail[i],
1698 	    (cnt - i) * sizeof(phys_avail[0]));
1699 	phys_avail[i + 1] = pa;
1700 	phys_avail[i + 2] = pa;
1701 	vm_phys_avail_check(i);
1702 	vm_phys_avail_check(i+2);
1703 
1704 	return (0);
1705 }
1706 
1707 /*
1708  * Check if a given physical address can be included as part of a crash dump.
1709  */
1710 bool
vm_phys_is_dumpable(vm_paddr_t pa)1711 vm_phys_is_dumpable(vm_paddr_t pa)
1712 {
1713 	vm_page_t m;
1714 	int i;
1715 
1716 	if ((m = vm_phys_paddr_to_vm_page(pa)) != NULL)
1717 		return ((m->flags & PG_NODUMP) == 0);
1718 
1719 	for (i = 0; dump_avail[i] != 0 || dump_avail[i + 1] != 0; i += 2) {
1720 		if (pa >= dump_avail[i] && pa < dump_avail[i + 1])
1721 			return (true);
1722 	}
1723 	return (false);
1724 }
1725 
1726 void
vm_phys_early_add_seg(vm_paddr_t start,vm_paddr_t end)1727 vm_phys_early_add_seg(vm_paddr_t start, vm_paddr_t end)
1728 {
1729 	struct vm_phys_seg *seg;
1730 
1731 	if (vm_phys_early_nsegs == -1)
1732 		panic("%s: called after initialization", __func__);
1733 	if (vm_phys_early_nsegs == nitems(vm_phys_early_segs))
1734 		panic("%s: ran out of early segments", __func__);
1735 
1736 	seg = &vm_phys_early_segs[vm_phys_early_nsegs++];
1737 	seg->start = start;
1738 	seg->end = end;
1739 }
1740 
1741 /*
1742  * This routine allocates NUMA node specific memory before the page
1743  * allocator is bootstrapped.
1744  */
1745 vm_paddr_t
vm_phys_early_alloc(int domain,size_t alloc_size)1746 vm_phys_early_alloc(int domain, size_t alloc_size)
1747 {
1748 #ifdef NUMA
1749 	int mem_index;
1750 #endif
1751 	int i, biggestone;
1752 	vm_paddr_t pa, mem_start, mem_end, size, biggestsize, align;
1753 
1754 	KASSERT(domain == -1 || (domain >= 0 && domain < vm_ndomains),
1755 	    ("%s: invalid domain index %d", __func__, domain));
1756 
1757 	/*
1758 	 * Search the mem_affinity array for the biggest address
1759 	 * range in the desired domain.  This is used to constrain
1760 	 * the phys_avail selection below.
1761 	 */
1762 	biggestsize = 0;
1763 	mem_start = 0;
1764 	mem_end = -1;
1765 #ifdef NUMA
1766 	mem_index = 0;
1767 	if (mem_affinity != NULL) {
1768 		for (i = 0;; i++) {
1769 			size = mem_affinity[i].end - mem_affinity[i].start;
1770 			if (size == 0)
1771 				break;
1772 			if (domain != -1 && mem_affinity[i].domain != domain)
1773 				continue;
1774 			if (size > biggestsize) {
1775 				mem_index = i;
1776 				biggestsize = size;
1777 			}
1778 		}
1779 		mem_start = mem_affinity[mem_index].start;
1780 		mem_end = mem_affinity[mem_index].end;
1781 	}
1782 #endif
1783 
1784 	/*
1785 	 * Now find biggest physical segment in within the desired
1786 	 * numa domain.
1787 	 */
1788 	biggestsize = 0;
1789 	biggestone = 0;
1790 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
1791 		/* skip regions that are out of range */
1792 		if (phys_avail[i+1] - alloc_size < mem_start ||
1793 		    phys_avail[i+1] > mem_end)
1794 			continue;
1795 		size = vm_phys_avail_size(i);
1796 		if (size > biggestsize) {
1797 			biggestone = i;
1798 			biggestsize = size;
1799 		}
1800 	}
1801 	alloc_size = round_page(alloc_size);
1802 
1803 	/*
1804 	 * Grab single pages from the front to reduce fragmentation.
1805 	 */
1806 	if (alloc_size == PAGE_SIZE) {
1807 		pa = phys_avail[biggestone];
1808 		phys_avail[biggestone] += PAGE_SIZE;
1809 		vm_phys_avail_check(biggestone);
1810 		return (pa);
1811 	}
1812 
1813 	/*
1814 	 * Naturally align large allocations.
1815 	 */
1816 	align = phys_avail[biggestone + 1] & (alloc_size - 1);
1817 	if (alloc_size + align > biggestsize)
1818 		panic("cannot find a large enough size\n");
1819 	if (align != 0 &&
1820 	    vm_phys_avail_split(phys_avail[biggestone + 1] - align,
1821 	    biggestone) != 0)
1822 		/* Wasting memory. */
1823 		phys_avail[biggestone + 1] -= align;
1824 
1825 	phys_avail[biggestone + 1] -= alloc_size;
1826 	vm_phys_avail_check(biggestone);
1827 	pa = phys_avail[biggestone + 1];
1828 	return (pa);
1829 }
1830 
1831 void
vm_phys_early_startup(void)1832 vm_phys_early_startup(void)
1833 {
1834 	struct vm_phys_seg *seg;
1835 	int i;
1836 
1837 	if (phys_avail[1] == 0)
1838 		panic("phys_avail[] is empty");
1839 
1840 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
1841 		phys_avail[i] = round_page(phys_avail[i]);
1842 		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
1843 	}
1844 
1845 	for (i = 0; i < vm_phys_early_nsegs; i++) {
1846 		seg = &vm_phys_early_segs[i];
1847 		vm_phys_add_seg(seg->start, seg->end);
1848 	}
1849 	vm_phys_early_nsegs = -1;
1850 
1851 #ifdef NUMA
1852 	/* Force phys_avail to be split by domain. */
1853 	if (mem_affinity != NULL) {
1854 		int idx;
1855 
1856 		for (i = 0; mem_affinity[i].end != 0; i++) {
1857 			idx = vm_phys_avail_find(mem_affinity[i].start);
1858 			if (idx != -1)
1859 				vm_phys_avail_split(mem_affinity[i].start, idx);
1860 			idx = vm_phys_avail_find(mem_affinity[i].end);
1861 			if (idx != -1)
1862 				vm_phys_avail_split(mem_affinity[i].end, idx);
1863 		}
1864 	}
1865 #endif
1866 }
1867 
1868 #ifdef DDB
1869 /*
1870  * Show the number of physical pages in each of the free lists.
1871  */
DB_SHOW_COMMAND_FLAGS(freepages,db_show_freepages,DB_CMD_MEMSAFE)1872 DB_SHOW_COMMAND_FLAGS(freepages, db_show_freepages, DB_CMD_MEMSAFE)
1873 {
1874 	struct vm_freelist *fl;
1875 	int flind, oind, pind, dom;
1876 
1877 	for (dom = 0; dom < vm_ndomains; dom++) {
1878 		db_printf("DOMAIN: %d\n", dom);
1879 		for (flind = 0; flind < vm_nfreelists; flind++) {
1880 			db_printf("FREE LIST %d:\n"
1881 			    "\n  ORDER (SIZE)  |  NUMBER"
1882 			    "\n              ", flind);
1883 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
1884 				db_printf("  |  POOL %d", pind);
1885 			db_printf("\n--            ");
1886 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
1887 				db_printf("-- --      ");
1888 			db_printf("--\n");
1889 			for (oind = VM_NFREEORDER - 1; oind >= 0; oind--) {
1890 				db_printf("  %2.2d (%6.6dK)", oind,
1891 				    1 << (PAGE_SHIFT - 10 + oind));
1892 				for (pind = 0; pind < VM_NFREEPOOL; pind++) {
1893 				fl = vm_phys_free_queues[dom][flind][pind];
1894 					db_printf("  |  %6.6d", fl[oind].lcnt);
1895 				}
1896 				db_printf("\n");
1897 			}
1898 			db_printf("\n");
1899 		}
1900 		db_printf("\n");
1901 	}
1902 }
1903 #endif
1904