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