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