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