xref: /freebsd/sys/vm/vm_page.c (revision 3b3a8eb937bf8045231e8364bfd1b94cd4a95979)
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 block
855  *	here so we *can't* do this anyway.
856  *
857  *	The object and page must be locked.
858  *	This routine may not block.
859  */
860 void
861 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
862 {
863 	vm_page_t root;
864 
865 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
866 	if (m->object != NULL)
867 		panic("vm_page_insert: page already inserted");
868 
869 	/*
870 	 * Record the object/offset pair in this page
871 	 */
872 	m->object = object;
873 	m->pindex = pindex;
874 
875 	/*
876 	 * Now link into the object's ordered list of backed pages.
877 	 */
878 	root = object->root;
879 	if (root == NULL) {
880 		m->left = NULL;
881 		m->right = NULL;
882 		TAILQ_INSERT_TAIL(&object->memq, m, listq);
883 	} else {
884 		root = vm_page_splay(pindex, root);
885 		if (pindex < root->pindex) {
886 			m->left = root->left;
887 			m->right = root;
888 			root->left = NULL;
889 			TAILQ_INSERT_BEFORE(root, m, listq);
890 		} else if (pindex == root->pindex)
891 			panic("vm_page_insert: offset already allocated");
892 		else {
893 			m->right = root->right;
894 			m->left = root;
895 			root->right = NULL;
896 			TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
897 		}
898 	}
899 	object->root = m;
900 
901 	/*
902 	 * show that the object has one more resident page.
903 	 */
904 	object->resident_page_count++;
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((struct vnode *)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  *				NOTE: used by device pager as well -wfj
922  *
923  *	Removes the given mem entry from the object/offset-page
924  *	table and the object page list, but do not invalidate/terminate
925  *	the backing store.
926  *
927  *	The object and page must be locked.
928  *	The underlying pmap entry (if any) is NOT removed here.
929  *	This routine may not block.
930  */
931 void
932 vm_page_remove(vm_page_t m)
933 {
934 	vm_object_t object;
935 	vm_page_t next, prev, root;
936 
937 	if ((m->oflags & VPO_UNMANAGED) == 0)
938 		vm_page_lock_assert(m, MA_OWNED);
939 	if ((object = m->object) == NULL)
940 		return;
941 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
942 	if (m->oflags & VPO_BUSY) {
943 		m->oflags &= ~VPO_BUSY;
944 		vm_page_flash(m);
945 	}
946 
947 	/*
948 	 * Now remove from the object's list of backed pages.
949 	 */
950 	if ((next = TAILQ_NEXT(m, listq)) != NULL && next->left == m) {
951 		/*
952 		 * Since the page's successor in the list is also its parent
953 		 * in the tree, its right subtree must be empty.
954 		 */
955 		next->left = m->left;
956 		KASSERT(m->right == NULL,
957 		    ("vm_page_remove: page %p has right child", m));
958 	} else if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
959 	    prev->right == m) {
960 		/*
961 		 * Since the page's predecessor in the list is also its parent
962 		 * in the tree, its left subtree must be empty.
963 		 */
964 		KASSERT(m->left == NULL,
965 		    ("vm_page_remove: page %p has left child", m));
966 		prev->right = m->right;
967 	} else {
968 		if (m != object->root)
969 			vm_page_splay(m->pindex, object->root);
970 		if (m->left == NULL)
971 			root = m->right;
972 		else if (m->right == NULL)
973 			root = m->left;
974 		else {
975 			/*
976 			 * Move the page's successor to the root, because
977 			 * pages are usually removed in ascending order.
978 			 */
979 			if (m->right != next)
980 				vm_page_splay(m->pindex, m->right);
981 			next->left = m->left;
982 			root = next;
983 		}
984 		object->root = root;
985 	}
986 	TAILQ_REMOVE(&object->memq, m, listq);
987 
988 	/*
989 	 * And show that the object has one fewer resident page.
990 	 */
991 	object->resident_page_count--;
992 	/*
993 	 * The vnode may now be recycled.
994 	 */
995 	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
996 		vdrop((struct vnode *)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  *	This routine may not block.
1009  *	This is a critical path routine
1010  */
1011 vm_page_t
1012 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1013 {
1014 	vm_page_t m;
1015 
1016 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1017 	if ((m = object->root) != NULL && m->pindex != pindex) {
1018 		m = vm_page_splay(pindex, m);
1019 		if ((object->root = m)->pindex != pindex)
1020 			m = NULL;
1021 	}
1022 	return (m);
1023 }
1024 
1025 /*
1026  *	vm_page_find_least:
1027  *
1028  *	Returns the page associated with the object with least pindex
1029  *	greater than or equal to the parameter pindex, or NULL.
1030  *
1031  *	The object must be locked.
1032  *	The routine may not block.
1033  */
1034 vm_page_t
1035 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1036 {
1037 	vm_page_t m;
1038 
1039 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1040 	if ((m = TAILQ_FIRST(&object->memq)) != NULL) {
1041 		if (m->pindex < pindex) {
1042 			m = vm_page_splay(pindex, object->root);
1043 			if ((object->root = m)->pindex < pindex)
1044 				m = TAILQ_NEXT(m, listq);
1045 		}
1046 	}
1047 	return (m);
1048 }
1049 
1050 /*
1051  * Returns the given page's successor (by pindex) within the object if it is
1052  * resident; if none is found, NULL is returned.
1053  *
1054  * The object must be locked.
1055  */
1056 vm_page_t
1057 vm_page_next(vm_page_t m)
1058 {
1059 	vm_page_t next;
1060 
1061 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1062 	if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1063 	    next->pindex != m->pindex + 1)
1064 		next = NULL;
1065 	return (next);
1066 }
1067 
1068 /*
1069  * Returns the given page's predecessor (by pindex) within the object if it is
1070  * resident; if none is found, NULL is returned.
1071  *
1072  * The object must be locked.
1073  */
1074 vm_page_t
1075 vm_page_prev(vm_page_t m)
1076 {
1077 	vm_page_t prev;
1078 
1079 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1080 	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1081 	    prev->pindex != m->pindex - 1)
1082 		prev = NULL;
1083 	return (prev);
1084 }
1085 
1086 /*
1087  *	vm_page_rename:
1088  *
1089  *	Move the given memory entry from its
1090  *	current object to the specified target object/offset.
1091  *
1092  *	The object must be locked.
1093  *	This routine may not block.
1094  *
1095  *	Note: swap associated with the page must be invalidated by the move.  We
1096  *	      have to do this for several reasons:  (1) we aren't freeing the
1097  *	      page, (2) we are dirtying the page, (3) the VM system is probably
1098  *	      moving the page from object A to B, and will then later move
1099  *	      the backing store from A to B and we can't have a conflict.
1100  *
1101  *	Note: we *always* dirty the page.  It is necessary both for the
1102  *	      fact that we moved it, and because we may be invalidating
1103  *	      swap.  If the page is on the cache, we have to deactivate it
1104  *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
1105  *	      on the cache.
1106  */
1107 void
1108 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1109 {
1110 
1111 	vm_page_remove(m);
1112 	vm_page_insert(m, new_object, new_pindex);
1113 	vm_page_dirty(m);
1114 }
1115 
1116 /*
1117  *	Convert all of the given object's cached pages that have a
1118  *	pindex within the given range into free pages.  If the value
1119  *	zero is given for "end", then the range's upper bound is
1120  *	infinity.  If the given object is backed by a vnode and it
1121  *	transitions from having one or more cached pages to none, the
1122  *	vnode's hold count is reduced.
1123  */
1124 void
1125 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1126 {
1127 	vm_page_t m, m_next;
1128 	boolean_t empty;
1129 
1130 	mtx_lock(&vm_page_queue_free_mtx);
1131 	if (__predict_false(object->cache == NULL)) {
1132 		mtx_unlock(&vm_page_queue_free_mtx);
1133 		return;
1134 	}
1135 	m = object->cache = vm_page_splay(start, object->cache);
1136 	if (m->pindex < start) {
1137 		if (m->right == NULL)
1138 			m = NULL;
1139 		else {
1140 			m_next = vm_page_splay(start, m->right);
1141 			m_next->left = m;
1142 			m->right = NULL;
1143 			m = object->cache = m_next;
1144 		}
1145 	}
1146 
1147 	/*
1148 	 * At this point, "m" is either (1) a reference to the page
1149 	 * with the least pindex that is greater than or equal to
1150 	 * "start" or (2) NULL.
1151 	 */
1152 	for (; m != NULL && (m->pindex < end || end == 0); m = m_next) {
1153 		/*
1154 		 * Find "m"'s successor and remove "m" from the
1155 		 * object's cache.
1156 		 */
1157 		if (m->right == NULL) {
1158 			object->cache = m->left;
1159 			m_next = NULL;
1160 		} else {
1161 			m_next = vm_page_splay(start, m->right);
1162 			m_next->left = m->left;
1163 			object->cache = m_next;
1164 		}
1165 		/* Convert "m" to a free page. */
1166 		m->object = NULL;
1167 		m->valid = 0;
1168 		/* Clear PG_CACHED and set PG_FREE. */
1169 		m->flags ^= PG_CACHED | PG_FREE;
1170 		KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
1171 		    ("vm_page_cache_free: page %p has inconsistent flags", m));
1172 		cnt.v_cache_count--;
1173 		cnt.v_free_count++;
1174 	}
1175 	empty = object->cache == NULL;
1176 	mtx_unlock(&vm_page_queue_free_mtx);
1177 	if (object->type == OBJT_VNODE && empty)
1178 		vdrop(object->handle);
1179 }
1180 
1181 /*
1182  *	Returns the cached page that is associated with the given
1183  *	object and offset.  If, however, none exists, returns NULL.
1184  *
1185  *	The free page queue must be locked.
1186  */
1187 static inline vm_page_t
1188 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1189 {
1190 	vm_page_t m;
1191 
1192 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1193 	if ((m = object->cache) != NULL && m->pindex != pindex) {
1194 		m = vm_page_splay(pindex, m);
1195 		if ((object->cache = m)->pindex != pindex)
1196 			m = NULL;
1197 	}
1198 	return (m);
1199 }
1200 
1201 /*
1202  *	Remove the given cached page from its containing object's
1203  *	collection of cached pages.
1204  *
1205  *	The free page queue must be locked.
1206  */
1207 static void
1208 vm_page_cache_remove(vm_page_t m)
1209 {
1210 	vm_object_t object;
1211 	vm_page_t root;
1212 
1213 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1214 	KASSERT((m->flags & PG_CACHED) != 0,
1215 	    ("vm_page_cache_remove: page %p is not cached", m));
1216 	object = m->object;
1217 	if (m != object->cache) {
1218 		root = vm_page_splay(m->pindex, object->cache);
1219 		KASSERT(root == m,
1220 		    ("vm_page_cache_remove: page %p is not cached in object %p",
1221 		    m, object));
1222 	}
1223 	if (m->left == NULL)
1224 		root = m->right;
1225 	else if (m->right == NULL)
1226 		root = m->left;
1227 	else {
1228 		root = vm_page_splay(m->pindex, m->left);
1229 		root->right = m->right;
1230 	}
1231 	object->cache = root;
1232 	m->object = NULL;
1233 	cnt.v_cache_count--;
1234 }
1235 
1236 /*
1237  *	Transfer all of the cached pages with offset greater than or
1238  *	equal to 'offidxstart' from the original object's cache to the
1239  *	new object's cache.  However, any cached pages with offset
1240  *	greater than or equal to the new object's size are kept in the
1241  *	original object.  Initially, the new object's cache must be
1242  *	empty.  Offset 'offidxstart' in the original object must
1243  *	correspond to offset zero in the new object.
1244  *
1245  *	The new object must be locked.
1246  */
1247 void
1248 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1249     vm_object_t new_object)
1250 {
1251 	vm_page_t m, m_next;
1252 
1253 	/*
1254 	 * Insertion into an object's collection of cached pages
1255 	 * requires the object to be locked.  In contrast, removal does
1256 	 * not.
1257 	 */
1258 	VM_OBJECT_LOCK_ASSERT(new_object, MA_OWNED);
1259 	KASSERT(new_object->cache == NULL,
1260 	    ("vm_page_cache_transfer: object %p has cached pages",
1261 	    new_object));
1262 	mtx_lock(&vm_page_queue_free_mtx);
1263 	if ((m = orig_object->cache) != NULL) {
1264 		/*
1265 		 * Transfer all of the pages with offset greater than or
1266 		 * equal to 'offidxstart' from the original object's
1267 		 * cache to the new object's cache.
1268 		 */
1269 		m = vm_page_splay(offidxstart, m);
1270 		if (m->pindex < offidxstart) {
1271 			orig_object->cache = m;
1272 			new_object->cache = m->right;
1273 			m->right = NULL;
1274 		} else {
1275 			orig_object->cache = m->left;
1276 			new_object->cache = m;
1277 			m->left = NULL;
1278 		}
1279 		while ((m = new_object->cache) != NULL) {
1280 			if ((m->pindex - offidxstart) >= new_object->size) {
1281 				/*
1282 				 * Return all of the cached pages with
1283 				 * offset greater than or equal to the
1284 				 * new object's size to the original
1285 				 * object's cache.
1286 				 */
1287 				new_object->cache = m->left;
1288 				m->left = orig_object->cache;
1289 				orig_object->cache = m;
1290 				break;
1291 			}
1292 			m_next = vm_page_splay(m->pindex, m->right);
1293 			/* Update the page's object and offset. */
1294 			m->object = new_object;
1295 			m->pindex -= offidxstart;
1296 			if (m_next == NULL)
1297 				break;
1298 			m->right = NULL;
1299 			m_next->left = m;
1300 			new_object->cache = m_next;
1301 		}
1302 		KASSERT(new_object->cache == NULL ||
1303 		    new_object->type == OBJT_SWAP,
1304 		    ("vm_page_cache_transfer: object %p's type is incompatible"
1305 		    " with cached pages", new_object));
1306 	}
1307 	mtx_unlock(&vm_page_queue_free_mtx);
1308 }
1309 
1310 /*
1311  *	Returns TRUE if a cached page is associated with the given object and
1312  *	offset, and FALSE otherwise.
1313  *
1314  *	The object must be locked.
1315  */
1316 boolean_t
1317 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1318 {
1319 	vm_page_t m;
1320 
1321 	/*
1322 	 * Insertion into an object's collection of cached pages requires the
1323 	 * object to be locked.  Therefore, if the object is locked and the
1324 	 * object's collection is empty, there is no need to acquire the free
1325 	 * page queues lock in order to prove that the specified page doesn't
1326 	 * exist.
1327 	 */
1328 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1329 	if (__predict_true(object->cache == NULL))
1330 		return (FALSE);
1331 	mtx_lock(&vm_page_queue_free_mtx);
1332 	m = vm_page_cache_lookup(object, pindex);
1333 	mtx_unlock(&vm_page_queue_free_mtx);
1334 	return (m != NULL);
1335 }
1336 
1337 /*
1338  *	vm_page_alloc:
1339  *
1340  *	Allocate and return a page that is associated with the specified
1341  *	object and offset pair.  By default, this page has the flag VPO_BUSY
1342  *	set.
1343  *
1344  *	The caller must always specify an allocation class.
1345  *
1346  *	allocation classes:
1347  *	VM_ALLOC_NORMAL		normal process request
1348  *	VM_ALLOC_SYSTEM		system *really* needs a page
1349  *	VM_ALLOC_INTERRUPT	interrupt time request
1350  *
1351  *	optional allocation flags:
1352  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1353  *				intends to allocate
1354  *	VM_ALLOC_IFCACHED	return page only if it is cached
1355  *	VM_ALLOC_IFNOTCACHED	return NULL, do not reactivate if the page
1356  *				is cached
1357  *	VM_ALLOC_NOBUSY		do not set the flag VPO_BUSY on the page
1358  *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1359  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1360  *				should not have the flag VPO_BUSY set
1361  *	VM_ALLOC_WIRED		wire the allocated page
1362  *	VM_ALLOC_ZERO		prefer a zeroed page
1363  *
1364  *	This routine may not sleep.
1365  */
1366 vm_page_t
1367 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1368 {
1369 	struct vnode *vp = NULL;
1370 	vm_object_t m_object;
1371 	vm_page_t m;
1372 	int flags, req_class;
1373 
1374 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0),
1375 	    ("vm_page_alloc: inconsistent object/req"));
1376 	if (object != NULL)
1377 		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1378 
1379 	req_class = req & VM_ALLOC_CLASS_MASK;
1380 
1381 	/*
1382 	 * The page daemon is allowed to dig deeper into the free page list.
1383 	 */
1384 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1385 		req_class = VM_ALLOC_SYSTEM;
1386 
1387 	mtx_lock(&vm_page_queue_free_mtx);
1388 	if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1389 	    (req_class == VM_ALLOC_SYSTEM &&
1390 	    cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1391 	    (req_class == VM_ALLOC_INTERRUPT &&
1392 	    cnt.v_free_count + cnt.v_cache_count > 0)) {
1393 		/*
1394 		 * Allocate from the free queue if the number of free pages
1395 		 * exceeds the minimum for the request class.
1396 		 */
1397 		if (object != NULL &&
1398 		    (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1399 			if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1400 				mtx_unlock(&vm_page_queue_free_mtx);
1401 				return (NULL);
1402 			}
1403 			if (vm_phys_unfree_page(m))
1404 				vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1405 #if VM_NRESERVLEVEL > 0
1406 			else if (!vm_reserv_reactivate_page(m))
1407 #else
1408 			else
1409 #endif
1410 				panic("vm_page_alloc: cache page %p is missing"
1411 				    " from the free queue", m);
1412 		} else if ((req & VM_ALLOC_IFCACHED) != 0) {
1413 			mtx_unlock(&vm_page_queue_free_mtx);
1414 			return (NULL);
1415 #if VM_NRESERVLEVEL > 0
1416 		} else if (object == NULL || object->type == OBJT_DEVICE ||
1417 		    object->type == OBJT_SG ||
1418 		    (object->flags & OBJ_COLORED) == 0 ||
1419 		    (m = vm_reserv_alloc_page(object, pindex)) == NULL) {
1420 #else
1421 		} else {
1422 #endif
1423 			m = vm_phys_alloc_pages(object != NULL ?
1424 			    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1425 #if VM_NRESERVLEVEL > 0
1426 			if (m == NULL && vm_reserv_reclaim_inactive()) {
1427 				m = vm_phys_alloc_pages(object != NULL ?
1428 				    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1429 				    0);
1430 			}
1431 #endif
1432 		}
1433 	} else {
1434 		/*
1435 		 * Not allocatable, give up.
1436 		 */
1437 		mtx_unlock(&vm_page_queue_free_mtx);
1438 		atomic_add_int(&vm_pageout_deficit,
1439 		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1440 		pagedaemon_wakeup();
1441 		return (NULL);
1442 	}
1443 
1444 	/*
1445 	 *  At this point we had better have found a good page.
1446 	 */
1447 	KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1448 	KASSERT(m->queue == PQ_NONE,
1449 	    ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1450 	KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1451 	KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1452 	KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1453 	KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1454 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1455 	    ("vm_page_alloc: page %p has unexpected memattr %d", m,
1456 	    pmap_page_get_memattr(m)));
1457 	if ((m->flags & PG_CACHED) != 0) {
1458 		KASSERT((m->flags & PG_ZERO) == 0,
1459 		    ("vm_page_alloc: cached page %p is PG_ZERO", m));
1460 		KASSERT(m->valid != 0,
1461 		    ("vm_page_alloc: cached page %p is invalid", m));
1462 		if (m->object == object && m->pindex == pindex)
1463 	  		cnt.v_reactivated++;
1464 		else
1465 			m->valid = 0;
1466 		m_object = m->object;
1467 		vm_page_cache_remove(m);
1468 		if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
1469 			vp = m_object->handle;
1470 	} else {
1471 		KASSERT(VM_PAGE_IS_FREE(m),
1472 		    ("vm_page_alloc: page %p is not free", m));
1473 		KASSERT(m->valid == 0,
1474 		    ("vm_page_alloc: free page %p is valid", m));
1475 		cnt.v_free_count--;
1476 	}
1477 
1478 	/*
1479 	 * Only the PG_ZERO flag is inherited.  The PG_CACHED or PG_FREE flag
1480 	 * must be cleared before the free page queues lock is released.
1481 	 */
1482 	flags = 0;
1483 	if (req & VM_ALLOC_NODUMP)
1484 		flags |= PG_NODUMP;
1485 	if (m->flags & PG_ZERO) {
1486 		vm_page_zero_count--;
1487 		if (req & VM_ALLOC_ZERO)
1488 			flags = PG_ZERO;
1489 	}
1490 	m->flags = flags;
1491 	mtx_unlock(&vm_page_queue_free_mtx);
1492 	m->aflags = 0;
1493 	if (object == NULL || object->type == OBJT_PHYS)
1494 		m->oflags = VPO_UNMANAGED;
1495 	else
1496 		m->oflags = 0;
1497 	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ)) == 0)
1498 		m->oflags |= VPO_BUSY;
1499 	if (req & VM_ALLOC_WIRED) {
1500 		/*
1501 		 * The page lock is not required for wiring a page until that
1502 		 * page is inserted into the object.
1503 		 */
1504 		atomic_add_int(&cnt.v_wire_count, 1);
1505 		m->wire_count = 1;
1506 	}
1507 	m->act_count = 0;
1508 
1509 	if (object != NULL) {
1510 		/* Ignore device objects; the pager sets "memattr" for them. */
1511 		if (object->memattr != VM_MEMATTR_DEFAULT &&
1512 		    object->type != OBJT_DEVICE && object->type != OBJT_SG)
1513 			pmap_page_set_memattr(m, object->memattr);
1514 		vm_page_insert(m, object, pindex);
1515 	} else
1516 		m->pindex = pindex;
1517 
1518 	/*
1519 	 * The following call to vdrop() must come after the above call
1520 	 * to vm_page_insert() in case both affect the same object and
1521 	 * vnode.  Otherwise, the affected vnode's hold count could
1522 	 * temporarily become zero.
1523 	 */
1524 	if (vp != NULL)
1525 		vdrop(vp);
1526 
1527 	/*
1528 	 * Don't wakeup too often - wakeup the pageout daemon when
1529 	 * we would be nearly out of memory.
1530 	 */
1531 	if (vm_paging_needed())
1532 		pagedaemon_wakeup();
1533 
1534 	return (m);
1535 }
1536 
1537 /*
1538  *	vm_page_alloc_contig:
1539  *
1540  *	Allocate a contiguous set of physical pages of the given size "npages"
1541  *	from the free lists.  All of the physical pages must be at or above
1542  *	the given physical address "low" and below the given physical address
1543  *	"high".  The given value "alignment" determines the alignment of the
1544  *	first physical page in the set.  If the given value "boundary" is
1545  *	non-zero, then the set of physical pages cannot cross any physical
1546  *	address boundary that is a multiple of that value.  Both "alignment"
1547  *	and "boundary" must be a power of two.
1548  *
1549  *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1550  *	then the memory attribute setting for the physical pages is configured
1551  *	to the object's memory attribute setting.  Otherwise, the memory
1552  *	attribute setting for the physical pages is configured to "memattr",
1553  *	overriding the object's memory attribute setting.  However, if the
1554  *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1555  *	memory attribute setting for the physical pages cannot be configured
1556  *	to VM_MEMATTR_DEFAULT.
1557  *
1558  *	The caller must always specify an allocation class.
1559  *
1560  *	allocation classes:
1561  *	VM_ALLOC_NORMAL		normal process request
1562  *	VM_ALLOC_SYSTEM		system *really* needs a page
1563  *	VM_ALLOC_INTERRUPT	interrupt time request
1564  *
1565  *	optional allocation flags:
1566  *	VM_ALLOC_NOBUSY		do not set the flag VPO_BUSY on the page
1567  *	VM_ALLOC_NOOBJ		page is not associated with an object and
1568  *				should not have the flag VPO_BUSY set
1569  *	VM_ALLOC_WIRED		wire the allocated page
1570  *	VM_ALLOC_ZERO		prefer a zeroed page
1571  *
1572  *	This routine may not sleep.
1573  */
1574 vm_page_t
1575 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1576     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1577     vm_paddr_t boundary, vm_memattr_t memattr)
1578 {
1579 	struct vnode *drop;
1580 	vm_page_t deferred_vdrop_list, m, m_ret;
1581 	u_int flags, oflags;
1582 	int req_class;
1583 
1584 	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0),
1585 	    ("vm_page_alloc_contig: inconsistent object/req"));
1586 	if (object != NULL) {
1587 		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1588 		KASSERT(object->type == OBJT_PHYS,
1589 		    ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1590 		    object));
1591 	}
1592 	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1593 	req_class = req & VM_ALLOC_CLASS_MASK;
1594 
1595 	/*
1596 	 * The page daemon is allowed to dig deeper into the free page list.
1597 	 */
1598 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1599 		req_class = VM_ALLOC_SYSTEM;
1600 
1601 	deferred_vdrop_list = NULL;
1602 	mtx_lock(&vm_page_queue_free_mtx);
1603 	if (cnt.v_free_count + cnt.v_cache_count >= npages +
1604 	    cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1605 	    cnt.v_free_count + cnt.v_cache_count >= npages +
1606 	    cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1607 	    cnt.v_free_count + cnt.v_cache_count >= npages)) {
1608 #if VM_NRESERVLEVEL > 0
1609 retry:
1610 		if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1611 		    (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1612 		    low, high, alignment, boundary)) == NULL)
1613 #endif
1614 			m_ret = vm_phys_alloc_contig(npages, low, high,
1615 			    alignment, boundary);
1616 	} else {
1617 		mtx_unlock(&vm_page_queue_free_mtx);
1618 		atomic_add_int(&vm_pageout_deficit, npages);
1619 		pagedaemon_wakeup();
1620 		return (NULL);
1621 	}
1622 	if (m_ret != NULL)
1623 		for (m = m_ret; m < &m_ret[npages]; m++) {
1624 			drop = vm_page_alloc_init(m);
1625 			if (drop != NULL) {
1626 				/*
1627 				 * Enqueue the vnode for deferred vdrop().
1628 				 *
1629 				 * Once the pages are removed from the free
1630 				 * page list, "pageq" can be safely abused to
1631 				 * construct a short-lived list of vnodes.
1632 				 */
1633 				m->pageq.tqe_prev = (void *)drop;
1634 				m->pageq.tqe_next = deferred_vdrop_list;
1635 				deferred_vdrop_list = m;
1636 			}
1637 		}
1638 	else {
1639 #if VM_NRESERVLEVEL > 0
1640 		if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1641 		    boundary))
1642 			goto retry;
1643 #endif
1644 	}
1645 	mtx_unlock(&vm_page_queue_free_mtx);
1646 	if (m_ret == NULL)
1647 		return (NULL);
1648 
1649 	/*
1650 	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
1651 	 */
1652 	flags = 0;
1653 	if ((req & VM_ALLOC_ZERO) != 0)
1654 		flags = PG_ZERO;
1655 	if ((req & VM_ALLOC_NODUMP) != 0)
1656 		flags |= PG_NODUMP;
1657 	if ((req & VM_ALLOC_WIRED) != 0)
1658 		atomic_add_int(&cnt.v_wire_count, npages);
1659 	oflags = VPO_UNMANAGED;
1660 	if (object != NULL) {
1661 		if ((req & VM_ALLOC_NOBUSY) == 0)
1662 			oflags |= VPO_BUSY;
1663 		if (object->memattr != VM_MEMATTR_DEFAULT &&
1664 		    memattr == VM_MEMATTR_DEFAULT)
1665 			memattr = object->memattr;
1666 	}
1667 	for (m = m_ret; m < &m_ret[npages]; m++) {
1668 		m->aflags = 0;
1669 		m->flags = (m->flags | PG_NODUMP) & flags;
1670 		if ((req & VM_ALLOC_WIRED) != 0)
1671 			m->wire_count = 1;
1672 		/* Unmanaged pages don't use "act_count". */
1673 		m->oflags = oflags;
1674 		if (memattr != VM_MEMATTR_DEFAULT)
1675 			pmap_page_set_memattr(m, memattr);
1676 		if (object != NULL)
1677 			vm_page_insert(m, object, pindex);
1678 		else
1679 			m->pindex = pindex;
1680 		pindex++;
1681 	}
1682 	while (deferred_vdrop_list != NULL) {
1683 		vdrop((struct vnode *)deferred_vdrop_list->pageq.tqe_prev);
1684 		deferred_vdrop_list = deferred_vdrop_list->pageq.tqe_next;
1685 	}
1686 	if (vm_paging_needed())
1687 		pagedaemon_wakeup();
1688 	return (m_ret);
1689 }
1690 
1691 /*
1692  * Initialize a page that has been freshly dequeued from a freelist.
1693  * The caller has to drop the vnode returned, if it is not NULL.
1694  *
1695  * This function may only be used to initialize unmanaged pages.
1696  *
1697  * To be called with vm_page_queue_free_mtx held.
1698  */
1699 static struct vnode *
1700 vm_page_alloc_init(vm_page_t m)
1701 {
1702 	struct vnode *drop;
1703 	vm_object_t m_object;
1704 
1705 	KASSERT(m->queue == PQ_NONE,
1706 	    ("vm_page_alloc_init: page %p has unexpected queue %d",
1707 	    m, m->queue));
1708 	KASSERT(m->wire_count == 0,
1709 	    ("vm_page_alloc_init: page %p is wired", m));
1710 	KASSERT(m->hold_count == 0,
1711 	    ("vm_page_alloc_init: page %p is held", m));
1712 	KASSERT(m->busy == 0,
1713 	    ("vm_page_alloc_init: page %p is busy", m));
1714 	KASSERT(m->dirty == 0,
1715 	    ("vm_page_alloc_init: page %p is dirty", m));
1716 	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1717 	    ("vm_page_alloc_init: page %p has unexpected memattr %d",
1718 	    m, pmap_page_get_memattr(m)));
1719 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1720 	drop = NULL;
1721 	if ((m->flags & PG_CACHED) != 0) {
1722 		KASSERT((m->flags & PG_ZERO) == 0,
1723 		    ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1724 		m->valid = 0;
1725 		m_object = m->object;
1726 		vm_page_cache_remove(m);
1727 		if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
1728 			drop = m_object->handle;
1729 	} else {
1730 		KASSERT(VM_PAGE_IS_FREE(m),
1731 		    ("vm_page_alloc_init: page %p is not free", m));
1732 		KASSERT(m->valid == 0,
1733 		    ("vm_page_alloc_init: free page %p is valid", m));
1734 		cnt.v_free_count--;
1735 		if ((m->flags & PG_ZERO) != 0)
1736 			vm_page_zero_count--;
1737 	}
1738 	/* Don't clear the PG_ZERO flag; we'll need it later. */
1739 	m->flags &= PG_ZERO;
1740 	return (drop);
1741 }
1742 
1743 /*
1744  * 	vm_page_alloc_freelist:
1745  *
1746  *	Allocate a physical page from the specified free page list.
1747  *
1748  *	The caller must always specify an allocation class.
1749  *
1750  *	allocation classes:
1751  *	VM_ALLOC_NORMAL		normal process request
1752  *	VM_ALLOC_SYSTEM		system *really* needs a page
1753  *	VM_ALLOC_INTERRUPT	interrupt time request
1754  *
1755  *	optional allocation flags:
1756  *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1757  *				intends to allocate
1758  *	VM_ALLOC_WIRED		wire the allocated page
1759  *	VM_ALLOC_ZERO		prefer a zeroed page
1760  *
1761  *	This routine may not sleep.
1762  */
1763 vm_page_t
1764 vm_page_alloc_freelist(int flind, int req)
1765 {
1766 	struct vnode *drop;
1767 	vm_page_t m;
1768 	u_int flags;
1769 	int req_class;
1770 
1771 	req_class = req & VM_ALLOC_CLASS_MASK;
1772 
1773 	/*
1774 	 * The page daemon is allowed to dig deeper into the free page list.
1775 	 */
1776 	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1777 		req_class = VM_ALLOC_SYSTEM;
1778 
1779 	/*
1780 	 * Do not allocate reserved pages unless the req has asked for it.
1781 	 */
1782 	mtx_lock(&vm_page_queue_free_mtx);
1783 	if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1784 	    (req_class == VM_ALLOC_SYSTEM &&
1785 	    cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1786 	    (req_class == VM_ALLOC_INTERRUPT &&
1787 	    cnt.v_free_count + cnt.v_cache_count > 0))
1788 		m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1789 	else {
1790 		mtx_unlock(&vm_page_queue_free_mtx);
1791 		atomic_add_int(&vm_pageout_deficit,
1792 		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1793 		pagedaemon_wakeup();
1794 		return (NULL);
1795 	}
1796 	if (m == NULL) {
1797 		mtx_unlock(&vm_page_queue_free_mtx);
1798 		return (NULL);
1799 	}
1800 	drop = vm_page_alloc_init(m);
1801 	mtx_unlock(&vm_page_queue_free_mtx);
1802 
1803 	/*
1804 	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1805 	 */
1806 	m->aflags = 0;
1807 	flags = 0;
1808 	if ((req & VM_ALLOC_ZERO) != 0)
1809 		flags = PG_ZERO;
1810 	m->flags &= flags;
1811 	if ((req & VM_ALLOC_WIRED) != 0) {
1812 		/*
1813 		 * The page lock is not required for wiring a page that does
1814 		 * not belong to an object.
1815 		 */
1816 		atomic_add_int(&cnt.v_wire_count, 1);
1817 		m->wire_count = 1;
1818 	}
1819 	/* Unmanaged pages don't use "act_count". */
1820 	m->oflags = VPO_UNMANAGED;
1821 	if (drop != NULL)
1822 		vdrop(drop);
1823 	if (vm_paging_needed())
1824 		pagedaemon_wakeup();
1825 	return (m);
1826 }
1827 
1828 /*
1829  *	vm_wait:	(also see VM_WAIT macro)
1830  *
1831  *	Block until free pages are available for allocation
1832  *	- Called in various places before memory allocations.
1833  */
1834 void
1835 vm_wait(void)
1836 {
1837 
1838 	mtx_lock(&vm_page_queue_free_mtx);
1839 	if (curproc == pageproc) {
1840 		vm_pageout_pages_needed = 1;
1841 		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1842 		    PDROP | PSWP, "VMWait", 0);
1843 	} else {
1844 		if (!vm_pages_needed) {
1845 			vm_pages_needed = 1;
1846 			wakeup(&vm_pages_needed);
1847 		}
1848 		msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1849 		    "vmwait", 0);
1850 	}
1851 }
1852 
1853 /*
1854  *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
1855  *
1856  *	Block until free pages are available for allocation
1857  *	- Called only in vm_fault so that processes page faulting
1858  *	  can be easily tracked.
1859  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1860  *	  processes will be able to grab memory first.  Do not change
1861  *	  this balance without careful testing first.
1862  */
1863 void
1864 vm_waitpfault(void)
1865 {
1866 
1867 	mtx_lock(&vm_page_queue_free_mtx);
1868 	if (!vm_pages_needed) {
1869 		vm_pages_needed = 1;
1870 		wakeup(&vm_pages_needed);
1871 	}
1872 	msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1873 	    "pfault", 0);
1874 }
1875 
1876 /*
1877  *	vm_page_requeue:
1878  *
1879  *	Move the given page to the tail of its present page queue.
1880  *
1881  *	The page queues must be locked.
1882  */
1883 void
1884 vm_page_requeue(vm_page_t m)
1885 {
1886 	struct vpgqueues *vpq;
1887 	int queue;
1888 
1889 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1890 	queue = m->queue;
1891 	KASSERT(queue != PQ_NONE,
1892 	    ("vm_page_requeue: page %p is not queued", m));
1893 	vpq = &vm_page_queues[queue];
1894 	TAILQ_REMOVE(&vpq->pl, m, pageq);
1895 	TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1896 }
1897 
1898 /*
1899  *	vm_page_queue_remove:
1900  *
1901  *	Remove the given page from the specified queue.
1902  *
1903  *	The page and page queues must be locked.
1904  */
1905 static __inline void
1906 vm_page_queue_remove(int queue, vm_page_t m)
1907 {
1908 	struct vpgqueues *pq;
1909 
1910 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1911 	vm_page_lock_assert(m, MA_OWNED);
1912 	pq = &vm_page_queues[queue];
1913 	TAILQ_REMOVE(&pq->pl, m, pageq);
1914 	(*pq->cnt)--;
1915 }
1916 
1917 /*
1918  *	vm_pageq_remove:
1919  *
1920  *	Remove a page from its queue.
1921  *
1922  *	The given page must be locked.
1923  *	This routine may not block.
1924  */
1925 void
1926 vm_pageq_remove(vm_page_t m)
1927 {
1928 	int queue;
1929 
1930 	vm_page_lock_assert(m, MA_OWNED);
1931 	if ((queue = m->queue) != PQ_NONE) {
1932 		vm_page_lock_queues();
1933 		m->queue = PQ_NONE;
1934 		vm_page_queue_remove(queue, m);
1935 		vm_page_unlock_queues();
1936 	}
1937 }
1938 
1939 /*
1940  *	vm_page_enqueue:
1941  *
1942  *	Add the given page to the specified queue.
1943  *
1944  *	The page queues must be locked.
1945  */
1946 static void
1947 vm_page_enqueue(int queue, vm_page_t m)
1948 {
1949 	struct vpgqueues *vpq;
1950 
1951 	vpq = &vm_page_queues[queue];
1952 	m->queue = queue;
1953 	TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1954 	++*vpq->cnt;
1955 }
1956 
1957 /*
1958  *	vm_page_activate:
1959  *
1960  *	Put the specified page on the active list (if appropriate).
1961  *	Ensure that act_count is at least ACT_INIT but do not otherwise
1962  *	mess with it.
1963  *
1964  *	The page must be locked.
1965  *	This routine may not block.
1966  */
1967 void
1968 vm_page_activate(vm_page_t m)
1969 {
1970 	int queue;
1971 
1972 	vm_page_lock_assert(m, MA_OWNED);
1973 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1974 	if ((queue = m->queue) != PQ_ACTIVE) {
1975 		if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
1976 			if (m->act_count < ACT_INIT)
1977 				m->act_count = ACT_INIT;
1978 			vm_page_lock_queues();
1979 			if (queue != PQ_NONE)
1980 				vm_page_queue_remove(queue, m);
1981 			vm_page_enqueue(PQ_ACTIVE, m);
1982 			vm_page_unlock_queues();
1983 		} else
1984 			KASSERT(queue == PQ_NONE,
1985 			    ("vm_page_activate: wired page %p is queued", m));
1986 	} else {
1987 		if (m->act_count < ACT_INIT)
1988 			m->act_count = ACT_INIT;
1989 	}
1990 }
1991 
1992 /*
1993  *	vm_page_free_wakeup:
1994  *
1995  *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
1996  *	routine is called when a page has been added to the cache or free
1997  *	queues.
1998  *
1999  *	The page queues must be locked.
2000  *	This routine may not block.
2001  */
2002 static inline void
2003 vm_page_free_wakeup(void)
2004 {
2005 
2006 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2007 	/*
2008 	 * if pageout daemon needs pages, then tell it that there are
2009 	 * some free.
2010 	 */
2011 	if (vm_pageout_pages_needed &&
2012 	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
2013 		wakeup(&vm_pageout_pages_needed);
2014 		vm_pageout_pages_needed = 0;
2015 	}
2016 	/*
2017 	 * wakeup processes that are waiting on memory if we hit a
2018 	 * high water mark. And wakeup scheduler process if we have
2019 	 * lots of memory. this process will swapin processes.
2020 	 */
2021 	if (vm_pages_needed && !vm_page_count_min()) {
2022 		vm_pages_needed = 0;
2023 		wakeup(&cnt.v_free_count);
2024 	}
2025 }
2026 
2027 /*
2028  *	vm_page_free_toq:
2029  *
2030  *	Returns the given page to the free list,
2031  *	disassociating it with any VM object.
2032  *
2033  *	Object and page must be locked prior to entry.
2034  *	This routine may not block.
2035  */
2036 
2037 void
2038 vm_page_free_toq(vm_page_t m)
2039 {
2040 
2041 	if ((m->oflags & VPO_UNMANAGED) == 0) {
2042 		vm_page_lock_assert(m, MA_OWNED);
2043 		KASSERT(!pmap_page_is_mapped(m),
2044 		    ("vm_page_free_toq: freeing mapped page %p", m));
2045 	}
2046 	PCPU_INC(cnt.v_tfree);
2047 
2048 	if (VM_PAGE_IS_FREE(m))
2049 		panic("vm_page_free: freeing free page %p", m);
2050 	else if (m->busy != 0)
2051 		panic("vm_page_free: freeing busy page %p", m);
2052 
2053 	/*
2054 	 * unqueue, then remove page.  Note that we cannot destroy
2055 	 * the page here because we do not want to call the pager's
2056 	 * callback routine until after we've put the page on the
2057 	 * appropriate free queue.
2058 	 */
2059 	if ((m->oflags & VPO_UNMANAGED) == 0)
2060 		vm_pageq_remove(m);
2061 	vm_page_remove(m);
2062 
2063 	/*
2064 	 * If fictitious remove object association and
2065 	 * return, otherwise delay object association removal.
2066 	 */
2067 	if ((m->flags & PG_FICTITIOUS) != 0) {
2068 		return;
2069 	}
2070 
2071 	m->valid = 0;
2072 	vm_page_undirty(m);
2073 
2074 	if (m->wire_count != 0)
2075 		panic("vm_page_free: freeing wired page %p", m);
2076 	if (m->hold_count != 0) {
2077 		m->flags &= ~PG_ZERO;
2078 		vm_page_lock_queues();
2079 		vm_page_enqueue(PQ_HOLD, m);
2080 		vm_page_unlock_queues();
2081 	} else {
2082 		/*
2083 		 * Restore the default memory attribute to the page.
2084 		 */
2085 		if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2086 			pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2087 
2088 		/*
2089 		 * Insert the page into the physical memory allocator's
2090 		 * cache/free page queues.
2091 		 */
2092 		mtx_lock(&vm_page_queue_free_mtx);
2093 		m->flags |= PG_FREE;
2094 		cnt.v_free_count++;
2095 #if VM_NRESERVLEVEL > 0
2096 		if (!vm_reserv_free_page(m))
2097 #else
2098 		if (TRUE)
2099 #endif
2100 			vm_phys_free_pages(m, 0);
2101 		if ((m->flags & PG_ZERO) != 0)
2102 			++vm_page_zero_count;
2103 		else
2104 			vm_page_zero_idle_wakeup();
2105 		vm_page_free_wakeup();
2106 		mtx_unlock(&vm_page_queue_free_mtx);
2107 	}
2108 }
2109 
2110 /*
2111  *	vm_page_wire:
2112  *
2113  *	Mark this page as wired down by yet
2114  *	another map, removing it from paging queues
2115  *	as necessary.
2116  *
2117  *	If the page is fictitious, then its wire count must remain one.
2118  *
2119  *	The page must be locked.
2120  *	This routine may not block.
2121  */
2122 void
2123 vm_page_wire(vm_page_t m)
2124 {
2125 
2126 	/*
2127 	 * Only bump the wire statistics if the page is not already wired,
2128 	 * and only unqueue the page if it is on some queue (if it is unmanaged
2129 	 * it is already off the queues).
2130 	 */
2131 	vm_page_lock_assert(m, MA_OWNED);
2132 	if ((m->flags & PG_FICTITIOUS) != 0) {
2133 		KASSERT(m->wire_count == 1,
2134 		    ("vm_page_wire: fictitious page %p's wire count isn't one",
2135 		    m));
2136 		return;
2137 	}
2138 	if (m->wire_count == 0) {
2139 		if ((m->oflags & VPO_UNMANAGED) == 0)
2140 			vm_pageq_remove(m);
2141 		atomic_add_int(&cnt.v_wire_count, 1);
2142 	}
2143 	m->wire_count++;
2144 	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2145 }
2146 
2147 /*
2148  * vm_page_unwire:
2149  *
2150  * Release one wiring of the specified page, potentially enabling it to be
2151  * paged again.  If paging is enabled, then the value of the parameter
2152  * "activate" determines to which queue the page is added.  If "activate" is
2153  * non-zero, then the page is added to the active queue.  Otherwise, it is
2154  * added to the inactive queue.
2155  *
2156  * However, unless the page belongs to an object, it is not enqueued because
2157  * it cannot be paged out.
2158  *
2159  * If a page is fictitious, then its wire count must alway be one.
2160  *
2161  * A managed page must be locked.
2162  */
2163 void
2164 vm_page_unwire(vm_page_t m, int activate)
2165 {
2166 
2167 	if ((m->oflags & VPO_UNMANAGED) == 0)
2168 		vm_page_lock_assert(m, MA_OWNED);
2169 	if ((m->flags & PG_FICTITIOUS) != 0) {
2170 		KASSERT(m->wire_count == 1,
2171 	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2172 		return;
2173 	}
2174 	if (m->wire_count > 0) {
2175 		m->wire_count--;
2176 		if (m->wire_count == 0) {
2177 			atomic_subtract_int(&cnt.v_wire_count, 1);
2178 			if ((m->oflags & VPO_UNMANAGED) != 0 ||
2179 			    m->object == NULL)
2180 				return;
2181 			if (!activate)
2182 				m->flags &= ~PG_WINATCFLS;
2183 			vm_page_lock_queues();
2184 			vm_page_enqueue(activate ? PQ_ACTIVE : PQ_INACTIVE, m);
2185 			vm_page_unlock_queues();
2186 		}
2187 	} else
2188 		panic("vm_page_unwire: page %p's wire count is zero", m);
2189 }
2190 
2191 /*
2192  * Move the specified page to the inactive queue.
2193  *
2194  * Many pages placed on the inactive queue should actually go
2195  * into the cache, but it is difficult to figure out which.  What
2196  * we do instead, if the inactive target is well met, is to put
2197  * clean pages at the head of the inactive queue instead of the tail.
2198  * This will cause them to be moved to the cache more quickly and
2199  * if not actively re-referenced, reclaimed more quickly.  If we just
2200  * stick these pages at the end of the inactive queue, heavy filesystem
2201  * meta-data accesses can cause an unnecessary paging load on memory bound
2202  * processes.  This optimization causes one-time-use metadata to be
2203  * reused more quickly.
2204  *
2205  * Normally athead is 0 resulting in LRU operation.  athead is set
2206  * to 1 if we want this page to be 'as if it were placed in the cache',
2207  * except without unmapping it from the process address space.
2208  *
2209  * This routine may not block.
2210  */
2211 static inline void
2212 _vm_page_deactivate(vm_page_t m, int athead)
2213 {
2214 	int queue;
2215 
2216 	vm_page_lock_assert(m, MA_OWNED);
2217 
2218 	/*
2219 	 * Ignore if already inactive.
2220 	 */
2221 	if ((queue = m->queue) == PQ_INACTIVE)
2222 		return;
2223 	if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2224 		m->flags &= ~PG_WINATCFLS;
2225 		vm_page_lock_queues();
2226 		if (queue != PQ_NONE)
2227 			vm_page_queue_remove(queue, m);
2228 		if (athead)
2229 			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m,
2230 			    pageq);
2231 		else
2232 			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m,
2233 			    pageq);
2234 		m->queue = PQ_INACTIVE;
2235 		cnt.v_inactive_count++;
2236 		vm_page_unlock_queues();
2237 	}
2238 }
2239 
2240 /*
2241  * Move the specified page to the inactive queue.
2242  *
2243  * The page must be locked.
2244  */
2245 void
2246 vm_page_deactivate(vm_page_t m)
2247 {
2248 
2249 	_vm_page_deactivate(m, 0);
2250 }
2251 
2252 /*
2253  * vm_page_try_to_cache:
2254  *
2255  * Returns 0 on failure, 1 on success
2256  */
2257 int
2258 vm_page_try_to_cache(vm_page_t m)
2259 {
2260 
2261 	vm_page_lock_assert(m, MA_OWNED);
2262 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2263 	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2264 	    (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2265 		return (0);
2266 	pmap_remove_all(m);
2267 	if (m->dirty)
2268 		return (0);
2269 	vm_page_cache(m);
2270 	return (1);
2271 }
2272 
2273 /*
2274  * vm_page_try_to_free()
2275  *
2276  *	Attempt to free the page.  If we cannot free it, we do nothing.
2277  *	1 is returned on success, 0 on failure.
2278  */
2279 int
2280 vm_page_try_to_free(vm_page_t m)
2281 {
2282 
2283 	vm_page_lock_assert(m, MA_OWNED);
2284 	if (m->object != NULL)
2285 		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2286 	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2287 	    (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2288 		return (0);
2289 	pmap_remove_all(m);
2290 	if (m->dirty)
2291 		return (0);
2292 	vm_page_free(m);
2293 	return (1);
2294 }
2295 
2296 /*
2297  * vm_page_cache
2298  *
2299  * Put the specified page onto the page cache queue (if appropriate).
2300  *
2301  * This routine may not block.
2302  */
2303 void
2304 vm_page_cache(vm_page_t m)
2305 {
2306 	vm_object_t object;
2307 	vm_page_t next, prev, root;
2308 
2309 	vm_page_lock_assert(m, MA_OWNED);
2310 	object = m->object;
2311 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2312 	if ((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) || m->busy ||
2313 	    m->hold_count || m->wire_count)
2314 		panic("vm_page_cache: attempting to cache busy page");
2315 	pmap_remove_all(m);
2316 	if (m->dirty != 0)
2317 		panic("vm_page_cache: page %p is dirty", m);
2318 	if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2319 	    (object->type == OBJT_SWAP &&
2320 	    !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2321 		/*
2322 		 * Hypothesis: A cache-elgible page belonging to a
2323 		 * default object or swap object but without a backing
2324 		 * store must be zero filled.
2325 		 */
2326 		vm_page_free(m);
2327 		return;
2328 	}
2329 	KASSERT((m->flags & PG_CACHED) == 0,
2330 	    ("vm_page_cache: page %p is already cached", m));
2331 	PCPU_INC(cnt.v_tcached);
2332 
2333 	/*
2334 	 * Remove the page from the paging queues.
2335 	 */
2336 	vm_pageq_remove(m);
2337 
2338 	/*
2339 	 * Remove the page from the object's collection of resident
2340 	 * pages.
2341 	 */
2342 	if ((next = TAILQ_NEXT(m, listq)) != NULL && next->left == m) {
2343 		/*
2344 		 * Since the page's successor in the list is also its parent
2345 		 * in the tree, its right subtree must be empty.
2346 		 */
2347 		next->left = m->left;
2348 		KASSERT(m->right == NULL,
2349 		    ("vm_page_cache: page %p has right child", m));
2350 	} else if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
2351 	    prev->right == m) {
2352 		/*
2353 		 * Since the page's predecessor in the list is also its parent
2354 		 * in the tree, its left subtree must be empty.
2355 		 */
2356 		KASSERT(m->left == NULL,
2357 		    ("vm_page_cache: page %p has left child", m));
2358 		prev->right = m->right;
2359 	} else {
2360 		if (m != object->root)
2361 			vm_page_splay(m->pindex, object->root);
2362 		if (m->left == NULL)
2363 			root = m->right;
2364 		else if (m->right == NULL)
2365 			root = m->left;
2366 		else {
2367 			/*
2368 			 * Move the page's successor to the root, because
2369 			 * pages are usually removed in ascending order.
2370 			 */
2371 			if (m->right != next)
2372 				vm_page_splay(m->pindex, m->right);
2373 			next->left = m->left;
2374 			root = next;
2375 		}
2376 		object->root = root;
2377 	}
2378 	TAILQ_REMOVE(&object->memq, m, listq);
2379 	object->resident_page_count--;
2380 
2381 	/*
2382 	 * Restore the default memory attribute to the page.
2383 	 */
2384 	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2385 		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2386 
2387 	/*
2388 	 * Insert the page into the object's collection of cached pages
2389 	 * and the physical memory allocator's cache/free page queues.
2390 	 */
2391 	m->flags &= ~PG_ZERO;
2392 	mtx_lock(&vm_page_queue_free_mtx);
2393 	m->flags |= PG_CACHED;
2394 	cnt.v_cache_count++;
2395 	root = object->cache;
2396 	if (root == NULL) {
2397 		m->left = NULL;
2398 		m->right = NULL;
2399 	} else {
2400 		root = vm_page_splay(m->pindex, root);
2401 		if (m->pindex < root->pindex) {
2402 			m->left = root->left;
2403 			m->right = root;
2404 			root->left = NULL;
2405 		} else if (__predict_false(m->pindex == root->pindex))
2406 			panic("vm_page_cache: offset already cached");
2407 		else {
2408 			m->right = root->right;
2409 			m->left = root;
2410 			root->right = NULL;
2411 		}
2412 	}
2413 	object->cache = m;
2414 #if VM_NRESERVLEVEL > 0
2415 	if (!vm_reserv_free_page(m)) {
2416 #else
2417 	if (TRUE) {
2418 #endif
2419 		vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2420 		vm_phys_free_pages(m, 0);
2421 	}
2422 	vm_page_free_wakeup();
2423 	mtx_unlock(&vm_page_queue_free_mtx);
2424 
2425 	/*
2426 	 * Increment the vnode's hold count if this is the object's only
2427 	 * cached page.  Decrement the vnode's hold count if this was
2428 	 * the object's only resident page.
2429 	 */
2430 	if (object->type == OBJT_VNODE) {
2431 		if (root == NULL && object->resident_page_count != 0)
2432 			vhold(object->handle);
2433 		else if (root != NULL && object->resident_page_count == 0)
2434 			vdrop(object->handle);
2435 	}
2436 }
2437 
2438 /*
2439  * vm_page_dontneed
2440  *
2441  *	Cache, deactivate, or do nothing as appropriate.  This routine
2442  *	is typically used by madvise() MADV_DONTNEED.
2443  *
2444  *	Generally speaking we want to move the page into the cache so
2445  *	it gets reused quickly.  However, this can result in a silly syndrome
2446  *	due to the page recycling too quickly.  Small objects will not be
2447  *	fully cached.  On the otherhand, if we move the page to the inactive
2448  *	queue we wind up with a problem whereby very large objects
2449  *	unnecessarily blow away our inactive and cache queues.
2450  *
2451  *	The solution is to move the pages based on a fixed weighting.  We
2452  *	either leave them alone, deactivate them, or move them to the cache,
2453  *	where moving them to the cache has the highest weighting.
2454  *	By forcing some pages into other queues we eventually force the
2455  *	system to balance the queues, potentially recovering other unrelated
2456  *	space from active.  The idea is to not force this to happen too
2457  *	often.
2458  */
2459 void
2460 vm_page_dontneed(vm_page_t m)
2461 {
2462 	int dnw;
2463 	int head;
2464 
2465 	vm_page_lock_assert(m, MA_OWNED);
2466 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2467 	dnw = PCPU_GET(dnweight);
2468 	PCPU_INC(dnweight);
2469 
2470 	/*
2471 	 * Occasionally leave the page alone.
2472 	 */
2473 	if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2474 		if (m->act_count >= ACT_INIT)
2475 			--m->act_count;
2476 		return;
2477 	}
2478 
2479 	/*
2480 	 * Clear any references to the page.  Otherwise, the page daemon will
2481 	 * immediately reactivate the page.
2482 	 *
2483 	 * Perform the pmap_clear_reference() first.  Otherwise, a concurrent
2484 	 * pmap operation, such as pmap_remove(), could clear a reference in
2485 	 * the pmap and set PGA_REFERENCED on the page before the
2486 	 * pmap_clear_reference() had completed.  Consequently, the page would
2487 	 * appear referenced based upon an old reference that occurred before
2488 	 * this function ran.
2489 	 */
2490 	pmap_clear_reference(m);
2491 	vm_page_aflag_clear(m, PGA_REFERENCED);
2492 
2493 	if (m->dirty == 0 && pmap_is_modified(m))
2494 		vm_page_dirty(m);
2495 
2496 	if (m->dirty || (dnw & 0x0070) == 0) {
2497 		/*
2498 		 * Deactivate the page 3 times out of 32.
2499 		 */
2500 		head = 0;
2501 	} else {
2502 		/*
2503 		 * Cache the page 28 times out of every 32.  Note that
2504 		 * the page is deactivated instead of cached, but placed
2505 		 * at the head of the queue instead of the tail.
2506 		 */
2507 		head = 1;
2508 	}
2509 	_vm_page_deactivate(m, head);
2510 }
2511 
2512 /*
2513  * Grab a page, waiting until we are waken up due to the page
2514  * changing state.  We keep on waiting, if the page continues
2515  * to be in the object.  If the page doesn't exist, first allocate it
2516  * and then conditionally zero it.
2517  *
2518  * The caller must always specify the VM_ALLOC_RETRY flag.  This is intended
2519  * to facilitate its eventual removal.
2520  *
2521  * This routine may block.
2522  */
2523 vm_page_t
2524 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2525 {
2526 	vm_page_t m;
2527 
2528 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2529 	KASSERT((allocflags & VM_ALLOC_RETRY) != 0,
2530 	    ("vm_page_grab: VM_ALLOC_RETRY is required"));
2531 retrylookup:
2532 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
2533 		if ((m->oflags & VPO_BUSY) != 0 ||
2534 		    ((allocflags & VM_ALLOC_IGN_SBUSY) == 0 && m->busy != 0)) {
2535 			/*
2536 			 * Reference the page before unlocking and
2537 			 * sleeping so that the page daemon is less
2538 			 * likely to reclaim it.
2539 			 */
2540 			vm_page_aflag_set(m, PGA_REFERENCED);
2541 			vm_page_sleep(m, "pgrbwt");
2542 			goto retrylookup;
2543 		} else {
2544 			if ((allocflags & VM_ALLOC_WIRED) != 0) {
2545 				vm_page_lock(m);
2546 				vm_page_wire(m);
2547 				vm_page_unlock(m);
2548 			}
2549 			if ((allocflags & VM_ALLOC_NOBUSY) == 0)
2550 				vm_page_busy(m);
2551 			return (m);
2552 		}
2553 	}
2554 	m = vm_page_alloc(object, pindex, allocflags & ~(VM_ALLOC_RETRY |
2555 	    VM_ALLOC_IGN_SBUSY));
2556 	if (m == NULL) {
2557 		VM_OBJECT_UNLOCK(object);
2558 		VM_WAIT;
2559 		VM_OBJECT_LOCK(object);
2560 		goto retrylookup;
2561 	} else if (m->valid != 0)
2562 		return (m);
2563 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2564 		pmap_zero_page(m);
2565 	return (m);
2566 }
2567 
2568 /*
2569  * Mapping function for valid bits or for dirty bits in
2570  * a page.  May not block.
2571  *
2572  * Inputs are required to range within a page.
2573  */
2574 vm_page_bits_t
2575 vm_page_bits(int base, int size)
2576 {
2577 	int first_bit;
2578 	int last_bit;
2579 
2580 	KASSERT(
2581 	    base + size <= PAGE_SIZE,
2582 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
2583 	);
2584 
2585 	if (size == 0)		/* handle degenerate case */
2586 		return (0);
2587 
2588 	first_bit = base >> DEV_BSHIFT;
2589 	last_bit = (base + size - 1) >> DEV_BSHIFT;
2590 
2591 	return (((vm_page_bits_t)2 << last_bit) -
2592 	    ((vm_page_bits_t)1 << first_bit));
2593 }
2594 
2595 /*
2596  *	vm_page_set_valid_range:
2597  *
2598  *	Sets portions of a page valid.  The arguments are expected
2599  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2600  *	of any partial chunks touched by the range.  The invalid portion of
2601  *	such chunks will be zeroed.
2602  *
2603  *	(base + size) must be less then or equal to PAGE_SIZE.
2604  */
2605 void
2606 vm_page_set_valid_range(vm_page_t m, int base, int size)
2607 {
2608 	int endoff, frag;
2609 
2610 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2611 	if (size == 0)	/* handle degenerate case */
2612 		return;
2613 
2614 	/*
2615 	 * If the base is not DEV_BSIZE aligned and the valid
2616 	 * bit is clear, we have to zero out a portion of the
2617 	 * first block.
2618 	 */
2619 	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2620 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2621 		pmap_zero_page_area(m, frag, base - frag);
2622 
2623 	/*
2624 	 * If the ending offset is not DEV_BSIZE aligned and the
2625 	 * valid bit is clear, we have to zero out a portion of
2626 	 * the last block.
2627 	 */
2628 	endoff = base + size;
2629 	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2630 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2631 		pmap_zero_page_area(m, endoff,
2632 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2633 
2634 	/*
2635 	 * Assert that no previously invalid block that is now being validated
2636 	 * is already dirty.
2637 	 */
2638 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2639 	    ("vm_page_set_valid_range: page %p is dirty", m));
2640 
2641 	/*
2642 	 * Set valid bits inclusive of any overlap.
2643 	 */
2644 	m->valid |= vm_page_bits(base, size);
2645 }
2646 
2647 /*
2648  * Clear the given bits from the specified page's dirty field.
2649  */
2650 static __inline void
2651 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2652 {
2653 	uintptr_t addr;
2654 #if PAGE_SIZE < 16384
2655 	int shift;
2656 #endif
2657 
2658 	/*
2659 	 * If the object is locked and the page is neither VPO_BUSY nor
2660 	 * write mapped, then the page's dirty field cannot possibly be
2661 	 * set by a concurrent pmap operation.
2662 	 */
2663 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2664 	if ((m->oflags & VPO_BUSY) == 0 && !pmap_page_is_write_mapped(m))
2665 		m->dirty &= ~pagebits;
2666 	else {
2667 		/*
2668 		 * The pmap layer can call vm_page_dirty() without
2669 		 * holding a distinguished lock.  The combination of
2670 		 * the object's lock and an atomic operation suffice
2671 		 * to guarantee consistency of the page dirty field.
2672 		 *
2673 		 * For PAGE_SIZE == 32768 case, compiler already
2674 		 * properly aligns the dirty field, so no forcible
2675 		 * alignment is needed. Only require existence of
2676 		 * atomic_clear_64 when page size is 32768.
2677 		 */
2678 		addr = (uintptr_t)&m->dirty;
2679 #if PAGE_SIZE == 32768
2680 		atomic_clear_64((uint64_t *)addr, pagebits);
2681 #elif PAGE_SIZE == 16384
2682 		atomic_clear_32((uint32_t *)addr, pagebits);
2683 #else		/* PAGE_SIZE <= 8192 */
2684 		/*
2685 		 * Use a trick to perform a 32-bit atomic on the
2686 		 * containing aligned word, to not depend on the existence
2687 		 * of atomic_clear_{8, 16}.
2688 		 */
2689 		shift = addr & (sizeof(uint32_t) - 1);
2690 #if BYTE_ORDER == BIG_ENDIAN
2691 		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2692 #else
2693 		shift *= NBBY;
2694 #endif
2695 		addr &= ~(sizeof(uint32_t) - 1);
2696 		atomic_clear_32((uint32_t *)addr, pagebits << shift);
2697 #endif		/* PAGE_SIZE */
2698 	}
2699 }
2700 
2701 /*
2702  *	vm_page_set_validclean:
2703  *
2704  *	Sets portions of a page valid and clean.  The arguments are expected
2705  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2706  *	of any partial chunks touched by the range.  The invalid portion of
2707  *	such chunks will be zero'd.
2708  *
2709  *	This routine may not block.
2710  *
2711  *	(base + size) must be less then or equal to PAGE_SIZE.
2712  */
2713 void
2714 vm_page_set_validclean(vm_page_t m, int base, int size)
2715 {
2716 	vm_page_bits_t oldvalid, pagebits;
2717 	int endoff, frag;
2718 
2719 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2720 	if (size == 0)	/* handle degenerate case */
2721 		return;
2722 
2723 	/*
2724 	 * If the base is not DEV_BSIZE aligned and the valid
2725 	 * bit is clear, we have to zero out a portion of the
2726 	 * first block.
2727 	 */
2728 	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2729 	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2730 		pmap_zero_page_area(m, frag, base - frag);
2731 
2732 	/*
2733 	 * If the ending offset is not DEV_BSIZE aligned and the
2734 	 * valid bit is clear, we have to zero out a portion of
2735 	 * the last block.
2736 	 */
2737 	endoff = base + size;
2738 	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2739 	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2740 		pmap_zero_page_area(m, endoff,
2741 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2742 
2743 	/*
2744 	 * Set valid, clear dirty bits.  If validating the entire
2745 	 * page we can safely clear the pmap modify bit.  We also
2746 	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2747 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
2748 	 * be set again.
2749 	 *
2750 	 * We set valid bits inclusive of any overlap, but we can only
2751 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
2752 	 * the range.
2753 	 */
2754 	oldvalid = m->valid;
2755 	pagebits = vm_page_bits(base, size);
2756 	m->valid |= pagebits;
2757 #if 0	/* NOT YET */
2758 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2759 		frag = DEV_BSIZE - frag;
2760 		base += frag;
2761 		size -= frag;
2762 		if (size < 0)
2763 			size = 0;
2764 	}
2765 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2766 #endif
2767 	if (base == 0 && size == PAGE_SIZE) {
2768 		/*
2769 		 * The page can only be modified within the pmap if it is
2770 		 * mapped, and it can only be mapped if it was previously
2771 		 * fully valid.
2772 		 */
2773 		if (oldvalid == VM_PAGE_BITS_ALL)
2774 			/*
2775 			 * Perform the pmap_clear_modify() first.  Otherwise,
2776 			 * a concurrent pmap operation, such as
2777 			 * pmap_protect(), could clear a modification in the
2778 			 * pmap and set the dirty field on the page before
2779 			 * pmap_clear_modify() had begun and after the dirty
2780 			 * field was cleared here.
2781 			 */
2782 			pmap_clear_modify(m);
2783 		m->dirty = 0;
2784 		m->oflags &= ~VPO_NOSYNC;
2785 	} else if (oldvalid != VM_PAGE_BITS_ALL)
2786 		m->dirty &= ~pagebits;
2787 	else
2788 		vm_page_clear_dirty_mask(m, pagebits);
2789 }
2790 
2791 void
2792 vm_page_clear_dirty(vm_page_t m, int base, int size)
2793 {
2794 
2795 	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2796 }
2797 
2798 /*
2799  *	vm_page_set_invalid:
2800  *
2801  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
2802  *	valid and dirty bits for the effected areas are cleared.
2803  *
2804  *	May not block.
2805  */
2806 void
2807 vm_page_set_invalid(vm_page_t m, int base, int size)
2808 {
2809 	vm_page_bits_t bits;
2810 
2811 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2812 	KASSERT((m->oflags & VPO_BUSY) == 0,
2813 	    ("vm_page_set_invalid: page %p is busy", m));
2814 	bits = vm_page_bits(base, size);
2815 	if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2816 		pmap_remove_all(m);
2817 	KASSERT(!pmap_page_is_mapped(m),
2818 	    ("vm_page_set_invalid: page %p is mapped", m));
2819 	m->valid &= ~bits;
2820 	m->dirty &= ~bits;
2821 }
2822 
2823 /*
2824  * vm_page_zero_invalid()
2825  *
2826  *	The kernel assumes that the invalid portions of a page contain
2827  *	garbage, but such pages can be mapped into memory by user code.
2828  *	When this occurs, we must zero out the non-valid portions of the
2829  *	page so user code sees what it expects.
2830  *
2831  *	Pages are most often semi-valid when the end of a file is mapped
2832  *	into memory and the file's size is not page aligned.
2833  */
2834 void
2835 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2836 {
2837 	int b;
2838 	int i;
2839 
2840 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2841 	/*
2842 	 * Scan the valid bits looking for invalid sections that
2843 	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2844 	 * valid bit may be set ) have already been zerod by
2845 	 * vm_page_set_validclean().
2846 	 */
2847 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2848 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
2849 		    (m->valid & ((vm_page_bits_t)1 << i))) {
2850 			if (i > b) {
2851 				pmap_zero_page_area(m,
2852 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2853 			}
2854 			b = i + 1;
2855 		}
2856 	}
2857 
2858 	/*
2859 	 * setvalid is TRUE when we can safely set the zero'd areas
2860 	 * as being valid.  We can do this if there are no cache consistancy
2861 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2862 	 */
2863 	if (setvalid)
2864 		m->valid = VM_PAGE_BITS_ALL;
2865 }
2866 
2867 /*
2868  *	vm_page_is_valid:
2869  *
2870  *	Is (partial) page valid?  Note that the case where size == 0
2871  *	will return FALSE in the degenerate case where the page is
2872  *	entirely invalid, and TRUE otherwise.
2873  *
2874  *	May not block.
2875  */
2876 int
2877 vm_page_is_valid(vm_page_t m, int base, int size)
2878 {
2879 	vm_page_bits_t bits;
2880 
2881 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2882 	bits = vm_page_bits(base, size);
2883 	if (m->valid && ((m->valid & bits) == bits))
2884 		return 1;
2885 	else
2886 		return 0;
2887 }
2888 
2889 /*
2890  * update dirty bits from pmap/mmu.  May not block.
2891  */
2892 void
2893 vm_page_test_dirty(vm_page_t m)
2894 {
2895 
2896 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2897 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
2898 		vm_page_dirty(m);
2899 }
2900 
2901 void
2902 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
2903 {
2904 
2905 	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
2906 }
2907 
2908 void
2909 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
2910 {
2911 
2912 	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
2913 }
2914 
2915 int
2916 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
2917 {
2918 
2919 	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
2920 }
2921 
2922 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
2923 void
2924 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
2925 {
2926 
2927 	mtx_assert_(vm_page_lockptr(m), a, file, line);
2928 }
2929 #endif
2930 
2931 int so_zerocp_fullpage = 0;
2932 
2933 /*
2934  *	Replace the given page with a copy.  The copied page assumes
2935  *	the portion of the given page's "wire_count" that is not the
2936  *	responsibility of this copy-on-write mechanism.
2937  *
2938  *	The object containing the given page must have a non-zero
2939  *	paging-in-progress count and be locked.
2940  */
2941 void
2942 vm_page_cowfault(vm_page_t m)
2943 {
2944 	vm_page_t mnew;
2945 	vm_object_t object;
2946 	vm_pindex_t pindex;
2947 
2948 	mtx_assert(&vm_page_queue_mtx, MA_NOTOWNED);
2949 	vm_page_lock_assert(m, MA_OWNED);
2950 	object = m->object;
2951 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2952 	KASSERT(object->paging_in_progress != 0,
2953 	    ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2954 	    object));
2955 	pindex = m->pindex;
2956 
2957  retry_alloc:
2958 	pmap_remove_all(m);
2959 	vm_page_remove(m);
2960 	mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2961 	if (mnew == NULL) {
2962 		vm_page_insert(m, object, pindex);
2963 		vm_page_unlock(m);
2964 		VM_OBJECT_UNLOCK(object);
2965 		VM_WAIT;
2966 		VM_OBJECT_LOCK(object);
2967 		if (m == vm_page_lookup(object, pindex)) {
2968 			vm_page_lock(m);
2969 			goto retry_alloc;
2970 		} else {
2971 			/*
2972 			 * Page disappeared during the wait.
2973 			 */
2974 			return;
2975 		}
2976 	}
2977 
2978 	if (m->cow == 0) {
2979 		/*
2980 		 * check to see if we raced with an xmit complete when
2981 		 * waiting to allocate a page.  If so, put things back
2982 		 * the way they were
2983 		 */
2984 		vm_page_unlock(m);
2985 		vm_page_lock(mnew);
2986 		vm_page_free(mnew);
2987 		vm_page_unlock(mnew);
2988 		vm_page_insert(m, object, pindex);
2989 	} else { /* clear COW & copy page */
2990 		if (!so_zerocp_fullpage)
2991 			pmap_copy_page(m, mnew);
2992 		mnew->valid = VM_PAGE_BITS_ALL;
2993 		vm_page_dirty(mnew);
2994 		mnew->wire_count = m->wire_count - m->cow;
2995 		m->wire_count = m->cow;
2996 		vm_page_unlock(m);
2997 	}
2998 }
2999 
3000 void
3001 vm_page_cowclear(vm_page_t m)
3002 {
3003 
3004 	vm_page_lock_assert(m, MA_OWNED);
3005 	if (m->cow) {
3006 		m->cow--;
3007 		/*
3008 		 * let vm_fault add back write permission  lazily
3009 		 */
3010 	}
3011 	/*
3012 	 *  sf_buf_free() will free the page, so we needn't do it here
3013 	 */
3014 }
3015 
3016 int
3017 vm_page_cowsetup(vm_page_t m)
3018 {
3019 
3020 	vm_page_lock_assert(m, MA_OWNED);
3021 	if ((m->flags & PG_FICTITIOUS) != 0 ||
3022 	    (m->oflags & VPO_UNMANAGED) != 0 ||
3023 	    m->cow == USHRT_MAX - 1 || !VM_OBJECT_TRYLOCK(m->object))
3024 		return (EBUSY);
3025 	m->cow++;
3026 	pmap_remove_write(m);
3027 	VM_OBJECT_UNLOCK(m->object);
3028 	return (0);
3029 }
3030 
3031 #ifdef INVARIANTS
3032 void
3033 vm_page_object_lock_assert(vm_page_t m)
3034 {
3035 
3036 	/*
3037 	 * Certain of the page's fields may only be modified by the
3038 	 * holder of the containing object's lock or the setter of the
3039 	 * page's VPO_BUSY flag.  Unfortunately, the setter of the
3040 	 * VPO_BUSY flag is not recorded, and thus cannot be checked
3041 	 * here.
3042 	 */
3043 	if (m->object != NULL && (m->oflags & VPO_BUSY) == 0)
3044 		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
3045 }
3046 #endif
3047 
3048 #include "opt_ddb.h"
3049 #ifdef DDB
3050 #include <sys/kernel.h>
3051 
3052 #include <ddb/ddb.h>
3053 
3054 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3055 {
3056 	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
3057 	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
3058 	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
3059 	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
3060 	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
3061 	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
3062 	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
3063 	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
3064 	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
3065 	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
3066 }
3067 
3068 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3069 {
3070 
3071 	db_printf("PQ_FREE:");
3072 	db_printf(" %d", cnt.v_free_count);
3073 	db_printf("\n");
3074 
3075 	db_printf("PQ_CACHE:");
3076 	db_printf(" %d", cnt.v_cache_count);
3077 	db_printf("\n");
3078 
3079 	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
3080 		*vm_page_queues[PQ_ACTIVE].cnt,
3081 		*vm_page_queues[PQ_INACTIVE].cnt);
3082 }
3083 #endif /* DDB */
3084