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