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