xref: /freebsd/sys/vm/vm_phys.c (revision 27c43fe1f3795622c5bd4bbfc465a29a800c0799)
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/sbuf.h>
56 #include <sys/sysctl.h>
57 #include <sys/vmmeter.h>
58 
59 #include <ddb/ddb.h>
60 
61 #include <vm/vm.h>
62 #include <vm/vm_param.h>
63 #include <vm/vm_kern.h>
64 #include <vm/vm_object.h>
65 #include <vm/vm_page.h>
66 #include <vm/vm_phys.h>
67 
68 _Static_assert(sizeof(long) * NBBY >= VM_PHYSSEG_MAX,
69     "Too many physsegs.");
70 
71 struct mem_affinity *mem_affinity;
72 
73 int vm_ndomains = 1;
74 
75 struct vm_phys_seg vm_phys_segs[VM_PHYSSEG_MAX];
76 int vm_phys_nsegs;
77 
78 #define VM_PHYS_FICTITIOUS_NSEGS	8
79 static struct vm_phys_fictitious_seg {
80 	vm_paddr_t	start;
81 	vm_paddr_t	end;
82 	vm_page_t	first_page;
83 } vm_phys_fictitious_segs[VM_PHYS_FICTITIOUS_NSEGS];
84 static struct mtx vm_phys_fictitious_reg_mtx;
85 MALLOC_DEFINE(M_FICT_PAGES, "vm_fictitious", "Fictitious VM pages");
86 
87 static struct vm_freelist
88     vm_phys_free_queues[MAXMEMDOM][VM_NFREELIST][VM_NFREEPOOL][VM_NFREEORDER];
89 
90 static int vm_nfreelists = VM_FREELIST_DEFAULT + 1;
91 
92 static int cnt_prezero;
93 SYSCTL_INT(_vm_stats_misc, OID_AUTO, cnt_prezero, CTLFLAG_RD,
94     &cnt_prezero, 0, "The number of physical pages prezeroed at idle time");
95 
96 static int sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS);
97 SYSCTL_OID(_vm, OID_AUTO, phys_free, CTLTYPE_STRING | CTLFLAG_RD,
98     NULL, 0, sysctl_vm_phys_free, "A", "Phys Free Info");
99 
100 static int sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS);
101 SYSCTL_OID(_vm, OID_AUTO, phys_segs, CTLTYPE_STRING | CTLFLAG_RD,
102     NULL, 0, sysctl_vm_phys_segs, "A", "Phys Seg Info");
103 
104 SYSCTL_INT(_vm, OID_AUTO, ndomains, CTLFLAG_RD,
105     &vm_ndomains, 0, "Number of physical memory domains available.");
106 
107 static vm_page_t vm_phys_alloc_domain_pages(int domain, int flind, int pool,
108     int order);
109 static void _vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int flind,
110     int domain);
111 static void vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int flind);
112 static int vm_phys_paddr_to_segind(vm_paddr_t pa);
113 static void vm_phys_split_pages(vm_page_t m, int oind, struct vm_freelist *fl,
114     int order);
115 
116 static __inline int
117 vm_rr_selectdomain(void)
118 {
119 #if MAXMEMDOM > 1
120 	struct thread *td;
121 
122 	td = curthread;
123 
124 	td->td_dom_rr_idx++;
125 	td->td_dom_rr_idx %= vm_ndomains;
126 	return (td->td_dom_rr_idx);
127 #else
128 	return (0);
129 #endif
130 }
131 
132 boolean_t
133 vm_phys_domain_intersects(long mask, vm_paddr_t low, vm_paddr_t high)
134 {
135 	struct vm_phys_seg *s;
136 	int idx;
137 
138 	while ((idx = ffsl(mask)) != 0) {
139 		idx--;	/* ffsl counts from 1 */
140 		mask &= ~(1UL << idx);
141 		s = &vm_phys_segs[idx];
142 		if (low < s->end && high > s->start)
143 			return (TRUE);
144 	}
145 	return (FALSE);
146 }
147 
148 /*
149  * Outputs the state of the physical memory allocator, specifically,
150  * the amount of physical memory in each free list.
151  */
152 static int
153 sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
154 {
155 	struct sbuf sbuf;
156 	struct vm_freelist *fl;
157 	int dom, error, flind, oind, pind;
158 
159 	error = sysctl_wire_old_buffer(req, 0);
160 	if (error != 0)
161 		return (error);
162 	sbuf_new_for_sysctl(&sbuf, NULL, 128 * vm_ndomains, req);
163 	for (dom = 0; dom < vm_ndomains; dom++) {
164 		sbuf_printf(&sbuf,"\nDOMAIN %d:\n", dom);
165 		for (flind = 0; flind < vm_nfreelists; flind++) {
166 			sbuf_printf(&sbuf, "\nFREE LIST %d:\n"
167 			    "\n  ORDER (SIZE)  |  NUMBER"
168 			    "\n              ", flind);
169 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
170 				sbuf_printf(&sbuf, "  |  POOL %d", pind);
171 			sbuf_printf(&sbuf, "\n--            ");
172 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
173 				sbuf_printf(&sbuf, "-- --      ");
174 			sbuf_printf(&sbuf, "--\n");
175 			for (oind = VM_NFREEORDER - 1; oind >= 0; oind--) {
176 				sbuf_printf(&sbuf, "  %2d (%6dK)", oind,
177 				    1 << (PAGE_SHIFT - 10 + oind));
178 				for (pind = 0; pind < VM_NFREEPOOL; pind++) {
179 				fl = vm_phys_free_queues[dom][flind][pind];
180 					sbuf_printf(&sbuf, "  |  %6d",
181 					    fl[oind].lcnt);
182 				}
183 				sbuf_printf(&sbuf, "\n");
184 			}
185 		}
186 	}
187 	error = sbuf_finish(&sbuf);
188 	sbuf_delete(&sbuf);
189 	return (error);
190 }
191 
192 /*
193  * Outputs the set of physical memory segments.
194  */
195 static int
196 sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
197 {
198 	struct sbuf sbuf;
199 	struct vm_phys_seg *seg;
200 	int error, segind;
201 
202 	error = sysctl_wire_old_buffer(req, 0);
203 	if (error != 0)
204 		return (error);
205 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
206 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
207 		sbuf_printf(&sbuf, "\nSEGMENT %d:\n\n", segind);
208 		seg = &vm_phys_segs[segind];
209 		sbuf_printf(&sbuf, "start:     %#jx\n",
210 		    (uintmax_t)seg->start);
211 		sbuf_printf(&sbuf, "end:       %#jx\n",
212 		    (uintmax_t)seg->end);
213 		sbuf_printf(&sbuf, "domain:    %d\n", seg->domain);
214 		sbuf_printf(&sbuf, "free list: %p\n", seg->free_queues);
215 	}
216 	error = sbuf_finish(&sbuf);
217 	sbuf_delete(&sbuf);
218 	return (error);
219 }
220 
221 static void
222 vm_freelist_add(struct vm_freelist *fl, vm_page_t m, int order, int tail)
223 {
224 
225 	m->order = order;
226 	if (tail)
227 		TAILQ_INSERT_TAIL(&fl[order].pl, m, plinks.q);
228 	else
229 		TAILQ_INSERT_HEAD(&fl[order].pl, m, plinks.q);
230 	fl[order].lcnt++;
231 }
232 
233 static void
234 vm_freelist_rem(struct vm_freelist *fl, vm_page_t m, int order)
235 {
236 
237 	TAILQ_REMOVE(&fl[order].pl, m, plinks.q);
238 	fl[order].lcnt--;
239 	m->order = VM_NFREEORDER;
240 }
241 
242 /*
243  * Create a physical memory segment.
244  */
245 static void
246 _vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int flind, int domain)
247 {
248 	struct vm_phys_seg *seg;
249 #ifdef VM_PHYSSEG_SPARSE
250 	long pages;
251 	int segind;
252 
253 	pages = 0;
254 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
255 		seg = &vm_phys_segs[segind];
256 		pages += atop(seg->end - seg->start);
257 	}
258 #endif
259 	KASSERT(vm_phys_nsegs < VM_PHYSSEG_MAX,
260 	    ("vm_phys_create_seg: increase VM_PHYSSEG_MAX"));
261 	KASSERT(domain < vm_ndomains,
262 	    ("vm_phys_create_seg: invalid domain provided"));
263 	seg = &vm_phys_segs[vm_phys_nsegs++];
264 	seg->start = start;
265 	seg->end = end;
266 	seg->domain = domain;
267 #ifdef VM_PHYSSEG_SPARSE
268 	seg->first_page = &vm_page_array[pages];
269 #else
270 	seg->first_page = PHYS_TO_VM_PAGE(start);
271 #endif
272 	seg->free_queues = &vm_phys_free_queues[domain][flind];
273 }
274 
275 static void
276 vm_phys_create_seg(vm_paddr_t start, vm_paddr_t end, int flind)
277 {
278 	int i;
279 
280 	if (mem_affinity == NULL) {
281 		_vm_phys_create_seg(start, end, flind, 0);
282 		return;
283 	}
284 
285 	for (i = 0;; i++) {
286 		if (mem_affinity[i].end == 0)
287 			panic("Reached end of affinity info");
288 		if (mem_affinity[i].end <= start)
289 			continue;
290 		if (mem_affinity[i].start > start)
291 			panic("No affinity info for start %jx",
292 			    (uintmax_t)start);
293 		if (mem_affinity[i].end >= end) {
294 			_vm_phys_create_seg(start, end, flind,
295 			    mem_affinity[i].domain);
296 			break;
297 		}
298 		_vm_phys_create_seg(start, mem_affinity[i].end, flind,
299 		    mem_affinity[i].domain);
300 		start = mem_affinity[i].end;
301 	}
302 }
303 
304 /*
305  * Initialize the physical memory allocator.
306  */
307 void
308 vm_phys_init(void)
309 {
310 	struct vm_freelist *fl;
311 	int dom, flind, i, oind, pind;
312 
313 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
314 #ifdef	VM_FREELIST_ISADMA
315 		if (phys_avail[i] < 16777216) {
316 			if (phys_avail[i + 1] > 16777216) {
317 				vm_phys_create_seg(phys_avail[i], 16777216,
318 				    VM_FREELIST_ISADMA);
319 				vm_phys_create_seg(16777216, phys_avail[i + 1],
320 				    VM_FREELIST_DEFAULT);
321 			} else {
322 				vm_phys_create_seg(phys_avail[i],
323 				    phys_avail[i + 1], VM_FREELIST_ISADMA);
324 			}
325 			if (VM_FREELIST_ISADMA >= vm_nfreelists)
326 				vm_nfreelists = VM_FREELIST_ISADMA + 1;
327 		} else
328 #endif
329 #ifdef	VM_FREELIST_HIGHMEM
330 		if (phys_avail[i + 1] > VM_HIGHMEM_ADDRESS) {
331 			if (phys_avail[i] < VM_HIGHMEM_ADDRESS) {
332 				vm_phys_create_seg(phys_avail[i],
333 				    VM_HIGHMEM_ADDRESS, VM_FREELIST_DEFAULT);
334 				vm_phys_create_seg(VM_HIGHMEM_ADDRESS,
335 				    phys_avail[i + 1], VM_FREELIST_HIGHMEM);
336 			} else {
337 				vm_phys_create_seg(phys_avail[i],
338 				    phys_avail[i + 1], VM_FREELIST_HIGHMEM);
339 			}
340 			if (VM_FREELIST_HIGHMEM >= vm_nfreelists)
341 				vm_nfreelists = VM_FREELIST_HIGHMEM + 1;
342 		} else
343 #endif
344 		vm_phys_create_seg(phys_avail[i], phys_avail[i + 1],
345 		    VM_FREELIST_DEFAULT);
346 	}
347 	for (dom = 0; dom < vm_ndomains; dom++) {
348 		for (flind = 0; flind < vm_nfreelists; flind++) {
349 			for (pind = 0; pind < VM_NFREEPOOL; pind++) {
350 				fl = vm_phys_free_queues[dom][flind][pind];
351 				for (oind = 0; oind < VM_NFREEORDER; oind++)
352 					TAILQ_INIT(&fl[oind].pl);
353 			}
354 		}
355 	}
356 	mtx_init(&vm_phys_fictitious_reg_mtx, "vmfctr", NULL, MTX_DEF);
357 }
358 
359 /*
360  * Split a contiguous, power of two-sized set of physical pages.
361  */
362 static __inline void
363 vm_phys_split_pages(vm_page_t m, int oind, struct vm_freelist *fl, int order)
364 {
365 	vm_page_t m_buddy;
366 
367 	while (oind > order) {
368 		oind--;
369 		m_buddy = &m[1 << oind];
370 		KASSERT(m_buddy->order == VM_NFREEORDER,
371 		    ("vm_phys_split_pages: page %p has unexpected order %d",
372 		    m_buddy, m_buddy->order));
373 		vm_freelist_add(fl, m_buddy, oind, 0);
374         }
375 }
376 
377 /*
378  * Initialize a physical page and add it to the free lists.
379  */
380 void
381 vm_phys_add_page(vm_paddr_t pa)
382 {
383 	vm_page_t m;
384 	struct vm_domain *vmd;
385 
386 	cnt.v_page_count++;
387 	m = vm_phys_paddr_to_vm_page(pa);
388 	m->phys_addr = pa;
389 	m->queue = PQ_NONE;
390 	m->segind = vm_phys_paddr_to_segind(pa);
391 	vmd = vm_phys_domain(m);
392 	vmd->vmd_page_count++;
393 	vmd->vmd_segs |= 1UL << m->segind;
394 	KASSERT(m->order == VM_NFREEORDER,
395 	    ("vm_phys_add_page: page %p has unexpected order %d",
396 	    m, m->order));
397 	m->pool = VM_FREEPOOL_DEFAULT;
398 	pmap_page_init(m);
399 	mtx_lock(&vm_page_queue_free_mtx);
400 	vm_phys_freecnt_adj(m, 1);
401 	vm_phys_free_pages(m, 0);
402 	mtx_unlock(&vm_page_queue_free_mtx);
403 }
404 
405 /*
406  * Allocate a contiguous, power of two-sized set of physical pages
407  * from the free lists.
408  *
409  * The free page queues must be locked.
410  */
411 vm_page_t
412 vm_phys_alloc_pages(int pool, int order)
413 {
414 	vm_page_t m;
415 	int dom, domain, flind;
416 
417 	KASSERT(pool < VM_NFREEPOOL,
418 	    ("vm_phys_alloc_pages: pool %d is out of range", pool));
419 	KASSERT(order < VM_NFREEORDER,
420 	    ("vm_phys_alloc_pages: order %d is out of range", order));
421 
422 	for (dom = 0; dom < vm_ndomains; dom++) {
423 		domain = vm_rr_selectdomain();
424 		for (flind = 0; flind < vm_nfreelists; flind++) {
425 			m = vm_phys_alloc_domain_pages(domain, flind, pool,
426 			    order);
427 			if (m != NULL)
428 				return (m);
429 		}
430 	}
431 	return (NULL);
432 }
433 
434 /*
435  * Find and dequeue a free page on the given free list, with the
436  * specified pool and order
437  */
438 vm_page_t
439 vm_phys_alloc_freelist_pages(int flind, int pool, int order)
440 {
441 	vm_page_t m;
442 	int dom, domain;
443 
444 	KASSERT(flind < VM_NFREELIST,
445 	    ("vm_phys_alloc_freelist_pages: freelist %d is out of range", flind));
446 	KASSERT(pool < VM_NFREEPOOL,
447 	    ("vm_phys_alloc_freelist_pages: pool %d is out of range", pool));
448 	KASSERT(order < VM_NFREEORDER,
449 	    ("vm_phys_alloc_freelist_pages: order %d is out of range", order));
450 
451 	for (dom = 0; dom < vm_ndomains; dom++) {
452 		domain = vm_rr_selectdomain();
453 		m = vm_phys_alloc_domain_pages(domain, flind, pool, order);
454 		if (m != NULL)
455 			return (m);
456 	}
457 	return (NULL);
458 }
459 
460 static vm_page_t
461 vm_phys_alloc_domain_pages(int domain, int flind, int pool, int order)
462 {
463 	struct vm_freelist *fl;
464 	struct vm_freelist *alt;
465 	int oind, pind;
466 	vm_page_t m;
467 
468 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
469 	fl = &vm_phys_free_queues[domain][flind][pool][0];
470 	for (oind = order; oind < VM_NFREEORDER; oind++) {
471 		m = TAILQ_FIRST(&fl[oind].pl);
472 		if (m != NULL) {
473 			vm_freelist_rem(fl, m, oind);
474 			vm_phys_split_pages(m, oind, fl, order);
475 			return (m);
476 		}
477 	}
478 
479 	/*
480 	 * The given pool was empty.  Find the largest
481 	 * contiguous, power-of-two-sized set of pages in any
482 	 * pool.  Transfer these pages to the given pool, and
483 	 * use them to satisfy the allocation.
484 	 */
485 	for (oind = VM_NFREEORDER - 1; oind >= order; oind--) {
486 		for (pind = 0; pind < VM_NFREEPOOL; pind++) {
487 			alt = &vm_phys_free_queues[domain][flind][pind][0];
488 			m = TAILQ_FIRST(&alt[oind].pl);
489 			if (m != NULL) {
490 				vm_freelist_rem(alt, m, oind);
491 				vm_phys_set_pool(pool, m, oind);
492 				vm_phys_split_pages(m, oind, fl, order);
493 				return (m);
494 			}
495 		}
496 	}
497 	return (NULL);
498 }
499 
500 /*
501  * Find the vm_page corresponding to the given physical address.
502  */
503 vm_page_t
504 vm_phys_paddr_to_vm_page(vm_paddr_t pa)
505 {
506 	struct vm_phys_seg *seg;
507 	int segind;
508 
509 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
510 		seg = &vm_phys_segs[segind];
511 		if (pa >= seg->start && pa < seg->end)
512 			return (&seg->first_page[atop(pa - seg->start)]);
513 	}
514 	return (NULL);
515 }
516 
517 vm_page_t
518 vm_phys_fictitious_to_vm_page(vm_paddr_t pa)
519 {
520 	struct vm_phys_fictitious_seg *seg;
521 	vm_page_t m;
522 	int segind;
523 
524 	m = NULL;
525 	for (segind = 0; segind < VM_PHYS_FICTITIOUS_NSEGS; segind++) {
526 		seg = &vm_phys_fictitious_segs[segind];
527 		if (pa >= seg->start && pa < seg->end) {
528 			m = &seg->first_page[atop(pa - seg->start)];
529 			KASSERT((m->flags & PG_FICTITIOUS) != 0,
530 			    ("%p not fictitious", m));
531 			break;
532 		}
533 	}
534 	return (m);
535 }
536 
537 int
538 vm_phys_fictitious_reg_range(vm_paddr_t start, vm_paddr_t end,
539     vm_memattr_t memattr)
540 {
541 	struct vm_phys_fictitious_seg *seg;
542 	vm_page_t fp;
543 	long i, page_count;
544 	int segind;
545 #ifdef VM_PHYSSEG_DENSE
546 	long pi;
547 	boolean_t malloced;
548 #endif
549 
550 	page_count = (end - start) / PAGE_SIZE;
551 
552 #ifdef VM_PHYSSEG_DENSE
553 	pi = atop(start);
554 	if (pi >= first_page && atop(end) < vm_page_array_size) {
555 		fp = &vm_page_array[pi - first_page];
556 		malloced = FALSE;
557 	} else
558 #endif
559 	{
560 		fp = malloc(page_count * sizeof(struct vm_page), M_FICT_PAGES,
561 		    M_WAITOK | M_ZERO);
562 #ifdef VM_PHYSSEG_DENSE
563 		malloced = TRUE;
564 #endif
565 	}
566 	for (i = 0; i < page_count; i++) {
567 		vm_page_initfake(&fp[i], start + PAGE_SIZE * i, memattr);
568 		fp[i].oflags &= ~VPO_UNMANAGED;
569 		fp[i].busy_lock = VPB_UNBUSIED;
570 	}
571 	mtx_lock(&vm_phys_fictitious_reg_mtx);
572 	for (segind = 0; segind < VM_PHYS_FICTITIOUS_NSEGS; segind++) {
573 		seg = &vm_phys_fictitious_segs[segind];
574 		if (seg->start == 0 && seg->end == 0) {
575 			seg->start = start;
576 			seg->end = end;
577 			seg->first_page = fp;
578 			mtx_unlock(&vm_phys_fictitious_reg_mtx);
579 			return (0);
580 		}
581 	}
582 	mtx_unlock(&vm_phys_fictitious_reg_mtx);
583 #ifdef VM_PHYSSEG_DENSE
584 	if (malloced)
585 #endif
586 		free(fp, M_FICT_PAGES);
587 	return (EBUSY);
588 }
589 
590 void
591 vm_phys_fictitious_unreg_range(vm_paddr_t start, vm_paddr_t end)
592 {
593 	struct vm_phys_fictitious_seg *seg;
594 	vm_page_t fp;
595 	int segind;
596 #ifdef VM_PHYSSEG_DENSE
597 	long pi;
598 #endif
599 
600 #ifdef VM_PHYSSEG_DENSE
601 	pi = atop(start);
602 #endif
603 
604 	mtx_lock(&vm_phys_fictitious_reg_mtx);
605 	for (segind = 0; segind < VM_PHYS_FICTITIOUS_NSEGS; segind++) {
606 		seg = &vm_phys_fictitious_segs[segind];
607 		if (seg->start == start && seg->end == end) {
608 			seg->start = seg->end = 0;
609 			fp = seg->first_page;
610 			seg->first_page = NULL;
611 			mtx_unlock(&vm_phys_fictitious_reg_mtx);
612 #ifdef VM_PHYSSEG_DENSE
613 			if (pi < first_page || atop(end) >= vm_page_array_size)
614 #endif
615 				free(fp, M_FICT_PAGES);
616 			return;
617 		}
618 	}
619 	mtx_unlock(&vm_phys_fictitious_reg_mtx);
620 	KASSERT(0, ("Unregistering not registered fictitious range"));
621 }
622 
623 /*
624  * Find the segment containing the given physical address.
625  */
626 static int
627 vm_phys_paddr_to_segind(vm_paddr_t pa)
628 {
629 	struct vm_phys_seg *seg;
630 	int segind;
631 
632 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
633 		seg = &vm_phys_segs[segind];
634 		if (pa >= seg->start && pa < seg->end)
635 			return (segind);
636 	}
637 	panic("vm_phys_paddr_to_segind: paddr %#jx is not in any segment" ,
638 	    (uintmax_t)pa);
639 }
640 
641 /*
642  * Free a contiguous, power of two-sized set of physical pages.
643  *
644  * The free page queues must be locked.
645  */
646 void
647 vm_phys_free_pages(vm_page_t m, int order)
648 {
649 	struct vm_freelist *fl;
650 	struct vm_phys_seg *seg;
651 	vm_paddr_t pa;
652 	vm_page_t m_buddy;
653 
654 	KASSERT(m->order == VM_NFREEORDER,
655 	    ("vm_phys_free_pages: page %p has unexpected order %d",
656 	    m, m->order));
657 	KASSERT(m->pool < VM_NFREEPOOL,
658 	    ("vm_phys_free_pages: page %p has unexpected pool %d",
659 	    m, m->pool));
660 	KASSERT(order < VM_NFREEORDER,
661 	    ("vm_phys_free_pages: order %d is out of range", order));
662 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
663 	seg = &vm_phys_segs[m->segind];
664 	if (order < VM_NFREEORDER - 1) {
665 		pa = VM_PAGE_TO_PHYS(m);
666 		do {
667 			pa ^= ((vm_paddr_t)1 << (PAGE_SHIFT + order));
668 			if (pa < seg->start || pa >= seg->end)
669 				break;
670 			m_buddy = &seg->first_page[atop(pa - seg->start)];
671 			if (m_buddy->order != order)
672 				break;
673 			fl = (*seg->free_queues)[m_buddy->pool];
674 			vm_freelist_rem(fl, m_buddy, order);
675 			if (m_buddy->pool != m->pool)
676 				vm_phys_set_pool(m->pool, m_buddy, order);
677 			order++;
678 			pa &= ~(((vm_paddr_t)1 << (PAGE_SHIFT + order)) - 1);
679 			m = &seg->first_page[atop(pa - seg->start)];
680 		} while (order < VM_NFREEORDER - 1);
681 	}
682 	fl = (*seg->free_queues)[m->pool];
683 	vm_freelist_add(fl, m, order, 1);
684 }
685 
686 /*
687  * Free a contiguous, arbitrarily sized set of physical pages.
688  *
689  * The free page queues must be locked.
690  */
691 void
692 vm_phys_free_contig(vm_page_t m, u_long npages)
693 {
694 	u_int n;
695 	int order;
696 
697 	/*
698 	 * Avoid unnecessary coalescing by freeing the pages in the largest
699 	 * possible power-of-two-sized subsets.
700 	 */
701 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
702 	for (;; npages -= n) {
703 		/*
704 		 * Unsigned "min" is used here so that "order" is assigned
705 		 * "VM_NFREEORDER - 1" when "m"'s physical address is zero
706 		 * or the low-order bits of its physical address are zero
707 		 * because the size of a physical address exceeds the size of
708 		 * a long.
709 		 */
710 		order = min(ffsl(VM_PAGE_TO_PHYS(m) >> PAGE_SHIFT) - 1,
711 		    VM_NFREEORDER - 1);
712 		n = 1 << order;
713 		if (npages < n)
714 			break;
715 		vm_phys_free_pages(m, order);
716 		m += n;
717 	}
718 	/* The residual "npages" is less than "1 << (VM_NFREEORDER - 1)". */
719 	for (; npages > 0; npages -= n) {
720 		order = flsl(npages) - 1;
721 		n = 1 << order;
722 		vm_phys_free_pages(m, order);
723 		m += n;
724 	}
725 }
726 
727 /*
728  * Set the pool for a contiguous, power of two-sized set of physical pages.
729  */
730 void
731 vm_phys_set_pool(int pool, vm_page_t m, int order)
732 {
733 	vm_page_t m_tmp;
734 
735 	for (m_tmp = m; m_tmp < &m[1 << order]; m_tmp++)
736 		m_tmp->pool = pool;
737 }
738 
739 /*
740  * Search for the given physical page "m" in the free lists.  If the search
741  * succeeds, remove "m" from the free lists and return TRUE.  Otherwise, return
742  * FALSE, indicating that "m" is not in the free lists.
743  *
744  * The free page queues must be locked.
745  */
746 boolean_t
747 vm_phys_unfree_page(vm_page_t m)
748 {
749 	struct vm_freelist *fl;
750 	struct vm_phys_seg *seg;
751 	vm_paddr_t pa, pa_half;
752 	vm_page_t m_set, m_tmp;
753 	int order;
754 
755 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
756 
757 	/*
758 	 * First, find the contiguous, power of two-sized set of free
759 	 * physical pages containing the given physical page "m" and
760 	 * assign it to "m_set".
761 	 */
762 	seg = &vm_phys_segs[m->segind];
763 	for (m_set = m, order = 0; m_set->order == VM_NFREEORDER &&
764 	    order < VM_NFREEORDER - 1; ) {
765 		order++;
766 		pa = m->phys_addr & (~(vm_paddr_t)0 << (PAGE_SHIFT + order));
767 		if (pa >= seg->start)
768 			m_set = &seg->first_page[atop(pa - seg->start)];
769 		else
770 			return (FALSE);
771 	}
772 	if (m_set->order < order)
773 		return (FALSE);
774 	if (m_set->order == VM_NFREEORDER)
775 		return (FALSE);
776 	KASSERT(m_set->order < VM_NFREEORDER,
777 	    ("vm_phys_unfree_page: page %p has unexpected order %d",
778 	    m_set, m_set->order));
779 
780 	/*
781 	 * Next, remove "m_set" from the free lists.  Finally, extract
782 	 * "m" from "m_set" using an iterative algorithm: While "m_set"
783 	 * is larger than a page, shrink "m_set" by returning the half
784 	 * of "m_set" that does not contain "m" to the free lists.
785 	 */
786 	fl = (*seg->free_queues)[m_set->pool];
787 	order = m_set->order;
788 	vm_freelist_rem(fl, m_set, order);
789 	while (order > 0) {
790 		order--;
791 		pa_half = m_set->phys_addr ^ (1 << (PAGE_SHIFT + order));
792 		if (m->phys_addr < pa_half)
793 			m_tmp = &seg->first_page[atop(pa_half - seg->start)];
794 		else {
795 			m_tmp = m_set;
796 			m_set = &seg->first_page[atop(pa_half - seg->start)];
797 		}
798 		vm_freelist_add(fl, m_tmp, order, 0);
799 	}
800 	KASSERT(m_set == m, ("vm_phys_unfree_page: fatal inconsistency"));
801 	return (TRUE);
802 }
803 
804 /*
805  * Try to zero one physical page.  Used by an idle priority thread.
806  */
807 boolean_t
808 vm_phys_zero_pages_idle(void)
809 {
810 	static struct vm_freelist *fl;
811 	static int flind, oind, pind;
812 	vm_page_t m, m_tmp;
813 	int domain;
814 
815 	domain = vm_rr_selectdomain();
816 	fl = vm_phys_free_queues[domain][0][0];
817 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
818 	for (;;) {
819 		TAILQ_FOREACH_REVERSE(m, &fl[oind].pl, pglist, plinks.q) {
820 			for (m_tmp = m; m_tmp < &m[1 << oind]; m_tmp++) {
821 				if ((m_tmp->flags & (PG_CACHED | PG_ZERO)) == 0) {
822 					vm_phys_unfree_page(m_tmp);
823 					vm_phys_freecnt_adj(m, -1);
824 					mtx_unlock(&vm_page_queue_free_mtx);
825 					pmap_zero_page_idle(m_tmp);
826 					m_tmp->flags |= PG_ZERO;
827 					mtx_lock(&vm_page_queue_free_mtx);
828 					vm_phys_freecnt_adj(m, 1);
829 					vm_phys_free_pages(m_tmp, 0);
830 					vm_page_zero_count++;
831 					cnt_prezero++;
832 					return (TRUE);
833 				}
834 			}
835 		}
836 		oind++;
837 		if (oind == VM_NFREEORDER) {
838 			oind = 0;
839 			pind++;
840 			if (pind == VM_NFREEPOOL) {
841 				pind = 0;
842 				flind++;
843 				if (flind == vm_nfreelists)
844 					flind = 0;
845 			}
846 			fl = vm_phys_free_queues[domain][flind][pind];
847 		}
848 	}
849 }
850 
851 /*
852  * Allocate a contiguous set of physical pages of the given size
853  * "npages" from the free lists.  All of the physical pages must be at
854  * or above the given physical address "low" and below the given
855  * physical address "high".  The given value "alignment" determines the
856  * alignment of the first physical page in the set.  If the given value
857  * "boundary" is non-zero, then the set of physical pages cannot cross
858  * any physical address boundary that is a multiple of that value.  Both
859  * "alignment" and "boundary" must be a power of two.
860  */
861 vm_page_t
862 vm_phys_alloc_contig(u_long npages, vm_paddr_t low, vm_paddr_t high,
863     u_long alignment, vm_paddr_t boundary)
864 {
865 	struct vm_freelist *fl;
866 	struct vm_phys_seg *seg;
867 	vm_paddr_t pa, pa_last, size;
868 	vm_page_t m, m_ret;
869 	u_long npages_end;
870 	int dom, domain, flind, oind, order, pind;
871 
872 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
873 	size = npages << PAGE_SHIFT;
874 	KASSERT(size != 0,
875 	    ("vm_phys_alloc_contig: size must not be 0"));
876 	KASSERT((alignment & (alignment - 1)) == 0,
877 	    ("vm_phys_alloc_contig: alignment must be a power of 2"));
878 	KASSERT((boundary & (boundary - 1)) == 0,
879 	    ("vm_phys_alloc_contig: boundary must be a power of 2"));
880 	/* Compute the queue that is the best fit for npages. */
881 	for (order = 0; (1 << order) < npages; order++);
882 	dom = 0;
883 restartdom:
884 	domain = vm_rr_selectdomain();
885 	for (flind = 0; flind < vm_nfreelists; flind++) {
886 		for (oind = min(order, VM_NFREEORDER - 1); oind < VM_NFREEORDER; oind++) {
887 			for (pind = 0; pind < VM_NFREEPOOL; pind++) {
888 				fl = &vm_phys_free_queues[domain][flind][pind][0];
889 				TAILQ_FOREACH(m_ret, &fl[oind].pl, plinks.q) {
890 					/*
891 					 * A free list may contain physical pages
892 					 * from one or more segments.
893 					 */
894 					seg = &vm_phys_segs[m_ret->segind];
895 					if (seg->start > high ||
896 					    low >= seg->end)
897 						continue;
898 
899 					/*
900 					 * Is the size of this allocation request
901 					 * larger than the largest block size?
902 					 */
903 					if (order >= VM_NFREEORDER) {
904 						/*
905 						 * Determine if a sufficient number
906 						 * of subsequent blocks to satisfy
907 						 * the allocation request are free.
908 						 */
909 						pa = VM_PAGE_TO_PHYS(m_ret);
910 						pa_last = pa + size;
911 						for (;;) {
912 							pa += 1 << (PAGE_SHIFT + VM_NFREEORDER - 1);
913 							if (pa >= pa_last)
914 								break;
915 							if (pa < seg->start ||
916 							    pa >= seg->end)
917 								break;
918 							m = &seg->first_page[atop(pa - seg->start)];
919 							if (m->order != VM_NFREEORDER - 1)
920 								break;
921 						}
922 						/* If not, continue to the next block. */
923 						if (pa < pa_last)
924 							continue;
925 					}
926 
927 					/*
928 					 * Determine if the blocks are within the given range,
929 					 * satisfy the given alignment, and do not cross the
930 					 * given boundary.
931 					 */
932 					pa = VM_PAGE_TO_PHYS(m_ret);
933 					if (pa >= low &&
934 					    pa + size <= high &&
935 					    (pa & (alignment - 1)) == 0 &&
936 					    ((pa ^ (pa + size - 1)) & ~(boundary - 1)) == 0)
937 						goto done;
938 				}
939 			}
940 		}
941 	}
942 	if (++dom < vm_ndomains)
943 		goto restartdom;
944 	return (NULL);
945 done:
946 	for (m = m_ret; m < &m_ret[npages]; m = &m[1 << oind]) {
947 		fl = (*seg->free_queues)[m->pool];
948 		vm_freelist_rem(fl, m, m->order);
949 	}
950 	if (m_ret->pool != VM_FREEPOOL_DEFAULT)
951 		vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m_ret, oind);
952 	fl = (*seg->free_queues)[m_ret->pool];
953 	vm_phys_split_pages(m_ret, oind, fl, order);
954 	/* Return excess pages to the free lists. */
955 	npages_end = roundup2(npages, 1 << imin(oind, order));
956 	if (npages < npages_end)
957 		vm_phys_free_contig(&m_ret[npages], npages_end - npages);
958 	return (m_ret);
959 }
960 
961 #ifdef DDB
962 /*
963  * Show the number of physical pages in each of the free lists.
964  */
965 DB_SHOW_COMMAND(freepages, db_show_freepages)
966 {
967 	struct vm_freelist *fl;
968 	int flind, oind, pind, dom;
969 
970 	for (dom = 0; dom < vm_ndomains; dom++) {
971 		db_printf("DOMAIN: %d\n", dom);
972 		for (flind = 0; flind < vm_nfreelists; flind++) {
973 			db_printf("FREE LIST %d:\n"
974 			    "\n  ORDER (SIZE)  |  NUMBER"
975 			    "\n              ", flind);
976 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
977 				db_printf("  |  POOL %d", pind);
978 			db_printf("\n--            ");
979 			for (pind = 0; pind < VM_NFREEPOOL; pind++)
980 				db_printf("-- --      ");
981 			db_printf("--\n");
982 			for (oind = VM_NFREEORDER - 1; oind >= 0; oind--) {
983 				db_printf("  %2.2d (%6.6dK)", oind,
984 				    1 << (PAGE_SHIFT - 10 + oind));
985 				for (pind = 0; pind < VM_NFREEPOOL; pind++) {
986 				fl = vm_phys_free_queues[dom][flind][pind];
987 					db_printf("  |  %6.6d", fl[oind].lcnt);
988 				}
989 				db_printf("\n");
990 			}
991 			db_printf("\n");
992 		}
993 		db_printf("\n");
994 	}
995 }
996 #endif
997