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