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