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