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