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