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