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