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