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