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