uvm_page.c revision 1.14
1/*	$OpenBSD: uvm_page.c,v 1.14 2001/03/22 03:05:56 smart Exp $	*/
2/*	$NetBSD: uvm_page.c,v 1.24 1999/07/22 22:58:38 thorpej Exp $	*/
3
4/*
5 * Copyright (c) 1997 Charles D. Cranor and Washington University.
6 * Copyright (c) 1991, 1993, The Regents of the University of California.
7 *
8 * All rights reserved.
9 *
10 * This code is derived from software contributed to Berkeley by
11 * The Mach Operating System project at Carnegie-Mellon University.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 *    notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 *    notice, this list of conditions and the following disclaimer in the
20 *    documentation and/or other materials provided with the distribution.
21 * 3. All advertising materials mentioning features or use of this software
22 *    must display the following acknowledgement:
23 *	This product includes software developed by Charles D. Cranor,
24 *      Washington University, the University of California, Berkeley and
25 *      its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 *    may be used to endorse or promote products derived from this software
28 *    without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * SUCH DAMAGE.
41 *
42 *	@(#)vm_page.c   8.3 (Berkeley) 3/21/94
43 * from: Id: uvm_page.c,v 1.1.2.18 1998/02/06 05:24:42 chs Exp
44 *
45 *
46 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
47 * All rights reserved.
48 *
49 * Permission to use, copy, modify and distribute this software and
50 * its documentation is hereby granted, provided that both the copyright
51 * notice and this permission notice appear in all copies of the
52 * software, derivative works or modified versions, and any portions
53 * thereof, and that both notices appear in supporting documentation.
54 *
55 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58 *
59 * Carnegie Mellon requests users of this software to return to
60 *
61 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62 *  School of Computer Science
63 *  Carnegie Mellon University
64 *  Pittsburgh PA 15213-3890
65 *
66 * any improvements or extensions that they make and grant Carnegie the
67 * rights to redistribute these changes.
68 */
69
70/*
71 * uvm_page.c: page ops.
72 */
73
74#include <sys/param.h>
75#include <sys/systm.h>
76#include <sys/malloc.h>
77#include <sys/proc.h>
78
79#include <vm/vm.h>
80#include <vm/vm_page.h>
81#include <vm/vm_kern.h>
82
83#define UVM_PAGE                /* pull in uvm_page.h functions */
84#include <uvm/uvm.h>
85
86/*
87 * global vars... XXXCDC: move to uvm. structure.
88 */
89
90/*
91 * physical memory config is stored in vm_physmem.
92 */
93
94struct vm_physseg vm_physmem[VM_PHYSSEG_MAX];	/* XXXCDC: uvm.physmem */
95int vm_nphysseg = 0;				/* XXXCDC: uvm.nphysseg */
96
97/*
98 * local variables
99 */
100
101/*
102 * these variables record the values returned by vm_page_bootstrap,
103 * for debugging purposes.  The implementation of uvm_pageboot_alloc
104 * and pmap_startup here also uses them internally.
105 */
106
107static vaddr_t      virtual_space_start;
108static vaddr_t      virtual_space_end;
109
110/*
111 * we use a hash table with only one bucket during bootup.  we will
112 * later rehash (resize) the hash table once the allocator is ready.
113 * we static allocate the one bootstrap bucket below...
114 */
115
116static struct pglist uvm_bootbucket;
117
118/*
119 * local prototypes
120 */
121
122static void uvm_pageinsert __P((struct vm_page *));
123
124
125/*
126 * inline functions
127 */
128
129/*
130 * uvm_pageinsert: insert a page in the object and the hash table
131 *
132 * => caller must lock object
133 * => caller must lock page queues
134 * => call should have already set pg's object and offset pointers
135 *    and bumped the version counter
136 */
137
138__inline static void
139uvm_pageinsert(pg)
140	struct vm_page *pg;
141{
142	struct pglist *buck;
143	int s;
144
145#ifdef DIAGNOSTIC
146	if (pg->flags & PG_TABLED)
147		panic("uvm_pageinsert: already inserted");
148#endif
149
150	buck = &uvm.page_hash[uvm_pagehash(pg->uobject,pg->offset)];
151	s = splimp();
152	simple_lock(&uvm.hashlock);
153	TAILQ_INSERT_TAIL(buck, pg, hashq);	/* put in hash */
154	simple_unlock(&uvm.hashlock);
155	splx(s);
156
157	TAILQ_INSERT_TAIL(&pg->uobject->memq, pg, listq); /* put in object */
158	pg->flags |= PG_TABLED;
159	pg->uobject->uo_npages++;
160
161}
162
163/*
164 * uvm_page_remove: remove page from object and hash
165 *
166 * => caller must lock object
167 * => caller must lock page queues
168 */
169
170void __inline
171uvm_pageremove(pg)
172	struct vm_page *pg;
173{
174	struct pglist *buck;
175	int s;
176
177#ifdef DIAGNOSTIC
178	if ((pg->flags & (PG_FAULTING)) != 0)
179		panic("uvm_pageremove: page is faulting");
180#endif
181
182	if ((pg->flags & PG_TABLED) == 0)
183		return;				/* XXX: log */
184
185	buck = &uvm.page_hash[uvm_pagehash(pg->uobject,pg->offset)];
186	s = splimp();
187	simple_lock(&uvm.hashlock);
188	TAILQ_REMOVE(buck, pg, hashq);
189	simple_unlock(&uvm.hashlock);
190	splx(s);
191
192	/* object should be locked */
193	TAILQ_REMOVE(&pg->uobject->memq, pg, listq);
194
195	pg->flags &= ~PG_TABLED;
196	pg->uobject->uo_npages--;
197	pg->uobject = NULL;
198	pg->version++;
199
200}
201
202/*
203 * uvm_page_init: init the page system.   called from uvm_init().
204 *
205 * => we return the range of kernel virtual memory in kvm_startp/kvm_endp
206 */
207
208void
209uvm_page_init(kvm_startp, kvm_endp)
210	vaddr_t *kvm_startp, *kvm_endp;
211{
212	int freepages, pagecount;
213	vm_page_t pagearray;
214	int lcv, n, i;
215	paddr_t paddr;
216
217
218	/*
219	 * step 1: init the page queues and page queue locks
220	 */
221	for (lcv = 0; lcv < VM_NFREELIST; lcv++)
222	  TAILQ_INIT(&uvm.page_free[lcv]);
223	TAILQ_INIT(&uvm.page_active);
224	TAILQ_INIT(&uvm.page_inactive_swp);
225	TAILQ_INIT(&uvm.page_inactive_obj);
226	simple_lock_init(&uvm.pageqlock);
227	simple_lock_init(&uvm.fpageqlock);
228
229	/*
230	 * step 2: init the <obj,offset> => <page> hash table. for now
231	 * we just have one bucket (the bootstrap bucket).   later on we
232	 * will allocate new buckets as we dynamically resize the hash table.
233	 */
234
235	uvm.page_nhash = 1;			/* 1 bucket */
236	uvm.page_hashmask = 0;		/* mask for hash function */
237	uvm.page_hash = &uvm_bootbucket;	/* install bootstrap bucket */
238	TAILQ_INIT(uvm.page_hash);		/* init hash table */
239	simple_lock_init(&uvm.hashlock);	/* init hash table lock */
240
241	/*
242	 * step 3: allocate vm_page structures.
243	 */
244
245	/*
246	 * sanity check:
247	 * before calling this function the MD code is expected to register
248	 * some free RAM with the uvm_page_physload() function.   our job
249	 * now is to allocate vm_page structures for this memory.
250	 */
251
252	if (vm_nphysseg == 0)
253		panic("vm_page_bootstrap: no memory pre-allocated");
254
255	/*
256	 * first calculate the number of free pages...
257	 *
258	 * note that we use start/end rather than avail_start/avail_end.
259	 * this allows us to allocate extra vm_page structures in case we
260	 * want to return some memory to the pool after booting.
261	 */
262
263	freepages = 0;
264	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
265		freepages += (vm_physmem[lcv].end - vm_physmem[lcv].start);
266
267	/*
268	 * we now know we have (PAGE_SIZE * freepages) bytes of memory we can
269	 * use.   for each page of memory we use we need a vm_page structure.
270	 * thus, the total number of pages we can use is the total size of
271	 * the memory divided by the PAGE_SIZE plus the size of the vm_page
272	 * structure.   we add one to freepages as a fudge factor to avoid
273	 * truncation errors (since we can only allocate in terms of whole
274	 * pages).
275	 */
276
277	pagecount = ((freepages + 1) << PAGE_SHIFT) /
278	    (PAGE_SIZE + sizeof(struct vm_page));
279	pagearray = (vm_page_t)uvm_pageboot_alloc(pagecount *
280	    sizeof(struct vm_page));
281	memset(pagearray, 0, pagecount * sizeof(struct vm_page));
282
283	/*
284	 * step 4: init the vm_page structures and put them in the correct
285	 * place...
286	 */
287
288	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++) {
289
290		n = vm_physmem[lcv].end - vm_physmem[lcv].start;
291		if (n > pagecount) {
292			printf("uvm_page_init: lost %d page(s) in init\n",
293			    n - pagecount);
294			panic("uvm_page_init");  /* XXXCDC: shouldn't happen? */
295			/* n = pagecount; */
296		}
297		/* set up page array pointers */
298		vm_physmem[lcv].pgs = pagearray;
299		pagearray += n;
300		pagecount -= n;
301		vm_physmem[lcv].lastpg = vm_physmem[lcv].pgs + (n - 1);
302
303		/* init and free vm_pages (we've already zeroed them) */
304		paddr = ptoa(vm_physmem[lcv].start);
305		for (i = 0 ; i < n ; i++, paddr += PAGE_SIZE) {
306			vm_physmem[lcv].pgs[i].phys_addr = paddr;
307			if (atop(paddr) >= vm_physmem[lcv].avail_start &&
308			    atop(paddr) <= vm_physmem[lcv].avail_end) {
309				uvmexp.npages++;
310				/* add page to free pool */
311				uvm_pagefree(&vm_physmem[lcv].pgs[i]);
312			}
313		}
314	}
315	/*
316	 * step 5: pass up the values of virtual_space_start and
317	 * virtual_space_end (obtained by uvm_pageboot_alloc) to the upper
318	 * layers of the VM.
319	 */
320
321	*kvm_startp = round_page(virtual_space_start);
322	*kvm_endp = trunc_page(virtual_space_end);
323
324	/*
325	 * step 6: init pagedaemon lock
326	 */
327
328	simple_lock_init(&uvm.pagedaemon_lock);
329
330	/*
331	 * step 7: init reserve thresholds
332	 * XXXCDC - values may need adjusting
333	 */
334	uvmexp.reserve_pagedaemon = 4;
335	uvmexp.reserve_kernel = 6;
336
337	/*
338	 * done!
339	 */
340
341}
342
343/*
344 * uvm_setpagesize: set the page size
345 *
346 * => sets page_shift and page_mask from uvmexp.pagesize.
347 * => XXXCDC: move global vars.
348 */
349
350void
351uvm_setpagesize()
352{
353	if (uvmexp.pagesize == 0)
354		uvmexp.pagesize = DEFAULT_PAGE_SIZE;
355	uvmexp.pagemask = uvmexp.pagesize - 1;
356	if ((uvmexp.pagemask & uvmexp.pagesize) != 0)
357		panic("uvm_setpagesize: page size not a power of two");
358	for (uvmexp.pageshift = 0; ; uvmexp.pageshift++)
359		if ((1 << uvmexp.pageshift) == uvmexp.pagesize)
360			break;
361}
362
363/*
364 * uvm_pageboot_alloc: steal memory from physmem for bootstrapping
365 */
366
367vaddr_t
368uvm_pageboot_alloc(size)
369	vsize_t size;
370{
371#if defined(PMAP_STEAL_MEMORY)
372	vaddr_t addr;
373
374	/*
375	 * defer bootstrap allocation to MD code (it may want to allocate
376	 * from a direct-mapped segment).  pmap_steal_memory should round
377	 * off virtual_space_start/virtual_space_end.
378	 */
379
380	addr = pmap_steal_memory(size, &virtual_space_start,
381	    &virtual_space_end);
382
383	return(addr);
384
385#else /* !PMAP_STEAL_MEMORY */
386
387	static boolean_t initialized = FALSE;
388	vaddr_t addr, vaddr;
389	paddr_t paddr;
390
391	/* round to page size */
392	size = round_page(size);
393
394	/*
395	 * on first call to this function, initialize ourselves.
396	 */
397	if (initialized == FALSE) {
398		pmap_virtual_space(&virtual_space_start, &virtual_space_end);
399
400		/* round it the way we like it */
401		virtual_space_start = round_page(virtual_space_start);
402		virtual_space_end = trunc_page(virtual_space_end);
403
404		initialized = TRUE;
405	}
406
407	/*
408	 * allocate virtual memory for this request
409	 */
410	if (virtual_space_start == virtual_space_end ||
411	    (virtual_space_end - virtual_space_start) < size)
412		panic("uvm_pageboot_alloc: out of virtual space");
413
414	addr = virtual_space_start;
415
416#ifdef PMAP_GROWKERNEL
417	/*
418	 * If the kernel pmap can't map the requested space,
419	 * then allocate more resources for it.
420	 */
421	if (uvm_maxkaddr < (addr + size)) {
422		uvm_maxkaddr = pmap_growkernel(addr + size);
423		if (uvm_maxkaddr < (addr + size))
424			panic("uvm_pageboot_alloc: pmap_growkernel() failed");
425	}
426#endif
427
428	virtual_space_start += size;
429
430	/*
431	 * allocate and mapin physical pages to back new virtual pages
432	 */
433
434	for (vaddr = round_page(addr) ; vaddr < addr + size ;
435	    vaddr += PAGE_SIZE) {
436
437		if (!uvm_page_physget(&paddr))
438			panic("uvm_pageboot_alloc: out of memory");
439
440		/* XXX: should be wired, but some pmaps don't like that ... */
441#if defined(PMAP_NEW)
442		/*
443		 * Note this memory is no longer managed, so using
444		 * pmap_kenter is safe.
445		 */
446		pmap_kenter_pa(vaddr, paddr, VM_PROT_READ|VM_PROT_WRITE);
447#else
448		pmap_enter(pmap_kernel(), vaddr, paddr,
449		    VM_PROT_READ|VM_PROT_WRITE, FALSE,
450		    VM_PROT_READ|VM_PROT_WRITE);
451#endif
452
453	}
454	return(addr);
455#endif	/* PMAP_STEAL_MEMORY */
456}
457
458#if !defined(PMAP_STEAL_MEMORY)
459/*
460 * uvm_page_physget: "steal" one page from the vm_physmem structure.
461 *
462 * => attempt to allocate it off the end of a segment in which the "avail"
463 *    values match the start/end values.   if we can't do that, then we
464 *    will advance both values (making them equal, and removing some
465 *    vm_page structures from the non-avail area).
466 * => return false if out of memory.
467 */
468
469boolean_t
470uvm_page_physget(paddrp)
471	paddr_t *paddrp;
472{
473	int lcv, x;
474
475	/* pass 1: try allocating from a matching end */
476#if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST) || \
477	(VM_PHYSSEG_STRAT == VM_PSTRAT_BSEARCH)
478	for (lcv = vm_nphysseg - 1 ; lcv >= 0 ; lcv--)
479#else
480	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
481#endif
482	{
483
484		if (vm_physmem[lcv].pgs)
485			panic("vm_page_physget: called _after_ bootstrap");
486
487		/* try from front */
488		if (vm_physmem[lcv].avail_start == vm_physmem[lcv].start &&
489		    vm_physmem[lcv].avail_start < vm_physmem[lcv].avail_end) {
490			*paddrp = ptoa(vm_physmem[lcv].avail_start);
491			vm_physmem[lcv].avail_start++;
492			vm_physmem[lcv].start++;
493			/* nothing left?   nuke it */
494			if (vm_physmem[lcv].avail_start ==
495			    vm_physmem[lcv].end) {
496				if (vm_nphysseg == 1)
497				    panic("vm_page_physget: out of memory!");
498				vm_nphysseg--;
499				for (x = lcv ; x < vm_nphysseg ; x++)
500					/* structure copy */
501					vm_physmem[x] = vm_physmem[x+1];
502			}
503			return (TRUE);
504		}
505
506		/* try from rear */
507		if (vm_physmem[lcv].avail_end == vm_physmem[lcv].end &&
508		    vm_physmem[lcv].avail_start < vm_physmem[lcv].avail_end) {
509			*paddrp = ptoa(vm_physmem[lcv].avail_end - 1);
510			vm_physmem[lcv].avail_end--;
511			vm_physmem[lcv].end--;
512			/* nothing left?   nuke it */
513			if (vm_physmem[lcv].avail_end ==
514			    vm_physmem[lcv].start) {
515				if (vm_nphysseg == 1)
516				    panic("vm_page_physget: out of memory!");
517				vm_nphysseg--;
518				for (x = lcv ; x < vm_nphysseg ; x++)
519					/* structure copy */
520					vm_physmem[x] = vm_physmem[x+1];
521			}
522			return (TRUE);
523		}
524	}
525
526	/* pass2: forget about matching ends, just allocate something */
527#if (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST) || \
528	(VM_PHYSSEG_STRAT == VM_PSTRAT_BSEARCH)
529	for (lcv = vm_nphysseg - 1 ; lcv >= 0 ; lcv--)
530#else
531	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
532#endif
533	{
534
535		/* any room in this bank? */
536		if (vm_physmem[lcv].avail_start >= vm_physmem[lcv].avail_end)
537			continue;  /* nope */
538
539		*paddrp = ptoa(vm_physmem[lcv].avail_start);
540		vm_physmem[lcv].avail_start++;
541		/* truncate! */
542		vm_physmem[lcv].start = vm_physmem[lcv].avail_start;
543
544		/* nothing left?   nuke it */
545		if (vm_physmem[lcv].avail_start == vm_physmem[lcv].end) {
546			if (vm_nphysseg == 1)
547				panic("vm_page_physget: out of memory!");
548			vm_nphysseg--;
549			for (x = lcv ; x < vm_nphysseg ; x++)
550				/* structure copy */
551				vm_physmem[x] = vm_physmem[x+1];
552		}
553		return (TRUE);
554	}
555
556	return (FALSE);        /* whoops! */
557}
558#endif /* PMAP_STEAL_MEMORY */
559
560/*
561 * uvm_page_physload: load physical memory into VM system
562 *
563 * => all args are PFs
564 * => all pages in start/end get vm_page structures
565 * => areas marked by avail_start/avail_end get added to the free page pool
566 * => we are limited to VM_PHYSSEG_MAX physical memory segments
567 */
568
569void
570uvm_page_physload(start, end, avail_start, avail_end, free_list)
571	vaddr_t start, end, avail_start, avail_end;
572	int free_list;
573{
574	int preload, lcv;
575	psize_t npages;
576	struct vm_page *pgs;
577	struct vm_physseg *ps;
578
579	if (uvmexp.pagesize == 0)
580		panic("vm_page_physload: page size not set!");
581
582	if (free_list >= VM_NFREELIST || free_list < VM_FREELIST_DEFAULT)
583		panic("uvm_page_physload: bad free list %d\n", free_list);
584
585	/*
586	 * do we have room?
587	 */
588	if (vm_nphysseg == VM_PHYSSEG_MAX) {
589		printf("vm_page_physload: unable to load physical memory "
590		    "segment\n");
591		printf("\t%d segments allocated, ignoring 0x%lx -> 0x%lx\n",
592		    VM_PHYSSEG_MAX, start, end);
593		return;
594	}
595
596	/*
597	 * check to see if this is a "preload" (i.e. uvm_mem_init hasn't been
598	 * called yet, so malloc is not available).
599	 */
600	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++) {
601		if (vm_physmem[lcv].pgs)
602			break;
603	}
604	preload = (lcv == vm_nphysseg);
605
606	/*
607	 * if VM is already running, attempt to malloc() vm_page structures
608	 */
609	if (!preload) {
610#if defined(VM_PHYSSEG_NOADD)
611		panic("vm_page_physload: tried to add RAM after vm_mem_init");
612#else
613		/* XXXCDC: need some sort of lockout for this case */
614		paddr_t paddr;
615		npages = end - start;  /* # of pages */
616		MALLOC(pgs, struct vm_page *, sizeof(struct vm_page) * npages,
617					 M_VMPAGE, M_NOWAIT);
618		if (pgs == NULL) {
619			printf("vm_page_physload: can not malloc vm_page "
620			    "structs for segment\n");
621			printf("\tignoring 0x%lx -> 0x%lx\n", start, end);
622			return;
623		}
624		/* zero data, init phys_addr and free_list, and free pages */
625		memset(pgs, 0, sizeof(struct vm_page) * npages);
626		for (lcv = 0, paddr = ptoa(start) ;
627				 lcv < npages ; lcv++, paddr += PAGE_SIZE) {
628			pgs[lcv].phys_addr = paddr;
629			pgs[lcv].free_list = free_list;
630			if (atop(paddr) >= avail_start &&
631			    atop(paddr) <= avail_end)
632				uvm_pagefree(&pgs[lcv]);
633		}
634		/* XXXCDC: incomplete: need to update uvmexp.free, what else? */
635		/* XXXCDC: need hook to tell pmap to rebuild pv_list, etc... */
636#endif
637	} else {
638
639		/* gcc complains if these don't get init'd */
640		pgs = NULL;
641		npages = 0;
642
643	}
644
645	/*
646	 * now insert us in the proper place in vm_physmem[]
647	 */
648
649#if (VM_PHYSSEG_STRAT == VM_PSTRAT_RANDOM)
650
651	/* random: put it at the end (easy!) */
652	ps = &vm_physmem[vm_nphysseg];
653
654#elif (VM_PHYSSEG_STRAT == VM_PSTRAT_BSEARCH)
655
656	{
657		int x;
658		/* sort by address for binary search */
659		for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
660			if (start < vm_physmem[lcv].start)
661				break;
662		ps = &vm_physmem[lcv];
663		/* move back other entries, if necessary ... */
664		for (x = vm_nphysseg ; x > lcv ; x--)
665			/* structure copy */
666			vm_physmem[x] = vm_physmem[x - 1];
667	}
668
669#elif (VM_PHYSSEG_STRAT == VM_PSTRAT_BIGFIRST)
670
671	{
672		int x;
673		/* sort by largest segment first */
674		for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
675			if ((end - start) >
676			    (vm_physmem[lcv].end - vm_physmem[lcv].start))
677				break;
678		ps = &vm_physmem[lcv];
679		/* move back other entries, if necessary ... */
680		for (x = vm_nphysseg ; x > lcv ; x--)
681			/* structure copy */
682			vm_physmem[x] = vm_physmem[x - 1];
683	}
684
685#else
686
687	panic("vm_page_physload: unknown physseg strategy selected!");
688
689#endif
690
691	ps->start = start;
692	ps->end = end;
693	ps->avail_start = avail_start;
694	ps->avail_end = avail_end;
695	if (preload) {
696		ps->pgs = NULL;
697	} else {
698		ps->pgs = pgs;
699		ps->lastpg = pgs + npages - 1;
700	}
701	ps->free_list = free_list;
702	vm_nphysseg++;
703
704	/*
705	 * done!
706	 */
707
708	if (!preload)
709		uvm_page_rehash();
710
711	return;
712}
713
714/*
715 * uvm_page_rehash: reallocate hash table based on number of free pages.
716 */
717
718void
719uvm_page_rehash()
720{
721	int freepages, lcv, bucketcount, s, oldcount;
722	struct pglist *newbuckets, *oldbuckets;
723	struct vm_page *pg;
724
725	/*
726	 * compute number of pages that can go in the free pool
727	 */
728
729	freepages = 0;
730	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
731		freepages +=
732		    (vm_physmem[lcv].avail_end - vm_physmem[lcv].avail_start);
733
734	/*
735	 * compute number of buckets needed for this number of pages
736	 */
737
738	bucketcount = 1;
739	while (bucketcount < freepages)
740		bucketcount = bucketcount * 2;
741
742	/*
743	 * malloc new buckets
744	 */
745
746	MALLOC(newbuckets, struct pglist *, sizeof(struct pglist) * bucketcount,
747					 M_VMPBUCKET, M_NOWAIT);
748	if (newbuckets == NULL) {
749		printf("uvm_page_physrehash: WARNING: could not grow page "
750		    "hash table\n");
751		return;
752	}
753	for (lcv = 0 ; lcv < bucketcount ; lcv++)
754		TAILQ_INIT(&newbuckets[lcv]);
755
756	/*
757	 * now replace the old buckets with the new ones and rehash everything
758	 */
759
760	s = splimp();
761	simple_lock(&uvm.hashlock);
762	/* swap old for new ... */
763	oldbuckets = uvm.page_hash;
764	oldcount = uvm.page_nhash;
765	uvm.page_hash = newbuckets;
766	uvm.page_nhash = bucketcount;
767	uvm.page_hashmask = bucketcount - 1;  /* power of 2 */
768
769	/* ... and rehash */
770	for (lcv = 0 ; lcv < oldcount ; lcv++) {
771		while ((pg = oldbuckets[lcv].tqh_first) != NULL) {
772			TAILQ_REMOVE(&oldbuckets[lcv], pg, hashq);
773			TAILQ_INSERT_TAIL(
774			  &uvm.page_hash[uvm_pagehash(pg->uobject, pg->offset)],
775			  pg, hashq);
776		}
777	}
778	simple_unlock(&uvm.hashlock);
779	splx(s);
780
781	/*
782	 * free old bucket array if is not the boot-time table
783	 */
784
785	if (oldbuckets != &uvm_bootbucket)
786		FREE(oldbuckets, M_VMPBUCKET);
787
788	/*
789	 * done
790	 */
791	return;
792}
793
794
795#if 1 /* XXXCDC: TMP TMP TMP DEBUG DEBUG DEBUG */
796
797void uvm_page_physdump __P((void)); /* SHUT UP GCC */
798
799/* call from DDB */
800void
801uvm_page_physdump()
802{
803	int lcv;
804
805	printf("rehash: physical memory config [segs=%d of %d]:\n",
806				 vm_nphysseg, VM_PHYSSEG_MAX);
807	for (lcv = 0 ; lcv < vm_nphysseg ; lcv++)
808		printf("0x%lx->0x%lx [0x%lx->0x%lx]\n", vm_physmem[lcv].start,
809		    vm_physmem[lcv].end, vm_physmem[lcv].avail_start,
810		    vm_physmem[lcv].avail_end);
811	printf("STRATEGY = ");
812	switch (VM_PHYSSEG_STRAT) {
813	case VM_PSTRAT_RANDOM: printf("RANDOM\n"); break;
814	case VM_PSTRAT_BSEARCH: printf("BSEARCH\n"); break;
815	case VM_PSTRAT_BIGFIRST: printf("BIGFIRST\n"); break;
816	default: printf("<<UNKNOWN>>!!!!\n");
817	}
818	printf("number of buckets = %d\n", uvm.page_nhash);
819}
820#endif
821
822/*
823 * uvm_pagealloc_strat: allocate vm_page from a particular free list.
824 *
825 * => return null if no pages free
826 * => wake up pagedaemon if number of free pages drops below low water mark
827 * => if obj != NULL, obj must be locked (to put in hash)
828 * => if anon != NULL, anon must be locked (to put in anon)
829 * => only one of obj or anon can be non-null
830 * => caller must activate/deactivate page if it is not wired.
831 * => free_list is ignored if strat == UVM_PGA_STRAT_NORMAL.
832 */
833
834struct vm_page *
835uvm_pagealloc_strat(obj, off, anon, flags, strat, free_list)
836	struct uvm_object *obj;
837	vaddr_t off;
838	int flags;
839	struct vm_anon *anon;
840	int strat, free_list;
841{
842	int lcv, s;
843	struct vm_page *pg;
844	struct pglist *freeq;
845	boolean_t use_reserve;
846
847#ifdef DIAGNOSTIC
848	/* sanity check */
849	if (obj && anon)
850		panic("uvm_pagealloc: obj and anon != NULL");
851#endif
852
853	s = uvm_lock_fpageq();		/* lock free page queue */
854
855	/*
856	 * check to see if we need to generate some free pages waking
857	 * the pagedaemon.
858	 */
859
860	if (uvmexp.free < uvmexp.freemin || (uvmexp.free < uvmexp.freetarg &&
861	    uvmexp.inactive < uvmexp.inactarg))
862		wakeup(&uvm.pagedaemon);
863
864	/*
865	 * fail if any of these conditions is true:
866	 * [1]  there really are no free pages, or
867	 * [2]  only kernel "reserved" pages remain and
868	 *        the page isn't being allocated to a kernel object.
869	 * [3]  only pagedaemon "reserved" pages remain and
870	 *        the requestor isn't the pagedaemon.
871	 */
872
873	use_reserve = (flags & UVM_PGA_USERESERVE) ||
874		(obj && UVM_OBJ_IS_KERN_OBJECT(obj));
875	if ((uvmexp.free <= uvmexp.reserve_kernel && !use_reserve) ||
876	    (uvmexp.free <= uvmexp.reserve_pagedaemon &&
877	     !(use_reserve && (curproc == uvm.pagedaemon_proc ||
878				curproc == syncerproc))))
879		goto fail;
880
881 again:
882	switch (strat) {
883	case UVM_PGA_STRAT_NORMAL:
884		/* Check all freelists in descending priority order. */
885		for (lcv = 0; lcv < VM_NFREELIST; lcv++) {
886			freeq = &uvm.page_free[lcv];
887			if ((pg = freeq->tqh_first) != NULL)
888				goto gotit;
889		}
890
891		/* No pages free! */
892		goto fail;
893
894	case UVM_PGA_STRAT_ONLY:
895	case UVM_PGA_STRAT_FALLBACK:
896		/* Attempt to allocate from the specified free list. */
897#ifdef DIAGNOSTIC
898		if (free_list >= VM_NFREELIST || free_list < 0)
899			panic("uvm_pagealloc_strat: bad free list %d",
900			    free_list);
901#endif
902		freeq = &uvm.page_free[free_list];
903		if ((pg = freeq->tqh_first) != NULL)
904			goto gotit;
905
906		/* Fall back, if possible. */
907		if (strat == UVM_PGA_STRAT_FALLBACK) {
908			strat = UVM_PGA_STRAT_NORMAL;
909			goto again;
910		}
911
912		/* No pages free! */
913		goto fail;
914
915	default:
916		panic("uvm_pagealloc_strat: bad strat %d", strat);
917		/* NOTREACHED */
918	}
919
920 gotit:
921	TAILQ_REMOVE(freeq, pg, pageq);
922	uvmexp.free--;
923
924	uvm_unlock_fpageq(s);		/* unlock free page queue */
925
926	pg->offset = off;
927	pg->uobject = obj;
928	pg->uanon = anon;
929	pg->flags = PG_BUSY|PG_CLEAN|PG_FAKE;
930	pg->version++;
931	pg->wire_count = 0;
932	pg->loan_count = 0;
933	if (anon) {
934		anon->u.an_page = pg;
935		pg->pqflags = PQ_ANON;
936	} else {
937		if (obj)
938			uvm_pageinsert(pg);
939		pg->pqflags = 0;
940	}
941#if defined(UVM_PAGE_TRKOWN)
942	pg->owner_tag = NULL;
943#endif
944	UVM_PAGE_OWN(pg, "new alloc");
945
946	return(pg);
947
948 fail:
949	uvm_unlock_fpageq(s);
950	return (NULL);
951}
952
953/*
954 * uvm_pagealloc_contig: allocate contiguous memory.
955 *
956 * XXX - fix comment.
957 */
958
959vaddr_t
960uvm_pagealloc_contig(size, low, high, alignment)
961	vaddr_t size;
962	vaddr_t low, high;
963	vaddr_t alignment;
964{
965	struct pglist pglist;
966	struct vm_page *pg;
967	vaddr_t addr, temp_addr;
968
969	size = round_page(size);
970
971	TAILQ_INIT(&pglist);
972	if (uvm_pglistalloc(size, low, high, alignment, 0,
973			    &pglist, 1, FALSE))
974		return 0;
975	addr = vm_map_min(kernel_map);
976	if (uvm_map(kernel_map, &addr, size, NULL, UVM_UNKNOWN_OFFSET,
977		    UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
978				UVM_ADV_RANDOM, 0)) != KERN_SUCCESS) {
979		uvm_pglistfree(&pglist);
980		return 0;
981	}
982	temp_addr = addr;
983	for (pg = TAILQ_FIRST(&pglist); pg != NULL;
984	     pg = TAILQ_NEXT(pg, pageq)) {
985	        pg->uobject = uvm.kernel_object;
986		pg->offset = temp_addr - vm_map_min(kernel_map);
987		uvm_pageinsert(pg);
988		uvm_pagewire(pg);
989#if defined(PMAP_NEW)
990		pmap_kenter_pa(temp_addr, VM_PAGE_TO_PHYS(pg),
991			       VM_PROT_READ|VM_PROT_WRITE);
992#else
993		pmap_enter(pmap_kernel(), temp_addr, VM_PAGE_TO_PHYS(pg),
994			   VM_PROT_READ|VM_PROT_WRITE, TRUE,
995			   VM_PROT_READ|VM_PROT_WRITE);
996#endif
997		temp_addr += PAGE_SIZE;
998	}
999	return addr;
1000}
1001
1002/*
1003 * uvm_pagerealloc: reallocate a page from one object to another
1004 *
1005 * => both objects must be locked
1006 */
1007
1008void
1009uvm_pagerealloc(pg, newobj, newoff)
1010	struct vm_page *pg;
1011	struct uvm_object *newobj;
1012	vaddr_t newoff;
1013{
1014	/*
1015	 * remove it from the old object
1016	 */
1017
1018	if (pg->uobject) {
1019		uvm_pageremove(pg);
1020	}
1021
1022	/*
1023	 * put it in the new object
1024	 */
1025
1026	if (newobj) {
1027		pg->uobject = newobj;
1028		pg->offset = newoff;
1029		pg->version++;
1030		uvm_pageinsert(pg);
1031	}
1032
1033	return;
1034}
1035
1036
1037/*
1038 * uvm_pagefree: free page
1039 *
1040 * => erase page's identity (i.e. remove from hash/object)
1041 * => put page on free list
1042 * => caller must lock owning object (either anon or uvm_object)
1043 * => caller must lock page queues
1044 * => assumes all valid mappings of pg are gone
1045 */
1046
1047void uvm_pagefree(pg)
1048
1049struct vm_page *pg;
1050
1051{
1052	int s;
1053	int saved_loan_count = pg->loan_count;
1054
1055	/*
1056	 * if the page was an object page (and thus "TABLED"), remove it
1057	 * from the object.
1058	 */
1059
1060	if (pg->flags & PG_TABLED) {
1061
1062		/*
1063		 * if the object page is on loan we are going to drop ownership.
1064		 * it is possible that an anon will take over as owner for this
1065		 * page later on.   the anon will want a !PG_CLEAN page so that
1066		 * it knows it needs to allocate swap if it wants to page the
1067		 * page out.
1068		 */
1069
1070		if (saved_loan_count)
1071			pg->flags &= ~PG_CLEAN;	/* in case an anon takes over */
1072
1073		uvm_pageremove(pg);
1074
1075		/*
1076		 * if our page was on loan, then we just lost control over it
1077		 * (in fact, if it was loaned to an anon, the anon may have
1078		 * already taken over ownership of the page by now and thus
1079		 * changed the loan_count [e.g. in uvmfault_anonget()]) we just
1080		 * return (when the last loan is dropped, then the page can be
1081		 * freed by whatever was holding the last loan).
1082		 */
1083		if (saved_loan_count)
1084			return;
1085
1086	} else if (saved_loan_count && (pg->pqflags & PQ_ANON)) {
1087
1088		/*
1089		 * if our page is owned by an anon and is loaned out to the
1090		 * kernel then we just want to drop ownership and return.
1091		 * the kernel must free the page when all its loans clear ...
1092		 * note that the kernel can't change the loan status of our
1093		 * page as long as we are holding PQ lock.
1094		 */
1095		pg->pqflags &= ~PQ_ANON;
1096		pg->uanon = NULL;
1097		return;
1098	}
1099
1100#ifdef DIAGNOSTIC
1101	if (saved_loan_count) {
1102		printf("uvm_pagefree: warning: freeing page with a loan "
1103		    "count of %d\n", saved_loan_count);
1104		panic("uvm_pagefree: loan count");
1105	}
1106#endif
1107
1108
1109	/*
1110	 * now remove the page from the queues
1111	 */
1112
1113	if (pg->pqflags & PQ_ACTIVE) {
1114		TAILQ_REMOVE(&uvm.page_active, pg, pageq);
1115		pg->pqflags &= ~PQ_ACTIVE;
1116		uvmexp.active--;
1117	}
1118	if (pg->pqflags & PQ_INACTIVE) {
1119		if (pg->pqflags & PQ_SWAPBACKED)
1120			TAILQ_REMOVE(&uvm.page_inactive_swp, pg, pageq);
1121		else
1122			TAILQ_REMOVE(&uvm.page_inactive_obj, pg, pageq);
1123		pg->pqflags &= ~PQ_INACTIVE;
1124		uvmexp.inactive--;
1125	}
1126
1127	/*
1128	 * if the page was wired, unwire it now.
1129	 */
1130	if (pg->wire_count)
1131	{
1132		pg->wire_count = 0;
1133		uvmexp.wired--;
1134	}
1135
1136	/*
1137	 * and put on free queue
1138	 */
1139
1140	s = uvm_lock_fpageq();
1141	TAILQ_INSERT_TAIL(&uvm.page_free[uvm_page_lookup_freelist(pg)],
1142	    pg, pageq);
1143	pg->pqflags = PQ_FREE;
1144#ifdef DEBUG
1145	pg->uobject = (void *)0xdeadbeef;
1146	pg->offset = 0xdeadbeef;
1147	pg->uanon = (void *)0xdeadbeef;
1148#endif
1149	uvmexp.free++;
1150	uvm_unlock_fpageq(s);
1151}
1152
1153#if defined(UVM_PAGE_TRKOWN)
1154/*
1155 * uvm_page_own: set or release page ownership
1156 *
1157 * => this is a debugging function that keeps track of who sets PG_BUSY
1158 *	and where they do it.   it can be used to track down problems
1159 *	such a process setting "PG_BUSY" and never releasing it.
1160 * => page's object [if any] must be locked
1161 * => if "tag" is NULL then we are releasing page ownership
1162 */
1163void
1164uvm_page_own(pg, tag)
1165	struct vm_page *pg;
1166	char *tag;
1167{
1168	/* gain ownership? */
1169	if (tag) {
1170		if (pg->owner_tag) {
1171			printf("uvm_page_own: page %p already owned "
1172			    "by proc %d [%s]\n", pg,
1173			     pg->owner, pg->owner_tag);
1174			panic("uvm_page_own");
1175		}
1176		pg->owner = (curproc) ? curproc->p_pid :  (pid_t) -1;
1177		pg->owner_tag = tag;
1178		return;
1179	}
1180
1181	/* drop ownership */
1182	if (pg->owner_tag == NULL) {
1183		printf("uvm_page_own: dropping ownership of an non-owned "
1184		    "page (%p)\n", pg);
1185		panic("uvm_page_own");
1186	}
1187	pg->owner_tag = NULL;
1188	return;
1189}
1190#endif
1191