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