xref: /freebsd/sys/vm/vm_reserv.c (revision d06955f9bdb1416d9196043ed781f9b36dae9adc)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2006 Rice University
5  * Copyright (c) 2007-2011 Alan L. Cox <alc@cs.rice.edu>
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Alan L. Cox,
9  * Olivier Crameri, Peter Druschel, Sitaram Iyer, and Juan Navarro.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
24  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
30  * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  *	Superpage reservation management module
36  *
37  * Any external functions defined by this module are only to be used by the
38  * virtual memory system.
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_vm.h"
45 
46 #include <sys/param.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/mutex.h>
51 #include <sys/queue.h>
52 #include <sys/rwlock.h>
53 #include <sys/sbuf.h>
54 #include <sys/sysctl.h>
55 #include <sys/systm.h>
56 #include <sys/vmmeter.h>
57 
58 #include <vm/vm.h>
59 #include <vm/vm_param.h>
60 #include <vm/vm_object.h>
61 #include <vm/vm_page.h>
62 #include <vm/vm_phys.h>
63 #include <vm/vm_radix.h>
64 #include <vm/vm_reserv.h>
65 
66 /*
67  * The reservation system supports the speculative allocation of large physical
68  * pages ("superpages").  Speculative allocation enables the fully automatic
69  * utilization of superpages by the virtual memory system.  In other words, no
70  * programmatic directives are required to use superpages.
71  */
72 
73 #if VM_NRESERVLEVEL > 0
74 
75 /*
76  * The number of small pages that are contained in a level 0 reservation
77  */
78 #define	VM_LEVEL_0_NPAGES	(1 << VM_LEVEL_0_ORDER)
79 
80 /*
81  * The number of bits by which a physical address is shifted to obtain the
82  * reservation number
83  */
84 #define	VM_LEVEL_0_SHIFT	(VM_LEVEL_0_ORDER + PAGE_SHIFT)
85 
86 /*
87  * The size of a level 0 reservation in bytes
88  */
89 #define	VM_LEVEL_0_SIZE		(1 << VM_LEVEL_0_SHIFT)
90 
91 /*
92  * Computes the index of the small page underlying the given (object, pindex)
93  * within the reservation's array of small pages.
94  */
95 #define	VM_RESERV_INDEX(object, pindex)	\
96     (((object)->pg_color + (pindex)) & (VM_LEVEL_0_NPAGES - 1))
97 
98 /*
99  * The size of a population map entry
100  */
101 typedef	u_long		popmap_t;
102 
103 /*
104  * The number of bits in a population map entry
105  */
106 #define	NBPOPMAP	(NBBY * sizeof(popmap_t))
107 
108 /*
109  * The number of population map entries in a reservation
110  */
111 #define	NPOPMAP		howmany(VM_LEVEL_0_NPAGES, NBPOPMAP)
112 
113 /*
114  * Clear a bit in the population map.
115  */
116 static __inline void
117 popmap_clear(popmap_t popmap[], int i)
118 {
119 
120 	popmap[i / NBPOPMAP] &= ~(1UL << (i % NBPOPMAP));
121 }
122 
123 /*
124  * Set a bit in the population map.
125  */
126 static __inline void
127 popmap_set(popmap_t popmap[], int i)
128 {
129 
130 	popmap[i / NBPOPMAP] |= 1UL << (i % NBPOPMAP);
131 }
132 
133 /*
134  * Is a bit in the population map clear?
135  */
136 static __inline boolean_t
137 popmap_is_clear(popmap_t popmap[], int i)
138 {
139 
140 	return ((popmap[i / NBPOPMAP] & (1UL << (i % NBPOPMAP))) == 0);
141 }
142 
143 /*
144  * Is a bit in the population map set?
145  */
146 static __inline boolean_t
147 popmap_is_set(popmap_t popmap[], int i)
148 {
149 
150 	return ((popmap[i / NBPOPMAP] & (1UL << (i % NBPOPMAP))) != 0);
151 }
152 
153 /*
154  * The reservation structure
155  *
156  * A reservation structure is constructed whenever a large physical page is
157  * speculatively allocated to an object.  The reservation provides the small
158  * physical pages for the range [pindex, pindex + VM_LEVEL_0_NPAGES) of offsets
159  * within that object.  The reservation's "popcnt" tracks the number of these
160  * small physical pages that are in use at any given time.  When and if the
161  * reservation is not fully utilized, it appears in the queue of partially
162  * populated reservations.  The reservation always appears on the containing
163  * object's list of reservations.
164  *
165  * A partially populated reservation can be broken and reclaimed at any time.
166  */
167 struct vm_reserv {
168 	TAILQ_ENTRY(vm_reserv) partpopq;
169 	LIST_ENTRY(vm_reserv) objq;
170 	vm_object_t	object;			/* containing object */
171 	vm_pindex_t	pindex;			/* offset within object */
172 	vm_page_t	pages;			/* first page of a superpage */
173 	int		domain;			/* NUMA domain */
174 	int		popcnt;			/* # of pages in use */
175 	char		inpartpopq;
176 	popmap_t	popmap[NPOPMAP];	/* bit vector of used pages */
177 };
178 
179 /*
180  * The reservation array
181  *
182  * This array is analoguous in function to vm_page_array.  It differs in the
183  * respect that it may contain a greater number of useful reservation
184  * structures than there are (physical) superpages.  These "invalid"
185  * reservation structures exist to trade-off space for time in the
186  * implementation of vm_reserv_from_page().  Invalid reservation structures are
187  * distinguishable from "valid" reservation structures by inspecting the
188  * reservation's "pages" field.  Invalid reservation structures have a NULL
189  * "pages" field.
190  *
191  * vm_reserv_from_page() maps a small (physical) page to an element of this
192  * array by computing a physical reservation number from the page's physical
193  * address.  The physical reservation number is used as the array index.
194  *
195  * An "active" reservation is a valid reservation structure that has a non-NULL
196  * "object" field and a non-zero "popcnt" field.  In other words, every active
197  * reservation belongs to a particular object.  Moreover, every active
198  * reservation has an entry in the containing object's list of reservations.
199  */
200 static vm_reserv_t vm_reserv_array;
201 
202 /*
203  * The partially populated reservation queue
204  *
205  * This queue enables the fast recovery of an unused free small page from a
206  * partially populated reservation.  The reservation at the head of this queue
207  * is the least recently changed, partially populated reservation.
208  *
209  * Access to this queue is synchronized by the free page queue lock.
210  */
211 static TAILQ_HEAD(, vm_reserv) vm_rvq_partpop[MAXMEMDOM];
212 
213 static SYSCTL_NODE(_vm, OID_AUTO, reserv, CTLFLAG_RD, 0, "Reservation Info");
214 
215 static long vm_reserv_broken;
216 SYSCTL_LONG(_vm_reserv, OID_AUTO, broken, CTLFLAG_RD,
217     &vm_reserv_broken, 0, "Cumulative number of broken reservations");
218 
219 static long vm_reserv_freed;
220 SYSCTL_LONG(_vm_reserv, OID_AUTO, freed, CTLFLAG_RD,
221     &vm_reserv_freed, 0, "Cumulative number of freed reservations");
222 
223 static int sysctl_vm_reserv_fullpop(SYSCTL_HANDLER_ARGS);
224 
225 SYSCTL_PROC(_vm_reserv, OID_AUTO, fullpop, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
226     sysctl_vm_reserv_fullpop, "I", "Current number of full reservations");
227 
228 static int sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS);
229 
230 SYSCTL_OID(_vm_reserv, OID_AUTO, partpopq, CTLTYPE_STRING | CTLFLAG_RD, NULL, 0,
231     sysctl_vm_reserv_partpopq, "A", "Partially populated reservation queues");
232 
233 static long vm_reserv_reclaimed;
234 SYSCTL_LONG(_vm_reserv, OID_AUTO, reclaimed, CTLFLAG_RD,
235     &vm_reserv_reclaimed, 0, "Cumulative number of reclaimed reservations");
236 
237 static void		vm_reserv_break(vm_reserv_t rv, vm_page_t m);
238 static void		vm_reserv_depopulate(vm_reserv_t rv, int index);
239 static vm_reserv_t	vm_reserv_from_page(vm_page_t m);
240 static boolean_t	vm_reserv_has_pindex(vm_reserv_t rv,
241 			    vm_pindex_t pindex);
242 static void		vm_reserv_populate(vm_reserv_t rv, int index);
243 static void		vm_reserv_reclaim(vm_reserv_t rv);
244 
245 /*
246  * Returns the current number of full reservations.
247  *
248  * Since the number of full reservations is computed without acquiring the
249  * free page queue lock, the returned value may be inexact.
250  */
251 static int
252 sysctl_vm_reserv_fullpop(SYSCTL_HANDLER_ARGS)
253 {
254 	vm_paddr_t paddr;
255 	struct vm_phys_seg *seg;
256 	vm_reserv_t rv;
257 	int fullpop, segind;
258 
259 	fullpop = 0;
260 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
261 		seg = &vm_phys_segs[segind];
262 		paddr = roundup2(seg->start, VM_LEVEL_0_SIZE);
263 		while (paddr + VM_LEVEL_0_SIZE <= seg->end) {
264 			rv = &vm_reserv_array[paddr >> VM_LEVEL_0_SHIFT];
265 			fullpop += rv->popcnt == VM_LEVEL_0_NPAGES;
266 			paddr += VM_LEVEL_0_SIZE;
267 		}
268 	}
269 	return (sysctl_handle_int(oidp, &fullpop, 0, req));
270 }
271 
272 /*
273  * Describes the current state of the partially populated reservation queue.
274  */
275 static int
276 sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
277 {
278 	struct sbuf sbuf;
279 	vm_reserv_t rv;
280 	int counter, error, domain, level, unused_pages;
281 
282 	error = sysctl_wire_old_buffer(req, 0);
283 	if (error != 0)
284 		return (error);
285 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
286 	sbuf_printf(&sbuf, "\nDOMAIN    LEVEL     SIZE  NUMBER\n\n");
287 	for (domain = 0; domain < vm_ndomains; domain++) {
288 		for (level = -1; level <= VM_NRESERVLEVEL - 2; level++) {
289 			counter = 0;
290 			unused_pages = 0;
291 			mtx_lock(&vm_page_queue_free_mtx);
292 			TAILQ_FOREACH(rv, &vm_rvq_partpop[domain], partpopq) {
293 				counter++;
294 				unused_pages += VM_LEVEL_0_NPAGES - rv->popcnt;
295 			}
296 			mtx_unlock(&vm_page_queue_free_mtx);
297 			sbuf_printf(&sbuf, "%6d, %7d, %6dK, %6d\n",
298 			    domain, level,
299 			    unused_pages * ((int)PAGE_SIZE / 1024), counter);
300 		}
301 	}
302 	error = sbuf_finish(&sbuf);
303 	sbuf_delete(&sbuf);
304 	return (error);
305 }
306 
307 /*
308  * Reduces the given reservation's population count.  If the population count
309  * becomes zero, the reservation is destroyed.  Additionally, moves the
310  * reservation to the tail of the partially populated reservation queue if the
311  * population count is non-zero.
312  *
313  * The free page queue lock must be held.
314  */
315 static void
316 vm_reserv_depopulate(vm_reserv_t rv, int index)
317 {
318 
319 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
320 	KASSERT(rv->object != NULL,
321 	    ("vm_reserv_depopulate: reserv %p is free", rv));
322 	KASSERT(popmap_is_set(rv->popmap, index),
323 	    ("vm_reserv_depopulate: reserv %p's popmap[%d] is clear", rv,
324 	    index));
325 	KASSERT(rv->popcnt > 0,
326 	    ("vm_reserv_depopulate: reserv %p's popcnt is corrupted", rv));
327 	KASSERT(rv->domain >= 0 && rv->domain < vm_ndomains,
328 	    ("vm_reserv_depopulate: reserv %p's domain is corrupted %d",
329 	    rv, rv->domain));
330 	if (rv->inpartpopq) {
331 		TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
332 		rv->inpartpopq = FALSE;
333 	} else {
334 		KASSERT(rv->pages->psind == 1,
335 		    ("vm_reserv_depopulate: reserv %p is already demoted",
336 		    rv));
337 		rv->pages->psind = 0;
338 	}
339 	popmap_clear(rv->popmap, index);
340 	rv->popcnt--;
341 	if (rv->popcnt == 0) {
342 		LIST_REMOVE(rv, objq);
343 		rv->object = NULL;
344 		rv->domain = -1;
345 		vm_phys_free_pages(rv->pages, VM_LEVEL_0_ORDER);
346 		vm_reserv_freed++;
347 	} else {
348 		rv->inpartpopq = TRUE;
349 		TAILQ_INSERT_TAIL(&vm_rvq_partpop[rv->domain], rv, partpopq);
350 	}
351 }
352 
353 /*
354  * Returns the reservation to which the given page might belong.
355  */
356 static __inline vm_reserv_t
357 vm_reserv_from_page(vm_page_t m)
358 {
359 
360 	return (&vm_reserv_array[VM_PAGE_TO_PHYS(m) >> VM_LEVEL_0_SHIFT]);
361 }
362 
363 /*
364  * Returns TRUE if the given reservation contains the given page index and
365  * FALSE otherwise.
366  */
367 static __inline boolean_t
368 vm_reserv_has_pindex(vm_reserv_t rv, vm_pindex_t pindex)
369 {
370 
371 	return (((pindex - rv->pindex) & ~(VM_LEVEL_0_NPAGES - 1)) == 0);
372 }
373 
374 /*
375  * Increases the given reservation's population count.  Moves the reservation
376  * to the tail of the partially populated reservation queue.
377  *
378  * The free page queue must be locked.
379  */
380 static void
381 vm_reserv_populate(vm_reserv_t rv, int index)
382 {
383 
384 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
385 	KASSERT(rv->object != NULL,
386 	    ("vm_reserv_populate: reserv %p is free", rv));
387 	KASSERT(popmap_is_clear(rv->popmap, index),
388 	    ("vm_reserv_populate: reserv %p's popmap[%d] is set", rv,
389 	    index));
390 	KASSERT(rv->popcnt < VM_LEVEL_0_NPAGES,
391 	    ("vm_reserv_populate: reserv %p is already full", rv));
392 	KASSERT(rv->pages->psind == 0,
393 	    ("vm_reserv_populate: reserv %p is already promoted", rv));
394 	KASSERT(rv->domain >= 0 && rv->domain < vm_ndomains,
395 	    ("vm_reserv_populate: reserv %p's domain is corrupted %d",
396 	    rv, rv->domain));
397 	if (rv->inpartpopq) {
398 		TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
399 		rv->inpartpopq = FALSE;
400 	}
401 	popmap_set(rv->popmap, index);
402 	rv->popcnt++;
403 	if (rv->popcnt < VM_LEVEL_0_NPAGES) {
404 		rv->inpartpopq = TRUE;
405 		TAILQ_INSERT_TAIL(&vm_rvq_partpop[rv->domain], rv, partpopq);
406 	} else
407 		rv->pages->psind = 1;
408 }
409 
410 /*
411  * Allocates a contiguous set of physical pages of the given size "npages"
412  * from existing or newly created reservations.  All of the physical pages
413  * must be at or above the given physical address "low" and below the given
414  * physical address "high".  The given value "alignment" determines the
415  * alignment of the first physical page in the set.  If the given value
416  * "boundary" is non-zero, then the set of physical pages cannot cross any
417  * physical address boundary that is a multiple of that value.  Both
418  * "alignment" and "boundary" must be a power of two.
419  *
420  * The page "mpred" must immediately precede the offset "pindex" within the
421  * specified object.
422  *
423  * The object and free page queue must be locked.
424  */
425 vm_page_t
426 vm_reserv_alloc_contig(vm_object_t object, vm_pindex_t pindex, int domain,
427     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
428     vm_paddr_t boundary, vm_page_t mpred)
429 {
430 	vm_paddr_t pa, size;
431 	vm_page_t m, m_ret, msucc;
432 	vm_pindex_t first, leftcap, rightcap;
433 	vm_reserv_t rv;
434 	u_long allocpages, maxpages, minpages;
435 	int i, index, n;
436 
437 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
438 	VM_OBJECT_ASSERT_WLOCKED(object);
439 	KASSERT(npages != 0, ("vm_reserv_alloc_contig: npages is 0"));
440 
441 	/*
442 	 * Is a reservation fundamentally impossible?
443 	 */
444 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
445 	    pindex + npages > object->size)
446 		return (NULL);
447 
448 	/*
449 	 * All reservations of a particular size have the same alignment.
450 	 * Assuming that the first page is allocated from a reservation, the
451 	 * least significant bits of its physical address can be determined
452 	 * from its offset from the beginning of the reservation and the size
453 	 * of the reservation.
454 	 *
455 	 * Could the specified index within a reservation of the smallest
456 	 * possible size satisfy the alignment and boundary requirements?
457 	 */
458 	pa = VM_RESERV_INDEX(object, pindex) << PAGE_SHIFT;
459 	if ((pa & (alignment - 1)) != 0)
460 		return (NULL);
461 	size = npages << PAGE_SHIFT;
462 	if (((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
463 		return (NULL);
464 
465 	/*
466 	 * Look for an existing reservation.
467 	 */
468 	if (mpred != NULL) {
469 		KASSERT(mpred->object == object,
470 		    ("vm_reserv_alloc_contig: object doesn't contain mpred"));
471 		KASSERT(mpred->pindex < pindex,
472 		    ("vm_reserv_alloc_contig: mpred doesn't precede pindex"));
473 		rv = vm_reserv_from_page(mpred);
474 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
475 			goto found;
476 		msucc = TAILQ_NEXT(mpred, listq);
477 	} else
478 		msucc = TAILQ_FIRST(&object->memq);
479 	if (msucc != NULL) {
480 		KASSERT(msucc->pindex > pindex,
481 		    ("vm_reserv_alloc_contig: msucc doesn't succeed pindex"));
482 		rv = vm_reserv_from_page(msucc);
483 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
484 			goto found;
485 	}
486 
487 	/*
488 	 * Could at least one reservation fit between the first index to the
489 	 * left that can be used ("leftcap") and the first index to the right
490 	 * that cannot be used ("rightcap")?
491 	 */
492 	first = pindex - VM_RESERV_INDEX(object, pindex);
493 	if (mpred != NULL) {
494 		if ((rv = vm_reserv_from_page(mpred))->object != object)
495 			leftcap = mpred->pindex + 1;
496 		else
497 			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
498 		if (leftcap > first)
499 			return (NULL);
500 	}
501 	minpages = VM_RESERV_INDEX(object, pindex) + npages;
502 	maxpages = roundup2(minpages, VM_LEVEL_0_NPAGES);
503 	allocpages = maxpages;
504 	if (msucc != NULL) {
505 		if ((rv = vm_reserv_from_page(msucc))->object != object)
506 			rightcap = msucc->pindex;
507 		else
508 			rightcap = rv->pindex;
509 		if (first + maxpages > rightcap) {
510 			if (maxpages == VM_LEVEL_0_NPAGES)
511 				return (NULL);
512 
513 			/*
514 			 * At least one reservation will fit between "leftcap"
515 			 * and "rightcap".  However, a reservation for the
516 			 * last of the requested pages will not fit.  Reduce
517 			 * the size of the upcoming allocation accordingly.
518 			 */
519 			allocpages = minpages;
520 		}
521 	}
522 
523 	/*
524 	 * Would the last new reservation extend past the end of the object?
525 	 */
526 	if (first + maxpages > object->size) {
527 		/*
528 		 * Don't allocate the last new reservation if the object is a
529 		 * vnode or backed by another object that is a vnode.
530 		 */
531 		if (object->type == OBJT_VNODE ||
532 		    (object->backing_object != NULL &&
533 		    object->backing_object->type == OBJT_VNODE)) {
534 			if (maxpages == VM_LEVEL_0_NPAGES)
535 				return (NULL);
536 			allocpages = minpages;
537 		}
538 		/* Speculate that the object may grow. */
539 	}
540 
541 	/*
542 	 * Allocate the physical pages.  The alignment and boundary specified
543 	 * for this allocation may be different from the alignment and
544 	 * boundary specified for the requested pages.  For instance, the
545 	 * specified index may not be the first page within the first new
546 	 * reservation.
547 	 */
548 	m = vm_phys_alloc_contig(domain, allocpages, low, high, ulmax(alignment,
549 	    VM_LEVEL_0_SIZE), boundary > VM_LEVEL_0_SIZE ? boundary : 0);
550 	if (m == NULL)
551 		return (NULL);
552 
553 	/*
554 	 * The allocated physical pages always begin at a reservation
555 	 * boundary, but they do not always end at a reservation boundary.
556 	 * Initialize every reservation that is completely covered by the
557 	 * allocated physical pages.
558 	 */
559 	m_ret = NULL;
560 	index = VM_RESERV_INDEX(object, pindex);
561 	do {
562 		rv = vm_reserv_from_page(m);
563 		KASSERT(rv->pages == m,
564 		    ("vm_reserv_alloc_contig: reserv %p's pages is corrupted",
565 		    rv));
566 		KASSERT(rv->object == NULL,
567 		    ("vm_reserv_alloc_contig: reserv %p isn't free", rv));
568 		LIST_INSERT_HEAD(&object->rvq, rv, objq);
569 		rv->object = object;
570 		rv->pindex = first;
571 		rv->domain = vm_phys_domidx(m);
572 		KASSERT(rv->popcnt == 0,
573 		    ("vm_reserv_alloc_contig: reserv %p's popcnt is corrupted",
574 		    rv));
575 		KASSERT(!rv->inpartpopq,
576 		    ("vm_reserv_alloc_contig: reserv %p's inpartpopq is TRUE",
577 		    rv));
578 		for (i = 0; i < NPOPMAP; i++)
579 			KASSERT(rv->popmap[i] == 0,
580 		    ("vm_reserv_alloc_contig: reserv %p's popmap is corrupted",
581 			    rv));
582 		n = ulmin(VM_LEVEL_0_NPAGES - index, npages);
583 		for (i = 0; i < n; i++)
584 			vm_reserv_populate(rv, index + i);
585 		npages -= n;
586 		if (m_ret == NULL) {
587 			m_ret = &rv->pages[index];
588 			index = 0;
589 		}
590 		m += VM_LEVEL_0_NPAGES;
591 		first += VM_LEVEL_0_NPAGES;
592 		allocpages -= VM_LEVEL_0_NPAGES;
593 	} while (allocpages >= VM_LEVEL_0_NPAGES);
594 	return (m_ret);
595 
596 	/*
597 	 * Found a matching reservation.
598 	 */
599 found:
600 	index = VM_RESERV_INDEX(object, pindex);
601 	/* Does the allocation fit within the reservation? */
602 	if (index + npages > VM_LEVEL_0_NPAGES)
603 		return (NULL);
604 	m = &rv->pages[index];
605 	pa = VM_PAGE_TO_PHYS(m);
606 	if (pa < low || pa + size > high || (pa & (alignment - 1)) != 0 ||
607 	    ((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
608 		return (NULL);
609 	/* Handle vm_page_rename(m, new_object, ...). */
610 	for (i = 0; i < npages; i++)
611 		if (popmap_is_set(rv->popmap, index + i))
612 			return (NULL);
613 	for (i = 0; i < npages; i++)
614 		vm_reserv_populate(rv, index + i);
615 	return (m);
616 }
617 
618 /*
619  * Allocates a page from an existing or newly created reservation.
620  *
621  * The page "mpred" must immediately precede the offset "pindex" within the
622  * specified object.
623  *
624  * The object and free page queue must be locked.
625  */
626 vm_page_t
627 vm_reserv_alloc_page(vm_object_t object, vm_pindex_t pindex, int domain,
628     vm_page_t mpred)
629 {
630 	vm_page_t m, msucc;
631 	vm_pindex_t first, leftcap, rightcap;
632 	vm_reserv_t rv;
633 	int i, index;
634 
635 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
636 	VM_OBJECT_ASSERT_WLOCKED(object);
637 
638 	/*
639 	 * Is a reservation fundamentally impossible?
640 	 */
641 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
642 	    pindex >= object->size)
643 		return (NULL);
644 
645 	/*
646 	 * Look for an existing reservation.
647 	 */
648 	if (mpred != NULL) {
649 		KASSERT(mpred->object == object,
650 		    ("vm_reserv_alloc_page: object doesn't contain mpred"));
651 		KASSERT(mpred->pindex < pindex,
652 		    ("vm_reserv_alloc_page: mpred doesn't precede pindex"));
653 		rv = vm_reserv_from_page(mpred);
654 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
655 			goto found;
656 		msucc = TAILQ_NEXT(mpred, listq);
657 	} else
658 		msucc = TAILQ_FIRST(&object->memq);
659 	if (msucc != NULL) {
660 		KASSERT(msucc->pindex > pindex,
661 		    ("vm_reserv_alloc_page: msucc doesn't succeed pindex"));
662 		rv = vm_reserv_from_page(msucc);
663 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
664 			goto found;
665 	}
666 
667 	/*
668 	 * Could a reservation fit between the first index to the left that
669 	 * can be used and the first index to the right that cannot be used?
670 	 */
671 	first = pindex - VM_RESERV_INDEX(object, pindex);
672 	if (mpred != NULL) {
673 		if ((rv = vm_reserv_from_page(mpred))->object != object)
674 			leftcap = mpred->pindex + 1;
675 		else
676 			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
677 		if (leftcap > first)
678 			return (NULL);
679 	}
680 	if (msucc != NULL) {
681 		if ((rv = vm_reserv_from_page(msucc))->object != object)
682 			rightcap = msucc->pindex;
683 		else
684 			rightcap = rv->pindex;
685 		if (first + VM_LEVEL_0_NPAGES > rightcap)
686 			return (NULL);
687 	}
688 
689 	/*
690 	 * Would a new reservation extend past the end of the object?
691 	 */
692 	if (first + VM_LEVEL_0_NPAGES > object->size) {
693 		/*
694 		 * Don't allocate a new reservation if the object is a vnode or
695 		 * backed by another object that is a vnode.
696 		 */
697 		if (object->type == OBJT_VNODE ||
698 		    (object->backing_object != NULL &&
699 		    object->backing_object->type == OBJT_VNODE))
700 			return (NULL);
701 		/* Speculate that the object may grow. */
702 	}
703 
704 	/*
705 	 * Allocate and populate the new reservation.
706 	 */
707 	m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT, VM_LEVEL_0_ORDER);
708 	if (m == NULL)
709 		return (NULL);
710 	rv = vm_reserv_from_page(m);
711 	KASSERT(rv->pages == m,
712 	    ("vm_reserv_alloc_page: reserv %p's pages is corrupted", rv));
713 	KASSERT(rv->object == NULL,
714 	    ("vm_reserv_alloc_page: reserv %p isn't free", rv));
715 	LIST_INSERT_HEAD(&object->rvq, rv, objq);
716 	rv->object = object;
717 	rv->pindex = first;
718 	rv->domain = vm_phys_domidx(m);
719 	KASSERT(rv->popcnt == 0,
720 	    ("vm_reserv_alloc_page: reserv %p's popcnt is corrupted", rv));
721 	KASSERT(!rv->inpartpopq,
722 	    ("vm_reserv_alloc_page: reserv %p's inpartpopq is TRUE", rv));
723 	for (i = 0; i < NPOPMAP; i++)
724 		KASSERT(rv->popmap[i] == 0,
725 		    ("vm_reserv_alloc_page: reserv %p's popmap is corrupted",
726 		    rv));
727 	index = VM_RESERV_INDEX(object, pindex);
728 	vm_reserv_populate(rv, index);
729 	return (&rv->pages[index]);
730 
731 	/*
732 	 * Found a matching reservation.
733 	 */
734 found:
735 	index = VM_RESERV_INDEX(object, pindex);
736 	m = &rv->pages[index];
737 	/* Handle vm_page_rename(m, new_object, ...). */
738 	if (popmap_is_set(rv->popmap, index))
739 		return (NULL);
740 	vm_reserv_populate(rv, index);
741 	return (m);
742 }
743 
744 /*
745  * Breaks the given reservation.  Except for the specified free page, all free
746  * pages in the reservation are returned to the physical memory allocator.
747  * The reservation's population count and map are reset to their initial
748  * state.
749  *
750  * The given reservation must not be in the partially populated reservation
751  * queue.  The free page queue lock must be held.
752  */
753 static void
754 vm_reserv_break(vm_reserv_t rv, vm_page_t m)
755 {
756 	int begin_zeroes, hi, i, lo;
757 
758 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
759 	KASSERT(rv->object != NULL,
760 	    ("vm_reserv_break: reserv %p is free", rv));
761 	KASSERT(!rv->inpartpopq,
762 	    ("vm_reserv_break: reserv %p's inpartpopq is TRUE", rv));
763 	LIST_REMOVE(rv, objq);
764 	rv->object = NULL;
765 	rv->domain = -1;
766 	if (m != NULL) {
767 		/*
768 		 * Since the reservation is being broken, there is no harm in
769 		 * abusing the population map to stop "m" from being returned
770 		 * to the physical memory allocator.
771 		 */
772 		i = m - rv->pages;
773 		KASSERT(popmap_is_clear(rv->popmap, i),
774 		    ("vm_reserv_break: reserv %p's popmap is corrupted", rv));
775 		popmap_set(rv->popmap, i);
776 		rv->popcnt++;
777 	}
778 	i = hi = 0;
779 	do {
780 		/* Find the next 0 bit.  Any previous 0 bits are < "hi". */
781 		lo = ffsl(~(((1UL << hi) - 1) | rv->popmap[i]));
782 		if (lo == 0) {
783 			/* Redundantly clears bits < "hi". */
784 			rv->popmap[i] = 0;
785 			rv->popcnt -= NBPOPMAP - hi;
786 			while (++i < NPOPMAP) {
787 				lo = ffsl(~rv->popmap[i]);
788 				if (lo == 0) {
789 					rv->popmap[i] = 0;
790 					rv->popcnt -= NBPOPMAP;
791 				} else
792 					break;
793 			}
794 			if (i == NPOPMAP)
795 				break;
796 			hi = 0;
797 		}
798 		KASSERT(lo > 0, ("vm_reserv_break: lo is %d", lo));
799 		/* Convert from ffsl() to ordinary bit numbering. */
800 		lo--;
801 		if (lo > 0) {
802 			/* Redundantly clears bits < "hi". */
803 			rv->popmap[i] &= ~((1UL << lo) - 1);
804 			rv->popcnt -= lo - hi;
805 		}
806 		begin_zeroes = NBPOPMAP * i + lo;
807 		/* Find the next 1 bit. */
808 		do
809 			hi = ffsl(rv->popmap[i]);
810 		while (hi == 0 && ++i < NPOPMAP);
811 		if (i != NPOPMAP)
812 			/* Convert from ffsl() to ordinary bit numbering. */
813 			hi--;
814 		vm_phys_free_contig(&rv->pages[begin_zeroes], NBPOPMAP * i +
815 		    hi - begin_zeroes);
816 	} while (i < NPOPMAP);
817 	KASSERT(rv->popcnt == 0,
818 	    ("vm_reserv_break: reserv %p's popcnt is corrupted", rv));
819 	vm_reserv_broken++;
820 }
821 
822 /*
823  * Breaks all reservations belonging to the given object.
824  */
825 void
826 vm_reserv_break_all(vm_object_t object)
827 {
828 	vm_reserv_t rv;
829 
830 	mtx_lock(&vm_page_queue_free_mtx);
831 	while ((rv = LIST_FIRST(&object->rvq)) != NULL) {
832 		KASSERT(rv->object == object,
833 		    ("vm_reserv_break_all: reserv %p is corrupted", rv));
834 		if (rv->inpartpopq) {
835 			TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
836 			rv->inpartpopq = FALSE;
837 		}
838 		vm_reserv_break(rv, NULL);
839 	}
840 	mtx_unlock(&vm_page_queue_free_mtx);
841 }
842 
843 /*
844  * Frees the given page if it belongs to a reservation.  Returns TRUE if the
845  * page is freed and FALSE otherwise.
846  *
847  * The free page queue lock must be held.
848  */
849 boolean_t
850 vm_reserv_free_page(vm_page_t m)
851 {
852 	vm_reserv_t rv;
853 
854 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
855 	rv = vm_reserv_from_page(m);
856 	if (rv->object == NULL)
857 		return (FALSE);
858 	vm_reserv_depopulate(rv, m - rv->pages);
859 	return (TRUE);
860 }
861 
862 /*
863  * Initializes the reservation management system.  Specifically, initializes
864  * the reservation array.
865  *
866  * Requires that vm_page_array and first_page are initialized!
867  */
868 void
869 vm_reserv_init(void)
870 {
871 	vm_paddr_t paddr;
872 	struct vm_phys_seg *seg;
873 	int i, segind;
874 
875 	/*
876 	 * Initialize the reservation array.  Specifically, initialize the
877 	 * "pages" field for every element that has an underlying superpage.
878 	 */
879 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
880 		seg = &vm_phys_segs[segind];
881 		paddr = roundup2(seg->start, VM_LEVEL_0_SIZE);
882 		while (paddr + VM_LEVEL_0_SIZE <= seg->end) {
883 			vm_reserv_array[paddr >> VM_LEVEL_0_SHIFT].pages =
884 			    PHYS_TO_VM_PAGE(paddr);
885 			paddr += VM_LEVEL_0_SIZE;
886 		}
887 	}
888 	for (i = 0; i < MAXMEMDOM; i++)
889 		TAILQ_INIT(&vm_rvq_partpop[i]);
890 }
891 
892 /*
893  * Returns true if the given page belongs to a reservation and that page is
894  * free.  Otherwise, returns false.
895  */
896 bool
897 vm_reserv_is_page_free(vm_page_t m)
898 {
899 	vm_reserv_t rv;
900 
901 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
902 	rv = vm_reserv_from_page(m);
903 	if (rv->object == NULL)
904 		return (false);
905 	return (popmap_is_clear(rv->popmap, m - rv->pages));
906 }
907 
908 /*
909  * If the given page belongs to a reservation, returns the level of that
910  * reservation.  Otherwise, returns -1.
911  */
912 int
913 vm_reserv_level(vm_page_t m)
914 {
915 	vm_reserv_t rv;
916 
917 	rv = vm_reserv_from_page(m);
918 	return (rv->object != NULL ? 0 : -1);
919 }
920 
921 /*
922  * Returns a reservation level if the given page belongs to a fully populated
923  * reservation and -1 otherwise.
924  */
925 int
926 vm_reserv_level_iffullpop(vm_page_t m)
927 {
928 	vm_reserv_t rv;
929 
930 	rv = vm_reserv_from_page(m);
931 	return (rv->popcnt == VM_LEVEL_0_NPAGES ? 0 : -1);
932 }
933 
934 /*
935  * Breaks the given partially populated reservation, releasing its free pages
936  * to the physical memory allocator.
937  *
938  * The free page queue lock must be held.
939  */
940 static void
941 vm_reserv_reclaim(vm_reserv_t rv)
942 {
943 
944 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
945 	KASSERT(rv->inpartpopq,
946 	    ("vm_reserv_reclaim: reserv %p's inpartpopq is FALSE", rv));
947 	KASSERT(rv->domain >= 0 && rv->domain < vm_ndomains,
948 	    ("vm_reserv_reclaim: reserv %p's domain is corrupted %d",
949 	    rv, rv->domain));
950 	TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
951 	rv->inpartpopq = FALSE;
952 	vm_reserv_break(rv, NULL);
953 	vm_reserv_reclaimed++;
954 }
955 
956 /*
957  * Breaks the reservation at the head of the partially populated reservation
958  * queue, releasing its free pages to the physical memory allocator.  Returns
959  * TRUE if a reservation is broken and FALSE otherwise.
960  *
961  * The free page queue lock must be held.
962  */
963 boolean_t
964 vm_reserv_reclaim_inactive(int domain)
965 {
966 	vm_reserv_t rv;
967 
968 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
969 	if ((rv = TAILQ_FIRST(&vm_rvq_partpop[domain])) != NULL) {
970 		vm_reserv_reclaim(rv);
971 		return (TRUE);
972 	}
973 	return (FALSE);
974 }
975 
976 /*
977  * Searches the partially populated reservation queue for the least recently
978  * changed reservation with free pages that satisfy the given request for
979  * contiguous physical memory.  If a satisfactory reservation is found, it is
980  * broken.  Returns TRUE if a reservation is broken and FALSE otherwise.
981  *
982  * The free page queue lock must be held.
983  */
984 boolean_t
985 vm_reserv_reclaim_contig(int domain, u_long npages, vm_paddr_t low,
986     vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
987 {
988 	vm_paddr_t pa, size;
989 	vm_reserv_t rv;
990 	int hi, i, lo, low_index, next_free;
991 
992 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
993 	if (npages > VM_LEVEL_0_NPAGES - 1)
994 		return (FALSE);
995 	size = npages << PAGE_SHIFT;
996 	TAILQ_FOREACH(rv, &vm_rvq_partpop[domain], partpopq) {
997 		pa = VM_PAGE_TO_PHYS(&rv->pages[VM_LEVEL_0_NPAGES - 1]);
998 		if (pa + PAGE_SIZE - size < low) {
999 			/* This entire reservation is too low; go to next. */
1000 			continue;
1001 		}
1002 		pa = VM_PAGE_TO_PHYS(&rv->pages[0]);
1003 		if (pa + size > high) {
1004 			/* This entire reservation is too high; go to next. */
1005 			continue;
1006 		}
1007 		if (pa < low) {
1008 			/* Start the search for free pages at "low". */
1009 			low_index = (low + PAGE_MASK - pa) >> PAGE_SHIFT;
1010 			i = low_index / NBPOPMAP;
1011 			hi = low_index % NBPOPMAP;
1012 		} else
1013 			i = hi = 0;
1014 		do {
1015 			/* Find the next free page. */
1016 			lo = ffsl(~(((1UL << hi) - 1) | rv->popmap[i]));
1017 			while (lo == 0 && ++i < NPOPMAP)
1018 				lo = ffsl(~rv->popmap[i]);
1019 			if (i == NPOPMAP)
1020 				break;
1021 			/* Convert from ffsl() to ordinary bit numbering. */
1022 			lo--;
1023 			next_free = NBPOPMAP * i + lo;
1024 			pa = VM_PAGE_TO_PHYS(&rv->pages[next_free]);
1025 			KASSERT(pa >= low,
1026 			    ("vm_reserv_reclaim_contig: pa is too low"));
1027 			if (pa + size > high) {
1028 				/* The rest of this reservation is too high. */
1029 				break;
1030 			} else if ((pa & (alignment - 1)) != 0 ||
1031 			    ((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0) {
1032 				/*
1033 				 * The current page doesn't meet the alignment
1034 				 * and/or boundary requirements.  Continue
1035 				 * searching this reservation until the rest
1036 				 * of its free pages are either excluded or
1037 				 * exhausted.
1038 				 */
1039 				hi = lo + 1;
1040 				if (hi >= NBPOPMAP) {
1041 					hi = 0;
1042 					i++;
1043 				}
1044 				continue;
1045 			}
1046 			/* Find the next used page. */
1047 			hi = ffsl(rv->popmap[i] & ~((1UL << lo) - 1));
1048 			while (hi == 0 && ++i < NPOPMAP) {
1049 				if ((NBPOPMAP * i - next_free) * PAGE_SIZE >=
1050 				    size) {
1051 					vm_reserv_reclaim(rv);
1052 					return (TRUE);
1053 				}
1054 				hi = ffsl(rv->popmap[i]);
1055 			}
1056 			/* Convert from ffsl() to ordinary bit numbering. */
1057 			if (i != NPOPMAP)
1058 				hi--;
1059 			if ((NBPOPMAP * i + hi - next_free) * PAGE_SIZE >=
1060 			    size) {
1061 				vm_reserv_reclaim(rv);
1062 				return (TRUE);
1063 			}
1064 		} while (i < NPOPMAP);
1065 	}
1066 	return (FALSE);
1067 }
1068 
1069 /*
1070  * Transfers the reservation underlying the given page to a new object.
1071  *
1072  * The object must be locked.
1073  */
1074 void
1075 vm_reserv_rename(vm_page_t m, vm_object_t new_object, vm_object_t old_object,
1076     vm_pindex_t old_object_offset)
1077 {
1078 	vm_reserv_t rv;
1079 
1080 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1081 	rv = vm_reserv_from_page(m);
1082 	if (rv->object == old_object) {
1083 		mtx_lock(&vm_page_queue_free_mtx);
1084 		if (rv->object == old_object) {
1085 			LIST_REMOVE(rv, objq);
1086 			LIST_INSERT_HEAD(&new_object->rvq, rv, objq);
1087 			rv->object = new_object;
1088 			rv->pindex -= old_object_offset;
1089 		}
1090 		mtx_unlock(&vm_page_queue_free_mtx);
1091 	}
1092 }
1093 
1094 /*
1095  * Returns the size (in bytes) of a reservation of the specified level.
1096  */
1097 int
1098 vm_reserv_size(int level)
1099 {
1100 
1101 	switch (level) {
1102 	case 0:
1103 		return (VM_LEVEL_0_SIZE);
1104 	case -1:
1105 		return (PAGE_SIZE);
1106 	default:
1107 		return (0);
1108 	}
1109 }
1110 
1111 /*
1112  * Allocates the virtual and physical memory required by the reservation
1113  * management system's data structures, in particular, the reservation array.
1114  */
1115 vm_paddr_t
1116 vm_reserv_startup(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t high_water)
1117 {
1118 	vm_paddr_t new_end;
1119 	size_t size;
1120 
1121 	/*
1122 	 * Calculate the size (in bytes) of the reservation array.  Round up
1123 	 * from "high_water" because every small page is mapped to an element
1124 	 * in the reservation array based on its physical address.  Thus, the
1125 	 * number of elements in the reservation array can be greater than the
1126 	 * number of superpages.
1127 	 */
1128 	size = howmany(high_water, VM_LEVEL_0_SIZE) * sizeof(struct vm_reserv);
1129 
1130 	/*
1131 	 * Allocate and map the physical memory for the reservation array.  The
1132 	 * next available virtual address is returned by reference.
1133 	 */
1134 	new_end = end - round_page(size);
1135 	vm_reserv_array = (void *)(uintptr_t)pmap_map(vaddr, new_end, end,
1136 	    VM_PROT_READ | VM_PROT_WRITE);
1137 	bzero(vm_reserv_array, size);
1138 
1139 	/*
1140 	 * Return the next available physical address.
1141 	 */
1142 	return (new_end);
1143 }
1144 
1145 /*
1146  * Returns the superpage containing the given page.
1147  */
1148 vm_page_t
1149 vm_reserv_to_superpage(vm_page_t m)
1150 {
1151 	vm_reserv_t rv;
1152 
1153 	VM_OBJECT_ASSERT_LOCKED(m->object);
1154 	rv = vm_reserv_from_page(m);
1155 	return (rv->object == m->object && rv->popcnt == VM_LEVEL_0_NPAGES ?
1156 	    rv->pages : NULL);
1157 }
1158 
1159 #endif	/* VM_NRESERVLEVEL > 0 */
1160