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