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