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