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