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