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