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