xref: /freebsd-12.1/sys/vm/vm_page.c (revision 8cb553dc)
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * The Mach Operating System project at Carnegie-Mellon University.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
36  */
37 
38 /*-
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
43  *
44  * Permission to use, copy, modify and distribute this software and
45  * its documentation is hereby granted, provided that both the copyright
46  * notice and this permission notice appear in all copies of the
47  * software, derivative works or modified versions, and any portions
48  * thereof, and that both notices appear in supporting documentation.
49  *
50  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
53  *
54  * Carnegie Mellon requests users of this software to return to
55  *
56  *  Software Distribution Coordinator  or  [email protected]
57  *  School of Computer Science
58  *  Carnegie Mellon University
59  *  Pittsburgh PA 15213-3890
60  *
61  * any improvements or extensions that they make and grant Carnegie the
62  * rights to redistribute these changes.
63  */
64 
65 /*
66  *	Resident memory management module.
67  */
68 
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
71 
72 #include "opt_vm.h"
73 
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/lock.h>
77 #include <sys/domainset.h>
78 #include <sys/kernel.h>
79 #include <sys/limits.h>
80 #include <sys/linker.h>
81 #include <sys/malloc.h>
82 #include <sys/mman.h>
83 #include <sys/msgbuf.h>
84 #include <sys/mutex.h>
85 #include <sys/proc.h>
86 #include <sys/rwlock.h>
87 #include <sys/sbuf.h>
88 #include <sys/sched.h>
89 #include <sys/smp.h>
90 #include <sys/sysctl.h>
91 #include <sys/vmmeter.h>
92 #include <sys/vnode.h>
93 
94 #include <vm/vm.h>
95 #include <vm/pmap.h>
96 #include <vm/vm_param.h>
97 #include <vm/vm_domainset.h>
98 #include <vm/vm_kern.h>
99 #include <vm/vm_map.h>
100 #include <vm/vm_object.h>
101 #include <vm/vm_page.h>
102 #include <vm/vm_pageout.h>
103 #include <vm/vm_phys.h>
104 #include <vm/vm_pagequeue.h>
105 #include <vm/vm_pager.h>
106 #include <vm/vm_radix.h>
107 #include <vm/vm_reserv.h>
108 #include <vm/vm_extern.h>
109 #include <vm/uma.h>
110 #include <vm/uma_int.h>
111 
112 #include <machine/md_var.h>
113 
114 extern int	uma_startup_count(int);
115 extern void	uma_startup(void *, int);
116 extern int	vmem_startup_count(void);
117 
118 struct vm_domain vm_dom[MAXMEMDOM];
119 
120 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
121 
122 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
123 
124 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
125 /* The following fields are protected by the domainset lock. */
126 domainset_t __exclusive_cache_line vm_min_domains;
127 domainset_t __exclusive_cache_line vm_severe_domains;
128 static int vm_min_waiters;
129 static int vm_severe_waiters;
130 static int vm_pageproc_waiters;
131 
132 /*
133  * bogus page -- for I/O to/from partially complete buffers,
134  * or for paging into sparsely invalid regions.
135  */
136 vm_page_t bogus_page;
137 
138 vm_page_t vm_page_array;
139 long vm_page_array_size;
140 long first_page;
141 
142 static int boot_pages;
143 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
144     &boot_pages, 0,
145     "number of pages allocated for bootstrapping the VM system");
146 
147 static int pa_tryrelock_restart;
148 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
149     &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
150 
151 static TAILQ_HEAD(, vm_page) blacklist_head;
152 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
153 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
154     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
155 
156 static uma_zone_t fakepg_zone;
157 
158 static void vm_page_alloc_check(vm_page_t m);
159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160 static void vm_page_dequeue_complete(vm_page_t m);
161 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
162 static void vm_page_init(void *dummy);
163 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
164     vm_pindex_t pindex, vm_page_t mpred);
165 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
166     vm_page_t mpred);
167 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
168     vm_page_t m_run, vm_paddr_t high);
169 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
170     int req);
171 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
172     int flags);
173 static void vm_page_zone_release(void *arg, void **store, int cnt);
174 
175 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
176 
177 static void
vm_page_init(void * dummy)178 vm_page_init(void *dummy)
179 {
180 
181 	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
182 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
183 	bogus_page = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ |
184 	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
185 }
186 
187 /*
188  * The cache page zone is initialized later since we need to be able to allocate
189  * pages before UMA is fully initialized.
190  */
191 static void
vm_page_init_cache_zones(void * dummy __unused)192 vm_page_init_cache_zones(void *dummy __unused)
193 {
194 	struct vm_domain *vmd;
195 	struct vm_pgcache *pgcache;
196 	int domain, pool;
197 
198 	for (domain = 0; domain < vm_ndomains; domain++) {
199 		vmd = VM_DOMAIN(domain);
200 
201 		/*
202 		 * Don't allow the page caches to take up more than .25% of
203 		 * memory.
204 		 */
205 		if (vmd->vmd_page_count / 400 < 256 * mp_ncpus * VM_NFREEPOOL)
206 			continue;
207 		for (pool = 0; pool < VM_NFREEPOOL; pool++) {
208 			pgcache = &vmd->vmd_pgcache[pool];
209 			pgcache->domain = domain;
210 			pgcache->pool = pool;
211 			pgcache->zone = uma_zcache_create("vm pgcache",
212 			    sizeof(struct vm_page), NULL, NULL, NULL, NULL,
213 			    vm_page_zone_import, vm_page_zone_release, pgcache,
214 			    UMA_ZONE_NOBUCKETCACHE | UMA_ZONE_MAXBUCKET |
215 			    UMA_ZONE_VM);
216 		}
217 	}
218 }
219 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
220 
221 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
222 #if PAGE_SIZE == 32768
223 #ifdef CTASSERT
224 CTASSERT(sizeof(u_long) >= 8);
225 #endif
226 #endif
227 
228 /*
229  * Try to acquire a physical address lock while a pmap is locked.  If we
230  * fail to trylock we unlock and lock the pmap directly and cache the
231  * locked pa in *locked.  The caller should then restart their loop in case
232  * the virtual to physical mapping has changed.
233  */
234 int
vm_page_pa_tryrelock(pmap_t pmap,vm_paddr_t pa,vm_paddr_t * locked)235 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
236 {
237 	vm_paddr_t lockpa;
238 
239 	lockpa = *locked;
240 	*locked = pa;
241 	if (lockpa) {
242 		PA_LOCK_ASSERT(lockpa, MA_OWNED);
243 		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
244 			return (0);
245 		PA_UNLOCK(lockpa);
246 	}
247 	if (PA_TRYLOCK(pa))
248 		return (0);
249 	PMAP_UNLOCK(pmap);
250 	atomic_add_int(&pa_tryrelock_restart, 1);
251 	PA_LOCK(pa);
252 	PMAP_LOCK(pmap);
253 	return (EAGAIN);
254 }
255 
256 /*
257  *	vm_set_page_size:
258  *
259  *	Sets the page size, perhaps based upon the memory
260  *	size.  Must be called before any use of page-size
261  *	dependent functions.
262  */
263 void
vm_set_page_size(void)264 vm_set_page_size(void)
265 {
266 	if (vm_cnt.v_page_size == 0)
267 		vm_cnt.v_page_size = PAGE_SIZE;
268 	if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
269 		panic("vm_set_page_size: page size not a power of two");
270 }
271 
272 /*
273  *	vm_page_blacklist_next:
274  *
275  *	Find the next entry in the provided string of blacklist
276  *	addresses.  Entries are separated by space, comma, or newline.
277  *	If an invalid integer is encountered then the rest of the
278  *	string is skipped.  Updates the list pointer to the next
279  *	character, or NULL if the string is exhausted or invalid.
280  */
281 static vm_paddr_t
vm_page_blacklist_next(char ** list,char * end)282 vm_page_blacklist_next(char **list, char *end)
283 {
284 	vm_paddr_t bad;
285 	char *cp, *pos;
286 
287 	if (list == NULL || *list == NULL)
288 		return (0);
289 	if (**list =='\0') {
290 		*list = NULL;
291 		return (0);
292 	}
293 
294 	/*
295 	 * If there's no end pointer then the buffer is coming from
296 	 * the kenv and we know it's null-terminated.
297 	 */
298 	if (end == NULL)
299 		end = *list + strlen(*list);
300 
301 	/* Ensure that strtoq() won't walk off the end */
302 	if (*end != '\0') {
303 		if (*end == '\n' || *end == ' ' || *end  == ',')
304 			*end = '\0';
305 		else {
306 			printf("Blacklist not terminated, skipping\n");
307 			*list = NULL;
308 			return (0);
309 		}
310 	}
311 
312 	for (pos = *list; *pos != '\0'; pos = cp) {
313 		bad = strtoq(pos, &cp, 0);
314 		if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
315 			if (bad == 0) {
316 				if (++cp < end)
317 					continue;
318 				else
319 					break;
320 			}
321 		} else
322 			break;
323 		if (*cp == '\0' || ++cp >= end)
324 			*list = NULL;
325 		else
326 			*list = cp;
327 		return (trunc_page(bad));
328 	}
329 	printf("Garbage in RAM blacklist, skipping\n");
330 	*list = NULL;
331 	return (0);
332 }
333 
334 bool
vm_page_blacklist_add(vm_paddr_t pa,bool verbose)335 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
336 {
337 	struct vm_domain *vmd;
338 	vm_page_t m;
339 	int ret;
340 
341 	m = vm_phys_paddr_to_vm_page(pa);
342 	if (m == NULL)
343 		return (true); /* page does not exist, no failure */
344 
345 	vmd = vm_pagequeue_domain(m);
346 	vm_domain_free_lock(vmd);
347 	ret = vm_phys_unfree_page(m);
348 	vm_domain_free_unlock(vmd);
349 	if (ret != 0) {
350 		vm_domain_freecnt_inc(vmd, -1);
351 		TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
352 		if (verbose)
353 			printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
354 	}
355 	return (ret);
356 }
357 
358 /*
359  *	vm_page_blacklist_check:
360  *
361  *	Iterate through the provided string of blacklist addresses, pulling
362  *	each entry out of the physical allocator free list and putting it
363  *	onto a list for reporting via the vm.page_blacklist sysctl.
364  */
365 static void
vm_page_blacklist_check(char * list,char * end)366 vm_page_blacklist_check(char *list, char *end)
367 {
368 	vm_paddr_t pa;
369 	char *next;
370 
371 	next = list;
372 	while (next != NULL) {
373 		if ((pa = vm_page_blacklist_next(&next, end)) == 0)
374 			continue;
375 		vm_page_blacklist_add(pa, bootverbose);
376 	}
377 }
378 
379 /*
380  *	vm_page_blacklist_load:
381  *
382  *	Search for a special module named "ram_blacklist".  It'll be a
383  *	plain text file provided by the user via the loader directive
384  *	of the same name.
385  */
386 static void
vm_page_blacklist_load(char ** list,char ** end)387 vm_page_blacklist_load(char **list, char **end)
388 {
389 	void *mod;
390 	u_char *ptr;
391 	u_int len;
392 
393 	mod = NULL;
394 	ptr = NULL;
395 
396 	mod = preload_search_by_type("ram_blacklist");
397 	if (mod != NULL) {
398 		ptr = preload_fetch_addr(mod);
399 		len = preload_fetch_size(mod);
400         }
401 	*list = ptr;
402 	if (ptr != NULL)
403 		*end = ptr + len;
404 	else
405 		*end = NULL;
406 	return;
407 }
408 
409 static int
sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)410 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
411 {
412 	vm_page_t m;
413 	struct sbuf sbuf;
414 	int error, first;
415 
416 	first = 1;
417 	error = sysctl_wire_old_buffer(req, 0);
418 	if (error != 0)
419 		return (error);
420 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
421 	TAILQ_FOREACH(m, &blacklist_head, listq) {
422 		sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
423 		    (uintmax_t)m->phys_addr);
424 		first = 0;
425 	}
426 	error = sbuf_finish(&sbuf);
427 	sbuf_delete(&sbuf);
428 	return (error);
429 }
430 
431 /*
432  * Initialize a dummy page for use in scans of the specified paging queue.
433  * In principle, this function only needs to set the flag PG_MARKER.
434  * Nonetheless, it write busies and initializes the hold count to one as
435  * safety precautions.
436  */
437 static void
vm_page_init_marker(vm_page_t marker,int queue,uint8_t aflags)438 vm_page_init_marker(vm_page_t marker, int queue, uint8_t aflags)
439 {
440 
441 	bzero(marker, sizeof(*marker));
442 	marker->flags = PG_MARKER;
443 	marker->aflags = aflags;
444 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
445 	marker->queue = queue;
446 	marker->hold_count = 1;
447 }
448 
449 static void
vm_page_domain_init(int domain)450 vm_page_domain_init(int domain)
451 {
452 	struct vm_domain *vmd;
453 	struct vm_pagequeue *pq;
454 	int i;
455 
456 	vmd = VM_DOMAIN(domain);
457 	bzero(vmd, sizeof(*vmd));
458 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
459 	    "vm inactive pagequeue";
460 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
461 	    "vm active pagequeue";
462 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
463 	    "vm laundry pagequeue";
464 	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
465 	    "vm unswappable pagequeue";
466 	vmd->vmd_domain = domain;
467 	vmd->vmd_page_count = 0;
468 	vmd->vmd_free_count = 0;
469 	vmd->vmd_segs = 0;
470 	vmd->vmd_oom = FALSE;
471 	for (i = 0; i < PQ_COUNT; i++) {
472 		pq = &vmd->vmd_pagequeues[i];
473 		TAILQ_INIT(&pq->pq_pl);
474 		mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
475 		    MTX_DEF | MTX_DUPOK);
476 		pq->pq_pdpages = 0;
477 		vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
478 	}
479 	mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
480 	mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
481 	snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
482 
483 	/*
484 	 * inacthead is used to provide FIFO ordering for LRU-bypassing
485 	 * insertions.
486 	 */
487 	vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
488 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
489 	    &vmd->vmd_inacthead, plinks.q);
490 
491 	/*
492 	 * The clock pages are used to implement active queue scanning without
493 	 * requeues.  Scans start at clock[0], which is advanced after the scan
494 	 * ends.  When the two clock hands meet, they are reset and scanning
495 	 * resumes from the head of the queue.
496 	 */
497 	vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
498 	vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
499 	TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
500 	    &vmd->vmd_clock[0], plinks.q);
501 	TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
502 	    &vmd->vmd_clock[1], plinks.q);
503 }
504 
505 /*
506  * Initialize a physical page in preparation for adding it to the free
507  * lists.
508  */
509 static void
vm_page_init_page(vm_page_t m,vm_paddr_t pa,int segind)510 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
511 {
512 
513 	m->object = NULL;
514 	m->wire_count = 0;
515 	m->busy_lock = VPB_UNBUSIED;
516 	m->hold_count = 0;
517 	m->flags = m->aflags = 0;
518 	m->phys_addr = pa;
519 	m->queue = PQ_NONE;
520 	m->psind = 0;
521 	m->segind = segind;
522 	m->order = VM_NFREEORDER;
523 	m->pool = VM_FREEPOOL_DEFAULT;
524 	m->valid = m->dirty = 0;
525 	pmap_page_init(m);
526 }
527 
528 /*
529  *	vm_page_startup:
530  *
531  *	Initializes the resident memory module.  Allocates physical memory for
532  *	bootstrapping UMA and some data structures that are used to manage
533  *	physical pages.  Initializes these structures, and populates the free
534  *	page queues.
535  */
536 vm_offset_t
vm_page_startup(vm_offset_t vaddr)537 vm_page_startup(vm_offset_t vaddr)
538 {
539 	struct vm_phys_seg *seg;
540 	vm_page_t m;
541 	char *list, *listend;
542 	vm_offset_t mapped;
543 	vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
544 	vm_paddr_t biggestsize, last_pa, pa;
545 	u_long pagecount;
546 	int biggestone, i, segind;
547 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
548 	long ii;
549 #endif
550 
551 	biggestsize = 0;
552 	biggestone = 0;
553 	vaddr = round_page(vaddr);
554 
555 	for (i = 0; phys_avail[i + 1]; i += 2) {
556 		phys_avail[i] = round_page(phys_avail[i]);
557 		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
558 	}
559 	for (i = 0; phys_avail[i + 1]; i += 2) {
560 		size = phys_avail[i + 1] - phys_avail[i];
561 		if (size > biggestsize) {
562 			biggestone = i;
563 			biggestsize = size;
564 		}
565 	}
566 
567 	end = phys_avail[biggestone+1];
568 
569 	/*
570 	 * Initialize the page and queue locks.
571 	 */
572 	mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
573 	for (i = 0; i < PA_LOCK_COUNT; i++)
574 		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
575 	for (i = 0; i < vm_ndomains; i++)
576 		vm_page_domain_init(i);
577 
578 	/*
579 	 * Allocate memory for use when boot strapping the kernel memory
580 	 * allocator.  Tell UMA how many zones we are going to create
581 	 * before going fully functional.  UMA will add its zones.
582 	 *
583 	 * VM startup zones: vmem, vmem_btag, VM OBJECT, RADIX NODE, MAP,
584 	 * KMAP ENTRY, MAP ENTRY, VMSPACE.
585 	 */
586 	boot_pages = uma_startup_count(8);
587 
588 #ifndef UMA_MD_SMALL_ALLOC
589 	/* vmem_startup() calls uma_prealloc(). */
590 	boot_pages += vmem_startup_count();
591 	/* vm_map_startup() calls uma_prealloc(). */
592 	boot_pages += howmany(MAX_KMAP,
593 	    UMA_SLAB_SPACE / sizeof(struct vm_map));
594 
595 	/*
596 	 * Before going fully functional kmem_init() does allocation
597 	 * from "KMAP ENTRY" and vmem_create() does allocation from "vmem".
598 	 */
599 	boot_pages += 2;
600 #endif
601 	/*
602 	 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
603 	 * manually fetch the value.
604 	 */
605 	TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
606 	new_end = end - (boot_pages * UMA_SLAB_SIZE);
607 	new_end = trunc_page(new_end);
608 	mapped = pmap_map(&vaddr, new_end, end,
609 	    VM_PROT_READ | VM_PROT_WRITE);
610 	bzero((void *)mapped, end - new_end);
611 	uma_startup((void *)mapped, boot_pages);
612 
613 #ifdef WITNESS
614 	end = new_end;
615 	new_end = end - round_page(witness_startup_count());
616 	mapped = pmap_map(&vaddr, new_end, end,
617 	    VM_PROT_READ | VM_PROT_WRITE);
618 	bzero((void *)mapped, end - new_end);
619 	witness_startup((void *)mapped);
620 #endif
621 
622 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
623     defined(__i386__) || defined(__mips__) || defined(__riscv)
624 	/*
625 	 * Allocate a bitmap to indicate that a random physical page
626 	 * needs to be included in a minidump.
627 	 *
628 	 * The amd64 port needs this to indicate which direct map pages
629 	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
630 	 *
631 	 * However, i386 still needs this workspace internally within the
632 	 * minidump code.  In theory, they are not needed on i386, but are
633 	 * included should the sf_buf code decide to use them.
634 	 */
635 	last_pa = 0;
636 	for (i = 0; dump_avail[i + 1] != 0; i += 2)
637 		if (dump_avail[i + 1] > last_pa)
638 			last_pa = dump_avail[i + 1];
639 	page_range = last_pa / PAGE_SIZE;
640 	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
641 	new_end -= vm_page_dump_size;
642 	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
643 	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
644 	bzero((void *)vm_page_dump, vm_page_dump_size);
645 #else
646 	(void)last_pa;
647 #endif
648 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
649     defined(__riscv)
650 	/*
651 	 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
652 	 * When pmap_map() uses the direct map, they are not automatically
653 	 * included.
654 	 */
655 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
656 		dump_add_page(pa);
657 #endif
658 	phys_avail[biggestone + 1] = new_end;
659 #ifdef __amd64__
660 	/*
661 	 * Request that the physical pages underlying the message buffer be
662 	 * included in a crash dump.  Since the message buffer is accessed
663 	 * through the direct map, they are not automatically included.
664 	 */
665 	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
666 	last_pa = pa + round_page(msgbufsize);
667 	while (pa < last_pa) {
668 		dump_add_page(pa);
669 		pa += PAGE_SIZE;
670 	}
671 #endif
672 	/*
673 	 * Compute the number of pages of memory that will be available for
674 	 * use, taking into account the overhead of a page structure per page.
675 	 * In other words, solve
676 	 *	"available physical memory" - round_page(page_range *
677 	 *	    sizeof(struct vm_page)) = page_range * PAGE_SIZE
678 	 * for page_range.
679 	 */
680 	low_avail = phys_avail[0];
681 	high_avail = phys_avail[1];
682 	for (i = 0; i < vm_phys_nsegs; i++) {
683 		if (vm_phys_segs[i].start < low_avail)
684 			low_avail = vm_phys_segs[i].start;
685 		if (vm_phys_segs[i].end > high_avail)
686 			high_avail = vm_phys_segs[i].end;
687 	}
688 	/* Skip the first chunk.  It is already accounted for. */
689 	for (i = 2; phys_avail[i + 1] != 0; i += 2) {
690 		if (phys_avail[i] < low_avail)
691 			low_avail = phys_avail[i];
692 		if (phys_avail[i + 1] > high_avail)
693 			high_avail = phys_avail[i + 1];
694 	}
695 	first_page = low_avail / PAGE_SIZE;
696 #ifdef VM_PHYSSEG_SPARSE
697 	size = 0;
698 	for (i = 0; i < vm_phys_nsegs; i++)
699 		size += vm_phys_segs[i].end - vm_phys_segs[i].start;
700 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
701 		size += phys_avail[i + 1] - phys_avail[i];
702 #elif defined(VM_PHYSSEG_DENSE)
703 	size = high_avail - low_avail;
704 #else
705 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
706 #endif
707 
708 #ifdef VM_PHYSSEG_DENSE
709 	/*
710 	 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
711 	 * the overhead of a page structure per page only if vm_page_array is
712 	 * allocated from the last physical memory chunk.  Otherwise, we must
713 	 * allocate page structures representing the physical memory
714 	 * underlying vm_page_array, even though they will not be used.
715 	 */
716 	if (new_end != high_avail)
717 		page_range = size / PAGE_SIZE;
718 	else
719 #endif
720 	{
721 		page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
722 
723 		/*
724 		 * If the partial bytes remaining are large enough for
725 		 * a page (PAGE_SIZE) without a corresponding
726 		 * 'struct vm_page', then new_end will contain an
727 		 * extra page after subtracting the length of the VM
728 		 * page array.  Compensate by subtracting an extra
729 		 * page from new_end.
730 		 */
731 		if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
732 			if (new_end == high_avail)
733 				high_avail -= PAGE_SIZE;
734 			new_end -= PAGE_SIZE;
735 		}
736 	}
737 	end = new_end;
738 
739 	/*
740 	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
741 	 * However, because this page is allocated from KVM, out-of-bounds
742 	 * accesses using the direct map will not be trapped.
743 	 */
744 	vaddr += PAGE_SIZE;
745 
746 	/*
747 	 * Allocate physical memory for the page structures, and map it.
748 	 */
749 	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
750 	mapped = pmap_map(&vaddr, new_end, end,
751 	    VM_PROT_READ | VM_PROT_WRITE);
752 	vm_page_array = (vm_page_t)mapped;
753 	vm_page_array_size = page_range;
754 
755 #if VM_NRESERVLEVEL > 0
756 	/*
757 	 * Allocate physical memory for the reservation management system's
758 	 * data structures, and map it.
759 	 */
760 	if (high_avail == end)
761 		high_avail = new_end;
762 	new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
763 #endif
764 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
765     defined(__riscv)
766 	/*
767 	 * Include vm_page_array and vm_reserv_array in a crash dump.
768 	 */
769 	for (pa = new_end; pa < end; pa += PAGE_SIZE)
770 		dump_add_page(pa);
771 #endif
772 	phys_avail[biggestone + 1] = new_end;
773 
774 	/*
775 	 * Add physical memory segments corresponding to the available
776 	 * physical pages.
777 	 */
778 	for (i = 0; phys_avail[i + 1] != 0; i += 2)
779 		vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
780 
781 	/*
782 	 * Initialize the physical memory allocator.
783 	 */
784 	vm_phys_init();
785 
786 	/*
787 	 * Initialize the page structures and add every available page to the
788 	 * physical memory allocator's free lists.
789 	 */
790 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
791 	for (ii = 0; ii < vm_page_array_size; ii++) {
792 		m = &vm_page_array[ii];
793 		vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0);
794 		m->flags = PG_FICTITIOUS;
795 	}
796 #endif
797 	vm_cnt.v_page_count = 0;
798 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
799 		seg = &vm_phys_segs[segind];
800 		for (m = seg->first_page, pa = seg->start; pa < seg->end;
801 		    m++, pa += PAGE_SIZE)
802 			vm_page_init_page(m, pa, segind);
803 
804 		/*
805 		 * Add the segment to the free lists only if it is covered by
806 		 * one of the ranges in phys_avail.  Because we've added the
807 		 * ranges to the vm_phys_segs array, we can assume that each
808 		 * segment is either entirely contained in one of the ranges,
809 		 * or doesn't overlap any of them.
810 		 */
811 		for (i = 0; phys_avail[i + 1] != 0; i += 2) {
812 			struct vm_domain *vmd;
813 
814 			if (seg->start < phys_avail[i] ||
815 			    seg->end > phys_avail[i + 1])
816 				continue;
817 
818 			m = seg->first_page;
819 			pagecount = (u_long)atop(seg->end - seg->start);
820 
821 			vmd = VM_DOMAIN(seg->domain);
822 			vm_domain_free_lock(vmd);
823 			vm_phys_free_contig(m, pagecount);
824 			vm_domain_free_unlock(vmd);
825 			vm_domain_freecnt_inc(vmd, pagecount);
826 			vm_cnt.v_page_count += (u_int)pagecount;
827 
828 			vmd = VM_DOMAIN(seg->domain);
829 			vmd->vmd_page_count += (u_int)pagecount;
830 			vmd->vmd_segs |= 1UL << m->segind;
831 			break;
832 		}
833 	}
834 
835 	/*
836 	 * Remove blacklisted pages from the physical memory allocator.
837 	 */
838 	TAILQ_INIT(&blacklist_head);
839 	vm_page_blacklist_load(&list, &listend);
840 	vm_page_blacklist_check(list, listend);
841 
842 	list = kern_getenv("vm.blacklist");
843 	vm_page_blacklist_check(list, NULL);
844 
845 	freeenv(list);
846 #if VM_NRESERVLEVEL > 0
847 	/*
848 	 * Initialize the reservation management system.
849 	 */
850 	vm_reserv_init();
851 #endif
852 
853 	return (vaddr);
854 }
855 
856 void
vm_page_reference(vm_page_t m)857 vm_page_reference(vm_page_t m)
858 {
859 
860 	vm_page_aflag_set(m, PGA_REFERENCED);
861 }
862 
863 /*
864  *	vm_page_busy_downgrade:
865  *
866  *	Downgrade an exclusive busy page into a single shared busy page.
867  */
868 void
vm_page_busy_downgrade(vm_page_t m)869 vm_page_busy_downgrade(vm_page_t m)
870 {
871 	u_int x;
872 	bool locked;
873 
874 	vm_page_assert_xbusied(m);
875 	locked = mtx_owned(vm_page_lockptr(m));
876 
877 	for (;;) {
878 		x = m->busy_lock;
879 		x &= VPB_BIT_WAITERS;
880 		if (x != 0 && !locked)
881 			vm_page_lock(m);
882 		if (atomic_cmpset_rel_int(&m->busy_lock,
883 		    VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
884 			break;
885 		if (x != 0 && !locked)
886 			vm_page_unlock(m);
887 	}
888 	if (x != 0) {
889 		wakeup(m);
890 		if (!locked)
891 			vm_page_unlock(m);
892 	}
893 }
894 
895 /*
896  *	vm_page_sbusied:
897  *
898  *	Return a positive value if the page is shared busied, 0 otherwise.
899  */
900 int
vm_page_sbusied(vm_page_t m)901 vm_page_sbusied(vm_page_t m)
902 {
903 	u_int x;
904 
905 	x = m->busy_lock;
906 	return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
907 }
908 
909 /*
910  *	vm_page_sunbusy:
911  *
912  *	Shared unbusy a page.
913  */
914 void
vm_page_sunbusy(vm_page_t m)915 vm_page_sunbusy(vm_page_t m)
916 {
917 	u_int x;
918 
919 	vm_page_lock_assert(m, MA_NOTOWNED);
920 	vm_page_assert_sbusied(m);
921 
922 	for (;;) {
923 		x = m->busy_lock;
924 		if (VPB_SHARERS(x) > 1) {
925 			if (atomic_cmpset_int(&m->busy_lock, x,
926 			    x - VPB_ONE_SHARER))
927 				break;
928 			continue;
929 		}
930 		if ((x & VPB_BIT_WAITERS) == 0) {
931 			KASSERT(x == VPB_SHARERS_WORD(1),
932 			    ("vm_page_sunbusy: invalid lock state"));
933 			if (atomic_cmpset_int(&m->busy_lock,
934 			    VPB_SHARERS_WORD(1), VPB_UNBUSIED))
935 				break;
936 			continue;
937 		}
938 		KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
939 		    ("vm_page_sunbusy: invalid lock state for waiters"));
940 
941 		vm_page_lock(m);
942 		if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
943 			vm_page_unlock(m);
944 			continue;
945 		}
946 		wakeup(m);
947 		vm_page_unlock(m);
948 		break;
949 	}
950 }
951 
952 /*
953  *	vm_page_busy_sleep:
954  *
955  *	Sleep and release the page lock, using the page pointer as wchan.
956  *	This is used to implement the hard-path of busying mechanism.
957  *
958  *	The given page must be locked.
959  *
960  *	If nonshared is true, sleep only if the page is xbusy.
961  */
962 void
vm_page_busy_sleep(vm_page_t m,const char * wmesg,bool nonshared)963 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
964 {
965 	u_int x;
966 
967 	vm_page_assert_locked(m);
968 
969 	x = m->busy_lock;
970 	if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
971 	    ((x & VPB_BIT_WAITERS) == 0 &&
972 	    !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
973 		vm_page_unlock(m);
974 		return;
975 	}
976 	msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
977 }
978 
979 /*
980  *	vm_page_trysbusy:
981  *
982  *	Try to shared busy a page.
983  *	If the operation succeeds 1 is returned otherwise 0.
984  *	The operation never sleeps.
985  */
986 int
vm_page_trysbusy(vm_page_t m)987 vm_page_trysbusy(vm_page_t m)
988 {
989 	u_int x;
990 
991 	for (;;) {
992 		x = m->busy_lock;
993 		if ((x & VPB_BIT_SHARED) == 0)
994 			return (0);
995 		if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
996 			return (1);
997 	}
998 }
999 
1000 static void
vm_page_xunbusy_locked(vm_page_t m)1001 vm_page_xunbusy_locked(vm_page_t m)
1002 {
1003 
1004 	vm_page_assert_xbusied(m);
1005 	vm_page_assert_locked(m);
1006 
1007 	atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1008 	/* There is a waiter, do wakeup() instead of vm_page_flash(). */
1009 	wakeup(m);
1010 }
1011 
1012 void
vm_page_xunbusy_maybelocked(vm_page_t m)1013 vm_page_xunbusy_maybelocked(vm_page_t m)
1014 {
1015 	bool lockacq;
1016 
1017 	vm_page_assert_xbusied(m);
1018 
1019 	/*
1020 	 * Fast path for unbusy.  If it succeeds, we know that there
1021 	 * are no waiters, so we do not need a wakeup.
1022 	 */
1023 	if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
1024 	    VPB_UNBUSIED))
1025 		return;
1026 
1027 	lockacq = !mtx_owned(vm_page_lockptr(m));
1028 	if (lockacq)
1029 		vm_page_lock(m);
1030 	vm_page_xunbusy_locked(m);
1031 	if (lockacq)
1032 		vm_page_unlock(m);
1033 }
1034 
1035 /*
1036  *	vm_page_xunbusy_hard:
1037  *
1038  *	Called after the first try the exclusive unbusy of a page failed.
1039  *	It is assumed that the waiters bit is on.
1040  */
1041 void
vm_page_xunbusy_hard(vm_page_t m)1042 vm_page_xunbusy_hard(vm_page_t m)
1043 {
1044 
1045 	vm_page_assert_xbusied(m);
1046 
1047 	vm_page_lock(m);
1048 	vm_page_xunbusy_locked(m);
1049 	vm_page_unlock(m);
1050 }
1051 
1052 /*
1053  *	vm_page_flash:
1054  *
1055  *	Wakeup anyone waiting for the page.
1056  *	The ownership bits do not change.
1057  *
1058  *	The given page must be locked.
1059  */
1060 void
vm_page_flash(vm_page_t m)1061 vm_page_flash(vm_page_t m)
1062 {
1063 	u_int x;
1064 
1065 	vm_page_lock_assert(m, MA_OWNED);
1066 
1067 	for (;;) {
1068 		x = m->busy_lock;
1069 		if ((x & VPB_BIT_WAITERS) == 0)
1070 			return;
1071 		if (atomic_cmpset_int(&m->busy_lock, x,
1072 		    x & (~VPB_BIT_WAITERS)))
1073 			break;
1074 	}
1075 	wakeup(m);
1076 }
1077 
1078 /*
1079  * Avoid releasing and reacquiring the same page lock.
1080  */
1081 void
vm_page_change_lock(vm_page_t m,struct mtx ** mtx)1082 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
1083 {
1084 	struct mtx *mtx1;
1085 
1086 	mtx1 = vm_page_lockptr(m);
1087 	if (*mtx == mtx1)
1088 		return;
1089 	if (*mtx != NULL)
1090 		mtx_unlock(*mtx);
1091 	*mtx = mtx1;
1092 	mtx_lock(mtx1);
1093 }
1094 
1095 /*
1096  * Keep page from being freed by the page daemon
1097  * much of the same effect as wiring, except much lower
1098  * overhead and should be used only for *very* temporary
1099  * holding ("wiring").
1100  */
1101 void
vm_page_hold(vm_page_t mem)1102 vm_page_hold(vm_page_t mem)
1103 {
1104 
1105 	vm_page_lock_assert(mem, MA_OWNED);
1106         mem->hold_count++;
1107 }
1108 
1109 void
vm_page_unhold(vm_page_t mem)1110 vm_page_unhold(vm_page_t mem)
1111 {
1112 
1113 	vm_page_lock_assert(mem, MA_OWNED);
1114 	KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
1115 	--mem->hold_count;
1116 	if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
1117 		vm_page_free_toq(mem);
1118 }
1119 
1120 /*
1121  *	vm_page_unhold_pages:
1122  *
1123  *	Unhold each of the pages that is referenced by the given array.
1124  */
1125 void
vm_page_unhold_pages(vm_page_t * ma,int count)1126 vm_page_unhold_pages(vm_page_t *ma, int count)
1127 {
1128 	struct mtx *mtx;
1129 
1130 	mtx = NULL;
1131 	for (; count != 0; count--) {
1132 		vm_page_change_lock(*ma, &mtx);
1133 		vm_page_unhold(*ma);
1134 		ma++;
1135 	}
1136 	if (mtx != NULL)
1137 		mtx_unlock(mtx);
1138 }
1139 
1140 vm_page_t
PHYS_TO_VM_PAGE(vm_paddr_t pa)1141 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1142 {
1143 	vm_page_t m;
1144 
1145 #ifdef VM_PHYSSEG_SPARSE
1146 	m = vm_phys_paddr_to_vm_page(pa);
1147 	if (m == NULL)
1148 		m = vm_phys_fictitious_to_vm_page(pa);
1149 	return (m);
1150 #elif defined(VM_PHYSSEG_DENSE)
1151 	long pi;
1152 
1153 	pi = atop(pa);
1154 	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1155 		m = &vm_page_array[pi - first_page];
1156 		return (m);
1157 	}
1158 	return (vm_phys_fictitious_to_vm_page(pa));
1159 #else
1160 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1161 #endif
1162 }
1163 
1164 /*
1165  *	vm_page_getfake:
1166  *
1167  *	Create a fictitious page with the specified physical address and
1168  *	memory attribute.  The memory attribute is the only the machine-
1169  *	dependent aspect of a fictitious page that must be initialized.
1170  */
1171 vm_page_t
vm_page_getfake(vm_paddr_t paddr,vm_memattr_t memattr)1172 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1173 {
1174 	vm_page_t m;
1175 
1176 	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1177 	vm_page_initfake(m, paddr, memattr);
1178 	return (m);
1179 }
1180 
1181 void
vm_page_initfake(vm_page_t m,vm_paddr_t paddr,vm_memattr_t memattr)1182 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1183 {
1184 
1185 	if ((m->flags & PG_FICTITIOUS) != 0) {
1186 		/*
1187 		 * The page's memattr might have changed since the
1188 		 * previous initialization.  Update the pmap to the
1189 		 * new memattr.
1190 		 */
1191 		goto memattr;
1192 	}
1193 	m->phys_addr = paddr;
1194 	m->queue = PQ_NONE;
1195 	/* Fictitious pages don't use "segind". */
1196 	m->flags = PG_FICTITIOUS;
1197 	/* Fictitious pages don't use "order" or "pool". */
1198 	m->oflags = VPO_UNMANAGED;
1199 	m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1200 	m->wire_count = 1;
1201 	pmap_page_init(m);
1202 memattr:
1203 	pmap_page_set_memattr(m, memattr);
1204 }
1205 
1206 /*
1207  *	vm_page_putfake:
1208  *
1209  *	Release a fictitious page.
1210  */
1211 void
vm_page_putfake(vm_page_t m)1212 vm_page_putfake(vm_page_t m)
1213 {
1214 
1215 	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1216 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1217 	    ("vm_page_putfake: bad page %p", m));
1218 	uma_zfree(fakepg_zone, m);
1219 }
1220 
1221 /*
1222  *	vm_page_updatefake:
1223  *
1224  *	Update the given fictitious page to the specified physical address and
1225  *	memory attribute.
1226  */
1227 void
vm_page_updatefake(vm_page_t m,vm_paddr_t paddr,vm_memattr_t memattr)1228 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1229 {
1230 
1231 	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1232 	    ("vm_page_updatefake: bad page %p", m));
1233 	m->phys_addr = paddr;
1234 	pmap_page_set_memattr(m, memattr);
1235 }
1236 
1237 /*
1238  *	vm_page_free:
1239  *
1240  *	Free a page.
1241  */
1242 void
vm_page_free(vm_page_t m)1243 vm_page_free(vm_page_t m)
1244 {
1245 
1246 	m->flags &= ~PG_ZERO;
1247 	vm_page_free_toq(m);
1248 }
1249 
1250 /*
1251  *	vm_page_free_zero:
1252  *
1253  *	Free a page to the zerod-pages queue
1254  */
1255 void
vm_page_free_zero(vm_page_t m)1256 vm_page_free_zero(vm_page_t m)
1257 {
1258 
1259 	m->flags |= PG_ZERO;
1260 	vm_page_free_toq(m);
1261 }
1262 
1263 /*
1264  * Unbusy and handle the page queueing for a page from a getpages request that
1265  * was optionally read ahead or behind.
1266  */
1267 void
vm_page_readahead_finish(vm_page_t m)1268 vm_page_readahead_finish(vm_page_t m)
1269 {
1270 
1271 	/* We shouldn't put invalid pages on queues. */
1272 	KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1273 
1274 	/*
1275 	 * Since the page is not the actually needed one, whether it should
1276 	 * be activated or deactivated is not obvious.  Empirical results
1277 	 * have shown that deactivating the page is usually the best choice,
1278 	 * unless the page is wanted by another thread.
1279 	 */
1280 	vm_page_lock(m);
1281 	if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1282 		vm_page_activate(m);
1283 	else
1284 		vm_page_deactivate(m);
1285 	vm_page_unlock(m);
1286 	vm_page_xunbusy(m);
1287 }
1288 
1289 /*
1290  *	vm_page_sleep_if_busy:
1291  *
1292  *	Sleep and release the page queues lock if the page is busied.
1293  *	Returns TRUE if the thread slept.
1294  *
1295  *	The given page must be unlocked and object containing it must
1296  *	be locked.
1297  */
1298 int
vm_page_sleep_if_busy(vm_page_t m,const char * msg)1299 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1300 {
1301 	vm_object_t obj;
1302 
1303 	vm_page_lock_assert(m, MA_NOTOWNED);
1304 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1305 
1306 	if (vm_page_busied(m)) {
1307 		/*
1308 		 * The page-specific object must be cached because page
1309 		 * identity can change during the sleep, causing the
1310 		 * re-lock of a different object.
1311 		 * It is assumed that a reference to the object is already
1312 		 * held by the callers.
1313 		 */
1314 		obj = m->object;
1315 		vm_page_lock(m);
1316 		VM_OBJECT_WUNLOCK(obj);
1317 		vm_page_busy_sleep(m, msg, false);
1318 		VM_OBJECT_WLOCK(obj);
1319 		return (TRUE);
1320 	}
1321 	return (FALSE);
1322 }
1323 
1324 /*
1325  *	vm_page_dirty_KBI:		[ internal use only ]
1326  *
1327  *	Set all bits in the page's dirty field.
1328  *
1329  *	The object containing the specified page must be locked if the
1330  *	call is made from the machine-independent layer.
1331  *
1332  *	See vm_page_clear_dirty_mask().
1333  *
1334  *	This function should only be called by vm_page_dirty().
1335  */
1336 void
vm_page_dirty_KBI(vm_page_t m)1337 vm_page_dirty_KBI(vm_page_t m)
1338 {
1339 
1340 	/* Refer to this operation by its public name. */
1341 	KASSERT(m->valid == VM_PAGE_BITS_ALL,
1342 	    ("vm_page_dirty: page is invalid!"));
1343 	m->dirty = VM_PAGE_BITS_ALL;
1344 }
1345 
1346 /*
1347  *	vm_page_insert:		[ internal use only ]
1348  *
1349  *	Inserts the given mem entry into the object and object list.
1350  *
1351  *	The object must be locked.
1352  */
1353 int
vm_page_insert(vm_page_t m,vm_object_t object,vm_pindex_t pindex)1354 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1355 {
1356 	vm_page_t mpred;
1357 
1358 	VM_OBJECT_ASSERT_WLOCKED(object);
1359 	mpred = vm_radix_lookup_le(&object->rtree, pindex);
1360 	return (vm_page_insert_after(m, object, pindex, mpred));
1361 }
1362 
1363 /*
1364  *	vm_page_insert_after:
1365  *
1366  *	Inserts the page "m" into the specified object at offset "pindex".
1367  *
1368  *	The page "mpred" must immediately precede the offset "pindex" within
1369  *	the specified object.
1370  *
1371  *	The object must be locked.
1372  */
1373 static int
vm_page_insert_after(vm_page_t m,vm_object_t object,vm_pindex_t pindex,vm_page_t mpred)1374 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1375     vm_page_t mpred)
1376 {
1377 	vm_page_t msucc;
1378 
1379 	VM_OBJECT_ASSERT_WLOCKED(object);
1380 	KASSERT(m->object == NULL,
1381 	    ("vm_page_insert_after: page already inserted"));
1382 	if (mpred != NULL) {
1383 		KASSERT(mpred->object == object,
1384 		    ("vm_page_insert_after: object doesn't contain mpred"));
1385 		KASSERT(mpred->pindex < pindex,
1386 		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1387 		msucc = TAILQ_NEXT(mpred, listq);
1388 	} else
1389 		msucc = TAILQ_FIRST(&object->memq);
1390 	if (msucc != NULL)
1391 		KASSERT(msucc->pindex > pindex,
1392 		    ("vm_page_insert_after: msucc doesn't succeed pindex"));
1393 
1394 	/*
1395 	 * Record the object/offset pair in this page
1396 	 */
1397 	m->object = object;
1398 	m->pindex = pindex;
1399 
1400 	/*
1401 	 * Now link into the object's ordered list of backed pages.
1402 	 */
1403 	if (vm_radix_insert(&object->rtree, m)) {
1404 		m->object = NULL;
1405 		m->pindex = 0;
1406 		return (1);
1407 	}
1408 	vm_page_insert_radixdone(m, object, mpred);
1409 	return (0);
1410 }
1411 
1412 /*
1413  *	vm_page_insert_radixdone:
1414  *
1415  *	Complete page "m" insertion into the specified object after the
1416  *	radix trie hooking.
1417  *
1418  *	The page "mpred" must precede the offset "m->pindex" within the
1419  *	specified object.
1420  *
1421  *	The object must be locked.
1422  */
1423 static void
vm_page_insert_radixdone(vm_page_t m,vm_object_t object,vm_page_t mpred)1424 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1425 {
1426 
1427 	VM_OBJECT_ASSERT_WLOCKED(object);
1428 	KASSERT(object != NULL && m->object == object,
1429 	    ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1430 	if (mpred != NULL) {
1431 		KASSERT(mpred->object == object,
1432 		    ("vm_page_insert_after: object doesn't contain mpred"));
1433 		KASSERT(mpred->pindex < m->pindex,
1434 		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1435 	}
1436 
1437 	if (mpred != NULL)
1438 		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1439 	else
1440 		TAILQ_INSERT_HEAD(&object->memq, m, listq);
1441 
1442 	/*
1443 	 * Show that the object has one more resident page.
1444 	 */
1445 	object->resident_page_count++;
1446 
1447 	/*
1448 	 * Hold the vnode until the last page is released.
1449 	 */
1450 	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1451 		vhold(object->handle);
1452 
1453 	/*
1454 	 * Since we are inserting a new and possibly dirty page,
1455 	 * update the object's OBJ_MIGHTBEDIRTY flag.
1456 	 */
1457 	if (pmap_page_is_write_mapped(m))
1458 		vm_object_set_writeable_dirty(object);
1459 }
1460 
1461 /*
1462  *	vm_page_remove:
1463  *
1464  *	Removes the specified page from its containing object, but does not
1465  *	invalidate any backing storage.  Return true if the page may be safely
1466  *	freed and false otherwise.
1467  *
1468  *	The object must be locked.  The page must be locked if it is managed.
1469  */
1470 bool
vm_page_remove(vm_page_t m)1471 vm_page_remove(vm_page_t m)
1472 {
1473 	vm_object_t object;
1474 	vm_page_t mrem;
1475 
1476 	object = m->object;
1477 
1478 	if ((m->oflags & VPO_UNMANAGED) == 0)
1479 		vm_page_assert_locked(m);
1480 	VM_OBJECT_ASSERT_WLOCKED(object);
1481 	if (vm_page_xbusied(m))
1482 		vm_page_xunbusy_maybelocked(m);
1483 	mrem = vm_radix_remove(&object->rtree, m->pindex);
1484 	KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1485 
1486 	/*
1487 	 * Now remove from the object's list of backed pages.
1488 	 */
1489 	TAILQ_REMOVE(&object->memq, m, listq);
1490 
1491 	/*
1492 	 * And show that the object has one fewer resident page.
1493 	 */
1494 	object->resident_page_count--;
1495 
1496 	/*
1497 	 * The vnode may now be recycled.
1498 	 */
1499 	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1500 		vdrop(object->handle);
1501 
1502 	m->object = NULL;
1503 	return (!vm_page_wired(m));
1504 }
1505 
1506 /*
1507  *	vm_page_lookup:
1508  *
1509  *	Returns the page associated with the object/offset
1510  *	pair specified; if none is found, NULL is returned.
1511  *
1512  *	The object must be locked.
1513  */
1514 vm_page_t
vm_page_lookup(vm_object_t object,vm_pindex_t pindex)1515 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1516 {
1517 
1518 	VM_OBJECT_ASSERT_LOCKED(object);
1519 	return (vm_radix_lookup(&object->rtree, pindex));
1520 }
1521 
1522 /*
1523  *	vm_page_find_least:
1524  *
1525  *	Returns the page associated with the object with least pindex
1526  *	greater than or equal to the parameter pindex, or NULL.
1527  *
1528  *	The object must be locked.
1529  */
1530 vm_page_t
vm_page_find_least(vm_object_t object,vm_pindex_t pindex)1531 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1532 {
1533 	vm_page_t m;
1534 
1535 	VM_OBJECT_ASSERT_LOCKED(object);
1536 	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1537 		m = vm_radix_lookup_ge(&object->rtree, pindex);
1538 	return (m);
1539 }
1540 
1541 /*
1542  * Returns the given page's successor (by pindex) within the object if it is
1543  * resident; if none is found, NULL is returned.
1544  *
1545  * The object must be locked.
1546  */
1547 vm_page_t
vm_page_next(vm_page_t m)1548 vm_page_next(vm_page_t m)
1549 {
1550 	vm_page_t next;
1551 
1552 	VM_OBJECT_ASSERT_LOCKED(m->object);
1553 	if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1554 		MPASS(next->object == m->object);
1555 		if (next->pindex != m->pindex + 1)
1556 			next = NULL;
1557 	}
1558 	return (next);
1559 }
1560 
1561 /*
1562  * Returns the given page's predecessor (by pindex) within the object if it is
1563  * resident; if none is found, NULL is returned.
1564  *
1565  * The object must be locked.
1566  */
1567 vm_page_t
vm_page_prev(vm_page_t m)1568 vm_page_prev(vm_page_t m)
1569 {
1570 	vm_page_t prev;
1571 
1572 	VM_OBJECT_ASSERT_LOCKED(m->object);
1573 	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1574 		MPASS(prev->object == m->object);
1575 		if (prev->pindex != m->pindex - 1)
1576 			prev = NULL;
1577 	}
1578 	return (prev);
1579 }
1580 
1581 /*
1582  * Uses the page mnew as a replacement for an existing page at index
1583  * pindex which must be already present in the object.
1584  *
1585  * The existing page must not be on a paging queue.
1586  */
1587 vm_page_t
vm_page_replace(vm_page_t mnew,vm_object_t object,vm_pindex_t pindex)1588 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1589 {
1590 	vm_page_t mold;
1591 
1592 	VM_OBJECT_ASSERT_WLOCKED(object);
1593 	KASSERT(mnew->object == NULL,
1594 	    ("vm_page_replace: page %p already in object", mnew));
1595 	KASSERT(mnew->queue == PQ_NONE,
1596 	    ("vm_page_replace: new page %p is on a paging queue", mnew));
1597 
1598 	/*
1599 	 * This function mostly follows vm_page_insert() and
1600 	 * vm_page_remove() without the radix, object count and vnode
1601 	 * dance.  Double check such functions for more comments.
1602 	 */
1603 
1604 	mnew->object = object;
1605 	mnew->pindex = pindex;
1606 	mold = vm_radix_replace(&object->rtree, mnew);
1607 	KASSERT(mold->queue == PQ_NONE,
1608 	    ("vm_page_replace: old page %p is on a paging queue", mold));
1609 
1610 	/* Keep the resident page list in sorted order. */
1611 	TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1612 	TAILQ_REMOVE(&object->memq, mold, listq);
1613 
1614 	mold->object = NULL;
1615 	vm_page_xunbusy_maybelocked(mold);
1616 
1617 	/*
1618 	 * The object's resident_page_count does not change because we have
1619 	 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1620 	 */
1621 	if (pmap_page_is_write_mapped(mnew))
1622 		vm_object_set_writeable_dirty(object);
1623 	return (mold);
1624 }
1625 
1626 /*
1627  *	vm_page_rename:
1628  *
1629  *	Move the given memory entry from its
1630  *	current object to the specified target object/offset.
1631  *
1632  *	Note: swap associated with the page must be invalidated by the move.  We
1633  *	      have to do this for several reasons:  (1) we aren't freeing the
1634  *	      page, (2) we are dirtying the page, (3) the VM system is probably
1635  *	      moving the page from object A to B, and will then later move
1636  *	      the backing store from A to B and we can't have a conflict.
1637  *
1638  *	Note: we *always* dirty the page.  It is necessary both for the
1639  *	      fact that we moved it, and because we may be invalidating
1640  *	      swap.
1641  *
1642  *	The objects must be locked.
1643  */
1644 int
vm_page_rename(vm_page_t m,vm_object_t new_object,vm_pindex_t new_pindex)1645 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1646 {
1647 	vm_page_t mpred;
1648 	vm_pindex_t opidx;
1649 
1650 	VM_OBJECT_ASSERT_WLOCKED(new_object);
1651 
1652 	mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1653 	KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1654 	    ("vm_page_rename: pindex already renamed"));
1655 
1656 	/*
1657 	 * Create a custom version of vm_page_insert() which does not depend
1658 	 * by m_prev and can cheat on the implementation aspects of the
1659 	 * function.
1660 	 */
1661 	opidx = m->pindex;
1662 	m->pindex = new_pindex;
1663 	if (vm_radix_insert(&new_object->rtree, m)) {
1664 		m->pindex = opidx;
1665 		return (1);
1666 	}
1667 
1668 	/*
1669 	 * The operation cannot fail anymore.  The removal must happen before
1670 	 * the listq iterator is tainted.
1671 	 */
1672 	m->pindex = opidx;
1673 	vm_page_lock(m);
1674 	(void)vm_page_remove(m);
1675 
1676 	/* Return back to the new pindex to complete vm_page_insert(). */
1677 	m->pindex = new_pindex;
1678 	m->object = new_object;
1679 	vm_page_unlock(m);
1680 	vm_page_insert_radixdone(m, new_object, mpred);
1681 	vm_page_dirty(m);
1682 	return (0);
1683 }
1684 
1685 /*
1686  *	vm_page_alloc:
1687  *
1688  *	Allocate and return a page that is associated with the specified
1689  *	object and offset pair.  By default, this page is exclusive busied.
1690  *
1691  *	The caller must always specify an allocation class.
1692  *
1693  *	allocation classes:
1694  *	VM_ALLOC_NORMAL		normal process request
1695  *	VM_ALLOC_SYSTEM		system *really* needs a page
1696  *	VM_ALLOC_INTERRUPT	interrupt time request
1697  *
1698  *	optional allocation flags:
1699  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1700  *				intends to allocate
1701  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1702  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1703  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1704  *				should not be exclusive busy
1705  *	VM_ALLOC_SBUSY		shared busy the allocated page
1706  *	VM_ALLOC_WIRED		wire the allocated page
1707  *	VM_ALLOC_ZERO		prefer a zeroed page
1708  */
1709 vm_page_t
vm_page_alloc(vm_object_t object,vm_pindex_t pindex,int req)1710 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1711 {
1712 
1713 	return (vm_page_alloc_after(object, pindex, req, object != NULL ?
1714 	    vm_radix_lookup_le(&object->rtree, pindex) : NULL));
1715 }
1716 
1717 vm_page_t
vm_page_alloc_domain(vm_object_t object,vm_pindex_t pindex,int domain,int req)1718 vm_page_alloc_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1719     int req)
1720 {
1721 
1722 	return (vm_page_alloc_domain_after(object, pindex, domain, req,
1723 	    object != NULL ? vm_radix_lookup_le(&object->rtree, pindex) :
1724 	    NULL));
1725 }
1726 
1727 /*
1728  * Allocate a page in the specified object with the given page index.  To
1729  * optimize insertion of the page into the object, the caller must also specifiy
1730  * the resident page in the object with largest index smaller than the given
1731  * page index, or NULL if no such page exists.
1732  */
1733 vm_page_t
vm_page_alloc_after(vm_object_t object,vm_pindex_t pindex,int req,vm_page_t mpred)1734 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
1735     int req, vm_page_t mpred)
1736 {
1737 	struct vm_domainset_iter di;
1738 	vm_page_t m;
1739 	int domain;
1740 
1741 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1742 	do {
1743 		m = vm_page_alloc_domain_after(object, pindex, domain, req,
1744 		    mpred);
1745 		if (m != NULL)
1746 			break;
1747 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
1748 
1749 	return (m);
1750 }
1751 
1752 /*
1753  * Returns true if the number of free pages exceeds the minimum
1754  * for the request class and false otherwise.
1755  */
1756 int
vm_domain_allocate(struct vm_domain * vmd,int req,int npages)1757 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
1758 {
1759 	u_int limit, old, new;
1760 
1761 	req = req & VM_ALLOC_CLASS_MASK;
1762 
1763 	/*
1764 	 * The page daemon is allowed to dig deeper into the free page list.
1765 	 */
1766 	if (curproc == pageproc && req != VM_ALLOC_INTERRUPT)
1767 		req = VM_ALLOC_SYSTEM;
1768 	if (req == VM_ALLOC_INTERRUPT)
1769 		limit = 0;
1770 	else if (req == VM_ALLOC_SYSTEM)
1771 		limit = vmd->vmd_interrupt_free_min;
1772 	else
1773 		limit = vmd->vmd_free_reserved;
1774 
1775 	/*
1776 	 * Attempt to reserve the pages.  Fail if we're below the limit.
1777 	 */
1778 	limit += npages;
1779 	old = vmd->vmd_free_count;
1780 	do {
1781 		if (old < limit)
1782 			return (0);
1783 		new = old - npages;
1784 	} while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
1785 
1786 	/* Wake the page daemon if we've crossed the threshold. */
1787 	if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
1788 		pagedaemon_wakeup(vmd->vmd_domain);
1789 
1790 	/* Only update bitsets on transitions. */
1791 	if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
1792 	    (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
1793 		vm_domain_set(vmd);
1794 
1795 	return (1);
1796 }
1797 
1798 vm_page_t
vm_page_alloc_domain_after(vm_object_t object,vm_pindex_t pindex,int domain,int req,vm_page_t mpred)1799 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
1800     int req, vm_page_t mpred)
1801 {
1802 	struct vm_domain *vmd;
1803 	vm_page_t m;
1804 	int flags, pool;
1805 
1806 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1807 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1808 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1809 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1810 	    ("inconsistent object(%p)/req(%x)", object, req));
1811 	KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
1812 	    ("Can't sleep and retry object insertion."));
1813 	KASSERT(mpred == NULL || mpred->pindex < pindex,
1814 	    ("mpred %p doesn't precede pindex 0x%jx", mpred,
1815 	    (uintmax_t)pindex));
1816 	if (object != NULL)
1817 		VM_OBJECT_ASSERT_WLOCKED(object);
1818 
1819 	flags = 0;
1820 	m = NULL;
1821 	pool = object != NULL ? VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT;
1822 again:
1823 #if VM_NRESERVLEVEL > 0
1824 	/*
1825 	 * Can we allocate the page from a reservation?
1826 	 */
1827 	if (vm_object_reserv(object) &&
1828 	    ((m = vm_reserv_extend(req, object, pindex, domain, mpred)) != NULL ||
1829 	    (m = vm_reserv_alloc_page(req, object, pindex, domain, mpred)) != NULL)) {
1830 		domain = vm_phys_domain(m);
1831 		vmd = VM_DOMAIN(domain);
1832 		goto found;
1833 	}
1834 #endif
1835 	vmd = VM_DOMAIN(domain);
1836 	if (vmd->vmd_pgcache[pool].zone != NULL) {
1837 		m = uma_zalloc(vmd->vmd_pgcache[pool].zone, M_NOWAIT);
1838 		if (m != NULL) {
1839 			flags |= PG_PCPU_CACHE;
1840 			goto found;
1841 		}
1842 	}
1843 	if (vm_domain_allocate(vmd, req, 1)) {
1844 		/*
1845 		 * If not, allocate it from the free page queues.
1846 		 */
1847 		vm_domain_free_lock(vmd);
1848 		m = vm_phys_alloc_pages(domain, pool, 0);
1849 		vm_domain_free_unlock(vmd);
1850 		if (m == NULL) {
1851 			vm_domain_freecnt_inc(vmd, 1);
1852 #if VM_NRESERVLEVEL > 0
1853 			if (vm_reserv_reclaim_inactive(domain))
1854 				goto again;
1855 #endif
1856 		}
1857 	}
1858 	if (m == NULL) {
1859 		/*
1860 		 * Not allocatable, give up.
1861 		 */
1862 		if (vm_domain_alloc_fail(vmd, object, req))
1863 			goto again;
1864 		return (NULL);
1865 	}
1866 
1867 	/*
1868 	 * At this point we had better have found a good page.
1869 	 */
1870 found:
1871 	vm_page_dequeue(m);
1872 	vm_page_alloc_check(m);
1873 
1874 	/*
1875 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1876 	 */
1877 	if ((req & VM_ALLOC_ZERO) != 0)
1878 		flags |= (m->flags & PG_ZERO);
1879 	if ((req & VM_ALLOC_NODUMP) != 0)
1880 		flags |= PG_NODUMP;
1881 	m->flags = flags;
1882 	m->aflags = 0;
1883 	m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1884 	    VPO_UNMANAGED : 0;
1885 	m->busy_lock = VPB_UNBUSIED;
1886 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1887 		m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1888 	if ((req & VM_ALLOC_SBUSY) != 0)
1889 		m->busy_lock = VPB_SHARERS_WORD(1);
1890 	if (req & VM_ALLOC_WIRED) {
1891 		/*
1892 		 * The page lock is not required for wiring a page until that
1893 		 * page is inserted into the object.
1894 		 */
1895 		vm_wire_add(1);
1896 		m->wire_count = 1;
1897 	}
1898 	m->act_count = 0;
1899 
1900 	if (object != NULL) {
1901 		if (vm_page_insert_after(m, object, pindex, mpred)) {
1902 			if (req & VM_ALLOC_WIRED) {
1903 				vm_wire_sub(1);
1904 				m->wire_count = 0;
1905 			}
1906 			KASSERT(m->object == NULL, ("page %p has object", m));
1907 			m->oflags = VPO_UNMANAGED;
1908 			m->busy_lock = VPB_UNBUSIED;
1909 			/* Don't change PG_ZERO. */
1910 			vm_page_free_toq(m);
1911 			if (req & VM_ALLOC_WAITFAIL) {
1912 				VM_OBJECT_WUNLOCK(object);
1913 				vm_radix_wait();
1914 				VM_OBJECT_WLOCK(object);
1915 			}
1916 			return (NULL);
1917 		}
1918 
1919 		/* Ignore device objects; the pager sets "memattr" for them. */
1920 		if (object->memattr != VM_MEMATTR_DEFAULT &&
1921 		    (object->flags & OBJ_FICTITIOUS) == 0)
1922 			pmap_page_set_memattr(m, object->memattr);
1923 	} else
1924 		m->pindex = pindex;
1925 
1926 	return (m);
1927 }
1928 
1929 /*
1930  *	vm_page_alloc_contig:
1931  *
1932  *	Allocate a contiguous set of physical pages of the given size "npages"
1933  *	from the free lists.  All of the physical pages must be at or above
1934  *	the given physical address "low" and below the given physical address
1935  *	"high".  The given value "alignment" determines the alignment of the
1936  *	first physical page in the set.  If the given value "boundary" is
1937  *	non-zero, then the set of physical pages cannot cross any physical
1938  *	address boundary that is a multiple of that value.  Both "alignment"
1939  *	and "boundary" must be a power of two.
1940  *
1941  *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1942  *	then the memory attribute setting for the physical pages is configured
1943  *	to the object's memory attribute setting.  Otherwise, the memory
1944  *	attribute setting for the physical pages is configured to "memattr",
1945  *	overriding the object's memory attribute setting.  However, if the
1946  *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1947  *	memory attribute setting for the physical pages cannot be configured
1948  *	to VM_MEMATTR_DEFAULT.
1949  *
1950  *	The specified object may not contain fictitious pages.
1951  *
1952  *	The caller must always specify an allocation class.
1953  *
1954  *	allocation classes:
1955  *	VM_ALLOC_NORMAL		normal process request
1956  *	VM_ALLOC_SYSTEM		system *really* needs a page
1957  *	VM_ALLOC_INTERRUPT	interrupt time request
1958  *
1959  *	optional allocation flags:
1960  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1961  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1962  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1963  *				should not be exclusive busy
1964  *	VM_ALLOC_SBUSY		shared busy the allocated page
1965  *	VM_ALLOC_WIRED		wire the allocated page
1966  *	VM_ALLOC_ZERO		prefer a zeroed page
1967  */
1968 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)1969 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1970     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1971     vm_paddr_t boundary, vm_memattr_t memattr)
1972 {
1973 	struct vm_domainset_iter di;
1974 	vm_page_t m;
1975 	int domain;
1976 
1977 	vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
1978 	do {
1979 		m = vm_page_alloc_contig_domain(object, pindex, domain, req,
1980 		    npages, low, high, alignment, boundary, memattr);
1981 		if (m != NULL)
1982 			break;
1983 	} while (vm_domainset_iter_page(&di, object, &domain) == 0);
1984 
1985 	return (m);
1986 }
1987 
1988 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)1989 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
1990     int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1991     vm_paddr_t boundary, vm_memattr_t memattr)
1992 {
1993 	struct vm_domain *vmd;
1994 	vm_page_t m, m_ret, mpred;
1995 	u_int busy_lock, flags, oflags;
1996 
1997 	mpred = NULL;	/* XXX: pacify gcc */
1998 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1999 	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
2000 	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2001 	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2002 	    ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
2003 	    req));
2004 	KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
2005 	    ("Can't sleep and retry object insertion."));
2006 	if (object != NULL) {
2007 		VM_OBJECT_ASSERT_WLOCKED(object);
2008 		KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2009 		    ("vm_page_alloc_contig: object %p has fictitious pages",
2010 		    object));
2011 	}
2012 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2013 
2014 	if (object != NULL) {
2015 		mpred = vm_radix_lookup_le(&object->rtree, pindex);
2016 		KASSERT(mpred == NULL || mpred->pindex != pindex,
2017 		    ("vm_page_alloc_contig: pindex already allocated"));
2018 	}
2019 
2020 	/*
2021 	 * Can we allocate the pages without the number of free pages falling
2022 	 * below the lower bound for the allocation class?
2023 	 */
2024 	m_ret = NULL;
2025 again:
2026 #if VM_NRESERVLEVEL > 0
2027 	/*
2028 	 * Can we allocate the pages from a reservation?
2029 	 */
2030 	if (vm_object_reserv(object) &&
2031 	    ((m_ret = vm_reserv_extend_contig(req, object, pindex, domain,
2032 	    npages, low, high, alignment, boundary, mpred)) != NULL ||
2033 	    (m_ret = vm_reserv_alloc_contig(req, object, pindex, domain,
2034 	    npages, low, high, alignment, boundary, mpred)) != NULL)) {
2035 		domain = vm_phys_domain(m_ret);
2036 		vmd = VM_DOMAIN(domain);
2037 		goto found;
2038 	}
2039 #endif
2040 	vmd = VM_DOMAIN(domain);
2041 	if (vm_domain_allocate(vmd, req, npages)) {
2042 		/*
2043 		 * allocate them from the free page queues.
2044 		 */
2045 		vm_domain_free_lock(vmd);
2046 		m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2047 		    alignment, boundary);
2048 		vm_domain_free_unlock(vmd);
2049 		if (m_ret == NULL) {
2050 			vm_domain_freecnt_inc(vmd, npages);
2051 #if VM_NRESERVLEVEL > 0
2052 			if (vm_reserv_reclaim_contig(domain, npages, low,
2053 			    high, alignment, boundary))
2054 				goto again;
2055 #endif
2056 		}
2057 	}
2058 	if (m_ret == NULL) {
2059 		if (vm_domain_alloc_fail(vmd, object, req))
2060 			goto again;
2061 		return (NULL);
2062 	}
2063 #if VM_NRESERVLEVEL > 0
2064 found:
2065 #endif
2066 	for (m = m_ret; m < &m_ret[npages]; m++) {
2067 		vm_page_dequeue(m);
2068 		vm_page_alloc_check(m);
2069 	}
2070 
2071 	/*
2072 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
2073 	 */
2074 	flags = 0;
2075 	if ((req & VM_ALLOC_ZERO) != 0)
2076 		flags = PG_ZERO;
2077 	if ((req & VM_ALLOC_NODUMP) != 0)
2078 		flags |= PG_NODUMP;
2079 	oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
2080 	    VPO_UNMANAGED : 0;
2081 	busy_lock = VPB_UNBUSIED;
2082 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
2083 		busy_lock = VPB_SINGLE_EXCLUSIVER;
2084 	if ((req & VM_ALLOC_SBUSY) != 0)
2085 		busy_lock = VPB_SHARERS_WORD(1);
2086 	if ((req & VM_ALLOC_WIRED) != 0)
2087 		vm_wire_add(npages);
2088 	if (object != NULL) {
2089 		if (object->memattr != VM_MEMATTR_DEFAULT &&
2090 		    memattr == VM_MEMATTR_DEFAULT)
2091 			memattr = object->memattr;
2092 	}
2093 	for (m = m_ret; m < &m_ret[npages]; m++) {
2094 		m->aflags = 0;
2095 		m->flags = (m->flags | PG_NODUMP) & flags;
2096 		m->busy_lock = busy_lock;
2097 		if ((req & VM_ALLOC_WIRED) != 0)
2098 			m->wire_count = 1;
2099 		m->act_count = 0;
2100 		m->oflags = oflags;
2101 		if (object != NULL) {
2102 			if (vm_page_insert_after(m, object, pindex, mpred)) {
2103 				if ((req & VM_ALLOC_WIRED) != 0)
2104 					vm_wire_sub(npages);
2105 				KASSERT(m->object == NULL,
2106 				    ("page %p has object", m));
2107 				mpred = m;
2108 				for (m = m_ret; m < &m_ret[npages]; m++) {
2109 					if (m <= mpred &&
2110 					    (req & VM_ALLOC_WIRED) != 0)
2111 						m->wire_count = 0;
2112 					m->oflags = VPO_UNMANAGED;
2113 					m->busy_lock = VPB_UNBUSIED;
2114 					/* Don't change PG_ZERO. */
2115 					vm_page_free_toq(m);
2116 				}
2117 				if (req & VM_ALLOC_WAITFAIL) {
2118 					VM_OBJECT_WUNLOCK(object);
2119 					vm_radix_wait();
2120 					VM_OBJECT_WLOCK(object);
2121 				}
2122 				return (NULL);
2123 			}
2124 			mpred = m;
2125 		} else
2126 			m->pindex = pindex;
2127 		if (memattr != VM_MEMATTR_DEFAULT)
2128 			pmap_page_set_memattr(m, memattr);
2129 		pindex++;
2130 	}
2131 	return (m_ret);
2132 }
2133 
2134 /*
2135  * Check a page that has been freshly dequeued from a freelist.
2136  */
2137 static void
vm_page_alloc_check(vm_page_t m)2138 vm_page_alloc_check(vm_page_t m)
2139 {
2140 
2141 	KASSERT(m->object == NULL, ("page %p has object", m));
2142 	KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
2143 	    ("page %p has unexpected queue %d, flags %#x",
2144 	    m, m->queue, (m->aflags & PGA_QUEUE_STATE_MASK)));
2145 	KASSERT(!vm_page_held(m), ("page %p is held", m));
2146 	KASSERT(!vm_page_busied(m), ("page %p is busy", m));
2147 	KASSERT(m->dirty == 0, ("page %p is dirty", m));
2148 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2149 	    ("page %p has unexpected memattr %d",
2150 	    m, pmap_page_get_memattr(m)));
2151 	KASSERT(m->valid == 0, ("free page %p is valid", m));
2152 }
2153 
2154 /*
2155  * 	vm_page_alloc_freelist:
2156  *
2157  *	Allocate a physical page from the specified free page list.
2158  *
2159  *	The caller must always specify an allocation class.
2160  *
2161  *	allocation classes:
2162  *	VM_ALLOC_NORMAL		normal process request
2163  *	VM_ALLOC_SYSTEM		system *really* needs a page
2164  *	VM_ALLOC_INTERRUPT	interrupt time request
2165  *
2166  *	optional allocation flags:
2167  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
2168  *				intends to allocate
2169  *	VM_ALLOC_WIRED		wire the allocated page
2170  *	VM_ALLOC_ZERO		prefer a zeroed page
2171  */
2172 vm_page_t
vm_page_alloc_freelist(int freelist,int req)2173 vm_page_alloc_freelist(int freelist, int req)
2174 {
2175 	struct vm_domainset_iter di;
2176 	vm_page_t m;
2177 	int domain;
2178 
2179 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2180 	do {
2181 		m = vm_page_alloc_freelist_domain(domain, freelist, req);
2182 		if (m != NULL)
2183 			break;
2184 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2185 
2186 	return (m);
2187 }
2188 
2189 vm_page_t
vm_page_alloc_freelist_domain(int domain,int freelist,int req)2190 vm_page_alloc_freelist_domain(int domain, int freelist, int req)
2191 {
2192 	struct vm_domain *vmd;
2193 	vm_page_t m;
2194 	u_int flags;
2195 
2196 	m = NULL;
2197 	vmd = VM_DOMAIN(domain);
2198 again:
2199 	if (vm_domain_allocate(vmd, req, 1)) {
2200 		vm_domain_free_lock(vmd);
2201 		m = vm_phys_alloc_freelist_pages(domain, freelist,
2202 		    VM_FREEPOOL_DIRECT, 0);
2203 		vm_domain_free_unlock(vmd);
2204 		if (m == NULL)
2205 			vm_domain_freecnt_inc(vmd, 1);
2206 	}
2207 	if (m == NULL) {
2208 		if (vm_domain_alloc_fail(vmd, NULL, req))
2209 			goto again;
2210 		return (NULL);
2211 	}
2212 	vm_page_dequeue(m);
2213 	vm_page_alloc_check(m);
2214 
2215 	/*
2216 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
2217 	 */
2218 	m->aflags = 0;
2219 	flags = 0;
2220 	if ((req & VM_ALLOC_ZERO) != 0)
2221 		flags = PG_ZERO;
2222 	m->flags &= flags;
2223 	if ((req & VM_ALLOC_WIRED) != 0) {
2224 		/*
2225 		 * The page lock is not required for wiring a page that does
2226 		 * not belong to an object.
2227 		 */
2228 		vm_wire_add(1);
2229 		m->wire_count = 1;
2230 	}
2231 	/* Unmanaged pages don't use "act_count". */
2232 	m->oflags = VPO_UNMANAGED;
2233 	return (m);
2234 }
2235 
2236 static int
vm_page_zone_import(void * arg,void ** store,int cnt,int domain,int flags)2237 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2238 {
2239 	struct vm_domain *vmd;
2240 	struct vm_pgcache *pgcache;
2241 	int i;
2242 
2243 	pgcache = arg;
2244 	vmd = VM_DOMAIN(pgcache->domain);
2245 	/* Only import if we can bring in a full bucket. */
2246 	if (cnt == 1 || !vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2247 		return (0);
2248 	domain = vmd->vmd_domain;
2249 	vm_domain_free_lock(vmd);
2250 	i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2251 	    (vm_page_t *)store);
2252 	vm_domain_free_unlock(vmd);
2253 	if (cnt != i)
2254 		vm_domain_freecnt_inc(vmd, cnt - i);
2255 
2256 	return (i);
2257 }
2258 
2259 static void
vm_page_zone_release(void * arg,void ** store,int cnt)2260 vm_page_zone_release(void *arg, void **store, int cnt)
2261 {
2262 	struct vm_domain *vmd;
2263 	struct vm_pgcache *pgcache;
2264 	vm_page_t m;
2265 	int i;
2266 
2267 	pgcache = arg;
2268 	vmd = VM_DOMAIN(pgcache->domain);
2269 	vm_domain_free_lock(vmd);
2270 	for (i = 0; i < cnt; i++) {
2271 		m = (vm_page_t)store[i];
2272 		vm_phys_free_pages(m, 0);
2273 	}
2274 	vm_domain_free_unlock(vmd);
2275 	vm_domain_freecnt_inc(vmd, cnt);
2276 }
2277 
2278 #define	VPSC_ANY	0	/* No restrictions. */
2279 #define	VPSC_NORESERV	1	/* Skip reservations; implies VPSC_NOSUPER. */
2280 #define	VPSC_NOSUPER	2	/* Skip superpages. */
2281 
2282 /*
2283  *	vm_page_scan_contig:
2284  *
2285  *	Scan vm_page_array[] between the specified entries "m_start" and
2286  *	"m_end" for a run of contiguous physical pages that satisfy the
2287  *	specified conditions, and return the lowest page in the run.  The
2288  *	specified "alignment" determines the alignment of the lowest physical
2289  *	page in the run.  If the specified "boundary" is non-zero, then the
2290  *	run of physical pages cannot span a physical address that is a
2291  *	multiple of "boundary".
2292  *
2293  *	"m_end" is never dereferenced, so it need not point to a vm_page
2294  *	structure within vm_page_array[].
2295  *
2296  *	"npages" must be greater than zero.  "m_start" and "m_end" must not
2297  *	span a hole (or discontiguity) in the physical address space.  Both
2298  *	"alignment" and "boundary" must be a power of two.
2299  */
2300 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)2301 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2302     u_long alignment, vm_paddr_t boundary, int options)
2303 {
2304 	struct mtx *m_mtx;
2305 	vm_object_t object;
2306 	vm_paddr_t pa;
2307 	vm_page_t m, m_run;
2308 #if VM_NRESERVLEVEL > 0
2309 	int level;
2310 #endif
2311 	int m_inc, order, run_ext, run_len;
2312 
2313 	KASSERT(npages > 0, ("npages is 0"));
2314 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2315 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2316 	m_run = NULL;
2317 	run_len = 0;
2318 	m_mtx = NULL;
2319 	for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2320 		KASSERT((m->flags & PG_MARKER) == 0,
2321 		    ("page %p is PG_MARKER", m));
2322 		KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
2323 		    ("fictitious page %p has invalid wire count", m));
2324 
2325 		/*
2326 		 * If the current page would be the start of a run, check its
2327 		 * physical address against the end, alignment, and boundary
2328 		 * conditions.  If it doesn't satisfy these conditions, either
2329 		 * terminate the scan or advance to the next page that
2330 		 * satisfies the failed condition.
2331 		 */
2332 		if (run_len == 0) {
2333 			KASSERT(m_run == NULL, ("m_run != NULL"));
2334 			if (m + npages > m_end)
2335 				break;
2336 			pa = VM_PAGE_TO_PHYS(m);
2337 			if ((pa & (alignment - 1)) != 0) {
2338 				m_inc = atop(roundup2(pa, alignment) - pa);
2339 				continue;
2340 			}
2341 			if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2342 			    boundary) != 0) {
2343 				m_inc = atop(roundup2(pa, boundary) - pa);
2344 				continue;
2345 			}
2346 		} else
2347 			KASSERT(m_run != NULL, ("m_run == NULL"));
2348 
2349 		vm_page_change_lock(m, &m_mtx);
2350 		m_inc = 1;
2351 retry:
2352 		if (vm_page_held(m))
2353 			run_ext = 0;
2354 #if VM_NRESERVLEVEL > 0
2355 		else if ((level = vm_reserv_level(m)) >= 0 &&
2356 		    (options & VPSC_NORESERV) != 0) {
2357 			run_ext = 0;
2358 			/* Advance to the end of the reservation. */
2359 			pa = VM_PAGE_TO_PHYS(m);
2360 			m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2361 			    pa);
2362 		}
2363 #endif
2364 		else if ((object = m->object) != NULL) {
2365 			/*
2366 			 * The page is considered eligible for relocation if
2367 			 * and only if it could be laundered or reclaimed by
2368 			 * the page daemon.
2369 			 */
2370 			if (!VM_OBJECT_TRYRLOCK(object)) {
2371 				mtx_unlock(m_mtx);
2372 				VM_OBJECT_RLOCK(object);
2373 				mtx_lock(m_mtx);
2374 				if (m->object != object) {
2375 					/*
2376 					 * The page may have been freed.
2377 					 */
2378 					VM_OBJECT_RUNLOCK(object);
2379 					goto retry;
2380 				} else if (vm_page_held(m)) {
2381 					run_ext = 0;
2382 					goto unlock;
2383 				}
2384 			}
2385 			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2386 			    ("page %p is PG_UNHOLDFREE", m));
2387 			/* Don't care: PG_NODUMP, PG_ZERO. */
2388 			if (object->type != OBJT_DEFAULT &&
2389 			    object->type != OBJT_SWAP &&
2390 			    object->type != OBJT_VNODE) {
2391 				run_ext = 0;
2392 #if VM_NRESERVLEVEL > 0
2393 			} else if ((options & VPSC_NOSUPER) != 0 &&
2394 			    (level = vm_reserv_level_iffullpop(m)) >= 0) {
2395 				run_ext = 0;
2396 				/* Advance to the end of the superpage. */
2397 				pa = VM_PAGE_TO_PHYS(m);
2398 				m_inc = atop(roundup2(pa + 1,
2399 				    vm_reserv_size(level)) - pa);
2400 #endif
2401 			} else if (object->memattr == VM_MEMATTR_DEFAULT &&
2402 			    vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2403 				/*
2404 				 * The page is allocated but eligible for
2405 				 * relocation.  Extend the current run by one
2406 				 * page.
2407 				 */
2408 				KASSERT(pmap_page_get_memattr(m) ==
2409 				    VM_MEMATTR_DEFAULT,
2410 				    ("page %p has an unexpected memattr", m));
2411 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2412 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2413 				    ("page %p has unexpected oflags", m));
2414 				/* Don't care: VPO_NOSYNC. */
2415 				run_ext = 1;
2416 			} else
2417 				run_ext = 0;
2418 unlock:
2419 			VM_OBJECT_RUNLOCK(object);
2420 #if VM_NRESERVLEVEL > 0
2421 		} else if (level >= 0) {
2422 			/*
2423 			 * The page is reserved but not yet allocated.  In
2424 			 * other words, it is still free.  Extend the current
2425 			 * run by one page.
2426 			 */
2427 			run_ext = 1;
2428 #endif
2429 		} else if ((order = m->order) < VM_NFREEORDER) {
2430 			/*
2431 			 * The page is enqueued in the physical memory
2432 			 * allocator's free page queues.  Moreover, it is the
2433 			 * first page in a power-of-two-sized run of
2434 			 * contiguous free pages.  Add these pages to the end
2435 			 * of the current run, and jump ahead.
2436 			 */
2437 			run_ext = 1 << order;
2438 			m_inc = 1 << order;
2439 		} else {
2440 			/*
2441 			 * Skip the page for one of the following reasons: (1)
2442 			 * It is enqueued in the physical memory allocator's
2443 			 * free page queues.  However, it is not the first
2444 			 * page in a run of contiguous free pages.  (This case
2445 			 * rarely occurs because the scan is performed in
2446 			 * ascending order.) (2) It is not reserved, and it is
2447 			 * transitioning from free to allocated.  (Conversely,
2448 			 * the transition from allocated to free for managed
2449 			 * pages is blocked by the page lock.) (3) It is
2450 			 * allocated but not contained by an object and not
2451 			 * wired, e.g., allocated by Xen's balloon driver.
2452 			 */
2453 			run_ext = 0;
2454 		}
2455 
2456 		/*
2457 		 * Extend or reset the current run of pages.
2458 		 */
2459 		if (run_ext > 0) {
2460 			if (run_len == 0)
2461 				m_run = m;
2462 			run_len += run_ext;
2463 		} else {
2464 			if (run_len > 0) {
2465 				m_run = NULL;
2466 				run_len = 0;
2467 			}
2468 		}
2469 	}
2470 	if (m_mtx != NULL)
2471 		mtx_unlock(m_mtx);
2472 	if (run_len >= npages)
2473 		return (m_run);
2474 	return (NULL);
2475 }
2476 
2477 /*
2478  *	vm_page_reclaim_run:
2479  *
2480  *	Try to relocate each of the allocated virtual pages within the
2481  *	specified run of physical pages to a new physical address.  Free the
2482  *	physical pages underlying the relocated virtual pages.  A virtual page
2483  *	is relocatable if and only if it could be laundered or reclaimed by
2484  *	the page daemon.  Whenever possible, a virtual page is relocated to a
2485  *	physical address above "high".
2486  *
2487  *	Returns 0 if every physical page within the run was already free or
2488  *	just freed by a successful relocation.  Otherwise, returns a non-zero
2489  *	value indicating why the last attempt to relocate a virtual page was
2490  *	unsuccessful.
2491  *
2492  *	"req_class" must be an allocation class.
2493  */
2494 static int
vm_page_reclaim_run(int req_class,int domain,u_long npages,vm_page_t m_run,vm_paddr_t high)2495 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2496     vm_paddr_t high)
2497 {
2498 	struct vm_domain *vmd;
2499 	struct mtx *m_mtx;
2500 	struct spglist free;
2501 	vm_object_t object;
2502 	vm_paddr_t pa;
2503 	vm_page_t m, m_end, m_new;
2504 	int error, order, req;
2505 
2506 	KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2507 	    ("req_class is not an allocation class"));
2508 	SLIST_INIT(&free);
2509 	error = 0;
2510 	m = m_run;
2511 	m_end = m_run + npages;
2512 	m_mtx = NULL;
2513 	for (; error == 0 && m < m_end; m++) {
2514 		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2515 		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2516 
2517 		/*
2518 		 * Avoid releasing and reacquiring the same page lock.
2519 		 */
2520 		vm_page_change_lock(m, &m_mtx);
2521 retry:
2522 		if (vm_page_held(m))
2523 			error = EBUSY;
2524 		else if ((object = m->object) != NULL) {
2525 			/*
2526 			 * The page is relocated if and only if it could be
2527 			 * laundered or reclaimed by the page daemon.
2528 			 */
2529 			if (!VM_OBJECT_TRYWLOCK(object)) {
2530 				mtx_unlock(m_mtx);
2531 				VM_OBJECT_WLOCK(object);
2532 				mtx_lock(m_mtx);
2533 				if (m->object != object) {
2534 					/*
2535 					 * The page may have been freed.
2536 					 */
2537 					VM_OBJECT_WUNLOCK(object);
2538 					goto retry;
2539 				} else if (vm_page_held(m)) {
2540 					error = EBUSY;
2541 					goto unlock;
2542 				}
2543 			}
2544 			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2545 			    ("page %p is PG_UNHOLDFREE", m));
2546 			/* Don't care: PG_NODUMP, PG_ZERO. */
2547 			if (object->type != OBJT_DEFAULT &&
2548 			    object->type != OBJT_SWAP &&
2549 			    object->type != OBJT_VNODE)
2550 				error = EINVAL;
2551 			else if (object->memattr != VM_MEMATTR_DEFAULT)
2552 				error = EINVAL;
2553 			else if (vm_page_queue(m) != PQ_NONE &&
2554 			    !vm_page_busied(m)) {
2555 				KASSERT(pmap_page_get_memattr(m) ==
2556 				    VM_MEMATTR_DEFAULT,
2557 				    ("page %p has an unexpected memattr", m));
2558 				KASSERT((m->oflags & (VPO_SWAPINPROG |
2559 				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2560 				    ("page %p has unexpected oflags", m));
2561 				/* Don't care: VPO_NOSYNC. */
2562 				if (m->valid != 0) {
2563 					/*
2564 					 * First, try to allocate a new page
2565 					 * that is above "high".  Failing
2566 					 * that, try to allocate a new page
2567 					 * that is below "m_run".  Allocate
2568 					 * the new page between the end of
2569 					 * "m_run" and "high" only as a last
2570 					 * resort.
2571 					 */
2572 					req = req_class | VM_ALLOC_NOOBJ;
2573 					if ((m->flags & PG_NODUMP) != 0)
2574 						req |= VM_ALLOC_NODUMP;
2575 					if (trunc_page(high) !=
2576 					    ~(vm_paddr_t)PAGE_MASK) {
2577 						m_new = vm_page_alloc_contig(
2578 						    NULL, 0, req, 1,
2579 						    round_page(high),
2580 						    ~(vm_paddr_t)0,
2581 						    PAGE_SIZE, 0,
2582 						    VM_MEMATTR_DEFAULT);
2583 					} else
2584 						m_new = NULL;
2585 					if (m_new == NULL) {
2586 						pa = VM_PAGE_TO_PHYS(m_run);
2587 						m_new = vm_page_alloc_contig(
2588 						    NULL, 0, req, 1,
2589 						    0, pa - 1, PAGE_SIZE, 0,
2590 						    VM_MEMATTR_DEFAULT);
2591 					}
2592 					if (m_new == NULL) {
2593 						pa += ptoa(npages);
2594 						m_new = vm_page_alloc_contig(
2595 						    NULL, 0, req, 1,
2596 						    pa, high, PAGE_SIZE, 0,
2597 						    VM_MEMATTR_DEFAULT);
2598 					}
2599 					if (m_new == NULL) {
2600 						error = ENOMEM;
2601 						goto unlock;
2602 					}
2603 					KASSERT(!vm_page_wired(m_new),
2604 					    ("page %p is wired", m_new));
2605 
2606 					/*
2607 					 * Replace "m" with the new page.  For
2608 					 * vm_page_replace(), "m" must be busy
2609 					 * and dequeued.  Finally, change "m"
2610 					 * as if vm_page_free() was called.
2611 					 */
2612 					if (object->ref_count != 0)
2613 						pmap_remove_all(m);
2614 					m_new->aflags = m->aflags &
2615 					    ~PGA_QUEUE_STATE_MASK;
2616 					KASSERT(m_new->oflags == VPO_UNMANAGED,
2617 					    ("page %p is managed", m_new));
2618 					m_new->oflags = m->oflags & VPO_NOSYNC;
2619 					pmap_copy_page(m, m_new);
2620 					m_new->valid = m->valid;
2621 					m_new->dirty = m->dirty;
2622 					m->flags &= ~PG_ZERO;
2623 					vm_page_xbusy(m);
2624 					vm_page_dequeue(m);
2625 					vm_page_replace_checked(m_new, object,
2626 					    m->pindex, m);
2627 					if (vm_page_free_prep(m))
2628 						SLIST_INSERT_HEAD(&free, m,
2629 						    plinks.s.ss);
2630 
2631 					/*
2632 					 * The new page must be deactivated
2633 					 * before the object is unlocked.
2634 					 */
2635 					vm_page_change_lock(m_new, &m_mtx);
2636 					vm_page_deactivate(m_new);
2637 				} else {
2638 					m->flags &= ~PG_ZERO;
2639 					vm_page_dequeue(m);
2640 					if (vm_page_free_prep(m))
2641 						SLIST_INSERT_HEAD(&free, m,
2642 						    plinks.s.ss);
2643 					KASSERT(m->dirty == 0,
2644 					    ("page %p is dirty", m));
2645 				}
2646 			} else
2647 				error = EBUSY;
2648 unlock:
2649 			VM_OBJECT_WUNLOCK(object);
2650 		} else {
2651 			MPASS(vm_phys_domain(m) == domain);
2652 			vmd = VM_DOMAIN(domain);
2653 			vm_domain_free_lock(vmd);
2654 			order = m->order;
2655 			if (order < VM_NFREEORDER) {
2656 				/*
2657 				 * The page is enqueued in the physical memory
2658 				 * allocator's free page queues.  Moreover, it
2659 				 * is the first page in a power-of-two-sized
2660 				 * run of contiguous free pages.  Jump ahead
2661 				 * to the last page within that run, and
2662 				 * continue from there.
2663 				 */
2664 				m += (1 << order) - 1;
2665 			}
2666 #if VM_NRESERVLEVEL > 0
2667 			else if (vm_reserv_is_page_free(m))
2668 				order = 0;
2669 #endif
2670 			vm_domain_free_unlock(vmd);
2671 			if (order == VM_NFREEORDER)
2672 				error = EINVAL;
2673 		}
2674 	}
2675 	if (m_mtx != NULL)
2676 		mtx_unlock(m_mtx);
2677 	if ((m = SLIST_FIRST(&free)) != NULL) {
2678 		int cnt;
2679 
2680 		vmd = VM_DOMAIN(domain);
2681 		cnt = 0;
2682 		vm_domain_free_lock(vmd);
2683 		do {
2684 			MPASS(vm_phys_domain(m) == domain);
2685 			SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2686 			vm_phys_free_pages(m, 0);
2687 			cnt++;
2688 		} while ((m = SLIST_FIRST(&free)) != NULL);
2689 		vm_domain_free_unlock(vmd);
2690 		vm_domain_freecnt_inc(vmd, cnt);
2691 	}
2692 	return (error);
2693 }
2694 
2695 #define	NRUNS	16
2696 
2697 CTASSERT(powerof2(NRUNS));
2698 
2699 #define	RUN_INDEX(count)	((count) & (NRUNS - 1))
2700 
2701 #define	MIN_RECLAIM	8
2702 
2703 /*
2704  *	vm_page_reclaim_contig:
2705  *
2706  *	Reclaim allocated, contiguous physical memory satisfying the specified
2707  *	conditions by relocating the virtual pages using that physical memory.
2708  *	Returns true if reclamation is successful and false otherwise.  Since
2709  *	relocation requires the allocation of physical pages, reclamation may
2710  *	fail due to a shortage of free pages.  When reclamation fails, callers
2711  *	are expected to perform vm_wait() before retrying a failed allocation
2712  *	operation, e.g., vm_page_alloc_contig().
2713  *
2714  *	The caller must always specify an allocation class through "req".
2715  *
2716  *	allocation classes:
2717  *	VM_ALLOC_NORMAL		normal process request
2718  *	VM_ALLOC_SYSTEM		system *really* needs a page
2719  *	VM_ALLOC_INTERRUPT	interrupt time request
2720  *
2721  *	The optional allocation flags are ignored.
2722  *
2723  *	"npages" must be greater than zero.  Both "alignment" and "boundary"
2724  *	must be a power of two.
2725  */
2726 bool
vm_page_reclaim_contig_domain(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)2727 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
2728     vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2729 {
2730 	struct vm_domain *vmd;
2731 	vm_paddr_t curr_low;
2732 	vm_page_t m_run, m_runs[NRUNS];
2733 	u_long count, reclaimed;
2734 	int error, i, options, req_class;
2735 
2736 	KASSERT(npages > 0, ("npages is 0"));
2737 	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2738 	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2739 	req_class = req & VM_ALLOC_CLASS_MASK;
2740 
2741 	/*
2742 	 * The page daemon is allowed to dig deeper into the free page list.
2743 	 */
2744 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2745 		req_class = VM_ALLOC_SYSTEM;
2746 
2747 	/*
2748 	 * Return if the number of free pages cannot satisfy the requested
2749 	 * allocation.
2750 	 */
2751 	vmd = VM_DOMAIN(domain);
2752 	count = vmd->vmd_free_count;
2753 	if (count < npages + vmd->vmd_free_reserved || (count < npages +
2754 	    vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2755 	    (count < npages && req_class == VM_ALLOC_INTERRUPT))
2756 		return (false);
2757 
2758 	/*
2759 	 * Scan up to three times, relaxing the restrictions ("options") on
2760 	 * the reclamation of reservations and superpages each time.
2761 	 */
2762 	for (options = VPSC_NORESERV;;) {
2763 		/*
2764 		 * Find the highest runs that satisfy the given constraints
2765 		 * and restrictions, and record them in "m_runs".
2766 		 */
2767 		curr_low = low;
2768 		count = 0;
2769 		for (;;) {
2770 			m_run = vm_phys_scan_contig(domain, npages, curr_low,
2771 			    high, alignment, boundary, options);
2772 			if (m_run == NULL)
2773 				break;
2774 			curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2775 			m_runs[RUN_INDEX(count)] = m_run;
2776 			count++;
2777 		}
2778 
2779 		/*
2780 		 * Reclaim the highest runs in LIFO (descending) order until
2781 		 * the number of reclaimed pages, "reclaimed", is at least
2782 		 * MIN_RECLAIM.  Reset "reclaimed" each time because each
2783 		 * reclamation is idempotent, and runs will (likely) recur
2784 		 * from one scan to the next as restrictions are relaxed.
2785 		 */
2786 		reclaimed = 0;
2787 		for (i = 0; count > 0 && i < NRUNS; i++) {
2788 			count--;
2789 			m_run = m_runs[RUN_INDEX(count)];
2790 			error = vm_page_reclaim_run(req_class, domain, npages,
2791 			    m_run, high);
2792 			if (error == 0) {
2793 				reclaimed += npages;
2794 				if (reclaimed >= MIN_RECLAIM)
2795 					return (true);
2796 			}
2797 		}
2798 
2799 		/*
2800 		 * Either relax the restrictions on the next scan or return if
2801 		 * the last scan had no restrictions.
2802 		 */
2803 		if (options == VPSC_NORESERV)
2804 			options = VPSC_NOSUPER;
2805 		else if (options == VPSC_NOSUPER)
2806 			options = VPSC_ANY;
2807 		else if (options == VPSC_ANY)
2808 			return (reclaimed != 0);
2809 	}
2810 }
2811 
2812 bool
vm_page_reclaim_contig(int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)2813 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2814     u_long alignment, vm_paddr_t boundary)
2815 {
2816 	struct vm_domainset_iter di;
2817 	int domain;
2818 	bool ret;
2819 
2820 	vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2821 	do {
2822 		ret = vm_page_reclaim_contig_domain(domain, req, npages, low,
2823 		    high, alignment, boundary);
2824 		if (ret)
2825 			break;
2826 	} while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2827 
2828 	return (ret);
2829 }
2830 
2831 /*
2832  * Set the domain in the appropriate page level domainset.
2833  */
2834 void
vm_domain_set(struct vm_domain * vmd)2835 vm_domain_set(struct vm_domain *vmd)
2836 {
2837 
2838 	mtx_lock(&vm_domainset_lock);
2839 	if (!vmd->vmd_minset && vm_paging_min(vmd)) {
2840 		vmd->vmd_minset = 1;
2841 		DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
2842 	}
2843 	if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
2844 		vmd->vmd_severeset = 1;
2845 		DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
2846 	}
2847 	mtx_unlock(&vm_domainset_lock);
2848 }
2849 
2850 /*
2851  * Clear the domain from the appropriate page level domainset.
2852  */
2853 void
vm_domain_clear(struct vm_domain * vmd)2854 vm_domain_clear(struct vm_domain *vmd)
2855 {
2856 
2857 	mtx_lock(&vm_domainset_lock);
2858 	if (vmd->vmd_minset && !vm_paging_min(vmd)) {
2859 		vmd->vmd_minset = 0;
2860 		DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
2861 		if (vm_min_waiters != 0) {
2862 			vm_min_waiters = 0;
2863 			wakeup(&vm_min_domains);
2864 		}
2865 	}
2866 	if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
2867 		vmd->vmd_severeset = 0;
2868 		DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
2869 		if (vm_severe_waiters != 0) {
2870 			vm_severe_waiters = 0;
2871 			wakeup(&vm_severe_domains);
2872 		}
2873 	}
2874 
2875 	/*
2876 	 * If pageout daemon needs pages, then tell it that there are
2877 	 * some free.
2878 	 */
2879 	if (vmd->vmd_pageout_pages_needed &&
2880 	    vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
2881 		wakeup(&vmd->vmd_pageout_pages_needed);
2882 		vmd->vmd_pageout_pages_needed = 0;
2883 	}
2884 
2885 	/* See comments in vm_wait_doms(). */
2886 	if (vm_pageproc_waiters) {
2887 		vm_pageproc_waiters = 0;
2888 		wakeup(&vm_pageproc_waiters);
2889 	}
2890 	mtx_unlock(&vm_domainset_lock);
2891 }
2892 
2893 /*
2894  * Wait for free pages to exceed the min threshold globally.
2895  */
2896 void
vm_wait_min(void)2897 vm_wait_min(void)
2898 {
2899 
2900 	mtx_lock(&vm_domainset_lock);
2901 	while (vm_page_count_min()) {
2902 		vm_min_waiters++;
2903 		msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
2904 	}
2905 	mtx_unlock(&vm_domainset_lock);
2906 }
2907 
2908 /*
2909  * Wait for free pages to exceed the severe threshold globally.
2910  */
2911 void
vm_wait_severe(void)2912 vm_wait_severe(void)
2913 {
2914 
2915 	mtx_lock(&vm_domainset_lock);
2916 	while (vm_page_count_severe()) {
2917 		vm_severe_waiters++;
2918 		msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
2919 		    "vmwait", 0);
2920 	}
2921 	mtx_unlock(&vm_domainset_lock);
2922 }
2923 
2924 u_int
vm_wait_count(void)2925 vm_wait_count(void)
2926 {
2927 
2928 	return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
2929 }
2930 
2931 void
vm_wait_doms(const domainset_t * wdoms)2932 vm_wait_doms(const domainset_t *wdoms)
2933 {
2934 
2935 	/*
2936 	 * We use racey wakeup synchronization to avoid expensive global
2937 	 * locking for the pageproc when sleeping with a non-specific vm_wait.
2938 	 * To handle this, we only sleep for one tick in this instance.  It
2939 	 * is expected that most allocations for the pageproc will come from
2940 	 * kmem or vm_page_grab* which will use the more specific and
2941 	 * race-free vm_wait_domain().
2942 	 */
2943 	if (curproc == pageproc) {
2944 		mtx_lock(&vm_domainset_lock);
2945 		vm_pageproc_waiters++;
2946 		msleep(&vm_pageproc_waiters, &vm_domainset_lock, PVM | PDROP,
2947 		    "pageprocwait", 1);
2948 	} else {
2949 		/*
2950 		 * XXX Ideally we would wait only until the allocation could
2951 		 * be satisfied.  This condition can cause new allocators to
2952 		 * consume all freed pages while old allocators wait.
2953 		 */
2954 		mtx_lock(&vm_domainset_lock);
2955 		if (vm_page_count_min_set(wdoms)) {
2956 			vm_min_waiters++;
2957 			msleep(&vm_min_domains, &vm_domainset_lock,
2958 			    PVM | PDROP, "vmwait", 0);
2959 		} else
2960 			mtx_unlock(&vm_domainset_lock);
2961 	}
2962 }
2963 
2964 /*
2965  *	vm_wait_domain:
2966  *
2967  *	Sleep until free pages are available for allocation.
2968  *	- Called in various places after failed memory allocations.
2969  */
2970 void
vm_wait_domain(int domain)2971 vm_wait_domain(int domain)
2972 {
2973 	struct vm_domain *vmd;
2974 	domainset_t wdom;
2975 
2976 	vmd = VM_DOMAIN(domain);
2977 	vm_domain_free_assert_unlocked(vmd);
2978 
2979 	if (curproc == pageproc) {
2980 		mtx_lock(&vm_domainset_lock);
2981 		if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
2982 			vmd->vmd_pageout_pages_needed = 1;
2983 			msleep(&vmd->vmd_pageout_pages_needed,
2984 			    &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
2985 		} else
2986 			mtx_unlock(&vm_domainset_lock);
2987 	} else {
2988 		if (pageproc == NULL)
2989 			panic("vm_wait in early boot");
2990 		DOMAINSET_ZERO(&wdom);
2991 		DOMAINSET_SET(vmd->vmd_domain, &wdom);
2992 		vm_wait_doms(&wdom);
2993 	}
2994 }
2995 
2996 /*
2997  *	vm_wait:
2998  *
2999  *	Sleep until free pages are available for allocation in the
3000  *	affinity domains of the obj.  If obj is NULL, the domain set
3001  *	for the calling thread is used.
3002  *	Called in various places after failed memory allocations.
3003  */
3004 void
vm_wait(vm_object_t obj)3005 vm_wait(vm_object_t obj)
3006 {
3007 	struct domainset *d;
3008 
3009 	d = NULL;
3010 
3011 	/*
3012 	 * Carefully fetch pointers only once: the struct domainset
3013 	 * itself is ummutable but the pointer might change.
3014 	 */
3015 	if (obj != NULL)
3016 		d = obj->domain.dr_policy;
3017 	if (d == NULL)
3018 		d = curthread->td_domain.dr_policy;
3019 
3020 	vm_wait_doms(&d->ds_mask);
3021 }
3022 
3023 /*
3024  *	vm_domain_alloc_fail:
3025  *
3026  *	Called when a page allocation function fails.  Informs the
3027  *	pagedaemon and performs the requested wait.  Requires the
3028  *	domain_free and object lock on entry.  Returns with the
3029  *	object lock held and free lock released.  Returns an error when
3030  *	retry is necessary.
3031  *
3032  */
3033 static int
vm_domain_alloc_fail(struct vm_domain * vmd,vm_object_t object,int req)3034 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3035 {
3036 
3037 	vm_domain_free_assert_unlocked(vmd);
3038 
3039 	atomic_add_int(&vmd->vmd_pageout_deficit,
3040 	    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3041 	if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3042 		if (object != NULL)
3043 			VM_OBJECT_WUNLOCK(object);
3044 		vm_wait_domain(vmd->vmd_domain);
3045 		if (object != NULL)
3046 			VM_OBJECT_WLOCK(object);
3047 		if (req & VM_ALLOC_WAITOK)
3048 			return (EAGAIN);
3049 	}
3050 
3051 	return (0);
3052 }
3053 
3054 /*
3055  *	vm_waitpfault:
3056  *
3057  *	Sleep until free pages are available for allocation.
3058  *	- Called only in vm_fault so that processes page faulting
3059  *	  can be easily tracked.
3060  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3061  *	  processes will be able to grab memory first.  Do not change
3062  *	  this balance without careful testing first.
3063  */
3064 void
vm_waitpfault(struct domainset * dset,int timo)3065 vm_waitpfault(struct domainset *dset, int timo)
3066 {
3067 
3068 	/*
3069 	 * XXX Ideally we would wait only until the allocation could
3070 	 * be satisfied.  This condition can cause new allocators to
3071 	 * consume all freed pages while old allocators wait.
3072 	 */
3073 	mtx_lock(&vm_domainset_lock);
3074 	if (vm_page_count_min_set(&dset->ds_mask)) {
3075 		vm_min_waiters++;
3076 		msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3077 		    "pfault", timo);
3078 	} else
3079 		mtx_unlock(&vm_domainset_lock);
3080 }
3081 
3082 static struct vm_pagequeue *
vm_page_pagequeue(vm_page_t m)3083 vm_page_pagequeue(vm_page_t m)
3084 {
3085 
3086 	uint8_t queue;
3087 
3088 	if ((queue = atomic_load_8(&m->queue)) == PQ_NONE)
3089 		return (NULL);
3090 	return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3091 }
3092 
3093 static inline void
vm_pqbatch_process_page(struct vm_pagequeue * pq,vm_page_t m)3094 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m)
3095 {
3096 	struct vm_domain *vmd;
3097 	uint8_t qflags;
3098 
3099 	CRITICAL_ASSERT(curthread);
3100 	vm_pagequeue_assert_locked(pq);
3101 
3102 	/*
3103 	 * The page daemon is allowed to set m->queue = PQ_NONE without
3104 	 * the page queue lock held.  In this case it is about to free the page,
3105 	 * which must not have any queue state.
3106 	 */
3107 	qflags = atomic_load_8(&m->aflags);
3108 	KASSERT(pq == vm_page_pagequeue(m) ||
3109 	    (qflags & PGA_QUEUE_STATE_MASK) == 0,
3110 	    ("page %p doesn't belong to queue %p but has aflags %#x",
3111 	    m, pq, qflags));
3112 
3113 	if ((qflags & PGA_DEQUEUE) != 0) {
3114 		if (__predict_true((qflags & PGA_ENQUEUED) != 0))
3115 			vm_pagequeue_remove(pq, m);
3116 		vm_page_dequeue_complete(m);
3117 	} else if ((qflags & (PGA_REQUEUE | PGA_REQUEUE_HEAD)) != 0) {
3118 		if ((qflags & PGA_ENQUEUED) != 0)
3119 			TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3120 		else {
3121 			vm_pagequeue_cnt_inc(pq);
3122 			vm_page_aflag_set(m, PGA_ENQUEUED);
3123 		}
3124 
3125 		/*
3126 		 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE.
3127 		 * In particular, if both flags are set in close succession,
3128 		 * only PGA_REQUEUE_HEAD will be applied, even if it was set
3129 		 * first.
3130 		 */
3131 		if ((qflags & PGA_REQUEUE_HEAD) != 0) {
3132 			KASSERT(m->queue == PQ_INACTIVE,
3133 			    ("head enqueue not supported for page %p", m));
3134 			vmd = vm_pagequeue_domain(m);
3135 			TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3136 		} else
3137 			TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3138 
3139 		vm_page_aflag_clear(m, qflags & (PGA_REQUEUE |
3140 		    PGA_REQUEUE_HEAD));
3141 	}
3142 }
3143 
3144 static void
vm_pqbatch_process(struct vm_pagequeue * pq,struct vm_batchqueue * bq,uint8_t queue)3145 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3146     uint8_t queue)
3147 {
3148 	vm_page_t m;
3149 	int i;
3150 
3151 	for (i = 0; i < bq->bq_cnt; i++) {
3152 		m = bq->bq_pa[i];
3153 		if (__predict_false(m->queue != queue))
3154 			continue;
3155 		vm_pqbatch_process_page(pq, m);
3156 	}
3157 	vm_batchqueue_init(bq);
3158 }
3159 
3160 static void
vm_pqbatch_submit_page(vm_page_t m,uint8_t queue)3161 vm_pqbatch_submit_page(vm_page_t m, uint8_t queue)
3162 {
3163 	struct vm_batchqueue *bq;
3164 	struct vm_pagequeue *pq;
3165 	int domain;
3166 
3167 	vm_page_assert_locked(m);
3168 	KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3169 
3170 	domain = vm_phys_domain(m);
3171 	pq = &vm_pagequeue_domain(m)->vmd_pagequeues[queue];
3172 
3173 	critical_enter();
3174 	bq = DPCPU_PTR(pqbatch[domain][queue]);
3175 	if (vm_batchqueue_insert(bq, m)) {
3176 		critical_exit();
3177 		return;
3178 	}
3179 	if (!vm_pagequeue_trylock(pq)) {
3180 		critical_exit();
3181 		vm_pagequeue_lock(pq);
3182 		critical_enter();
3183 		bq = DPCPU_PTR(pqbatch[domain][queue]);
3184 	}
3185 	vm_pqbatch_process(pq, bq, queue);
3186 
3187 	/*
3188 	 * The page may have been logically dequeued before we acquired the
3189 	 * page queue lock.  In this case, the page lock prevents the page
3190 	 * from being logically enqueued elsewhere.
3191 	 */
3192 	if (__predict_true(m->queue == queue))
3193 		vm_pqbatch_process_page(pq, m);
3194 	else {
3195 		KASSERT(m->queue == PQ_NONE,
3196 		    ("invalid queue transition for page %p", m));
3197 		KASSERT((m->aflags & PGA_ENQUEUED) == 0,
3198 		    ("page %p is enqueued with invalid queue index", m));
3199 		vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3200 	}
3201 	vm_pagequeue_unlock(pq);
3202 	critical_exit();
3203 }
3204 
3205 /*
3206  *	vm_page_drain_pqbatch:		[ internal use only ]
3207  *
3208  *	Force all per-CPU page queue batch queues to be drained.  This is
3209  *	intended for use in severe memory shortages, to ensure that pages
3210  *	do not remain stuck in the batch queues.
3211  */
3212 void
vm_page_drain_pqbatch(void)3213 vm_page_drain_pqbatch(void)
3214 {
3215 	struct thread *td;
3216 	struct vm_domain *vmd;
3217 	struct vm_pagequeue *pq;
3218 	int cpu, domain, queue;
3219 
3220 	td = curthread;
3221 	CPU_FOREACH(cpu) {
3222 		thread_lock(td);
3223 		sched_bind(td, cpu);
3224 		thread_unlock(td);
3225 
3226 		for (domain = 0; domain < vm_ndomains; domain++) {
3227 			vmd = VM_DOMAIN(domain);
3228 			for (queue = 0; queue < PQ_COUNT; queue++) {
3229 				pq = &vmd->vmd_pagequeues[queue];
3230 				vm_pagequeue_lock(pq);
3231 				critical_enter();
3232 				vm_pqbatch_process(pq,
3233 				    DPCPU_PTR(pqbatch[domain][queue]), queue);
3234 				critical_exit();
3235 				vm_pagequeue_unlock(pq);
3236 			}
3237 		}
3238 	}
3239 	thread_lock(td);
3240 	sched_unbind(td);
3241 	thread_unlock(td);
3242 }
3243 
3244 /*
3245  * Complete the logical removal of a page from a page queue.  We must be
3246  * careful to synchronize with the page daemon, which may be concurrently
3247  * examining the page with only the page lock held.  The page must not be
3248  * in a state where it appears to be logically enqueued.
3249  */
3250 static void
vm_page_dequeue_complete(vm_page_t m)3251 vm_page_dequeue_complete(vm_page_t m)
3252 {
3253 
3254 	m->queue = PQ_NONE;
3255 	atomic_thread_fence_rel();
3256 	vm_page_aflag_clear(m, PGA_QUEUE_STATE_MASK);
3257 }
3258 
3259 /*
3260  *	vm_page_dequeue_deferred:	[ internal use only ]
3261  *
3262  *	Request removal of the given page from its current page
3263  *	queue.  Physical removal from the queue may be deferred
3264  *	indefinitely.
3265  *
3266  *	The page must be locked.
3267  */
3268 void
vm_page_dequeue_deferred(vm_page_t m)3269 vm_page_dequeue_deferred(vm_page_t m)
3270 {
3271 	uint8_t queue;
3272 
3273 	vm_page_assert_locked(m);
3274 
3275 	if ((queue = vm_page_queue(m)) == PQ_NONE)
3276 		return;
3277 	vm_page_aflag_set(m, PGA_DEQUEUE);
3278 	vm_pqbatch_submit_page(m, queue);
3279 }
3280 
3281 /*
3282  *	vm_page_dequeue:
3283  *
3284  *	Remove the page from whichever page queue it's in, if any.
3285  *	The page must either be locked or unallocated.  This constraint
3286  *	ensures that the queue state of the page will remain consistent
3287  *	after this function returns.
3288  */
3289 void
vm_page_dequeue(vm_page_t m)3290 vm_page_dequeue(vm_page_t m)
3291 {
3292 	struct vm_pagequeue *pq, *pq1;
3293 	uint8_t aflags;
3294 
3295 	KASSERT(mtx_owned(vm_page_lockptr(m)) || m->object == NULL,
3296 	    ("page %p is allocated and unlocked", m));
3297 
3298 	for (pq = vm_page_pagequeue(m);; pq = pq1) {
3299 		if (pq == NULL) {
3300 			/*
3301 			 * A thread may be concurrently executing
3302 			 * vm_page_dequeue_complete().  Ensure that all queue
3303 			 * state is cleared before we return.
3304 			 */
3305 			aflags = atomic_load_8(&m->aflags);
3306 			if ((aflags & PGA_QUEUE_STATE_MASK) == 0)
3307 				return;
3308 			KASSERT((aflags & PGA_DEQUEUE) != 0,
3309 			    ("page %p has unexpected queue state flags %#x",
3310 			    m, aflags));
3311 
3312 			/*
3313 			 * Busy wait until the thread updating queue state is
3314 			 * finished.  Such a thread must be executing in a
3315 			 * critical section.
3316 			 */
3317 			cpu_spinwait();
3318 			pq1 = vm_page_pagequeue(m);
3319 			continue;
3320 		}
3321 		vm_pagequeue_lock(pq);
3322 		if ((pq1 = vm_page_pagequeue(m)) == pq)
3323 			break;
3324 		vm_pagequeue_unlock(pq);
3325 	}
3326 	KASSERT(pq == vm_page_pagequeue(m),
3327 	    ("%s: page %p migrated directly between queues", __func__, m));
3328 	KASSERT((m->aflags & PGA_DEQUEUE) != 0 ||
3329 	    mtx_owned(vm_page_lockptr(m)),
3330 	    ("%s: queued unlocked page %p", __func__, m));
3331 
3332 	if ((m->aflags & PGA_ENQUEUED) != 0)
3333 		vm_pagequeue_remove(pq, m);
3334 	vm_page_dequeue_complete(m);
3335 	vm_pagequeue_unlock(pq);
3336 }
3337 
3338 /*
3339  * Schedule the given page for insertion into the specified page queue.
3340  * Physical insertion of the page may be deferred indefinitely.
3341  */
3342 static void
vm_page_enqueue(vm_page_t m,uint8_t queue)3343 vm_page_enqueue(vm_page_t m, uint8_t queue)
3344 {
3345 
3346 	vm_page_assert_locked(m);
3347 	KASSERT(m->queue == PQ_NONE && (m->aflags & PGA_QUEUE_STATE_MASK) == 0,
3348 	    ("%s: page %p is already enqueued", __func__, m));
3349 
3350 	m->queue = queue;
3351 	if ((m->aflags & PGA_REQUEUE) == 0)
3352 		vm_page_aflag_set(m, PGA_REQUEUE);
3353 	vm_pqbatch_submit_page(m, queue);
3354 }
3355 
3356 /*
3357  *	vm_page_requeue:		[ internal use only ]
3358  *
3359  *	Schedule a requeue of the given page.
3360  *
3361  *	The page must be locked.
3362  */
3363 void
vm_page_requeue(vm_page_t m)3364 vm_page_requeue(vm_page_t m)
3365 {
3366 
3367 	vm_page_assert_locked(m);
3368 	KASSERT(vm_page_queue(m) != PQ_NONE,
3369 	    ("%s: page %p is not logically enqueued", __func__, m));
3370 
3371 	if ((m->aflags & PGA_REQUEUE) == 0)
3372 		vm_page_aflag_set(m, PGA_REQUEUE);
3373 	vm_pqbatch_submit_page(m, atomic_load_8(&m->queue));
3374 }
3375 
3376 /*
3377  *	vm_page_free_prep:
3378  *
3379  *	Prepares the given page to be put on the free list,
3380  *	disassociating it from any VM object. The caller may return
3381  *	the page to the free list only if this function returns true.
3382  *
3383  *	The object must be locked.  The page must be locked if it is
3384  *	managed.
3385  */
3386 bool
vm_page_free_prep(vm_page_t m)3387 vm_page_free_prep(vm_page_t m)
3388 {
3389 
3390 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
3391 	if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
3392 		uint64_t *p;
3393 		int i;
3394 		p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3395 		for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
3396 			KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
3397 			    m, i, (uintmax_t)*p));
3398 	}
3399 #endif
3400 	if ((m->oflags & VPO_UNMANAGED) == 0) {
3401 		vm_page_lock_assert(m, MA_OWNED);
3402 		KASSERT(!pmap_page_is_mapped(m),
3403 		    ("vm_page_free_prep: freeing mapped page %p", m));
3404 	} else
3405 		KASSERT(m->queue == PQ_NONE,
3406 		    ("vm_page_free_prep: unmanaged page %p is queued", m));
3407 	VM_CNT_INC(v_tfree);
3408 
3409 	if (vm_page_sbusied(m))
3410 		panic("vm_page_free_prep: freeing busy page %p", m);
3411 
3412 	if (m->object != NULL)
3413 		(void)vm_page_remove(m);
3414 
3415 	/*
3416 	 * If fictitious remove object association and
3417 	 * return.
3418 	 */
3419 	if ((m->flags & PG_FICTITIOUS) != 0) {
3420 		KASSERT(m->wire_count == 1,
3421 		    ("fictitious page %p is not wired", m));
3422 		KASSERT(m->queue == PQ_NONE,
3423 		    ("fictitious page %p is queued", m));
3424 		return (false);
3425 	}
3426 
3427 	/*
3428 	 * Pages need not be dequeued before they are returned to the physical
3429 	 * memory allocator, but they must at least be marked for a deferred
3430 	 * dequeue.
3431 	 */
3432 	if ((m->oflags & VPO_UNMANAGED) == 0)
3433 		vm_page_dequeue_deferred(m);
3434 
3435 	m->valid = 0;
3436 	vm_page_undirty(m);
3437 
3438 	if (vm_page_wired(m) != 0)
3439 		panic("vm_page_free_prep: freeing wired page %p", m);
3440 	if (m->hold_count != 0) {
3441 		m->flags &= ~PG_ZERO;
3442 		KASSERT((m->flags & PG_UNHOLDFREE) == 0,
3443 		    ("vm_page_free_prep: freeing PG_UNHOLDFREE page %p", m));
3444 		m->flags |= PG_UNHOLDFREE;
3445 		return (false);
3446 	}
3447 
3448 	/*
3449 	 * Restore the default memory attribute to the page.
3450 	 */
3451 	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
3452 		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
3453 
3454 #if VM_NRESERVLEVEL > 0
3455 	/*
3456 	 * Determine whether the page belongs to a reservation.  If the page was
3457 	 * allocated from a per-CPU cache, it cannot belong to a reservation, so
3458 	 * as an optimization, we avoid the check in that case.
3459 	 */
3460 	if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
3461 		return (false);
3462 #endif
3463 
3464 	return (true);
3465 }
3466 
3467 /*
3468  *	vm_page_free_toq:
3469  *
3470  *	Returns the given page to the free list, disassociating it
3471  *	from any VM object.
3472  *
3473  *	The object must be locked.  The page must be locked if it is
3474  *	managed.
3475  */
3476 void
vm_page_free_toq(vm_page_t m)3477 vm_page_free_toq(vm_page_t m)
3478 {
3479 	struct vm_domain *vmd;
3480 	uma_zone_t zone;
3481 
3482 	if (!vm_page_free_prep(m))
3483 		return;
3484 
3485 	vmd = vm_pagequeue_domain(m);
3486 	zone = vmd->vmd_pgcache[m->pool].zone;
3487 	if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
3488 		uma_zfree(zone, m);
3489 		return;
3490 	}
3491 	vm_domain_free_lock(vmd);
3492 	vm_phys_free_pages(m, 0);
3493 	vm_domain_free_unlock(vmd);
3494 	vm_domain_freecnt_inc(vmd, 1);
3495 }
3496 
3497 /*
3498  *	vm_page_free_pages_toq:
3499  *
3500  *	Returns a list of pages to the free list, disassociating it
3501  *	from any VM object.  In other words, this is equivalent to
3502  *	calling vm_page_free_toq() for each page of a list of VM objects.
3503  *
3504  *	The objects must be locked.  The pages must be locked if it is
3505  *	managed.
3506  */
3507 void
vm_page_free_pages_toq(struct spglist * free,bool update_wire_count)3508 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
3509 {
3510 	vm_page_t m;
3511 	int count;
3512 
3513 	if (SLIST_EMPTY(free))
3514 		return;
3515 
3516 	count = 0;
3517 	while ((m = SLIST_FIRST(free)) != NULL) {
3518 		count++;
3519 		SLIST_REMOVE_HEAD(free, plinks.s.ss);
3520 		vm_page_free_toq(m);
3521 	}
3522 
3523 	if (update_wire_count)
3524 		vm_wire_sub(count);
3525 }
3526 
3527 /*
3528  *	vm_page_wire:
3529  *
3530  * Mark this page as wired down.  If the page is fictitious, then
3531  * its wire count must remain one.
3532  *
3533  * The page must be locked.
3534  */
3535 void
vm_page_wire(vm_page_t m)3536 vm_page_wire(vm_page_t m)
3537 {
3538 
3539 	vm_page_assert_locked(m);
3540 	if ((m->flags & PG_FICTITIOUS) != 0) {
3541 		KASSERT(m->wire_count == 1,
3542 		    ("vm_page_wire: fictitious page %p's wire count isn't one",
3543 		    m));
3544 		return;
3545 	}
3546 	if (!vm_page_wired(m)) {
3547 		KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
3548 		    m->queue == PQ_NONE,
3549 		    ("vm_page_wire: unmanaged page %p is queued", m));
3550 		vm_wire_add(1);
3551 	}
3552 	m->wire_count++;
3553 	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
3554 }
3555 
3556 /*
3557  * vm_page_unwire:
3558  *
3559  * Release one wiring of the specified page, potentially allowing it to be
3560  * paged out.  Returns TRUE if the number of wirings transitions to zero and
3561  * FALSE otherwise.
3562  *
3563  * Only managed pages belonging to an object can be paged out.  If the number
3564  * of wirings transitions to zero and the page is eligible for page out, then
3565  * the page is added to the specified paging queue (unless PQ_NONE is
3566  * specified, in which case the page is dequeued if it belongs to a paging
3567  * queue).
3568  *
3569  * If a page is fictitious, then its wire count must always be one.
3570  *
3571  * A managed page must be locked.
3572  */
3573 bool
vm_page_unwire(vm_page_t m,uint8_t queue)3574 vm_page_unwire(vm_page_t m, uint8_t queue)
3575 {
3576 	bool unwired;
3577 
3578 	KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
3579 	    ("vm_page_unwire: invalid queue %u request for page %p",
3580 	    queue, m));
3581 	if ((m->oflags & VPO_UNMANAGED) == 0)
3582 		vm_page_assert_locked(m);
3583 
3584 	unwired = vm_page_unwire_noq(m);
3585 	if (!unwired || (m->oflags & VPO_UNMANAGED) != 0 || m->object == NULL)
3586 		return (unwired);
3587 
3588 	if (vm_page_queue(m) == queue) {
3589 		if (queue == PQ_ACTIVE)
3590 			vm_page_reference(m);
3591 		else if (queue != PQ_NONE)
3592 			vm_page_requeue(m);
3593 	} else {
3594 		vm_page_dequeue(m);
3595 		if (queue != PQ_NONE) {
3596 			vm_page_enqueue(m, queue);
3597 			if (queue == PQ_ACTIVE)
3598 				/* Initialize act_count. */
3599 				vm_page_activate(m);
3600 		}
3601 	}
3602 	return (unwired);
3603 }
3604 
3605 /*
3606  *
3607  * vm_page_unwire_noq:
3608  *
3609  * Unwire a page without (re-)inserting it into a page queue.  It is up
3610  * to the caller to enqueue, requeue, or free the page as appropriate.
3611  * In most cases, vm_page_unwire() should be used instead.
3612  */
3613 bool
vm_page_unwire_noq(vm_page_t m)3614 vm_page_unwire_noq(vm_page_t m)
3615 {
3616 
3617 	if ((m->oflags & VPO_UNMANAGED) == 0)
3618 		vm_page_assert_locked(m);
3619 	if ((m->flags & PG_FICTITIOUS) != 0) {
3620 		KASSERT(m->wire_count == 1,
3621 	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
3622 		return (false);
3623 	}
3624 	if (!vm_page_wired(m))
3625 		panic("vm_page_unwire: page %p's wire count is zero", m);
3626 	m->wire_count--;
3627 	if (m->wire_count == 0) {
3628 		vm_wire_sub(1);
3629 		return (true);
3630 	} else
3631 		return (false);
3632 }
3633 
3634 /*
3635  *	vm_page_activate:
3636  *
3637  *	Put the specified page on the active list (if appropriate).
3638  *	Ensure that act_count is at least ACT_INIT but do not otherwise
3639  *	mess with it.
3640  *
3641  *	The page must be locked.
3642  */
3643 void
vm_page_activate(vm_page_t m)3644 vm_page_activate(vm_page_t m)
3645 {
3646 
3647 	vm_page_assert_locked(m);
3648 
3649 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3650 		return;
3651 	if (vm_page_queue(m) == PQ_ACTIVE) {
3652 		if (m->act_count < ACT_INIT)
3653 			m->act_count = ACT_INIT;
3654 		return;
3655 	}
3656 
3657 	vm_page_dequeue(m);
3658 	if (m->act_count < ACT_INIT)
3659 		m->act_count = ACT_INIT;
3660 	vm_page_enqueue(m, PQ_ACTIVE);
3661 }
3662 
3663 /*
3664  * Move the specified page to the tail of the inactive queue, or requeue
3665  * the page if it is already in the inactive queue.
3666  *
3667  * The page must be locked.
3668  */
3669 void
vm_page_deactivate(vm_page_t m)3670 vm_page_deactivate(vm_page_t m)
3671 {
3672 
3673 	vm_page_assert_locked(m);
3674 
3675 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3676 		return;
3677 
3678 	if (!vm_page_inactive(m)) {
3679 		vm_page_dequeue(m);
3680 		vm_page_enqueue(m, PQ_INACTIVE);
3681 	} else
3682 		vm_page_requeue(m);
3683 }
3684 
3685 /*
3686  * Move the specified page close to the head of the inactive queue,
3687  * bypassing LRU.  A marker page is used to maintain FIFO ordering.
3688  * As with regular enqueues, we use a per-CPU batch queue to reduce
3689  * contention on the page queue lock.
3690  *
3691  * The page must be locked.
3692  */
3693 void
vm_page_deactivate_noreuse(vm_page_t m)3694 vm_page_deactivate_noreuse(vm_page_t m)
3695 {
3696 
3697 	vm_page_assert_locked(m);
3698 
3699 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3700 		return;
3701 
3702 	if (!vm_page_inactive(m)) {
3703 		vm_page_dequeue(m);
3704 		m->queue = PQ_INACTIVE;
3705 	}
3706 	if ((m->aflags & PGA_REQUEUE_HEAD) == 0)
3707 		vm_page_aflag_set(m, PGA_REQUEUE_HEAD);
3708 	vm_pqbatch_submit_page(m, PQ_INACTIVE);
3709 }
3710 
3711 /*
3712  * vm_page_launder
3713  *
3714  * 	Put a page in the laundry, or requeue it if it is already there.
3715  */
3716 void
vm_page_launder(vm_page_t m)3717 vm_page_launder(vm_page_t m)
3718 {
3719 
3720 	vm_page_assert_locked(m);
3721 	if (vm_page_wired(m) || (m->oflags & VPO_UNMANAGED) != 0)
3722 		return;
3723 
3724 	if (vm_page_in_laundry(m))
3725 		vm_page_requeue(m);
3726 	else {
3727 		vm_page_dequeue(m);
3728 		vm_page_enqueue(m, PQ_LAUNDRY);
3729 	}
3730 }
3731 
3732 /*
3733  * vm_page_unswappable
3734  *
3735  *	Put a page in the PQ_UNSWAPPABLE holding queue.
3736  */
3737 void
vm_page_unswappable(vm_page_t m)3738 vm_page_unswappable(vm_page_t m)
3739 {
3740 
3741 	vm_page_assert_locked(m);
3742 	KASSERT(!vm_page_wired(m) && (m->oflags & VPO_UNMANAGED) == 0,
3743 	    ("page %p already unswappable", m));
3744 
3745 	vm_page_dequeue(m);
3746 	vm_page_enqueue(m, PQ_UNSWAPPABLE);
3747 }
3748 
3749 static void
vm_page_release_toq(vm_page_t m,int flags)3750 vm_page_release_toq(vm_page_t m, int flags)
3751 {
3752 
3753 	/*
3754 	 * Use a check of the valid bits to determine whether we should
3755 	 * accelerate reclamation of the page.  The object lock might not be
3756 	 * held here, in which case the check is racy.  At worst we will either
3757 	 * accelerate reclamation of a valid page and violate LRU, or
3758 	 * unnecessarily defer reclamation of an invalid page.
3759 	 *
3760 	 * If we were asked to not cache the page, place it near the head of the
3761 	 * inactive queue so that is reclaimed sooner.
3762 	 */
3763 	if ((flags & (VPR_TRYFREE | VPR_NOREUSE)) != 0 || m->valid == 0)
3764 		vm_page_deactivate_noreuse(m);
3765 	else if (vm_page_active(m))
3766 		vm_page_reference(m);
3767 	else
3768 		vm_page_deactivate(m);
3769 }
3770 
3771 /*
3772  * Unwire a page and either attempt to free it or re-add it to the page queues.
3773  */
3774 void
vm_page_release(vm_page_t m,int flags)3775 vm_page_release(vm_page_t m, int flags)
3776 {
3777 	vm_object_t object;
3778 	bool freed;
3779 
3780 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3781 	    ("vm_page_release: page %p is unmanaged", m));
3782 
3783 	vm_page_lock(m);
3784 	if (m->object != NULL)
3785 		VM_OBJECT_ASSERT_UNLOCKED(m->object);
3786 	if (vm_page_unwire_noq(m)) {
3787 		if ((object = m->object) == NULL) {
3788 			vm_page_free(m);
3789 		} else {
3790 			freed = false;
3791 			if ((flags & VPR_TRYFREE) != 0 && !vm_page_busied(m) &&
3792 			    /* Depends on type stability. */
3793 			    VM_OBJECT_TRYWLOCK(object)) {
3794 				/*
3795 				 * Only free unmapped pages.  The busy test from
3796 				 * before the object was locked cannot be relied
3797 				 * upon.
3798 				 */
3799 				if ((object->ref_count == 0 ||
3800 				    !pmap_page_is_mapped(m)) && m->dirty == 0 &&
3801 				    !vm_page_busied(m)) {
3802 					vm_page_free(m);
3803 					freed = true;
3804 				}
3805 				VM_OBJECT_WUNLOCK(object);
3806 			}
3807 
3808 			if (!freed)
3809 				vm_page_release_toq(m, flags);
3810 		}
3811 	}
3812 	vm_page_unlock(m);
3813 }
3814 
3815 /* See vm_page_release(). */
3816 void
vm_page_release_locked(vm_page_t m,int flags)3817 vm_page_release_locked(vm_page_t m, int flags)
3818 {
3819 
3820 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3821 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3822 	    ("vm_page_release_locked: page %p is unmanaged", m));
3823 
3824 	vm_page_lock(m);
3825 	if (vm_page_unwire_noq(m)) {
3826 		if ((flags & VPR_TRYFREE) != 0 &&
3827 		    (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
3828 		    m->dirty == 0 && !vm_page_busied(m)) {
3829 			vm_page_free(m);
3830 		} else {
3831 			vm_page_release_toq(m, flags);
3832 		}
3833 	}
3834 	vm_page_unlock(m);
3835 }
3836 
3837 /*
3838  * vm_page_advise
3839  *
3840  * 	Apply the specified advice to the given page.
3841  *
3842  *	The object and page must be locked.
3843  */
3844 void
vm_page_advise(vm_page_t m,int advice)3845 vm_page_advise(vm_page_t m, int advice)
3846 {
3847 
3848 	vm_page_assert_locked(m);
3849 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3850 	if (advice == MADV_FREE)
3851 		/*
3852 		 * Mark the page clean.  This will allow the page to be freed
3853 		 * without first paging it out.  MADV_FREE pages are often
3854 		 * quickly reused by malloc(3), so we do not do anything that
3855 		 * would result in a page fault on a later access.
3856 		 */
3857 		vm_page_undirty(m);
3858 	else if (advice != MADV_DONTNEED) {
3859 		if (advice == MADV_WILLNEED)
3860 			vm_page_activate(m);
3861 		return;
3862 	}
3863 
3864 	/*
3865 	 * Clear any references to the page.  Otherwise, the page daemon will
3866 	 * immediately reactivate the page.
3867 	 */
3868 	vm_page_aflag_clear(m, PGA_REFERENCED);
3869 
3870 	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3871 		vm_page_dirty(m);
3872 
3873 	/*
3874 	 * Place clean pages near the head of the inactive queue rather than
3875 	 * the tail, thus defeating the queue's LRU operation and ensuring that
3876 	 * the page will be reused quickly.  Dirty pages not already in the
3877 	 * laundry are moved there.
3878 	 */
3879 	if (m->dirty == 0)
3880 		vm_page_deactivate_noreuse(m);
3881 	else if (!vm_page_in_laundry(m))
3882 		vm_page_launder(m);
3883 }
3884 
3885 /*
3886  * Grab a page, waiting until we are waken up due to the page
3887  * changing state.  We keep on waiting, if the page continues
3888  * to be in the object.  If the page doesn't exist, first allocate it
3889  * and then conditionally zero it.
3890  *
3891  * This routine may sleep.
3892  *
3893  * The object must be locked on entry.  The lock will, however, be released
3894  * and reacquired if the routine sleeps.
3895  */
3896 vm_page_t
vm_page_grab(vm_object_t object,vm_pindex_t pindex,int allocflags)3897 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3898 {
3899 	vm_page_t m;
3900 	int sleep;
3901 	int pflags;
3902 
3903 	VM_OBJECT_ASSERT_WLOCKED(object);
3904 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3905 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3906 	    ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3907 	pflags = allocflags &
3908 	    ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
3909 	if ((allocflags & VM_ALLOC_NOWAIT) == 0)
3910 		pflags |= VM_ALLOC_WAITFAIL;
3911 retrylookup:
3912 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
3913 		sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3914 		    vm_page_xbusied(m) : vm_page_busied(m);
3915 		if (sleep) {
3916 			if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3917 				return (NULL);
3918 			/*
3919 			 * Reference the page before unlocking and
3920 			 * sleeping so that the page daemon is less
3921 			 * likely to reclaim it.
3922 			 */
3923 			vm_page_aflag_set(m, PGA_REFERENCED);
3924 			vm_page_lock(m);
3925 			VM_OBJECT_WUNLOCK(object);
3926 			vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3927 			    VM_ALLOC_IGN_SBUSY) != 0);
3928 			VM_OBJECT_WLOCK(object);
3929 			goto retrylookup;
3930 		} else {
3931 			if ((allocflags & VM_ALLOC_WIRED) != 0) {
3932 				vm_page_lock(m);
3933 				vm_page_wire(m);
3934 				vm_page_unlock(m);
3935 			}
3936 			if ((allocflags &
3937 			    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3938 				vm_page_xbusy(m);
3939 			if ((allocflags & VM_ALLOC_SBUSY) != 0)
3940 				vm_page_sbusy(m);
3941 			return (m);
3942 		}
3943 	}
3944 	m = vm_page_alloc(object, pindex, pflags);
3945 	if (m == NULL) {
3946 		if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3947 			return (NULL);
3948 		goto retrylookup;
3949 	}
3950 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3951 		pmap_zero_page(m);
3952 	return (m);
3953 }
3954 
3955 /*
3956  * Return the specified range of pages from the given object.  For each
3957  * page offset within the range, if a page already exists within the object
3958  * at that offset and it is busy, then wait for it to change state.  If,
3959  * instead, the page doesn't exist, then allocate it.
3960  *
3961  * The caller must always specify an allocation class.
3962  *
3963  * allocation classes:
3964  *	VM_ALLOC_NORMAL		normal process request
3965  *	VM_ALLOC_SYSTEM		system *really* needs the pages
3966  *
3967  * The caller must always specify that the pages are to be busied and/or
3968  * wired.
3969  *
3970  * optional allocation flags:
3971  *	VM_ALLOC_IGN_SBUSY	do not sleep on soft busy pages
3972  *	VM_ALLOC_NOBUSY		do not exclusive busy the page
3973  *	VM_ALLOC_NOWAIT		do not sleep
3974  *	VM_ALLOC_SBUSY		set page to sbusy state
3975  *	VM_ALLOC_WIRED		wire the pages
3976  *	VM_ALLOC_ZERO		zero and validate any invalid pages
3977  *
3978  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
3979  * may return a partial prefix of the requested range.
3980  */
3981 int
vm_page_grab_pages(vm_object_t object,vm_pindex_t pindex,int allocflags,vm_page_t * ma,int count)3982 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
3983     vm_page_t *ma, int count)
3984 {
3985 	vm_page_t m, mpred;
3986 	int pflags;
3987 	int i;
3988 	bool sleep;
3989 
3990 	VM_OBJECT_ASSERT_WLOCKED(object);
3991 	KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
3992 	    ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
3993 	KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
3994 	    (allocflags & VM_ALLOC_WIRED) != 0,
3995 	    ("vm_page_grab_pages: the pages must be busied or wired"));
3996 	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3997 	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3998 	    ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
3999 	if (count == 0)
4000 		return (0);
4001 	pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
4002 	    VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
4003 	if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4004 		pflags |= VM_ALLOC_WAITFAIL;
4005 	i = 0;
4006 retrylookup:
4007 	m = vm_radix_lookup_le(&object->rtree, pindex + i);
4008 	if (m == NULL || m->pindex != pindex + i) {
4009 		mpred = m;
4010 		m = NULL;
4011 	} else
4012 		mpred = TAILQ_PREV(m, pglist, listq);
4013 	for (; i < count; i++) {
4014 		if (m != NULL) {
4015 			sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
4016 			    vm_page_xbusied(m) : vm_page_busied(m);
4017 			if (sleep) {
4018 				if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4019 					break;
4020 				/*
4021 				 * Reference the page before unlocking and
4022 				 * sleeping so that the page daemon is less
4023 				 * likely to reclaim it.
4024 				 */
4025 				vm_page_aflag_set(m, PGA_REFERENCED);
4026 				vm_page_lock(m);
4027 				VM_OBJECT_WUNLOCK(object);
4028 				vm_page_busy_sleep(m, "grbmaw", (allocflags &
4029 				    VM_ALLOC_IGN_SBUSY) != 0);
4030 				VM_OBJECT_WLOCK(object);
4031 				goto retrylookup;
4032 			}
4033 			if ((allocflags & VM_ALLOC_WIRED) != 0) {
4034 				vm_page_lock(m);
4035 				vm_page_wire(m);
4036 				vm_page_unlock(m);
4037 			}
4038 			if ((allocflags & (VM_ALLOC_NOBUSY |
4039 			    VM_ALLOC_SBUSY)) == 0)
4040 				vm_page_xbusy(m);
4041 			if ((allocflags & VM_ALLOC_SBUSY) != 0)
4042 				vm_page_sbusy(m);
4043 		} else {
4044 			m = vm_page_alloc_after(object, pindex + i,
4045 			    pflags | VM_ALLOC_COUNT(count - i), mpred);
4046 			if (m == NULL) {
4047 				if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4048 					break;
4049 				goto retrylookup;
4050 			}
4051 		}
4052 		if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
4053 			if ((m->flags & PG_ZERO) == 0)
4054 				pmap_zero_page(m);
4055 			m->valid = VM_PAGE_BITS_ALL;
4056 		}
4057 		ma[i] = mpred = m;
4058 		m = vm_page_next(m);
4059 	}
4060 	return (i);
4061 }
4062 
4063 /*
4064  * Mapping function for valid or dirty bits in a page.
4065  *
4066  * Inputs are required to range within a page.
4067  */
4068 vm_page_bits_t
vm_page_bits(int base,int size)4069 vm_page_bits(int base, int size)
4070 {
4071 	int first_bit;
4072 	int last_bit;
4073 
4074 	KASSERT(
4075 	    base + size <= PAGE_SIZE,
4076 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
4077 	);
4078 
4079 	if (size == 0)		/* handle degenerate case */
4080 		return (0);
4081 
4082 	first_bit = base >> DEV_BSHIFT;
4083 	last_bit = (base + size - 1) >> DEV_BSHIFT;
4084 
4085 	return (((vm_page_bits_t)2 << last_bit) -
4086 	    ((vm_page_bits_t)1 << first_bit));
4087 }
4088 
4089 /*
4090  *	vm_page_set_valid_range:
4091  *
4092  *	Sets portions of a page valid.  The arguments are expected
4093  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4094  *	of any partial chunks touched by the range.  The invalid portion of
4095  *	such chunks will be zeroed.
4096  *
4097  *	(base + size) must be less then or equal to PAGE_SIZE.
4098  */
4099 void
vm_page_set_valid_range(vm_page_t m,int base,int size)4100 vm_page_set_valid_range(vm_page_t m, int base, int size)
4101 {
4102 	int endoff, frag;
4103 
4104 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4105 	if (size == 0)	/* handle degenerate case */
4106 		return;
4107 
4108 	/*
4109 	 * If the base is not DEV_BSIZE aligned and the valid
4110 	 * bit is clear, we have to zero out a portion of the
4111 	 * first block.
4112 	 */
4113 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4114 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
4115 		pmap_zero_page_area(m, frag, base - frag);
4116 
4117 	/*
4118 	 * If the ending offset is not DEV_BSIZE aligned and the
4119 	 * valid bit is clear, we have to zero out a portion of
4120 	 * the last block.
4121 	 */
4122 	endoff = base + size;
4123 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4124 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
4125 		pmap_zero_page_area(m, endoff,
4126 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4127 
4128 	/*
4129 	 * Assert that no previously invalid block that is now being validated
4130 	 * is already dirty.
4131 	 */
4132 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
4133 	    ("vm_page_set_valid_range: page %p is dirty", m));
4134 
4135 	/*
4136 	 * Set valid bits inclusive of any overlap.
4137 	 */
4138 	m->valid |= vm_page_bits(base, size);
4139 }
4140 
4141 /*
4142  * Clear the given bits from the specified page's dirty field.
4143  */
4144 static __inline void
vm_page_clear_dirty_mask(vm_page_t m,vm_page_bits_t pagebits)4145 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
4146 {
4147 	uintptr_t addr;
4148 #if PAGE_SIZE < 16384
4149 	int shift;
4150 #endif
4151 
4152 	/*
4153 	 * If the object is locked and the page is neither exclusive busy nor
4154 	 * write mapped, then the page's dirty field cannot possibly be
4155 	 * set by a concurrent pmap operation.
4156 	 */
4157 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4158 	if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
4159 		m->dirty &= ~pagebits;
4160 	else {
4161 		/*
4162 		 * The pmap layer can call vm_page_dirty() without
4163 		 * holding a distinguished lock.  The combination of
4164 		 * the object's lock and an atomic operation suffice
4165 		 * to guarantee consistency of the page dirty field.
4166 		 *
4167 		 * For PAGE_SIZE == 32768 case, compiler already
4168 		 * properly aligns the dirty field, so no forcible
4169 		 * alignment is needed. Only require existence of
4170 		 * atomic_clear_64 when page size is 32768.
4171 		 */
4172 		addr = (uintptr_t)&m->dirty;
4173 #if PAGE_SIZE == 32768
4174 		atomic_clear_64((uint64_t *)addr, pagebits);
4175 #elif PAGE_SIZE == 16384
4176 		atomic_clear_32((uint32_t *)addr, pagebits);
4177 #else		/* PAGE_SIZE <= 8192 */
4178 		/*
4179 		 * Use a trick to perform a 32-bit atomic on the
4180 		 * containing aligned word, to not depend on the existence
4181 		 * of atomic_clear_{8, 16}.
4182 		 */
4183 		shift = addr & (sizeof(uint32_t) - 1);
4184 #if BYTE_ORDER == BIG_ENDIAN
4185 		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
4186 #else
4187 		shift *= NBBY;
4188 #endif
4189 		addr &= ~(sizeof(uint32_t) - 1);
4190 		atomic_clear_32((uint32_t *)addr, pagebits << shift);
4191 #endif		/* PAGE_SIZE */
4192 	}
4193 }
4194 
4195 /*
4196  *	vm_page_set_validclean:
4197  *
4198  *	Sets portions of a page valid and clean.  The arguments are expected
4199  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
4200  *	of any partial chunks touched by the range.  The invalid portion of
4201  *	such chunks will be zero'd.
4202  *
4203  *	(base + size) must be less then or equal to PAGE_SIZE.
4204  */
4205 void
vm_page_set_validclean(vm_page_t m,int base,int size)4206 vm_page_set_validclean(vm_page_t m, int base, int size)
4207 {
4208 	vm_page_bits_t oldvalid, pagebits;
4209 	int endoff, frag;
4210 
4211 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4212 	if (size == 0)	/* handle degenerate case */
4213 		return;
4214 
4215 	/*
4216 	 * If the base is not DEV_BSIZE aligned and the valid
4217 	 * bit is clear, we have to zero out a portion of the
4218 	 * first block.
4219 	 */
4220 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
4221 	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
4222 		pmap_zero_page_area(m, frag, base - frag);
4223 
4224 	/*
4225 	 * If the ending offset is not DEV_BSIZE aligned and the
4226 	 * valid bit is clear, we have to zero out a portion of
4227 	 * the last block.
4228 	 */
4229 	endoff = base + size;
4230 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
4231 	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
4232 		pmap_zero_page_area(m, endoff,
4233 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
4234 
4235 	/*
4236 	 * Set valid, clear dirty bits.  If validating the entire
4237 	 * page we can safely clear the pmap modify bit.  We also
4238 	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
4239 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
4240 	 * be set again.
4241 	 *
4242 	 * We set valid bits inclusive of any overlap, but we can only
4243 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
4244 	 * the range.
4245 	 */
4246 	oldvalid = m->valid;
4247 	pagebits = vm_page_bits(base, size);
4248 	m->valid |= pagebits;
4249 #if 0	/* NOT YET */
4250 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
4251 		frag = DEV_BSIZE - frag;
4252 		base += frag;
4253 		size -= frag;
4254 		if (size < 0)
4255 			size = 0;
4256 	}
4257 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
4258 #endif
4259 	if (base == 0 && size == PAGE_SIZE) {
4260 		/*
4261 		 * The page can only be modified within the pmap if it is
4262 		 * mapped, and it can only be mapped if it was previously
4263 		 * fully valid.
4264 		 */
4265 		if (oldvalid == VM_PAGE_BITS_ALL)
4266 			/*
4267 			 * Perform the pmap_clear_modify() first.  Otherwise,
4268 			 * a concurrent pmap operation, such as
4269 			 * pmap_protect(), could clear a modification in the
4270 			 * pmap and set the dirty field on the page before
4271 			 * pmap_clear_modify() had begun and after the dirty
4272 			 * field was cleared here.
4273 			 */
4274 			pmap_clear_modify(m);
4275 		m->dirty = 0;
4276 		m->oflags &= ~VPO_NOSYNC;
4277 	} else if (oldvalid != VM_PAGE_BITS_ALL)
4278 		m->dirty &= ~pagebits;
4279 	else
4280 		vm_page_clear_dirty_mask(m, pagebits);
4281 }
4282 
4283 void
vm_page_clear_dirty(vm_page_t m,int base,int size)4284 vm_page_clear_dirty(vm_page_t m, int base, int size)
4285 {
4286 
4287 	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
4288 }
4289 
4290 /*
4291  *	vm_page_set_invalid:
4292  *
4293  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
4294  *	valid and dirty bits for the effected areas are cleared.
4295  */
4296 void
vm_page_set_invalid(vm_page_t m,int base,int size)4297 vm_page_set_invalid(vm_page_t m, int base, int size)
4298 {
4299 	vm_page_bits_t bits;
4300 	vm_object_t object;
4301 
4302 	object = m->object;
4303 	VM_OBJECT_ASSERT_WLOCKED(object);
4304 	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
4305 	    size >= object->un_pager.vnp.vnp_size)
4306 		bits = VM_PAGE_BITS_ALL;
4307 	else
4308 		bits = vm_page_bits(base, size);
4309 	if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
4310 	    bits != 0)
4311 		pmap_remove_all(m);
4312 	KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
4313 	    !pmap_page_is_mapped(m),
4314 	    ("vm_page_set_invalid: page %p is mapped", m));
4315 	m->valid &= ~bits;
4316 	m->dirty &= ~bits;
4317 }
4318 
4319 /*
4320  * vm_page_zero_invalid()
4321  *
4322  *	The kernel assumes that the invalid portions of a page contain
4323  *	garbage, but such pages can be mapped into memory by user code.
4324  *	When this occurs, we must zero out the non-valid portions of the
4325  *	page so user code sees what it expects.
4326  *
4327  *	Pages are most often semi-valid when the end of a file is mapped
4328  *	into memory and the file's size is not page aligned.
4329  */
4330 void
vm_page_zero_invalid(vm_page_t m,boolean_t setvalid)4331 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
4332 {
4333 	int b;
4334 	int i;
4335 
4336 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4337 	/*
4338 	 * Scan the valid bits looking for invalid sections that
4339 	 * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
4340 	 * valid bit may be set ) have already been zeroed by
4341 	 * vm_page_set_validclean().
4342 	 */
4343 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
4344 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
4345 		    (m->valid & ((vm_page_bits_t)1 << i))) {
4346 			if (i > b) {
4347 				pmap_zero_page_area(m,
4348 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
4349 			}
4350 			b = i + 1;
4351 		}
4352 	}
4353 
4354 	/*
4355 	 * setvalid is TRUE when we can safely set the zero'd areas
4356 	 * as being valid.  We can do this if there are no cache consistancy
4357 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
4358 	 */
4359 	if (setvalid)
4360 		m->valid = VM_PAGE_BITS_ALL;
4361 }
4362 
4363 /*
4364  *	vm_page_is_valid:
4365  *
4366  *	Is (partial) page valid?  Note that the case where size == 0
4367  *	will return FALSE in the degenerate case where the page is
4368  *	entirely invalid, and TRUE otherwise.
4369  */
4370 int
vm_page_is_valid(vm_page_t m,int base,int size)4371 vm_page_is_valid(vm_page_t m, int base, int size)
4372 {
4373 	vm_page_bits_t bits;
4374 
4375 	VM_OBJECT_ASSERT_LOCKED(m->object);
4376 	bits = vm_page_bits(base, size);
4377 	return (m->valid != 0 && (m->valid & bits) == bits);
4378 }
4379 
4380 /*
4381  * Returns true if all of the specified predicates are true for the entire
4382  * (super)page and false otherwise.
4383  */
4384 bool
vm_page_ps_test(vm_page_t m,int flags,vm_page_t skip_m)4385 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
4386 {
4387 	vm_object_t object;
4388 	int i, npages;
4389 
4390 	object = m->object;
4391 	if (skip_m != NULL && skip_m->object != object)
4392 		return (false);
4393 	VM_OBJECT_ASSERT_LOCKED(object);
4394 	npages = atop(pagesizes[m->psind]);
4395 
4396 	/*
4397 	 * The physically contiguous pages that make up a superpage, i.e., a
4398 	 * page with a page size index ("psind") greater than zero, will
4399 	 * occupy adjacent entries in vm_page_array[].
4400 	 */
4401 	for (i = 0; i < npages; i++) {
4402 		/* Always test object consistency, including "skip_m". */
4403 		if (m[i].object != object)
4404 			return (false);
4405 		if (&m[i] == skip_m)
4406 			continue;
4407 		if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
4408 			return (false);
4409 		if ((flags & PS_ALL_DIRTY) != 0) {
4410 			/*
4411 			 * Calling vm_page_test_dirty() or pmap_is_modified()
4412 			 * might stop this case from spuriously returning
4413 			 * "false".  However, that would require a write lock
4414 			 * on the object containing "m[i]".
4415 			 */
4416 			if (m[i].dirty != VM_PAGE_BITS_ALL)
4417 				return (false);
4418 		}
4419 		if ((flags & PS_ALL_VALID) != 0 &&
4420 		    m[i].valid != VM_PAGE_BITS_ALL)
4421 			return (false);
4422 	}
4423 	return (true);
4424 }
4425 
4426 /*
4427  * Set the page's dirty bits if the page is modified.
4428  */
4429 void
vm_page_test_dirty(vm_page_t m)4430 vm_page_test_dirty(vm_page_t m)
4431 {
4432 
4433 	VM_OBJECT_ASSERT_WLOCKED(m->object);
4434 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
4435 		vm_page_dirty(m);
4436 }
4437 
4438 void
vm_page_lock_KBI(vm_page_t m,const char * file,int line)4439 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
4440 {
4441 
4442 	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
4443 }
4444 
4445 void
vm_page_unlock_KBI(vm_page_t m,const char * file,int line)4446 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
4447 {
4448 
4449 	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
4450 }
4451 
4452 int
vm_page_trylock_KBI(vm_page_t m,const char * file,int line)4453 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
4454 {
4455 
4456 	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
4457 }
4458 
4459 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
4460 void
vm_page_assert_locked_KBI(vm_page_t m,const char * file,int line)4461 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
4462 {
4463 
4464 	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
4465 }
4466 
4467 void
vm_page_lock_assert_KBI(vm_page_t m,int a,const char * file,int line)4468 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
4469 {
4470 
4471 	mtx_assert_(vm_page_lockptr(m), a, file, line);
4472 }
4473 #endif
4474 
4475 #ifdef INVARIANTS
4476 void
vm_page_object_lock_assert(vm_page_t m)4477 vm_page_object_lock_assert(vm_page_t m)
4478 {
4479 
4480 	/*
4481 	 * Certain of the page's fields may only be modified by the
4482 	 * holder of the containing object's lock or the exclusive busy.
4483 	 * holder.  Unfortunately, the holder of the write busy is
4484 	 * not recorded, and thus cannot be checked here.
4485 	 */
4486 	if (m->object != NULL && !vm_page_xbusied(m))
4487 		VM_OBJECT_ASSERT_WLOCKED(m->object);
4488 }
4489 
4490 void
vm_page_assert_pga_writeable(vm_page_t m,uint8_t bits)4491 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
4492 {
4493 
4494 	if ((bits & PGA_WRITEABLE) == 0)
4495 		return;
4496 
4497 	/*
4498 	 * The PGA_WRITEABLE flag can only be set if the page is
4499 	 * managed, is exclusively busied or the object is locked.
4500 	 * Currently, this flag is only set by pmap_enter().
4501 	 */
4502 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4503 	    ("PGA_WRITEABLE on unmanaged page"));
4504 	if (!vm_page_xbusied(m))
4505 		VM_OBJECT_ASSERT_LOCKED(m->object);
4506 }
4507 #endif
4508 
4509 #include "opt_ddb.h"
4510 #ifdef DDB
4511 #include <sys/kernel.h>
4512 
4513 #include <ddb/ddb.h>
4514 
DB_SHOW_COMMAND(page,vm_page_print_page_info)4515 DB_SHOW_COMMAND(page, vm_page_print_page_info)
4516 {
4517 
4518 	db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
4519 	db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
4520 	db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
4521 	db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
4522 	db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
4523 	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
4524 	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
4525 	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
4526 	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
4527 }
4528 
DB_SHOW_COMMAND(pageq,vm_page_print_pageq_info)4529 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
4530 {
4531 	int dom;
4532 
4533 	db_printf("pq_free %d\n", vm_free_count());
4534 	for (dom = 0; dom < vm_ndomains; dom++) {
4535 		db_printf(
4536     "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
4537 		    dom,
4538 		    vm_dom[dom].vmd_page_count,
4539 		    vm_dom[dom].vmd_free_count,
4540 		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
4541 		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
4542 		    vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
4543 		    vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
4544 	}
4545 }
4546 
DB_SHOW_COMMAND(pginfo,vm_page_print_pginfo)4547 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
4548 {
4549 	vm_page_t m;
4550 	boolean_t phys, virt;
4551 
4552 	if (!have_addr) {
4553 		db_printf("show pginfo addr\n");
4554 		return;
4555 	}
4556 
4557 	phys = strchr(modif, 'p') != NULL;
4558 	virt = strchr(modif, 'v') != NULL;
4559 	if (virt)
4560 		m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
4561 	else if (phys)
4562 		m = PHYS_TO_VM_PAGE(addr);
4563 	else
4564 		m = (vm_page_t)addr;
4565 	db_printf(
4566     "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
4567     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
4568 	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
4569 	    m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
4570 	    m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);
4571 }
4572 #endif /* DDB */
4573