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