xref: /freebsd/sys/vm/vm_page.c (revision 84ee9401a3fc8d3c22424266f421a928989cd692)
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
33  */
34 
35 /*-
36  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
37  * All rights reserved.
38  *
39  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
40  *
41  * Permission to use, copy, modify and distribute this software and
42  * its documentation is hereby granted, provided that both the copyright
43  * notice and this permission notice appear in all copies of the
44  * software, derivative works or modified versions, and any portions
45  * thereof, and that both notices appear in supporting documentation.
46  *
47  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
48  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
49  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
50  *
51  * Carnegie Mellon requests users of this software to return to
52  *
53  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
54  *  School of Computer Science
55  *  Carnegie Mellon University
56  *  Pittsburgh PA 15213-3890
57  *
58  * any improvements or extensions that they make and grant Carnegie the
59  * rights to redistribute these changes.
60  */
61 
62 /*
63  *			GENERAL RULES ON VM_PAGE MANIPULATION
64  *
65  *	- a pageq mutex is required when adding or removing a page from a
66  *	  page queue (vm_page_queue[]), regardless of other mutexes or the
67  *	  busy state of a page.
68  *
69  *	- a hash chain mutex is required when associating or disassociating
70  *	  a page from the VM PAGE CACHE hash table (vm_page_buckets),
71  *	  regardless of other mutexes or the busy state of a page.
72  *
73  *	- either a hash chain mutex OR a busied page is required in order
74  *	  to modify the page flags.  A hash chain mutex must be obtained in
75  *	  order to busy a page.  A page's flags cannot be modified by a
76  *	  hash chain mutex if the page is marked busy.
77  *
78  *	- The object memq mutex is held when inserting or removing
79  *	  pages from an object (vm_page_insert() or vm_page_remove()).  This
80  *	  is different from the object's main mutex.
81  *
82  *	Generally speaking, you have to be aware of side effects when running
83  *	vm_page ops.  A vm_page_lookup() will return with the hash chain
84  *	locked, whether it was able to lookup the page or not.  vm_page_free(),
85  *	vm_page_cache(), vm_page_activate(), and a number of other routines
86  *	will release the hash chain mutex for you.  Intermediate manipulation
87  *	routines such as vm_page_flag_set() expect the hash chain to be held
88  *	on entry and the hash chain will remain held on return.
89  *
90  *	pageq scanning can only occur with the pageq in question locked.
91  *	We have a known bottleneck with the active queue, but the cache
92  *	and free queues are actually arrays already.
93  */
94 
95 /*
96  *	Resident memory management module.
97  */
98 
99 #include <sys/cdefs.h>
100 __FBSDID("$FreeBSD$");
101 
102 #include <sys/param.h>
103 #include <sys/systm.h>
104 #include <sys/lock.h>
105 #include <sys/kernel.h>
106 #include <sys/malloc.h>
107 #include <sys/mutex.h>
108 #include <sys/proc.h>
109 #include <sys/sysctl.h>
110 #include <sys/vmmeter.h>
111 #include <sys/vnode.h>
112 
113 #include <vm/vm.h>
114 #include <vm/vm_param.h>
115 #include <vm/vm_kern.h>
116 #include <vm/vm_object.h>
117 #include <vm/vm_page.h>
118 #include <vm/vm_pageout.h>
119 #include <vm/vm_pager.h>
120 #include <vm/vm_extern.h>
121 #include <vm/uma.h>
122 #include <vm/uma_int.h>
123 
124 #include <machine/md_var.h>
125 
126 /*
127  *	Associated with page of user-allocatable memory is a
128  *	page structure.
129  */
130 
131 struct mtx vm_page_queue_mtx;
132 struct mtx vm_page_queue_free_mtx;
133 
134 vm_page_t vm_page_array = 0;
135 int vm_page_array_size = 0;
136 long first_page = 0;
137 int vm_page_zero_count = 0;
138 
139 static int boot_pages = UMA_BOOT_PAGES;
140 TUNABLE_INT("vm.boot_pages", &boot_pages);
141 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
142 	"number of pages allocated for bootstrapping the VM system");
143 
144 /*
145  *	vm_set_page_size:
146  *
147  *	Sets the page size, perhaps based upon the memory
148  *	size.  Must be called before any use of page-size
149  *	dependent functions.
150  */
151 void
152 vm_set_page_size(void)
153 {
154 	if (cnt.v_page_size == 0)
155 		cnt.v_page_size = PAGE_SIZE;
156 	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
157 		panic("vm_set_page_size: page size not a power of two");
158 }
159 
160 /*
161  *	vm_page_blacklist_lookup:
162  *
163  *	See if a physical address in this page has been listed
164  *	in the blacklist tunable.  Entries in the tunable are
165  *	separated by spaces or commas.  If an invalid integer is
166  *	encountered then the rest of the string is skipped.
167  */
168 static int
169 vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
170 {
171 	vm_paddr_t bad;
172 	char *cp, *pos;
173 
174 	for (pos = list; *pos != '\0'; pos = cp) {
175 		bad = strtoq(pos, &cp, 0);
176 		if (*cp != '\0') {
177 			if (*cp == ' ' || *cp == ',') {
178 				cp++;
179 				if (cp == pos)
180 					continue;
181 			} else
182 				break;
183 		}
184 		if (pa == trunc_page(bad))
185 			return (1);
186 	}
187 	return (0);
188 }
189 
190 /*
191  *	vm_page_startup:
192  *
193  *	Initializes the resident memory module.
194  *
195  *	Allocates memory for the page cells, and
196  *	for the object/offset-to-page hash table headers.
197  *	Each page cell is initialized and placed on the free list.
198  */
199 vm_offset_t
200 vm_page_startup(vm_offset_t vaddr)
201 {
202 	vm_offset_t mapped;
203 	vm_size_t npages;
204 	vm_paddr_t page_range;
205 	vm_paddr_t new_end;
206 	int i;
207 	vm_paddr_t pa;
208 	int nblocks;
209 	vm_paddr_t last_pa;
210 	char *list;
211 
212 	/* the biggest memory array is the second group of pages */
213 	vm_paddr_t end;
214 	vm_paddr_t biggestsize;
215 	int biggestone;
216 
217 	vm_paddr_t total;
218 
219 	total = 0;
220 	biggestsize = 0;
221 	biggestone = 0;
222 	nblocks = 0;
223 	vaddr = round_page(vaddr);
224 
225 	for (i = 0; phys_avail[i + 1]; i += 2) {
226 		phys_avail[i] = round_page(phys_avail[i]);
227 		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
228 	}
229 
230 	for (i = 0; phys_avail[i + 1]; i += 2) {
231 		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
232 
233 		if (size > biggestsize) {
234 			biggestone = i;
235 			biggestsize = size;
236 		}
237 		++nblocks;
238 		total += size;
239 	}
240 
241 	end = phys_avail[biggestone+1];
242 
243 	/*
244 	 * Initialize the locks.
245 	 */
246 	mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
247 	    MTX_RECURSE);
248 	mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
249 	    MTX_SPIN);
250 
251 	/*
252 	 * Initialize the queue headers for the free queue, the active queue
253 	 * and the inactive queue.
254 	 */
255 	vm_pageq_init();
256 
257 	/*
258 	 * Allocate memory for use when boot strapping the kernel memory
259 	 * allocator.
260 	 */
261 	new_end = end - (boot_pages * UMA_SLAB_SIZE);
262 	new_end = trunc_page(new_end);
263 	mapped = pmap_map(&vaddr, new_end, end,
264 	    VM_PROT_READ | VM_PROT_WRITE);
265 	bzero((void *)mapped, end - new_end);
266 	uma_startup((void *)mapped, boot_pages);
267 
268 #if defined(__amd64__) || defined(__i386__)
269 	/*
270 	 * Allocate a bitmap to indicate that a random physical page
271 	 * needs to be included in a minidump.
272 	 *
273 	 * The amd64 port needs this to indicate which direct map pages
274 	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
275 	 *
276 	 * However, i386 still needs this workspace internally within the
277 	 * minidump code.  In theory, they are not needed on i386, but are
278 	 * included should the sf_buf code decide to use them.
279 	 */
280 	page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE;
281 	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
282 	new_end -= vm_page_dump_size;
283 	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
284 	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
285 	bzero((void *)vm_page_dump, vm_page_dump_size);
286 #endif
287 	/*
288 	 * Compute the number of pages of memory that will be available for
289 	 * use (taking into account the overhead of a page structure per
290 	 * page).
291 	 */
292 	first_page = phys_avail[0] / PAGE_SIZE;
293 	page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
294 	npages = (total - (page_range * sizeof(struct vm_page)) -
295 	    (end - new_end)) / PAGE_SIZE;
296 	end = new_end;
297 
298 	/*
299 	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
300 	 */
301 	vaddr += PAGE_SIZE;
302 
303 	/*
304 	 * Initialize the mem entry structures now, and put them in the free
305 	 * queue.
306 	 */
307 	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
308 	mapped = pmap_map(&vaddr, new_end, end,
309 	    VM_PROT_READ | VM_PROT_WRITE);
310 	vm_page_array = (vm_page_t) mapped;
311 #ifdef __amd64__
312 	/*
313 	 * pmap_map on amd64 comes out of the direct-map, not kvm like i386,
314 	 * so the pages must be tracked for a crashdump to include this data.
315 	 * This includes the vm_page_array and the early UMA bootstrap pages.
316 	 */
317 	for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
318 		dump_add_page(pa);
319 #endif
320 	phys_avail[biggestone + 1] = new_end;
321 
322 	/*
323 	 * Clear all of the page structures
324 	 */
325 	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
326 	vm_page_array_size = page_range;
327 
328 	/*
329 	 * Construct the free queue(s) in descending order (by physical
330 	 * address) so that the first 16MB of physical memory is allocated
331 	 * last rather than first.  On large-memory machines, this avoids
332 	 * the exhaustion of low physical memory before isa_dma_init has run.
333 	 */
334 	cnt.v_page_count = 0;
335 	cnt.v_free_count = 0;
336 	list = getenv("vm.blacklist");
337 	for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
338 		pa = phys_avail[i];
339 		last_pa = phys_avail[i + 1];
340 		while (pa < last_pa && npages-- > 0) {
341 			if (list != NULL &&
342 			    vm_page_blacklist_lookup(list, pa))
343 				printf("Skipping page with pa 0x%jx\n",
344 				    (uintmax_t)pa);
345 			else
346 				vm_pageq_add_new_page(pa);
347 			pa += PAGE_SIZE;
348 		}
349 	}
350 	freeenv(list);
351 	return (vaddr);
352 }
353 
354 void
355 vm_page_flag_set(vm_page_t m, unsigned short bits)
356 {
357 
358 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
359 	m->flags |= bits;
360 }
361 
362 void
363 vm_page_flag_clear(vm_page_t m, unsigned short bits)
364 {
365 
366 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
367 	m->flags &= ~bits;
368 }
369 
370 void
371 vm_page_busy(vm_page_t m)
372 {
373 
374 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
375 	KASSERT((m->flags & PG_BUSY) == 0,
376 	    ("vm_page_busy: page already busy!!!"));
377 	vm_page_flag_set(m, PG_BUSY);
378 }
379 
380 /*
381  *      vm_page_flash:
382  *
383  *      wakeup anyone waiting for the page.
384  */
385 void
386 vm_page_flash(vm_page_t m)
387 {
388 
389 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
390 	if (m->oflags & VPO_WANTED) {
391 		m->oflags &= ~VPO_WANTED;
392 		wakeup(m);
393 	}
394 }
395 
396 /*
397  *      vm_page_wakeup:
398  *
399  *      clear the PG_BUSY flag and wakeup anyone waiting for the
400  *      page.
401  *
402  */
403 void
404 vm_page_wakeup(vm_page_t m)
405 {
406 
407 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
408 	KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
409 	vm_page_flag_clear(m, PG_BUSY);
410 	vm_page_flash(m);
411 }
412 
413 void
414 vm_page_io_start(vm_page_t m)
415 {
416 
417 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
418 	m->busy++;
419 }
420 
421 void
422 vm_page_io_finish(vm_page_t m)
423 {
424 
425 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
426 	m->busy--;
427 	if (m->busy == 0)
428 		vm_page_flash(m);
429 }
430 
431 /*
432  * Keep page from being freed by the page daemon
433  * much of the same effect as wiring, except much lower
434  * overhead and should be used only for *very* temporary
435  * holding ("wiring").
436  */
437 void
438 vm_page_hold(vm_page_t mem)
439 {
440 
441 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
442         mem->hold_count++;
443 }
444 
445 void
446 vm_page_unhold(vm_page_t mem)
447 {
448 
449 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
450 	--mem->hold_count;
451 	KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
452 	if (mem->hold_count == 0 && VM_PAGE_INQUEUE2(mem, PQ_HOLD))
453 		vm_page_free_toq(mem);
454 }
455 
456 /*
457  *	vm_page_free:
458  *
459  *	Free a page
460  *
461  *	The clearing of PG_ZERO is a temporary safety until the code can be
462  *	reviewed to determine that PG_ZERO is being properly cleared on
463  *	write faults or maps.  PG_ZERO was previously cleared in
464  *	vm_page_alloc().
465  */
466 void
467 vm_page_free(vm_page_t m)
468 {
469 	vm_page_flag_clear(m, PG_ZERO);
470 	vm_page_free_toq(m);
471 	vm_page_zero_idle_wakeup();
472 }
473 
474 /*
475  *	vm_page_free_zero:
476  *
477  *	Free a page to the zerod-pages queue
478  */
479 void
480 vm_page_free_zero(vm_page_t m)
481 {
482 	vm_page_flag_set(m, PG_ZERO);
483 	vm_page_free_toq(m);
484 }
485 
486 /*
487  *	vm_page_sleep:
488  *
489  *	Sleep and release the page queues lock.
490  *
491  *	The object containing the given page must be locked.
492  */
493 void
494 vm_page_sleep(vm_page_t m, const char *msg)
495 {
496 
497 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
498 	if (!mtx_owned(&vm_page_queue_mtx))
499 		vm_page_lock_queues();
500 	vm_page_flag_set(m, PG_REFERENCED);
501 	vm_page_unlock_queues();
502 
503 	/*
504 	 * It's possible that while we sleep, the page will get
505 	 * unbusied and freed.  If we are holding the object
506 	 * lock, we will assume we hold a reference to the object
507 	 * such that even if m->object changes, we can re-lock
508 	 * it.
509 	 */
510 	m->oflags |= VPO_WANTED;
511 	msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
512 }
513 
514 /*
515  *	vm_page_dirty:
516  *
517  *	make page all dirty
518  */
519 void
520 vm_page_dirty(vm_page_t m)
521 {
522 	KASSERT(VM_PAGE_GETKNOWNQUEUE1(m) != PQ_CACHE,
523 	    ("vm_page_dirty: page in cache!"));
524 	KASSERT(VM_PAGE_GETKNOWNQUEUE1(m) != PQ_FREE,
525 	    ("vm_page_dirty: page is free!"));
526 	m->dirty = VM_PAGE_BITS_ALL;
527 }
528 
529 /*
530  *	vm_page_splay:
531  *
532  *	Implements Sleator and Tarjan's top-down splay algorithm.  Returns
533  *	the vm_page containing the given pindex.  If, however, that
534  *	pindex is not found in the vm_object, returns a vm_page that is
535  *	adjacent to the pindex, coming before or after it.
536  */
537 vm_page_t
538 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
539 {
540 	struct vm_page dummy;
541 	vm_page_t lefttreemax, righttreemin, y;
542 
543 	if (root == NULL)
544 		return (root);
545 	lefttreemax = righttreemin = &dummy;
546 	for (;; root = y) {
547 		if (pindex < root->pindex) {
548 			if ((y = root->left) == NULL)
549 				break;
550 			if (pindex < y->pindex) {
551 				/* Rotate right. */
552 				root->left = y->right;
553 				y->right = root;
554 				root = y;
555 				if ((y = root->left) == NULL)
556 					break;
557 			}
558 			/* Link into the new root's right tree. */
559 			righttreemin->left = root;
560 			righttreemin = root;
561 		} else if (pindex > root->pindex) {
562 			if ((y = root->right) == NULL)
563 				break;
564 			if (pindex > y->pindex) {
565 				/* Rotate left. */
566 				root->right = y->left;
567 				y->left = root;
568 				root = y;
569 				if ((y = root->right) == NULL)
570 					break;
571 			}
572 			/* Link into the new root's left tree. */
573 			lefttreemax->right = root;
574 			lefttreemax = root;
575 		} else
576 			break;
577 	}
578 	/* Assemble the new root. */
579 	lefttreemax->right = root->left;
580 	righttreemin->left = root->right;
581 	root->left = dummy.right;
582 	root->right = dummy.left;
583 	return (root);
584 }
585 
586 /*
587  *	vm_page_insert:		[ internal use only ]
588  *
589  *	Inserts the given mem entry into the object and object list.
590  *
591  *	The pagetables are not updated but will presumably fault the page
592  *	in if necessary, or if a kernel page the caller will at some point
593  *	enter the page into the kernel's pmap.  We are not allowed to block
594  *	here so we *can't* do this anyway.
595  *
596  *	The object and page must be locked.
597  *	This routine may not block.
598  */
599 void
600 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
601 {
602 	vm_page_t root;
603 
604 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
605 	if (m->object != NULL)
606 		panic("vm_page_insert: page already inserted");
607 
608 	/*
609 	 * Record the object/offset pair in this page
610 	 */
611 	m->object = object;
612 	m->pindex = pindex;
613 
614 	/*
615 	 * Now link into the object's ordered list of backed pages.
616 	 */
617 	root = object->root;
618 	if (root == NULL) {
619 		m->left = NULL;
620 		m->right = NULL;
621 		TAILQ_INSERT_TAIL(&object->memq, m, listq);
622 	} else {
623 		root = vm_page_splay(pindex, root);
624 		if (pindex < root->pindex) {
625 			m->left = root->left;
626 			m->right = root;
627 			root->left = NULL;
628 			TAILQ_INSERT_BEFORE(root, m, listq);
629 		} else if (pindex == root->pindex)
630 			panic("vm_page_insert: offset already allocated");
631 		else {
632 			m->right = root->right;
633 			m->left = root;
634 			root->right = NULL;
635 			TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
636 		}
637 	}
638 	object->root = m;
639 	object->generation++;
640 
641 	/*
642 	 * show that the object has one more resident page.
643 	 */
644 	object->resident_page_count++;
645 	/*
646 	 * Hold the vnode until the last page is released.
647 	 */
648 	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
649 		vhold((struct vnode *)object->handle);
650 
651 	/*
652 	 * Since we are inserting a new and possibly dirty page,
653 	 * update the object's OBJ_MIGHTBEDIRTY flag.
654 	 */
655 	if (m->flags & PG_WRITEABLE)
656 		vm_object_set_writeable_dirty(object);
657 }
658 
659 /*
660  *	vm_page_remove:
661  *				NOTE: used by device pager as well -wfj
662  *
663  *	Removes the given mem entry from the object/offset-page
664  *	table and the object page list, but do not invalidate/terminate
665  *	the backing store.
666  *
667  *	The object and page must be locked.
668  *	The underlying pmap entry (if any) is NOT removed here.
669  *	This routine may not block.
670  */
671 void
672 vm_page_remove(vm_page_t m)
673 {
674 	vm_object_t object;
675 	vm_page_t root;
676 
677 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
678 	if ((object = m->object) == NULL)
679 		return;
680 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
681 	if (m->flags & PG_BUSY) {
682 		vm_page_flag_clear(m, PG_BUSY);
683 		vm_page_flash(m);
684 	}
685 
686 	/*
687 	 * Now remove from the object's list of backed pages.
688 	 */
689 	if (m != object->root)
690 		vm_page_splay(m->pindex, object->root);
691 	if (m->left == NULL)
692 		root = m->right;
693 	else {
694 		root = vm_page_splay(m->pindex, m->left);
695 		root->right = m->right;
696 	}
697 	object->root = root;
698 	TAILQ_REMOVE(&object->memq, m, listq);
699 
700 	/*
701 	 * And show that the object has one fewer resident page.
702 	 */
703 	object->resident_page_count--;
704 	object->generation++;
705 	/*
706 	 * The vnode may now be recycled.
707 	 */
708 	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
709 		vdrop((struct vnode *)object->handle);
710 
711 	m->object = NULL;
712 }
713 
714 /*
715  *	vm_page_lookup:
716  *
717  *	Returns the page associated with the object/offset
718  *	pair specified; if none is found, NULL is returned.
719  *
720  *	The object must be locked.
721  *	This routine may not block.
722  *	This is a critical path routine
723  */
724 vm_page_t
725 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
726 {
727 	vm_page_t m;
728 
729 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
730 	if ((m = object->root) != NULL && m->pindex != pindex) {
731 		m = vm_page_splay(pindex, m);
732 		if ((object->root = m)->pindex != pindex)
733 			m = NULL;
734 	}
735 	return (m);
736 }
737 
738 /*
739  *	vm_page_rename:
740  *
741  *	Move the given memory entry from its
742  *	current object to the specified target object/offset.
743  *
744  *	The object must be locked.
745  *	This routine may not block.
746  *
747  *	Note: swap associated with the page must be invalidated by the move.  We
748  *	      have to do this for several reasons:  (1) we aren't freeing the
749  *	      page, (2) we are dirtying the page, (3) the VM system is probably
750  *	      moving the page from object A to B, and will then later move
751  *	      the backing store from A to B and we can't have a conflict.
752  *
753  *	Note: we *always* dirty the page.  It is necessary both for the
754  *	      fact that we moved it, and because we may be invalidating
755  *	      swap.  If the page is on the cache, we have to deactivate it
756  *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
757  *	      on the cache.
758  */
759 void
760 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
761 {
762 
763 	vm_page_remove(m);
764 	vm_page_insert(m, new_object, new_pindex);
765 	if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
766 		vm_page_deactivate(m);
767 	vm_page_dirty(m);
768 }
769 
770 /*
771  *	vm_page_select_cache:
772  *
773  *	Move a page of the given color from the cache queue to the free
774  *	queue.  As pages might be found, but are not applicable, they are
775  *	deactivated.
776  *
777  *	This routine may not block.
778  */
779 vm_page_t
780 vm_page_select_cache(int color)
781 {
782 	vm_object_t object;
783 	vm_page_t m;
784 	boolean_t was_trylocked;
785 
786 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
787 	while ((m = vm_pageq_find(PQ_CACHE, color, FALSE)) != NULL) {
788 		KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
789 		KASSERT(!pmap_page_is_mapped(m),
790 		    ("Found mapped cache page %p", m));
791 		KASSERT((m->flags & PG_UNMANAGED) == 0,
792 		    ("Found unmanaged cache page %p", m));
793 		KASSERT(m->wire_count == 0, ("Found wired cache page %p", m));
794 		if (m->hold_count == 0 && (object = m->object,
795 		    (was_trylocked = VM_OBJECT_TRYLOCK(object)) ||
796 		    VM_OBJECT_LOCKED(object))) {
797 			KASSERT((m->flags & PG_BUSY) == 0 && m->busy == 0,
798 			    ("Found busy cache page %p", m));
799 			vm_page_free(m);
800 			if (was_trylocked)
801 				VM_OBJECT_UNLOCK(object);
802 			break;
803 		}
804 		vm_page_deactivate(m);
805 	}
806 	return (m);
807 }
808 
809 /*
810  *	vm_page_alloc:
811  *
812  *	Allocate and return a memory cell associated
813  *	with this VM object/offset pair.
814  *
815  *	page_req classes:
816  *	VM_ALLOC_NORMAL		normal process request
817  *	VM_ALLOC_SYSTEM		system *really* needs a page
818  *	VM_ALLOC_INTERRUPT	interrupt time request
819  *	VM_ALLOC_ZERO		zero page
820  *
821  *	This routine may not block.
822  *
823  *	Additional special handling is required when called from an
824  *	interrupt (VM_ALLOC_INTERRUPT).  We are not allowed to mess with
825  *	the page cache in this case.
826  */
827 vm_page_t
828 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
829 {
830 	vm_page_t m = NULL;
831 	int color, flags, page_req;
832 
833 	page_req = req & VM_ALLOC_CLASS_MASK;
834 	KASSERT(curthread->td_intr_nesting_level == 0 ||
835 	    page_req == VM_ALLOC_INTERRUPT,
836 	    ("vm_page_alloc(NORMAL|SYSTEM) in interrupt context"));
837 
838 	if ((req & VM_ALLOC_NOOBJ) == 0) {
839 		KASSERT(object != NULL,
840 		    ("vm_page_alloc: NULL object."));
841 		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
842 		color = (pindex + object->pg_color) & PQ_COLORMASK;
843 	} else
844 		color = pindex & PQ_COLORMASK;
845 
846 	/*
847 	 * The pager is allowed to eat deeper into the free page list.
848 	 */
849 	if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
850 		page_req = VM_ALLOC_SYSTEM;
851 	};
852 
853 loop:
854 	mtx_lock_spin(&vm_page_queue_free_mtx);
855 	if (cnt.v_free_count > cnt.v_free_reserved ||
856 	    (page_req == VM_ALLOC_SYSTEM &&
857 	     cnt.v_cache_count == 0 &&
858 	     cnt.v_free_count > cnt.v_interrupt_free_min) ||
859 	    (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
860 		/*
861 		 * Allocate from the free queue if the number of free pages
862 		 * exceeds the minimum for the request class.
863 		 */
864 		m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
865 	} else if (page_req != VM_ALLOC_INTERRUPT) {
866 		mtx_unlock_spin(&vm_page_queue_free_mtx);
867 		/*
868 		 * Allocatable from cache (non-interrupt only).  On success,
869 		 * we must free the page and try again, thus ensuring that
870 		 * cnt.v_*_free_min counters are replenished.
871 		 */
872 		vm_page_lock_queues();
873 		if ((m = vm_page_select_cache(color)) == NULL) {
874 			KASSERT(cnt.v_cache_count == 0,
875 			    ("vm_page_alloc: cache queue is missing %d pages",
876 			    cnt.v_cache_count));
877 			vm_page_unlock_queues();
878 			atomic_add_int(&vm_pageout_deficit, 1);
879 			pagedaemon_wakeup();
880 
881 			if (page_req != VM_ALLOC_SYSTEM)
882 				return (NULL);
883 
884 			mtx_lock_spin(&vm_page_queue_free_mtx);
885 			if (cnt.v_free_count <= cnt.v_interrupt_free_min) {
886 				mtx_unlock_spin(&vm_page_queue_free_mtx);
887 				return (NULL);
888 			}
889 			m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
890 		} else {
891 			vm_page_unlock_queues();
892 			goto loop;
893 		}
894 	} else {
895 		/*
896 		 * Not allocatable from cache from interrupt, give up.
897 		 */
898 		mtx_unlock_spin(&vm_page_queue_free_mtx);
899 		atomic_add_int(&vm_pageout_deficit, 1);
900 		pagedaemon_wakeup();
901 		return (NULL);
902 	}
903 
904 	/*
905 	 *  At this point we had better have found a good page.
906 	 */
907 
908 	KASSERT(
909 	    m != NULL,
910 	    ("vm_page_alloc(): missing page on free queue")
911 	);
912 
913 	/*
914 	 * Remove from free queue
915 	 */
916 	vm_pageq_remove_nowakeup(m);
917 
918 	/*
919 	 * Initialize structure.  Only the PG_ZERO flag is inherited.
920 	 */
921 	flags = PG_BUSY;
922 	if (m->flags & PG_ZERO) {
923 		vm_page_zero_count--;
924 		if (req & VM_ALLOC_ZERO)
925 			flags = PG_ZERO | PG_BUSY;
926 	}
927 	if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
928 		flags &= ~PG_BUSY;
929 	m->flags = flags;
930 	m->oflags = 0;
931 	if (req & VM_ALLOC_WIRED) {
932 		atomic_add_int(&cnt.v_wire_count, 1);
933 		m->wire_count = 1;
934 	} else
935 		m->wire_count = 0;
936 	m->hold_count = 0;
937 	m->act_count = 0;
938 	m->busy = 0;
939 	m->valid = 0;
940 	KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
941 	mtx_unlock_spin(&vm_page_queue_free_mtx);
942 
943 	if ((req & VM_ALLOC_NOOBJ) == 0)
944 		vm_page_insert(m, object, pindex);
945 	else
946 		m->pindex = pindex;
947 
948 	/*
949 	 * Don't wakeup too often - wakeup the pageout daemon when
950 	 * we would be nearly out of memory.
951 	 */
952 	if (vm_paging_needed())
953 		pagedaemon_wakeup();
954 
955 	return (m);
956 }
957 
958 /*
959  *	vm_wait:	(also see VM_WAIT macro)
960  *
961  *	Block until free pages are available for allocation
962  *	- Called in various places before memory allocations.
963  */
964 void
965 vm_wait(void)
966 {
967 
968 	vm_page_lock_queues();
969 	if (curproc == pageproc) {
970 		vm_pageout_pages_needed = 1;
971 		msleep(&vm_pageout_pages_needed, &vm_page_queue_mtx,
972 		    PDROP | PSWP, "VMWait", 0);
973 	} else {
974 		if (!vm_pages_needed) {
975 			vm_pages_needed = 1;
976 			wakeup(&vm_pages_needed);
977 		}
978 		msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PVM,
979 		    "vmwait", 0);
980 	}
981 }
982 
983 /*
984  *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
985  *
986  *	Block until free pages are available for allocation
987  *	- Called only in vm_fault so that processes page faulting
988  *	  can be easily tracked.
989  *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
990  *	  processes will be able to grab memory first.  Do not change
991  *	  this balance without careful testing first.
992  */
993 void
994 vm_waitpfault(void)
995 {
996 
997 	vm_page_lock_queues();
998 	if (!vm_pages_needed) {
999 		vm_pages_needed = 1;
1000 		wakeup(&vm_pages_needed);
1001 	}
1002 	msleep(&cnt.v_free_count, &vm_page_queue_mtx, PDROP | PUSER,
1003 	    "pfault", 0);
1004 }
1005 
1006 /*
1007  *	vm_page_activate:
1008  *
1009  *	Put the specified page on the active list (if appropriate).
1010  *	Ensure that act_count is at least ACT_INIT but do not otherwise
1011  *	mess with it.
1012  *
1013  *	The page queues must be locked.
1014  *	This routine may not block.
1015  */
1016 void
1017 vm_page_activate(vm_page_t m)
1018 {
1019 
1020 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1021 	if (VM_PAGE_GETKNOWNQUEUE2(m) != PQ_ACTIVE) {
1022 		if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1023 			cnt.v_reactivated++;
1024 		vm_pageq_remove(m);
1025 		if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1026 			if (m->act_count < ACT_INIT)
1027 				m->act_count = ACT_INIT;
1028 			vm_pageq_enqueue(PQ_ACTIVE, m);
1029 		}
1030 	} else {
1031 		if (m->act_count < ACT_INIT)
1032 			m->act_count = ACT_INIT;
1033 	}
1034 }
1035 
1036 /*
1037  *	vm_page_free_wakeup:
1038  *
1039  *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
1040  *	routine is called when a page has been added to the cache or free
1041  *	queues.
1042  *
1043  *	The page queues must be locked.
1044  *	This routine may not block.
1045  */
1046 static inline void
1047 vm_page_free_wakeup(void)
1048 {
1049 
1050 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1051 	/*
1052 	 * if pageout daemon needs pages, then tell it that there are
1053 	 * some free.
1054 	 */
1055 	if (vm_pageout_pages_needed &&
1056 	    cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1057 		wakeup(&vm_pageout_pages_needed);
1058 		vm_pageout_pages_needed = 0;
1059 	}
1060 	/*
1061 	 * wakeup processes that are waiting on memory if we hit a
1062 	 * high water mark. And wakeup scheduler process if we have
1063 	 * lots of memory. this process will swapin processes.
1064 	 */
1065 	if (vm_pages_needed && !vm_page_count_min()) {
1066 		vm_pages_needed = 0;
1067 		wakeup(&cnt.v_free_count);
1068 	}
1069 }
1070 
1071 /*
1072  *	vm_page_free_toq:
1073  *
1074  *	Returns the given page to the PQ_FREE list,
1075  *	disassociating it with any VM object.
1076  *
1077  *	Object and page must be locked prior to entry.
1078  *	This routine may not block.
1079  */
1080 
1081 void
1082 vm_page_free_toq(vm_page_t m)
1083 {
1084 	struct vpgqueues *pq;
1085 
1086 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1087 	KASSERT(!pmap_page_is_mapped(m),
1088 	    ("vm_page_free_toq: freeing mapped page %p", m));
1089 	cnt.v_tfree++;
1090 
1091 	if (m->busy || VM_PAGE_INQUEUE1(m, PQ_FREE)) {
1092 		printf(
1093 		"vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1094 		    (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1095 		    m->hold_count);
1096 		if (VM_PAGE_INQUEUE1(m, PQ_FREE))
1097 			panic("vm_page_free: freeing free page");
1098 		else
1099 			panic("vm_page_free: freeing busy page");
1100 	}
1101 
1102 	/*
1103 	 * unqueue, then remove page.  Note that we cannot destroy
1104 	 * the page here because we do not want to call the pager's
1105 	 * callback routine until after we've put the page on the
1106 	 * appropriate free queue.
1107 	 */
1108 	vm_pageq_remove_nowakeup(m);
1109 	vm_page_remove(m);
1110 
1111 	/*
1112 	 * If fictitious remove object association and
1113 	 * return, otherwise delay object association removal.
1114 	 */
1115 	if ((m->flags & PG_FICTITIOUS) != 0) {
1116 		return;
1117 	}
1118 
1119 	m->valid = 0;
1120 	vm_page_undirty(m);
1121 
1122 	if (m->wire_count != 0) {
1123 		if (m->wire_count > 1) {
1124 			panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1125 				m->wire_count, (long)m->pindex);
1126 		}
1127 		panic("vm_page_free: freeing wired page");
1128 	}
1129 	if (m->hold_count != 0) {
1130 		m->flags &= ~PG_ZERO;
1131 		VM_PAGE_SETQUEUE2(m, PQ_HOLD);
1132 	} else
1133 		VM_PAGE_SETQUEUE1(m, PQ_FREE);
1134 	pq = &vm_page_queues[VM_PAGE_GETQUEUE(m)];
1135 	mtx_lock_spin(&vm_page_queue_free_mtx);
1136 	pq->lcnt++;
1137 	++(*pq->cnt);
1138 
1139 	/*
1140 	 * Put zero'd pages on the end ( where we look for zero'd pages
1141 	 * first ) and non-zerod pages at the head.
1142 	 */
1143 	if (m->flags & PG_ZERO) {
1144 		TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1145 		++vm_page_zero_count;
1146 	} else {
1147 		TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1148 	}
1149 	mtx_unlock_spin(&vm_page_queue_free_mtx);
1150 	vm_page_free_wakeup();
1151 }
1152 
1153 /*
1154  *	vm_page_unmanage:
1155  *
1156  * 	Prevent PV management from being done on the page.  The page is
1157  *	removed from the paging queues as if it were wired, and as a
1158  *	consequence of no longer being managed the pageout daemon will not
1159  *	touch it (since there is no way to locate the pte mappings for the
1160  *	page).  madvise() calls that mess with the pmap will also no longer
1161  *	operate on the page.
1162  *
1163  *	Beyond that the page is still reasonably 'normal'.  Freeing the page
1164  *	will clear the flag.
1165  *
1166  *	This routine is used by OBJT_PHYS objects - objects using unswappable
1167  *	physical memory as backing store rather then swap-backed memory and
1168  *	will eventually be extended to support 4MB unmanaged physical
1169  *	mappings.
1170  */
1171 void
1172 vm_page_unmanage(vm_page_t m)
1173 {
1174 
1175 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1176 	if ((m->flags & PG_UNMANAGED) == 0) {
1177 		if (m->wire_count == 0)
1178 			vm_pageq_remove(m);
1179 	}
1180 	vm_page_flag_set(m, PG_UNMANAGED);
1181 }
1182 
1183 /*
1184  *	vm_page_wire:
1185  *
1186  *	Mark this page as wired down by yet
1187  *	another map, removing it from paging queues
1188  *	as necessary.
1189  *
1190  *	The page queues must be locked.
1191  *	This routine may not block.
1192  */
1193 void
1194 vm_page_wire(vm_page_t m)
1195 {
1196 
1197 	/*
1198 	 * Only bump the wire statistics if the page is not already wired,
1199 	 * and only unqueue the page if it is on some queue (if it is unmanaged
1200 	 * it is already off the queues).
1201 	 */
1202 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1203 	if (m->flags & PG_FICTITIOUS)
1204 		return;
1205 	if (m->wire_count == 0) {
1206 		if ((m->flags & PG_UNMANAGED) == 0)
1207 			vm_pageq_remove(m);
1208 		atomic_add_int(&cnt.v_wire_count, 1);
1209 	}
1210 	m->wire_count++;
1211 	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1212 }
1213 
1214 /*
1215  *	vm_page_unwire:
1216  *
1217  *	Release one wiring of this page, potentially
1218  *	enabling it to be paged again.
1219  *
1220  *	Many pages placed on the inactive queue should actually go
1221  *	into the cache, but it is difficult to figure out which.  What
1222  *	we do instead, if the inactive target is well met, is to put
1223  *	clean pages at the head of the inactive queue instead of the tail.
1224  *	This will cause them to be moved to the cache more quickly and
1225  *	if not actively re-referenced, freed more quickly.  If we just
1226  *	stick these pages at the end of the inactive queue, heavy filesystem
1227  *	meta-data accesses can cause an unnecessary paging load on memory bound
1228  *	processes.  This optimization causes one-time-use metadata to be
1229  *	reused more quickly.
1230  *
1231  *	BUT, if we are in a low-memory situation we have no choice but to
1232  *	put clean pages on the cache queue.
1233  *
1234  *	A number of routines use vm_page_unwire() to guarantee that the page
1235  *	will go into either the inactive or active queues, and will NEVER
1236  *	be placed in the cache - for example, just after dirtying a page.
1237  *	dirty pages in the cache are not allowed.
1238  *
1239  *	The page queues must be locked.
1240  *	This routine may not block.
1241  */
1242 void
1243 vm_page_unwire(vm_page_t m, int activate)
1244 {
1245 
1246 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1247 	if (m->flags & PG_FICTITIOUS)
1248 		return;
1249 	if (m->wire_count > 0) {
1250 		m->wire_count--;
1251 		if (m->wire_count == 0) {
1252 			atomic_subtract_int(&cnt.v_wire_count, 1);
1253 			if (m->flags & PG_UNMANAGED) {
1254 				;
1255 			} else if (activate)
1256 				vm_pageq_enqueue(PQ_ACTIVE, m);
1257 			else {
1258 				vm_page_flag_clear(m, PG_WINATCFLS);
1259 				vm_pageq_enqueue(PQ_INACTIVE, m);
1260 			}
1261 		}
1262 	} else {
1263 		panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1264 	}
1265 }
1266 
1267 
1268 /*
1269  * Move the specified page to the inactive queue.  If the page has
1270  * any associated swap, the swap is deallocated.
1271  *
1272  * Normally athead is 0 resulting in LRU operation.  athead is set
1273  * to 1 if we want this page to be 'as if it were placed in the cache',
1274  * except without unmapping it from the process address space.
1275  *
1276  * This routine may not block.
1277  */
1278 static inline void
1279 _vm_page_deactivate(vm_page_t m, int athead)
1280 {
1281 
1282 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1283 
1284 	/*
1285 	 * Ignore if already inactive.
1286 	 */
1287 	if (VM_PAGE_INQUEUE2(m, PQ_INACTIVE))
1288 		return;
1289 	if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1290 		if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1291 			cnt.v_reactivated++;
1292 		vm_page_flag_clear(m, PG_WINATCFLS);
1293 		vm_pageq_remove(m);
1294 		if (athead)
1295 			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1296 		else
1297 			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1298 		VM_PAGE_SETQUEUE2(m, PQ_INACTIVE);
1299 		vm_page_queues[PQ_INACTIVE].lcnt++;
1300 		cnt.v_inactive_count++;
1301 	}
1302 }
1303 
1304 void
1305 vm_page_deactivate(vm_page_t m)
1306 {
1307     _vm_page_deactivate(m, 0);
1308 }
1309 
1310 /*
1311  * vm_page_try_to_cache:
1312  *
1313  * Returns 0 on failure, 1 on success
1314  */
1315 int
1316 vm_page_try_to_cache(vm_page_t m)
1317 {
1318 
1319 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1320 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1321 	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1322 	    (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1323 		return (0);
1324 	}
1325 	pmap_remove_all(m);
1326 	if (m->dirty)
1327 		return (0);
1328 	vm_page_cache(m);
1329 	return (1);
1330 }
1331 
1332 /*
1333  * vm_page_try_to_free()
1334  *
1335  *	Attempt to free the page.  If we cannot free it, we do nothing.
1336  *	1 is returned on success, 0 on failure.
1337  */
1338 int
1339 vm_page_try_to_free(vm_page_t m)
1340 {
1341 
1342 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1343 	if (m->object != NULL)
1344 		VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1345 	if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1346 	    (m->flags & (PG_BUSY|PG_UNMANAGED))) {
1347 		return (0);
1348 	}
1349 	pmap_remove_all(m);
1350 	if (m->dirty)
1351 		return (0);
1352 	vm_page_free(m);
1353 	return (1);
1354 }
1355 
1356 /*
1357  * vm_page_cache
1358  *
1359  * Put the specified page onto the page cache queue (if appropriate).
1360  *
1361  * This routine may not block.
1362  */
1363 void
1364 vm_page_cache(vm_page_t m)
1365 {
1366 
1367 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1368 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1369 	if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
1370 	    m->hold_count || m->wire_count) {
1371 		printf("vm_page_cache: attempting to cache busy page\n");
1372 		return;
1373 	}
1374 	if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1375 		return;
1376 
1377 	/*
1378 	 * Remove all pmaps and indicate that the page is not
1379 	 * writeable or mapped.
1380 	 */
1381 	pmap_remove_all(m);
1382 	if (m->dirty != 0) {
1383 		panic("vm_page_cache: caching a dirty page, pindex: %ld",
1384 			(long)m->pindex);
1385 	}
1386 	vm_pageq_remove_nowakeup(m);
1387 	vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1388 	vm_page_free_wakeup();
1389 }
1390 
1391 /*
1392  * vm_page_dontneed
1393  *
1394  *	Cache, deactivate, or do nothing as appropriate.  This routine
1395  *	is typically used by madvise() MADV_DONTNEED.
1396  *
1397  *	Generally speaking we want to move the page into the cache so
1398  *	it gets reused quickly.  However, this can result in a silly syndrome
1399  *	due to the page recycling too quickly.  Small objects will not be
1400  *	fully cached.  On the otherhand, if we move the page to the inactive
1401  *	queue we wind up with a problem whereby very large objects
1402  *	unnecessarily blow away our inactive and cache queues.
1403  *
1404  *	The solution is to move the pages based on a fixed weighting.  We
1405  *	either leave them alone, deactivate them, or move them to the cache,
1406  *	where moving them to the cache has the highest weighting.
1407  *	By forcing some pages into other queues we eventually force the
1408  *	system to balance the queues, potentially recovering other unrelated
1409  *	space from active.  The idea is to not force this to happen too
1410  *	often.
1411  */
1412 void
1413 vm_page_dontneed(vm_page_t m)
1414 {
1415 	static int dnweight;
1416 	int dnw;
1417 	int head;
1418 
1419 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1420 	dnw = ++dnweight;
1421 
1422 	/*
1423 	 * occassionally leave the page alone
1424 	 */
1425 	if ((dnw & 0x01F0) == 0 ||
1426 	    VM_PAGE_INQUEUE2(m, PQ_INACTIVE) ||
1427 	    VM_PAGE_INQUEUE1(m, PQ_CACHE)
1428 	) {
1429 		if (m->act_count >= ACT_INIT)
1430 			--m->act_count;
1431 		return;
1432 	}
1433 
1434 	if (m->dirty == 0 && pmap_is_modified(m))
1435 		vm_page_dirty(m);
1436 
1437 	if (m->dirty || (dnw & 0x0070) == 0) {
1438 		/*
1439 		 * Deactivate the page 3 times out of 32.
1440 		 */
1441 		head = 0;
1442 	} else {
1443 		/*
1444 		 * Cache the page 28 times out of every 32.  Note that
1445 		 * the page is deactivated instead of cached, but placed
1446 		 * at the head of the queue instead of the tail.
1447 		 */
1448 		head = 1;
1449 	}
1450 	_vm_page_deactivate(m, head);
1451 }
1452 
1453 /*
1454  * Grab a page, waiting until we are waken up due to the page
1455  * changing state.  We keep on waiting, if the page continues
1456  * to be in the object.  If the page doesn't exist, first allocate it
1457  * and then conditionally zero it.
1458  *
1459  * This routine may block.
1460  */
1461 vm_page_t
1462 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1463 {
1464 	vm_page_t m;
1465 
1466 	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1467 retrylookup:
1468 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
1469 		if (vm_page_sleep_if_busy(m, TRUE, "pgrbwt")) {
1470 			if ((allocflags & VM_ALLOC_RETRY) == 0)
1471 				return (NULL);
1472 			goto retrylookup;
1473 		} else {
1474 			vm_page_lock_queues();
1475 			if (allocflags & VM_ALLOC_WIRED)
1476 				vm_page_wire(m);
1477 			if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1478 				vm_page_busy(m);
1479 			vm_page_unlock_queues();
1480 			return (m);
1481 		}
1482 	}
1483 	m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1484 	if (m == NULL) {
1485 		VM_OBJECT_UNLOCK(object);
1486 		VM_WAIT;
1487 		VM_OBJECT_LOCK(object);
1488 		if ((allocflags & VM_ALLOC_RETRY) == 0)
1489 			return (NULL);
1490 		goto retrylookup;
1491 	}
1492 	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1493 		pmap_zero_page(m);
1494 	return (m);
1495 }
1496 
1497 /*
1498  * Mapping function for valid bits or for dirty bits in
1499  * a page.  May not block.
1500  *
1501  * Inputs are required to range within a page.
1502  */
1503 inline int
1504 vm_page_bits(int base, int size)
1505 {
1506 	int first_bit;
1507 	int last_bit;
1508 
1509 	KASSERT(
1510 	    base + size <= PAGE_SIZE,
1511 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
1512 	);
1513 
1514 	if (size == 0)		/* handle degenerate case */
1515 		return (0);
1516 
1517 	first_bit = base >> DEV_BSHIFT;
1518 	last_bit = (base + size - 1) >> DEV_BSHIFT;
1519 
1520 	return ((2 << last_bit) - (1 << first_bit));
1521 }
1522 
1523 /*
1524  *	vm_page_set_validclean:
1525  *
1526  *	Sets portions of a page valid and clean.  The arguments are expected
1527  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1528  *	of any partial chunks touched by the range.  The invalid portion of
1529  *	such chunks will be zero'd.
1530  *
1531  *	This routine may not block.
1532  *
1533  *	(base + size) must be less then or equal to PAGE_SIZE.
1534  */
1535 void
1536 vm_page_set_validclean(vm_page_t m, int base, int size)
1537 {
1538 	int pagebits;
1539 	int frag;
1540 	int endoff;
1541 
1542 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1543 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1544 	if (size == 0)	/* handle degenerate case */
1545 		return;
1546 
1547 	/*
1548 	 * If the base is not DEV_BSIZE aligned and the valid
1549 	 * bit is clear, we have to zero out a portion of the
1550 	 * first block.
1551 	 */
1552 	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1553 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1554 		pmap_zero_page_area(m, frag, base - frag);
1555 
1556 	/*
1557 	 * If the ending offset is not DEV_BSIZE aligned and the
1558 	 * valid bit is clear, we have to zero out a portion of
1559 	 * the last block.
1560 	 */
1561 	endoff = base + size;
1562 	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1563 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1564 		pmap_zero_page_area(m, endoff,
1565 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1566 
1567 	/*
1568 	 * Set valid, clear dirty bits.  If validating the entire
1569 	 * page we can safely clear the pmap modify bit.  We also
1570 	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
1571 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
1572 	 * be set again.
1573 	 *
1574 	 * We set valid bits inclusive of any overlap, but we can only
1575 	 * clear dirty bits for DEV_BSIZE chunks that are fully within
1576 	 * the range.
1577 	 */
1578 	pagebits = vm_page_bits(base, size);
1579 	m->valid |= pagebits;
1580 #if 0	/* NOT YET */
1581 	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1582 		frag = DEV_BSIZE - frag;
1583 		base += frag;
1584 		size -= frag;
1585 		if (size < 0)
1586 			size = 0;
1587 	}
1588 	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1589 #endif
1590 	m->dirty &= ~pagebits;
1591 	if (base == 0 && size == PAGE_SIZE) {
1592 		pmap_clear_modify(m);
1593 		m->oflags &= ~VPO_NOSYNC;
1594 	}
1595 }
1596 
1597 void
1598 vm_page_clear_dirty(vm_page_t m, int base, int size)
1599 {
1600 
1601 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1602 	m->dirty &= ~vm_page_bits(base, size);
1603 }
1604 
1605 /*
1606  *	vm_page_set_invalid:
1607  *
1608  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
1609  *	valid and dirty bits for the effected areas are cleared.
1610  *
1611  *	May not block.
1612  */
1613 void
1614 vm_page_set_invalid(vm_page_t m, int base, int size)
1615 {
1616 	int bits;
1617 
1618 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1619 	bits = vm_page_bits(base, size);
1620 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1621 	if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
1622 		pmap_remove_all(m);
1623 	m->valid &= ~bits;
1624 	m->dirty &= ~bits;
1625 	m->object->generation++;
1626 }
1627 
1628 /*
1629  * vm_page_zero_invalid()
1630  *
1631  *	The kernel assumes that the invalid portions of a page contain
1632  *	garbage, but such pages can be mapped into memory by user code.
1633  *	When this occurs, we must zero out the non-valid portions of the
1634  *	page so user code sees what it expects.
1635  *
1636  *	Pages are most often semi-valid when the end of a file is mapped
1637  *	into memory and the file's size is not page aligned.
1638  */
1639 void
1640 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1641 {
1642 	int b;
1643 	int i;
1644 
1645 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1646 	/*
1647 	 * Scan the valid bits looking for invalid sections that
1648 	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1649 	 * valid bit may be set ) have already been zerod by
1650 	 * vm_page_set_validclean().
1651 	 */
1652 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1653 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
1654 		    (m->valid & (1 << i))
1655 		) {
1656 			if (i > b) {
1657 				pmap_zero_page_area(m,
1658 				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1659 			}
1660 			b = i + 1;
1661 		}
1662 	}
1663 
1664 	/*
1665 	 * setvalid is TRUE when we can safely set the zero'd areas
1666 	 * as being valid.  We can do this if there are no cache consistancy
1667 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1668 	 */
1669 	if (setvalid)
1670 		m->valid = VM_PAGE_BITS_ALL;
1671 }
1672 
1673 /*
1674  *	vm_page_is_valid:
1675  *
1676  *	Is (partial) page valid?  Note that the case where size == 0
1677  *	will return FALSE in the degenerate case where the page is
1678  *	entirely invalid, and TRUE otherwise.
1679  *
1680  *	May not block.
1681  */
1682 int
1683 vm_page_is_valid(vm_page_t m, int base, int size)
1684 {
1685 	int bits = vm_page_bits(base, size);
1686 
1687 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1688 	if (m->valid && ((m->valid & bits) == bits))
1689 		return 1;
1690 	else
1691 		return 0;
1692 }
1693 
1694 /*
1695  * update dirty bits from pmap/mmu.  May not block.
1696  */
1697 void
1698 vm_page_test_dirty(vm_page_t m)
1699 {
1700 	if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1701 		vm_page_dirty(m);
1702 	}
1703 }
1704 
1705 int so_zerocp_fullpage = 0;
1706 
1707 void
1708 vm_page_cowfault(vm_page_t m)
1709 {
1710 	vm_page_t mnew;
1711 	vm_object_t object;
1712 	vm_pindex_t pindex;
1713 
1714 	object = m->object;
1715 	pindex = m->pindex;
1716 
1717  retry_alloc:
1718 	pmap_remove_all(m);
1719 	vm_page_remove(m);
1720 	mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
1721 	if (mnew == NULL) {
1722 		vm_page_insert(m, object, pindex);
1723 		vm_page_unlock_queues();
1724 		VM_OBJECT_UNLOCK(object);
1725 		VM_WAIT;
1726 		VM_OBJECT_LOCK(object);
1727 		vm_page_lock_queues();
1728 		goto retry_alloc;
1729 	}
1730 
1731 	if (m->cow == 0) {
1732 		/*
1733 		 * check to see if we raced with an xmit complete when
1734 		 * waiting to allocate a page.  If so, put things back
1735 		 * the way they were
1736 		 */
1737 		vm_page_free(mnew);
1738 		vm_page_insert(m, object, pindex);
1739 	} else { /* clear COW & copy page */
1740 		if (!so_zerocp_fullpage)
1741 			pmap_copy_page(m, mnew);
1742 		mnew->valid = VM_PAGE_BITS_ALL;
1743 		vm_page_dirty(mnew);
1744 		mnew->wire_count = m->wire_count - m->cow;
1745 		m->wire_count = m->cow;
1746 	}
1747 }
1748 
1749 void
1750 vm_page_cowclear(vm_page_t m)
1751 {
1752 
1753 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1754 	if (m->cow) {
1755 		m->cow--;
1756 		/*
1757 		 * let vm_fault add back write permission  lazily
1758 		 */
1759 	}
1760 	/*
1761 	 *  sf_buf_free() will free the page, so we needn't do it here
1762 	 */
1763 }
1764 
1765 void
1766 vm_page_cowsetup(vm_page_t m)
1767 {
1768 
1769 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1770 	m->cow++;
1771 	pmap_remove_write(m);
1772 }
1773 
1774 #include "opt_ddb.h"
1775 #ifdef DDB
1776 #include <sys/kernel.h>
1777 
1778 #include <ddb/ddb.h>
1779 
1780 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1781 {
1782 	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1783 	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1784 	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1785 	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1786 	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1787 	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1788 	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1789 	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1790 	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1791 	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1792 }
1793 
1794 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1795 {
1796 	int i;
1797 	db_printf("PQ_FREE:");
1798 	for (i = 0; i < PQ_NUMCOLORS; i++) {
1799 		db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1800 	}
1801 	db_printf("\n");
1802 
1803 	db_printf("PQ_CACHE:");
1804 	for (i = 0; i < PQ_NUMCOLORS; i++) {
1805 		db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1806 	}
1807 	db_printf("\n");
1808 
1809 	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1810 		vm_page_queues[PQ_ACTIVE].lcnt,
1811 		vm_page_queues[PQ_INACTIVE].lcnt);
1812 }
1813 #endif /* DDB */
1814