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