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