xref: /freebsd/sys/vm/vm_reserv.c (revision f1f890804985a1043da42a5def13c79dc005f5e9)
1 /*-
2  * Copyright (c) 2002-2006 Rice University
3  * Copyright (c) 2007-2008 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  *	Superpage reservation management module
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_vm.h"
43 
44 #include <sys/param.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/mutex.h>
49 #include <sys/queue.h>
50 #include <sys/rwlock.h>
51 #include <sys/sbuf.h>
52 #include <sys/sysctl.h>
53 #include <sys/systm.h>
54 
55 #include <vm/vm.h>
56 #include <vm/vm_param.h>
57 #include <vm/vm_object.h>
58 #include <vm/vm_page.h>
59 #include <vm/vm_phys.h>
60 #include <vm/vm_reserv.h>
61 
62 /*
63  * The reservation system supports the speculative allocation of large physical
64  * pages ("superpages").  Speculative allocation enables the fully-automatic
65  * utilization of superpages by the virtual memory system.  In other words, no
66  * programmatic directives are required to use superpages.
67  */
68 
69 #if VM_NRESERVLEVEL > 0
70 
71 /*
72  * The number of small pages that are contained in a level 0 reservation
73  */
74 #define	VM_LEVEL_0_NPAGES	(1 << VM_LEVEL_0_ORDER)
75 
76 /*
77  * The number of bits by which a physical address is shifted to obtain the
78  * reservation number
79  */
80 #define	VM_LEVEL_0_SHIFT	(VM_LEVEL_0_ORDER + PAGE_SHIFT)
81 
82 /*
83  * The size of a level 0 reservation in bytes
84  */
85 #define	VM_LEVEL_0_SIZE		(1 << VM_LEVEL_0_SHIFT)
86 
87 /*
88  * Computes the index of the small page underlying the given (object, pindex)
89  * within the reservation's array of small pages.
90  */
91 #define	VM_RESERV_INDEX(object, pindex)	\
92     (((object)->pg_color + (pindex)) & (VM_LEVEL_0_NPAGES - 1))
93 
94 /*
95  * The reservation structure
96  *
97  * A reservation structure is constructed whenever a large physical page is
98  * speculatively allocated to an object.  The reservation provides the small
99  * physical pages for the range [pindex, pindex + VM_LEVEL_0_NPAGES) of offsets
100  * within that object.  The reservation's "popcnt" tracks the number of these
101  * small physical pages that are in use at any given time.  When and if the
102  * reservation is not fully utilized, it appears in the queue of partially-
103  * populated reservations.  The reservation always appears on the containing
104  * object's list of reservations.
105  *
106  * A partially-populated reservation can be broken and reclaimed at any time.
107  */
108 struct vm_reserv {
109 	TAILQ_ENTRY(vm_reserv) partpopq;
110 	LIST_ENTRY(vm_reserv) objq;
111 	vm_object_t	object;			/* containing object */
112 	vm_pindex_t	pindex;			/* offset within object */
113 	vm_page_t	pages;			/* first page of a superpage */
114 	int		popcnt;			/* # of pages in use */
115 	char		inpartpopq;
116 };
117 
118 /*
119  * The reservation array
120  *
121  * This array is analoguous in function to vm_page_array.  It differs in the
122  * respect that it may contain a greater number of useful reservation
123  * structures than there are (physical) superpages.  These "invalid"
124  * reservation structures exist to trade-off space for time in the
125  * implementation of vm_reserv_from_page().  Invalid reservation structures are
126  * distinguishable from "valid" reservation structures by inspecting the
127  * reservation's "pages" field.  Invalid reservation structures have a NULL
128  * "pages" field.
129  *
130  * vm_reserv_from_page() maps a small (physical) page to an element of this
131  * array by computing a physical reservation number from the page's physical
132  * address.  The physical reservation number is used as the array index.
133  *
134  * An "active" reservation is a valid reservation structure that has a non-NULL
135  * "object" field and a non-zero "popcnt" field.  In other words, every active
136  * reservation belongs to a particular object.  Moreover, every active
137  * reservation has an entry in the containing object's list of reservations.
138  */
139 static vm_reserv_t vm_reserv_array;
140 
141 /*
142  * The partially-populated reservation queue
143  *
144  * This queue enables the fast recovery of an unused cached or free small page
145  * from a partially-populated reservation.  The reservation at the head of
146  * this queue is the least-recently-changed, partially-populated reservation.
147  *
148  * Access to this queue is synchronized by the free page queue lock.
149  */
150 static TAILQ_HEAD(, vm_reserv) vm_rvq_partpop =
151 			    TAILQ_HEAD_INITIALIZER(vm_rvq_partpop);
152 
153 static SYSCTL_NODE(_vm, OID_AUTO, reserv, CTLFLAG_RD, 0, "Reservation Info");
154 
155 static long vm_reserv_broken;
156 SYSCTL_LONG(_vm_reserv, OID_AUTO, broken, CTLFLAG_RD,
157     &vm_reserv_broken, 0, "Cumulative number of broken reservations");
158 
159 static long vm_reserv_freed;
160 SYSCTL_LONG(_vm_reserv, OID_AUTO, freed, CTLFLAG_RD,
161     &vm_reserv_freed, 0, "Cumulative number of freed reservations");
162 
163 static int sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS);
164 
165 SYSCTL_OID(_vm_reserv, OID_AUTO, partpopq, CTLTYPE_STRING | CTLFLAG_RD, NULL, 0,
166     sysctl_vm_reserv_partpopq, "A", "Partially-populated reservation queues");
167 
168 static long vm_reserv_reclaimed;
169 SYSCTL_LONG(_vm_reserv, OID_AUTO, reclaimed, CTLFLAG_RD,
170     &vm_reserv_reclaimed, 0, "Cumulative number of reclaimed reservations");
171 
172 static void		vm_reserv_depopulate(vm_reserv_t rv);
173 static vm_reserv_t	vm_reserv_from_page(vm_page_t m);
174 static boolean_t	vm_reserv_has_pindex(vm_reserv_t rv,
175 			    vm_pindex_t pindex);
176 static void		vm_reserv_populate(vm_reserv_t rv);
177 static void		vm_reserv_reclaim(vm_reserv_t rv);
178 
179 /*
180  * Describes the current state of the partially-populated reservation queue.
181  */
182 static int
183 sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
184 {
185 	struct sbuf sbuf;
186 	vm_reserv_t rv;
187 	int counter, error, level, unused_pages;
188 
189 	error = sysctl_wire_old_buffer(req, 0);
190 	if (error != 0)
191 		return (error);
192 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
193 	sbuf_printf(&sbuf, "\nLEVEL     SIZE  NUMBER\n\n");
194 	for (level = -1; level <= VM_NRESERVLEVEL - 2; level++) {
195 		counter = 0;
196 		unused_pages = 0;
197 		mtx_lock(&vm_page_queue_free_mtx);
198 		TAILQ_FOREACH(rv, &vm_rvq_partpop/*[level]*/, partpopq) {
199 			counter++;
200 			unused_pages += VM_LEVEL_0_NPAGES - rv->popcnt;
201 		}
202 		mtx_unlock(&vm_page_queue_free_mtx);
203 		sbuf_printf(&sbuf, "%5d: %6dK, %6d\n", level,
204 		    unused_pages * ((int)PAGE_SIZE / 1024), counter);
205 	}
206 	error = sbuf_finish(&sbuf);
207 	sbuf_delete(&sbuf);
208 	return (error);
209 }
210 
211 /*
212  * Reduces the given reservation's population count.  If the population count
213  * becomes zero, the reservation is destroyed.  Additionally, moves the
214  * reservation to the tail of the partially-populated reservations queue if the
215  * population count is non-zero.
216  *
217  * The free page queue lock must be held.
218  */
219 static void
220 vm_reserv_depopulate(vm_reserv_t rv)
221 {
222 
223 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
224 	KASSERT(rv->object != NULL,
225 	    ("vm_reserv_depopulate: reserv %p is free", rv));
226 	KASSERT(rv->popcnt > 0,
227 	    ("vm_reserv_depopulate: reserv %p's popcnt is corrupted", rv));
228 	if (rv->inpartpopq) {
229 		TAILQ_REMOVE(&vm_rvq_partpop, rv, partpopq);
230 		rv->inpartpopq = FALSE;
231 	}
232 	rv->popcnt--;
233 	if (rv->popcnt == 0) {
234 		LIST_REMOVE(rv, objq);
235 		rv->object = NULL;
236 		vm_phys_free_pages(rv->pages, VM_LEVEL_0_ORDER);
237 		vm_reserv_freed++;
238 	} else {
239 		rv->inpartpopq = TRUE;
240 		TAILQ_INSERT_TAIL(&vm_rvq_partpop, rv, partpopq);
241 	}
242 }
243 
244 /*
245  * Returns the reservation to which the given page might belong.
246  */
247 static __inline vm_reserv_t
248 vm_reserv_from_page(vm_page_t m)
249 {
250 
251 	return (&vm_reserv_array[VM_PAGE_TO_PHYS(m) >> VM_LEVEL_0_SHIFT]);
252 }
253 
254 /*
255  * Returns TRUE if the given reservation contains the given page index and
256  * FALSE otherwise.
257  */
258 static __inline boolean_t
259 vm_reserv_has_pindex(vm_reserv_t rv, vm_pindex_t pindex)
260 {
261 
262 	return (((pindex - rv->pindex) & ~(VM_LEVEL_0_NPAGES - 1)) == 0);
263 }
264 
265 /*
266  * Increases the given reservation's population count.  Moves the reservation
267  * to the tail of the partially-populated reservation queue.
268  *
269  * The free page queue must be locked.
270  */
271 static void
272 vm_reserv_populate(vm_reserv_t rv)
273 {
274 
275 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
276 	KASSERT(rv->object != NULL,
277 	    ("vm_reserv_populate: reserv %p is free", rv));
278 	KASSERT(rv->popcnt < VM_LEVEL_0_NPAGES,
279 	    ("vm_reserv_populate: reserv %p is already full", rv));
280 	if (rv->inpartpopq) {
281 		TAILQ_REMOVE(&vm_rvq_partpop, rv, partpopq);
282 		rv->inpartpopq = FALSE;
283 	}
284 	rv->popcnt++;
285 	if (rv->popcnt < VM_LEVEL_0_NPAGES) {
286 		rv->inpartpopq = TRUE;
287 		TAILQ_INSERT_TAIL(&vm_rvq_partpop, rv, partpopq);
288 	}
289 }
290 
291 /*
292  * Allocates a contiguous set of physical pages of the given size "npages"
293  * from an existing or newly-created reservation.  All of the physical pages
294  * must be at or above the given physical address "low" and below the given
295  * physical address "high".  The given value "alignment" determines the
296  * alignment of the first physical page in the set.  If the given value
297  * "boundary" is non-zero, then the set of physical pages cannot cross any
298  * physical address boundary that is a multiple of that value.  Both
299  * "alignment" and "boundary" must be a power of two.
300  *
301  * The object and free page queue must be locked.
302  */
303 vm_page_t
304 vm_reserv_alloc_contig(vm_object_t object, vm_pindex_t pindex, u_long npages,
305     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
306 {
307 	vm_paddr_t pa, size;
308 	vm_page_t m, m_ret, mpred, msucc;
309 	vm_pindex_t first, leftcap, rightcap;
310 	vm_reserv_t rv;
311 	u_long allocpages, maxpages, minpages;
312 	int i, index, n;
313 
314 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
315 	VM_OBJECT_ASSERT_WLOCKED(object);
316 	KASSERT(npages != 0, ("vm_reserv_alloc_contig: npages is 0"));
317 
318 	/*
319 	 * Is a reservation fundamentally impossible?
320 	 */
321 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
322 	    pindex + npages > object->size)
323 		return (NULL);
324 
325 	/*
326 	 * All reservations of a particular size have the same alignment.
327 	 * Assuming that the first page is allocated from a reservation, the
328 	 * least significant bits of its physical address can be determined
329 	 * from its offset from the beginning of the reservation and the size
330 	 * of the reservation.
331 	 *
332 	 * Could the specified index within a reservation of the smallest
333 	 * possible size satisfy the alignment and boundary requirements?
334 	 */
335 	pa = VM_RESERV_INDEX(object, pindex) << PAGE_SHIFT;
336 	if ((pa & (alignment - 1)) != 0)
337 		return (NULL);
338 	size = npages << PAGE_SHIFT;
339 	if (((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
340 		return (NULL);
341 
342 	/*
343 	 * Look for an existing reservation.
344 	 */
345 	msucc = NULL;
346 	mpred = object->root;
347 	while (mpred != NULL) {
348 		KASSERT(mpred->pindex != pindex,
349 		    ("vm_reserv_alloc_contig: pindex already allocated"));
350 		rv = vm_reserv_from_page(mpred);
351 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
352 			goto found;
353 		else if (mpred->pindex < pindex) {
354 			if (msucc != NULL ||
355 			    (msucc = TAILQ_NEXT(mpred, listq)) == NULL)
356 				break;
357 			KASSERT(msucc->pindex != pindex,
358 		    ("vm_reserv_alloc_contig: pindex already allocated"));
359 			rv = vm_reserv_from_page(msucc);
360 			if (rv->object == object &&
361 			    vm_reserv_has_pindex(rv, pindex))
362 				goto found;
363 			else if (pindex < msucc->pindex)
364 				break;
365 		} else if (msucc == NULL) {
366 			msucc = mpred;
367 			mpred = TAILQ_PREV(msucc, pglist, listq);
368 			continue;
369 		}
370 		msucc = NULL;
371 		mpred = object->root = vm_page_splay(pindex, object->root);
372 	}
373 
374 	/*
375 	 * Could at least one reservation fit between the first index to the
376 	 * left that can be used and the first index to the right that cannot
377 	 * be used?
378 	 */
379 	first = pindex - VM_RESERV_INDEX(object, pindex);
380 	if (mpred != NULL) {
381 		if ((rv = vm_reserv_from_page(mpred))->object != object)
382 			leftcap = mpred->pindex + 1;
383 		else
384 			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
385 		if (leftcap > first)
386 			return (NULL);
387 	}
388 	minpages = VM_RESERV_INDEX(object, pindex) + npages;
389 	maxpages = roundup2(minpages, VM_LEVEL_0_NPAGES);
390 	allocpages = maxpages;
391 	if (msucc != NULL) {
392 		if ((rv = vm_reserv_from_page(msucc))->object != object)
393 			rightcap = msucc->pindex;
394 		else
395 			rightcap = rv->pindex;
396 		if (first + maxpages > rightcap) {
397 			if (maxpages == VM_LEVEL_0_NPAGES)
398 				return (NULL);
399 			allocpages = minpages;
400 		}
401 	}
402 
403 	/*
404 	 * Would the last new reservation extend past the end of the object?
405 	 */
406 	if (first + maxpages > object->size) {
407 		/*
408 		 * Don't allocate the last new reservation if the object is a
409 		 * vnode or backed by another object that is a vnode.
410 		 */
411 		if (object->type == OBJT_VNODE ||
412 		    (object->backing_object != NULL &&
413 		    object->backing_object->type == OBJT_VNODE)) {
414 			if (maxpages == VM_LEVEL_0_NPAGES)
415 				return (NULL);
416 			allocpages = minpages;
417 		}
418 		/* Speculate that the object may grow. */
419 	}
420 
421 	/*
422 	 * Allocate and populate the new reservations.  The alignment and
423 	 * boundary specified for this allocation may be different from the
424 	 * alignment and boundary specified for the requested pages.  For
425 	 * instance, the specified index may not be the first page within the
426 	 * first new reservation.
427 	 */
428 	m = vm_phys_alloc_contig(allocpages, low, high, ulmax(alignment,
429 	    VM_LEVEL_0_SIZE), boundary > VM_LEVEL_0_SIZE ? boundary : 0);
430 	if (m == NULL)
431 		return (NULL);
432 	m_ret = NULL;
433 	index = VM_RESERV_INDEX(object, pindex);
434 	do {
435 		rv = vm_reserv_from_page(m);
436 		KASSERT(rv->pages == m,
437 		    ("vm_reserv_alloc_contig: reserv %p's pages is corrupted",
438 		    rv));
439 		KASSERT(rv->object == NULL,
440 		    ("vm_reserv_alloc_contig: reserv %p isn't free", rv));
441 		LIST_INSERT_HEAD(&object->rvq, rv, objq);
442 		rv->object = object;
443 		rv->pindex = first;
444 		KASSERT(rv->popcnt == 0,
445 		    ("vm_reserv_alloc_contig: reserv %p's popcnt is corrupted",
446 		    rv));
447 		KASSERT(!rv->inpartpopq,
448 		    ("vm_reserv_alloc_contig: reserv %p's inpartpopq is TRUE",
449 		    rv));
450 		n = ulmin(VM_LEVEL_0_NPAGES - index, npages);
451 		for (i = 0; i < n; i++)
452 			vm_reserv_populate(rv);
453 		npages -= n;
454 		if (m_ret == NULL) {
455 			m_ret = &rv->pages[index];
456 			index = 0;
457 		}
458 		m += VM_LEVEL_0_NPAGES;
459 		first += VM_LEVEL_0_NPAGES;
460 		allocpages -= VM_LEVEL_0_NPAGES;
461 	} while (allocpages > 0);
462 	return (m_ret);
463 
464 	/*
465 	 * Found a matching reservation.
466 	 */
467 found:
468 	index = VM_RESERV_INDEX(object, pindex);
469 	/* Does the allocation fit within the reservation? */
470 	if (index + npages > VM_LEVEL_0_NPAGES)
471 		return (NULL);
472 	m = &rv->pages[index];
473 	pa = VM_PAGE_TO_PHYS(m);
474 	if (pa < low || pa + size > high || (pa & (alignment - 1)) != 0 ||
475 	    ((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
476 		return (NULL);
477 	/* Handle vm_page_rename(m, new_object, ...). */
478 	for (i = 0; i < npages; i++)
479 		if ((rv->pages[index + i].flags & (PG_CACHED | PG_FREE)) == 0)
480 			return (NULL);
481 	for (i = 0; i < npages; i++)
482 		vm_reserv_populate(rv);
483 	return (m);
484 }
485 
486 /*
487  * Allocates a page from an existing or newly-created reservation.
488  *
489  * The object and free page queue must be locked.
490  */
491 vm_page_t
492 vm_reserv_alloc_page(vm_object_t object, vm_pindex_t pindex)
493 {
494 	vm_page_t m, mpred, msucc;
495 	vm_pindex_t first, leftcap, rightcap;
496 	vm_reserv_t rv;
497 
498 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
499 	VM_OBJECT_ASSERT_WLOCKED(object);
500 
501 	/*
502 	 * Is a reservation fundamentally impossible?
503 	 */
504 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
505 	    pindex >= object->size)
506 		return (NULL);
507 
508 	/*
509 	 * Look for an existing reservation.
510 	 */
511 	msucc = NULL;
512 	mpred = object->root;
513 	while (mpred != NULL) {
514 		KASSERT(mpred->pindex != pindex,
515 		    ("vm_reserv_alloc_page: pindex already allocated"));
516 		rv = vm_reserv_from_page(mpred);
517 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
518 			goto found;
519 		else if (mpred->pindex < pindex) {
520 			if (msucc != NULL ||
521 			    (msucc = TAILQ_NEXT(mpred, listq)) == NULL)
522 				break;
523 			KASSERT(msucc->pindex != pindex,
524 			    ("vm_reserv_alloc_page: pindex already allocated"));
525 			rv = vm_reserv_from_page(msucc);
526 			if (rv->object == object &&
527 			    vm_reserv_has_pindex(rv, pindex))
528 				goto found;
529 			else if (pindex < msucc->pindex)
530 				break;
531 		} else if (msucc == NULL) {
532 			msucc = mpred;
533 			mpred = TAILQ_PREV(msucc, pglist, listq);
534 			continue;
535 		}
536 		msucc = NULL;
537 		mpred = object->root = vm_page_splay(pindex, object->root);
538 	}
539 
540 	/*
541 	 * Could a reservation fit between the first index to the left that
542 	 * can be used and the first index to the right that cannot be used?
543 	 */
544 	first = pindex - VM_RESERV_INDEX(object, pindex);
545 	if (mpred != NULL) {
546 		if ((rv = vm_reserv_from_page(mpred))->object != object)
547 			leftcap = mpred->pindex + 1;
548 		else
549 			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
550 		if (leftcap > first)
551 			return (NULL);
552 	}
553 	if (msucc != NULL) {
554 		if ((rv = vm_reserv_from_page(msucc))->object != object)
555 			rightcap = msucc->pindex;
556 		else
557 			rightcap = rv->pindex;
558 		if (first + VM_LEVEL_0_NPAGES > rightcap)
559 			return (NULL);
560 	}
561 
562 	/*
563 	 * Would a new reservation extend past the end of the object?
564 	 */
565 	if (first + VM_LEVEL_0_NPAGES > object->size) {
566 		/*
567 		 * Don't allocate a new reservation if the object is a vnode or
568 		 * backed by another object that is a vnode.
569 		 */
570 		if (object->type == OBJT_VNODE ||
571 		    (object->backing_object != NULL &&
572 		    object->backing_object->type == OBJT_VNODE))
573 			return (NULL);
574 		/* Speculate that the object may grow. */
575 	}
576 
577 	/*
578 	 * Allocate and populate the new reservation.
579 	 */
580 	m = vm_phys_alloc_pages(VM_FREEPOOL_DEFAULT, VM_LEVEL_0_ORDER);
581 	if (m == NULL)
582 		return (NULL);
583 	rv = vm_reserv_from_page(m);
584 	KASSERT(rv->pages == m,
585 	    ("vm_reserv_alloc_page: reserv %p's pages is corrupted", rv));
586 	KASSERT(rv->object == NULL,
587 	    ("vm_reserv_alloc_page: reserv %p isn't free", rv));
588 	LIST_INSERT_HEAD(&object->rvq, rv, objq);
589 	rv->object = object;
590 	rv->pindex = first;
591 	KASSERT(rv->popcnt == 0,
592 	    ("vm_reserv_alloc_page: reserv %p's popcnt is corrupted", rv));
593 	KASSERT(!rv->inpartpopq,
594 	    ("vm_reserv_alloc_page: reserv %p's inpartpopq is TRUE", rv));
595 	vm_reserv_populate(rv);
596 	return (&rv->pages[VM_RESERV_INDEX(object, pindex)]);
597 
598 	/*
599 	 * Found a matching reservation.
600 	 */
601 found:
602 	m = &rv->pages[VM_RESERV_INDEX(object, pindex)];
603 	/* Handle vm_page_rename(m, new_object, ...). */
604 	if ((m->flags & (PG_CACHED | PG_FREE)) == 0)
605 		return (NULL);
606 	vm_reserv_populate(rv);
607 	return (m);
608 }
609 
610 /*
611  * Breaks all reservations belonging to the given object.
612  */
613 void
614 vm_reserv_break_all(vm_object_t object)
615 {
616 	vm_reserv_t rv;
617 	int i;
618 
619 	mtx_lock(&vm_page_queue_free_mtx);
620 	while ((rv = LIST_FIRST(&object->rvq)) != NULL) {
621 		KASSERT(rv->object == object,
622 		    ("vm_reserv_break_all: reserv %p is corrupted", rv));
623 		if (rv->inpartpopq) {
624 			TAILQ_REMOVE(&vm_rvq_partpop, rv, partpopq);
625 			rv->inpartpopq = FALSE;
626 		}
627 		LIST_REMOVE(rv, objq);
628 		rv->object = NULL;
629 		for (i = 0; i < VM_LEVEL_0_NPAGES; i++) {
630 			if ((rv->pages[i].flags & (PG_CACHED | PG_FREE)) != 0)
631 				vm_phys_free_pages(&rv->pages[i], 0);
632 			else
633 				rv->popcnt--;
634 		}
635 		KASSERT(rv->popcnt == 0,
636 		    ("vm_reserv_break_all: reserv %p's popcnt is corrupted",
637 		    rv));
638 		vm_reserv_broken++;
639 	}
640 	mtx_unlock(&vm_page_queue_free_mtx);
641 }
642 
643 /*
644  * Frees the given page if it belongs to a reservation.  Returns TRUE if the
645  * page is freed and FALSE otherwise.
646  *
647  * The free page queue lock must be held.
648  */
649 boolean_t
650 vm_reserv_free_page(vm_page_t m)
651 {
652 	vm_reserv_t rv;
653 
654 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
655 	rv = vm_reserv_from_page(m);
656 	if (rv->object == NULL)
657 		return (FALSE);
658 	if ((m->flags & PG_CACHED) != 0 && m->pool != VM_FREEPOOL_CACHE)
659 		vm_phys_set_pool(VM_FREEPOOL_CACHE, rv->pages,
660 		    VM_LEVEL_0_ORDER);
661 	vm_reserv_depopulate(rv);
662 	return (TRUE);
663 }
664 
665 /*
666  * Initializes the reservation management system.  Specifically, initializes
667  * the reservation array.
668  *
669  * Requires that vm_page_array and first_page are initialized!
670  */
671 void
672 vm_reserv_init(void)
673 {
674 	vm_paddr_t paddr;
675 	int i;
676 
677 	/*
678 	 * Initialize the reservation array.  Specifically, initialize the
679 	 * "pages" field for every element that has an underlying superpage.
680 	 */
681 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
682 		paddr = roundup2(phys_avail[i], VM_LEVEL_0_SIZE);
683 		while (paddr + VM_LEVEL_0_SIZE <= phys_avail[i + 1]) {
684 			vm_reserv_array[paddr >> VM_LEVEL_0_SHIFT].pages =
685 			    PHYS_TO_VM_PAGE(paddr);
686 			paddr += VM_LEVEL_0_SIZE;
687 		}
688 	}
689 }
690 
691 /*
692  * Returns a reservation level if the given page belongs to a fully-populated
693  * reservation and -1 otherwise.
694  */
695 int
696 vm_reserv_level_iffullpop(vm_page_t m)
697 {
698 	vm_reserv_t rv;
699 
700 	rv = vm_reserv_from_page(m);
701 	return (rv->popcnt == VM_LEVEL_0_NPAGES ? 0 : -1);
702 }
703 
704 /*
705  * Prepare for the reactivation of a cached page.
706  *
707  * First, suppose that the given page "m" was allocated individually, i.e., not
708  * as part of a reservation, and cached.  Then, suppose a reservation
709  * containing "m" is allocated by the same object.  Although "m" and the
710  * reservation belong to the same object, "m"'s pindex may not match the
711  * reservation's.
712  *
713  * The free page queue must be locked.
714  */
715 boolean_t
716 vm_reserv_reactivate_page(vm_page_t m)
717 {
718 	vm_reserv_t rv;
719 	int i, m_index;
720 
721 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
722 	rv = vm_reserv_from_page(m);
723 	if (rv->object == NULL)
724 		return (FALSE);
725 	KASSERT((m->flags & PG_CACHED) != 0,
726 	    ("vm_reserv_uncache_page: page %p is not cached", m));
727 	if (m->object == rv->object &&
728 	    m->pindex - rv->pindex == VM_RESERV_INDEX(m->object, m->pindex))
729 		vm_reserv_populate(rv);
730 	else {
731 		KASSERT(rv->inpartpopq,
732 		    ("vm_reserv_uncache_page: reserv %p's inpartpopq is FALSE",
733 		    rv));
734 		TAILQ_REMOVE(&vm_rvq_partpop, rv, partpopq);
735 		rv->inpartpopq = FALSE;
736 		LIST_REMOVE(rv, objq);
737 		rv->object = NULL;
738 		/* Don't vm_phys_free_pages(m, 0). */
739 		m_index = m - rv->pages;
740 		for (i = 0; i < m_index; i++) {
741 			if ((rv->pages[i].flags & (PG_CACHED | PG_FREE)) != 0)
742 				vm_phys_free_pages(&rv->pages[i], 0);
743 			else
744 				rv->popcnt--;
745 		}
746 		for (i++; i < VM_LEVEL_0_NPAGES; i++) {
747 			if ((rv->pages[i].flags & (PG_CACHED | PG_FREE)) != 0)
748 				vm_phys_free_pages(&rv->pages[i], 0);
749 			else
750 				rv->popcnt--;
751 		}
752 		KASSERT(rv->popcnt == 0,
753 		    ("vm_reserv_uncache_page: reserv %p's popcnt is corrupted",
754 		    rv));
755 		vm_reserv_broken++;
756 	}
757 	return (TRUE);
758 }
759 
760 /*
761  * Breaks the given partially-populated reservation, releasing its cached and
762  * free pages to the physical memory allocator.
763  *
764  * The free page queue lock must be held.
765  */
766 static void
767 vm_reserv_reclaim(vm_reserv_t rv)
768 {
769 	int i;
770 
771 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
772 	KASSERT(rv->inpartpopq,
773 	    ("vm_reserv_reclaim: reserv %p's inpartpopq is corrupted", rv));
774 	TAILQ_REMOVE(&vm_rvq_partpop, rv, partpopq);
775 	rv->inpartpopq = FALSE;
776 	KASSERT(rv->object != NULL,
777 	    ("vm_reserv_reclaim: reserv %p is free", rv));
778 	LIST_REMOVE(rv, objq);
779 	rv->object = NULL;
780 	for (i = 0; i < VM_LEVEL_0_NPAGES; i++) {
781 		if ((rv->pages[i].flags & (PG_CACHED | PG_FREE)) != 0)
782 			vm_phys_free_pages(&rv->pages[i], 0);
783 		else
784 			rv->popcnt--;
785 	}
786 	KASSERT(rv->popcnt == 0,
787 	    ("vm_reserv_reclaim: reserv %p's popcnt is corrupted", rv));
788 	vm_reserv_reclaimed++;
789 }
790 
791 /*
792  * Breaks the reservation at the head of the partially-populated reservation
793  * queue, releasing its cached and free pages to the physical memory
794  * allocator.  Returns TRUE if a reservation is broken and FALSE otherwise.
795  *
796  * The free page queue lock must be held.
797  */
798 boolean_t
799 vm_reserv_reclaim_inactive(void)
800 {
801 	vm_reserv_t rv;
802 
803 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
804 	if ((rv = TAILQ_FIRST(&vm_rvq_partpop)) != NULL) {
805 		vm_reserv_reclaim(rv);
806 		return (TRUE);
807 	}
808 	return (FALSE);
809 }
810 
811 /*
812  * Searches the partially-populated reservation queue for the least recently
813  * active reservation with unused pages, i.e., cached or free, that satisfy the
814  * given request for contiguous physical memory.  If a satisfactory reservation
815  * is found, it is broken.  Returns TRUE if a reservation is broken and FALSE
816  * otherwise.
817  *
818  * The free page queue lock must be held.
819  */
820 boolean_t
821 vm_reserv_reclaim_contig(u_long npages, vm_paddr_t low, vm_paddr_t high,
822     u_long alignment, vm_paddr_t boundary)
823 {
824 	vm_paddr_t pa, pa_length, size;
825 	vm_reserv_t rv;
826 	int i;
827 
828 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
829 	if (npages > VM_LEVEL_0_NPAGES - 1)
830 		return (FALSE);
831 	size = npages << PAGE_SHIFT;
832 	TAILQ_FOREACH(rv, &vm_rvq_partpop, partpopq) {
833 		pa = VM_PAGE_TO_PHYS(&rv->pages[VM_LEVEL_0_NPAGES - 1]);
834 		if (pa + PAGE_SIZE - size < low) {
835 			/* this entire reservation is too low; go to next */
836 			continue;
837 		}
838 		pa_length = 0;
839 		for (i = 0; i < VM_LEVEL_0_NPAGES; i++)
840 			if ((rv->pages[i].flags & (PG_CACHED | PG_FREE)) != 0) {
841 				pa_length += PAGE_SIZE;
842 				if (pa_length == PAGE_SIZE) {
843 					pa = VM_PAGE_TO_PHYS(&rv->pages[i]);
844 					if (pa + size > high) {
845 						/* skip to next reservation */
846 						break;
847 					} else if (pa < low ||
848 					    (pa & (alignment - 1)) != 0 ||
849 					    ((pa ^ (pa + size - 1)) &
850 					    ~(boundary - 1)) != 0)
851 						pa_length = 0;
852 				}
853 				if (pa_length >= size) {
854 					vm_reserv_reclaim(rv);
855 					return (TRUE);
856 				}
857 			} else
858 				pa_length = 0;
859 	}
860 	return (FALSE);
861 }
862 
863 /*
864  * Transfers the reservation underlying the given page to a new object.
865  *
866  * The object must be locked.
867  */
868 void
869 vm_reserv_rename(vm_page_t m, vm_object_t new_object, vm_object_t old_object,
870     vm_pindex_t old_object_offset)
871 {
872 	vm_reserv_t rv;
873 
874 	VM_OBJECT_ASSERT_WLOCKED(new_object);
875 	rv = vm_reserv_from_page(m);
876 	if (rv->object == old_object) {
877 		mtx_lock(&vm_page_queue_free_mtx);
878 		if (rv->object == old_object) {
879 			LIST_REMOVE(rv, objq);
880 			LIST_INSERT_HEAD(&new_object->rvq, rv, objq);
881 			rv->object = new_object;
882 			rv->pindex -= old_object_offset;
883 		}
884 		mtx_unlock(&vm_page_queue_free_mtx);
885 	}
886 }
887 
888 /*
889  * Allocates the virtual and physical memory required by the reservation
890  * management system's data structures, in particular, the reservation array.
891  */
892 vm_paddr_t
893 vm_reserv_startup(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t high_water)
894 {
895 	vm_paddr_t new_end;
896 	size_t size;
897 
898 	/*
899 	 * Calculate the size (in bytes) of the reservation array.  Round up
900 	 * from "high_water" because every small page is mapped to an element
901 	 * in the reservation array based on its physical address.  Thus, the
902 	 * number of elements in the reservation array can be greater than the
903 	 * number of superpages.
904 	 */
905 	size = howmany(high_water, VM_LEVEL_0_SIZE) * sizeof(struct vm_reserv);
906 
907 	/*
908 	 * Allocate and map the physical memory for the reservation array.  The
909 	 * next available virtual address is returned by reference.
910 	 */
911 	new_end = end - round_page(size);
912 	vm_reserv_array = (void *)(uintptr_t)pmap_map(vaddr, new_end, end,
913 	    VM_PROT_READ | VM_PROT_WRITE);
914 	bzero(vm_reserv_array, size);
915 
916 	/*
917 	 * Return the next available physical address.
918 	 */
919 	return (new_end);
920 }
921 
922 #endif	/* VM_NRESERVLEVEL > 0 */
923