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