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