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