xref: /freebsd/sys/vm/vm_phys.c (revision 15c433351f54e7cd5bec8d36c8e89e6a7fa55b26)
1 /*-
2  * Copyright (c) 2002-2006 Rice University
3  * Copyright (c) 2007 Alan L. Cox <alc@cs.rice.edu>
4  * All rights reserved.
5  *
6  * This software was developed for the FreeBSD Project by Alan L. Cox,
7  * Olivier Crameri, Peter Druschel, Sitaram Iyer, and Juan Navarro.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
22  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
25  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
28  * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  *	Physical memory system implementation
34  *
35  * Any external functions defined by this module are only to be used by the
36  * virtual memory system.
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_ddb.h"
43 #include "opt_vm.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/lock.h>
48 #include <sys/kernel.h>
49 #include <sys/malloc.h>
50 #include <sys/mutex.h>
51 #if MAXMEMDOM > 1
52 #include <sys/proc.h>
53 #endif
54 #include <sys/queue.h>
55 #include <sys/rwlock.h>
56 #include <sys/sbuf.h>
57 #include <sys/sysctl.h>
58 #include <sys/tree.h>
59 #include <sys/vmmeter.h>
60 #include <sys/seq.h>
61 
62 #include <ddb/ddb.h>
63 
64 #include <vm/vm.h>
65 #include <vm/vm_param.h>
66 #include <vm/vm_kern.h>
67 #include <vm/vm_object.h>
68 #include <vm/vm_page.h>
69 #include <vm/vm_phys.h>
70 
71 #include <vm/vm_domain.h>
72 
73 _Static_assert(sizeof(long) * NBBY >= VM_PHYSSEG_MAX,
74     "Too many physsegs.");
75 
76 struct mem_affinity *mem_affinity;
77 int *mem_locality;
78 
79 int vm_ndomains = 1;
80 
81 struct vm_phys_seg vm_phys_segs[VM_PHYSSEG_MAX];
82 int vm_phys_nsegs;
83 
84 struct vm_phys_fictitious_seg;
85 static int vm_phys_fictitious_cmp(struct vm_phys_fictitious_seg *,
86     struct vm_phys_fictitious_seg *);
87 
88 RB_HEAD(fict_tree, vm_phys_fictitious_seg) vm_phys_fictitious_tree =
89     RB_INITIALIZER(_vm_phys_fictitious_tree);
90 
91 struct vm_phys_fictitious_seg {
92 	RB_ENTRY(vm_phys_fictitious_seg) node;
93 	/* Memory region data */
94 	vm_paddr_t	start;
95 	vm_paddr_t	end;
96 	vm_page_t	first_page;
97 };
98 
99 RB_GENERATE_STATIC(fict_tree, vm_phys_fictitious_seg, node,
100     vm_phys_fictitious_cmp);
101 
102 static struct rwlock vm_phys_fictitious_reg_lock;
103 MALLOC_DEFINE(M_FICT_PAGES, "vm_fictitious", "Fictitious VM pages");
104 
105 static struct vm_freelist
106     vm_phys_free_queues[MAXMEMDOM][VM_NFREELIST][VM_NFREEPOOL][VM_NFREEORDER];
107 
108 static int vm_nfreelists;
109 
110 /*
111  * Provides the mapping from VM_FREELIST_* to free list indices (flind).
112  */
113 static int vm_freelist_to_flind[VM_NFREELIST];
114 
115 CTASSERT(VM_FREELIST_DEFAULT == 0);
116 
117 #ifdef VM_FREELIST_ISADMA
118 #define	VM_ISADMA_BOUNDARY	16777216
119 #endif
120 #ifdef VM_FREELIST_DMA32
121 #define	VM_DMA32_BOUNDARY	((vm_paddr_t)1 << 32)
122 #endif
123 
124 /*
125  * Enforce the assumptions made by vm_phys_add_seg() and vm_phys_init() about
126  * the ordering of the free list boundaries.
127  */
128 #if defined(VM_ISADMA_BOUNDARY) && defined(VM_LOWMEM_BOUNDARY)
129 CTASSERT(VM_ISADMA_BOUNDARY < VM_LOWMEM_BOUNDARY);
130 #endif
131 #if defined(VM_LOWMEM_BOUNDARY) && defined(VM_DMA32_BOUNDARY)
132 CTASSERT(VM_LOWMEM_BOUNDARY < VM_DMA32_BOUNDARY);
133 #endif
134 
135 static int cnt_prezero;
136 SYSCTL_INT(_vm_stats_misc, OID_AUTO, cnt_prezero, CTLFLAG_RD,
137     &cnt_prezero, 0, "The number of physical pages prezeroed at idle time");
138 
139 static int sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS);
140 SYSCTL_OID(_vm, OID_AUTO, phys_free, CTLTYPE_STRING | CTLFLAG_RD,
141     NULL, 0, sysctl_vm_phys_free, "A", "Phys Free Info");
142 
143 static int sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS);
144 SYSCTL_OID(_vm, OID_AUTO, phys_segs, CTLTYPE_STRING | CTLFLAG_RD,
145     NULL, 0, sysctl_vm_phys_segs, "A", "Phys Seg Info");
146 
147 #if MAXMEMDOM > 1
148 static int sysctl_vm_phys_locality(SYSCTL_HANDLER_ARGS);
149 SYSCTL_OID(_vm, OID_AUTO, phys_locality, CTLTYPE_STRING | CTLFLAG_RD,
150     NULL, 0, sysctl_vm_phys_locality, "A", "Phys Locality Info");
151 #endif
152 
153 SYSCTL_INT(_vm, OID_AUTO, ndomains, CTLFLAG_RD,
154     &vm_ndomains, 0, "Number of physical memory domains available.");
155 
156 /*
157  * Default to first-touch + round-robin.
158  */
159 static struct mtx vm_default_policy_mtx;
160 MTX_SYSINIT(vm_default_policy, &vm_default_policy_mtx, "default policy mutex",
161     MTX_DEF);
162 #if MAXMEMDOM > 1
163 static struct vm_domain_policy vm_default_policy =
164     VM_DOMAIN_POLICY_STATIC_INITIALISER(VM_POLICY_FIRST_TOUCH_ROUND_ROBIN, 0);
165 #else
166 /* Use round-robin so the domain policy code will only try once per allocation */
167 static struct vm_domain_policy vm_default_policy =
168     VM_DOMAIN_POLICY_STATIC_INITIALISER(VM_POLICY_ROUND_ROBIN, 0);
169 #endif
170 
171 static vm_page_t vm_phys_alloc_domain_pages(int domain, int flind, int pool,
172     int order);
173 static vm_page_t vm_phys_alloc_seg_contig(struct vm_phys_seg *seg,
174     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
175     vm_paddr_t boundary);
176 static void _vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int domain);
177 static void vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end);
178 static int vm_phys_paddr_to_segind(vm_paddr_t pa);
179 static void vm_phys_split_pages(vm_page_t m, int oind, struct vm_freelist *fl,
180     int order);
181 
182 static int
183 sysctl_vm_default_policy(SYSCTL_HANDLER_ARGS)
184 {
185 	char policy_name[32];
186 	int error;
187 
188 	mtx_lock(&vm_default_policy_mtx);
189 
190 	/* Map policy to output string */
191 	switch (vm_default_policy.p.policy) {
192 	case VM_POLICY_FIRST_TOUCH:
193 		strcpy(policy_name, "first-touch");
194 		break;
195 	case VM_POLICY_FIRST_TOUCH_ROUND_ROBIN:
196 		strcpy(policy_name, "first-touch-rr");
197 		break;
198 	case VM_POLICY_ROUND_ROBIN:
199 	default:
200 		strcpy(policy_name, "rr");
201 		break;
202 	}
203 	mtx_unlock(&vm_default_policy_mtx);
204 
205 	error = sysctl_handle_string(oidp, &policy_name[0],
206 	    sizeof(policy_name), req);
207 	if (error != 0 || req->newptr == NULL)
208 		return (error);
209 
210 	mtx_lock(&vm_default_policy_mtx);
211 	/* Set: match on the subset of policies that make sense as a default */
212 	if (strcmp("first-touch-rr", policy_name) == 0) {
213 		vm_domain_policy_set(&vm_default_policy,
214 		    VM_POLICY_FIRST_TOUCH_ROUND_ROBIN, 0);
215 	} else if (strcmp("first-touch", policy_name) == 0) {
216 		vm_domain_policy_set(&vm_default_policy,
217 		    VM_POLICY_FIRST_TOUCH, 0);
218 	} else if (strcmp("rr", policy_name) == 0) {
219 		vm_domain_policy_set(&vm_default_policy,
220 		    VM_POLICY_ROUND_ROBIN, 0);
221 	} else {
222 		error = EINVAL;
223 		goto finish;
224 	}
225 
226 	error = 0;
227 finish:
228 	mtx_unlock(&vm_default_policy_mtx);
229 	return (error);
230 }
231 
232 SYSCTL_PROC(_vm, OID_AUTO, default_policy, CTLTYPE_STRING | CTLFLAG_RW,
233     0, 0, sysctl_vm_default_policy, "A",
234     "Default policy (rr, first-touch, first-touch-rr");
235 
236 /*
237  * Red-black tree helpers for vm fictitious range management.
238  */
239 static inline int
240 vm_phys_fictitious_in_range(struct vm_phys_fictitious_seg *p,
241     struct vm_phys_fictitious_seg *range)
242 {
243 
244 	KASSERT(range->start != 0 && range->end != 0,
245 	    ("Invalid range passed on search for vm_fictitious page"));
246 	if (p->start >= range->end)
247 		return (1);
248 	if (p->start < range->start)
249 		return (-1);
250 
251 	return (0);
252 }
253 
254 static int
255 vm_phys_fictitious_cmp(struct vm_phys_fictitious_seg *p1,
256     struct vm_phys_fictitious_seg *p2)
257 {
258 
259 	/* Check if this is a search for a page */
260 	if (p1->end == 0)
261 		return (vm_phys_fictitious_in_range(p1, p2));
262 
263 	KASSERT(p2->end != 0,
264     ("Invalid range passed as second parameter to vm fictitious comparison"));
265 
266 	/* Searching to add a new range */
267 	if (p1->end <= p2->start)
268 		return (-1);
269 	if (p1->start >= p2->end)
270 		return (1);
271 
272 	panic("Trying to add overlapping vm fictitious ranges:\n"
273 	    "[%#jx:%#jx] and [%#jx:%#jx]", (uintmax_t)p1->start,
274 	    (uintmax_t)p1->end, (uintmax_t)p2->start, (uintmax_t)p2->end);
275 }
276 
277 static __inline int
278 vm_rr_selectdomain(void)
279 {
280 #if MAXMEMDOM > 1
281 	struct thread *td;
282 
283 	td = curthread;
284 
285 	td->td_dom_rr_idx++;
286 	td->td_dom_rr_idx %= vm_ndomains;
287 	return (td->td_dom_rr_idx);
288 #else
289 	return (0);
290 #endif
291 }
292 
293 /*
294  * Initialise a VM domain iterator.
295  *
296  * Check the thread policy, then the proc policy,
297  * then default to the system policy.
298  *
299  * Later on the various layers will have this logic
300  * plumbed into them and the phys code will be explicitly
301  * handed a VM domain policy to use.
302  */
303 static void
304 vm_policy_iterator_init(struct vm_domain_iterator *vi)
305 {
306 #if MAXMEMDOM > 1
307 	struct vm_domain_policy lcl;
308 #endif
309 
310 	vm_domain_iterator_init(vi);
311 
312 #if MAXMEMDOM > 1
313 	/* Copy out the thread policy */
314 	vm_domain_policy_localcopy(&lcl, &curthread->td_vm_dom_policy);
315 	if (lcl.p.policy != VM_POLICY_NONE) {
316 		/* Thread policy is present; use it */
317 		vm_domain_iterator_set_policy(vi, &lcl);
318 		return;
319 	}
320 
321 	vm_domain_policy_localcopy(&lcl,
322 	    &curthread->td_proc->p_vm_dom_policy);
323 	if (lcl.p.policy != VM_POLICY_NONE) {
324 		/* Process policy is present; use it */
325 		vm_domain_iterator_set_policy(vi, &lcl);
326 		return;
327 	}
328 #endif
329 	/* Use system default policy */
330 	vm_domain_iterator_set_policy(vi, &vm_default_policy);
331 }
332 
333 static void
334 vm_policy_iterator_finish(struct vm_domain_iterator *vi)
335 {
336 
337 	vm_domain_iterator_cleanup(vi);
338 }
339 
340 boolean_t
341 vm_phys_domain_intersects(long mask, vm_paddr_t low, vm_paddr_t high)
342 {
343 	struct vm_phys_seg *s;
344 	int idx;
345 
346 	while ((idx = ffsl(mask)) != 0) {
347 		idx--;	/* ffsl counts from 1 */
348 		mask &= ~(1UL << idx);
349 		s = &vm_phys_segs[idx];
350 		if (low < s->end && high > s->start)
351 			return (TRUE);
352 	}
353 	return (FALSE);
354 }
355 
356 /*
357  * Outputs the state of the physical memory allocator, specifically,
358  * the amount of physical memory in each free list.
359  */
360 static int
361 sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
362 {
363 	struct sbuf sbuf;
364 	struct vm_freelist *fl;
365 	int dom, error, flind, oind, pind;
366 
367 	error = sysctl_wire_old_buffer(req, 0);
368 	if (error != 0)
369 		return (error);
370 	sbuf_new_for_sysctl(&sbuf, NULL, 128 * vm_ndomains, req);
371 	for (dom = 0; dom < vm_ndomains; dom++) {
372 		sbuf_printf(&sbuf,"\nDOMAIN %d:\n", dom);
373 		for (flind = 0; flind < vm_nfreelists; flind++) {
374 			sbuf_printf(&sbuf, "\nFREE LIST %d:\n"
375 			    "\n  ORDER (SIZE)  |  NUMBER"
376 			    "\n              ", flind);
377 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
378 				sbuf_printf(&sbuf, "  |  POOL %d", pind);
379 			sbuf_printf(&sbuf, "\n--            ");
380 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
381 				sbuf_printf(&sbuf, "-- --      ");
382 			sbuf_printf(&sbuf, "--\n");
383 			for (oind = VM_NFREEORDER - 1; oind >= 0; oind--) {
384 				sbuf_printf(&sbuf, "  %2d (%6dK)", oind,
385 				    1 << (PAGE_SHIFT - 10 + oind));
386 				for (pind = 0; pind < VM_NFREEPOOL; pind++) {
387 				fl = vm_phys_free_queues[dom][flind][pind];
388 					sbuf_printf(&sbuf, "  |  %6d",
389 					    fl[oind].lcnt);
390 				}
391 				sbuf_printf(&sbuf, "\n");
392 			}
393 		}
394 	}
395 	error = sbuf_finish(&sbuf);
396 	sbuf_delete(&sbuf);
397 	return (error);
398 }
399 
400 /*
401  * Outputs the set of physical memory segments.
402  */
403 static int
404 sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
405 {
406 	struct sbuf sbuf;
407 	struct vm_phys_seg *seg;
408 	int error, segind;
409 
410 	error = sysctl_wire_old_buffer(req, 0);
411 	if (error != 0)
412 		return (error);
413 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
414 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
415 		sbuf_printf(&sbuf, "\nSEGMENT %d:\n\n", segind);
416 		seg = &vm_phys_segs[segind];
417 		sbuf_printf(&sbuf, "start:     %#jx\n",
418 		    (uintmax_t)seg->start);
419 		sbuf_printf(&sbuf, "end:       %#jx\n",
420 		    (uintmax_t)seg->end);
421 		sbuf_printf(&sbuf, "domain:    %d\n", seg->domain);
422 		sbuf_printf(&sbuf, "free list: %p\n", seg->free_queues);
423 	}
424 	error = sbuf_finish(&sbuf);
425 	sbuf_delete(&sbuf);
426 	return (error);
427 }
428 
429 /*
430  * Return affinity, or -1 if there's no affinity information.
431  */
432 int
433 vm_phys_mem_affinity(int f, int t)
434 {
435 
436 #if MAXMEMDOM > 1
437 	if (mem_locality == NULL)
438 		return (-1);
439 	if (f >= vm_ndomains || t >= vm_ndomains)
440 		return (-1);
441 	return (mem_locality[f * vm_ndomains + t]);
442 #else
443 	return (-1);
444 #endif
445 }
446 
447 #if MAXMEMDOM > 1
448 /*
449  * Outputs the VM locality table.
450  */
451 static int
452 sysctl_vm_phys_locality(SYSCTL_HANDLER_ARGS)
453 {
454 	struct sbuf sbuf;
455 	int error, i, j;
456 
457 	error = sysctl_wire_old_buffer(req, 0);
458 	if (error != 0)
459 		return (error);
460 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
461 
462 	sbuf_printf(&sbuf, "\n");
463 
464 	for (i = 0; i < vm_ndomains; i++) {
465 		sbuf_printf(&sbuf, "%d: ", i);
466 		for (j = 0; j < vm_ndomains; j++) {
467 			sbuf_printf(&sbuf, "%d ", vm_phys_mem_affinity(i, j));
468 		}
469 		sbuf_printf(&sbuf, "\n");
470 	}
471 	error = sbuf_finish(&sbuf);
472 	sbuf_delete(&sbuf);
473 	return (error);
474 }
475 #endif
476 
477 static void
478 vm_freelist_add(struct vm_freelist *fl, vm_page_t m, int order, int tail)
479 {
480 
481 	m->order = order;
482 	if (tail)
483 		TAILQ_INSERT_TAIL(&fl[order].pl, m, plinks.q);
484 	else
485 		TAILQ_INSERT_HEAD(&fl[order].pl, m, plinks.q);
486 	fl[order].lcnt++;
487 }
488 
489 static void
490 vm_freelist_rem(struct vm_freelist *fl, vm_page_t m, int order)
491 {
492 
493 	TAILQ_REMOVE(&fl[order].pl, m, plinks.q);
494 	fl[order].lcnt--;
495 	m->order = VM_NFREEORDER;
496 }
497 
498 /*
499  * Create a physical memory segment.
500  */
501 static void
502 _vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int domain)
503 {
504 	struct vm_phys_seg *seg;
505 
506 	KASSERT(vm_phys_nsegs < VM_PHYSSEG_MAX,
507 	    ("vm_phys_create_seg: increase VM_PHYSSEG_MAX"));
508 	KASSERT(domain < vm_ndomains,
509 	    ("vm_phys_create_seg: invalid domain provided"));
510 	seg = &vm_phys_segs[vm_phys_nsegs++];
511 	while (seg > vm_phys_segs && (seg - 1)->start >= end) {
512 		*seg = *(seg - 1);
513 		seg--;
514 	}
515 	seg->start = start;
516 	seg->end = end;
517 	seg->domain = domain;
518 }
519 
520 static void
521 vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end)
522 {
523 	int i;
524 
525 	if (mem_affinity == NULL) {
526 		_vm_phys_create_seg(start, end, 0);
527 		return;
528 	}
529 
530 	for (i = 0;; i++) {
531 		if (mem_affinity[i].end == 0)
532 			panic("Reached end of affinity info");
533 		if (mem_affinity[i].end <= start)
534 			continue;
535 		if (mem_affinity[i].start > start)
536 			panic("No affinity info for start %jx",
537 			    (uintmax_t)start);
538 		if (mem_affinity[i].end >= end) {
539 			_vm_phys_create_seg(start, end,
540 			    mem_affinity[i].domain);
541 			break;
542 		}
543 		_vm_phys_create_seg(start, mem_affinity[i].end,
544 		    mem_affinity[i].domain);
545 		start = mem_affinity[i].end;
546 	}
547 }
548 
549 /*
550  * Add a physical memory segment.
551  */
552 void
553 vm_phys_add_seg(vm_paddr_t start, vm_paddr_t end)
554 {
555 	vm_paddr_t paddr;
556 
557 	KASSERT((start & PAGE_MASK) == 0,
558 	    ("vm_phys_define_seg: start is not page aligned"));
559 	KASSERT((end & PAGE_MASK) == 0,
560 	    ("vm_phys_define_seg: end is not page aligned"));
561 
562 	/*
563 	 * Split the physical memory segment if it spans two or more free
564 	 * list boundaries.
565 	 */
566 	paddr = start;
567 #ifdef	VM_FREELIST_ISADMA
568 	if (paddr < VM_ISADMA_BOUNDARY && end > VM_ISADMA_BOUNDARY) {
569 		vm_phys_create_seg(paddr, VM_ISADMA_BOUNDARY);
570 		paddr = VM_ISADMA_BOUNDARY;
571 	}
572 #endif
573 #ifdef	VM_FREELIST_LOWMEM
574 	if (paddr < VM_LOWMEM_BOUNDARY && end > VM_LOWMEM_BOUNDARY) {
575 		vm_phys_create_seg(paddr, VM_LOWMEM_BOUNDARY);
576 		paddr = VM_LOWMEM_BOUNDARY;
577 	}
578 #endif
579 #ifdef	VM_FREELIST_DMA32
580 	if (paddr < VM_DMA32_BOUNDARY && end > VM_DMA32_BOUNDARY) {
581 		vm_phys_create_seg(paddr, VM_DMA32_BOUNDARY);
582 		paddr = VM_DMA32_BOUNDARY;
583 	}
584 #endif
585 	vm_phys_create_seg(paddr, end);
586 }
587 
588 /*
589  * Initialize the physical memory allocator.
590  *
591  * Requires that vm_page_array is initialized!
592  */
593 void
594 vm_phys_init(void)
595 {
596 	struct vm_freelist *fl;
597 	struct vm_phys_seg *seg;
598 	u_long npages;
599 	int dom, flind, freelist, oind, pind, segind;
600 
601 	/*
602 	 * Compute the number of free lists, and generate the mapping from the
603 	 * manifest constants VM_FREELIST_* to the free list indices.
604 	 *
605 	 * Initially, the entries of vm_freelist_to_flind[] are set to either
606 	 * 0 or 1 to indicate which free lists should be created.
607 	 */
608 	npages = 0;
609 	for (segind = vm_phys_nsegs - 1; segind >= 0; segind--) {
610 		seg = &vm_phys_segs[segind];
611 #ifdef	VM_FREELIST_ISADMA
612 		if (seg->end <= VM_ISADMA_BOUNDARY)
613 			vm_freelist_to_flind[VM_FREELIST_ISADMA] = 1;
614 		else
615 #endif
616 #ifdef	VM_FREELIST_LOWMEM
617 		if (seg->end <= VM_LOWMEM_BOUNDARY)
618 			vm_freelist_to_flind[VM_FREELIST_LOWMEM] = 1;
619 		else
620 #endif
621 #ifdef	VM_FREELIST_DMA32
622 		if (
623 #ifdef	VM_DMA32_NPAGES_THRESHOLD
624 		    /*
625 		     * Create the DMA32 free list only if the amount of
626 		     * physical memory above physical address 4G exceeds the
627 		     * given threshold.
628 		     */
629 		    npages > VM_DMA32_NPAGES_THRESHOLD &&
630 #endif
631 		    seg->end <= VM_DMA32_BOUNDARY)
632 			vm_freelist_to_flind[VM_FREELIST_DMA32] = 1;
633 		else
634 #endif
635 		{
636 			npages += atop(seg->end - seg->start);
637 			vm_freelist_to_flind[VM_FREELIST_DEFAULT] = 1;
638 		}
639 	}
640 	/* Change each entry into a running total of the free lists. */
641 	for (freelist = 1; freelist < VM_NFREELIST; freelist++) {
642 		vm_freelist_to_flind[freelist] +=
643 		    vm_freelist_to_flind[freelist - 1];
644 	}
645 	vm_nfreelists = vm_freelist_to_flind[VM_NFREELIST - 1];
646 	KASSERT(vm_nfreelists > 0, ("vm_phys_init: no free lists"));
647 	/* Change each entry into a free list index. */
648 	for (freelist = 0; freelist < VM_NFREELIST; freelist++)
649 		vm_freelist_to_flind[freelist]--;
650 
651 	/*
652 	 * Initialize the first_page and free_queues fields of each physical
653 	 * memory segment.
654 	 */
655 #ifdef VM_PHYSSEG_SPARSE
656 	npages = 0;
657 #endif
658 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
659 		seg = &vm_phys_segs[segind];
660 #ifdef VM_PHYSSEG_SPARSE
661 		seg->first_page = &vm_page_array[npages];
662 		npages += atop(seg->end - seg->start);
663 #else
664 		seg->first_page = PHYS_TO_VM_PAGE(seg->start);
665 #endif
666 #ifdef	VM_FREELIST_ISADMA
667 		if (seg->end <= VM_ISADMA_BOUNDARY) {
668 			flind = vm_freelist_to_flind[VM_FREELIST_ISADMA];
669 			KASSERT(flind >= 0,
670 			    ("vm_phys_init: ISADMA flind < 0"));
671 		} else
672 #endif
673 #ifdef	VM_FREELIST_LOWMEM
674 		if (seg->end <= VM_LOWMEM_BOUNDARY) {
675 			flind = vm_freelist_to_flind[VM_FREELIST_LOWMEM];
676 			KASSERT(flind >= 0,
677 			    ("vm_phys_init: LOWMEM flind < 0"));
678 		} else
679 #endif
680 #ifdef	VM_FREELIST_DMA32
681 		if (seg->end <= VM_DMA32_BOUNDARY) {
682 			flind = vm_freelist_to_flind[VM_FREELIST_DMA32];
683 			KASSERT(flind >= 0,
684 			    ("vm_phys_init: DMA32 flind < 0"));
685 		} else
686 #endif
687 		{
688 			flind = vm_freelist_to_flind[VM_FREELIST_DEFAULT];
689 			KASSERT(flind >= 0,
690 			    ("vm_phys_init: DEFAULT flind < 0"));
691 		}
692 		seg->free_queues = &vm_phys_free_queues[seg->domain][flind];
693 	}
694 
695 	/*
696 	 * Initialize the free queues.
697 	 */
698 	for (dom = 0; dom < vm_ndomains; dom++) {
699 		for (flind = 0; flind < vm_nfreelists; flind++) {
700 			for (pind = 0; pind < VM_NFREEPOOL; pind++) {
701 				fl = vm_phys_free_queues[dom][flind][pind];
702 				for (oind = 0; oind < VM_NFREEORDER; oind++)
703 					TAILQ_INIT(&fl[oind].pl);
704 			}
705 		}
706 	}
707 
708 	rw_init(&vm_phys_fictitious_reg_lock, "vmfctr");
709 }
710 
711 /*
712  * Split a contiguous, power of two-sized set of physical pages.
713  */
714 static __inline void
715 vm_phys_split_pages(vm_page_t m, int oind, struct vm_freelist *fl, int order)
716 {
717 	vm_page_t m_buddy;
718 
719 	while (oind > order) {
720 		oind--;
721 		m_buddy = &m[1 << oind];
722 		KASSERT(m_buddy->order == VM_NFREEORDER,
723 		    ("vm_phys_split_pages: page %p has unexpected order %d",
724 		    m_buddy, m_buddy->order));
725 		vm_freelist_add(fl, m_buddy, oind, 0);
726         }
727 }
728 
729 /*
730  * Initialize a physical page and add it to the free lists.
731  */
732 void
733 vm_phys_add_page(vm_paddr_t pa)
734 {
735 	vm_page_t m;
736 	struct vm_domain *vmd;
737 
738 	vm_cnt.v_page_count++;
739 	m = vm_phys_paddr_to_vm_page(pa);
740 	m->phys_addr = pa;
741 	m->queue = PQ_NONE;
742 	m->segind = vm_phys_paddr_to_segind(pa);
743 	vmd = vm_phys_domain(m);
744 	vmd->vmd_page_count++;
745 	vmd->vmd_segs |= 1UL << m->segind;
746 	KASSERT(m->order == VM_NFREEORDER,
747 	    ("vm_phys_add_page: page %p has unexpected order %d",
748 	    m, m->order));
749 	m->pool = VM_FREEPOOL_DEFAULT;
750 	pmap_page_init(m);
751 	mtx_lock(&vm_page_queue_free_mtx);
752 	vm_phys_freecnt_adj(m, 1);
753 	vm_phys_free_pages(m, 0);
754 	mtx_unlock(&vm_page_queue_free_mtx);
755 }
756 
757 /*
758  * Allocate a contiguous, power of two-sized set of physical pages
759  * from the free lists.
760  *
761  * The free page queues must be locked.
762  */
763 vm_page_t
764 vm_phys_alloc_pages(int pool, int order)
765 {
766 	vm_page_t m;
767 	int domain, flind;
768 	struct vm_domain_iterator vi;
769 
770 	KASSERT(pool < VM_NFREEPOOL,
771 	    ("vm_phys_alloc_pages: pool %d is out of range", pool));
772 	KASSERT(order < VM_NFREEORDER,
773 	    ("vm_phys_alloc_pages: order %d is out of range", order));
774 
775 	vm_policy_iterator_init(&vi);
776 
777 	while ((vm_domain_iterator_run(&vi, &domain)) == 0) {
778 		for (flind = 0; flind < vm_nfreelists; flind++) {
779 			m = vm_phys_alloc_domain_pages(domain, flind, pool,
780 			    order);
781 			if (m != NULL)
782 				return (m);
783 		}
784 	}
785 
786 	vm_policy_iterator_finish(&vi);
787 	return (NULL);
788 }
789 
790 /*
791  * Allocate a contiguous, power of two-sized set of physical pages from the
792  * specified free list.  The free list must be specified using one of the
793  * manifest constants VM_FREELIST_*.
794  *
795  * The free page queues must be locked.
796  */
797 vm_page_t
798 vm_phys_alloc_freelist_pages(int freelist, int pool, int order)
799 {
800 	vm_page_t m;
801 	struct vm_domain_iterator vi;
802 	int domain;
803 
804 	KASSERT(freelist < VM_NFREELIST,
805 	    ("vm_phys_alloc_freelist_pages: freelist %d is out of range",
806 	    freelist));
807 	KASSERT(pool < VM_NFREEPOOL,
808 	    ("vm_phys_alloc_freelist_pages: pool %d is out of range", pool));
809 	KASSERT(order < VM_NFREEORDER,
810 	    ("vm_phys_alloc_freelist_pages: order %d is out of range", order));
811 
812 	vm_policy_iterator_init(&vi);
813 
814 	while ((vm_domain_iterator_run(&vi, &domain)) == 0) {
815 		m = vm_phys_alloc_domain_pages(domain,
816 		    vm_freelist_to_flind[freelist], pool, order);
817 		if (m != NULL)
818 			return (m);
819 	}
820 
821 	vm_policy_iterator_finish(&vi);
822 	return (NULL);
823 }
824 
825 static vm_page_t
826 vm_phys_alloc_domain_pages(int domain, int flind, int pool, int order)
827 {
828 	struct vm_freelist *fl;
829 	struct vm_freelist *alt;
830 	int oind, pind;
831 	vm_page_t m;
832 
833 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
834 	fl = &vm_phys_free_queues[domain][flind][pool][0];
835 	for (oind = order; oind < VM_NFREEORDER; oind++) {
836 		m = TAILQ_FIRST(&fl[oind].pl);
837 		if (m != NULL) {
838 			vm_freelist_rem(fl, m, oind);
839 			vm_phys_split_pages(m, oind, fl, order);
840 			return (m);
841 		}
842 	}
843 
844 	/*
845 	 * The given pool was empty.  Find the largest
846 	 * contiguous, power-of-two-sized set of pages in any
847 	 * pool.  Transfer these pages to the given pool, and
848 	 * use them to satisfy the allocation.
849 	 */
850 	for (oind = VM_NFREEORDER - 1; oind >= order; oind--) {
851 		for (pind = 0; pind < VM_NFREEPOOL; pind++) {
852 			alt = &vm_phys_free_queues[domain][flind][pind][0];
853 			m = TAILQ_FIRST(&alt[oind].pl);
854 			if (m != NULL) {
855 				vm_freelist_rem(alt, m, oind);
856 				vm_phys_set_pool(pool, m, oind);
857 				vm_phys_split_pages(m, oind, fl, order);
858 				return (m);
859 			}
860 		}
861 	}
862 	return (NULL);
863 }
864 
865 /*
866  * Find the vm_page corresponding to the given physical address.
867  */
868 vm_page_t
869 vm_phys_paddr_to_vm_page(vm_paddr_t pa)
870 {
871 	struct vm_phys_seg *seg;
872 	int segind;
873 
874 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
875 		seg = &vm_phys_segs[segind];
876 		if (pa >= seg->start && pa < seg->end)
877 			return (&seg->first_page[atop(pa - seg->start)]);
878 	}
879 	return (NULL);
880 }
881 
882 vm_page_t
883 vm_phys_fictitious_to_vm_page(vm_paddr_t pa)
884 {
885 	struct vm_phys_fictitious_seg tmp, *seg;
886 	vm_page_t m;
887 
888 	m = NULL;
889 	tmp.start = pa;
890 	tmp.end = 0;
891 
892 	rw_rlock(&vm_phys_fictitious_reg_lock);
893 	seg = RB_FIND(fict_tree, &vm_phys_fictitious_tree, &tmp);
894 	rw_runlock(&vm_phys_fictitious_reg_lock);
895 	if (seg == NULL)
896 		return (NULL);
897 
898 	m = &seg->first_page[atop(pa - seg->start)];
899 	KASSERT((m->flags & PG_FICTITIOUS) != 0, ("%p not fictitious", m));
900 
901 	return (m);
902 }
903 
904 static inline void
905 vm_phys_fictitious_init_range(vm_page_t range, vm_paddr_t start,
906     long page_count, vm_memattr_t memattr)
907 {
908 	long i;
909 
910 	for (i = 0; i < page_count; i++) {
911 		vm_page_initfake(&range[i], start + PAGE_SIZE * i, memattr);
912 		range[i].oflags &= ~VPO_UNMANAGED;
913 		range[i].busy_lock = VPB_UNBUSIED;
914 	}
915 }
916 
917 int
918 vm_phys_fictitious_reg_range(vm_paddr_t start, vm_paddr_t end,
919     vm_memattr_t memattr)
920 {
921 	struct vm_phys_fictitious_seg *seg;
922 	vm_page_t fp;
923 	long page_count;
924 #ifdef VM_PHYSSEG_DENSE
925 	long pi, pe;
926 	long dpage_count;
927 #endif
928 
929 	KASSERT(start < end,
930 	    ("Start of segment isn't less than end (start: %jx end: %jx)",
931 	    (uintmax_t)start, (uintmax_t)end));
932 
933 	page_count = (end - start) / PAGE_SIZE;
934 
935 #ifdef VM_PHYSSEG_DENSE
936 	pi = atop(start);
937 	pe = atop(end);
938 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
939 		fp = &vm_page_array[pi - first_page];
940 		if ((pe - first_page) > vm_page_array_size) {
941 			/*
942 			 * We have a segment that starts inside
943 			 * of vm_page_array, but ends outside of it.
944 			 *
945 			 * Use vm_page_array pages for those that are
946 			 * inside of the vm_page_array range, and
947 			 * allocate the remaining ones.
948 			 */
949 			dpage_count = vm_page_array_size - (pi - first_page);
950 			vm_phys_fictitious_init_range(fp, start, dpage_count,
951 			    memattr);
952 			page_count -= dpage_count;
953 			start += ptoa(dpage_count);
954 			goto alloc;
955 		}
956 		/*
957 		 * We can allocate the full range from vm_page_array,
958 		 * so there's no need to register the range in the tree.
959 		 */
960 		vm_phys_fictitious_init_range(fp, start, page_count, memattr);
961 		return (0);
962 	} else if (pe > first_page && (pe - first_page) < vm_page_array_size) {
963 		/*
964 		 * We have a segment that ends inside of vm_page_array,
965 		 * but starts outside of it.
966 		 */
967 		fp = &vm_page_array[0];
968 		dpage_count = pe - first_page;
969 		vm_phys_fictitious_init_range(fp, ptoa(first_page), dpage_count,
970 		    memattr);
971 		end -= ptoa(dpage_count);
972 		page_count -= dpage_count;
973 		goto alloc;
974 	} else if (pi < first_page && pe > (first_page + vm_page_array_size)) {
975 		/*
976 		 * Trying to register a fictitious range that expands before
977 		 * and after vm_page_array.
978 		 */
979 		return (EINVAL);
980 	} else {
981 alloc:
982 #endif
983 		fp = malloc(page_count * sizeof(struct vm_page), M_FICT_PAGES,
984 		    M_WAITOK | M_ZERO);
985 #ifdef VM_PHYSSEG_DENSE
986 	}
987 #endif
988 	vm_phys_fictitious_init_range(fp, start, page_count, memattr);
989 
990 	seg = malloc(sizeof(*seg), M_FICT_PAGES, M_WAITOK | M_ZERO);
991 	seg->start = start;
992 	seg->end = end;
993 	seg->first_page = fp;
994 
995 	rw_wlock(&vm_phys_fictitious_reg_lock);
996 	RB_INSERT(fict_tree, &vm_phys_fictitious_tree, seg);
997 	rw_wunlock(&vm_phys_fictitious_reg_lock);
998 
999 	return (0);
1000 }
1001 
1002 void
1003 vm_phys_fictitious_unreg_range(vm_paddr_t start, vm_paddr_t end)
1004 {
1005 	struct vm_phys_fictitious_seg *seg, tmp;
1006 #ifdef VM_PHYSSEG_DENSE
1007 	long pi, pe;
1008 #endif
1009 
1010 	KASSERT(start < end,
1011 	    ("Start of segment isn't less than end (start: %jx end: %jx)",
1012 	    (uintmax_t)start, (uintmax_t)end));
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 		if ((pe - first_page) <= vm_page_array_size) {
1019 			/*
1020 			 * This segment was allocated using vm_page_array
1021 			 * only, there's nothing to do since those pages
1022 			 * were never added to the tree.
1023 			 */
1024 			return;
1025 		}
1026 		/*
1027 		 * We have a segment that starts inside
1028 		 * of vm_page_array, but ends outside of it.
1029 		 *
1030 		 * Calculate how many pages were added to the
1031 		 * tree and free them.
1032 		 */
1033 		start = ptoa(first_page + vm_page_array_size);
1034 	} else if (pe > first_page && (pe - first_page) < vm_page_array_size) {
1035 		/*
1036 		 * We have a segment that ends inside of vm_page_array,
1037 		 * but starts outside of it.
1038 		 */
1039 		end = ptoa(first_page);
1040 	} else if (pi < first_page && pe > (first_page + vm_page_array_size)) {
1041 		/* Since it's not possible to register such a range, panic. */
1042 		panic(
1043 		    "Unregistering not registered fictitious range [%#jx:%#jx]",
1044 		    (uintmax_t)start, (uintmax_t)end);
1045 	}
1046 #endif
1047 	tmp.start = start;
1048 	tmp.end = 0;
1049 
1050 	rw_wlock(&vm_phys_fictitious_reg_lock);
1051 	seg = RB_FIND(fict_tree, &vm_phys_fictitious_tree, &tmp);
1052 	if (seg->start != start || seg->end != end) {
1053 		rw_wunlock(&vm_phys_fictitious_reg_lock);
1054 		panic(
1055 		    "Unregistering not registered fictitious range [%#jx:%#jx]",
1056 		    (uintmax_t)start, (uintmax_t)end);
1057 	}
1058 	RB_REMOVE(fict_tree, &vm_phys_fictitious_tree, seg);
1059 	rw_wunlock(&vm_phys_fictitious_reg_lock);
1060 	free(seg->first_page, M_FICT_PAGES);
1061 	free(seg, M_FICT_PAGES);
1062 }
1063 
1064 /*
1065  * Find the segment containing the given physical address.
1066  */
1067 static int
1068 vm_phys_paddr_to_segind(vm_paddr_t pa)
1069 {
1070 	struct vm_phys_seg *seg;
1071 	int segind;
1072 
1073 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
1074 		seg = &vm_phys_segs[segind];
1075 		if (pa >= seg->start && pa < seg->end)
1076 			return (segind);
1077 	}
1078 	panic("vm_phys_paddr_to_segind: paddr %#jx is not in any segment" ,
1079 	    (uintmax_t)pa);
1080 }
1081 
1082 /*
1083  * Free a contiguous, power of two-sized set of physical pages.
1084  *
1085  * The free page queues must be locked.
1086  */
1087 void
1088 vm_phys_free_pages(vm_page_t m, int order)
1089 {
1090 	struct vm_freelist *fl;
1091 	struct vm_phys_seg *seg;
1092 	vm_paddr_t pa;
1093 	vm_page_t m_buddy;
1094 
1095 	KASSERT(m->order == VM_NFREEORDER,
1096 	    ("vm_phys_free_pages: page %p has unexpected order %d",
1097 	    m, m->order));
1098 	KASSERT(m->pool < VM_NFREEPOOL,
1099 	    ("vm_phys_free_pages: page %p has unexpected pool %d",
1100 	    m, m->pool));
1101 	KASSERT(order < VM_NFREEORDER,
1102 	    ("vm_phys_free_pages: order %d is out of range", order));
1103 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1104 	seg = &vm_phys_segs[m->segind];
1105 	if (order < VM_NFREEORDER - 1) {
1106 		pa = VM_PAGE_TO_PHYS(m);
1107 		do {
1108 			pa ^= ((vm_paddr_t)1 << (PAGE_SHIFT + order));
1109 			if (pa < seg->start || pa >= seg->end)
1110 				break;
1111 			m_buddy = &seg->first_page[atop(pa - seg->start)];
1112 			if (m_buddy->order != order)
1113 				break;
1114 			fl = (*seg->free_queues)[m_buddy->pool];
1115 			vm_freelist_rem(fl, m_buddy, order);
1116 			if (m_buddy->pool != m->pool)
1117 				vm_phys_set_pool(m->pool, m_buddy, order);
1118 			order++;
1119 			pa &= ~(((vm_paddr_t)1 << (PAGE_SHIFT + order)) - 1);
1120 			m = &seg->first_page[atop(pa - seg->start)];
1121 		} while (order < VM_NFREEORDER - 1);
1122 	}
1123 	fl = (*seg->free_queues)[m->pool];
1124 	vm_freelist_add(fl, m, order, 1);
1125 }
1126 
1127 /*
1128  * Free a contiguous, arbitrarily sized set of physical pages.
1129  *
1130  * The free page queues must be locked.
1131  */
1132 void
1133 vm_phys_free_contig(vm_page_t m, u_long npages)
1134 {
1135 	u_int n;
1136 	int order;
1137 
1138 	/*
1139 	 * Avoid unnecessary coalescing by freeing the pages in the largest
1140 	 * possible power-of-two-sized subsets.
1141 	 */
1142 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1143 	for (;; npages -= n) {
1144 		/*
1145 		 * Unsigned "min" is used here so that "order" is assigned
1146 		 * "VM_NFREEORDER - 1" when "m"'s physical address is zero
1147 		 * or the low-order bits of its physical address are zero
1148 		 * because the size of a physical address exceeds the size of
1149 		 * a long.
1150 		 */
1151 		order = min(ffsl(VM_PAGE_TO_PHYS(m) >> PAGE_SHIFT) - 1,
1152 		    VM_NFREEORDER - 1);
1153 		n = 1 << order;
1154 		if (npages < n)
1155 			break;
1156 		vm_phys_free_pages(m, order);
1157 		m += n;
1158 	}
1159 	/* The residual "npages" is less than "1 << (VM_NFREEORDER - 1)". */
1160 	for (; npages > 0; npages -= n) {
1161 		order = flsl(npages) - 1;
1162 		n = 1 << order;
1163 		vm_phys_free_pages(m, order);
1164 		m += n;
1165 	}
1166 }
1167 
1168 /*
1169  * Scan physical memory between the specified addresses "low" and "high" for a
1170  * run of contiguous physical pages that satisfy the specified conditions, and
1171  * return the lowest page in the run.  The specified "alignment" determines
1172  * the alignment of the lowest physical page in the run.  If the specified
1173  * "boundary" is non-zero, then the run of physical pages cannot span a
1174  * physical address that is a multiple of "boundary".
1175  *
1176  * "npages" must be greater than zero.  Both "alignment" and "boundary" must
1177  * be a power of two.
1178  */
1179 vm_page_t
1180 vm_phys_scan_contig(u_long npages, vm_paddr_t low, vm_paddr_t high,
1181     u_long alignment, vm_paddr_t boundary, int options)
1182 {
1183 	vm_paddr_t pa_end;
1184 	vm_page_t m_end, m_run, m_start;
1185 	struct vm_phys_seg *seg;
1186 	int segind;
1187 
1188 	KASSERT(npages > 0, ("npages is 0"));
1189 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
1190 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
1191 	if (low >= high)
1192 		return (NULL);
1193 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
1194 		seg = &vm_phys_segs[segind];
1195 		if (seg->start >= high)
1196 			break;
1197 		if (low >= seg->end)
1198 			continue;
1199 		if (low <= seg->start)
1200 			m_start = seg->first_page;
1201 		else
1202 			m_start = &seg->first_page[atop(low - seg->start)];
1203 		if (high < seg->end)
1204 			pa_end = high;
1205 		else
1206 			pa_end = seg->end;
1207 		if (pa_end - VM_PAGE_TO_PHYS(m_start) < ptoa(npages))
1208 			continue;
1209 		m_end = &seg->first_page[atop(pa_end - seg->start)];
1210 		m_run = vm_page_scan_contig(npages, m_start, m_end,
1211 		    alignment, boundary, options);
1212 		if (m_run != NULL)
1213 			return (m_run);
1214 	}
1215 	return (NULL);
1216 }
1217 
1218 /*
1219  * Set the pool for a contiguous, power of two-sized set of physical pages.
1220  */
1221 void
1222 vm_phys_set_pool(int pool, vm_page_t m, int order)
1223 {
1224 	vm_page_t m_tmp;
1225 
1226 	for (m_tmp = m; m_tmp < &m[1 << order]; m_tmp++)
1227 		m_tmp->pool = pool;
1228 }
1229 
1230 /*
1231  * Search for the given physical page "m" in the free lists.  If the search
1232  * succeeds, remove "m" from the free lists and return TRUE.  Otherwise, return
1233  * FALSE, indicating that "m" is not in the free lists.
1234  *
1235  * The free page queues must be locked.
1236  */
1237 boolean_t
1238 vm_phys_unfree_page(vm_page_t m)
1239 {
1240 	struct vm_freelist *fl;
1241 	struct vm_phys_seg *seg;
1242 	vm_paddr_t pa, pa_half;
1243 	vm_page_t m_set, m_tmp;
1244 	int order;
1245 
1246 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1247 
1248 	/*
1249 	 * First, find the contiguous, power of two-sized set of free
1250 	 * physical pages containing the given physical page "m" and
1251 	 * assign it to "m_set".
1252 	 */
1253 	seg = &vm_phys_segs[m->segind];
1254 	for (m_set = m, order = 0; m_set->order == VM_NFREEORDER &&
1255 	    order < VM_NFREEORDER - 1; ) {
1256 		order++;
1257 		pa = m->phys_addr & (~(vm_paddr_t)0 << (PAGE_SHIFT + order));
1258 		if (pa >= seg->start)
1259 			m_set = &seg->first_page[atop(pa - seg->start)];
1260 		else
1261 			return (FALSE);
1262 	}
1263 	if (m_set->order < order)
1264 		return (FALSE);
1265 	if (m_set->order == VM_NFREEORDER)
1266 		return (FALSE);
1267 	KASSERT(m_set->order < VM_NFREEORDER,
1268 	    ("vm_phys_unfree_page: page %p has unexpected order %d",
1269 	    m_set, m_set->order));
1270 
1271 	/*
1272 	 * Next, remove "m_set" from the free lists.  Finally, extract
1273 	 * "m" from "m_set" using an iterative algorithm: While "m_set"
1274 	 * is larger than a page, shrink "m_set" by returning the half
1275 	 * of "m_set" that does not contain "m" to the free lists.
1276 	 */
1277 	fl = (*seg->free_queues)[m_set->pool];
1278 	order = m_set->order;
1279 	vm_freelist_rem(fl, m_set, order);
1280 	while (order > 0) {
1281 		order--;
1282 		pa_half = m_set->phys_addr ^ (1 << (PAGE_SHIFT + order));
1283 		if (m->phys_addr < pa_half)
1284 			m_tmp = &seg->first_page[atop(pa_half - seg->start)];
1285 		else {
1286 			m_tmp = m_set;
1287 			m_set = &seg->first_page[atop(pa_half - seg->start)];
1288 		}
1289 		vm_freelist_add(fl, m_tmp, order, 0);
1290 	}
1291 	KASSERT(m_set == m, ("vm_phys_unfree_page: fatal inconsistency"));
1292 	return (TRUE);
1293 }
1294 
1295 /*
1296  * Try to zero one physical page.  Used by an idle priority thread.
1297  */
1298 boolean_t
1299 vm_phys_zero_pages_idle(void)
1300 {
1301 	static struct vm_freelist *fl;
1302 	static int flind, oind, pind;
1303 	vm_page_t m, m_tmp;
1304 	int domain;
1305 
1306 	domain = vm_rr_selectdomain();
1307 	fl = vm_phys_free_queues[domain][0][0];
1308 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1309 	for (;;) {
1310 		TAILQ_FOREACH_REVERSE(m, &fl[oind].pl, pglist, plinks.q) {
1311 			for (m_tmp = m; m_tmp < &m[1 << oind]; m_tmp++) {
1312 				if ((m_tmp->flags & (PG_CACHED | PG_ZERO)) == 0) {
1313 					vm_phys_unfree_page(m_tmp);
1314 					vm_phys_freecnt_adj(m, -1);
1315 					mtx_unlock(&vm_page_queue_free_mtx);
1316 					pmap_zero_page_idle(m_tmp);
1317 					m_tmp->flags |= PG_ZERO;
1318 					mtx_lock(&vm_page_queue_free_mtx);
1319 					vm_phys_freecnt_adj(m, 1);
1320 					vm_phys_free_pages(m_tmp, 0);
1321 					vm_page_zero_count++;
1322 					cnt_prezero++;
1323 					return (TRUE);
1324 				}
1325 			}
1326 		}
1327 		oind++;
1328 		if (oind == VM_NFREEORDER) {
1329 			oind = 0;
1330 			pind++;
1331 			if (pind == VM_NFREEPOOL) {
1332 				pind = 0;
1333 				flind++;
1334 				if (flind == vm_nfreelists)
1335 					flind = 0;
1336 			}
1337 			fl = vm_phys_free_queues[domain][flind][pind];
1338 		}
1339 	}
1340 }
1341 
1342 /*
1343  * Allocate a contiguous set of physical pages of the given size
1344  * "npages" from the free lists.  All of the physical pages must be at
1345  * or above the given physical address "low" and below the given
1346  * physical address "high".  The given value "alignment" determines the
1347  * alignment of the first physical page in the set.  If the given value
1348  * "boundary" is non-zero, then the set of physical pages cannot cross
1349  * any physical address boundary that is a multiple of that value.  Both
1350  * "alignment" and "boundary" must be a power of two.
1351  */
1352 vm_page_t
1353 vm_phys_alloc_contig(u_long npages, vm_paddr_t low, vm_paddr_t high,
1354     u_long alignment, vm_paddr_t boundary)
1355 {
1356 	vm_paddr_t pa_end, pa_start;
1357 	vm_page_t m_run;
1358 	struct vm_domain_iterator vi;
1359 	struct vm_phys_seg *seg;
1360 	int domain, segind;
1361 
1362 	KASSERT(npages > 0, ("npages is 0"));
1363 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
1364 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
1365 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1366 	if (low >= high)
1367 		return (NULL);
1368 	vm_policy_iterator_init(&vi);
1369 restartdom:
1370 	if (vm_domain_iterator_run(&vi, &domain) != 0) {
1371 		vm_policy_iterator_finish(&vi);
1372 		return (NULL);
1373 	}
1374 	m_run = NULL;
1375 	for (segind = vm_phys_nsegs - 1; segind >= 0; segind--) {
1376 		seg = &vm_phys_segs[segind];
1377 		if (seg->start >= high || seg->domain != domain)
1378 			continue;
1379 		if (low >= seg->end)
1380 			break;
1381 		if (low <= seg->start)
1382 			pa_start = seg->start;
1383 		else
1384 			pa_start = low;
1385 		if (high < seg->end)
1386 			pa_end = high;
1387 		else
1388 			pa_end = seg->end;
1389 		if (pa_end - pa_start < ptoa(npages))
1390 			continue;
1391 		m_run = vm_phys_alloc_seg_contig(seg, npages, low, high,
1392 		    alignment, boundary);
1393 		if (m_run != NULL)
1394 			break;
1395 	}
1396 	if (m_run == NULL && !vm_domain_iterator_isdone(&vi))
1397 		goto restartdom;
1398 	vm_policy_iterator_finish(&vi);
1399 	return (m_run);
1400 }
1401 
1402 /*
1403  * Allocate a run of contiguous physical pages from the free list for the
1404  * specified segment.
1405  */
1406 static vm_page_t
1407 vm_phys_alloc_seg_contig(struct vm_phys_seg *seg, u_long npages,
1408     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
1409 {
1410 	struct vm_freelist *fl;
1411 	vm_paddr_t pa, pa_end, size;
1412 	vm_page_t m, m_ret;
1413 	u_long npages_end;
1414 	int oind, order, pind;
1415 
1416 	KASSERT(npages > 0, ("npages is 0"));
1417 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
1418 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
1419 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1420 	/* Compute the queue that is the best fit for npages. */
1421 	for (order = 0; (1 << order) < npages; order++);
1422 	/* Search for a run satisfying the specified conditions. */
1423 	size = npages << PAGE_SHIFT;
1424 	for (oind = min(order, VM_NFREEORDER - 1); oind < VM_NFREEORDER;
1425 	    oind++) {
1426 		for (pind = 0; pind < VM_NFREEPOOL; pind++) {
1427 			fl = (*seg->free_queues)[pind];
1428 			TAILQ_FOREACH(m_ret, &fl[oind].pl, plinks.q) {
1429 				/*
1430 				 * Is the size of this allocation request
1431 				 * larger than the largest block size?
1432 				 */
1433 				if (order >= VM_NFREEORDER) {
1434 					/*
1435 					 * Determine if a sufficient number of
1436 					 * subsequent blocks to satisfy the
1437 					 * allocation request are free.
1438 					 */
1439 					pa = VM_PAGE_TO_PHYS(m_ret);
1440 					pa_end = pa + size;
1441 					for (;;) {
1442 						pa += 1 << (PAGE_SHIFT +
1443 						    VM_NFREEORDER - 1);
1444 						if (pa >= pa_end ||
1445 						    pa < seg->start ||
1446 						    pa >= seg->end)
1447 							break;
1448 						m = &seg->first_page[atop(pa -
1449 						    seg->start)];
1450 						if (m->order != VM_NFREEORDER -
1451 						    1)
1452 							break;
1453 					}
1454 					/* If not, go to the next block. */
1455 					if (pa < pa_end)
1456 						continue;
1457 				}
1458 
1459 				/*
1460 				 * Determine if the blocks are within the
1461 				 * given range, satisfy the given alignment,
1462 				 * and do not cross the given boundary.
1463 				 */
1464 				pa = VM_PAGE_TO_PHYS(m_ret);
1465 				pa_end = pa + size;
1466 				if (pa >= low && pa_end <= high && (pa &
1467 				    (alignment - 1)) == 0 && ((pa ^ (pa_end -
1468 				    1)) & ~(boundary - 1)) == 0)
1469 					goto done;
1470 			}
1471 		}
1472 	}
1473 	return (NULL);
1474 done:
1475 	for (m = m_ret; m < &m_ret[npages]; m = &m[1 << oind]) {
1476 		fl = (*seg->free_queues)[m->pool];
1477 		vm_freelist_rem(fl, m, m->order);
1478 	}
1479 	if (m_ret->pool != VM_FREEPOOL_DEFAULT)
1480 		vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m_ret, oind);
1481 	fl = (*seg->free_queues)[m_ret->pool];
1482 	vm_phys_split_pages(m_ret, oind, fl, order);
1483 	/* Return excess pages to the free lists. */
1484 	npages_end = roundup2(npages, 1 << imin(oind, order));
1485 	if (npages < npages_end)
1486 		vm_phys_free_contig(&m_ret[npages], npages_end - npages);
1487 	return (m_ret);
1488 }
1489 
1490 #ifdef DDB
1491 /*
1492  * Show the number of physical pages in each of the free lists.
1493  */
1494 DB_SHOW_COMMAND(freepages, db_show_freepages)
1495 {
1496 	struct vm_freelist *fl;
1497 	int flind, oind, pind, dom;
1498 
1499 	for (dom = 0; dom < vm_ndomains; dom++) {
1500 		db_printf("DOMAIN: %d\n", dom);
1501 		for (flind = 0; flind < vm_nfreelists; flind++) {
1502 			db_printf("FREE LIST %d:\n"
1503 			    "\n  ORDER (SIZE)  |  NUMBER"
1504 			    "\n              ", flind);
1505 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
1506 				db_printf("  |  POOL %d", pind);
1507 			db_printf("\n--            ");
1508 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
1509 				db_printf("-- --      ");
1510 			db_printf("--\n");
1511 			for (oind = VM_NFREEORDER - 1; oind >= 0; oind--) {
1512 				db_printf("  %2.2d (%6.6dK)", oind,
1513 				    1 << (PAGE_SHIFT - 10 + oind));
1514 				for (pind = 0; pind < VM_NFREEPOOL; pind++) {
1515 				fl = vm_phys_free_queues[dom][flind][pind];
1516 					db_printf("  |  %6.6d", fl[oind].lcnt);
1517 				}
1518 				db_printf("\n");
1519 			}
1520 			db_printf("\n");
1521 		}
1522 		db_printf("\n");
1523 	}
1524 }
1525 #endif
1526