xref: /freebsd/sys/vm/vm_reserv.c (revision 74fe6c29fb7eef3418d7919dcd41dc1a04a982a1)
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_pageout.h>
63 #include <vm/vm_phys.h>
64 #include <vm/vm_pagequeue.h>
65 #include <vm/vm_radix.h>
66 #include <vm/vm_reserv.h>
67 
68 /*
69  * The reservation system supports the speculative allocation of large physical
70  * pages ("superpages").  Speculative allocation enables the fully automatic
71  * utilization of superpages by the virtual memory system.  In other words, no
72  * programmatic directives are required to use superpages.
73  */
74 
75 #if VM_NRESERVLEVEL > 0
76 
77 /*
78  * The number of small pages that are contained in a level 0 reservation
79  */
80 #define	VM_LEVEL_0_NPAGES	(1 << VM_LEVEL_0_ORDER)
81 
82 /*
83  * The number of bits by which a physical address is shifted to obtain the
84  * reservation number
85  */
86 #define	VM_LEVEL_0_SHIFT	(VM_LEVEL_0_ORDER + PAGE_SHIFT)
87 
88 /*
89  * The size of a level 0 reservation in bytes
90  */
91 #define	VM_LEVEL_0_SIZE		(1 << VM_LEVEL_0_SHIFT)
92 
93 /*
94  * Computes the index of the small page underlying the given (object, pindex)
95  * within the reservation's array of small pages.
96  */
97 #define	VM_RESERV_INDEX(object, pindex)	\
98     (((object)->pg_color + (pindex)) & (VM_LEVEL_0_NPAGES - 1))
99 
100 /*
101  * The size of a population map entry
102  */
103 typedef	u_long		popmap_t;
104 
105 /*
106  * The number of bits in a population map entry
107  */
108 #define	NBPOPMAP	(NBBY * sizeof(popmap_t))
109 
110 /*
111  * The number of population map entries in a reservation
112  */
113 #define	NPOPMAP		howmany(VM_LEVEL_0_NPAGES, NBPOPMAP)
114 
115 /*
116  * Clear a bit in the population map.
117  */
118 static __inline void
119 popmap_clear(popmap_t popmap[], int i)
120 {
121 
122 	popmap[i / NBPOPMAP] &= ~(1UL << (i % NBPOPMAP));
123 }
124 
125 /*
126  * Set a bit in the population map.
127  */
128 static __inline void
129 popmap_set(popmap_t popmap[], int i)
130 {
131 
132 	popmap[i / NBPOPMAP] |= 1UL << (i % NBPOPMAP);
133 }
134 
135 /*
136  * Is a bit in the population map clear?
137  */
138 static __inline boolean_t
139 popmap_is_clear(popmap_t popmap[], int i)
140 {
141 
142 	return ((popmap[i / NBPOPMAP] & (1UL << (i % NBPOPMAP))) == 0);
143 }
144 
145 /*
146  * Is a bit in the population map set?
147  */
148 static __inline boolean_t
149 popmap_is_set(popmap_t popmap[], int i)
150 {
151 
152 	return ((popmap[i / NBPOPMAP] & (1UL << (i % NBPOPMAP))) != 0);
153 }
154 
155 /*
156  * The reservation structure
157  *
158  * A reservation structure is constructed whenever a large physical page is
159  * speculatively allocated to an object.  The reservation provides the small
160  * physical pages for the range [pindex, pindex + VM_LEVEL_0_NPAGES) of offsets
161  * within that object.  The reservation's "popcnt" tracks the number of these
162  * small physical pages that are in use at any given time.  When and if the
163  * reservation is not fully utilized, it appears in the queue of partially
164  * populated reservations.  The reservation always appears on the containing
165  * object's list of reservations.
166  *
167  * A partially populated reservation can be broken and reclaimed at any time.
168  *
169  * f - vm_domain_free_lock
170  * o - vm_reserv_object_lock
171  * c - constant after boot
172  */
173 struct vm_reserv {
174 	TAILQ_ENTRY(vm_reserv) partpopq;	/* (f) per-domain queue. */
175 	LIST_ENTRY(vm_reserv) objq;		/* (o, f) object queue */
176 	vm_object_t	object;			/* (o, f) containing object */
177 	vm_pindex_t	pindex;			/* (o, f) offset in object */
178 	vm_page_t	pages;			/* (c) first page  */
179 	int		domain;			/* (c) NUMA domain. */
180 	int		popcnt;			/* (f) # of pages in use */
181 	char		inpartpopq;		/* (f) */
182 	popmap_t	popmap[NPOPMAP];	/* (f) bit vector, used pages */
183 };
184 
185 /*
186  * The reservation array
187  *
188  * This array is analoguous in function to vm_page_array.  It differs in the
189  * respect that it may contain a greater number of useful reservation
190  * structures than there are (physical) superpages.  These "invalid"
191  * reservation structures exist to trade-off space for time in the
192  * implementation of vm_reserv_from_page().  Invalid reservation structures are
193  * distinguishable from "valid" reservation structures by inspecting the
194  * reservation's "pages" field.  Invalid reservation structures have a NULL
195  * "pages" field.
196  *
197  * vm_reserv_from_page() maps a small (physical) page to an element of this
198  * array by computing a physical reservation number from the page's physical
199  * address.  The physical reservation number is used as the array index.
200  *
201  * An "active" reservation is a valid reservation structure that has a non-NULL
202  * "object" field and a non-zero "popcnt" field.  In other words, every active
203  * reservation belongs to a particular object.  Moreover, every active
204  * reservation has an entry in the containing object's list of reservations.
205  */
206 static vm_reserv_t vm_reserv_array;
207 
208 /*
209  * The partially populated reservation queue
210  *
211  * This queue enables the fast recovery of an unused free small page from a
212  * partially populated reservation.  The reservation at the head of this queue
213  * is the least recently changed, partially populated reservation.
214  *
215  * Access to this queue is synchronized by the free page queue lock.
216  */
217 static TAILQ_HEAD(, vm_reserv) vm_rvq_partpop[MAXMEMDOM];
218 
219 static SYSCTL_NODE(_vm, OID_AUTO, reserv, CTLFLAG_RD, 0, "Reservation Info");
220 
221 static long vm_reserv_broken;
222 SYSCTL_LONG(_vm_reserv, OID_AUTO, broken, CTLFLAG_RD,
223     &vm_reserv_broken, 0, "Cumulative number of broken reservations");
224 
225 static long vm_reserv_freed;
226 SYSCTL_LONG(_vm_reserv, OID_AUTO, freed, CTLFLAG_RD,
227     &vm_reserv_freed, 0, "Cumulative number of freed reservations");
228 
229 static int sysctl_vm_reserv_fullpop(SYSCTL_HANDLER_ARGS);
230 
231 SYSCTL_PROC(_vm_reserv, OID_AUTO, fullpop, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
232     sysctl_vm_reserv_fullpop, "I", "Current number of full reservations");
233 
234 static int sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS);
235 
236 SYSCTL_OID(_vm_reserv, OID_AUTO, partpopq, CTLTYPE_STRING | CTLFLAG_RD, NULL, 0,
237     sysctl_vm_reserv_partpopq, "A", "Partially populated reservation queues");
238 
239 static long vm_reserv_reclaimed;
240 SYSCTL_LONG(_vm_reserv, OID_AUTO, reclaimed, CTLFLAG_RD,
241     &vm_reserv_reclaimed, 0, "Cumulative number of reclaimed reservations");
242 
243 /*
244  * The object lock pool is used to synchronize the rvq.  We can not use a
245  * pool mutex because it is required before malloc works.
246  *
247  * The "hash" function could be made faster without divide and modulo.
248  */
249 #define	VM_RESERV_OBJ_LOCK_COUNT	MAXCPU
250 
251 struct mtx_padalign vm_reserv_object_mtx[VM_RESERV_OBJ_LOCK_COUNT];
252 
253 #define	vm_reserv_object_lock_idx(object)			\
254 	    (((uintptr_t)object / sizeof(*object)) % VM_RESERV_OBJ_LOCK_COUNT)
255 #define	vm_reserv_object_lock_ptr(object)			\
256 	    &vm_reserv_object_mtx[vm_reserv_object_lock_idx((object))]
257 #define	vm_reserv_object_lock(object)				\
258 	    mtx_lock(vm_reserv_object_lock_ptr((object)))
259 #define	vm_reserv_object_unlock(object)				\
260 	    mtx_unlock(vm_reserv_object_lock_ptr((object)))
261 
262 static void		vm_reserv_break(vm_reserv_t rv);
263 static void		vm_reserv_depopulate(vm_reserv_t rv, int index);
264 static vm_reserv_t	vm_reserv_from_page(vm_page_t m);
265 static boolean_t	vm_reserv_has_pindex(vm_reserv_t rv,
266 			    vm_pindex_t pindex);
267 static void		vm_reserv_populate(vm_reserv_t rv, int index);
268 static void		vm_reserv_reclaim(vm_reserv_t rv);
269 
270 /*
271  * Returns the current number of full reservations.
272  *
273  * Since the number of full reservations is computed without acquiring the
274  * free page queue lock, the returned value may be inexact.
275  */
276 static int
277 sysctl_vm_reserv_fullpop(SYSCTL_HANDLER_ARGS)
278 {
279 	vm_paddr_t paddr;
280 	struct vm_phys_seg *seg;
281 	vm_reserv_t rv;
282 	int fullpop, segind;
283 
284 	fullpop = 0;
285 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
286 		seg = &vm_phys_segs[segind];
287 		paddr = roundup2(seg->start, VM_LEVEL_0_SIZE);
288 		while (paddr + VM_LEVEL_0_SIZE <= seg->end) {
289 			rv = &vm_reserv_array[paddr >> VM_LEVEL_0_SHIFT];
290 			fullpop += rv->popcnt == VM_LEVEL_0_NPAGES;
291 			paddr += VM_LEVEL_0_SIZE;
292 		}
293 	}
294 	return (sysctl_handle_int(oidp, &fullpop, 0, req));
295 }
296 
297 /*
298  * Describes the current state of the partially populated reservation queue.
299  */
300 static int
301 sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
302 {
303 	struct sbuf sbuf;
304 	vm_reserv_t rv;
305 	int counter, error, domain, level, unused_pages;
306 
307 	error = sysctl_wire_old_buffer(req, 0);
308 	if (error != 0)
309 		return (error);
310 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
311 	sbuf_printf(&sbuf, "\nDOMAIN    LEVEL     SIZE  NUMBER\n\n");
312 	for (domain = 0; domain < vm_ndomains; domain++) {
313 		for (level = -1; level <= VM_NRESERVLEVEL - 2; level++) {
314 			counter = 0;
315 			unused_pages = 0;
316 			vm_domain_free_lock(VM_DOMAIN(domain));
317 			TAILQ_FOREACH(rv, &vm_rvq_partpop[domain], partpopq) {
318 				counter++;
319 				unused_pages += VM_LEVEL_0_NPAGES - rv->popcnt;
320 			}
321 			vm_domain_free_unlock(VM_DOMAIN(domain));
322 			sbuf_printf(&sbuf, "%6d, %7d, %6dK, %6d\n",
323 			    domain, level,
324 			    unused_pages * ((int)PAGE_SIZE / 1024), counter);
325 		}
326 	}
327 	error = sbuf_finish(&sbuf);
328 	sbuf_delete(&sbuf);
329 	return (error);
330 }
331 
332 /*
333  * Remove a reservation from the object's objq.
334  */
335 static void
336 vm_reserv_remove(vm_reserv_t rv)
337 {
338 	vm_object_t object;
339 
340 	KASSERT(rv->object != NULL,
341 	    ("vm_reserv_remove: reserv %p is free", rv));
342 	KASSERT(!rv->inpartpopq,
343 	    ("vm_reserv_remove: reserv %p's inpartpopq is TRUE", rv));
344 	object = rv->object;
345 	vm_reserv_object_lock(object);
346 	LIST_REMOVE(rv, objq);
347 	rv->object = NULL;
348 	vm_reserv_object_unlock(object);
349 }
350 
351 /*
352  * Insert a new reservation into the object's objq.
353  */
354 static void
355 vm_reserv_insert(vm_reserv_t rv, vm_object_t object, vm_pindex_t pindex)
356 {
357 	int i;
358 
359 	KASSERT(rv->object == NULL,
360 	    ("vm_reserv_insert: reserv %p isn't free", rv));
361 	KASSERT(rv->popcnt == 0,
362 	    ("vm_reserv_insert: reserv %p's popcnt is corrupted", rv));
363 	KASSERT(!rv->inpartpopq,
364 	    ("vm_reserv_insert: reserv %p's inpartpopq is TRUE", rv));
365 	for (i = 0; i < NPOPMAP; i++)
366 		KASSERT(rv->popmap[i] == 0,
367 		    ("vm_reserv_insert: reserv %p's popmap is corrupted", rv));
368 	vm_reserv_object_lock(object);
369 	rv->pindex = pindex;
370 	rv->object = object;
371 	LIST_INSERT_HEAD(&object->rvq, rv, objq);
372 	vm_reserv_object_unlock(object);
373 }
374 
375 /*
376  * Reduces the given reservation's population count.  If the population count
377  * becomes zero, the reservation is destroyed.  Additionally, moves the
378  * reservation to the tail of the partially populated reservation queue if the
379  * population count is non-zero.
380  *
381  * The free page queue lock must be held.
382  */
383 static void
384 vm_reserv_depopulate(vm_reserv_t rv, int index)
385 {
386 
387 	vm_domain_free_assert_locked(VM_DOMAIN(rv->domain));
388 	KASSERT(rv->object != NULL,
389 	    ("vm_reserv_depopulate: reserv %p is free", rv));
390 	KASSERT(popmap_is_set(rv->popmap, index),
391 	    ("vm_reserv_depopulate: reserv %p's popmap[%d] is clear", rv,
392 	    index));
393 	KASSERT(rv->popcnt > 0,
394 	    ("vm_reserv_depopulate: reserv %p's popcnt is corrupted", rv));
395 	KASSERT(rv->domain >= 0 && rv->domain < vm_ndomains,
396 	    ("vm_reserv_depopulate: reserv %p's domain is corrupted %d",
397 	    rv, rv->domain));
398 	if (rv->inpartpopq) {
399 		TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
400 		rv->inpartpopq = FALSE;
401 	} else {
402 		KASSERT(rv->pages->psind == 1,
403 		    ("vm_reserv_depopulate: reserv %p is already demoted",
404 		    rv));
405 		rv->pages->psind = 0;
406 	}
407 	popmap_clear(rv->popmap, index);
408 	rv->popcnt--;
409 	if (rv->popcnt == 0) {
410 		vm_reserv_remove(rv);
411 		vm_phys_free_pages(rv->pages, VM_LEVEL_0_ORDER);
412 		vm_reserv_freed++;
413 	} else {
414 		rv->inpartpopq = TRUE;
415 		TAILQ_INSERT_TAIL(&vm_rvq_partpop[rv->domain], rv, partpopq);
416 	}
417 }
418 
419 /*
420  * Returns the reservation to which the given page might belong.
421  */
422 static __inline vm_reserv_t
423 vm_reserv_from_page(vm_page_t m)
424 {
425 
426 	return (&vm_reserv_array[VM_PAGE_TO_PHYS(m) >> VM_LEVEL_0_SHIFT]);
427 }
428 
429 /*
430  * Returns an existing reservation or NULL and initialized successor pointer.
431  */
432 static vm_reserv_t
433 vm_reserv_from_object(vm_object_t object, vm_pindex_t pindex,
434     vm_page_t mpred, vm_page_t *msuccp)
435 {
436 	vm_reserv_t rv;
437 	vm_page_t msucc;
438 
439 	msucc = NULL;
440 	if (mpred != NULL) {
441 		KASSERT(mpred->object == object,
442 		    ("vm_reserv_from_object: object doesn't contain mpred"));
443 		KASSERT(mpred->pindex < pindex,
444 		    ("vm_reserv_from_object: mpred doesn't precede pindex"));
445 		rv = vm_reserv_from_page(mpred);
446 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
447 			goto found;
448 		msucc = TAILQ_NEXT(mpred, listq);
449 	} else
450 		msucc = TAILQ_FIRST(&object->memq);
451 	if (msucc != NULL) {
452 		KASSERT(msucc->pindex > pindex,
453 		    ("vm_reserv_from_object: msucc doesn't succeed pindex"));
454 		rv = vm_reserv_from_page(msucc);
455 		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
456 			goto found;
457 	}
458 	rv = NULL;
459 
460 found:
461 	*msuccp = msucc;
462 
463 	return (rv);
464 }
465 
466 /*
467  * Returns TRUE if the given reservation contains the given page index and
468  * FALSE otherwise.
469  */
470 static __inline boolean_t
471 vm_reserv_has_pindex(vm_reserv_t rv, vm_pindex_t pindex)
472 {
473 
474 	return (((pindex - rv->pindex) & ~(VM_LEVEL_0_NPAGES - 1)) == 0);
475 }
476 
477 /*
478  * Increases the given reservation's population count.  Moves the reservation
479  * to the tail of the partially populated reservation queue.
480  *
481  * The free page queue must be locked.
482  */
483 static void
484 vm_reserv_populate(vm_reserv_t rv, int index)
485 {
486 
487 	vm_domain_free_assert_locked(VM_DOMAIN(rv->domain));
488 	KASSERT(rv->object != NULL,
489 	    ("vm_reserv_populate: reserv %p is free", rv));
490 	KASSERT(popmap_is_clear(rv->popmap, index),
491 	    ("vm_reserv_populate: reserv %p's popmap[%d] is set", rv,
492 	    index));
493 	KASSERT(rv->popcnt < VM_LEVEL_0_NPAGES,
494 	    ("vm_reserv_populate: reserv %p is already full", rv));
495 	KASSERT(rv->pages->psind == 0,
496 	    ("vm_reserv_populate: reserv %p is already promoted", rv));
497 	KASSERT(rv->domain >= 0 && rv->domain < vm_ndomains,
498 	    ("vm_reserv_populate: reserv %p's domain is corrupted %d",
499 	    rv, rv->domain));
500 	if (rv->inpartpopq) {
501 		TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
502 		rv->inpartpopq = FALSE;
503 	}
504 	popmap_set(rv->popmap, index);
505 	rv->popcnt++;
506 	if (rv->popcnt < VM_LEVEL_0_NPAGES) {
507 		rv->inpartpopq = TRUE;
508 		TAILQ_INSERT_TAIL(&vm_rvq_partpop[rv->domain], rv, partpopq);
509 	} else
510 		rv->pages->psind = 1;
511 }
512 
513 /*
514  * Attempts to allocate a contiguous set of physical pages from existing
515  * reservations.  See vm_reserv_alloc_contig() for a description of the
516  * function's parameters.
517  *
518  * The page "mpred" must immediately precede the offset "pindex" within the
519  * specified object.
520  *
521  * The object must be locked.
522  */
523 vm_page_t
524 vm_reserv_extend_contig(int req, vm_object_t object, vm_pindex_t pindex,
525     int domain, u_long npages, vm_paddr_t low, vm_paddr_t high,
526     u_long alignment, vm_paddr_t boundary, vm_page_t mpred)
527 {
528 	struct vm_domain *vmd;
529 	vm_paddr_t pa, size;
530 	vm_page_t m, msucc;
531 	vm_reserv_t rv;
532 	int i, index;
533 
534 	VM_OBJECT_ASSERT_WLOCKED(object);
535 	KASSERT(npages != 0, ("vm_reserv_alloc_contig: npages is 0"));
536 
537 	/*
538 	 * Is a reservation fundamentally impossible?
539 	 */
540 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
541 	    pindex + npages > object->size || object->resident_page_count == 0)
542 		return (NULL);
543 
544 	/*
545 	 * All reservations of a particular size have the same alignment.
546 	 * Assuming that the first page is allocated from a reservation, the
547 	 * least significant bits of its physical address can be determined
548 	 * from its offset from the beginning of the reservation and the size
549 	 * of the reservation.
550 	 *
551 	 * Could the specified index within a reservation of the smallest
552 	 * possible size satisfy the alignment and boundary requirements?
553 	 */
554 	pa = VM_RESERV_INDEX(object, pindex) << PAGE_SHIFT;
555 	if ((pa & (alignment - 1)) != 0)
556 		return (NULL);
557 	size = npages << PAGE_SHIFT;
558 	if (((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
559 		return (NULL);
560 
561 	/*
562 	 * Look for an existing reservation.
563 	 */
564 	rv = vm_reserv_from_object(object, pindex, mpred, &msucc);
565 	if (rv == NULL)
566 		return (NULL);
567 	KASSERT(object != kernel_object || rv->domain == domain,
568 	    ("vm_reserv_extend_contig: Domain mismatch from reservation."));
569 	index = VM_RESERV_INDEX(object, pindex);
570 	/* Does the allocation fit within the reservation? */
571 	if (index + npages > VM_LEVEL_0_NPAGES)
572 		return (NULL);
573 	domain = rv->domain;
574 	vmd = VM_DOMAIN(domain);
575 	vm_domain_free_lock(vmd);
576 	if (rv->object != object || !vm_domain_available(vmd, req, npages)) {
577 		m = NULL;
578 		goto out;
579 	}
580 	m = &rv->pages[index];
581 	pa = VM_PAGE_TO_PHYS(m);
582 	if (pa < low || pa + size > high || (pa & (alignment - 1)) != 0 ||
583 	    ((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0) {
584 		m = NULL;
585 		goto out;
586 	}
587 	/* Handle vm_page_rename(m, new_object, ...). */
588 	for (i = 0; i < npages; i++) {
589 		if (popmap_is_set(rv->popmap, index + i)) {
590 			m = NULL;
591 			goto out;
592 		}
593 	}
594 	for (i = 0; i < npages; i++)
595 		vm_reserv_populate(rv, index + i);
596 	vm_domain_freecnt_dec(vmd, npages);
597 out:
598 	vm_domain_free_unlock(vmd);
599 	return (m);
600 }
601 
602 /*
603  * Allocates a contiguous set of physical pages of the given size "npages"
604  * from newly created reservations.  All of the physical pages
605  * must be at or above the given physical address "low" and below the given
606  * physical address "high".  The given value "alignment" determines the
607  * alignment of the first physical page in the set.  If the given value
608  * "boundary" is non-zero, then the set of physical pages cannot cross any
609  * physical address boundary that is a multiple of that value.  Both
610  * "alignment" and "boundary" must be a power of two.
611  *
612  * Callers should first invoke vm_reserv_extend_contig() to attempt an
613  * allocation from existing reservations.
614  *
615  * The page "mpred" must immediately precede the offset "pindex" within the
616  * specified object.
617  *
618  * The object and free page queue must be locked.
619  */
620 vm_page_t
621 vm_reserv_alloc_contig(vm_object_t object, vm_pindex_t pindex, int domain,
622     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
623     vm_paddr_t boundary, vm_page_t mpred)
624 {
625 	vm_paddr_t pa, size;
626 	vm_page_t m, m_ret, msucc;
627 	vm_pindex_t first, leftcap, rightcap;
628 	vm_reserv_t rv;
629 	u_long allocpages, maxpages, minpages;
630 	int i, index, n;
631 
632 	vm_domain_free_assert_locked(VM_DOMAIN(domain));
633 	VM_OBJECT_ASSERT_WLOCKED(object);
634 	KASSERT(npages != 0, ("vm_reserv_alloc_contig: npages is 0"));
635 
636 	/*
637 	 * Is a reservation fundamentally impossible?
638 	 */
639 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
640 	    pindex + npages > object->size)
641 		return (NULL);
642 
643 	/*
644 	 * All reservations of a particular size have the same alignment.
645 	 * Assuming that the first page is allocated from a reservation, the
646 	 * least significant bits of its physical address can be determined
647 	 * from its offset from the beginning of the reservation and the size
648 	 * of the reservation.
649 	 *
650 	 * Could the specified index within a reservation of the smallest
651 	 * possible size satisfy the alignment and boundary requirements?
652 	 */
653 	pa = VM_RESERV_INDEX(object, pindex) << PAGE_SHIFT;
654 	if ((pa & (alignment - 1)) != 0)
655 		return (NULL);
656 	size = npages << PAGE_SHIFT;
657 	if (((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
658 		return (NULL);
659 
660 	/*
661 	 * Callers should've extended an existing reservation prior to
662 	 * calling this function.  If a reservation exists it is
663 	 * incompatible with the allocation.
664 	 */
665 	rv = vm_reserv_from_object(object, pindex, mpred, &msucc);
666 	if (rv != NULL)
667 		return (NULL);
668 
669 	/*
670 	 * Could at least one reservation fit between the first index to the
671 	 * left that can be used ("leftcap") and the first index to the right
672 	 * that cannot be used ("rightcap")?
673 	 *
674 	 * We must synchronize with the reserv object lock to protect the
675 	 * pindex/object of the resulting reservations against rename while
676 	 * we are inspecting.
677 	 */
678 	first = pindex - VM_RESERV_INDEX(object, pindex);
679 	minpages = VM_RESERV_INDEX(object, pindex) + npages;
680 	maxpages = roundup2(minpages, VM_LEVEL_0_NPAGES);
681 	allocpages = maxpages;
682 	vm_reserv_object_lock(object);
683 	if (mpred != NULL) {
684 		if ((rv = vm_reserv_from_page(mpred))->object != object)
685 			leftcap = mpred->pindex + 1;
686 		else
687 			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
688 		if (leftcap > first) {
689 			vm_reserv_object_unlock(object);
690 			return (NULL);
691 		}
692 	}
693 	if (msucc != NULL) {
694 		if ((rv = vm_reserv_from_page(msucc))->object != object)
695 			rightcap = msucc->pindex;
696 		else
697 			rightcap = rv->pindex;
698 		if (first + maxpages > rightcap) {
699 			if (maxpages == VM_LEVEL_0_NPAGES) {
700 				vm_reserv_object_unlock(object);
701 				return (NULL);
702 			}
703 
704 			/*
705 			 * At least one reservation will fit between "leftcap"
706 			 * and "rightcap".  However, a reservation for the
707 			 * last of the requested pages will not fit.  Reduce
708 			 * the size of the upcoming allocation accordingly.
709 			 */
710 			allocpages = minpages;
711 		}
712 	}
713 	vm_reserv_object_unlock(object);
714 
715 	/*
716 	 * Would the last new reservation extend past the end of the object?
717 	 */
718 	if (first + maxpages > object->size) {
719 		/*
720 		 * Don't allocate the last new reservation if the object is a
721 		 * vnode or backed by another object that is a vnode.
722 		 */
723 		if (object->type == OBJT_VNODE ||
724 		    (object->backing_object != NULL &&
725 		    object->backing_object->type == OBJT_VNODE)) {
726 			if (maxpages == VM_LEVEL_0_NPAGES)
727 				return (NULL);
728 			allocpages = minpages;
729 		}
730 		/* Speculate that the object may grow. */
731 	}
732 
733 	/*
734 	 * Allocate the physical pages.  The alignment and boundary specified
735 	 * for this allocation may be different from the alignment and
736 	 * boundary specified for the requested pages.  For instance, the
737 	 * specified index may not be the first page within the first new
738 	 * reservation.
739 	 */
740 	m = vm_phys_alloc_contig(domain, allocpages, low, high, ulmax(alignment,
741 	    VM_LEVEL_0_SIZE), boundary > VM_LEVEL_0_SIZE ? boundary : 0);
742 	if (m == NULL)
743 		return (NULL);
744 	KASSERT(vm_phys_domain(m) == domain,
745 	    ("vm_reserv_alloc_contig: Page domain does not match requested."));
746 
747 	/*
748 	 * The allocated physical pages always begin at a reservation
749 	 * boundary, but they do not always end at a reservation boundary.
750 	 * Initialize every reservation that is completely covered by the
751 	 * allocated physical pages.
752 	 */
753 	m_ret = NULL;
754 	index = VM_RESERV_INDEX(object, pindex);
755 	do {
756 		rv = vm_reserv_from_page(m);
757 		KASSERT(rv->pages == m,
758 		    ("vm_reserv_alloc_contig: reserv %p's pages is corrupted",
759 		    rv));
760 		vm_reserv_insert(rv, object, first);
761 		n = ulmin(VM_LEVEL_0_NPAGES - index, npages);
762 		for (i = 0; i < n; i++)
763 			vm_reserv_populate(rv, index + i);
764 		npages -= n;
765 		if (m_ret == NULL) {
766 			m_ret = &rv->pages[index];
767 			index = 0;
768 		}
769 		m += VM_LEVEL_0_NPAGES;
770 		first += VM_LEVEL_0_NPAGES;
771 		allocpages -= VM_LEVEL_0_NPAGES;
772 	} while (allocpages >= VM_LEVEL_0_NPAGES);
773 	return (m_ret);
774 }
775 
776 /*
777  * Attempts to extend an existing reservation and allocate the page to the
778  * object.
779  *
780  * The page "mpred" must immediately precede the offset "pindex" within the
781  * specified object.
782  *
783  * The object must be locked.
784  */
785 vm_page_t
786 vm_reserv_extend(int req, vm_object_t object, vm_pindex_t pindex, int domain,
787     vm_page_t mpred)
788 {
789 	struct vm_domain *vmd;
790 	vm_page_t m, msucc;
791 	vm_reserv_t rv;
792 	int index;
793 
794 	VM_OBJECT_ASSERT_WLOCKED(object);
795 
796 	/*
797 	 * Could a reservation currently exist?
798 	 */
799 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
800 	    pindex >= object->size || object->resident_page_count == 0)
801 		return (NULL);
802 
803 	/*
804 	 * Look for an existing reservation.
805 	 */
806 	rv = vm_reserv_from_object(object, pindex, mpred, &msucc);
807 	if (rv == NULL)
808 		return (NULL);
809 
810 	KASSERT(object != kernel_object || rv->domain == domain,
811 	    ("vm_reserv_extend: Domain mismatch from reservation."));
812 	domain = rv->domain;
813 	vmd = VM_DOMAIN(domain);
814 	index = VM_RESERV_INDEX(object, pindex);
815 	m = &rv->pages[index];
816 	vm_domain_free_lock(vmd);
817 	if (vm_domain_available(vmd, req, 1) == 0 ||
818 	    /* Handle reclaim race. */
819 	    rv->object != object ||
820 	    /* Handle vm_page_rename(m, new_object, ...). */
821 	    popmap_is_set(rv->popmap, index))
822 		m = NULL;
823 	if (m != NULL) {
824 		vm_reserv_populate(rv, index);
825 		vm_domain_freecnt_dec(vmd, 1);
826 	}
827 	vm_domain_free_unlock(vmd);
828 
829 	return (m);
830 }
831 
832 /*
833  * Attempts to allocate a new reservation for the object, and allocates a
834  * page from that reservation.  Callers should first invoke vm_reserv_extend()
835  * to attempt an allocation from an existing reservation.
836  *
837  * The page "mpred" must immediately precede the offset "pindex" within the
838  * specified object.
839  *
840  * The object and free page queue must be locked.
841  */
842 vm_page_t
843 vm_reserv_alloc_page(vm_object_t object, vm_pindex_t pindex, int domain,
844     vm_page_t mpred)
845 {
846 	vm_page_t m, msucc;
847 	vm_pindex_t first, leftcap, rightcap;
848 	vm_reserv_t rv;
849 	int index;
850 
851 	vm_domain_free_assert_locked(VM_DOMAIN(domain));
852 	VM_OBJECT_ASSERT_WLOCKED(object);
853 
854 	/*
855 	 * Is a reservation fundamentally impossible?
856 	 */
857 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
858 	    pindex >= object->size)
859 		return (NULL);
860 
861 	/*
862 	 * Callers should've extended an existing reservation prior to
863 	 * calling this function.  If a reservation exists it is
864 	 * incompatible with the allocation.
865 	 */
866 	rv = vm_reserv_from_object(object, pindex, mpred, &msucc);
867 	if (rv != NULL)
868 		return (NULL);
869 
870 	/*
871 	 * Could a reservation fit between the first index to the left that
872 	 * can be used and the first index to the right that cannot be used?
873 	 *
874 	 * We must synchronize with the reserv object lock to protect the
875 	 * pindex/object of the resulting reservations against rename while
876 	 * we are inspecting.
877 	 */
878 	first = pindex - VM_RESERV_INDEX(object, pindex);
879 	vm_reserv_object_lock(object);
880 	if (mpred != NULL) {
881 		if ((rv = vm_reserv_from_page(mpred))->object != object)
882 			leftcap = mpred->pindex + 1;
883 		else
884 			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
885 		if (leftcap > first) {
886 			vm_reserv_object_unlock(object);
887 			return (NULL);
888 		}
889 	}
890 	if (msucc != NULL) {
891 		if ((rv = vm_reserv_from_page(msucc))->object != object)
892 			rightcap = msucc->pindex;
893 		else
894 			rightcap = rv->pindex;
895 		if (first + VM_LEVEL_0_NPAGES > rightcap) {
896 			vm_reserv_object_unlock(object);
897 			return (NULL);
898 		}
899 	}
900 	vm_reserv_object_unlock(object);
901 
902 	/*
903 	 * Would a new reservation extend past the end of the object?
904 	 */
905 	if (first + VM_LEVEL_0_NPAGES > object->size) {
906 		/*
907 		 * Don't allocate a new reservation if the object is a vnode or
908 		 * backed by another object that is a vnode.
909 		 */
910 		if (object->type == OBJT_VNODE ||
911 		    (object->backing_object != NULL &&
912 		    object->backing_object->type == OBJT_VNODE))
913 			return (NULL);
914 		/* Speculate that the object may grow. */
915 	}
916 
917 	/*
918 	 * Allocate and populate the new reservation.
919 	 */
920 	m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT, VM_LEVEL_0_ORDER);
921 	if (m == NULL)
922 		return (NULL);
923 	rv = vm_reserv_from_page(m);
924 	KASSERT(rv->pages == m,
925 	    ("vm_reserv_alloc_page: reserv %p's pages is corrupted", rv));
926 	vm_reserv_insert(rv, object, first);
927 	index = VM_RESERV_INDEX(object, pindex);
928 	vm_reserv_populate(rv, index);
929 	return (&rv->pages[index]);
930 }
931 
932 /*
933  * Breaks the given reservation.  All free pages in the reservation
934  * are returned to the physical memory allocator.  The reservation's
935  * population count and map are reset to their initial state.
936  *
937  * The given reservation must not be in the partially populated reservation
938  * queue.  The free page queue lock must be held.
939  */
940 static void
941 vm_reserv_break(vm_reserv_t rv)
942 {
943 	int begin_zeroes, hi, i, lo;
944 
945 	vm_domain_free_assert_locked(VM_DOMAIN(rv->domain));
946 	vm_reserv_remove(rv);
947 	rv->pages->psind = 0;
948 	i = hi = 0;
949 	do {
950 		/* Find the next 0 bit.  Any previous 0 bits are < "hi". */
951 		lo = ffsl(~(((1UL << hi) - 1) | rv->popmap[i]));
952 		if (lo == 0) {
953 			/* Redundantly clears bits < "hi". */
954 			rv->popmap[i] = 0;
955 			rv->popcnt -= NBPOPMAP - hi;
956 			while (++i < NPOPMAP) {
957 				lo = ffsl(~rv->popmap[i]);
958 				if (lo == 0) {
959 					rv->popmap[i] = 0;
960 					rv->popcnt -= NBPOPMAP;
961 				} else
962 					break;
963 			}
964 			if (i == NPOPMAP)
965 				break;
966 			hi = 0;
967 		}
968 		KASSERT(lo > 0, ("vm_reserv_break: lo is %d", lo));
969 		/* Convert from ffsl() to ordinary bit numbering. */
970 		lo--;
971 		if (lo > 0) {
972 			/* Redundantly clears bits < "hi". */
973 			rv->popmap[i] &= ~((1UL << lo) - 1);
974 			rv->popcnt -= lo - hi;
975 		}
976 		begin_zeroes = NBPOPMAP * i + lo;
977 		/* Find the next 1 bit. */
978 		do
979 			hi = ffsl(rv->popmap[i]);
980 		while (hi == 0 && ++i < NPOPMAP);
981 		if (i != NPOPMAP)
982 			/* Convert from ffsl() to ordinary bit numbering. */
983 			hi--;
984 		vm_phys_free_contig(&rv->pages[begin_zeroes], NBPOPMAP * i +
985 		    hi - begin_zeroes);
986 	} while (i < NPOPMAP);
987 	KASSERT(rv->popcnt == 0,
988 	    ("vm_reserv_break: reserv %p's popcnt is corrupted", rv));
989 	vm_reserv_broken++;
990 }
991 
992 /*
993  * Breaks all reservations belonging to the given object.
994  */
995 void
996 vm_reserv_break_all(vm_object_t object)
997 {
998 	vm_reserv_t rv;
999 	struct vm_domain *vmd;
1000 
1001 	/*
1002 	 * This access of object->rvq is unsynchronized so that the
1003 	 * object rvq lock can nest after the domain_free lock.  We
1004 	 * must check for races in the results.  However, the object
1005 	 * lock prevents new additions, so we are guaranteed that when
1006 	 * it returns NULL the object is properly empty.
1007 	 */
1008 	vmd = NULL;
1009 	while ((rv = LIST_FIRST(&object->rvq)) != NULL) {
1010 		if (vmd != VM_DOMAIN(rv->domain)) {
1011 			if (vmd != NULL)
1012 				vm_domain_free_unlock(vmd);
1013 			vmd = VM_DOMAIN(rv->domain);
1014 			vm_domain_free_lock(vmd);
1015 		}
1016 		/* Reclaim race. */
1017 		if (rv->object != object)
1018 			continue;
1019 		KASSERT(rv->object == object,
1020 		    ("vm_reserv_break_all: reserv %p is corrupted", rv));
1021 		if (rv->inpartpopq) {
1022 			TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
1023 			rv->inpartpopq = FALSE;
1024 		}
1025 		vm_reserv_break(rv);
1026 	}
1027 	if (vmd != NULL)
1028 		vm_domain_free_unlock(vmd);
1029 }
1030 
1031 /*
1032  * Frees the given page if it belongs to a reservation.  Returns TRUE if the
1033  * page is freed and FALSE otherwise.
1034  *
1035  * The free page queue lock must be held.
1036  */
1037 boolean_t
1038 vm_reserv_free_page(vm_page_t m)
1039 {
1040 	vm_reserv_t rv;
1041 
1042 	rv = vm_reserv_from_page(m);
1043 	if (rv->object == NULL)
1044 		return (FALSE);
1045 	vm_domain_free_assert_locked(VM_DOMAIN(rv->domain));
1046 	vm_reserv_depopulate(rv, m - rv->pages);
1047 	return (TRUE);
1048 }
1049 
1050 /*
1051  * Initializes the reservation management system.  Specifically, initializes
1052  * the reservation array.
1053  *
1054  * Requires that vm_page_array and first_page are initialized!
1055  */
1056 void
1057 vm_reserv_init(void)
1058 {
1059 	vm_paddr_t paddr;
1060 	struct vm_phys_seg *seg;
1061 	int i, segind;
1062 
1063 	/*
1064 	 * Initialize the reservation array.  Specifically, initialize the
1065 	 * "pages" field for every element that has an underlying superpage.
1066 	 */
1067 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
1068 		seg = &vm_phys_segs[segind];
1069 		paddr = roundup2(seg->start, VM_LEVEL_0_SIZE);
1070 		while (paddr + VM_LEVEL_0_SIZE <= seg->end) {
1071 			vm_reserv_array[paddr >> VM_LEVEL_0_SHIFT].pages =
1072 			    PHYS_TO_VM_PAGE(paddr);
1073 			vm_reserv_array[paddr >> VM_LEVEL_0_SHIFT].domain =
1074 			    seg->domain;
1075 			paddr += VM_LEVEL_0_SIZE;
1076 		}
1077 	}
1078 	for (i = 0; i < MAXMEMDOM; i++)
1079 		TAILQ_INIT(&vm_rvq_partpop[i]);
1080 }
1081 
1082 /*
1083  * Returns true if the given page belongs to a reservation and that page is
1084  * free.  Otherwise, returns false.
1085  */
1086 bool
1087 vm_reserv_is_page_free(vm_page_t m)
1088 {
1089 	vm_reserv_t rv;
1090 
1091 	rv = vm_reserv_from_page(m);
1092 	if (rv->object == NULL)
1093 		return (false);
1094 	vm_domain_free_assert_locked(VM_DOMAIN(rv->domain));
1095 	return (popmap_is_clear(rv->popmap, m - rv->pages));
1096 }
1097 
1098 /*
1099  * If the given page belongs to a reservation, returns the level of that
1100  * reservation.  Otherwise, returns -1.
1101  */
1102 int
1103 vm_reserv_level(vm_page_t m)
1104 {
1105 	vm_reserv_t rv;
1106 
1107 	rv = vm_reserv_from_page(m);
1108 	return (rv->object != NULL ? 0 : -1);
1109 }
1110 
1111 /*
1112  * Returns a reservation level if the given page belongs to a fully populated
1113  * reservation and -1 otherwise.
1114  */
1115 int
1116 vm_reserv_level_iffullpop(vm_page_t m)
1117 {
1118 	vm_reserv_t rv;
1119 
1120 	rv = vm_reserv_from_page(m);
1121 	return (rv->popcnt == VM_LEVEL_0_NPAGES ? 0 : -1);
1122 }
1123 
1124 /*
1125  * Breaks the given partially populated reservation, releasing its free pages
1126  * to the physical memory allocator.
1127  *
1128  * The free page queue lock must be held.
1129  */
1130 static void
1131 vm_reserv_reclaim(vm_reserv_t rv)
1132 {
1133 
1134 	vm_domain_free_assert_locked(VM_DOMAIN(rv->domain));
1135 	KASSERT(rv->inpartpopq,
1136 	    ("vm_reserv_reclaim: reserv %p's inpartpopq is FALSE", rv));
1137 	KASSERT(rv->domain >= 0 && rv->domain < vm_ndomains,
1138 	    ("vm_reserv_reclaim: reserv %p's domain is corrupted %d",
1139 	    rv, rv->domain));
1140 	TAILQ_REMOVE(&vm_rvq_partpop[rv->domain], rv, partpopq);
1141 	rv->inpartpopq = FALSE;
1142 	vm_reserv_break(rv);
1143 	vm_reserv_reclaimed++;
1144 }
1145 
1146 /*
1147  * Breaks the reservation at the head of the partially populated reservation
1148  * queue, releasing its free pages to the physical memory allocator.  Returns
1149  * TRUE if a reservation is broken and FALSE otherwise.
1150  *
1151  * The free page queue lock must be held.
1152  */
1153 boolean_t
1154 vm_reserv_reclaim_inactive(int domain)
1155 {
1156 	vm_reserv_t rv;
1157 
1158 	vm_domain_free_assert_locked(VM_DOMAIN(domain));
1159 	if ((rv = TAILQ_FIRST(&vm_rvq_partpop[domain])) != NULL) {
1160 		vm_reserv_reclaim(rv);
1161 		return (TRUE);
1162 	}
1163 	return (FALSE);
1164 }
1165 
1166 /*
1167  * Searches the partially populated reservation queue for the least recently
1168  * changed reservation with free pages that satisfy the given request for
1169  * contiguous physical memory.  If a satisfactory reservation is found, it is
1170  * broken.  Returns TRUE if a reservation is broken and FALSE otherwise.
1171  *
1172  * The free page queue lock must be held.
1173  */
1174 boolean_t
1175 vm_reserv_reclaim_contig(int domain, u_long npages, vm_paddr_t low,
1176     vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
1177 {
1178 	vm_paddr_t pa, size;
1179 	vm_reserv_t rv;
1180 	int hi, i, lo, low_index, next_free;
1181 
1182 	vm_domain_free_assert_locked(VM_DOMAIN(domain));
1183 	if (npages > VM_LEVEL_0_NPAGES - 1)
1184 		return (FALSE);
1185 	size = npages << PAGE_SHIFT;
1186 	TAILQ_FOREACH(rv, &vm_rvq_partpop[domain], partpopq) {
1187 		pa = VM_PAGE_TO_PHYS(&rv->pages[VM_LEVEL_0_NPAGES - 1]);
1188 		if (pa + PAGE_SIZE - size < low) {
1189 			/* This entire reservation is too low; go to next. */
1190 			continue;
1191 		}
1192 		pa = VM_PAGE_TO_PHYS(&rv->pages[0]);
1193 		if (pa + size > high) {
1194 			/* This entire reservation is too high; go to next. */
1195 			continue;
1196 		}
1197 		if (pa < low) {
1198 			/* Start the search for free pages at "low". */
1199 			low_index = (low + PAGE_MASK - pa) >> PAGE_SHIFT;
1200 			i = low_index / NBPOPMAP;
1201 			hi = low_index % NBPOPMAP;
1202 		} else
1203 			i = hi = 0;
1204 		do {
1205 			/* Find the next free page. */
1206 			lo = ffsl(~(((1UL << hi) - 1) | rv->popmap[i]));
1207 			while (lo == 0 && ++i < NPOPMAP)
1208 				lo = ffsl(~rv->popmap[i]);
1209 			if (i == NPOPMAP)
1210 				break;
1211 			/* Convert from ffsl() to ordinary bit numbering. */
1212 			lo--;
1213 			next_free = NBPOPMAP * i + lo;
1214 			pa = VM_PAGE_TO_PHYS(&rv->pages[next_free]);
1215 			KASSERT(pa >= low,
1216 			    ("vm_reserv_reclaim_contig: pa is too low"));
1217 			if (pa + size > high) {
1218 				/* The rest of this reservation is too high. */
1219 				break;
1220 			} else if ((pa & (alignment - 1)) != 0 ||
1221 			    ((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0) {
1222 				/*
1223 				 * The current page doesn't meet the alignment
1224 				 * and/or boundary requirements.  Continue
1225 				 * searching this reservation until the rest
1226 				 * of its free pages are either excluded or
1227 				 * exhausted.
1228 				 */
1229 				hi = lo + 1;
1230 				if (hi >= NBPOPMAP) {
1231 					hi = 0;
1232 					i++;
1233 				}
1234 				continue;
1235 			}
1236 			/* Find the next used page. */
1237 			hi = ffsl(rv->popmap[i] & ~((1UL << lo) - 1));
1238 			while (hi == 0 && ++i < NPOPMAP) {
1239 				if ((NBPOPMAP * i - next_free) * PAGE_SIZE >=
1240 				    size) {
1241 					vm_reserv_reclaim(rv);
1242 					return (TRUE);
1243 				}
1244 				hi = ffsl(rv->popmap[i]);
1245 			}
1246 			/* Convert from ffsl() to ordinary bit numbering. */
1247 			if (i != NPOPMAP)
1248 				hi--;
1249 			if ((NBPOPMAP * i + hi - next_free) * PAGE_SIZE >=
1250 			    size) {
1251 				vm_reserv_reclaim(rv);
1252 				return (TRUE);
1253 			}
1254 		} while (i < NPOPMAP);
1255 	}
1256 	return (FALSE);
1257 }
1258 
1259 /*
1260  * Transfers the reservation underlying the given page to a new object.
1261  *
1262  * The object must be locked.
1263  */
1264 void
1265 vm_reserv_rename(vm_page_t m, vm_object_t new_object, vm_object_t old_object,
1266     vm_pindex_t old_object_offset)
1267 {
1268 	vm_reserv_t rv;
1269 
1270 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1271 	rv = vm_reserv_from_page(m);
1272 	if (rv->object == old_object) {
1273 		vm_domain_free_lock(VM_DOMAIN(rv->domain));
1274 		if (rv->object == old_object) {
1275 			vm_reserv_object_lock(old_object);
1276 			rv->object = NULL;
1277 			LIST_REMOVE(rv, objq);
1278 			vm_reserv_object_unlock(old_object);
1279 			vm_reserv_object_lock(new_object);
1280 			rv->object = new_object;
1281 			rv->pindex -= old_object_offset;
1282 			LIST_INSERT_HEAD(&new_object->rvq, rv, objq);
1283 			vm_reserv_object_unlock(new_object);
1284 		}
1285 		vm_domain_free_unlock(VM_DOMAIN(rv->domain));
1286 	}
1287 }
1288 
1289 /*
1290  * Returns the size (in bytes) of a reservation of the specified level.
1291  */
1292 int
1293 vm_reserv_size(int level)
1294 {
1295 
1296 	switch (level) {
1297 	case 0:
1298 		return (VM_LEVEL_0_SIZE);
1299 	case -1:
1300 		return (PAGE_SIZE);
1301 	default:
1302 		return (0);
1303 	}
1304 }
1305 
1306 /*
1307  * Allocates the virtual and physical memory required by the reservation
1308  * management system's data structures, in particular, the reservation array.
1309  */
1310 vm_paddr_t
1311 vm_reserv_startup(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t high_water)
1312 {
1313 	vm_paddr_t new_end;
1314 	size_t size;
1315 	int i;
1316 
1317 	/*
1318 	 * Calculate the size (in bytes) of the reservation array.  Round up
1319 	 * from "high_water" because every small page is mapped to an element
1320 	 * in the reservation array based on its physical address.  Thus, the
1321 	 * number of elements in the reservation array can be greater than the
1322 	 * number of superpages.
1323 	 */
1324 	size = howmany(high_water, VM_LEVEL_0_SIZE) * sizeof(struct vm_reserv);
1325 
1326 	/*
1327 	 * Allocate and map the physical memory for the reservation array.  The
1328 	 * next available virtual address is returned by reference.
1329 	 */
1330 	new_end = end - round_page(size);
1331 	vm_reserv_array = (void *)(uintptr_t)pmap_map(vaddr, new_end, end,
1332 	    VM_PROT_READ | VM_PROT_WRITE);
1333 	bzero(vm_reserv_array, size);
1334 
1335 	for (i = 0; i < VM_RESERV_OBJ_LOCK_COUNT; i++)
1336 		mtx_init(&vm_reserv_object_mtx[i], "resv obj lock", NULL,
1337 		    MTX_DEF);
1338 
1339 	/*
1340 	 * Return the next available physical address.
1341 	 */
1342 	return (new_end);
1343 }
1344 
1345 /*
1346  * Returns the superpage containing the given page.
1347  */
1348 vm_page_t
1349 vm_reserv_to_superpage(vm_page_t m)
1350 {
1351 	vm_reserv_t rv;
1352 
1353 	VM_OBJECT_ASSERT_LOCKED(m->object);
1354 	rv = vm_reserv_from_page(m);
1355 	return (rv->object == m->object && rv->popcnt == VM_LEVEL_0_NPAGES ?
1356 	    rv->pages : NULL);
1357 }
1358 
1359 #endif	/* VM_NRESERVLEVEL > 0 */
1360