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