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