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