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