xref: /freebsd/sys/vm/vm_page.c (revision 7fbc896e28e4eb895bd299da40dbdbc32509376b)
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * The Mach Operating System project at Carnegie-Mellon University.
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  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 /*-
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62 
63 /*
64  *	Resident memory management module.
65  */
66 
67 #include <sys/cdefs.h>
68 #include "opt_vm.h"
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/counter.h>
73 #include <sys/domainset.h>
74 #include <sys/kernel.h>
75 #include <sys/limits.h>
76 #include <sys/linker.h>
77 #include <sys/lock.h>
78 #include <sys/malloc.h>
79 #include <sys/mman.h>
80 #include <sys/msgbuf.h>
81 #include <sys/mutex.h>
82 #include <sys/proc.h>
83 #include <sys/rwlock.h>
84 #include <sys/sleepqueue.h>
85 #include <sys/sbuf.h>
86 #include <sys/sched.h>
87 #include <sys/smp.h>
88 #include <sys/sysctl.h>
89 #include <sys/vmmeter.h>
90 #include <sys/vnode.h>
91 
92 #include <vm/vm.h>
93 #include <vm/pmap.h>
94 #include <vm/vm_param.h>
95 #include <vm/vm_domainset.h>
96 #include <vm/vm_kern.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_object.h>
99 #include <vm/vm_page.h>
100 #include <vm/vm_pageout.h>
101 #include <vm/vm_phys.h>
102 #include <vm/vm_pagequeue.h>
103 #include <vm/vm_pager.h>
104 #include <vm/vm_radix.h>
105 #include <vm/vm_reserv.h>
106 #include <vm/vm_extern.h>
107 #include <vm/vm_dumpset.h>
108 #include <vm/uma.h>
109 #include <vm/uma_int.h>
110 
111 #include <machine/md_var.h>
112 
113 struct vm_domain vm_dom[MAXMEMDOM];
114 
115 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
116 
117 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
118 
119 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
120 /* The following fields are protected by the domainset lock. */
121 domainset_t __exclusive_cache_line vm_min_domains;
122 domainset_t __exclusive_cache_line vm_severe_domains;
123 static int vm_min_waiters;
124 static int vm_severe_waiters;
125 static int vm_pageproc_waiters;
126 
127 static SYSCTL_NODE(_vm_stats, OID_AUTO, page, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
128     "VM page statistics");
129 
130 static COUNTER_U64_DEFINE_EARLY(pqstate_commit_retries);
131 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, pqstate_commit_retries,
132     CTLFLAG_RD, &pqstate_commit_retries,
133     "Number of failed per-page atomic queue state updates");
134 
135 static COUNTER_U64_DEFINE_EARLY(queue_ops);
136 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
137     CTLFLAG_RD, &queue_ops,
138     "Number of batched queue operations");
139 
140 static COUNTER_U64_DEFINE_EARLY(queue_nops);
141 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
142     CTLFLAG_RD, &queue_nops,
143     "Number of batched queue operations with no effects");
144 
145 /*
146  * bogus page -- for I/O to/from partially complete buffers,
147  * or for paging into sparsely invalid regions.
148  */
149 vm_page_t bogus_page;
150 
151 vm_page_t vm_page_array;
152 long vm_page_array_size;
153 long first_page;
154 
155 struct bitset *vm_page_dump;
156 long vm_page_dump_pages;
157 
158 static TAILQ_HEAD(, vm_page) blacklist_head;
159 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
160 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
161     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
162 
163 static uma_zone_t fakepg_zone;
164 
165 static vm_page_t vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
166     int req, vm_page_t mpred);
167 static void vm_page_alloc_check(vm_page_t m);
168 static vm_page_t vm_page_alloc_nofree_domain(int domain, int req);
169 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
170     vm_pindex_t pindex, const char *wmesg, int allocflags, bool locked);
171 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
172 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
173 static bool vm_page_free_prep(vm_page_t m);
174 static void vm_page_free_toq(vm_page_t m);
175 static void vm_page_init(void *dummy);
176 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
177     vm_pindex_t pindex, vm_page_t mpred);
178 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
179     vm_page_t mpred);
180 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
181     const uint16_t nflag);
182 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
183     vm_page_t m_run, vm_paddr_t high);
184 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
185 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
186     int req);
187 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
188     int flags);
189 static void vm_page_zone_release(void *arg, void **store, int cnt);
190 
191 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
192 
193 static void
vm_page_init(void * dummy)194 vm_page_init(void *dummy)
195 {
196 
197 	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
198 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
199 	bogus_page = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_NOFREE);
200 }
201 
202 static int pgcache_zone_max_pcpu;
203 SYSCTL_INT(_vm, OID_AUTO, pgcache_zone_max_pcpu,
204     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pgcache_zone_max_pcpu, 0,
205     "Per-CPU page cache size");
206 
207 /*
208  * The cache page zone is initialized later since we need to be able to allocate
209  * pages before UMA is fully initialized.
210  */
211 static void
vm_page_init_cache_zones(void * dummy __unused)212 vm_page_init_cache_zones(void *dummy __unused)
213 {
214 	struct vm_domain *vmd;
215 	struct vm_pgcache *pgcache;
216 	int cache, domain, maxcache, pool;
217 
218 	TUNABLE_INT_FETCH("vm.pgcache_zone_max_pcpu", &pgcache_zone_max_pcpu);
219 	maxcache = pgcache_zone_max_pcpu * mp_ncpus;
220 	for (domain = 0; domain < vm_ndomains; domain++) {
221 		vmd = VM_DOMAIN(domain);
222 		for (pool = 0; pool < VM_NFREEPOOL; pool++) {
223 			pgcache = &vmd->vmd_pgcache[pool];
224 			pgcache->domain = domain;
225 			pgcache->pool = pool;
226 			pgcache->zone = uma_zcache_create("vm pgcache",
227 			    PAGE_SIZE, NULL, NULL, NULL, NULL,
228 			    vm_page_zone_import, vm_page_zone_release, pgcache,
229 			    UMA_ZONE_VM);
230 
231 			/*
232 			 * Limit each pool's zone to 0.1% of the pages in the
233 			 * domain.
234 			 */
235 			cache = maxcache != 0 ? maxcache :
236 			    vmd->vmd_page_count / 1000;
237 			uma_zone_set_maxcache(pgcache->zone, cache);
238 		}
239 	}
240 }
241 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
242 
243 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
244 #if PAGE_SIZE == 32768
245 #ifdef CTASSERT
246 CTASSERT(sizeof(u_long) >= 8);
247 #endif
248 #endif
249 
250 /*
251  *	vm_set_page_size:
252  *
253  *	Sets the page size, perhaps based upon the memory
254  *	size.  Must be called before any use of page-size
255  *	dependent functions.
256  */
257 void
vm_set_page_size(void)258 vm_set_page_size(void)
259 {
260 	if (vm_cnt.v_page_size == 0)
261 		vm_cnt.v_page_size = PAGE_SIZE;
262 	if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
263 		panic("vm_set_page_size: page size not a power of two");
264 }
265 
266 /*
267  *	vm_page_blacklist_next:
268  *
269  *	Find the next entry in the provided string of blacklist
270  *	addresses.  Entries are separated by space, comma, or newline.
271  *	If an invalid integer is encountered then the rest of the
272  *	string is skipped.  Updates the list pointer to the next
273  *	character, or NULL if the string is exhausted or invalid.
274  */
275 static vm_paddr_t
vm_page_blacklist_next(char ** list,char * end)276 vm_page_blacklist_next(char **list, char *end)
277 {
278 	vm_paddr_t bad;
279 	char *cp, *pos;
280 
281 	if (list == NULL || *list == NULL)
282 		return (0);
283 	if (**list =='\0') {
284 		*list = NULL;
285 		return (0);
286 	}
287 
288 	/*
289 	 * If there's no end pointer then the buffer is coming from
290 	 * the kenv and we know it's null-terminated.
291 	 */
292 	if (end == NULL)
293 		end = *list + strlen(*list);
294 
295 	/* Ensure that strtoq() won't walk off the end */
296 	if (*end != '\0') {
297 		if (*end == '\n' || *end == ' ' || *end  == ',')
298 			*end = '\0';
299 		else {
300 			printf("Blacklist not terminated, skipping\n");
301 			*list = NULL;
302 			return (0);
303 		}
304 	}
305 
306 	for (pos = *list; *pos != '\0'; pos = cp) {
307 		bad = strtoq(pos, &cp, 0);
308 		if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
309 			if (bad == 0) {
310 				if (++cp < end)
311 					continue;
312 				else
313 					break;
314 			}
315 		} else
316 			break;
317 		if (*cp == '\0' || ++cp >= end)
318 			*list = NULL;
319 		else
320 			*list = cp;
321 		return (trunc_page(bad));
322 	}
323 	printf("Garbage in RAM blacklist, skipping\n");
324 	*list = NULL;
325 	return (0);
326 }
327 
328 bool
vm_page_blacklist_add(vm_paddr_t pa,bool verbose)329 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
330 {
331 	struct vm_domain *vmd;
332 	vm_page_t m;
333 	bool found;
334 
335 	m = vm_phys_paddr_to_vm_page(pa);
336 	if (m == NULL)
337 		return (true); /* page does not exist, no failure */
338 
339 	vmd = VM_DOMAIN(vm_phys_domain(pa));
340 	vm_domain_free_lock(vmd);
341 	found = vm_phys_unfree_page(pa);
342 	vm_domain_free_unlock(vmd);
343 	if (found) {
344 		vm_domain_freecnt_inc(vmd, -1);
345 		TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
346 		if (verbose)
347 			printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
348 	}
349 	return (found);
350 }
351 
352 /*
353  *	vm_page_blacklist_check:
354  *
355  *	Iterate through the provided string of blacklist addresses, pulling
356  *	each entry out of the physical allocator free list and putting it
357  *	onto a list for reporting via the vm.page_blacklist sysctl.
358  */
359 static void
vm_page_blacklist_check(char * list,char * end)360 vm_page_blacklist_check(char *list, char *end)
361 {
362 	vm_paddr_t pa;
363 	char *next;
364 
365 	next = list;
366 	while (next != NULL) {
367 		if ((pa = vm_page_blacklist_next(&next, end)) == 0)
368 			continue;
369 		vm_page_blacklist_add(pa, bootverbose);
370 	}
371 }
372 
373 /*
374  *	vm_page_blacklist_load:
375  *
376  *	Search for a special module named "ram_blacklist".  It'll be a
377  *	plain text file provided by the user via the loader directive
378  *	of the same name.
379  */
380 static void
vm_page_blacklist_load(char ** list,char ** end)381 vm_page_blacklist_load(char **list, char **end)
382 {
383 	void *mod;
384 	u_char *ptr;
385 	u_int len;
386 
387 	mod = NULL;
388 	ptr = NULL;
389 
390 	mod = preload_search_by_type("ram_blacklist");
391 	if (mod != NULL) {
392 		ptr = preload_fetch_addr(mod);
393 		len = preload_fetch_size(mod);
394         }
395 	*list = ptr;
396 	if (ptr != NULL)
397 		*end = ptr + len;
398 	else
399 		*end = NULL;
400 	return;
401 }
402 
403 static int
sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)404 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
405 {
406 	vm_page_t m;
407 	struct sbuf sbuf;
408 	int error, first;
409 
410 	first = 1;
411 	error = sysctl_wire_old_buffer(req, 0);
412 	if (error != 0)
413 		return (error);
414 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
415 	TAILQ_FOREACH(m, &blacklist_head, listq) {
416 		sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
417 		    (uintmax_t)m->phys_addr);
418 		first = 0;
419 	}
420 	error = sbuf_finish(&sbuf);
421 	sbuf_delete(&sbuf);
422 	return (error);
423 }
424 
425 /*
426  * Initialize a dummy page for use in scans of the specified paging queue.
427  * In principle, this function only needs to set the flag PG_MARKER.
428  * Nonetheless, it write busies the page as a safety precaution.
429  */
430 void
vm_page_init_marker(vm_page_t marker,int queue,uint16_t aflags)431 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
432 {
433 
434 	bzero(marker, sizeof(*marker));
435 	marker->flags = PG_MARKER;
436 	marker->a.flags = aflags;
437 	marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
438 	marker->a.queue = queue;
439 }
440 
441 static void
vm_page_domain_init(int domain)442 vm_page_domain_init(int domain)
443 {
444 	struct vm_domain *vmd;
445 	struct vm_pagequeue *pq;
446 	int i;
447 
448 	vmd = VM_DOMAIN(domain);
449 	bzero(vmd, sizeof(*vmd));
450 	*__DECONST(const char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
451 	    "vm inactive pagequeue";
452 	*__DECONST(const char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
453 	    "vm active pagequeue";
454 	*__DECONST(const char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
455 	    "vm laundry pagequeue";
456 	*__DECONST(const char **,
457 	    &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
458 	    "vm unswappable pagequeue";
459 	vmd->vmd_domain = domain;
460 	vmd->vmd_page_count = 0;
461 	vmd->vmd_free_count = 0;
462 	vmd->vmd_segs = 0;
463 	vmd->vmd_oom = FALSE;
464 	for (i = 0; i < PQ_COUNT; i++) {
465 		pq = &vmd->vmd_pagequeues[i];
466 		TAILQ_INIT(&pq->pq_pl);
467 		mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
468 		    MTX_DEF | MTX_DUPOK);
469 		pq->pq_pdpages = 0;
470 		vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
471 	}
472 	mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
473 	mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
474 	snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
475 
476 	/*
477 	 * inacthead is used to provide FIFO ordering for LRU-bypassing
478 	 * insertions.
479 	 */
480 	vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
481 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
482 	    &vmd->vmd_inacthead, plinks.q);
483 
484 	/*
485 	 * The clock pages are used to implement active queue scanning without
486 	 * requeues.  Scans start at clock[0], which is advanced after the scan
487 	 * ends.  When the two clock hands meet, they are reset and scanning
488 	 * resumes from the head of the queue.
489 	 */
490 	vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
491 	vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
492 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
493 	    &vmd->vmd_clock[0], plinks.q);
494 	TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
495 	    &vmd->vmd_clock[1], plinks.q);
496 }
497 
498 /*
499  * Initialize a physical page in preparation for adding it to the free
500  * lists.
501  */
502 void
vm_page_init_page(vm_page_t m,vm_paddr_t pa,int segind,int pool)503 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind, int pool)
504 {
505 	m->object = NULL;
506 	m->ref_count = 0;
507 	m->busy_lock = VPB_FREED;
508 	m->flags = m->a.flags = 0;
509 	m->phys_addr = pa;
510 	m->a.queue = PQ_NONE;
511 	m->psind = 0;
512 	m->segind = segind;
513 	m->order = VM_NFREEORDER;
514 	m->pool = pool;
515 	m->valid = m->dirty = 0;
516 	pmap_page_init(m);
517 }
518 
519 #ifndef PMAP_HAS_PAGE_ARRAY
520 static vm_paddr_t
vm_page_array_alloc(vm_offset_t * vaddr,vm_paddr_t end,vm_paddr_t page_range)521 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
522 {
523 	vm_paddr_t new_end;
524 
525 	/*
526 	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
527 	 * However, because this page is allocated from KVM, out-of-bounds
528 	 * accesses using the direct map will not be trapped.
529 	 */
530 	*vaddr += PAGE_SIZE;
531 
532 	/*
533 	 * Allocate physical memory for the page structures, and map it.
534 	 */
535 	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
536 	vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
537 	    VM_PROT_READ | VM_PROT_WRITE);
538 	vm_page_array_size = page_range;
539 
540 	return (new_end);
541 }
542 #endif
543 
544 /*
545  *	vm_page_startup:
546  *
547  *	Initializes the resident memory module.  Allocates physical memory for
548  *	bootstrapping UMA and some data structures that are used to manage
549  *	physical pages.  Initializes these structures, and populates the free
550  *	page queues.
551  */
552 vm_offset_t
vm_page_startup(vm_offset_t vaddr)553 vm_page_startup(vm_offset_t vaddr)
554 {
555 	struct vm_phys_seg *seg;
556 	struct vm_domain *vmd;
557 	vm_page_t m;
558 	char *list, *listend;
559 	vm_paddr_t end, high_avail, low_avail, new_end, size;
560 	vm_paddr_t page_range __unused;
561 	vm_paddr_t last_pa, pa, startp, endp;
562 	u_long pagecount;
563 #if MINIDUMP_PAGE_TRACKING
564 	u_long vm_page_dump_size;
565 #endif
566 	int biggestone, i, segind;
567 #ifdef WITNESS
568 	vm_offset_t mapped;
569 	int witness_size;
570 #endif
571 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
572 	long ii;
573 #endif
574 #ifdef VM_FREEPOOL_LAZYINIT
575 	int lazyinit;
576 #endif
577 
578 	vaddr = round_page(vaddr);
579 
580 	vm_phys_early_startup();
581 	biggestone = vm_phys_avail_largest();
582 	end = phys_avail[biggestone+1];
583 
584 	/*
585 	 * Initialize the page and queue locks.
586 	 */
587 	mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
588 	for (i = 0; i < PA_LOCK_COUNT; i++)
589 		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
590 	for (i = 0; i < vm_ndomains; i++)
591 		vm_page_domain_init(i);
592 
593 	new_end = end;
594 #ifdef WITNESS
595 	witness_size = round_page(witness_startup_count());
596 	new_end -= witness_size;
597 	mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
598 	    VM_PROT_READ | VM_PROT_WRITE);
599 	bzero((void *)mapped, witness_size);
600 	witness_startup((void *)mapped);
601 #endif
602 
603 #if MINIDUMP_PAGE_TRACKING
604 	/*
605 	 * Allocate a bitmap to indicate that a random physical page
606 	 * needs to be included in a minidump.
607 	 *
608 	 * The amd64 port needs this to indicate which direct map pages
609 	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
610 	 *
611 	 * However, i386 still needs this workspace internally within the
612 	 * minidump code.  In theory, they are not needed on i386, but are
613 	 * included should the sf_buf code decide to use them.
614 	 */
615 	last_pa = 0;
616 	vm_page_dump_pages = 0;
617 	for (i = 0; dump_avail[i + 1] != 0; i += 2) {
618 		vm_page_dump_pages += howmany(dump_avail[i + 1], PAGE_SIZE) -
619 		    dump_avail[i] / PAGE_SIZE;
620 		if (dump_avail[i + 1] > last_pa)
621 			last_pa = dump_avail[i + 1];
622 	}
623 	vm_page_dump_size = round_page(BITSET_SIZE(vm_page_dump_pages));
624 	new_end -= vm_page_dump_size;
625 	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
626 	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
627 	bzero((void *)vm_page_dump, vm_page_dump_size);
628 #if MINIDUMP_STARTUP_PAGE_TRACKING
629 	/*
630 	 * Include the UMA bootstrap pages, witness pages and vm_page_dump
631 	 * in a crash dump.  When pmap_map() uses the direct map, they are
632 	 * not automatically included.
633 	 */
634 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
635 		dump_add_page(pa);
636 #endif
637 #else
638 	(void)last_pa;
639 #endif
640 	phys_avail[biggestone + 1] = new_end;
641 #ifdef __amd64__
642 	/*
643 	 * Request that the physical pages underlying the message buffer be
644 	 * included in a crash dump.  Since the message buffer is accessed
645 	 * through the direct map, they are not automatically included.
646 	 */
647 	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
648 	last_pa = pa + round_page(msgbufsize);
649 	while (pa < last_pa) {
650 		dump_add_page(pa);
651 		pa += PAGE_SIZE;
652 	}
653 #endif
654 	/*
655 	 * Compute the number of pages of memory that will be available for
656 	 * use, taking into account the overhead of a page structure per page.
657 	 * In other words, solve
658 	 *	"available physical memory" - round_page(page_range *
659 	 *	    sizeof(struct vm_page)) = page_range * PAGE_SIZE
660 	 * for page_range.
661 	 */
662 	low_avail = phys_avail[0];
663 	high_avail = phys_avail[1];
664 	for (i = 0; i < vm_phys_nsegs; i++) {
665 		if (vm_phys_segs[i].start < low_avail)
666 			low_avail = vm_phys_segs[i].start;
667 		if (vm_phys_segs[i].end > high_avail)
668 			high_avail = vm_phys_segs[i].end;
669 	}
670 	/* Skip the first chunk.  It is already accounted for. */
671 	for (i = 2; phys_avail[i + 1] != 0; i += 2) {
672 		if (phys_avail[i] < low_avail)
673 			low_avail = phys_avail[i];
674 		if (phys_avail[i + 1] > high_avail)
675 			high_avail = phys_avail[i + 1];
676 	}
677 	first_page = low_avail / PAGE_SIZE;
678 #ifdef VM_PHYSSEG_SPARSE
679 	size = 0;
680 	for (i = 0; i < vm_phys_nsegs; i++)
681 		size += vm_phys_segs[i].end - vm_phys_segs[i].start;
682 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
683 		size += phys_avail[i + 1] - phys_avail[i];
684 #elif defined(VM_PHYSSEG_DENSE)
685 	size = high_avail - low_avail;
686 #else
687 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
688 #endif
689 
690 #ifdef PMAP_HAS_PAGE_ARRAY
691 	pmap_page_array_startup(size / PAGE_SIZE);
692 	biggestone = vm_phys_avail_largest();
693 	end = new_end = phys_avail[biggestone + 1];
694 #else
695 #ifdef VM_PHYSSEG_DENSE
696 	/*
697 	 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
698 	 * the overhead of a page structure per page only if vm_page_array is
699 	 * allocated from the last physical memory chunk.  Otherwise, we must
700 	 * allocate page structures representing the physical memory
701 	 * underlying vm_page_array, even though they will not be used.
702 	 */
703 	if (new_end != high_avail)
704 		page_range = size / PAGE_SIZE;
705 	else
706 #endif
707 	{
708 		page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
709 
710 		/*
711 		 * If the partial bytes remaining are large enough for
712 		 * a page (PAGE_SIZE) without a corresponding
713 		 * 'struct vm_page', then new_end will contain an
714 		 * extra page after subtracting the length of the VM
715 		 * page array.  Compensate by subtracting an extra
716 		 * page from new_end.
717 		 */
718 		if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
719 			if (new_end == high_avail)
720 				high_avail -= PAGE_SIZE;
721 			new_end -= PAGE_SIZE;
722 		}
723 	}
724 	end = new_end;
725 	new_end = vm_page_array_alloc(&vaddr, end, page_range);
726 #endif
727 
728 #if VM_NRESERVLEVEL > 0
729 	/*
730 	 * Allocate physical memory for the reservation management system's
731 	 * data structures, and map it.
732 	 */
733 	new_end = vm_reserv_startup(&vaddr, new_end);
734 #endif
735 #if MINIDUMP_PAGE_TRACKING && MINIDUMP_STARTUP_PAGE_TRACKING
736 	/*
737 	 * Include vm_page_array and vm_reserv_array in a crash dump.
738 	 */
739 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
740 		dump_add_page(pa);
741 #endif
742 	phys_avail[biggestone + 1] = new_end;
743 
744 	/*
745 	 * Add physical memory segments corresponding to the available
746 	 * physical pages.
747 	 */
748 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
749 		if (vm_phys_avail_size(i) != 0)
750 			vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
751 
752 	/*
753 	 * Initialize the physical memory allocator.
754 	 */
755 	vm_phys_init();
756 
757 #ifdef VM_FREEPOOL_LAZYINIT
758 	lazyinit = 1;
759 	TUNABLE_INT_FETCH("debug.vm.lazy_page_init", &lazyinit);
760 #endif
761 
762 	/*
763 	 * Initialize the page structures and add every available page to the
764 	 * physical memory allocator's free lists.
765 	 */
766 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
767 	for (ii = 0; ii < vm_page_array_size; ii++) {
768 		m = &vm_page_array[ii];
769 		vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0,
770 		    VM_FREEPOOL_DEFAULT);
771 		m->flags = PG_FICTITIOUS;
772 	}
773 #endif
774 	vm_cnt.v_page_count = 0;
775 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
776 		seg = &vm_phys_segs[segind];
777 
778 		/*
779 		 * If lazy vm_page initialization is not enabled, simply
780 		 * initialize all of the pages in the segment.  Otherwise, we
781 		 * only initialize:
782 		 * 1. Pages not covered by phys_avail[], since they might be
783 		 *    freed to the allocator at some future point, e.g., by
784 		 *    kmem_bootstrap_free().
785 		 * 2. The first page of each run of free pages handed to the
786 		 *    vm_phys allocator, which in turn defers initialization
787 		 *    of pages until they are needed.
788 		 * This avoids blocking the boot process for long periods, which
789 		 * may be relevant for VMs (which ought to boot as quickly as
790 		 * possible) and/or systems with large amounts of physical
791 		 * memory.
792 		 */
793 #ifdef VM_FREEPOOL_LAZYINIT
794 		if (lazyinit) {
795 			startp = seg->start;
796 			for (i = 0; phys_avail[i + 1] != 0; i += 2) {
797 				if (startp >= seg->end)
798 					break;
799 
800 				if (phys_avail[i + 1] < startp)
801 					continue;
802 				if (phys_avail[i] <= startp) {
803 					startp = phys_avail[i + 1];
804 					continue;
805 				}
806 
807 				m = vm_phys_seg_paddr_to_vm_page(seg, startp);
808 				for (endp = MIN(phys_avail[i], seg->end);
809 				    startp < endp; startp += PAGE_SIZE, m++) {
810 					vm_page_init_page(m, startp, segind,
811 					    VM_FREEPOOL_DEFAULT);
812 				}
813 			}
814 		} else
815 #endif
816 			for (m = seg->first_page, pa = seg->start;
817 			    pa < seg->end; m++, pa += PAGE_SIZE) {
818 				vm_page_init_page(m, pa, segind,
819 				    VM_FREEPOOL_DEFAULT);
820 			}
821 
822 		/*
823 		 * Add the segment's pages that are covered by one of
824 		 * phys_avail's ranges to the free lists.
825 		 */
826 		for (i = 0; phys_avail[i + 1] != 0; i += 2) {
827 			if (seg->end <= phys_avail[i] ||
828 			    seg->start >= phys_avail[i + 1])
829 				continue;
830 
831 			startp = MAX(seg->start, phys_avail[i]);
832 			endp = MIN(seg->end, phys_avail[i + 1]);
833 			pagecount = (u_long)atop(endp - startp);
834 			if (pagecount == 0)
835 				continue;
836 
837 			m = vm_phys_seg_paddr_to_vm_page(seg, startp);
838 #ifdef VM_FREEPOOL_LAZYINIT
839 			if (lazyinit) {
840 				vm_page_init_page(m, startp, segind,
841 				    VM_FREEPOOL_LAZYINIT);
842 			}
843 #endif
844 			vmd = VM_DOMAIN(seg->domain);
845 			vm_domain_free_lock(vmd);
846 			vm_phys_enqueue_contig(m, pagecount);
847 			vm_domain_free_unlock(vmd);
848 			vm_domain_freecnt_inc(vmd, pagecount);
849 			vm_cnt.v_page_count += (u_int)pagecount;
850 			vmd->vmd_page_count += (u_int)pagecount;
851 			vmd->vmd_segs |= 1UL << segind;
852 		}
853 	}
854 
855 	/*
856 	 * Remove blacklisted pages from the physical memory allocator.
857 	 */
858 	TAILQ_INIT(&blacklist_head);
859 	vm_page_blacklist_load(&list, &listend);
860 	vm_page_blacklist_check(list, listend);
861 
862 	list = kern_getenv("vm.blacklist");
863 	vm_page_blacklist_check(list, NULL);
864 
865 	freeenv(list);
866 #if VM_NRESERVLEVEL > 0
867 	/*
868 	 * Initialize the reservation management system.
869 	 */
870 	vm_reserv_init();
871 #endif
872 
873 	return (vaddr);
874 }
875 
876 void
vm_page_reference(vm_page_t m)877 vm_page_reference(vm_page_t m)
878 {
879 
880 	vm_page_aflag_set(m, PGA_REFERENCED);
881 }
882 
883 /*
884  *	vm_page_trybusy
885  *
886  *	Helper routine for grab functions to trylock busy.
887  *
888  *	Returns true on success and false on failure.
889  */
890 static bool
vm_page_trybusy(vm_page_t m,int allocflags)891 vm_page_trybusy(vm_page_t m, int allocflags)
892 {
893 
894 	if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
895 		return (vm_page_trysbusy(m));
896 	else
897 		return (vm_page_tryxbusy(m));
898 }
899 
900 /*
901  *	vm_page_tryacquire
902  *
903  *	Helper routine for grab functions to trylock busy and wire.
904  *
905  *	Returns true on success and false on failure.
906  */
907 static inline bool
vm_page_tryacquire(vm_page_t m,int allocflags)908 vm_page_tryacquire(vm_page_t m, int allocflags)
909 {
910 	bool locked;
911 
912 	locked = vm_page_trybusy(m, allocflags);
913 	if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
914 		vm_page_wire(m);
915 	return (locked);
916 }
917 
918 /*
919  *	vm_page_busy_acquire:
920  *
921  *	Acquire the busy lock as described by VM_ALLOC_* flags.  Will loop
922  *	and drop the object lock if necessary.
923  */
924 bool
vm_page_busy_acquire(vm_page_t m,int allocflags)925 vm_page_busy_acquire(vm_page_t m, int allocflags)
926 {
927 	vm_object_t obj;
928 	bool locked;
929 
930 	/*
931 	 * The page-specific object must be cached because page
932 	 * identity can change during the sleep, causing the
933 	 * re-lock of a different object.
934 	 * It is assumed that a reference to the object is already
935 	 * held by the callers.
936 	 */
937 	obj = atomic_load_ptr(&m->object);
938 	for (;;) {
939 		if (vm_page_tryacquire(m, allocflags))
940 			return (true);
941 		if ((allocflags & VM_ALLOC_NOWAIT) != 0)
942 			return (false);
943 		if (obj != NULL)
944 			locked = VM_OBJECT_WOWNED(obj);
945 		else
946 			locked = false;
947 		MPASS(locked || vm_page_wired(m));
948 		if (_vm_page_busy_sleep(obj, m, m->pindex, "vmpba", allocflags,
949 		    locked) && locked)
950 			VM_OBJECT_WLOCK(obj);
951 		if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
952 			return (false);
953 		KASSERT(m->object == obj || m->object == NULL,
954 		    ("vm_page_busy_acquire: page %p does not belong to %p",
955 		    m, obj));
956 	}
957 }
958 
959 /*
960  *	vm_page_busy_downgrade:
961  *
962  *	Downgrade an exclusive busy page into a single shared busy page.
963  */
964 void
vm_page_busy_downgrade(vm_page_t m)965 vm_page_busy_downgrade(vm_page_t m)
966 {
967 	u_int x;
968 
969 	vm_page_assert_xbusied(m);
970 
971 	x = vm_page_busy_fetch(m);
972 	for (;;) {
973 		if (atomic_fcmpset_rel_int(&m->busy_lock,
974 		    &x, VPB_SHARERS_WORD(1)))
975 			break;
976 	}
977 	if ((x & VPB_BIT_WAITERS) != 0)
978 		wakeup(m);
979 }
980 
981 /*
982  *
983  *	vm_page_busy_tryupgrade:
984  *
985  *	Attempt to upgrade a single shared busy into an exclusive busy.
986  */
987 int
vm_page_busy_tryupgrade(vm_page_t m)988 vm_page_busy_tryupgrade(vm_page_t m)
989 {
990 	u_int ce, x;
991 
992 	vm_page_assert_sbusied(m);
993 
994 	x = vm_page_busy_fetch(m);
995 	ce = VPB_CURTHREAD_EXCLUSIVE;
996 	for (;;) {
997 		if (VPB_SHARERS(x) > 1)
998 			return (0);
999 		KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
1000 		    ("vm_page_busy_tryupgrade: invalid lock state"));
1001 		if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
1002 		    ce | (x & VPB_BIT_WAITERS)))
1003 			continue;
1004 		return (1);
1005 	}
1006 }
1007 
1008 /*
1009  *	vm_page_sbusied:
1010  *
1011  *	Return a positive value if the page is shared busied, 0 otherwise.
1012  */
1013 int
vm_page_sbusied(vm_page_t m)1014 vm_page_sbusied(vm_page_t m)
1015 {
1016 	u_int x;
1017 
1018 	x = vm_page_busy_fetch(m);
1019 	return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
1020 }
1021 
1022 /*
1023  *	vm_page_sunbusy:
1024  *
1025  *	Shared unbusy a page.
1026  */
1027 void
vm_page_sunbusy(vm_page_t m)1028 vm_page_sunbusy(vm_page_t m)
1029 {
1030 	u_int x;
1031 
1032 	vm_page_assert_sbusied(m);
1033 
1034 	x = vm_page_busy_fetch(m);
1035 	for (;;) {
1036 		KASSERT(x != VPB_FREED,
1037 		    ("vm_page_sunbusy: Unlocking freed page."));
1038 		if (VPB_SHARERS(x) > 1) {
1039 			if (atomic_fcmpset_int(&m->busy_lock, &x,
1040 			    x - VPB_ONE_SHARER))
1041 				break;
1042 			continue;
1043 		}
1044 		KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
1045 		    ("vm_page_sunbusy: invalid lock state"));
1046 		if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1047 			continue;
1048 		if ((x & VPB_BIT_WAITERS) == 0)
1049 			break;
1050 		wakeup(m);
1051 		break;
1052 	}
1053 }
1054 
1055 /*
1056  *	vm_page_busy_sleep:
1057  *
1058  *	Sleep if the page is busy, using the page pointer as wchan.
1059  *	This is used to implement the hard-path of the busying mechanism.
1060  *
1061  *	If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1062  *	will not sleep if the page is shared-busy.
1063  *
1064  *	The object lock must be held on entry.
1065  *
1066  *	Returns true if it slept and dropped the object lock, or false
1067  *	if there was no sleep and the lock is still held.
1068  */
1069 bool
vm_page_busy_sleep(vm_page_t m,const char * wmesg,int allocflags)1070 vm_page_busy_sleep(vm_page_t m, const char *wmesg, int allocflags)
1071 {
1072 	vm_object_t obj;
1073 
1074 	obj = m->object;
1075 	VM_OBJECT_ASSERT_LOCKED(obj);
1076 
1077 	return (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, allocflags,
1078 	    true));
1079 }
1080 
1081 /*
1082  *	vm_page_busy_sleep_unlocked:
1083  *
1084  *	Sleep if the page is busy, using the page pointer as wchan.
1085  *	This is used to implement the hard-path of busying mechanism.
1086  *
1087  *	If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1088  *	will not sleep if the page is shared-busy.
1089  *
1090  *	The object lock must not be held on entry.  The operation will
1091  *	return if the page changes identity.
1092  */
1093 void
vm_page_busy_sleep_unlocked(vm_object_t obj,vm_page_t m,vm_pindex_t pindex,const char * wmesg,int allocflags)1094 vm_page_busy_sleep_unlocked(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1095     const char *wmesg, int allocflags)
1096 {
1097 	VM_OBJECT_ASSERT_UNLOCKED(obj);
1098 
1099 	(void)_vm_page_busy_sleep(obj, m, pindex, wmesg, allocflags, false);
1100 }
1101 
1102 /*
1103  *	_vm_page_busy_sleep:
1104  *
1105  *	Internal busy sleep function.  Verifies the page identity and
1106  *	lockstate against parameters.  Returns true if it sleeps and
1107  *	false otherwise.
1108  *
1109  *	allocflags uses VM_ALLOC_* flags to specify the lock required.
1110  *
1111  *	If locked is true the lock will be dropped for any true returns
1112  *	and held for any false returns.
1113  */
1114 static bool
_vm_page_busy_sleep(vm_object_t obj,vm_page_t m,vm_pindex_t pindex,const char * wmesg,int allocflags,bool locked)1115 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1116     const char *wmesg, int allocflags, bool locked)
1117 {
1118 	bool xsleep;
1119 	u_int x;
1120 
1121 	/*
1122 	 * If the object is busy we must wait for that to drain to zero
1123 	 * before trying the page again.
1124 	 */
1125 	if (obj != NULL && vm_object_busied(obj)) {
1126 		if (locked)
1127 			VM_OBJECT_DROP(obj);
1128 		vm_object_busy_wait(obj, wmesg);
1129 		return (true);
1130 	}
1131 
1132 	if (!vm_page_busied(m))
1133 		return (false);
1134 
1135 	xsleep = (allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0;
1136 	sleepq_lock(m);
1137 	x = vm_page_busy_fetch(m);
1138 	do {
1139 		/*
1140 		 * If the page changes objects or becomes unlocked we can
1141 		 * simply return.
1142 		 */
1143 		if (x == VPB_UNBUSIED ||
1144 		    (xsleep && (x & VPB_BIT_SHARED) != 0) ||
1145 		    m->object != obj || m->pindex != pindex) {
1146 			sleepq_release(m);
1147 			return (false);
1148 		}
1149 		if ((x & VPB_BIT_WAITERS) != 0)
1150 			break;
1151 	} while (!atomic_fcmpset_int(&m->busy_lock, &x, x | VPB_BIT_WAITERS));
1152 	if (locked)
1153 		VM_OBJECT_DROP(obj);
1154 	DROP_GIANT();
1155 	sleepq_add(m, NULL, wmesg, 0, 0);
1156 	sleepq_wait(m, PVM);
1157 	PICKUP_GIANT();
1158 	return (true);
1159 }
1160 
1161 /*
1162  *	vm_page_trysbusy:
1163  *
1164  *	Try to shared busy a page.
1165  *	If the operation succeeds 1 is returned otherwise 0.
1166  *	The operation never sleeps.
1167  */
1168 int
vm_page_trysbusy(vm_page_t m)1169 vm_page_trysbusy(vm_page_t m)
1170 {
1171 	vm_object_t obj;
1172 	u_int x;
1173 
1174 	obj = m->object;
1175 	x = vm_page_busy_fetch(m);
1176 	for (;;) {
1177 		if ((x & VPB_BIT_SHARED) == 0)
1178 			return (0);
1179 		/*
1180 		 * Reduce the window for transient busies that will trigger
1181 		 * false negatives in vm_page_ps_test().
1182 		 */
1183 		if (obj != NULL && vm_object_busied(obj))
1184 			return (0);
1185 		if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1186 		    x + VPB_ONE_SHARER))
1187 			break;
1188 	}
1189 
1190 	/* Refetch the object now that we're guaranteed that it is stable. */
1191 	obj = m->object;
1192 	if (obj != NULL && vm_object_busied(obj)) {
1193 		vm_page_sunbusy(m);
1194 		return (0);
1195 	}
1196 	return (1);
1197 }
1198 
1199 /*
1200  *	vm_page_tryxbusy:
1201  *
1202  *	Try to exclusive busy a page.
1203  *	If the operation succeeds 1 is returned otherwise 0.
1204  *	The operation never sleeps.
1205  */
1206 int
vm_page_tryxbusy(vm_page_t m)1207 vm_page_tryxbusy(vm_page_t m)
1208 {
1209 	vm_object_t obj;
1210 
1211         if (atomic_cmpset_acq_int(&m->busy_lock, VPB_UNBUSIED,
1212             VPB_CURTHREAD_EXCLUSIVE) == 0)
1213 		return (0);
1214 
1215 	obj = m->object;
1216 	if (obj != NULL && vm_object_busied(obj)) {
1217 		vm_page_xunbusy(m);
1218 		return (0);
1219 	}
1220 	return (1);
1221 }
1222 
1223 static void
vm_page_xunbusy_hard_tail(vm_page_t m)1224 vm_page_xunbusy_hard_tail(vm_page_t m)
1225 {
1226 	atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1227 	/* Wake the waiter. */
1228 	wakeup(m);
1229 }
1230 
1231 /*
1232  *	vm_page_xunbusy_hard:
1233  *
1234  *	Called when unbusy has failed because there is a waiter.
1235  */
1236 void
vm_page_xunbusy_hard(vm_page_t m)1237 vm_page_xunbusy_hard(vm_page_t m)
1238 {
1239 	vm_page_assert_xbusied(m);
1240 	vm_page_xunbusy_hard_tail(m);
1241 }
1242 
1243 void
vm_page_xunbusy_hard_unchecked(vm_page_t m)1244 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1245 {
1246 	vm_page_assert_xbusied_unchecked(m);
1247 	vm_page_xunbusy_hard_tail(m);
1248 }
1249 
1250 static void
vm_page_busy_free(vm_page_t m)1251 vm_page_busy_free(vm_page_t m)
1252 {
1253 	u_int x;
1254 
1255 	atomic_thread_fence_rel();
1256 	x = atomic_swap_int(&m->busy_lock, VPB_FREED);
1257 	if ((x & VPB_BIT_WAITERS) != 0)
1258 		wakeup(m);
1259 }
1260 
1261 /*
1262  *	vm_page_unhold_pages:
1263  *
1264  *	Unhold each of the pages that is referenced by the given array.
1265  */
1266 void
vm_page_unhold_pages(vm_page_t * ma,int count)1267 vm_page_unhold_pages(vm_page_t *ma, int count)
1268 {
1269 
1270 	for (; count != 0; count--) {
1271 		vm_page_unwire(*ma, PQ_ACTIVE);
1272 		ma++;
1273 	}
1274 }
1275 
1276 vm_page_t
PHYS_TO_VM_PAGE(vm_paddr_t pa)1277 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1278 {
1279 	vm_page_t m;
1280 
1281 #ifdef VM_PHYSSEG_SPARSE
1282 	m = vm_phys_paddr_to_vm_page(pa);
1283 	if (m == NULL)
1284 		m = vm_phys_fictitious_to_vm_page(pa);
1285 	return (m);
1286 #elif defined(VM_PHYSSEG_DENSE)
1287 	long pi;
1288 
1289 	pi = atop(pa);
1290 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1291 		m = &vm_page_array[pi - first_page];
1292 		return (m);
1293 	}
1294 	return (vm_phys_fictitious_to_vm_page(pa));
1295 #else
1296 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1297 #endif
1298 }
1299 
1300 /*
1301  *	vm_page_getfake:
1302  *
1303  *	Create a fictitious page with the specified physical address and
1304  *	memory attribute.  The memory attribute is the only the machine-
1305  *	dependent aspect of a fictitious page that must be initialized.
1306  */
1307 vm_page_t
vm_page_getfake(vm_paddr_t paddr,vm_memattr_t memattr)1308 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1309 {
1310 	vm_page_t m;
1311 
1312 	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1313 	vm_page_initfake(m, paddr, memattr);
1314 	return (m);
1315 }
1316 
1317 void
vm_page_initfake(vm_page_t m,vm_paddr_t paddr,vm_memattr_t memattr)1318 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1319 {
1320 
1321 	if ((m->flags & PG_FICTITIOUS) != 0) {
1322 		/*
1323 		 * The page's memattr might have changed since the
1324 		 * previous initialization.  Update the pmap to the
1325 		 * new memattr.
1326 		 */
1327 		goto memattr;
1328 	}
1329 	m->phys_addr = paddr;
1330 	m->a.queue = PQ_NONE;
1331 	/* Fictitious pages don't use "segind". */
1332 	m->flags = PG_FICTITIOUS;
1333 	/* Fictitious pages don't use "order" or "pool". */
1334 	m->oflags = VPO_UNMANAGED;
1335 	m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1336 	/* Fictitious pages are unevictable. */
1337 	m->ref_count = 1;
1338 	pmap_page_init(m);
1339 memattr:
1340 	pmap_page_set_memattr(m, memattr);
1341 }
1342 
1343 /*
1344  *	vm_page_putfake:
1345  *
1346  *	Release a fictitious page.
1347  */
1348 void
vm_page_putfake(vm_page_t m)1349 vm_page_putfake(vm_page_t m)
1350 {
1351 
1352 	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1353 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1354 	    ("vm_page_putfake: bad page %p", m));
1355 	vm_page_assert_xbusied(m);
1356 	vm_page_busy_free(m);
1357 	uma_zfree(fakepg_zone, m);
1358 }
1359 
1360 /*
1361  *	vm_page_updatefake:
1362  *
1363  *	Update the given fictitious page to the specified physical address and
1364  *	memory attribute.
1365  */
1366 void
vm_page_updatefake(vm_page_t m,vm_paddr_t paddr,vm_memattr_t memattr)1367 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1368 {
1369 
1370 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1371 	    ("vm_page_updatefake: bad page %p", m));
1372 	m->phys_addr = paddr;
1373 	pmap_page_set_memattr(m, memattr);
1374 }
1375 
1376 /*
1377  *	vm_page_free:
1378  *
1379  *	Free a page.
1380  */
1381 void
vm_page_free(vm_page_t m)1382 vm_page_free(vm_page_t m)
1383 {
1384 
1385 	m->flags &= ~PG_ZERO;
1386 	vm_page_free_toq(m);
1387 }
1388 
1389 /*
1390  *	vm_page_free_zero:
1391  *
1392  *	Free a page to the zerod-pages queue
1393  */
1394 void
vm_page_free_zero(vm_page_t m)1395 vm_page_free_zero(vm_page_t m)
1396 {
1397 
1398 	m->flags |= PG_ZERO;
1399 	vm_page_free_toq(m);
1400 }
1401 
1402 /*
1403  * Unbusy and handle the page queueing for a page from a getpages request that
1404  * was optionally read ahead or behind.
1405  */
1406 void
vm_page_readahead_finish(vm_page_t m)1407 vm_page_readahead_finish(vm_page_t m)
1408 {
1409 
1410 	/* We shouldn't put invalid pages on queues. */
1411 	KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1412 
1413 	/*
1414 	 * Since the page is not the actually needed one, whether it should
1415 	 * be activated or deactivated is not obvious.  Empirical results
1416 	 * have shown that deactivating the page is usually the best choice,
1417 	 * unless the page is wanted by another thread.
1418 	 */
1419 	if ((vm_page_busy_fetch(m) & VPB_BIT_WAITERS) != 0)
1420 		vm_page_activate(m);
1421 	else
1422 		vm_page_deactivate(m);
1423 	vm_page_xunbusy_unchecked(m);
1424 }
1425 
1426 /*
1427  * Destroy the identity of an invalid page and free it if possible.
1428  * This is intended to be used when reading a page from backing store fails.
1429  */
1430 void
vm_page_free_invalid(vm_page_t m)1431 vm_page_free_invalid(vm_page_t m)
1432 {
1433 
1434 	KASSERT(vm_page_none_valid(m), ("page %p is valid", m));
1435 	KASSERT(!pmap_page_is_mapped(m), ("page %p is mapped", m));
1436 	KASSERT(m->object != NULL, ("page %p has no object", m));
1437 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1438 
1439 	/*
1440 	 * We may be attempting to free the page as part of the handling for an
1441 	 * I/O error, in which case the page was xbusied by a different thread.
1442 	 */
1443 	vm_page_xbusy_claim(m);
1444 
1445 	/*
1446 	 * If someone has wired this page while the object lock
1447 	 * was not held, then the thread that unwires is responsible
1448 	 * for freeing the page.  Otherwise just free the page now.
1449 	 * The wire count of this unmapped page cannot change while
1450 	 * we have the page xbusy and the page's object wlocked.
1451 	 */
1452 	if (vm_page_remove(m))
1453 		vm_page_free(m);
1454 }
1455 
1456 /*
1457  *	vm_page_dirty_KBI:		[ internal use only ]
1458  *
1459  *	Set all bits in the page's dirty field.
1460  *
1461  *	The object containing the specified page must be locked if the
1462  *	call is made from the machine-independent layer.
1463  *
1464  *	See vm_page_clear_dirty_mask().
1465  *
1466  *	This function should only be called by vm_page_dirty().
1467  */
1468 void
vm_page_dirty_KBI(vm_page_t m)1469 vm_page_dirty_KBI(vm_page_t m)
1470 {
1471 
1472 	/* Refer to this operation by its public name. */
1473 	KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1474 	m->dirty = VM_PAGE_BITS_ALL;
1475 }
1476 
1477 /*
1478  * Insert the given page into the given object at the given pindex.  mpred is
1479  * used for memq linkage.  From vm_page_insert, lookup is true, mpred is
1480  * initially NULL, and this procedure looks it up.  From vm_page_insert_after
1481  * and vm_page_iter_insert, lookup is false and mpred is known to the caller
1482  * to be valid, and may be NULL if this will be the page with the lowest
1483  * pindex.
1484  *
1485  * The procedure is marked __always_inline to suggest to the compiler to
1486  * eliminate the lookup parameter and the associated alternate branch.
1487  */
1488 static __always_inline int
vm_page_insert_lookup(vm_page_t m,vm_object_t object,vm_pindex_t pindex,struct pctrie_iter * pages,bool iter,vm_page_t mpred,bool lookup)1489 vm_page_insert_lookup(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1490     struct pctrie_iter *pages, bool iter, vm_page_t mpred, bool lookup)
1491 {
1492 	int error;
1493 
1494 	VM_OBJECT_ASSERT_WLOCKED(object);
1495 	KASSERT(m->object == NULL,
1496 	    ("vm_page_insert: page %p already inserted", m));
1497 
1498 	/*
1499 	 * Record the object/offset pair in this page.
1500 	 */
1501 	m->object = object;
1502 	m->pindex = pindex;
1503 	m->ref_count |= VPRC_OBJREF;
1504 
1505 	/*
1506 	 * Add this page to the object's radix tree, and look up mpred if
1507 	 * needed.
1508 	 */
1509 	if (iter) {
1510 		KASSERT(!lookup, ("%s: cannot lookup mpred", __func__));
1511 		error = vm_radix_iter_insert(pages, m);
1512 	} else if (lookup)
1513 		error = vm_radix_insert_lookup_lt(&object->rtree, m, &mpred);
1514 	else
1515 		error = vm_radix_insert(&object->rtree, m);
1516 	if (__predict_false(error != 0)) {
1517 		m->object = NULL;
1518 		m->pindex = 0;
1519 		m->ref_count &= ~VPRC_OBJREF;
1520 		return (1);
1521 	}
1522 
1523 	/*
1524 	 * Now link into the object's ordered list of backed pages.
1525 	 */
1526 	vm_page_insert_radixdone(m, object, mpred);
1527 	vm_pager_page_inserted(object, m);
1528 	return (0);
1529 }
1530 
1531 /*
1532  *	vm_page_insert:		[ internal use only ]
1533  *
1534  *	Inserts the given mem entry into the object and object list.
1535  *
1536  *	The object must be locked.
1537  */
1538 int
vm_page_insert(vm_page_t m,vm_object_t object,vm_pindex_t pindex)1539 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1540 {
1541 	return (vm_page_insert_lookup(m, object, pindex, NULL, false, NULL,
1542 	    true));
1543 }
1544 
1545 /*
1546  *	vm_page_insert_after:
1547  *
1548  *	Inserts the page "m" into the specified object at offset "pindex".
1549  *
1550  *	The page "mpred" must immediately precede the offset "pindex" within
1551  *	the specified object.
1552  *
1553  *	The object must be locked.
1554  */
1555 static int
vm_page_insert_after(vm_page_t m,vm_object_t object,vm_pindex_t pindex,vm_page_t mpred)1556 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1557     vm_page_t mpred)
1558 {
1559 	return (vm_page_insert_lookup(m, object, pindex, NULL, false, mpred,
1560 	    false));
1561 }
1562 
1563 /*
1564  *	vm_page_iter_insert:
1565  *
1566  *	Tries to insert the page "m" into the specified object at offset
1567  *	"pindex" using the iterator "pages".  Returns 0 if the insertion was
1568  *	successful.
1569  *
1570  *	The page "mpred" must immediately precede the offset "pindex" within
1571  *	the specified object.
1572  *
1573  *	The object must be locked.
1574  */
1575 static int
vm_page_iter_insert(struct pctrie_iter * pages,vm_page_t m,vm_object_t object,vm_pindex_t pindex,vm_page_t mpred)1576 vm_page_iter_insert(struct pctrie_iter *pages, vm_page_t m, vm_object_t object,
1577     vm_pindex_t pindex, vm_page_t mpred)
1578 {
1579 	return (vm_page_insert_lookup(m, object, pindex, pages, true, mpred,
1580 	    false));
1581 }
1582 
1583 /*
1584  *	vm_page_insert_radixdone:
1585  *
1586  *	Complete page "m" insertion into the specified object after the
1587  *	radix trie hooking.
1588  *
1589  *	The page "mpred" must precede the offset "m->pindex" within the
1590  *	specified object.
1591  *
1592  *	The object must be locked.
1593  */
1594 static void
vm_page_insert_radixdone(vm_page_t m,vm_object_t object,vm_page_t mpred)1595 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1596 {
1597 
1598 	VM_OBJECT_ASSERT_WLOCKED(object);
1599 	KASSERT(object != NULL && m->object == object,
1600 	    ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1601 	KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1602 	    ("vm_page_insert_radixdone: page %p is missing object ref", m));
1603 	if (mpred != NULL) {
1604 		KASSERT(mpred->object == object,
1605 		    ("vm_page_insert_radixdone: object doesn't contain mpred"));
1606 		KASSERT(mpred->pindex < m->pindex,
1607 		    ("vm_page_insert_radixdone: mpred doesn't precede pindex"));
1608 		KASSERT(TAILQ_NEXT(mpred, listq) == NULL ||
1609 		    m->pindex < TAILQ_NEXT(mpred, listq)->pindex,
1610 		    ("vm_page_insert_radixdone: pindex doesn't precede msucc"));
1611 	} else {
1612 		KASSERT(TAILQ_EMPTY(&object->memq) ||
1613 		    m->pindex < TAILQ_FIRST(&object->memq)->pindex,
1614 		    ("vm_page_insert_radixdone: no mpred but not first page"));
1615 	}
1616 
1617 	if (mpred != NULL)
1618 		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1619 	else
1620 		TAILQ_INSERT_HEAD(&object->memq, m, listq);
1621 
1622 	/*
1623 	 * Show that the object has one more resident page.
1624 	 */
1625 	object->resident_page_count++;
1626 
1627 	/*
1628 	 * Hold the vnode until the last page is released.
1629 	 */
1630 	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1631 		vhold(object->handle);
1632 
1633 	/*
1634 	 * Since we are inserting a new and possibly dirty page,
1635 	 * update the object's generation count.
1636 	 */
1637 	if (pmap_page_is_write_mapped(m))
1638 		vm_object_set_writeable_dirty(object);
1639 }
1640 
1641 /*
1642  *	vm_page_remove_radixdone
1643  *
1644  *	Complete page "m" removal from the specified object after the radix trie
1645  *	unhooking.
1646  *
1647  *	The caller is responsible for updating the page's fields to reflect this
1648  *	removal.
1649  */
1650 static void
vm_page_remove_radixdone(vm_page_t m)1651 vm_page_remove_radixdone(vm_page_t m)
1652 {
1653 	vm_object_t object;
1654 
1655 	vm_page_assert_xbusied(m);
1656 	object = m->object;
1657 	VM_OBJECT_ASSERT_WLOCKED(object);
1658 	KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1659 	    ("page %p is missing its object ref", m));
1660 
1661 	/* Deferred free of swap space. */
1662 	if ((m->a.flags & PGA_SWAP_FREE) != 0)
1663 		vm_pager_page_unswapped(m);
1664 
1665 	vm_pager_page_removed(object, m);
1666 	m->object = NULL;
1667 
1668 	/*
1669 	 * Now remove from the object's list of backed pages.
1670 	 */
1671 	TAILQ_REMOVE(&object->memq, m, listq);
1672 
1673 	/*
1674 	 * And show that the object has one fewer resident page.
1675 	 */
1676 	object->resident_page_count--;
1677 
1678 	/*
1679 	 * The vnode may now be recycled.
1680 	 */
1681 	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1682 		vdrop(object->handle);
1683 }
1684 
1685 /*
1686  *	vm_page_free_object_prep:
1687  *
1688  *	Disassociates the given page from its VM object.
1689  *
1690  *	The object must be locked, and the page must be xbusy.
1691  */
1692 static void
vm_page_free_object_prep(vm_page_t m)1693 vm_page_free_object_prep(vm_page_t m)
1694 {
1695 	KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
1696 	    ((m->object->flags & OBJ_UNMANAGED) != 0),
1697 	    ("%s: managed flag mismatch for page %p",
1698 	     __func__, m));
1699 	vm_page_assert_xbusied(m);
1700 
1701 	/*
1702 	 * The object reference can be released without an atomic
1703 	 * operation.
1704 	 */
1705 	KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
1706 	    m->ref_count == VPRC_OBJREF,
1707 	    ("%s: page %p has unexpected ref_count %u",
1708 	    __func__, m, m->ref_count));
1709 	vm_page_remove_radixdone(m);
1710 	m->ref_count -= VPRC_OBJREF;
1711 }
1712 
1713 /*
1714  *	vm_page_iter_free:
1715  *
1716  *	Free the current page, as identified by iterator.
1717  */
1718 void
vm_page_iter_free(struct pctrie_iter * pages)1719 vm_page_iter_free(struct pctrie_iter *pages)
1720 {
1721 	vm_page_t m;
1722 
1723 	m = vm_radix_iter_page(pages);
1724 	vm_radix_iter_remove(pages);
1725 	vm_page_free_object_prep(m);
1726 	vm_page_xunbusy(m);
1727 	m->flags &= ~PG_ZERO;
1728 	vm_page_free_toq(m);
1729 }
1730 
1731 /*
1732  *	vm_page_remove:
1733  *
1734  *	Removes the specified page from its containing object, but does not
1735  *	invalidate any backing storage.  Returns true if the object's reference
1736  *	was the last reference to the page, and false otherwise.
1737  *
1738  *	The object must be locked and the page must be exclusively busied.
1739  *	The exclusive busy will be released on return.  If this is not the
1740  *	final ref and the caller does not hold a wire reference it may not
1741  *	continue to access the page.
1742  */
1743 bool
vm_page_remove(vm_page_t m)1744 vm_page_remove(vm_page_t m)
1745 {
1746 	bool dropped;
1747 
1748 	dropped = vm_page_remove_xbusy(m);
1749 	vm_page_xunbusy(m);
1750 
1751 	return (dropped);
1752 }
1753 
1754 /*
1755  *	vm_page_iter_remove:
1756  *
1757  *	Remove the current page, as identified by iterator, and remove it from the
1758  *	radix tree.
1759  */
1760 bool
vm_page_iter_remove(struct pctrie_iter * pages)1761 vm_page_iter_remove(struct pctrie_iter *pages)
1762 {
1763 	vm_page_t m;
1764 	bool dropped;
1765 
1766 	m = vm_radix_iter_page(pages);
1767 	vm_radix_iter_remove(pages);
1768 	vm_page_remove_radixdone(m);
1769 	dropped = (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1770 	vm_page_xunbusy(m);
1771 
1772 	return (dropped);
1773 }
1774 
1775 /*
1776  *	vm_page_radix_remove
1777  *
1778  *	Removes the specified page from the radix tree.
1779  */
1780 static void
vm_page_radix_remove(vm_page_t m)1781 vm_page_radix_remove(vm_page_t m)
1782 {
1783 	vm_page_t mrem __diagused;
1784 
1785 	mrem = vm_radix_remove(&m->object->rtree, m->pindex);
1786 	KASSERT(mrem == m,
1787 	    ("removed page %p, expected page %p", mrem, m));
1788 }
1789 
1790 /*
1791  *	vm_page_remove_xbusy
1792  *
1793  *	Removes the page but leaves the xbusy held.  Returns true if this
1794  *	removed the final ref and false otherwise.
1795  */
1796 bool
vm_page_remove_xbusy(vm_page_t m)1797 vm_page_remove_xbusy(vm_page_t m)
1798 {
1799 
1800 	vm_page_radix_remove(m);
1801 	vm_page_remove_radixdone(m);
1802 	return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1803 }
1804 
1805 /*
1806  *	vm_page_lookup:
1807  *
1808  *	Returns the page associated with the object/offset
1809  *	pair specified; if none is found, NULL is returned.
1810  *
1811  *	The object must be locked.
1812  */
1813 vm_page_t
vm_page_lookup(vm_object_t object,vm_pindex_t pindex)1814 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1815 {
1816 
1817 	VM_OBJECT_ASSERT_LOCKED(object);
1818 	return (vm_radix_lookup(&object->rtree, pindex));
1819 }
1820 
1821 /*
1822  *	vm_page_iter_init:
1823  *
1824  *	Initialize iterator for vm pages.
1825  */
1826 void
vm_page_iter_init(struct pctrie_iter * pages,vm_object_t object)1827 vm_page_iter_init(struct pctrie_iter *pages, vm_object_t object)
1828 {
1829 
1830 	vm_radix_iter_init(pages, &object->rtree);
1831 }
1832 
1833 /*
1834  *	vm_page_iter_init:
1835  *
1836  *	Initialize iterator for vm pages.
1837  */
1838 void
vm_page_iter_limit_init(struct pctrie_iter * pages,vm_object_t object,vm_pindex_t limit)1839 vm_page_iter_limit_init(struct pctrie_iter *pages, vm_object_t object,
1840     vm_pindex_t limit)
1841 {
1842 
1843 	vm_radix_iter_limit_init(pages, &object->rtree, limit);
1844 }
1845 
1846 /*
1847  *	vm_page_iter_lookup:
1848  *
1849  *	Returns the page associated with the object/offset pair specified, and
1850  *	stores the path to its position; if none is found, NULL is returned.
1851  *
1852  *	The iter pctrie must be locked.
1853  */
1854 vm_page_t
vm_page_iter_lookup(struct pctrie_iter * pages,vm_pindex_t pindex)1855 vm_page_iter_lookup(struct pctrie_iter *pages, vm_pindex_t pindex)
1856 {
1857 
1858 	return (vm_radix_iter_lookup(pages, pindex));
1859 }
1860 
1861 /*
1862  *	vm_page_lookup_unlocked:
1863  *
1864  *	Returns the page associated with the object/offset pair specified;
1865  *	if none is found, NULL is returned.  The page may be no longer be
1866  *	present in the object at the time that this function returns.  Only
1867  *	useful for opportunistic checks such as inmem().
1868  */
1869 vm_page_t
vm_page_lookup_unlocked(vm_object_t object,vm_pindex_t pindex)1870 vm_page_lookup_unlocked(vm_object_t object, vm_pindex_t pindex)
1871 {
1872 
1873 	return (vm_radix_lookup_unlocked(&object->rtree, pindex));
1874 }
1875 
1876 /*
1877  *	vm_page_relookup:
1878  *
1879  *	Returns a page that must already have been busied by
1880  *	the caller.  Used for bogus page replacement.
1881  */
1882 vm_page_t
vm_page_relookup(vm_object_t object,vm_pindex_t pindex)1883 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1884 {
1885 	vm_page_t m;
1886 
1887 	m = vm_page_lookup_unlocked(object, pindex);
1888 	KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1889 	    m->object == object && m->pindex == pindex,
1890 	    ("vm_page_relookup: Invalid page %p", m));
1891 	return (m);
1892 }
1893 
1894 /*
1895  * This should only be used by lockless functions for releasing transient
1896  * incorrect acquires.  The page may have been freed after we acquired a
1897  * busy lock.  In this case busy_lock == VPB_FREED and we have nothing
1898  * further to do.
1899  */
1900 static void
vm_page_busy_release(vm_page_t m)1901 vm_page_busy_release(vm_page_t m)
1902 {
1903 	u_int x;
1904 
1905 	x = vm_page_busy_fetch(m);
1906 	for (;;) {
1907 		if (x == VPB_FREED)
1908 			break;
1909 		if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1910 			if (atomic_fcmpset_int(&m->busy_lock, &x,
1911 			    x - VPB_ONE_SHARER))
1912 				break;
1913 			continue;
1914 		}
1915 		KASSERT((x & VPB_BIT_SHARED) != 0 ||
1916 		    (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1917 		    ("vm_page_busy_release: %p xbusy not owned.", m));
1918 		if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1919 			continue;
1920 		if ((x & VPB_BIT_WAITERS) != 0)
1921 			wakeup(m);
1922 		break;
1923 	}
1924 }
1925 
1926 /*
1927  *	vm_page_find_least:
1928  *
1929  *	Returns the page associated with the object with least pindex
1930  *	greater than or equal to the parameter pindex, or NULL.
1931  *
1932  *	The object must be locked.
1933  */
1934 vm_page_t
vm_page_find_least(vm_object_t object,vm_pindex_t pindex)1935 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1936 {
1937 	vm_page_t m;
1938 
1939 	VM_OBJECT_ASSERT_LOCKED(object);
1940 	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1941 		m = vm_radix_lookup_ge(&object->rtree, pindex);
1942 	return (m);
1943 }
1944 
1945 /*
1946  *	vm_page_iter_lookup_ge:
1947  *
1948  *	Returns the page associated with the object with least pindex
1949  *	greater than or equal to the parameter pindex, or NULL.  Initializes the
1950  *	iterator to point to that page.
1951  *
1952  *	The iter pctrie must be locked.
1953  */
1954 vm_page_t
vm_page_iter_lookup_ge(struct pctrie_iter * pages,vm_pindex_t pindex)1955 vm_page_iter_lookup_ge(struct pctrie_iter *pages, vm_pindex_t pindex)
1956 {
1957 
1958 	return (vm_radix_iter_lookup_ge(pages, pindex));
1959 }
1960 
1961 /*
1962  * Returns the given page's successor (by pindex) within the object if it is
1963  * resident; if none is found, NULL is returned.
1964  *
1965  * The object must be locked.
1966  */
1967 vm_page_t
vm_page_next(vm_page_t m)1968 vm_page_next(vm_page_t m)
1969 {
1970 	vm_page_t next;
1971 
1972 	VM_OBJECT_ASSERT_LOCKED(m->object);
1973 	if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1974 		MPASS(next->object == m->object);
1975 		if (next->pindex != m->pindex + 1)
1976 			next = NULL;
1977 	}
1978 	return (next);
1979 }
1980 
1981 /*
1982  * Returns the given page's predecessor (by pindex) within the object if it is
1983  * resident; if none is found, NULL is returned.
1984  *
1985  * The object must be locked.
1986  */
1987 vm_page_t
vm_page_prev(vm_page_t m)1988 vm_page_prev(vm_page_t m)
1989 {
1990 	vm_page_t prev;
1991 
1992 	VM_OBJECT_ASSERT_LOCKED(m->object);
1993 	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1994 		MPASS(prev->object == m->object);
1995 		if (prev->pindex != m->pindex - 1)
1996 			prev = NULL;
1997 	}
1998 	return (prev);
1999 }
2000 
2001 /*
2002  * Uses the page mnew as a replacement for an existing page at index
2003  * pindex which must be already present in the object.
2004  *
2005  * Both pages must be exclusively busied on enter.  The old page is
2006  * unbusied on exit.
2007  *
2008  * A return value of true means mold is now free.  If this is not the
2009  * final ref and the caller does not hold a wire reference it may not
2010  * continue to access the page.
2011  */
2012 static bool
vm_page_replace_hold(vm_page_t mnew,vm_object_t object,vm_pindex_t pindex,vm_page_t mold)2013 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
2014     vm_page_t mold)
2015 {
2016 	vm_page_t mret __diagused;
2017 	bool dropped;
2018 
2019 	VM_OBJECT_ASSERT_WLOCKED(object);
2020 	vm_page_assert_xbusied(mold);
2021 	KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
2022 	    ("vm_page_replace: page %p already in object", mnew));
2023 
2024 	/*
2025 	 * This function mostly follows vm_page_insert() and
2026 	 * vm_page_remove() without the radix, object count and vnode
2027 	 * dance.  Double check such functions for more comments.
2028 	 */
2029 
2030 	mnew->object = object;
2031 	mnew->pindex = pindex;
2032 	atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
2033 	mret = vm_radix_replace(&object->rtree, mnew);
2034 	KASSERT(mret == mold,
2035 	    ("invalid page replacement, mold=%p, mret=%p", mold, mret));
2036 	KASSERT((mold->oflags & VPO_UNMANAGED) ==
2037 	    (mnew->oflags & VPO_UNMANAGED),
2038 	    ("vm_page_replace: mismatched VPO_UNMANAGED"));
2039 
2040 	/* Keep the resident page list in sorted order. */
2041 	TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
2042 	TAILQ_REMOVE(&object->memq, mold, listq);
2043 	mold->object = NULL;
2044 
2045 	/*
2046 	 * The object's resident_page_count does not change because we have
2047 	 * swapped one page for another, but the generation count should
2048 	 * change if the page is dirty.
2049 	 */
2050 	if (pmap_page_is_write_mapped(mnew))
2051 		vm_object_set_writeable_dirty(object);
2052 	dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
2053 	vm_page_xunbusy(mold);
2054 
2055 	return (dropped);
2056 }
2057 
2058 void
vm_page_replace(vm_page_t mnew,vm_object_t object,vm_pindex_t pindex,vm_page_t mold)2059 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
2060     vm_page_t mold)
2061 {
2062 
2063 	vm_page_assert_xbusied(mnew);
2064 
2065 	if (vm_page_replace_hold(mnew, object, pindex, mold))
2066 		vm_page_free(mold);
2067 }
2068 
2069 /*
2070  *	vm_page_rename:
2071  *
2072  *	Move the current page, as identified by iterator, from its current
2073  *	object to the specified target object/offset.
2074  *
2075  *	Note: swap associated with the page must be invalidated by the move.  We
2076  *	      have to do this for several reasons:  (1) we aren't freeing the
2077  *	      page, (2) we are dirtying the page, (3) the VM system is probably
2078  *	      moving the page from object A to B, and will then later move
2079  *	      the backing store from A to B and we can't have a conflict.
2080  *
2081  *	Note: we *always* dirty the page.  It is necessary both for the
2082  *	      fact that we moved it, and because we may be invalidating
2083  *	      swap.
2084  *
2085  *	The objects must be locked.
2086  */
2087 int
vm_page_rename(struct pctrie_iter * pages,vm_object_t new_object,vm_pindex_t new_pindex)2088 vm_page_rename(struct pctrie_iter *pages,
2089     vm_object_t new_object, vm_pindex_t new_pindex)
2090 {
2091 	vm_page_t m, mpred;
2092 	vm_pindex_t opidx;
2093 
2094 	VM_OBJECT_ASSERT_WLOCKED(new_object);
2095 
2096 	m = vm_radix_iter_page(pages);
2097 	KASSERT(m->ref_count != 0, ("vm_page_rename: page %p has no refs", m));
2098 
2099 	/*
2100 	 * Create a custom version of vm_page_insert() which does not depend
2101 	 * by m_prev and can cheat on the implementation aspects of the
2102 	 * function.
2103 	 */
2104 	opidx = m->pindex;
2105 	m->pindex = new_pindex;
2106 	if (vm_radix_insert_lookup_lt(&new_object->rtree, m, &mpred) != 0) {
2107 		m->pindex = opidx;
2108 		return (1);
2109 	}
2110 
2111 	/*
2112 	 * The operation cannot fail anymore.  The removal must happen before
2113 	 * the listq iterator is tainted.
2114 	 */
2115 	m->pindex = opidx;
2116 	vm_radix_iter_remove(pages);
2117 	vm_page_remove_radixdone(m);
2118 
2119 	/* Return back to the new pindex to complete vm_page_insert(). */
2120 	m->pindex = new_pindex;
2121 	m->object = new_object;
2122 
2123 	vm_page_insert_radixdone(m, new_object, mpred);
2124 	vm_page_dirty(m);
2125 	vm_pager_page_inserted(new_object, m);
2126 	return (0);
2127 }
2128 
2129 /*
2130  *	vm_page_mpred:
2131  *
2132  *	Return the greatest page of the object with index <= pindex,
2133  *	or NULL, if there is none.  Assumes object lock is held.
2134  */
2135 vm_page_t
vm_page_mpred(vm_object_t object,vm_pindex_t pindex)2136 vm_page_mpred(vm_object_t object, vm_pindex_t pindex)
2137 {
2138 	return (vm_radix_lookup_le(&object->rtree, pindex));
2139 }
2140 
2141 /*
2142  *	vm_page_alloc:
2143  *
2144  *	Allocate and return a page that is associated with the specified
2145  *	object and offset pair.  By default, this page is exclusive busied.
2146  *
2147  *	The caller must always specify an allocation class.
2148  *
2149  *	allocation classes:
2150  *	VM_ALLOC_NORMAL		normal process request
2151  *	VM_ALLOC_SYSTEM		system *really* needs a page
2152  *	VM_ALLOC_INTERRUPT	interrupt time request
2153  *
2154  *	optional allocation flags:
2155  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
2156  *				intends to allocate
2157  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
2158  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
2159  *	VM_ALLOC_SBUSY		shared busy the allocated page
2160  *	VM_ALLOC_WIRED		wire the allocated page
2161  *	VM_ALLOC_ZERO		prefer a zeroed page
2162  */
2163 vm_page_t
vm_page_alloc(vm_object_t object,vm_pindex_t pindex,int req)2164 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
2165 {
2166 
2167 	return (vm_page_alloc_after(object, pindex, req,
2168 	    vm_page_mpred(object, pindex)));
2169 }
2170 
2171 /*
2172  * Allocate a page in the specified object with the given page index.  To
2173  * optimize insertion of the page into the object, the caller must also specify
2174  * the resident page in the object with largest index smaller than the given
2175  * page index, or NULL if no such page exists.
2176  */
2177 static vm_page_t
vm_page_alloc_after(vm_object_t object,vm_pindex_t pindex,int req,vm_page_t mpred)2178 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
2179     int req, vm_page_t mpred)
2180 {
2181 	struct vm_domainset_iter di;
2182 	vm_page_t m;
2183 	int domain;
2184 
2185 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2186 	do {
2187 		m = vm_page_alloc_domain_after(object, pindex, domain, req,
2188 		    mpred);
2189 		if (m != NULL)
2190 			break;
2191 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
2192 
2193 	return (m);
2194 }
2195 
2196 /*
2197  * Returns true if the number of free pages exceeds the minimum
2198  * for the request class and false otherwise.
2199  */
2200 static int
_vm_domain_allocate(struct vm_domain * vmd,int req_class,int npages)2201 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
2202 {
2203 	u_int limit, old, new;
2204 
2205 	if (req_class == VM_ALLOC_INTERRUPT)
2206 		limit = 0;
2207 	else if (req_class == VM_ALLOC_SYSTEM)
2208 		limit = vmd->vmd_interrupt_free_min;
2209 	else
2210 		limit = vmd->vmd_free_reserved;
2211 
2212 	/*
2213 	 * Attempt to reserve the pages.  Fail if we're below the limit.
2214 	 */
2215 	limit += npages;
2216 	old = atomic_load_int(&vmd->vmd_free_count);
2217 	do {
2218 		if (old < limit)
2219 			return (0);
2220 		new = old - npages;
2221 	} while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
2222 
2223 	/* Wake the page daemon if we've crossed the threshold. */
2224 	if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
2225 		pagedaemon_wakeup(vmd->vmd_domain);
2226 
2227 	/* Only update bitsets on transitions. */
2228 	if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
2229 	    (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2230 		vm_domain_set(vmd);
2231 
2232 	return (1);
2233 }
2234 
2235 int
vm_domain_allocate(struct vm_domain * vmd,int req,int npages)2236 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2237 {
2238 	int req_class;
2239 
2240 	/*
2241 	 * The page daemon is allowed to dig deeper into the free page list.
2242 	 */
2243 	req_class = req & VM_ALLOC_CLASS_MASK;
2244 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2245 		req_class = VM_ALLOC_SYSTEM;
2246 	return (_vm_domain_allocate(vmd, req_class, npages));
2247 }
2248 
2249 vm_page_t
vm_page_alloc_domain_after(vm_object_t object,vm_pindex_t pindex,int domain,int req,vm_page_t mpred)2250 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2251     int req, vm_page_t mpred)
2252 {
2253 	struct vm_domain *vmd;
2254 	vm_page_t m;
2255 	int flags;
2256 
2257 #define	VPA_FLAGS	(VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL |	\
2258 			 VM_ALLOC_NOWAIT | VM_ALLOC_NOBUSY |		\
2259 			 VM_ALLOC_SBUSY | VM_ALLOC_WIRED |		\
2260 			 VM_ALLOC_NODUMP | VM_ALLOC_ZERO |		\
2261 			 VM_ALLOC_NOFREE | VM_ALLOC_COUNT_MASK)
2262 	KASSERT((req & ~VPA_FLAGS) == 0,
2263 	    ("invalid request %#x", req));
2264 	KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2265 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2266 	    ("invalid request %#x", req));
2267 	KASSERT(mpred == NULL || mpred->pindex < pindex,
2268 	    ("mpred %p doesn't precede pindex 0x%jx", mpred,
2269 	    (uintmax_t)pindex));
2270 	VM_OBJECT_ASSERT_WLOCKED(object);
2271 
2272 	flags = 0;
2273 	m = NULL;
2274 	if (!vm_pager_can_alloc_page(object, pindex))
2275 		return (NULL);
2276 again:
2277 	if (__predict_false((req & VM_ALLOC_NOFREE) != 0)) {
2278 		m = vm_page_alloc_nofree_domain(domain, req);
2279 		if (m != NULL)
2280 			goto found;
2281 	}
2282 #if VM_NRESERVLEVEL > 0
2283 	/*
2284 	 * Can we allocate the page from a reservation?
2285 	 */
2286 	if (vm_object_reserv(object) &&
2287 	    (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2288 	    NULL) {
2289 		goto found;
2290 	}
2291 #endif
2292 	vmd = VM_DOMAIN(domain);
2293 	if (vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone != NULL) {
2294 		m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone,
2295 		    M_NOWAIT | M_NOVM);
2296 		if (m != NULL) {
2297 			flags |= PG_PCPU_CACHE;
2298 			goto found;
2299 		}
2300 	}
2301 	if (vm_domain_allocate(vmd, req, 1)) {
2302 		/*
2303 		 * If not, allocate it from the free page queues.
2304 		 */
2305 		vm_domain_free_lock(vmd);
2306 		m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT, 0);
2307 		vm_domain_free_unlock(vmd);
2308 		if (m == NULL) {
2309 			vm_domain_freecnt_inc(vmd, 1);
2310 #if VM_NRESERVLEVEL > 0
2311 			if (vm_reserv_reclaim_inactive(domain))
2312 				goto again;
2313 #endif
2314 		}
2315 	}
2316 	if (m == NULL) {
2317 		/*
2318 		 * Not allocatable, give up.
2319 		 */
2320 		if (vm_domain_alloc_fail(vmd, object, req))
2321 			goto again;
2322 		return (NULL);
2323 	}
2324 
2325 	/*
2326 	 * At this point we had better have found a good page.
2327 	 */
2328 found:
2329 	vm_page_dequeue(m);
2330 	vm_page_alloc_check(m);
2331 
2332 	/*
2333 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
2334 	 */
2335 	flags |= m->flags & PG_ZERO;
2336 	if ((req & VM_ALLOC_NODUMP) != 0)
2337 		flags |= PG_NODUMP;
2338 	if ((req & VM_ALLOC_NOFREE) != 0)
2339 		flags |= PG_NOFREE;
2340 	m->flags = flags;
2341 	m->a.flags = 0;
2342 	m->oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2343 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2344 		m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2345 	else if ((req & VM_ALLOC_SBUSY) != 0)
2346 		m->busy_lock = VPB_SHARERS_WORD(1);
2347 	else
2348 		m->busy_lock = VPB_UNBUSIED;
2349 	if (req & VM_ALLOC_WIRED) {
2350 		vm_wire_add(1);
2351 		m->ref_count = 1;
2352 	}
2353 	m->a.act_count = 0;
2354 
2355 	if (vm_page_insert_after(m, object, pindex, mpred)) {
2356 		if (req & VM_ALLOC_WIRED) {
2357 			vm_wire_sub(1);
2358 			m->ref_count = 0;
2359 		}
2360 		KASSERT(m->object == NULL, ("page %p has object", m));
2361 		m->oflags = VPO_UNMANAGED;
2362 		m->busy_lock = VPB_UNBUSIED;
2363 		/* Don't change PG_ZERO. */
2364 		vm_page_free_toq(m);
2365 		if (req & VM_ALLOC_WAITFAIL) {
2366 			VM_OBJECT_WUNLOCK(object);
2367 			vm_radix_wait();
2368 			VM_OBJECT_WLOCK(object);
2369 		}
2370 		return (NULL);
2371 	}
2372 
2373 	/* Ignore device objects; the pager sets "memattr" for them. */
2374 	if (object->memattr != VM_MEMATTR_DEFAULT &&
2375 	    (object->flags & OBJ_FICTITIOUS) == 0)
2376 		pmap_page_set_memattr(m, object->memattr);
2377 
2378 	return (m);
2379 }
2380 
2381 /*
2382  *	vm_page_alloc_contig:
2383  *
2384  *	Allocate a contiguous set of physical pages of the given size "npages"
2385  *	from the free lists.  All of the physical pages must be at or above
2386  *	the given physical address "low" and below the given physical address
2387  *	"high".  The given value "alignment" determines the alignment of the
2388  *	first physical page in the set.  If the given value "boundary" is
2389  *	non-zero, then the set of physical pages cannot cross any physical
2390  *	address boundary that is a multiple of that value.  Both "alignment"
2391  *	and "boundary" must be a power of two.
2392  *
2393  *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2394  *	then the memory attribute setting for the physical pages is configured
2395  *	to the object's memory attribute setting.  Otherwise, the memory
2396  *	attribute setting for the physical pages is configured to "memattr",
2397  *	overriding the object's memory attribute setting.  However, if the
2398  *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2399  *	memory attribute setting for the physical pages cannot be configured
2400  *	to VM_MEMATTR_DEFAULT.
2401  *
2402  *	The specified object may not contain fictitious pages.
2403  *
2404  *	The caller must always specify an allocation class.
2405  *
2406  *	allocation classes:
2407  *	VM_ALLOC_NORMAL		normal process request
2408  *	VM_ALLOC_SYSTEM		system *really* needs a page
2409  *	VM_ALLOC_INTERRUPT	interrupt time request
2410  *
2411  *	optional allocation flags:
2412  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
2413  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
2414  *	VM_ALLOC_SBUSY		shared busy the allocated page
2415  *	VM_ALLOC_WIRED		wire the allocated page
2416  *	VM_ALLOC_ZERO		prefer a zeroed page
2417  */
2418 vm_page_t
vm_page_alloc_contig(vm_object_t object,vm_pindex_t pindex,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2419 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2420     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2421     vm_paddr_t boundary, vm_memattr_t memattr)
2422 {
2423 	struct vm_domainset_iter di;
2424 	vm_page_t bounds[2];
2425 	vm_page_t m;
2426 	int domain;
2427 	int start_segind;
2428 
2429 	start_segind = -1;
2430 
2431 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2432 	do {
2433 		m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2434 		    npages, low, high, alignment, boundary, memattr);
2435 		if (m != NULL)
2436 			break;
2437 		if (start_segind == -1)
2438 			start_segind = vm_phys_lookup_segind(low);
2439 		if (vm_phys_find_range(bounds, start_segind, domain,
2440 		    npages, low, high) == -1) {
2441 			vm_domainset_iter_ignore(&di, domain);
2442 		}
2443 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
2444 
2445 	return (m);
2446 }
2447 
2448 static vm_page_t
vm_page_find_contig_domain(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)2449 vm_page_find_contig_domain(int domain, int req, u_long npages, vm_paddr_t low,
2450     vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2451 {
2452 	struct vm_domain *vmd;
2453 	vm_page_t m_ret;
2454 
2455 	/*
2456 	 * Can we allocate the pages without the number of free pages falling
2457 	 * below the lower bound for the allocation class?
2458 	 */
2459 	vmd = VM_DOMAIN(domain);
2460 	if (!vm_domain_allocate(vmd, req, npages))
2461 		return (NULL);
2462 	/*
2463 	 * Try to allocate the pages from the free page queues.
2464 	 */
2465 	vm_domain_free_lock(vmd);
2466 	m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2467 	    alignment, boundary);
2468 	vm_domain_free_unlock(vmd);
2469 	if (m_ret != NULL)
2470 		return (m_ret);
2471 #if VM_NRESERVLEVEL > 0
2472 	/*
2473 	 * Try to break a reservation to allocate the pages.
2474 	 */
2475 	if ((req & VM_ALLOC_NORECLAIM) == 0) {
2476 		m_ret = vm_reserv_reclaim_contig(domain, npages, low,
2477 	            high, alignment, boundary);
2478 		if (m_ret != NULL)
2479 			return (m_ret);
2480 	}
2481 #endif
2482 	vm_domain_freecnt_inc(vmd, npages);
2483 	return (NULL);
2484 }
2485 
2486 vm_page_t
vm_page_alloc_contig_domain(vm_object_t object,vm_pindex_t pindex,int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2487 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2488     int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2489     vm_paddr_t boundary, vm_memattr_t memattr)
2490 {
2491 	struct pctrie_iter pages;
2492 	vm_page_t m, m_ret, mpred;
2493 	u_int busy_lock, flags, oflags;
2494 
2495 #define	VPAC_FLAGS	(VPA_FLAGS | VM_ALLOC_NORECLAIM)
2496 	KASSERT((req & ~VPAC_FLAGS) == 0,
2497 	    ("invalid request %#x", req));
2498 	KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2499 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2500 	    ("invalid request %#x", req));
2501 	KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2502 	    (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2503 	    ("invalid request %#x", req));
2504 	VM_OBJECT_ASSERT_WLOCKED(object);
2505 	KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2506 	    ("vm_page_alloc_contig: object %p has fictitious pages",
2507 	    object));
2508 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2509 
2510 	vm_page_iter_init(&pages, object);
2511 	mpred = vm_radix_iter_lookup_le(&pages, pindex);
2512 	KASSERT(mpred == NULL || mpred->pindex != pindex,
2513 	    ("vm_page_alloc_contig: pindex already allocated"));
2514 	for (;;) {
2515 #if VM_NRESERVLEVEL > 0
2516 		/*
2517 		 * Can we allocate the pages from a reservation?
2518 		 */
2519 		if (vm_object_reserv(object) &&
2520 		    (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2521 		    mpred, npages, low, high, alignment, boundary)) != NULL) {
2522 			break;
2523 		}
2524 #endif
2525 		if ((m_ret = vm_page_find_contig_domain(domain, req, npages,
2526 		    low, high, alignment, boundary)) != NULL)
2527 			break;
2528 		if (!vm_domain_alloc_fail(VM_DOMAIN(domain), object, req))
2529 			return (NULL);
2530 	}
2531 
2532 	/*
2533 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
2534 	 */
2535 	flags = PG_ZERO;
2536 	if ((req & VM_ALLOC_NODUMP) != 0)
2537 		flags |= PG_NODUMP;
2538 	oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2539 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2540 		busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2541 	else if ((req & VM_ALLOC_SBUSY) != 0)
2542 		busy_lock = VPB_SHARERS_WORD(1);
2543 	else
2544 		busy_lock = VPB_UNBUSIED;
2545 	if ((req & VM_ALLOC_WIRED) != 0)
2546 		vm_wire_add(npages);
2547 	if (object->memattr != VM_MEMATTR_DEFAULT &&
2548 	    memattr == VM_MEMATTR_DEFAULT)
2549 		memattr = object->memattr;
2550 	for (m = m_ret; m < &m_ret[npages]; m++) {
2551 		vm_page_dequeue(m);
2552 		vm_page_alloc_check(m);
2553 		m->a.flags = 0;
2554 		m->flags = (m->flags | PG_NODUMP) & flags;
2555 		m->busy_lock = busy_lock;
2556 		if ((req & VM_ALLOC_WIRED) != 0)
2557 			m->ref_count = 1;
2558 		m->a.act_count = 0;
2559 		m->oflags = oflags;
2560 		if (vm_page_iter_insert(&pages, m, object, pindex, mpred)) {
2561 			if ((req & VM_ALLOC_WIRED) != 0)
2562 				vm_wire_sub(npages);
2563 			KASSERT(m->object == NULL,
2564 			    ("page %p has object", m));
2565 			mpred = m;
2566 			for (m = m_ret; m < &m_ret[npages]; m++) {
2567 				if (m <= mpred &&
2568 				    (req & VM_ALLOC_WIRED) != 0)
2569 					m->ref_count = 0;
2570 				m->oflags = VPO_UNMANAGED;
2571 				m->busy_lock = VPB_UNBUSIED;
2572 				/* Don't change PG_ZERO. */
2573 				vm_page_free_toq(m);
2574 			}
2575 			if (req & VM_ALLOC_WAITFAIL) {
2576 				VM_OBJECT_WUNLOCK(object);
2577 				vm_radix_wait();
2578 				VM_OBJECT_WLOCK(object);
2579 			}
2580 			return (NULL);
2581 		}
2582 		mpred = m;
2583 		if (memattr != VM_MEMATTR_DEFAULT)
2584 			pmap_page_set_memattr(m, memattr);
2585 		pindex++;
2586 	}
2587 	return (m_ret);
2588 }
2589 
2590 /*
2591  * Allocate a physical page that is not intended to be inserted into a VM
2592  * object.
2593  */
2594 vm_page_t
vm_page_alloc_noobj_domain(int domain,int req)2595 vm_page_alloc_noobj_domain(int domain, int req)
2596 {
2597 	struct vm_domain *vmd;
2598 	vm_page_t m;
2599 	int flags;
2600 
2601 #define	VPAN_FLAGS	(VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL |      \
2602 			 VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |		\
2603 			 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED |		\
2604 			 VM_ALLOC_NODUMP | VM_ALLOC_ZERO |		\
2605 			 VM_ALLOC_NOFREE | VM_ALLOC_COUNT_MASK)
2606 	KASSERT((req & ~VPAN_FLAGS) == 0,
2607 	    ("invalid request %#x", req));
2608 
2609 	flags = ((req & VM_ALLOC_NODUMP) != 0 ? PG_NODUMP : 0) |
2610 	    ((req & VM_ALLOC_NOFREE) != 0 ? PG_NOFREE : 0);
2611 	vmd = VM_DOMAIN(domain);
2612 again:
2613 	if (__predict_false((req & VM_ALLOC_NOFREE) != 0)) {
2614 		m = vm_page_alloc_nofree_domain(domain, req);
2615 		if (m != NULL)
2616 			goto found;
2617 	}
2618 
2619 	if (vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone != NULL) {
2620 		m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone,
2621 		    M_NOWAIT | M_NOVM);
2622 		if (m != NULL) {
2623 			flags |= PG_PCPU_CACHE;
2624 			goto found;
2625 		}
2626 	}
2627 
2628 	if (vm_domain_allocate(vmd, req, 1)) {
2629 		vm_domain_free_lock(vmd);
2630 		m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DIRECT, 0);
2631 		vm_domain_free_unlock(vmd);
2632 		if (m == NULL) {
2633 			vm_domain_freecnt_inc(vmd, 1);
2634 #if VM_NRESERVLEVEL > 0
2635 			if (vm_reserv_reclaim_inactive(domain))
2636 				goto again;
2637 #endif
2638 		}
2639 	}
2640 	if (m == NULL) {
2641 		if (vm_domain_alloc_fail(vmd, NULL, req))
2642 			goto again;
2643 		return (NULL);
2644 	}
2645 
2646 found:
2647 	vm_page_dequeue(m);
2648 	vm_page_alloc_check(m);
2649 
2650 	/*
2651 	 * Consumers should not rely on a useful default pindex value.
2652 	 */
2653 	m->pindex = 0xdeadc0dedeadc0de;
2654 	m->flags = (m->flags & PG_ZERO) | flags;
2655 	m->a.flags = 0;
2656 	m->oflags = VPO_UNMANAGED;
2657 	m->busy_lock = VPB_UNBUSIED;
2658 	if ((req & VM_ALLOC_WIRED) != 0) {
2659 		vm_wire_add(1);
2660 		m->ref_count = 1;
2661 	}
2662 
2663 	if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2664 		pmap_zero_page(m);
2665 
2666 	return (m);
2667 }
2668 
2669 #if VM_NRESERVLEVEL > 1
2670 #define	VM_NOFREE_IMPORT_ORDER	(VM_LEVEL_1_ORDER + VM_LEVEL_0_ORDER)
2671 #elif VM_NRESERVLEVEL > 0
2672 #define	VM_NOFREE_IMPORT_ORDER	VM_LEVEL_0_ORDER
2673 #else
2674 #define	VM_NOFREE_IMPORT_ORDER	8
2675 #endif
2676 
2677 /*
2678  * Allocate a single NOFREE page.
2679  *
2680  * This routine hands out NOFREE pages from higher-order
2681  * physical memory blocks in order to reduce memory fragmentation.
2682  * When a NOFREE for a given domain chunk is used up,
2683  * the routine will try to fetch a new one from the freelists
2684  * and discard the old one.
2685  */
2686 static vm_page_t
vm_page_alloc_nofree_domain(int domain,int req)2687 vm_page_alloc_nofree_domain(int domain, int req)
2688 {
2689 	vm_page_t m;
2690 	struct vm_domain *vmd;
2691 	struct vm_nofreeq *nqp;
2692 
2693 	KASSERT((req & VM_ALLOC_NOFREE) != 0, ("invalid request %#x", req));
2694 
2695 	vmd = VM_DOMAIN(domain);
2696 	nqp = &vmd->vmd_nofreeq;
2697 	vm_domain_free_lock(vmd);
2698 	if (nqp->offs >= (1 << VM_NOFREE_IMPORT_ORDER) || nqp->ma == NULL) {
2699 		if (!vm_domain_allocate(vmd, req,
2700 		    1 << VM_NOFREE_IMPORT_ORDER)) {
2701 			vm_domain_free_unlock(vmd);
2702 			return (NULL);
2703 		}
2704 		nqp->ma = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT,
2705 		    VM_NOFREE_IMPORT_ORDER);
2706 		if (nqp->ma == NULL) {
2707 			vm_domain_freecnt_inc(vmd, 1 << VM_NOFREE_IMPORT_ORDER);
2708 			vm_domain_free_unlock(vmd);
2709 			return (NULL);
2710 		}
2711 		nqp->offs = 0;
2712 	}
2713 	m = &nqp->ma[nqp->offs++];
2714 	vm_domain_free_unlock(vmd);
2715 	VM_CNT_ADD(v_nofree_count, 1);
2716 
2717 	return (m);
2718 }
2719 
2720 vm_page_t
vm_page_alloc_noobj(int req)2721 vm_page_alloc_noobj(int req)
2722 {
2723 	struct vm_domainset_iter di;
2724 	vm_page_t m;
2725 	int domain;
2726 
2727 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2728 	do {
2729 		m = vm_page_alloc_noobj_domain(domain, req);
2730 		if (m != NULL)
2731 			break;
2732 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2733 
2734 	return (m);
2735 }
2736 
2737 vm_page_t
vm_page_alloc_noobj_contig(int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2738 vm_page_alloc_noobj_contig(int req, u_long npages, vm_paddr_t low,
2739     vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2740     vm_memattr_t memattr)
2741 {
2742 	struct vm_domainset_iter di;
2743 	vm_page_t m;
2744 	int domain;
2745 
2746 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2747 	do {
2748 		m = vm_page_alloc_noobj_contig_domain(domain, req, npages, low,
2749 		    high, alignment, boundary, memattr);
2750 		if (m != NULL)
2751 			break;
2752 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2753 
2754 	return (m);
2755 }
2756 
2757 vm_page_t
vm_page_alloc_noobj_contig_domain(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2758 vm_page_alloc_noobj_contig_domain(int domain, int req, u_long npages,
2759     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2760     vm_memattr_t memattr)
2761 {
2762 	vm_page_t m, m_ret;
2763 	u_int flags;
2764 
2765 #define	VPANC_FLAGS	(VPAN_FLAGS | VM_ALLOC_NORECLAIM)
2766 	KASSERT((req & ~VPANC_FLAGS) == 0,
2767 	    ("invalid request %#x", req));
2768 	KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2769 	    (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2770 	    ("invalid request %#x", req));
2771 	KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2772 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2773 	    ("invalid request %#x", req));
2774 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2775 
2776 	while ((m_ret = vm_page_find_contig_domain(domain, req, npages,
2777 	    low, high, alignment, boundary)) == NULL) {
2778 		if (!vm_domain_alloc_fail(VM_DOMAIN(domain), NULL, req))
2779 			return (NULL);
2780 	}
2781 
2782 	/*
2783 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
2784 	 */
2785 	flags = PG_ZERO;
2786 	if ((req & VM_ALLOC_NODUMP) != 0)
2787 		flags |= PG_NODUMP;
2788 	if ((req & VM_ALLOC_WIRED) != 0)
2789 		vm_wire_add(npages);
2790 	for (m = m_ret; m < &m_ret[npages]; m++) {
2791 		vm_page_dequeue(m);
2792 		vm_page_alloc_check(m);
2793 
2794 		/*
2795 		 * Consumers should not rely on a useful default pindex value.
2796 		 */
2797 		m->pindex = 0xdeadc0dedeadc0de;
2798 		m->a.flags = 0;
2799 		m->flags = (m->flags | PG_NODUMP) & flags;
2800 		m->busy_lock = VPB_UNBUSIED;
2801 		if ((req & VM_ALLOC_WIRED) != 0)
2802 			m->ref_count = 1;
2803 		m->a.act_count = 0;
2804 		m->oflags = VPO_UNMANAGED;
2805 
2806 		/*
2807 		 * Zero the page before updating any mappings since the page is
2808 		 * not yet shared with any devices which might require the
2809 		 * non-default memory attribute.  pmap_page_set_memattr()
2810 		 * flushes data caches before returning.
2811 		 */
2812 		if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2813 			pmap_zero_page(m);
2814 		if (memattr != VM_MEMATTR_DEFAULT)
2815 			pmap_page_set_memattr(m, memattr);
2816 	}
2817 	return (m_ret);
2818 }
2819 
2820 /*
2821  * Check a page that has been freshly dequeued from a freelist.
2822  */
2823 static void
vm_page_alloc_check(vm_page_t m)2824 vm_page_alloc_check(vm_page_t m)
2825 {
2826 
2827 	KASSERT(m->object == NULL, ("page %p has object", m));
2828 	KASSERT(m->a.queue == PQ_NONE &&
2829 	    (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2830 	    ("page %p has unexpected queue %d, flags %#x",
2831 	    m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2832 	KASSERT(m->ref_count == 0, ("page %p has references", m));
2833 	KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2834 	KASSERT(m->dirty == 0, ("page %p is dirty", m));
2835 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2836 	    ("page %p has unexpected memattr %d",
2837 	    m, pmap_page_get_memattr(m)));
2838 	KASSERT(vm_page_none_valid(m), ("free page %p is valid", m));
2839 	pmap_vm_page_alloc_check(m);
2840 }
2841 
2842 static int
vm_page_zone_import(void * arg,void ** store,int cnt,int domain,int flags)2843 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2844 {
2845 	struct vm_domain *vmd;
2846 	struct vm_pgcache *pgcache;
2847 	int i;
2848 
2849 	pgcache = arg;
2850 	vmd = VM_DOMAIN(pgcache->domain);
2851 
2852 	/*
2853 	 * The page daemon should avoid creating extra memory pressure since its
2854 	 * main purpose is to replenish the store of free pages.
2855 	 */
2856 	if (vmd->vmd_severeset || curproc == pageproc ||
2857 	    !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2858 		return (0);
2859 	domain = vmd->vmd_domain;
2860 	vm_domain_free_lock(vmd);
2861 	i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2862 	    (vm_page_t *)store);
2863 	vm_domain_free_unlock(vmd);
2864 	if (cnt != i)
2865 		vm_domain_freecnt_inc(vmd, cnt - i);
2866 
2867 	return (i);
2868 }
2869 
2870 static void
vm_page_zone_release(void * arg,void ** store,int cnt)2871 vm_page_zone_release(void *arg, void **store, int cnt)
2872 {
2873 	struct vm_domain *vmd;
2874 	struct vm_pgcache *pgcache;
2875 	vm_page_t m;
2876 	int i;
2877 
2878 	pgcache = arg;
2879 	vmd = VM_DOMAIN(pgcache->domain);
2880 	vm_domain_free_lock(vmd);
2881 	for (i = 0; i < cnt; i++) {
2882 		m = (vm_page_t)store[i];
2883 		vm_phys_free_pages(m, 0);
2884 	}
2885 	vm_domain_free_unlock(vmd);
2886 	vm_domain_freecnt_inc(vmd, cnt);
2887 }
2888 
2889 #define	VPSC_ANY	0	/* No restrictions. */
2890 #define	VPSC_NORESERV	1	/* Skip reservations; implies VPSC_NOSUPER. */
2891 #define	VPSC_NOSUPER	2	/* Skip superpages. */
2892 
2893 /*
2894  *	vm_page_scan_contig:
2895  *
2896  *	Scan vm_page_array[] between the specified entries "m_start" and
2897  *	"m_end" for a run of contiguous physical pages that satisfy the
2898  *	specified conditions, and return the lowest page in the run.  The
2899  *	specified "alignment" determines the alignment of the lowest physical
2900  *	page in the run.  If the specified "boundary" is non-zero, then the
2901  *	run of physical pages cannot span a physical address that is a
2902  *	multiple of "boundary".
2903  *
2904  *	"m_end" is never dereferenced, so it need not point to a vm_page
2905  *	structure within vm_page_array[].
2906  *
2907  *	"npages" must be greater than zero.  "m_start" and "m_end" must not
2908  *	span a hole (or discontiguity) in the physical address space.  Both
2909  *	"alignment" and "boundary" must be a power of two.
2910  */
2911 static vm_page_t
vm_page_scan_contig(u_long npages,vm_page_t m_start,vm_page_t m_end,u_long alignment,vm_paddr_t boundary,int options)2912 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2913     u_long alignment, vm_paddr_t boundary, int options)
2914 {
2915 	vm_object_t object;
2916 	vm_paddr_t pa;
2917 	vm_page_t m, m_run;
2918 #if VM_NRESERVLEVEL > 0
2919 	int level;
2920 #endif
2921 	int m_inc, order, run_ext, run_len;
2922 
2923 	KASSERT(npages > 0, ("npages is 0"));
2924 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2925 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2926 	m_run = NULL;
2927 	run_len = 0;
2928 	for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2929 		KASSERT((m->flags & PG_MARKER) == 0,
2930 		    ("page %p is PG_MARKER", m));
2931 		KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2932 		    ("fictitious page %p has invalid ref count", m));
2933 
2934 		/*
2935 		 * If the current page would be the start of a run, check its
2936 		 * physical address against the end, alignment, and boundary
2937 		 * conditions.  If it doesn't satisfy these conditions, either
2938 		 * terminate the scan or advance to the next page that
2939 		 * satisfies the failed condition.
2940 		 */
2941 		if (run_len == 0) {
2942 			KASSERT(m_run == NULL, ("m_run != NULL"));
2943 			if (m + npages > m_end)
2944 				break;
2945 			pa = VM_PAGE_TO_PHYS(m);
2946 			if (!vm_addr_align_ok(pa, alignment)) {
2947 				m_inc = atop(roundup2(pa, alignment) - pa);
2948 				continue;
2949 			}
2950 			if (!vm_addr_bound_ok(pa, ptoa(npages), boundary)) {
2951 				m_inc = atop(roundup2(pa, boundary) - pa);
2952 				continue;
2953 			}
2954 		} else
2955 			KASSERT(m_run != NULL, ("m_run == NULL"));
2956 
2957 retry:
2958 		m_inc = 1;
2959 		if (vm_page_wired(m))
2960 			run_ext = 0;
2961 #if VM_NRESERVLEVEL > 0
2962 		else if ((level = vm_reserv_level(m)) >= 0 &&
2963 		    (options & VPSC_NORESERV) != 0) {
2964 			run_ext = 0;
2965 			/* Advance to the end of the reservation. */
2966 			pa = VM_PAGE_TO_PHYS(m);
2967 			m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2968 			    pa);
2969 		}
2970 #endif
2971 		else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2972 			/*
2973 			 * The page is considered eligible for relocation if
2974 			 * and only if it could be laundered or reclaimed by
2975 			 * the page daemon.
2976 			 */
2977 			VM_OBJECT_RLOCK(object);
2978 			if (object != m->object) {
2979 				VM_OBJECT_RUNLOCK(object);
2980 				goto retry;
2981 			}
2982 			/* Don't care: PG_NODUMP, PG_ZERO. */
2983 			if ((object->flags & OBJ_SWAP) == 0 &&
2984 			    object->type != OBJT_VNODE) {
2985 				run_ext = 0;
2986 #if VM_NRESERVLEVEL > 0
2987 			} else if ((options & VPSC_NOSUPER) != 0 &&
2988 			    (level = vm_reserv_level_iffullpop(m)) >= 0) {
2989 				run_ext = 0;
2990 				/* Advance to the end of the superpage. */
2991 				pa = VM_PAGE_TO_PHYS(m);
2992 				m_inc = atop(roundup2(pa + 1,
2993 				    vm_reserv_size(level)) - pa);
2994 #endif
2995 			} else if (object->memattr == VM_MEMATTR_DEFAULT &&
2996 			    vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2997 				/*
2998 				 * The page is allocated but eligible for
2999 				 * relocation.  Extend the current run by one
3000 				 * page.
3001 				 */
3002 				KASSERT(pmap_page_get_memattr(m) ==
3003 				    VM_MEMATTR_DEFAULT,
3004 				    ("page %p has an unexpected memattr", m));
3005 				KASSERT((m->oflags & (VPO_SWAPINPROG |
3006 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
3007 				    ("page %p has unexpected oflags", m));
3008 				/* Don't care: PGA_NOSYNC. */
3009 				run_ext = 1;
3010 			} else
3011 				run_ext = 0;
3012 			VM_OBJECT_RUNLOCK(object);
3013 #if VM_NRESERVLEVEL > 0
3014 		} else if (level >= 0) {
3015 			/*
3016 			 * The page is reserved but not yet allocated.  In
3017 			 * other words, it is still free.  Extend the current
3018 			 * run by one page.
3019 			 */
3020 			run_ext = 1;
3021 #endif
3022 		} else if ((order = m->order) < VM_NFREEORDER) {
3023 			/*
3024 			 * The page is enqueued in the physical memory
3025 			 * allocator's free page queues.  Moreover, it is the
3026 			 * first page in a power-of-two-sized run of
3027 			 * contiguous free pages.  Add these pages to the end
3028 			 * of the current run, and jump ahead.
3029 			 */
3030 			run_ext = 1 << order;
3031 			m_inc = 1 << order;
3032 		} else {
3033 			/*
3034 			 * Skip the page for one of the following reasons: (1)
3035 			 * It is enqueued in the physical memory allocator's
3036 			 * free page queues.  However, it is not the first
3037 			 * page in a run of contiguous free pages.  (This case
3038 			 * rarely occurs because the scan is performed in
3039 			 * ascending order.) (2) It is not reserved, and it is
3040 			 * transitioning from free to allocated.  (Conversely,
3041 			 * the transition from allocated to free for managed
3042 			 * pages is blocked by the page busy lock.) (3) It is
3043 			 * allocated but not contained by an object and not
3044 			 * wired, e.g., allocated by Xen's balloon driver.
3045 			 */
3046 			run_ext = 0;
3047 		}
3048 
3049 		/*
3050 		 * Extend or reset the current run of pages.
3051 		 */
3052 		if (run_ext > 0) {
3053 			if (run_len == 0)
3054 				m_run = m;
3055 			run_len += run_ext;
3056 		} else {
3057 			if (run_len > 0) {
3058 				m_run = NULL;
3059 				run_len = 0;
3060 			}
3061 		}
3062 	}
3063 	if (run_len >= npages)
3064 		return (m_run);
3065 	return (NULL);
3066 }
3067 
3068 /*
3069  *	vm_page_reclaim_run:
3070  *
3071  *	Try to relocate each of the allocated virtual pages within the
3072  *	specified run of physical pages to a new physical address.  Free the
3073  *	physical pages underlying the relocated virtual pages.  A virtual page
3074  *	is relocatable if and only if it could be laundered or reclaimed by
3075  *	the page daemon.  Whenever possible, a virtual page is relocated to a
3076  *	physical address above "high".
3077  *
3078  *	Returns 0 if every physical page within the run was already free or
3079  *	just freed by a successful relocation.  Otherwise, returns a non-zero
3080  *	value indicating why the last attempt to relocate a virtual page was
3081  *	unsuccessful.
3082  *
3083  *	"req_class" must be an allocation class.
3084  */
3085 static int
vm_page_reclaim_run(int req_class,int domain,u_long npages,vm_page_t m_run,vm_paddr_t high)3086 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
3087     vm_paddr_t high)
3088 {
3089 	struct vm_domain *vmd;
3090 	struct spglist free;
3091 	vm_object_t object;
3092 	vm_paddr_t pa;
3093 	vm_page_t m, m_end, m_new;
3094 	int error, order, req;
3095 
3096 	KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
3097 	    ("req_class is not an allocation class"));
3098 	SLIST_INIT(&free);
3099 	error = 0;
3100 	m = m_run;
3101 	m_end = m_run + npages;
3102 	for (; error == 0 && m < m_end; m++) {
3103 		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
3104 		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
3105 
3106 		/*
3107 		 * Racily check for wirings.  Races are handled once the object
3108 		 * lock is held and the page is unmapped.
3109 		 */
3110 		if (vm_page_wired(m))
3111 			error = EBUSY;
3112 		else if ((object = atomic_load_ptr(&m->object)) != NULL) {
3113 			/*
3114 			 * The page is relocated if and only if it could be
3115 			 * laundered or reclaimed by the page daemon.
3116 			 */
3117 			VM_OBJECT_WLOCK(object);
3118 			/* Don't care: PG_NODUMP, PG_ZERO. */
3119 			if (m->object != object ||
3120 			    ((object->flags & OBJ_SWAP) == 0 &&
3121 			    object->type != OBJT_VNODE))
3122 				error = EINVAL;
3123 			else if (object->memattr != VM_MEMATTR_DEFAULT)
3124 				error = EINVAL;
3125 			else if (vm_page_queue(m) != PQ_NONE &&
3126 			    vm_page_tryxbusy(m) != 0) {
3127 				if (vm_page_wired(m)) {
3128 					vm_page_xunbusy(m);
3129 					error = EBUSY;
3130 					goto unlock;
3131 				}
3132 				KASSERT(pmap_page_get_memattr(m) ==
3133 				    VM_MEMATTR_DEFAULT,
3134 				    ("page %p has an unexpected memattr", m));
3135 				KASSERT(m->oflags == 0,
3136 				    ("page %p has unexpected oflags", m));
3137 				/* Don't care: PGA_NOSYNC. */
3138 				if (!vm_page_none_valid(m)) {
3139 					/*
3140 					 * First, try to allocate a new page
3141 					 * that is above "high".  Failing
3142 					 * that, try to allocate a new page
3143 					 * that is below "m_run".  Allocate
3144 					 * the new page between the end of
3145 					 * "m_run" and "high" only as a last
3146 					 * resort.
3147 					 */
3148 					req = req_class;
3149 					if ((m->flags & PG_NODUMP) != 0)
3150 						req |= VM_ALLOC_NODUMP;
3151 					if (trunc_page(high) !=
3152 					    ~(vm_paddr_t)PAGE_MASK) {
3153 						m_new =
3154 						    vm_page_alloc_noobj_contig(
3155 						    req, 1, round_page(high),
3156 						    ~(vm_paddr_t)0, PAGE_SIZE,
3157 						    0, VM_MEMATTR_DEFAULT);
3158 					} else
3159 						m_new = NULL;
3160 					if (m_new == NULL) {
3161 						pa = VM_PAGE_TO_PHYS(m_run);
3162 						m_new =
3163 						    vm_page_alloc_noobj_contig(
3164 						    req, 1, 0, pa - 1,
3165 						    PAGE_SIZE, 0,
3166 						    VM_MEMATTR_DEFAULT);
3167 					}
3168 					if (m_new == NULL) {
3169 						pa += ptoa(npages);
3170 						m_new =
3171 						    vm_page_alloc_noobj_contig(
3172 						    req, 1, pa, high, PAGE_SIZE,
3173 						    0, VM_MEMATTR_DEFAULT);
3174 					}
3175 					if (m_new == NULL) {
3176 						vm_page_xunbusy(m);
3177 						error = ENOMEM;
3178 						goto unlock;
3179 					}
3180 
3181 					/*
3182 					 * Unmap the page and check for new
3183 					 * wirings that may have been acquired
3184 					 * through a pmap lookup.
3185 					 */
3186 					if (object->ref_count != 0 &&
3187 					    !vm_page_try_remove_all(m)) {
3188 						vm_page_xunbusy(m);
3189 						vm_page_free(m_new);
3190 						error = EBUSY;
3191 						goto unlock;
3192 					}
3193 
3194 					/*
3195 					 * Replace "m" with the new page.  For
3196 					 * vm_page_replace(), "m" must be busy
3197 					 * and dequeued.  Finally, change "m"
3198 					 * as if vm_page_free() was called.
3199 					 */
3200 					m_new->a.flags = m->a.flags &
3201 					    ~PGA_QUEUE_STATE_MASK;
3202 					KASSERT(m_new->oflags == VPO_UNMANAGED,
3203 					    ("page %p is managed", m_new));
3204 					m_new->oflags = 0;
3205 					pmap_copy_page(m, m_new);
3206 					m_new->valid = m->valid;
3207 					m_new->dirty = m->dirty;
3208 					m->flags &= ~PG_ZERO;
3209 					vm_page_dequeue(m);
3210 					if (vm_page_replace_hold(m_new, object,
3211 					    m->pindex, m) &&
3212 					    vm_page_free_prep(m))
3213 						SLIST_INSERT_HEAD(&free, m,
3214 						    plinks.s.ss);
3215 
3216 					/*
3217 					 * The new page must be deactivated
3218 					 * before the object is unlocked.
3219 					 */
3220 					vm_page_deactivate(m_new);
3221 				} else {
3222 					m->flags &= ~PG_ZERO;
3223 					vm_page_dequeue(m);
3224 					if (vm_page_free_prep(m))
3225 						SLIST_INSERT_HEAD(&free, m,
3226 						    plinks.s.ss);
3227 					KASSERT(m->dirty == 0,
3228 					    ("page %p is dirty", m));
3229 				}
3230 			} else
3231 				error = EBUSY;
3232 unlock:
3233 			VM_OBJECT_WUNLOCK(object);
3234 		} else {
3235 			MPASS(vm_page_domain(m) == domain);
3236 			vmd = VM_DOMAIN(domain);
3237 			vm_domain_free_lock(vmd);
3238 			order = m->order;
3239 			if (order < VM_NFREEORDER) {
3240 				/*
3241 				 * The page is enqueued in the physical memory
3242 				 * allocator's free page queues.  Moreover, it
3243 				 * is the first page in a power-of-two-sized
3244 				 * run of contiguous free pages.  Jump ahead
3245 				 * to the last page within that run, and
3246 				 * continue from there.
3247 				 */
3248 				m += (1 << order) - 1;
3249 			}
3250 #if VM_NRESERVLEVEL > 0
3251 			else if (vm_reserv_is_page_free(m))
3252 				order = 0;
3253 #endif
3254 			vm_domain_free_unlock(vmd);
3255 			if (order == VM_NFREEORDER)
3256 				error = EINVAL;
3257 		}
3258 	}
3259 	if ((m = SLIST_FIRST(&free)) != NULL) {
3260 		int cnt;
3261 
3262 		vmd = VM_DOMAIN(domain);
3263 		cnt = 0;
3264 		vm_domain_free_lock(vmd);
3265 		do {
3266 			MPASS(vm_page_domain(m) == domain);
3267 			SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3268 			vm_phys_free_pages(m, 0);
3269 			cnt++;
3270 		} while ((m = SLIST_FIRST(&free)) != NULL);
3271 		vm_domain_free_unlock(vmd);
3272 		vm_domain_freecnt_inc(vmd, cnt);
3273 	}
3274 	return (error);
3275 }
3276 
3277 #define	NRUNS	16
3278 
3279 #define	RUN_INDEX(count, nruns)	((count) % (nruns))
3280 
3281 #define	MIN_RECLAIM	8
3282 
3283 /*
3284  *	vm_page_reclaim_contig:
3285  *
3286  *	Reclaim allocated, contiguous physical memory satisfying the specified
3287  *	conditions by relocating the virtual pages using that physical memory.
3288  *	Returns 0 if reclamation is successful, ERANGE if the specified domain
3289  *	can't possibly satisfy the reclamation request, or ENOMEM if not
3290  *	currently able to reclaim the requested number of pages.  Since
3291  *	relocation requires the allocation of physical pages, reclamation may
3292  *	fail with ENOMEM due to a shortage of free pages.  When reclamation
3293  *	fails in this manner, callers are expected to perform vm_wait() before
3294  *	retrying a failed allocation operation, e.g., vm_page_alloc_contig().
3295  *
3296  *	The caller must always specify an allocation class through "req".
3297  *
3298  *	allocation classes:
3299  *	VM_ALLOC_NORMAL		normal process request
3300  *	VM_ALLOC_SYSTEM		system *really* needs a page
3301  *	VM_ALLOC_INTERRUPT	interrupt time request
3302  *
3303  *	The optional allocation flags are ignored.
3304  *
3305  *	"npages" must be greater than zero.  Both "alignment" and "boundary"
3306  *	must be a power of two.
3307  */
3308 int
vm_page_reclaim_contig_domain_ext(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,int desired_runs)3309 vm_page_reclaim_contig_domain_ext(int domain, int req, u_long npages,
3310     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
3311     int desired_runs)
3312 {
3313 	struct vm_domain *vmd;
3314 	vm_page_t bounds[2], m_run, _m_runs[NRUNS], *m_runs;
3315 	u_long count, minalign, reclaimed;
3316 	int error, i, min_reclaim, nruns, options, req_class;
3317 	int segind, start_segind;
3318 	int ret;
3319 
3320 	KASSERT(npages > 0, ("npages is 0"));
3321 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
3322 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
3323 
3324 	ret = ENOMEM;
3325 
3326 	/*
3327 	 * If the caller wants to reclaim multiple runs, try to allocate
3328 	 * space to store the runs.  If that fails, fall back to the old
3329 	 * behavior of just reclaiming MIN_RECLAIM pages.
3330 	 */
3331 	if (desired_runs > 1)
3332 		m_runs = malloc((NRUNS + desired_runs) * sizeof(*m_runs),
3333 		    M_TEMP, M_NOWAIT);
3334 	else
3335 		m_runs = NULL;
3336 
3337 	if (m_runs == NULL) {
3338 		m_runs = _m_runs;
3339 		nruns = NRUNS;
3340 	} else {
3341 		nruns = NRUNS + desired_runs - 1;
3342 	}
3343 	min_reclaim = MAX(desired_runs * npages, MIN_RECLAIM);
3344 
3345 	/*
3346 	 * The caller will attempt an allocation after some runs have been
3347 	 * reclaimed and added to the vm_phys buddy lists.  Due to limitations
3348 	 * of vm_phys_alloc_contig(), round up the requested length to the next
3349 	 * power of two or maximum chunk size, and ensure that each run is
3350 	 * suitably aligned.
3351 	 */
3352 	minalign = 1ul << imin(flsl(npages - 1), VM_NFREEORDER - 1);
3353 	npages = roundup2(npages, minalign);
3354 	if (alignment < ptoa(minalign))
3355 		alignment = ptoa(minalign);
3356 
3357 	/*
3358 	 * The page daemon is allowed to dig deeper into the free page list.
3359 	 */
3360 	req_class = req & VM_ALLOC_CLASS_MASK;
3361 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
3362 		req_class = VM_ALLOC_SYSTEM;
3363 
3364 	start_segind = vm_phys_lookup_segind(low);
3365 
3366 	/*
3367 	 * Return if the number of free pages cannot satisfy the requested
3368 	 * allocation.
3369 	 */
3370 	vmd = VM_DOMAIN(domain);
3371 	count = vmd->vmd_free_count;
3372 	if (count < npages + vmd->vmd_free_reserved || (count < npages +
3373 	    vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
3374 	    (count < npages && req_class == VM_ALLOC_INTERRUPT))
3375 		goto done;
3376 
3377 	/*
3378 	 * Scan up to three times, relaxing the restrictions ("options") on
3379 	 * the reclamation of reservations and superpages each time.
3380 	 */
3381 	for (options = VPSC_NORESERV;;) {
3382 		bool phys_range_exists = false;
3383 
3384 		/*
3385 		 * Find the highest runs that satisfy the given constraints
3386 		 * and restrictions, and record them in "m_runs".
3387 		 */
3388 		count = 0;
3389 		segind = start_segind;
3390 		while ((segind = vm_phys_find_range(bounds, segind, domain,
3391 		    npages, low, high)) != -1) {
3392 			phys_range_exists = true;
3393 			while ((m_run = vm_page_scan_contig(npages, bounds[0],
3394 			    bounds[1], alignment, boundary, options))) {
3395 				bounds[0] = m_run + npages;
3396 				m_runs[RUN_INDEX(count, nruns)] = m_run;
3397 				count++;
3398 			}
3399 			segind++;
3400 		}
3401 
3402 		if (!phys_range_exists) {
3403 			ret = ERANGE;
3404 			goto done;
3405 		}
3406 
3407 		/*
3408 		 * Reclaim the highest runs in LIFO (descending) order until
3409 		 * the number of reclaimed pages, "reclaimed", is at least
3410 		 * "min_reclaim".  Reset "reclaimed" each time because each
3411 		 * reclamation is idempotent, and runs will (likely) recur
3412 		 * from one scan to the next as restrictions are relaxed.
3413 		 */
3414 		reclaimed = 0;
3415 		for (i = 0; count > 0 && i < nruns; i++) {
3416 			count--;
3417 			m_run = m_runs[RUN_INDEX(count, nruns)];
3418 			error = vm_page_reclaim_run(req_class, domain, npages,
3419 			    m_run, high);
3420 			if (error == 0) {
3421 				reclaimed += npages;
3422 				if (reclaimed >= min_reclaim) {
3423 					ret = 0;
3424 					goto done;
3425 				}
3426 			}
3427 		}
3428 
3429 		/*
3430 		 * Either relax the restrictions on the next scan or return if
3431 		 * the last scan had no restrictions.
3432 		 */
3433 		if (options == VPSC_NORESERV)
3434 			options = VPSC_NOSUPER;
3435 		else if (options == VPSC_NOSUPER)
3436 			options = VPSC_ANY;
3437 		else if (options == VPSC_ANY) {
3438 			if (reclaimed != 0)
3439 				ret = 0;
3440 			goto done;
3441 		}
3442 	}
3443 done:
3444 	if (m_runs != _m_runs)
3445 		free(m_runs, M_TEMP);
3446 	return (ret);
3447 }
3448 
3449 int
vm_page_reclaim_contig_domain(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)3450 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
3451     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
3452 {
3453 	return (vm_page_reclaim_contig_domain_ext(domain, req, npages, low, high,
3454 	    alignment, boundary, 1));
3455 }
3456 
3457 int
vm_page_reclaim_contig(int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)3458 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3459     u_long alignment, vm_paddr_t boundary)
3460 {
3461 	struct vm_domainset_iter di;
3462 	int domain, ret, status;
3463 
3464 	ret = ERANGE;
3465 
3466 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3467 	do {
3468 		status = vm_page_reclaim_contig_domain(domain, req, npages, low,
3469 		    high, alignment, boundary);
3470 		if (status == 0)
3471 			return (0);
3472 		else if (status == ERANGE)
3473 			vm_domainset_iter_ignore(&di, domain);
3474 		else {
3475 			KASSERT(status == ENOMEM, ("Unrecognized error %d "
3476 			    "from vm_page_reclaim_contig_domain()", status));
3477 			ret = ENOMEM;
3478 		}
3479 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3480 
3481 	return (ret);
3482 }
3483 
3484 /*
3485  * Set the domain in the appropriate page level domainset.
3486  */
3487 void
vm_domain_set(struct vm_domain * vmd)3488 vm_domain_set(struct vm_domain *vmd)
3489 {
3490 
3491 	mtx_lock(&vm_domainset_lock);
3492 	if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3493 		vmd->vmd_minset = 1;
3494 		DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3495 	}
3496 	if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3497 		vmd->vmd_severeset = 1;
3498 		DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3499 	}
3500 	mtx_unlock(&vm_domainset_lock);
3501 }
3502 
3503 /*
3504  * Clear the domain from the appropriate page level domainset.
3505  */
3506 void
vm_domain_clear(struct vm_domain * vmd)3507 vm_domain_clear(struct vm_domain *vmd)
3508 {
3509 
3510 	mtx_lock(&vm_domainset_lock);
3511 	if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3512 		vmd->vmd_minset = 0;
3513 		DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3514 		if (vm_min_waiters != 0) {
3515 			vm_min_waiters = 0;
3516 			wakeup(&vm_min_domains);
3517 		}
3518 	}
3519 	if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3520 		vmd->vmd_severeset = 0;
3521 		DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3522 		if (vm_severe_waiters != 0) {
3523 			vm_severe_waiters = 0;
3524 			wakeup(&vm_severe_domains);
3525 		}
3526 	}
3527 
3528 	/*
3529 	 * If pageout daemon needs pages, then tell it that there are
3530 	 * some free.
3531 	 */
3532 	if (vmd->vmd_pageout_pages_needed &&
3533 	    vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3534 		wakeup(&vmd->vmd_pageout_pages_needed);
3535 		vmd->vmd_pageout_pages_needed = 0;
3536 	}
3537 
3538 	/* See comments in vm_wait_doms(). */
3539 	if (vm_pageproc_waiters) {
3540 		vm_pageproc_waiters = 0;
3541 		wakeup(&vm_pageproc_waiters);
3542 	}
3543 	mtx_unlock(&vm_domainset_lock);
3544 }
3545 
3546 /*
3547  * Wait for free pages to exceed the min threshold globally.
3548  */
3549 void
vm_wait_min(void)3550 vm_wait_min(void)
3551 {
3552 
3553 	mtx_lock(&vm_domainset_lock);
3554 	while (vm_page_count_min()) {
3555 		vm_min_waiters++;
3556 		msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3557 	}
3558 	mtx_unlock(&vm_domainset_lock);
3559 }
3560 
3561 /*
3562  * Wait for free pages to exceed the severe threshold globally.
3563  */
3564 void
vm_wait_severe(void)3565 vm_wait_severe(void)
3566 {
3567 
3568 	mtx_lock(&vm_domainset_lock);
3569 	while (vm_page_count_severe()) {
3570 		vm_severe_waiters++;
3571 		msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3572 		    "vmwait", 0);
3573 	}
3574 	mtx_unlock(&vm_domainset_lock);
3575 }
3576 
3577 u_int
vm_wait_count(void)3578 vm_wait_count(void)
3579 {
3580 
3581 	return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3582 }
3583 
3584 int
vm_wait_doms(const domainset_t * wdoms,int mflags)3585 vm_wait_doms(const domainset_t *wdoms, int mflags)
3586 {
3587 	int error;
3588 
3589 	error = 0;
3590 
3591 	/*
3592 	 * We use racey wakeup synchronization to avoid expensive global
3593 	 * locking for the pageproc when sleeping with a non-specific vm_wait.
3594 	 * To handle this, we only sleep for one tick in this instance.  It
3595 	 * is expected that most allocations for the pageproc will come from
3596 	 * kmem or vm_page_grab* which will use the more specific and
3597 	 * race-free vm_wait_domain().
3598 	 */
3599 	if (curproc == pageproc) {
3600 		mtx_lock(&vm_domainset_lock);
3601 		vm_pageproc_waiters++;
3602 		error = msleep(&vm_pageproc_waiters, &vm_domainset_lock,
3603 		    PVM | PDROP | mflags, "pageprocwait", 1);
3604 	} else {
3605 		/*
3606 		 * XXX Ideally we would wait only until the allocation could
3607 		 * be satisfied.  This condition can cause new allocators to
3608 		 * consume all freed pages while old allocators wait.
3609 		 */
3610 		mtx_lock(&vm_domainset_lock);
3611 		if (vm_page_count_min_set(wdoms)) {
3612 			if (pageproc == NULL)
3613 				panic("vm_wait in early boot");
3614 			vm_min_waiters++;
3615 			error = msleep(&vm_min_domains, &vm_domainset_lock,
3616 			    PVM | PDROP | mflags, "vmwait", 0);
3617 		} else
3618 			mtx_unlock(&vm_domainset_lock);
3619 	}
3620 	return (error);
3621 }
3622 
3623 /*
3624  *	vm_wait_domain:
3625  *
3626  *	Sleep until free pages are available for allocation.
3627  *	- Called in various places after failed memory allocations.
3628  */
3629 void
vm_wait_domain(int domain)3630 vm_wait_domain(int domain)
3631 {
3632 	struct vm_domain *vmd;
3633 	domainset_t wdom;
3634 
3635 	vmd = VM_DOMAIN(domain);
3636 	vm_domain_free_assert_unlocked(vmd);
3637 
3638 	if (curproc == pageproc) {
3639 		mtx_lock(&vm_domainset_lock);
3640 		if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3641 			vmd->vmd_pageout_pages_needed = 1;
3642 			msleep(&vmd->vmd_pageout_pages_needed,
3643 			    &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3644 		} else
3645 			mtx_unlock(&vm_domainset_lock);
3646 	} else {
3647 		DOMAINSET_ZERO(&wdom);
3648 		DOMAINSET_SET(vmd->vmd_domain, &wdom);
3649 		vm_wait_doms(&wdom, 0);
3650 	}
3651 }
3652 
3653 static int
vm_wait_flags(vm_object_t obj,int mflags)3654 vm_wait_flags(vm_object_t obj, int mflags)
3655 {
3656 	struct domainset *d;
3657 
3658 	d = NULL;
3659 
3660 	/*
3661 	 * Carefully fetch pointers only once: the struct domainset
3662 	 * itself is ummutable but the pointer might change.
3663 	 */
3664 	if (obj != NULL)
3665 		d = obj->domain.dr_policy;
3666 	if (d == NULL)
3667 		d = curthread->td_domain.dr_policy;
3668 
3669 	return (vm_wait_doms(&d->ds_mask, mflags));
3670 }
3671 
3672 /*
3673  *	vm_wait:
3674  *
3675  *	Sleep until free pages are available for allocation in the
3676  *	affinity domains of the obj.  If obj is NULL, the domain set
3677  *	for the calling thread is used.
3678  *	Called in various places after failed memory allocations.
3679  */
3680 void
vm_wait(vm_object_t obj)3681 vm_wait(vm_object_t obj)
3682 {
3683 	(void)vm_wait_flags(obj, 0);
3684 }
3685 
3686 int
vm_wait_intr(vm_object_t obj)3687 vm_wait_intr(vm_object_t obj)
3688 {
3689 	return (vm_wait_flags(obj, PCATCH));
3690 }
3691 
3692 /*
3693  *	vm_domain_alloc_fail:
3694  *
3695  *	Called when a page allocation function fails.  Informs the
3696  *	pagedaemon and performs the requested wait.  Requires the
3697  *	domain_free and object lock on entry.  Returns with the
3698  *	object lock held and free lock released.  Returns an error when
3699  *	retry is necessary.
3700  *
3701  */
3702 static int
vm_domain_alloc_fail(struct vm_domain * vmd,vm_object_t object,int req)3703 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3704 {
3705 
3706 	vm_domain_free_assert_unlocked(vmd);
3707 
3708 	atomic_add_int(&vmd->vmd_pageout_deficit,
3709 	    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3710 	if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3711 		if (object != NULL)
3712 			VM_OBJECT_WUNLOCK(object);
3713 		vm_wait_domain(vmd->vmd_domain);
3714 		if (object != NULL)
3715 			VM_OBJECT_WLOCK(object);
3716 		if (req & VM_ALLOC_WAITOK)
3717 			return (EAGAIN);
3718 	}
3719 
3720 	return (0);
3721 }
3722 
3723 /*
3724  *	vm_waitpfault:
3725  *
3726  *	Sleep until free pages are available for allocation.
3727  *	- Called only in vm_fault so that processes page faulting
3728  *	  can be easily tracked.
3729  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3730  *	  processes will be able to grab memory first.  Do not change
3731  *	  this balance without careful testing first.
3732  */
3733 void
vm_waitpfault(struct domainset * dset,int timo)3734 vm_waitpfault(struct domainset *dset, int timo)
3735 {
3736 
3737 	/*
3738 	 * XXX Ideally we would wait only until the allocation could
3739 	 * be satisfied.  This condition can cause new allocators to
3740 	 * consume all freed pages while old allocators wait.
3741 	 */
3742 	mtx_lock(&vm_domainset_lock);
3743 	if (vm_page_count_min_set(&dset->ds_mask)) {
3744 		vm_min_waiters++;
3745 		msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3746 		    "pfault", timo);
3747 	} else
3748 		mtx_unlock(&vm_domainset_lock);
3749 }
3750 
3751 static struct vm_pagequeue *
_vm_page_pagequeue(vm_page_t m,uint8_t queue)3752 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3753 {
3754 
3755 	return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3756 }
3757 
3758 #ifdef INVARIANTS
3759 static struct vm_pagequeue *
vm_page_pagequeue(vm_page_t m)3760 vm_page_pagequeue(vm_page_t m)
3761 {
3762 
3763 	return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3764 }
3765 #endif
3766 
3767 static __always_inline bool
vm_page_pqstate_fcmpset(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3768 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3769 {
3770 	vm_page_astate_t tmp;
3771 
3772 	tmp = *old;
3773 	do {
3774 		if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3775 			return (true);
3776 		counter_u64_add(pqstate_commit_retries, 1);
3777 	} while (old->_bits == tmp._bits);
3778 
3779 	return (false);
3780 }
3781 
3782 /*
3783  * Do the work of committing a queue state update that moves the page out of
3784  * its current queue.
3785  */
3786 static bool
_vm_page_pqstate_commit_dequeue(struct vm_pagequeue * pq,vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3787 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3788     vm_page_astate_t *old, vm_page_astate_t new)
3789 {
3790 	vm_page_t next;
3791 
3792 	vm_pagequeue_assert_locked(pq);
3793 	KASSERT(vm_page_pagequeue(m) == pq,
3794 	    ("%s: queue %p does not match page %p", __func__, pq, m));
3795 	KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3796 	    ("%s: invalid queue indices %d %d",
3797 	    __func__, old->queue, new.queue));
3798 
3799 	/*
3800 	 * Once the queue index of the page changes there is nothing
3801 	 * synchronizing with further updates to the page's physical
3802 	 * queue state.  Therefore we must speculatively remove the page
3803 	 * from the queue now and be prepared to roll back if the queue
3804 	 * state update fails.  If the page is not physically enqueued then
3805 	 * we just update its queue index.
3806 	 */
3807 	if ((old->flags & PGA_ENQUEUED) != 0) {
3808 		new.flags &= ~PGA_ENQUEUED;
3809 		next = TAILQ_NEXT(m, plinks.q);
3810 		TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3811 		vm_pagequeue_cnt_dec(pq);
3812 		if (!vm_page_pqstate_fcmpset(m, old, new)) {
3813 			if (next == NULL)
3814 				TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3815 			else
3816 				TAILQ_INSERT_BEFORE(next, m, plinks.q);
3817 			vm_pagequeue_cnt_inc(pq);
3818 			return (false);
3819 		} else {
3820 			return (true);
3821 		}
3822 	} else {
3823 		return (vm_page_pqstate_fcmpset(m, old, new));
3824 	}
3825 }
3826 
3827 static bool
vm_page_pqstate_commit_dequeue(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3828 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3829     vm_page_astate_t new)
3830 {
3831 	struct vm_pagequeue *pq;
3832 	vm_page_astate_t as;
3833 	bool ret;
3834 
3835 	pq = _vm_page_pagequeue(m, old->queue);
3836 
3837 	/*
3838 	 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3839 	 * corresponding page queue lock is held.
3840 	 */
3841 	vm_pagequeue_lock(pq);
3842 	as = vm_page_astate_load(m);
3843 	if (__predict_false(as._bits != old->_bits)) {
3844 		*old = as;
3845 		ret = false;
3846 	} else {
3847 		ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3848 	}
3849 	vm_pagequeue_unlock(pq);
3850 	return (ret);
3851 }
3852 
3853 /*
3854  * Commit a queue state update that enqueues or requeues a page.
3855  */
3856 static bool
_vm_page_pqstate_commit_requeue(struct vm_pagequeue * pq,vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3857 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3858     vm_page_astate_t *old, vm_page_astate_t new)
3859 {
3860 	struct vm_domain *vmd;
3861 
3862 	vm_pagequeue_assert_locked(pq);
3863 	KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3864 	    ("%s: invalid queue indices %d %d",
3865 	    __func__, old->queue, new.queue));
3866 
3867 	new.flags |= PGA_ENQUEUED;
3868 	if (!vm_page_pqstate_fcmpset(m, old, new))
3869 		return (false);
3870 
3871 	if ((old->flags & PGA_ENQUEUED) != 0)
3872 		TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3873 	else
3874 		vm_pagequeue_cnt_inc(pq);
3875 
3876 	/*
3877 	 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.  In particular, if
3878 	 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3879 	 * applied, even if it was set first.
3880 	 */
3881 	if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3882 		vmd = vm_pagequeue_domain(m);
3883 		KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3884 		    ("%s: invalid page queue for page %p", __func__, m));
3885 		TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3886 	} else {
3887 		TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3888 	}
3889 	return (true);
3890 }
3891 
3892 /*
3893  * Commit a queue state update that encodes a request for a deferred queue
3894  * operation.
3895  */
3896 static bool
vm_page_pqstate_commit_request(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3897 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3898     vm_page_astate_t new)
3899 {
3900 
3901 	KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3902 	    ("%s: invalid state, queue %d flags %x",
3903 	    __func__, new.queue, new.flags));
3904 
3905 	if (old->_bits != new._bits &&
3906 	    !vm_page_pqstate_fcmpset(m, old, new))
3907 		return (false);
3908 	vm_page_pqbatch_submit(m, new.queue);
3909 	return (true);
3910 }
3911 
3912 /*
3913  * A generic queue state update function.  This handles more cases than the
3914  * specialized functions above.
3915  */
3916 bool
vm_page_pqstate_commit(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3917 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3918 {
3919 
3920 	if (old->_bits == new._bits)
3921 		return (true);
3922 
3923 	if (old->queue != PQ_NONE && new.queue != old->queue) {
3924 		if (!vm_page_pqstate_commit_dequeue(m, old, new))
3925 			return (false);
3926 		if (new.queue != PQ_NONE)
3927 			vm_page_pqbatch_submit(m, new.queue);
3928 	} else {
3929 		if (!vm_page_pqstate_fcmpset(m, old, new))
3930 			return (false);
3931 		if (new.queue != PQ_NONE &&
3932 		    ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3933 			vm_page_pqbatch_submit(m, new.queue);
3934 	}
3935 	return (true);
3936 }
3937 
3938 /*
3939  * Apply deferred queue state updates to a page.
3940  */
3941 static inline void
vm_pqbatch_process_page(struct vm_pagequeue * pq,vm_page_t m,uint8_t queue)3942 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3943 {
3944 	vm_page_astate_t new, old;
3945 
3946 	CRITICAL_ASSERT(curthread);
3947 	vm_pagequeue_assert_locked(pq);
3948 	KASSERT(queue < PQ_COUNT,
3949 	    ("%s: invalid queue index %d", __func__, queue));
3950 	KASSERT(pq == _vm_page_pagequeue(m, queue),
3951 	    ("%s: page %p does not belong to queue %p", __func__, m, pq));
3952 
3953 	for (old = vm_page_astate_load(m);;) {
3954 		if (__predict_false(old.queue != queue ||
3955 		    (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3956 			counter_u64_add(queue_nops, 1);
3957 			break;
3958 		}
3959 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3960 		    ("%s: page %p is unmanaged", __func__, m));
3961 
3962 		new = old;
3963 		if ((old.flags & PGA_DEQUEUE) != 0) {
3964 			new.flags &= ~PGA_QUEUE_OP_MASK;
3965 			new.queue = PQ_NONE;
3966 			if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3967 			    m, &old, new))) {
3968 				counter_u64_add(queue_ops, 1);
3969 				break;
3970 			}
3971 		} else {
3972 			new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3973 			if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3974 			    m, &old, new))) {
3975 				counter_u64_add(queue_ops, 1);
3976 				break;
3977 			}
3978 		}
3979 	}
3980 }
3981 
3982 static void
vm_pqbatch_process(struct vm_pagequeue * pq,struct vm_batchqueue * bq,uint8_t queue)3983 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3984     uint8_t queue)
3985 {
3986 	int i;
3987 
3988 	for (i = 0; i < bq->bq_cnt; i++)
3989 		vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3990 	vm_batchqueue_init(bq);
3991 }
3992 
3993 /*
3994  *	vm_page_pqbatch_submit:		[ internal use only ]
3995  *
3996  *	Enqueue a page in the specified page queue's batched work queue.
3997  *	The caller must have encoded the requested operation in the page
3998  *	structure's a.flags field.
3999  */
4000 void
vm_page_pqbatch_submit(vm_page_t m,uint8_t queue)4001 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
4002 {
4003 	struct vm_batchqueue *bq;
4004 	struct vm_pagequeue *pq;
4005 	int domain, slots_remaining;
4006 
4007 	KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
4008 
4009 	domain = vm_page_domain(m);
4010 	critical_enter();
4011 	bq = DPCPU_PTR(pqbatch[domain][queue]);
4012 	slots_remaining = vm_batchqueue_insert(bq, m);
4013 	if (slots_remaining > (VM_BATCHQUEUE_SIZE >> 1)) {
4014 		/* keep building the bq */
4015 		critical_exit();
4016 		return;
4017 	} else if (slots_remaining > 0 ) {
4018 		/* Try to process the bq if we can get the lock */
4019 		pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
4020 		if (vm_pagequeue_trylock(pq)) {
4021 			vm_pqbatch_process(pq, bq, queue);
4022 			vm_pagequeue_unlock(pq);
4023 		}
4024 		critical_exit();
4025 		return;
4026 	}
4027 	critical_exit();
4028 
4029 	/* if we make it here, the bq is full so wait for the lock */
4030 
4031 	pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
4032 	vm_pagequeue_lock(pq);
4033 	critical_enter();
4034 	bq = DPCPU_PTR(pqbatch[domain][queue]);
4035 	vm_pqbatch_process(pq, bq, queue);
4036 	vm_pqbatch_process_page(pq, m, queue);
4037 	vm_pagequeue_unlock(pq);
4038 	critical_exit();
4039 }
4040 
4041 /*
4042  *	vm_page_pqbatch_drain:		[ internal use only ]
4043  *
4044  *	Force all per-CPU page queue batch queues to be drained.  This is
4045  *	intended for use in severe memory shortages, to ensure that pages
4046  *	do not remain stuck in the batch queues.
4047  */
4048 void
vm_page_pqbatch_drain(void)4049 vm_page_pqbatch_drain(void)
4050 {
4051 	struct thread *td;
4052 	struct vm_domain *vmd;
4053 	struct vm_pagequeue *pq;
4054 	int cpu, domain, queue;
4055 
4056 	td = curthread;
4057 	CPU_FOREACH(cpu) {
4058 		thread_lock(td);
4059 		sched_bind(td, cpu);
4060 		thread_unlock(td);
4061 
4062 		for (domain = 0; domain < vm_ndomains; domain++) {
4063 			vmd = VM_DOMAIN(domain);
4064 			for (queue = 0; queue < PQ_COUNT; queue++) {
4065 				pq = &vmd->vmd_pagequeues[queue];
4066 				vm_pagequeue_lock(pq);
4067 				critical_enter();
4068 				vm_pqbatch_process(pq,
4069 				    DPCPU_PTR(pqbatch[domain][queue]), queue);
4070 				critical_exit();
4071 				vm_pagequeue_unlock(pq);
4072 			}
4073 		}
4074 	}
4075 	thread_lock(td);
4076 	sched_unbind(td);
4077 	thread_unlock(td);
4078 }
4079 
4080 /*
4081  *	vm_page_dequeue_deferred:	[ internal use only ]
4082  *
4083  *	Request removal of the given page from its current page
4084  *	queue.  Physical removal from the queue may be deferred
4085  *	indefinitely.
4086  */
4087 void
vm_page_dequeue_deferred(vm_page_t m)4088 vm_page_dequeue_deferred(vm_page_t m)
4089 {
4090 	vm_page_astate_t new, old;
4091 
4092 	old = vm_page_astate_load(m);
4093 	do {
4094 		if (old.queue == PQ_NONE) {
4095 			KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
4096 			    ("%s: page %p has unexpected queue state",
4097 			    __func__, m));
4098 			break;
4099 		}
4100 		new = old;
4101 		new.flags |= PGA_DEQUEUE;
4102 	} while (!vm_page_pqstate_commit_request(m, &old, new));
4103 }
4104 
4105 /*
4106  *	vm_page_dequeue:
4107  *
4108  *	Remove the page from whichever page queue it's in, if any, before
4109  *	returning.
4110  */
4111 void
vm_page_dequeue(vm_page_t m)4112 vm_page_dequeue(vm_page_t m)
4113 {
4114 	vm_page_astate_t new, old;
4115 
4116 	old = vm_page_astate_load(m);
4117 	do {
4118 		if (old.queue == PQ_NONE) {
4119 			KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
4120 			    ("%s: page %p has unexpected queue state",
4121 			    __func__, m));
4122 			break;
4123 		}
4124 		new = old;
4125 		new.flags &= ~PGA_QUEUE_OP_MASK;
4126 		new.queue = PQ_NONE;
4127 	} while (!vm_page_pqstate_commit_dequeue(m, &old, new));
4128 
4129 }
4130 
4131 /*
4132  * Schedule the given page for insertion into the specified page queue.
4133  * Physical insertion of the page may be deferred indefinitely.
4134  */
4135 static void
vm_page_enqueue(vm_page_t m,uint8_t queue)4136 vm_page_enqueue(vm_page_t m, uint8_t queue)
4137 {
4138 
4139 	KASSERT(m->a.queue == PQ_NONE &&
4140 	    (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
4141 	    ("%s: page %p is already enqueued", __func__, m));
4142 	KASSERT(m->ref_count > 0,
4143 	    ("%s: page %p does not carry any references", __func__, m));
4144 
4145 	m->a.queue = queue;
4146 	if ((m->a.flags & PGA_REQUEUE) == 0)
4147 		vm_page_aflag_set(m, PGA_REQUEUE);
4148 	vm_page_pqbatch_submit(m, queue);
4149 }
4150 
4151 /*
4152  *	vm_page_free_prep:
4153  *
4154  *	Prepares the given page to be put on the free list,
4155  *	disassociating it from any VM object. The caller may return
4156  *	the page to the free list only if this function returns true.
4157  *
4158  *	The object, if it exists, must be locked, and then the page must
4159  *	be xbusy.  Otherwise the page must be not busied.  A managed
4160  *	page must be unmapped.
4161  */
4162 static bool
vm_page_free_prep(vm_page_t m)4163 vm_page_free_prep(vm_page_t m)
4164 {
4165 
4166 	/*
4167 	 * Synchronize with threads that have dropped a reference to this
4168 	 * page.
4169 	 */
4170 	atomic_thread_fence_acq();
4171 
4172 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
4173 	if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
4174 		uint64_t *p;
4175 		int i;
4176 		p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
4177 		for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
4178 			KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
4179 			    m, i, (uintmax_t)*p));
4180 	}
4181 #endif
4182 	KASSERT((m->flags & PG_NOFREE) == 0,
4183 	    ("%s: attempting to free a PG_NOFREE page", __func__));
4184 	if ((m->oflags & VPO_UNMANAGED) == 0) {
4185 		KASSERT(!pmap_page_is_mapped(m),
4186 		    ("vm_page_free_prep: freeing mapped page %p", m));
4187 		KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
4188 		    ("vm_page_free_prep: mapping flags set in page %p", m));
4189 	} else {
4190 		KASSERT(m->a.queue == PQ_NONE,
4191 		    ("vm_page_free_prep: unmanaged page %p is queued", m));
4192 	}
4193 	VM_CNT_INC(v_tfree);
4194 
4195 	if (m->object != NULL) {
4196 		vm_page_radix_remove(m);
4197 		vm_page_free_object_prep(m);
4198 	} else
4199 		vm_page_assert_unbusied(m);
4200 
4201 	vm_page_busy_free(m);
4202 
4203 	/*
4204 	 * If fictitious remove object association and
4205 	 * return.
4206 	 */
4207 	if ((m->flags & PG_FICTITIOUS) != 0) {
4208 		KASSERT(m->ref_count == 1,
4209 		    ("fictitious page %p is referenced", m));
4210 		KASSERT(m->a.queue == PQ_NONE,
4211 		    ("fictitious page %p is queued", m));
4212 		return (false);
4213 	}
4214 
4215 	/*
4216 	 * Pages need not be dequeued before they are returned to the physical
4217 	 * memory allocator, but they must at least be marked for a deferred
4218 	 * dequeue.
4219 	 */
4220 	if ((m->oflags & VPO_UNMANAGED) == 0)
4221 		vm_page_dequeue_deferred(m);
4222 
4223 	m->valid = 0;
4224 	vm_page_undirty(m);
4225 
4226 	if (m->ref_count != 0)
4227 		panic("vm_page_free_prep: page %p has references", m);
4228 
4229 	/*
4230 	 * Restore the default memory attribute to the page.
4231 	 */
4232 	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
4233 		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
4234 
4235 #if VM_NRESERVLEVEL > 0
4236 	/*
4237 	 * Determine whether the page belongs to a reservation.  If the page was
4238 	 * allocated from a per-CPU cache, it cannot belong to a reservation, so
4239 	 * as an optimization, we avoid the check in that case.
4240 	 */
4241 	if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
4242 		return (false);
4243 #endif
4244 
4245 	return (true);
4246 }
4247 
4248 /*
4249  *	vm_page_free_toq:
4250  *
4251  *	Returns the given page to the free list, disassociating it
4252  *	from any VM object.
4253  *
4254  *	The object must be locked.  The page must be exclusively busied if it
4255  *	belongs to an object.
4256  */
4257 static void
vm_page_free_toq(vm_page_t m)4258 vm_page_free_toq(vm_page_t m)
4259 {
4260 	struct vm_domain *vmd;
4261 	uma_zone_t zone;
4262 
4263 	if (!vm_page_free_prep(m))
4264 		return;
4265 
4266 	vmd = vm_pagequeue_domain(m);
4267 	zone = vmd->vmd_pgcache[m->pool].zone;
4268 	if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
4269 		uma_zfree(zone, m);
4270 		return;
4271 	}
4272 	vm_domain_free_lock(vmd);
4273 	vm_phys_free_pages(m, 0);
4274 	vm_domain_free_unlock(vmd);
4275 	vm_domain_freecnt_inc(vmd, 1);
4276 }
4277 
4278 /*
4279  *	vm_page_free_pages_toq:
4280  *
4281  *	Returns a list of pages to the free list, disassociating it
4282  *	from any VM object.  In other words, this is equivalent to
4283  *	calling vm_page_free_toq() for each page of a list of VM objects.
4284  */
4285 int
vm_page_free_pages_toq(struct spglist * free,bool update_wire_count)4286 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
4287 {
4288 	vm_page_t m;
4289 	int count;
4290 
4291 	if (SLIST_EMPTY(free))
4292 		return (0);
4293 
4294 	count = 0;
4295 	while ((m = SLIST_FIRST(free)) != NULL) {
4296 		count++;
4297 		SLIST_REMOVE_HEAD(free, plinks.s.ss);
4298 		vm_page_free_toq(m);
4299 	}
4300 
4301 	if (update_wire_count)
4302 		vm_wire_sub(count);
4303 	return (count);
4304 }
4305 
4306 /*
4307  * Mark this page as wired down.  For managed pages, this prevents reclamation
4308  * by the page daemon, or when the containing object, if any, is destroyed.
4309  */
4310 void
vm_page_wire(vm_page_t m)4311 vm_page_wire(vm_page_t m)
4312 {
4313 	u_int old;
4314 
4315 #ifdef INVARIANTS
4316 	if (m->object != NULL && !vm_page_busied(m) &&
4317 	    !vm_object_busied(m->object))
4318 		VM_OBJECT_ASSERT_LOCKED(m->object);
4319 #endif
4320 	KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
4321 	    VPRC_WIRE_COUNT(m->ref_count) >= 1,
4322 	    ("vm_page_wire: fictitious page %p has zero wirings", m));
4323 
4324 	old = atomic_fetchadd_int(&m->ref_count, 1);
4325 	KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
4326 	    ("vm_page_wire: counter overflow for page %p", m));
4327 	if (VPRC_WIRE_COUNT(old) == 0) {
4328 		if ((m->oflags & VPO_UNMANAGED) == 0)
4329 			vm_page_aflag_set(m, PGA_DEQUEUE);
4330 		vm_wire_add(1);
4331 	}
4332 }
4333 
4334 /*
4335  * Attempt to wire a mapped page following a pmap lookup of that page.
4336  * This may fail if a thread is concurrently tearing down mappings of the page.
4337  * The transient failure is acceptable because it translates to the
4338  * failure of the caller pmap_extract_and_hold(), which should be then
4339  * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
4340  */
4341 bool
vm_page_wire_mapped(vm_page_t m)4342 vm_page_wire_mapped(vm_page_t m)
4343 {
4344 	u_int old;
4345 
4346 	old = atomic_load_int(&m->ref_count);
4347 	do {
4348 		KASSERT(old > 0,
4349 		    ("vm_page_wire_mapped: wiring unreferenced page %p", m));
4350 		if ((old & VPRC_BLOCKED) != 0)
4351 			return (false);
4352 	} while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
4353 
4354 	if (VPRC_WIRE_COUNT(old) == 0) {
4355 		if ((m->oflags & VPO_UNMANAGED) == 0)
4356 			vm_page_aflag_set(m, PGA_DEQUEUE);
4357 		vm_wire_add(1);
4358 	}
4359 	return (true);
4360 }
4361 
4362 /*
4363  * Release a wiring reference to a managed page.  If the page still belongs to
4364  * an object, update its position in the page queues to reflect the reference.
4365  * If the wiring was the last reference to the page, free the page.
4366  */
4367 static void
vm_page_unwire_managed(vm_page_t m,uint8_t nqueue,bool noreuse)4368 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
4369 {
4370 	u_int old;
4371 
4372 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4373 	    ("%s: page %p is unmanaged", __func__, m));
4374 
4375 	/*
4376 	 * Update LRU state before releasing the wiring reference.
4377 	 * Use a release store when updating the reference count to
4378 	 * synchronize with vm_page_free_prep().
4379 	 */
4380 	old = atomic_load_int(&m->ref_count);
4381 	do {
4382 		u_int count;
4383 
4384 		KASSERT(VPRC_WIRE_COUNT(old) > 0,
4385 		    ("vm_page_unwire: wire count underflow for page %p", m));
4386 
4387 		count = old & ~VPRC_BLOCKED;
4388 		if (count > VPRC_OBJREF + 1) {
4389 			/*
4390 			 * The page has at least one other wiring reference.  An
4391 			 * earlier iteration of this loop may have called
4392 			 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
4393 			 * re-set it if necessary.
4394 			 */
4395 			if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
4396 				vm_page_aflag_set(m, PGA_DEQUEUE);
4397 		} else if (count == VPRC_OBJREF + 1) {
4398 			/*
4399 			 * This is the last wiring.  Clear PGA_DEQUEUE and
4400 			 * update the page's queue state to reflect the
4401 			 * reference.  If the page does not belong to an object
4402 			 * (i.e., the VPRC_OBJREF bit is clear), we only need to
4403 			 * clear leftover queue state.
4404 			 */
4405 			vm_page_release_toq(m, nqueue, noreuse);
4406 		} else if (count == 1) {
4407 			vm_page_aflag_clear(m, PGA_DEQUEUE);
4408 		}
4409 	} while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
4410 
4411 	if (VPRC_WIRE_COUNT(old) == 1) {
4412 		vm_wire_sub(1);
4413 		if (old == 1)
4414 			vm_page_free(m);
4415 	}
4416 }
4417 
4418 /*
4419  * Release one wiring of the specified page, potentially allowing it to be
4420  * paged out.
4421  *
4422  * Only managed pages belonging to an object can be paged out.  If the number
4423  * of wirings transitions to zero and the page is eligible for page out, then
4424  * the page is added to the specified paging queue.  If the released wiring
4425  * represented the last reference to the page, the page is freed.
4426  */
4427 void
vm_page_unwire(vm_page_t m,uint8_t nqueue)4428 vm_page_unwire(vm_page_t m, uint8_t nqueue)
4429 {
4430 
4431 	KASSERT(nqueue < PQ_COUNT,
4432 	    ("vm_page_unwire: invalid queue %u request for page %p",
4433 	    nqueue, m));
4434 
4435 	if ((m->oflags & VPO_UNMANAGED) != 0) {
4436 		if (vm_page_unwire_noq(m) && m->ref_count == 0)
4437 			vm_page_free(m);
4438 		return;
4439 	}
4440 	vm_page_unwire_managed(m, nqueue, false);
4441 }
4442 
4443 /*
4444  * Unwire a page without (re-)inserting it into a page queue.  It is up
4445  * to the caller to enqueue, requeue, or free the page as appropriate.
4446  * In most cases involving managed pages, vm_page_unwire() should be used
4447  * instead.
4448  */
4449 bool
vm_page_unwire_noq(vm_page_t m)4450 vm_page_unwire_noq(vm_page_t m)
4451 {
4452 	u_int old;
4453 
4454 	old = vm_page_drop(m, 1);
4455 	KASSERT(VPRC_WIRE_COUNT(old) != 0,
4456 	    ("%s: counter underflow for page %p", __func__,  m));
4457 	KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4458 	    ("%s: missing ref on fictitious page %p", __func__, m));
4459 
4460 	if (VPRC_WIRE_COUNT(old) > 1)
4461 		return (false);
4462 	if ((m->oflags & VPO_UNMANAGED) == 0)
4463 		vm_page_aflag_clear(m, PGA_DEQUEUE);
4464 	vm_wire_sub(1);
4465 	return (true);
4466 }
4467 
4468 /*
4469  * Ensure that the page ends up in the specified page queue.  If the page is
4470  * active or being moved to the active queue, ensure that its act_count is
4471  * at least ACT_INIT but do not otherwise mess with it.
4472  */
4473 static __always_inline void
vm_page_mvqueue(vm_page_t m,const uint8_t nqueue,const uint16_t nflag)4474 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4475 {
4476 	vm_page_astate_t old, new;
4477 
4478 	KASSERT(m->ref_count > 0,
4479 	    ("%s: page %p does not carry any references", __func__, m));
4480 	KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4481 	    ("%s: invalid flags %x", __func__, nflag));
4482 
4483 	if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4484 		return;
4485 
4486 	old = vm_page_astate_load(m);
4487 	do {
4488 		if ((old.flags & PGA_DEQUEUE) != 0)
4489 			break;
4490 		new = old;
4491 		new.flags &= ~PGA_QUEUE_OP_MASK;
4492 		if (nqueue == PQ_ACTIVE)
4493 			new.act_count = max(old.act_count, ACT_INIT);
4494 		if (old.queue == nqueue) {
4495 			/*
4496 			 * There is no need to requeue pages already in the
4497 			 * active queue.
4498 			 */
4499 			if (nqueue != PQ_ACTIVE ||
4500 			    (old.flags & PGA_ENQUEUED) == 0)
4501 				new.flags |= nflag;
4502 		} else {
4503 			new.flags |= nflag;
4504 			new.queue = nqueue;
4505 		}
4506 	} while (!vm_page_pqstate_commit(m, &old, new));
4507 }
4508 
4509 /*
4510  * Put the specified page on the active list (if appropriate).
4511  */
4512 void
vm_page_activate(vm_page_t m)4513 vm_page_activate(vm_page_t m)
4514 {
4515 
4516 	vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4517 }
4518 
4519 /*
4520  * Move the specified page to the tail of the inactive queue, or requeue
4521  * the page if it is already in the inactive queue.
4522  */
4523 void
vm_page_deactivate(vm_page_t m)4524 vm_page_deactivate(vm_page_t m)
4525 {
4526 
4527 	vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4528 }
4529 
4530 void
vm_page_deactivate_noreuse(vm_page_t m)4531 vm_page_deactivate_noreuse(vm_page_t m)
4532 {
4533 
4534 	vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4535 }
4536 
4537 /*
4538  * Put a page in the laundry, or requeue it if it is already there.
4539  */
4540 void
vm_page_launder(vm_page_t m)4541 vm_page_launder(vm_page_t m)
4542 {
4543 
4544 	vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4545 }
4546 
4547 /*
4548  * Put a page in the PQ_UNSWAPPABLE holding queue.
4549  */
4550 void
vm_page_unswappable(vm_page_t m)4551 vm_page_unswappable(vm_page_t m)
4552 {
4553 
4554 	VM_OBJECT_ASSERT_LOCKED(m->object);
4555 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4556 	    ("page %p already unswappable", m));
4557 
4558 	vm_page_dequeue(m);
4559 	vm_page_enqueue(m, PQ_UNSWAPPABLE);
4560 }
4561 
4562 /*
4563  * Release a page back to the page queues in preparation for unwiring.
4564  */
4565 static void
vm_page_release_toq(vm_page_t m,uint8_t nqueue,const bool noreuse)4566 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4567 {
4568 	vm_page_astate_t old, new;
4569 	uint16_t nflag;
4570 
4571 	/*
4572 	 * Use a check of the valid bits to determine whether we should
4573 	 * accelerate reclamation of the page.  The object lock might not be
4574 	 * held here, in which case the check is racy.  At worst we will either
4575 	 * accelerate reclamation of a valid page and violate LRU, or
4576 	 * unnecessarily defer reclamation of an invalid page.
4577 	 *
4578 	 * If we were asked to not cache the page, place it near the head of the
4579 	 * inactive queue so that is reclaimed sooner.
4580 	 */
4581 	if (noreuse || vm_page_none_valid(m)) {
4582 		nqueue = PQ_INACTIVE;
4583 		nflag = PGA_REQUEUE_HEAD;
4584 	} else {
4585 		nflag = PGA_REQUEUE;
4586 	}
4587 
4588 	old = vm_page_astate_load(m);
4589 	do {
4590 		new = old;
4591 
4592 		/*
4593 		 * If the page is already in the active queue and we are not
4594 		 * trying to accelerate reclamation, simply mark it as
4595 		 * referenced and avoid any queue operations.
4596 		 */
4597 		new.flags &= ~PGA_QUEUE_OP_MASK;
4598 		if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE &&
4599 		    (old.flags & PGA_ENQUEUED) != 0)
4600 			new.flags |= PGA_REFERENCED;
4601 		else {
4602 			new.flags |= nflag;
4603 			new.queue = nqueue;
4604 		}
4605 	} while (!vm_page_pqstate_commit(m, &old, new));
4606 }
4607 
4608 /*
4609  * Unwire a page and either attempt to free it or re-add it to the page queues.
4610  */
4611 void
vm_page_release(vm_page_t m,int flags)4612 vm_page_release(vm_page_t m, int flags)
4613 {
4614 	vm_object_t object;
4615 
4616 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4617 	    ("vm_page_release: page %p is unmanaged", m));
4618 
4619 	if ((flags & VPR_TRYFREE) != 0) {
4620 		for (;;) {
4621 			object = atomic_load_ptr(&m->object);
4622 			if (object == NULL)
4623 				break;
4624 			/* Depends on type-stability. */
4625 			if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4626 				break;
4627 			if (object == m->object) {
4628 				vm_page_release_locked(m, flags);
4629 				VM_OBJECT_WUNLOCK(object);
4630 				return;
4631 			}
4632 			VM_OBJECT_WUNLOCK(object);
4633 		}
4634 	}
4635 	vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4636 }
4637 
4638 /* See vm_page_release(). */
4639 void
vm_page_release_locked(vm_page_t m,int flags)4640 vm_page_release_locked(vm_page_t m, int flags)
4641 {
4642 
4643 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4644 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4645 	    ("vm_page_release_locked: page %p is unmanaged", m));
4646 
4647 	if (vm_page_unwire_noq(m)) {
4648 		if ((flags & VPR_TRYFREE) != 0 &&
4649 		    (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4650 		    m->dirty == 0 && vm_page_tryxbusy(m)) {
4651 			/*
4652 			 * An unlocked lookup may have wired the page before the
4653 			 * busy lock was acquired, in which case the page must
4654 			 * not be freed.
4655 			 */
4656 			if (__predict_true(!vm_page_wired(m))) {
4657 				vm_page_free(m);
4658 				return;
4659 			}
4660 			vm_page_xunbusy(m);
4661 		} else {
4662 			vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4663 		}
4664 	}
4665 }
4666 
4667 static bool
vm_page_try_blocked_op(vm_page_t m,void (* op)(vm_page_t))4668 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4669 {
4670 	u_int old;
4671 
4672 	KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4673 	    ("vm_page_try_blocked_op: page %p has no object", m));
4674 	KASSERT(vm_page_busied(m),
4675 	    ("vm_page_try_blocked_op: page %p is not busy", m));
4676 	VM_OBJECT_ASSERT_LOCKED(m->object);
4677 
4678 	old = atomic_load_int(&m->ref_count);
4679 	do {
4680 		KASSERT(old != 0,
4681 		    ("vm_page_try_blocked_op: page %p has no references", m));
4682 		KASSERT((old & VPRC_BLOCKED) == 0,
4683 		    ("vm_page_try_blocked_op: page %p blocks wirings", m));
4684 		if (VPRC_WIRE_COUNT(old) != 0)
4685 			return (false);
4686 	} while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4687 
4688 	(op)(m);
4689 
4690 	/*
4691 	 * If the object is read-locked, new wirings may be created via an
4692 	 * object lookup.
4693 	 */
4694 	old = vm_page_drop(m, VPRC_BLOCKED);
4695 	KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4696 	    old == (VPRC_BLOCKED | VPRC_OBJREF),
4697 	    ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4698 	    old, m));
4699 	return (true);
4700 }
4701 
4702 /*
4703  * Atomically check for wirings and remove all mappings of the page.
4704  */
4705 bool
vm_page_try_remove_all(vm_page_t m)4706 vm_page_try_remove_all(vm_page_t m)
4707 {
4708 
4709 	return (vm_page_try_blocked_op(m, pmap_remove_all));
4710 }
4711 
4712 /*
4713  * Atomically check for wirings and remove all writeable mappings of the page.
4714  */
4715 bool
vm_page_try_remove_write(vm_page_t m)4716 vm_page_try_remove_write(vm_page_t m)
4717 {
4718 
4719 	return (vm_page_try_blocked_op(m, pmap_remove_write));
4720 }
4721 
4722 /*
4723  * vm_page_advise
4724  *
4725  * 	Apply the specified advice to the given page.
4726  */
4727 void
vm_page_advise(vm_page_t m,int advice)4728 vm_page_advise(vm_page_t m, int advice)
4729 {
4730 
4731 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4732 	vm_page_assert_xbusied(m);
4733 
4734 	if (advice == MADV_FREE)
4735 		/*
4736 		 * Mark the page clean.  This will allow the page to be freed
4737 		 * without first paging it out.  MADV_FREE pages are often
4738 		 * quickly reused by malloc(3), so we do not do anything that
4739 		 * would result in a page fault on a later access.
4740 		 */
4741 		vm_page_undirty(m);
4742 	else if (advice != MADV_DONTNEED) {
4743 		if (advice == MADV_WILLNEED)
4744 			vm_page_activate(m);
4745 		return;
4746 	}
4747 
4748 	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4749 		vm_page_dirty(m);
4750 
4751 	/*
4752 	 * Clear any references to the page.  Otherwise, the page daemon will
4753 	 * immediately reactivate the page.
4754 	 */
4755 	vm_page_aflag_clear(m, PGA_REFERENCED);
4756 
4757 	/*
4758 	 * Place clean pages near the head of the inactive queue rather than
4759 	 * the tail, thus defeating the queue's LRU operation and ensuring that
4760 	 * the page will be reused quickly.  Dirty pages not already in the
4761 	 * laundry are moved there.
4762 	 */
4763 	if (m->dirty == 0)
4764 		vm_page_deactivate_noreuse(m);
4765 	else if (!vm_page_in_laundry(m))
4766 		vm_page_launder(m);
4767 }
4768 
4769 /*
4770  *	vm_page_grab_release
4771  *
4772  *	Helper routine for grab functions to release busy on return.
4773  */
4774 static inline void
vm_page_grab_release(vm_page_t m,int allocflags)4775 vm_page_grab_release(vm_page_t m, int allocflags)
4776 {
4777 
4778 	if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4779 		if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4780 			vm_page_sunbusy(m);
4781 		else
4782 			vm_page_xunbusy(m);
4783 	}
4784 }
4785 
4786 /*
4787  *	vm_page_grab_sleep
4788  *
4789  *	Sleep for busy according to VM_ALLOC_ parameters.  Returns true
4790  *	if the caller should retry and false otherwise.
4791  *
4792  *	If the object is locked on entry the object will be unlocked with
4793  *	false returns and still locked but possibly having been dropped
4794  *	with true returns.
4795  */
4796 static bool
vm_page_grab_sleep(vm_object_t object,vm_page_t m,vm_pindex_t pindex,const char * wmesg,int allocflags,bool locked)4797 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4798     const char *wmesg, int allocflags, bool locked)
4799 {
4800 
4801 	if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4802 		return (false);
4803 
4804 	/*
4805 	 * Reference the page before unlocking and sleeping so that
4806 	 * the page daemon is less likely to reclaim it.
4807 	 */
4808 	if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4809 		vm_page_reference(m);
4810 
4811 	if (_vm_page_busy_sleep(object, m, pindex, wmesg, allocflags, locked) &&
4812 	    locked)
4813 		VM_OBJECT_WLOCK(object);
4814 	if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4815 		return (false);
4816 
4817 	return (true);
4818 }
4819 
4820 /*
4821  * Assert that the grab flags are valid.
4822  */
4823 static inline void
vm_page_grab_check(int allocflags)4824 vm_page_grab_check(int allocflags)
4825 {
4826 
4827 	KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4828 	    (allocflags & VM_ALLOC_WIRED) != 0,
4829 	    ("vm_page_grab*: the pages must be busied or wired"));
4830 
4831 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4832 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4833 	    ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4834 }
4835 
4836 /*
4837  * Calculate the page allocation flags for grab.
4838  */
4839 static inline int
vm_page_grab_pflags(int allocflags)4840 vm_page_grab_pflags(int allocflags)
4841 {
4842 	int pflags;
4843 
4844 	pflags = allocflags &
4845 	    ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4846 	    VM_ALLOC_NOBUSY | VM_ALLOC_IGN_SBUSY);
4847 	if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4848 		pflags |= VM_ALLOC_WAITFAIL;
4849 	if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4850 		pflags |= VM_ALLOC_SBUSY;
4851 
4852 	return (pflags);
4853 }
4854 
4855 /*
4856  * Grab a page, waiting until we are waken up due to the page
4857  * changing state.  We keep on waiting, if the page continues
4858  * to be in the object.  If the page doesn't exist, first allocate it
4859  * and then conditionally zero it.
4860  *
4861  * This routine may sleep.
4862  *
4863  * The object must be locked on entry.  The lock will, however, be released
4864  * and reacquired if the routine sleeps.
4865  */
4866 vm_page_t
vm_page_grab(vm_object_t object,vm_pindex_t pindex,int allocflags)4867 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4868 {
4869 	vm_page_t m;
4870 
4871 	VM_OBJECT_ASSERT_WLOCKED(object);
4872 	vm_page_grab_check(allocflags);
4873 
4874 retrylookup:
4875 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
4876 		if (!vm_page_tryacquire(m, allocflags)) {
4877 			if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4878 			    allocflags, true))
4879 				goto retrylookup;
4880 			return (NULL);
4881 		}
4882 		goto out;
4883 	}
4884 	if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4885 		return (NULL);
4886 	m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4887 	if (m == NULL) {
4888 		if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4889 			return (NULL);
4890 		goto retrylookup;
4891 	}
4892 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4893 		pmap_zero_page(m);
4894 
4895 out:
4896 	vm_page_grab_release(m, allocflags);
4897 
4898 	return (m);
4899 }
4900 
4901 /*
4902  * Attempt to validate a page, locklessly acquiring it if necessary, given a
4903  * (object, pindex) tuple and either an invalided page or NULL.  The resulting
4904  * page will be validated against the identity tuple, and busied or wired as
4905  * requested.  A NULL page returned guarantees that the page was not in radix at
4906  * the time of the call but callers must perform higher level synchronization or
4907  * retry the operation under a lock if they require an atomic answer.  This is
4908  * the only lock free validation routine, other routines can depend on the
4909  * resulting page state.
4910  *
4911  * The return value PAGE_NOT_ACQUIRED indicates that the operation failed due to
4912  * caller flags.
4913  */
4914 #define PAGE_NOT_ACQUIRED ((vm_page_t)1)
4915 static vm_page_t
vm_page_acquire_unlocked(vm_object_t object,vm_pindex_t pindex,vm_page_t m,int allocflags)4916 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex, vm_page_t m,
4917     int allocflags)
4918 {
4919 	if (m == NULL)
4920 		m = vm_page_lookup_unlocked(object, pindex);
4921 	for (; m != NULL; m = vm_page_lookup_unlocked(object, pindex)) {
4922 		if (vm_page_trybusy(m, allocflags)) {
4923 			if (m->object == object && m->pindex == pindex) {
4924 				if ((allocflags & VM_ALLOC_WIRED) != 0)
4925 					vm_page_wire(m);
4926 				vm_page_grab_release(m, allocflags);
4927 				break;
4928 			}
4929 			/* relookup. */
4930 			vm_page_busy_release(m);
4931 			cpu_spinwait();
4932 			continue;
4933 		}
4934 		if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4935 		    allocflags, false))
4936 			return (PAGE_NOT_ACQUIRED);
4937 	}
4938 	return (m);
4939 }
4940 
4941 /*
4942  * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4943  * is not set.
4944  */
4945 vm_page_t
vm_page_grab_unlocked(vm_object_t object,vm_pindex_t pindex,int allocflags)4946 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4947 {
4948 	vm_page_t m;
4949 
4950 	vm_page_grab_check(allocflags);
4951 	m = vm_page_acquire_unlocked(object, pindex, NULL, allocflags);
4952 	if (m == PAGE_NOT_ACQUIRED)
4953 		return (NULL);
4954 	if (m != NULL)
4955 		return (m);
4956 
4957 	/*
4958 	 * The radix lockless lookup should never return a false negative
4959 	 * errors.  If the user specifies NOCREAT they are guaranteed there
4960 	 * was no page present at the instant of the call.  A NOCREAT caller
4961 	 * must handle create races gracefully.
4962 	 */
4963 	if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4964 		return (NULL);
4965 
4966 	VM_OBJECT_WLOCK(object);
4967 	m = vm_page_grab(object, pindex, allocflags);
4968 	VM_OBJECT_WUNLOCK(object);
4969 
4970 	return (m);
4971 }
4972 
4973 /*
4974  * Grab a page and make it valid, paging in if necessary.  Pages missing from
4975  * their pager are zero filled and validated.  If a VM_ALLOC_COUNT is supplied
4976  * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4977  * in simultaneously.  Additional pages will be left on a paging queue but
4978  * will neither be wired nor busy regardless of allocflags.
4979  */
4980 int
vm_page_grab_valid(vm_page_t * mp,vm_object_t object,vm_pindex_t pindex,int allocflags)4981 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4982 {
4983 	vm_page_t m;
4984 	vm_page_t ma[VM_INITIAL_PAGEIN];
4985 	int after, i, pflags, rv;
4986 
4987 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4988 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4989 	    ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4990 	KASSERT((allocflags &
4991 	    (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4992 	    ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4993 	VM_OBJECT_ASSERT_WLOCKED(object);
4994 	pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4995 	    VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY);
4996 	pflags |= VM_ALLOC_WAITFAIL;
4997 
4998 retrylookup:
4999 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
5000 		/*
5001 		 * If the page is fully valid it can only become invalid
5002 		 * with the object lock held.  If it is not valid it can
5003 		 * become valid with the busy lock held.  Therefore, we
5004 		 * may unnecessarily lock the exclusive busy here if we
5005 		 * race with I/O completion not using the object lock.
5006 		 * However, we will not end up with an invalid page and a
5007 		 * shared lock.
5008 		 */
5009 		if (!vm_page_trybusy(m,
5010 		    vm_page_all_valid(m) ? allocflags : 0)) {
5011 			(void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
5012 			    allocflags, true);
5013 			goto retrylookup;
5014 		}
5015 		if (vm_page_all_valid(m))
5016 			goto out;
5017 		if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
5018 			vm_page_busy_release(m);
5019 			*mp = NULL;
5020 			return (VM_PAGER_FAIL);
5021 		}
5022 	} else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
5023 		*mp = NULL;
5024 		return (VM_PAGER_FAIL);
5025 	} else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
5026 		if (!vm_pager_can_alloc_page(object, pindex)) {
5027 			*mp = NULL;
5028 			return (VM_PAGER_AGAIN);
5029 		}
5030 		goto retrylookup;
5031 	}
5032 
5033 	vm_page_assert_xbusied(m);
5034 	if (vm_pager_has_page(object, pindex, NULL, &after)) {
5035 		after = MIN(after, VM_INITIAL_PAGEIN);
5036 		after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
5037 		after = MAX(after, 1);
5038 		ma[0] = m;
5039 		for (i = 1; i < after; i++) {
5040 			if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
5041 				if (vm_page_any_valid(ma[i]) ||
5042 				    !vm_page_tryxbusy(ma[i]))
5043 					break;
5044 			} else {
5045 				ma[i] = vm_page_alloc(object, m->pindex + i,
5046 				    VM_ALLOC_NORMAL);
5047 				if (ma[i] == NULL)
5048 					break;
5049 			}
5050 		}
5051 		after = i;
5052 		vm_object_pip_add(object, after);
5053 		VM_OBJECT_WUNLOCK(object);
5054 		rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
5055 		VM_OBJECT_WLOCK(object);
5056 		vm_object_pip_wakeupn(object, after);
5057 		/* Pager may have replaced a page. */
5058 		m = ma[0];
5059 		if (rv != VM_PAGER_OK) {
5060 			for (i = 0; i < after; i++) {
5061 				if (!vm_page_wired(ma[i]))
5062 					vm_page_free(ma[i]);
5063 				else
5064 					vm_page_xunbusy(ma[i]);
5065 			}
5066 			*mp = NULL;
5067 			return (rv);
5068 		}
5069 		for (i = 1; i < after; i++)
5070 			vm_page_readahead_finish(ma[i]);
5071 		MPASS(vm_page_all_valid(m));
5072 	} else {
5073 		vm_page_zero_invalid(m, TRUE);
5074 	}
5075 out:
5076 	if ((allocflags & VM_ALLOC_WIRED) != 0)
5077 		vm_page_wire(m);
5078 	if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
5079 		vm_page_busy_downgrade(m);
5080 	else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
5081 		vm_page_busy_release(m);
5082 	*mp = m;
5083 	return (VM_PAGER_OK);
5084 }
5085 
5086 /*
5087  * Locklessly grab a valid page.  If the page is not valid or not yet
5088  * allocated this will fall back to the object lock method.
5089  */
5090 int
vm_page_grab_valid_unlocked(vm_page_t * mp,vm_object_t object,vm_pindex_t pindex,int allocflags)5091 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
5092     vm_pindex_t pindex, int allocflags)
5093 {
5094 	vm_page_t m;
5095 	int flags;
5096 	int error;
5097 
5098 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
5099 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
5100 	    ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
5101 	    "mismatch"));
5102 	KASSERT((allocflags &
5103 	    (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
5104 	    ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
5105 
5106 	/*
5107 	 * Attempt a lockless lookup and busy.  We need at least an sbusy
5108 	 * before we can inspect the valid field and return a wired page.
5109 	 */
5110 	flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
5111 	vm_page_grab_check(flags);
5112 	m = vm_page_acquire_unlocked(object, pindex, NULL, flags);
5113 	if (m == PAGE_NOT_ACQUIRED)
5114 		return (VM_PAGER_FAIL);
5115 	if (m != NULL) {
5116 		if (vm_page_all_valid(m)) {
5117 			if ((allocflags & VM_ALLOC_WIRED) != 0)
5118 				vm_page_wire(m);
5119 			vm_page_grab_release(m, allocflags);
5120 			*mp = m;
5121 			return (VM_PAGER_OK);
5122 		}
5123 		vm_page_busy_release(m);
5124 	}
5125 	if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
5126 		*mp = NULL;
5127 		return (VM_PAGER_FAIL);
5128 	}
5129 	VM_OBJECT_WLOCK(object);
5130 	error = vm_page_grab_valid(mp, object, pindex, allocflags);
5131 	VM_OBJECT_WUNLOCK(object);
5132 
5133 	return (error);
5134 }
5135 
5136 /*
5137  * Return the specified range of pages from the given object.  For each
5138  * page offset within the range, if a page already exists within the object
5139  * at that offset and it is busy, then wait for it to change state.  If,
5140  * instead, the page doesn't exist, then allocate it.
5141  *
5142  * The caller must always specify an allocation class.
5143  *
5144  * allocation classes:
5145  *	VM_ALLOC_NORMAL		normal process request
5146  *	VM_ALLOC_SYSTEM		system *really* needs the pages
5147  *
5148  * The caller must always specify that the pages are to be busied and/or
5149  * wired.
5150  *
5151  * optional allocation flags:
5152  *	VM_ALLOC_IGN_SBUSY	do not sleep on soft busy pages
5153  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
5154  *	VM_ALLOC_NOWAIT		do not sleep
5155  *	VM_ALLOC_SBUSY		set page to sbusy state
5156  *	VM_ALLOC_WIRED		wire the pages
5157  *	VM_ALLOC_ZERO		zero and validate any invalid pages
5158  *
5159  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
5160  * may return a partial prefix of the requested range.
5161  */
5162 int
vm_page_grab_pages(vm_object_t object,vm_pindex_t pindex,int allocflags,vm_page_t * ma,int count)5163 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
5164     vm_page_t *ma, int count)
5165 {
5166 	vm_page_t m, mpred;
5167 	int pflags;
5168 	int i;
5169 
5170 	VM_OBJECT_ASSERT_WLOCKED(object);
5171 	KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
5172 	    ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
5173 	KASSERT(count > 0,
5174 	    ("vm_page_grab_pages: invalid page count %d", count));
5175 	vm_page_grab_check(allocflags);
5176 
5177 	pflags = vm_page_grab_pflags(allocflags);
5178 	i = 0;
5179 retrylookup:
5180 	m = vm_page_mpred(object, pindex + i);
5181 	if (m == NULL || m->pindex != pindex + i) {
5182 		mpred = m;
5183 		m = NULL;
5184 	} else
5185 		mpred = TAILQ_PREV(m, pglist, listq);
5186 	for (; i < count; i++) {
5187 		if (m != NULL) {
5188 			if (!vm_page_tryacquire(m, allocflags)) {
5189 				if (vm_page_grab_sleep(object, m, pindex + i,
5190 				    "grbmaw", allocflags, true))
5191 					goto retrylookup;
5192 				break;
5193 			}
5194 		} else {
5195 			if ((allocflags & VM_ALLOC_NOCREAT) != 0)
5196 				break;
5197 			m = vm_page_alloc_after(object, pindex + i,
5198 			    pflags | VM_ALLOC_COUNT(count - i), mpred);
5199 			if (m == NULL) {
5200 				if ((allocflags & (VM_ALLOC_NOWAIT |
5201 				    VM_ALLOC_WAITFAIL)) != 0)
5202 					break;
5203 				goto retrylookup;
5204 			}
5205 		}
5206 		if (vm_page_none_valid(m) &&
5207 		    (allocflags & VM_ALLOC_ZERO) != 0) {
5208 			if ((m->flags & PG_ZERO) == 0)
5209 				pmap_zero_page(m);
5210 			vm_page_valid(m);
5211 		}
5212 		vm_page_grab_release(m, allocflags);
5213 		ma[i] = mpred = m;
5214 		m = vm_page_next(m);
5215 	}
5216 	return (i);
5217 }
5218 
5219 /*
5220  * Unlocked variant of vm_page_grab_pages().  This accepts the same flags
5221  * and will fall back to the locked variant to handle allocation.
5222  */
5223 int
vm_page_grab_pages_unlocked(vm_object_t object,vm_pindex_t pindex,int allocflags,vm_page_t * ma,int count)5224 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
5225     int allocflags, vm_page_t *ma, int count)
5226 {
5227 	vm_page_t m;
5228 	int flags;
5229 	int i;
5230 
5231 	KASSERT(count > 0,
5232 	    ("vm_page_grab_pages_unlocked: invalid page count %d", count));
5233 	vm_page_grab_check(allocflags);
5234 
5235 	/*
5236 	 * Modify flags for lockless acquire to hold the page until we
5237 	 * set it valid if necessary.
5238 	 */
5239 	flags = allocflags & ~VM_ALLOC_NOBUSY;
5240 	vm_page_grab_check(flags);
5241 	m = NULL;
5242 	for (i = 0; i < count; i++, pindex++) {
5243 		/*
5244 		 * We may see a false NULL here because the previous page has
5245 		 * been removed or just inserted and the list is loaded without
5246 		 * barriers.  Switch to radix to verify.
5247 		 */
5248 		if (m == NULL || QMD_IS_TRASHED(m) || m->pindex != pindex ||
5249 		    atomic_load_ptr(&m->object) != object) {
5250 			/*
5251 			 * This guarantees the result is instantaneously
5252 			 * correct.
5253 			 */
5254 			m = NULL;
5255 		}
5256 		m = vm_page_acquire_unlocked(object, pindex, m, flags);
5257 		if (m == PAGE_NOT_ACQUIRED)
5258 			return (i);
5259 		if (m == NULL)
5260 			break;
5261 		if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
5262 			if ((m->flags & PG_ZERO) == 0)
5263 				pmap_zero_page(m);
5264 			vm_page_valid(m);
5265 		}
5266 		/* m will still be wired or busy according to flags. */
5267 		vm_page_grab_release(m, allocflags);
5268 		ma[i] = m;
5269 		m = TAILQ_NEXT(m, listq);
5270 	}
5271 	if (i == count || (allocflags & VM_ALLOC_NOCREAT) != 0)
5272 		return (i);
5273 	count -= i;
5274 	VM_OBJECT_WLOCK(object);
5275 	i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
5276 	VM_OBJECT_WUNLOCK(object);
5277 
5278 	return (i);
5279 }
5280 
5281 /*
5282  * Mapping function for valid or dirty bits in a page.
5283  *
5284  * Inputs are required to range within a page.
5285  */
5286 vm_page_bits_t
vm_page_bits(int base,int size)5287 vm_page_bits(int base, int size)
5288 {
5289 	int first_bit;
5290 	int last_bit;
5291 
5292 	KASSERT(
5293 	    base + size <= PAGE_SIZE,
5294 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
5295 	);
5296 
5297 	if (size == 0)		/* handle degenerate case */
5298 		return (0);
5299 
5300 	first_bit = base >> DEV_BSHIFT;
5301 	last_bit = (base + size - 1) >> DEV_BSHIFT;
5302 
5303 	return (((vm_page_bits_t)2 << last_bit) -
5304 	    ((vm_page_bits_t)1 << first_bit));
5305 }
5306 
5307 void
vm_page_bits_set(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t set)5308 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
5309 {
5310 
5311 #if PAGE_SIZE == 32768
5312 	atomic_set_64((uint64_t *)bits, set);
5313 #elif PAGE_SIZE == 16384
5314 	atomic_set_32((uint32_t *)bits, set);
5315 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
5316 	atomic_set_16((uint16_t *)bits, set);
5317 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
5318 	atomic_set_8((uint8_t *)bits, set);
5319 #else		/* PAGE_SIZE <= 8192 */
5320 	uintptr_t addr;
5321 	int shift;
5322 
5323 	addr = (uintptr_t)bits;
5324 	/*
5325 	 * Use a trick to perform a 32-bit atomic on the
5326 	 * containing aligned word, to not depend on the existence
5327 	 * of atomic_{set, clear}_{8, 16}.
5328 	 */
5329 	shift = addr & (sizeof(uint32_t) - 1);
5330 #if BYTE_ORDER == BIG_ENDIAN
5331 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5332 #else
5333 	shift *= NBBY;
5334 #endif
5335 	addr &= ~(sizeof(uint32_t) - 1);
5336 	atomic_set_32((uint32_t *)addr, set << shift);
5337 #endif		/* PAGE_SIZE */
5338 }
5339 
5340 static inline void
vm_page_bits_clear(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t clear)5341 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
5342 {
5343 
5344 #if PAGE_SIZE == 32768
5345 	atomic_clear_64((uint64_t *)bits, clear);
5346 #elif PAGE_SIZE == 16384
5347 	atomic_clear_32((uint32_t *)bits, clear);
5348 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
5349 	atomic_clear_16((uint16_t *)bits, clear);
5350 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
5351 	atomic_clear_8((uint8_t *)bits, clear);
5352 #else		/* PAGE_SIZE <= 8192 */
5353 	uintptr_t addr;
5354 	int shift;
5355 
5356 	addr = (uintptr_t)bits;
5357 	/*
5358 	 * Use a trick to perform a 32-bit atomic on the
5359 	 * containing aligned word, to not depend on the existence
5360 	 * of atomic_{set, clear}_{8, 16}.
5361 	 */
5362 	shift = addr & (sizeof(uint32_t) - 1);
5363 #if BYTE_ORDER == BIG_ENDIAN
5364 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5365 #else
5366 	shift *= NBBY;
5367 #endif
5368 	addr &= ~(sizeof(uint32_t) - 1);
5369 	atomic_clear_32((uint32_t *)addr, clear << shift);
5370 #endif		/* PAGE_SIZE */
5371 }
5372 
5373 static inline vm_page_bits_t
vm_page_bits_swap(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t newbits)5374 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
5375 {
5376 #if PAGE_SIZE == 32768
5377 	uint64_t old;
5378 
5379 	old = *bits;
5380 	while (atomic_fcmpset_64(bits, &old, newbits) == 0);
5381 	return (old);
5382 #elif PAGE_SIZE == 16384
5383 	uint32_t old;
5384 
5385 	old = *bits;
5386 	while (atomic_fcmpset_32(bits, &old, newbits) == 0);
5387 	return (old);
5388 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
5389 	uint16_t old;
5390 
5391 	old = *bits;
5392 	while (atomic_fcmpset_16(bits, &old, newbits) == 0);
5393 	return (old);
5394 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
5395 	uint8_t old;
5396 
5397 	old = *bits;
5398 	while (atomic_fcmpset_8(bits, &old, newbits) == 0);
5399 	return (old);
5400 #else		/* PAGE_SIZE <= 4096*/
5401 	uintptr_t addr;
5402 	uint32_t old, new, mask;
5403 	int shift;
5404 
5405 	addr = (uintptr_t)bits;
5406 	/*
5407 	 * Use a trick to perform a 32-bit atomic on the
5408 	 * containing aligned word, to not depend on the existence
5409 	 * of atomic_{set, swap, clear}_{8, 16}.
5410 	 */
5411 	shift = addr & (sizeof(uint32_t) - 1);
5412 #if BYTE_ORDER == BIG_ENDIAN
5413 	shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5414 #else
5415 	shift *= NBBY;
5416 #endif
5417 	addr &= ~(sizeof(uint32_t) - 1);
5418 	mask = VM_PAGE_BITS_ALL << shift;
5419 
5420 	old = *bits;
5421 	do {
5422 		new = old & ~mask;
5423 		new |= newbits << shift;
5424 	} while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
5425 	return (old >> shift);
5426 #endif		/* PAGE_SIZE */
5427 }
5428 
5429 /*
5430  *	vm_page_set_valid_range:
5431  *
5432  *	Sets portions of a page valid.  The arguments are expected
5433  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5434  *	of any partial chunks touched by the range.  The invalid portion of
5435  *	such chunks will be zeroed.
5436  *
5437  *	(base + size) must be less then or equal to PAGE_SIZE.
5438  */
5439 void
vm_page_set_valid_range(vm_page_t m,int base,int size)5440 vm_page_set_valid_range(vm_page_t m, int base, int size)
5441 {
5442 	int endoff, frag;
5443 	vm_page_bits_t pagebits;
5444 
5445 	vm_page_assert_busied(m);
5446 	if (size == 0)	/* handle degenerate case */
5447 		return;
5448 
5449 	/*
5450 	 * If the base is not DEV_BSIZE aligned and the valid
5451 	 * bit is clear, we have to zero out a portion of the
5452 	 * first block.
5453 	 */
5454 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5455 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5456 		pmap_zero_page_area(m, frag, base - frag);
5457 
5458 	/*
5459 	 * If the ending offset is not DEV_BSIZE aligned and the
5460 	 * valid bit is clear, we have to zero out a portion of
5461 	 * the last block.
5462 	 */
5463 	endoff = base + size;
5464 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5465 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5466 		pmap_zero_page_area(m, endoff,
5467 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5468 
5469 	/*
5470 	 * Assert that no previously invalid block that is now being validated
5471 	 * is already dirty.
5472 	 */
5473 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5474 	    ("vm_page_set_valid_range: page %p is dirty", m));
5475 
5476 	/*
5477 	 * Set valid bits inclusive of any overlap.
5478 	 */
5479 	pagebits = vm_page_bits(base, size);
5480 	if (vm_page_xbusied(m))
5481 		m->valid |= pagebits;
5482 	else
5483 		vm_page_bits_set(m, &m->valid, pagebits);
5484 }
5485 
5486 /*
5487  * Set the page dirty bits and free the invalid swap space if
5488  * present.  Returns the previous dirty bits.
5489  */
5490 vm_page_bits_t
vm_page_set_dirty(vm_page_t m)5491 vm_page_set_dirty(vm_page_t m)
5492 {
5493 	vm_page_bits_t old;
5494 
5495 	VM_PAGE_OBJECT_BUSY_ASSERT(m);
5496 
5497 	if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5498 		old = m->dirty;
5499 		m->dirty = VM_PAGE_BITS_ALL;
5500 	} else
5501 		old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5502 	if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5503 		vm_pager_page_unswapped(m);
5504 
5505 	return (old);
5506 }
5507 
5508 /*
5509  * Clear the given bits from the specified page's dirty field.
5510  */
5511 static __inline void
vm_page_clear_dirty_mask(vm_page_t m,vm_page_bits_t pagebits)5512 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5513 {
5514 
5515 	vm_page_assert_busied(m);
5516 
5517 	/*
5518 	 * If the page is xbusied and not write mapped we are the
5519 	 * only thread that can modify dirty bits.  Otherwise, The pmap
5520 	 * layer can call vm_page_dirty() without holding a distinguished
5521 	 * lock.  The combination of page busy and atomic operations
5522 	 * suffice to guarantee consistency of the page dirty field.
5523 	 */
5524 	if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5525 		m->dirty &= ~pagebits;
5526 	else
5527 		vm_page_bits_clear(m, &m->dirty, pagebits);
5528 }
5529 
5530 /*
5531  *	vm_page_set_validclean:
5532  *
5533  *	Sets portions of a page valid and clean.  The arguments are expected
5534  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5535  *	of any partial chunks touched by the range.  The invalid portion of
5536  *	such chunks will be zero'd.
5537  *
5538  *	(base + size) must be less then or equal to PAGE_SIZE.
5539  */
5540 void
vm_page_set_validclean(vm_page_t m,int base,int size)5541 vm_page_set_validclean(vm_page_t m, int base, int size)
5542 {
5543 	vm_page_bits_t oldvalid, pagebits;
5544 	int endoff, frag;
5545 
5546 	vm_page_assert_busied(m);
5547 	if (size == 0)	/* handle degenerate case */
5548 		return;
5549 
5550 	/*
5551 	 * If the base is not DEV_BSIZE aligned and the valid
5552 	 * bit is clear, we have to zero out a portion of the
5553 	 * first block.
5554 	 */
5555 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5556 	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5557 		pmap_zero_page_area(m, frag, base - frag);
5558 
5559 	/*
5560 	 * If the ending offset is not DEV_BSIZE aligned and the
5561 	 * valid bit is clear, we have to zero out a portion of
5562 	 * the last block.
5563 	 */
5564 	endoff = base + size;
5565 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5566 	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5567 		pmap_zero_page_area(m, endoff,
5568 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5569 
5570 	/*
5571 	 * Set valid, clear dirty bits.  If validating the entire
5572 	 * page we can safely clear the pmap modify bit.  We also
5573 	 * use this opportunity to clear the PGA_NOSYNC flag.  If a process
5574 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
5575 	 * be set again.
5576 	 *
5577 	 * We set valid bits inclusive of any overlap, but we can only
5578 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
5579 	 * the range.
5580 	 */
5581 	oldvalid = m->valid;
5582 	pagebits = vm_page_bits(base, size);
5583 	if (vm_page_xbusied(m))
5584 		m->valid |= pagebits;
5585 	else
5586 		vm_page_bits_set(m, &m->valid, pagebits);
5587 #if 0	/* NOT YET */
5588 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5589 		frag = DEV_BSIZE - frag;
5590 		base += frag;
5591 		size -= frag;
5592 		if (size < 0)
5593 			size = 0;
5594 	}
5595 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5596 #endif
5597 	if (base == 0 && size == PAGE_SIZE) {
5598 		/*
5599 		 * The page can only be modified within the pmap if it is
5600 		 * mapped, and it can only be mapped if it was previously
5601 		 * fully valid.
5602 		 */
5603 		if (oldvalid == VM_PAGE_BITS_ALL)
5604 			/*
5605 			 * Perform the pmap_clear_modify() first.  Otherwise,
5606 			 * a concurrent pmap operation, such as
5607 			 * pmap_protect(), could clear a modification in the
5608 			 * pmap and set the dirty field on the page before
5609 			 * pmap_clear_modify() had begun and after the dirty
5610 			 * field was cleared here.
5611 			 */
5612 			pmap_clear_modify(m);
5613 		m->dirty = 0;
5614 		vm_page_aflag_clear(m, PGA_NOSYNC);
5615 	} else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5616 		m->dirty &= ~pagebits;
5617 	else
5618 		vm_page_clear_dirty_mask(m, pagebits);
5619 }
5620 
5621 void
vm_page_clear_dirty(vm_page_t m,int base,int size)5622 vm_page_clear_dirty(vm_page_t m, int base, int size)
5623 {
5624 
5625 	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5626 }
5627 
5628 /*
5629  *	vm_page_set_invalid:
5630  *
5631  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
5632  *	valid and dirty bits for the effected areas are cleared.
5633  */
5634 void
vm_page_set_invalid(vm_page_t m,int base,int size)5635 vm_page_set_invalid(vm_page_t m, int base, int size)
5636 {
5637 	vm_page_bits_t bits;
5638 	vm_object_t object;
5639 
5640 	/*
5641 	 * The object lock is required so that pages can't be mapped
5642 	 * read-only while we're in the process of invalidating them.
5643 	 */
5644 	object = m->object;
5645 	VM_OBJECT_ASSERT_WLOCKED(object);
5646 	vm_page_assert_busied(m);
5647 
5648 	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5649 	    size >= object->un_pager.vnp.vnp_size)
5650 		bits = VM_PAGE_BITS_ALL;
5651 	else
5652 		bits = vm_page_bits(base, size);
5653 	if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5654 		pmap_remove_all(m);
5655 	KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5656 	    !pmap_page_is_mapped(m),
5657 	    ("vm_page_set_invalid: page %p is mapped", m));
5658 	if (vm_page_xbusied(m)) {
5659 		m->valid &= ~bits;
5660 		m->dirty &= ~bits;
5661 	} else {
5662 		vm_page_bits_clear(m, &m->valid, bits);
5663 		vm_page_bits_clear(m, &m->dirty, bits);
5664 	}
5665 }
5666 
5667 /*
5668  *	vm_page_invalid:
5669  *
5670  *	Invalidates the entire page.  The page must be busy, unmapped, and
5671  *	the enclosing object must be locked.  The object locks protects
5672  *	against concurrent read-only pmap enter which is done without
5673  *	busy.
5674  */
5675 void
vm_page_invalid(vm_page_t m)5676 vm_page_invalid(vm_page_t m)
5677 {
5678 
5679 	vm_page_assert_busied(m);
5680 	VM_OBJECT_ASSERT_WLOCKED(m->object);
5681 	MPASS(!pmap_page_is_mapped(m));
5682 
5683 	if (vm_page_xbusied(m))
5684 		m->valid = 0;
5685 	else
5686 		vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5687 }
5688 
5689 /*
5690  * vm_page_zero_invalid()
5691  *
5692  *	The kernel assumes that the invalid portions of a page contain
5693  *	garbage, but such pages can be mapped into memory by user code.
5694  *	When this occurs, we must zero out the non-valid portions of the
5695  *	page so user code sees what it expects.
5696  *
5697  *	Pages are most often semi-valid when the end of a file is mapped
5698  *	into memory and the file's size is not page aligned.
5699  */
5700 void
vm_page_zero_invalid(vm_page_t m,boolean_t setvalid)5701 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5702 {
5703 	int b;
5704 	int i;
5705 
5706 	/*
5707 	 * Scan the valid bits looking for invalid sections that
5708 	 * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
5709 	 * valid bit may be set ) have already been zeroed by
5710 	 * vm_page_set_validclean().
5711 	 */
5712 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5713 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
5714 		    (m->valid & ((vm_page_bits_t)1 << i))) {
5715 			if (i > b) {
5716 				pmap_zero_page_area(m,
5717 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5718 			}
5719 			b = i + 1;
5720 		}
5721 	}
5722 
5723 	/*
5724 	 * setvalid is TRUE when we can safely set the zero'd areas
5725 	 * as being valid.  We can do this if there are no cache consistency
5726 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
5727 	 */
5728 	if (setvalid)
5729 		vm_page_valid(m);
5730 }
5731 
5732 /*
5733  *	vm_page_is_valid:
5734  *
5735  *	Is (partial) page valid?  Note that the case where size == 0
5736  *	will return FALSE in the degenerate case where the page is
5737  *	entirely invalid, and TRUE otherwise.
5738  *
5739  *	Some callers envoke this routine without the busy lock held and
5740  *	handle races via higher level locks.  Typical callers should
5741  *	hold a busy lock to prevent invalidation.
5742  */
5743 int
vm_page_is_valid(vm_page_t m,int base,int size)5744 vm_page_is_valid(vm_page_t m, int base, int size)
5745 {
5746 	vm_page_bits_t bits;
5747 
5748 	bits = vm_page_bits(base, size);
5749 	return (vm_page_any_valid(m) && (m->valid & bits) == bits);
5750 }
5751 
5752 /*
5753  * Returns true if all of the specified predicates are true for the entire
5754  * (super)page and false otherwise.
5755  */
5756 bool
vm_page_ps_test(vm_page_t m,int psind,int flags,vm_page_t skip_m)5757 vm_page_ps_test(vm_page_t m, int psind, int flags, vm_page_t skip_m)
5758 {
5759 	vm_object_t object;
5760 	int i, npages;
5761 
5762 	object = m->object;
5763 	if (skip_m != NULL && skip_m->object != object)
5764 		return (false);
5765 	VM_OBJECT_ASSERT_LOCKED(object);
5766 	KASSERT(psind <= m->psind,
5767 	    ("psind %d > psind %d of m %p", psind, m->psind, m));
5768 	npages = atop(pagesizes[psind]);
5769 
5770 	/*
5771 	 * The physically contiguous pages that make up a superpage, i.e., a
5772 	 * page with a page size index ("psind") greater than zero, will
5773 	 * occupy adjacent entries in vm_page_array[].
5774 	 */
5775 	for (i = 0; i < npages; i++) {
5776 		/* Always test object consistency, including "skip_m". */
5777 		if (m[i].object != object)
5778 			return (false);
5779 		if (&m[i] == skip_m)
5780 			continue;
5781 		if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5782 			return (false);
5783 		if ((flags & PS_ALL_DIRTY) != 0) {
5784 			/*
5785 			 * Calling vm_page_test_dirty() or pmap_is_modified()
5786 			 * might stop this case from spuriously returning
5787 			 * "false".  However, that would require a write lock
5788 			 * on the object containing "m[i]".
5789 			 */
5790 			if (m[i].dirty != VM_PAGE_BITS_ALL)
5791 				return (false);
5792 		}
5793 		if ((flags & PS_ALL_VALID) != 0 &&
5794 		    m[i].valid != VM_PAGE_BITS_ALL)
5795 			return (false);
5796 	}
5797 	return (true);
5798 }
5799 
5800 /*
5801  * Set the page's dirty bits if the page is modified.
5802  */
5803 void
vm_page_test_dirty(vm_page_t m)5804 vm_page_test_dirty(vm_page_t m)
5805 {
5806 
5807 	vm_page_assert_busied(m);
5808 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5809 		vm_page_dirty(m);
5810 }
5811 
5812 void
vm_page_valid(vm_page_t m)5813 vm_page_valid(vm_page_t m)
5814 {
5815 
5816 	vm_page_assert_busied(m);
5817 	if (vm_page_xbusied(m))
5818 		m->valid = VM_PAGE_BITS_ALL;
5819 	else
5820 		vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5821 }
5822 
5823 void
vm_page_lock_KBI(vm_page_t m,const char * file,int line)5824 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5825 {
5826 
5827 	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5828 }
5829 
5830 void
vm_page_unlock_KBI(vm_page_t m,const char * file,int line)5831 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5832 {
5833 
5834 	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5835 }
5836 
5837 int
vm_page_trylock_KBI(vm_page_t m,const char * file,int line)5838 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5839 {
5840 
5841 	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5842 }
5843 
5844 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5845 void
vm_page_assert_locked_KBI(vm_page_t m,const char * file,int line)5846 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5847 {
5848 
5849 	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5850 }
5851 
5852 void
vm_page_lock_assert_KBI(vm_page_t m,int a,const char * file,int line)5853 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5854 {
5855 
5856 	mtx_assert_(vm_page_lockptr(m), a, file, line);
5857 }
5858 #endif
5859 
5860 #ifdef INVARIANTS
5861 void
vm_page_object_busy_assert(vm_page_t m)5862 vm_page_object_busy_assert(vm_page_t m)
5863 {
5864 
5865 	/*
5866 	 * Certain of the page's fields may only be modified by the
5867 	 * holder of a page or object busy.
5868 	 */
5869 	if (m->object != NULL && !vm_page_busied(m))
5870 		VM_OBJECT_ASSERT_BUSY(m->object);
5871 }
5872 
5873 void
vm_page_assert_pga_writeable(vm_page_t m,uint16_t bits)5874 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5875 {
5876 
5877 	if ((bits & PGA_WRITEABLE) == 0)
5878 		return;
5879 
5880 	/*
5881 	 * The PGA_WRITEABLE flag can only be set if the page is
5882 	 * managed, is exclusively busied or the object is locked.
5883 	 * Currently, this flag is only set by pmap_enter().
5884 	 */
5885 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5886 	    ("PGA_WRITEABLE on unmanaged page"));
5887 	if (!vm_page_xbusied(m))
5888 		VM_OBJECT_ASSERT_BUSY(m->object);
5889 }
5890 #endif
5891 
5892 #include "opt_ddb.h"
5893 #ifdef DDB
5894 #include <sys/kernel.h>
5895 
5896 #include <ddb/ddb.h>
5897 
DB_SHOW_COMMAND_FLAGS(page,vm_page_print_page_info,DB_CMD_MEMSAFE)5898 DB_SHOW_COMMAND_FLAGS(page, vm_page_print_page_info, DB_CMD_MEMSAFE)
5899 {
5900 
5901 	db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5902 	db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5903 	db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5904 	db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5905 	db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5906 	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5907 	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5908 	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5909 	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5910 }
5911 
DB_SHOW_COMMAND_FLAGS(pageq,vm_page_print_pageq_info,DB_CMD_MEMSAFE)5912 DB_SHOW_COMMAND_FLAGS(pageq, vm_page_print_pageq_info, DB_CMD_MEMSAFE)
5913 {
5914 	int dom;
5915 
5916 	db_printf("pq_free %d\n", vm_free_count());
5917 	for (dom = 0; dom < vm_ndomains; dom++) {
5918 		db_printf(
5919     "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5920 		    dom,
5921 		    vm_dom[dom].vmd_page_count,
5922 		    vm_dom[dom].vmd_free_count,
5923 		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5924 		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5925 		    vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5926 		    vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5927 	}
5928 }
5929 
DB_SHOW_COMMAND(pginfo,vm_page_print_pginfo)5930 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5931 {
5932 	vm_page_t m;
5933 	boolean_t phys, virt;
5934 
5935 	if (!have_addr) {
5936 		db_printf("show pginfo addr\n");
5937 		return;
5938 	}
5939 
5940 	phys = strchr(modif, 'p') != NULL;
5941 	virt = strchr(modif, 'v') != NULL;
5942 	if (virt)
5943 		m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5944 	else if (phys)
5945 		m = PHYS_TO_VM_PAGE(addr);
5946 	else
5947 		m = (vm_page_t)addr;
5948 	db_printf(
5949     "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5950     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5951 	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5952 	    m->a.queue, m->ref_count, m->a.flags, m->oflags,
5953 	    m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);
5954 }
5955 #endif /* DDB */
5956