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