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