xref: /titanic_52/usr/src/uts/sun4/vm/sfmmu.c (revision c7158ae983f5a04c4a998f468ecefba6d23ba721)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <vm/hat.h>
30 #include <vm/hat_sfmmu.h>
31 #include <vm/page.h>
32 #include <sys/pte.h>
33 #include <sys/systm.h>
34 #include <sys/mman.h>
35 #include <sys/sysmacros.h>
36 #include <sys/machparam.h>
37 #include <sys/vtrace.h>
38 #include <sys/kmem.h>
39 #include <sys/mmu.h>
40 #include <sys/cmn_err.h>
41 #include <sys/cpu.h>
42 #include <sys/cpuvar.h>
43 #include <sys/debug.h>
44 #include <sys/lgrp.h>
45 #include <sys/archsystm.h>
46 #include <sys/machsystm.h>
47 #include <sys/vmsystm.h>
48 #include <sys/bitmap.h>
49 #include <vm/as.h>
50 #include <vm/seg.h>
51 #include <vm/seg_kmem.h>
52 #include <vm/seg_kp.h>
53 #include <vm/seg_kpm.h>
54 #include <vm/rm.h>
55 #include <vm/vm_dep.h>
56 #include <sys/t_lock.h>
57 #include <sys/vm_machparam.h>
58 #include <sys/promif.h>
59 #include <sys/prom_isa.h>
60 #include <sys/prom_plat.h>
61 #include <sys/prom_debug.h>
62 #include <sys/privregs.h>
63 #include <sys/bootconf.h>
64 #include <sys/memlist.h>
65 #include <sys/memlist_plat.h>
66 #include <sys/cpu_module.h>
67 #include <sys/reboot.h>
68 #include <sys/kdi.h>
69 
70 /*
71  * Static routines
72  */
73 static void	sfmmu_map_prom_mappings(struct translation *, size_t);
74 static struct translation *read_prom_mappings(size_t *);
75 static void	sfmmu_reloc_trap_handler(void *, void *, size_t);
76 
77 /*
78  * External routines
79  */
80 extern void sfmmu_remap_kernel(void);
81 extern void sfmmu_patch_utsb(void);
82 
83 /*
84  * Global Data:
85  */
86 extern caddr_t	textva, datava;
87 extern tte_t	ktext_tte, kdata_tte;	/* ttes for kernel text and data */
88 extern int	enable_bigktsb;
89 
90 uint64_t memsegspa = (uintptr_t)MSEG_NULLPTR_PA; /* memsegs physical linkage */
91 uint64_t memseg_phash[N_MEM_SLOTS];	/* use physical memseg addresses */
92 
93 int	sfmmu_kern_mapped = 0;
94 
95 /*
96  * DMMU primary context register for the kernel context. Machine specific code
97  * inserts correct page size codes when necessary
98  */
99 uint64_t kcontextreg = KCONTEXT;
100 
101 #ifdef DEBUG
102 static int ndata_middle_hole_detected = 0;
103 #endif
104 
105 /* Extern Global Data */
106 
107 extern int page_relocate_ready;
108 
109 /*
110  * Controls the logic which enables the use of the
111  * QUAD_LDD_PHYS ASI for TSB accesses.
112  */
113 extern int	ktsb_phys;
114 
115 /*
116  * Global Routines called from within:
117  *	usr/src/uts/sun4u
118  *	usr/src/uts/sfmmu
119  *	usr/src/uts/sun
120  */
121 
122 pfn_t
123 va_to_pfn(void *vaddr)
124 {
125 	u_longlong_t physaddr;
126 	int mode, valid;
127 
128 	if (tba_taken_over)
129 		return (hat_getpfnum(kas.a_hat, (caddr_t)vaddr));
130 
131 #if !defined(C_OBP)
132 	if ((caddr_t)vaddr >= kmem64_base && (caddr_t)vaddr < kmem64_end) {
133 		if (kmem64_pabase == (uint64_t)-1)
134 			prom_panic("va_to_pfn: kmem64_pabase not init");
135 		physaddr = kmem64_pabase + ((caddr_t)vaddr - kmem64_base);
136 		return ((pfn_t)physaddr >> MMU_PAGESHIFT);
137 	}
138 #endif	/* !C_OBP */
139 
140 	if ((prom_translate_virt(vaddr, &valid, &physaddr, &mode) != -1) &&
141 	    (valid == -1)) {
142 		return ((pfn_t)(physaddr >> MMU_PAGESHIFT));
143 	}
144 	return (PFN_INVALID);
145 }
146 
147 uint64_t
148 va_to_pa(void *vaddr)
149 {
150 	pfn_t pfn;
151 
152 	if ((pfn = va_to_pfn(vaddr)) == PFN_INVALID)
153 		return ((uint64_t)-1);
154 	return (((uint64_t)pfn << MMU_PAGESHIFT) |
155 	    ((uint64_t)vaddr & MMU_PAGEOFFSET));
156 }
157 
158 void
159 hat_kern_setup(void)
160 {
161 	struct translation *trans_root;
162 	size_t ntrans_root;
163 	extern void startup_fixup_physavail(void);
164 
165 	/*
166 	 * These are the steps we take to take over the mmu from the prom.
167 	 *
168 	 * (1)	Read the prom's mappings through the translation property.
169 	 * (2)	Remap the kernel text and kernel data with 2 locked 4MB ttes.
170 	 *	Create the the hmeblks for these 2 ttes at this time.
171 	 * (3)	Create hat structures for all other prom mappings.  Since the
172 	 *	kernel text and data hme_blks have already been created we
173 	 *	skip the equivalent prom's mappings.
174 	 * (4)	Initialize the tsb and its corresponding hardware regs.
175 	 * (5)	Take over the trap table (currently in startup).
176 	 * (6)	Up to this point it is possible the prom required some of its
177 	 *	locked tte's.  Now that we own the trap table we remove them.
178 	 */
179 
180 	ktsb_pbase = va_to_pa(ktsb_base);
181 	ktsb4m_pbase = va_to_pa(ktsb4m_base);
182 	PRM_DEBUG(ktsb_pbase);
183 	PRM_DEBUG(ktsb4m_pbase);
184 
185 	sfmmu_patch_ktsb();
186 	sfmmu_patch_utsb();
187 	sfmmu_patch_mmu_asi(ktsb_phys);
188 
189 	sfmmu_init_tsbs();
190 
191 	if (kpm_enable) {
192 		sfmmu_kpm_patch_tlbm();
193 		if (kpm_smallpages == 0) {
194 			sfmmu_kpm_patch_tsbm();
195 		}
196 	}
197 
198 	if (!shctx_on) {
199 		sfmmu_patch_shctx();
200 	}
201 
202 	/*
203 	 * The 8K-indexed kernel TSB space is used to hold
204 	 * translations below...
205 	 */
206 	trans_root = read_prom_mappings(&ntrans_root);
207 	sfmmu_remap_kernel();
208 	startup_fixup_physavail();
209 	mmu_init_kernel_pgsz(kas.a_hat);
210 	sfmmu_map_prom_mappings(trans_root, ntrans_root);
211 
212 	/*
213 	 * We invalidate 8K kernel TSB because we used it in
214 	 * sfmmu_map_prom_mappings()
215 	 */
216 	sfmmu_inv_tsb(ktsb_base, ktsb_sz);
217 	sfmmu_inv_tsb(ktsb4m_base, ktsb4m_sz);
218 
219 	sfmmu_init_ktsbinfo();
220 
221 
222 	sfmmu_kern_mapped = 1;
223 
224 	/*
225 	 * hments have been created for mapped pages, and thus we're ready
226 	 * for kmdb to start using its own trap table.  It walks the hments
227 	 * to resolve TLB misses, and can't be used until they're ready.
228 	 */
229 	if (boothowto & RB_DEBUG)
230 		kdi_dvec_vmready();
231 }
232 
233 /*
234  * Macro used below to convert the prom's 32-bit high and low fields into
235  * a value appropriate for the 64-bit kernel.
236  */
237 
238 #define	COMBINE(hi, lo) (((uint64_t)(uint32_t)(hi) << 32) | (uint32_t)(lo))
239 
240 /*
241  * Track larges pages used.
242  * Provides observability for this feature on non-debug kernels.
243  */
244 ulong_t map_prom_lpcount[MMU_PAGE_SIZES];
245 
246 /*
247  * This function traverses the prom mapping list and creates equivalent
248  * mappings in the sfmmu mapping hash.
249  */
250 static void
251 sfmmu_map_prom_mappings(struct translation *trans_root, size_t ntrans_root)
252 {
253 	struct translation *promt;
254 	tte_t	tte, oldtte, *ttep;
255 	pfn_t	pfn, oldpfn, basepfn;
256 	caddr_t vaddr;
257 	size_t	size, offset;
258 	unsigned long i;
259 	uint_t	attr;
260 	page_t *pp;
261 	extern struct memlist *virt_avail;
262 	char buf[256];
263 
264 	ttep = &tte;
265 	for (i = 0, promt = trans_root; i < ntrans_root; i++, promt++) {
266 		ASSERT(promt->tte_hi != 0);
267 		ASSERT32(promt->virt_hi == 0 && promt->size_hi == 0);
268 
269 		vaddr = (caddr_t)COMBINE(promt->virt_hi, promt->virt_lo);
270 
271 		/*
272 		 * hack until we get rid of map-for-unix
273 		 */
274 		if (vaddr < (caddr_t)KERNELBASE)
275 			continue;
276 
277 		ttep->tte_inthi = promt->tte_hi;
278 		ttep->tte_intlo = promt->tte_lo;
279 		attr = PROC_DATA | HAT_NOSYNC;
280 #if defined(TTE_IS_GLOBAL)
281 		if (TTE_IS_GLOBAL(ttep)) {
282 			/*
283 			 * The prom better not use global translations
284 			 * because a user process might use the same
285 			 * virtual addresses
286 			 */
287 			prom_panic("sfmmu_map_prom_mappings: global"
288 			    " translation");
289 			TTE_SET_LOFLAGS(ttep, TTE_GLB_INT, 0);
290 		}
291 #endif
292 		if (TTE_IS_LOCKED(ttep)) {
293 			/* clear the lock bits */
294 			TTE_CLR_LOCKED(ttep);
295 		}
296 		attr |= (TTE_IS_VCACHEABLE(ttep)) ? 0 : SFMMU_UNCACHEVTTE;
297 		attr |= (TTE_IS_PCACHEABLE(ttep)) ? 0 : SFMMU_UNCACHEPTTE;
298 		attr |= (TTE_IS_SIDEFFECT(ttep)) ? SFMMU_SIDEFFECT : 0;
299 		attr |= (TTE_IS_IE(ttep)) ? HAT_STRUCTURE_LE : 0;
300 
301 		size = COMBINE(promt->size_hi, promt->size_lo);
302 		offset = 0;
303 		basepfn = TTE_TO_PFN((caddr_t)COMBINE(promt->virt_hi,
304 		    promt->virt_lo), ttep);
305 		while (size) {
306 			vaddr = (caddr_t)(COMBINE(promt->virt_hi,
307 			    promt->virt_lo) + offset);
308 
309 			/*
310 			 * make sure address is not in virt-avail list
311 			 */
312 			if (address_in_memlist(virt_avail, (uint64_t)vaddr,
313 			    size)) {
314 				prom_panic("sfmmu_map_prom_mappings:"
315 				    " inconsistent translation/avail lists");
316 			}
317 
318 			pfn = basepfn + mmu_btop(offset);
319 			if (pf_is_memory(pfn)) {
320 				if (attr & SFMMU_UNCACHEPTTE) {
321 					prom_panic("sfmmu_map_prom_mappings:"
322 					    " uncached prom memory page");
323 				}
324 			} else {
325 				if (!(attr & SFMMU_SIDEFFECT)) {
326 					prom_panic("sfmmu_map_prom_mappings:"
327 					    " prom i/o page without"
328 					    " side-effect");
329 				}
330 			}
331 
332 			/*
333 			 * skip kmem64 area
334 			 */
335 			if (vaddr >= kmem64_base &&
336 			    vaddr < kmem64_aligned_end) {
337 #if !defined(C_OBP)
338 				prom_panic("sfmmu_map_prom_mappings:"
339 				    " unexpected kmem64 prom mapping");
340 #else	/* !C_OBP */
341 				size_t mapsz;
342 
343 				if (ptob(pfn) !=
344 				    kmem64_pabase + (vaddr - kmem64_base)) {
345 					prom_panic("sfmmu_map_prom_mappings:"
346 					    " unexpected kmem64 prom mapping");
347 				}
348 
349 				mapsz = kmem64_aligned_end - vaddr;
350 				if (mapsz >= size) {
351 					break;
352 				}
353 				size -= mapsz;
354 				offset += mapsz;
355 				continue;
356 #endif	/* !C_OBP */
357 			}
358 
359 			oldpfn = sfmmu_vatopfn(vaddr, KHATID, &oldtte);
360 			ASSERT(oldpfn != PFN_SUSPENDED);
361 			ASSERT(page_relocate_ready == 0);
362 
363 			if (oldpfn != PFN_INVALID) {
364 				/*
365 				 * mapping already exists.
366 				 * Verify they are equal
367 				 */
368 				if (pfn != oldpfn) {
369 					(void) snprintf(buf, sizeof (buf),
370 					"sfmmu_map_prom_mappings: mapping"
371 					" conflict (va = 0x%p, pfn = 0x%p,"
372 					" oldpfn = 0x%p)", (void *)vaddr,
373 					    (void *)pfn, (void *)oldpfn);
374 					prom_panic(buf);
375 				}
376 				size -= MMU_PAGESIZE;
377 				offset += MMU_PAGESIZE;
378 				continue;
379 			}
380 
381 			pp = page_numtopp_nolock(pfn);
382 			if ((pp != NULL) && PP_ISFREE((page_t *)pp)) {
383 				(void) snprintf(buf, sizeof (buf),
384 				"sfmmu_map_prom_mappings: prom-mapped"
385 				" page (va = 0x%p, pfn = 0x%p) on free list",
386 				    (void *)vaddr, (void *)pfn);
387 				prom_panic(buf);
388 			}
389 
390 			sfmmu_memtte(ttep, pfn, attr, TTE8K);
391 			sfmmu_tteload(kas.a_hat, ttep, vaddr, pp,
392 			    HAT_LOAD_LOCK | SFMMU_NO_TSBLOAD);
393 			size -= MMU_PAGESIZE;
394 			offset += MMU_PAGESIZE;
395 		}
396 	}
397 
398 	/*
399 	 * We claimed kmem64 from prom, so now we need to load tte.
400 	 */
401 	if (kmem64_base != NULL) {
402 		pgcnt_t pages;
403 		size_t psize;
404 		int pszc;
405 
406 		pszc = kmem64_szc;
407 #ifdef sun4u
408 		if (pszc > TTE8K) {
409 			pszc = segkmem_lpszc;
410 		}
411 #endif	/* sun4u */
412 		psize = TTEBYTES(pszc);
413 		pages = btop(psize);
414 		basepfn = kmem64_pabase >> MMU_PAGESHIFT;
415 		vaddr = kmem64_base;
416 		while (vaddr < kmem64_end) {
417 			sfmmu_memtte(ttep, basepfn,
418 			    PROC_DATA | HAT_NOSYNC, pszc);
419 			sfmmu_tteload(kas.a_hat, ttep, vaddr, NULL,
420 			    HAT_LOAD_LOCK | SFMMU_NO_TSBLOAD);
421 			vaddr += psize;
422 			basepfn += pages;
423 		}
424 		map_prom_lpcount[pszc] =
425 		    ((caddr_t)P2ROUNDUP((uintptr_t)kmem64_end, psize) -
426 		    kmem64_base) >> TTE_PAGE_SHIFT(pszc);
427 	}
428 }
429 
430 #undef COMBINE	/* local to previous routine */
431 
432 /*
433  * This routine reads in the "translations" property in to a buffer and
434  * returns a pointer to this buffer and the number of translations.
435  */
436 static struct translation *
437 read_prom_mappings(size_t *ntransrootp)
438 {
439 	char *prop = "translations";
440 	size_t translen;
441 	pnode_t node;
442 	struct translation *transroot;
443 
444 	/*
445 	 * the "translations" property is associated with the mmu node
446 	 */
447 	node = (pnode_t)prom_getphandle(prom_mmu_ihandle());
448 
449 	/*
450 	 * We use the TSB space to read in the prom mappings.  This space
451 	 * is currently not being used because we haven't taken over the
452 	 * trap table yet.  It should be big enough to hold the mappings.
453 	 */
454 	if ((translen = prom_getproplen(node, prop)) == -1)
455 		cmn_err(CE_PANIC, "no translations property");
456 	*ntransrootp = translen / sizeof (*transroot);
457 	translen = roundup(translen, MMU_PAGESIZE);
458 	PRM_DEBUG(translen);
459 	if (translen > TSB_BYTES(ktsb_szcode))
460 		cmn_err(CE_PANIC, "not enough space for translations");
461 
462 	transroot = (struct translation *)ktsb_base;
463 	ASSERT(transroot);
464 	if (prom_getprop(node, prop, (caddr_t)transroot) == -1) {
465 		cmn_err(CE_PANIC, "translations getprop failed");
466 	}
467 	return (transroot);
468 }
469 
470 /*
471  * Init routine of the nucleus data memory allocator.
472  *
473  * The nucleus data memory allocator is organized in ecache_alignsize'd
474  * memory chunks. Memory allocated by ndata_alloc() will never be freed.
475  *
476  * The ndata argument is used as header of the ndata freelist.
477  * Other freelist nodes are placed in the nucleus memory itself
478  * at the beginning of a free memory chunk. Therefore a freelist
479  * node (struct memlist) must fit into the smallest allocatable
480  * memory chunk (ecache_alignsize bytes).
481  *
482  * The memory interval [base, end] passed to ndata_alloc_init() must be
483  * bzero'd to allow the allocator to return bzero'd memory easily.
484  */
485 void
486 ndata_alloc_init(struct memlist *ndata, uintptr_t base, uintptr_t end)
487 {
488 	ASSERT(sizeof (struct memlist) <= ecache_alignsize);
489 
490 	base = roundup(base, ecache_alignsize);
491 	end = end - end % ecache_alignsize;
492 
493 	ASSERT(base < end);
494 
495 	ndata->address = base;
496 	ndata->size = end - base;
497 	ndata->next = NULL;
498 	ndata->prev = NULL;
499 }
500 
501 /*
502  * Deliver the size of the largest free memory chunk.
503  */
504 size_t
505 ndata_maxsize(struct memlist *ndata)
506 {
507 	size_t chunksize = ndata->size;
508 
509 	while ((ndata = ndata->next) != NULL) {
510 		if (chunksize < ndata->size)
511 			chunksize = ndata->size;
512 	}
513 
514 	return (chunksize);
515 }
516 
517 
518 /*
519  * Allocate the last properly aligned memory chunk.
520  * This function is called when no more large nucleus memory chunks
521  * will be allocated.  The remaining free nucleus memory at the end
522  * of the nucleus can be added to the phys_avail list.
523  */
524 void *
525 ndata_extra_base(struct memlist *ndata, size_t alignment, caddr_t endaddr)
526 {
527 	uintptr_t base;
528 	size_t wasteage = 0;
529 #ifdef	DEBUG
530 	static int called = 0;
531 
532 	if (called++ > 0)
533 		cmn_err(CE_PANIC, "ndata_extra_base() called more than once");
534 #endif /* DEBUG */
535 
536 	/*
537 	 * The alignment needs to be a multiple of ecache_alignsize.
538 	 */
539 	ASSERT((alignment % ecache_alignsize) ==  0);
540 
541 	while (ndata->next != NULL) {
542 		wasteage += ndata->size;
543 		ndata = ndata->next;
544 	}
545 
546 	base = roundup(ndata->address, alignment);
547 
548 	if (base >= ndata->address + ndata->size)
549 		return (NULL);
550 
551 	if ((caddr_t)(ndata->address + ndata->size) != endaddr) {
552 #ifdef DEBUG
553 		ndata_middle_hole_detected = 1;	/* see if we hit this again */
554 #endif
555 		return (NULL);
556 	}
557 
558 	if (base == ndata->address) {
559 		if (ndata->prev != NULL)
560 			ndata->prev->next = NULL;
561 		else
562 			ndata->size = 0;
563 
564 		bzero((void *)base, sizeof (struct memlist));
565 
566 	} else {
567 		ndata->size = base - ndata->address;
568 		wasteage += ndata->size;
569 	}
570 	PRM_DEBUG(wasteage);
571 
572 	return ((void *)base);
573 }
574 
575 /*
576  * Select the best matching buffer, avoid memory fragmentation.
577  */
578 static struct memlist *
579 ndata_select_chunk(struct memlist *ndata, size_t wanted, size_t alignment)
580 {
581 	struct memlist *fnd_below = NULL;
582 	struct memlist *fnd_above = NULL;
583 	struct memlist *fnd_unused = NULL;
584 	struct memlist *frlist;
585 	uintptr_t base;
586 	uintptr_t end;
587 	size_t below;
588 	size_t above;
589 	size_t unused;
590 	size_t best_below = ULONG_MAX;
591 	size_t best_above = ULONG_MAX;
592 	size_t best_unused = ULONG_MAX;
593 
594 	ASSERT(ndata != NULL);
595 
596 	/*
597 	 * Look for the best matching buffer, avoid memory fragmentation.
598 	 * The following strategy is used, try to find
599 	 *   1. an exact fitting buffer
600 	 *   2. avoid wasting any space below the buffer, take first
601 	 *	fitting buffer
602 	 *   3. avoid wasting any space above the buffer, take first
603 	 *	fitting buffer
604 	 *   4. avoid wasting space, take first fitting buffer
605 	 *   5. take the last buffer in chain
606 	 */
607 	for (frlist = ndata; frlist != NULL; frlist = frlist->next) {
608 		base = roundup(frlist->address, alignment);
609 		end = roundup(base + wanted, ecache_alignsize);
610 
611 		if (end > frlist->address + frlist->size)
612 			continue;
613 
614 		below = (base - frlist->address) / ecache_alignsize;
615 		above = (frlist->address + frlist->size - end) /
616 		    ecache_alignsize;
617 		unused = below + above;
618 
619 		if (unused == 0)
620 			return (frlist);
621 
622 		if (frlist->next == NULL)
623 			break;
624 
625 		if (below < best_below) {
626 			best_below = below;
627 			fnd_below = frlist;
628 		}
629 
630 		if (above < best_above) {
631 			best_above = above;
632 			fnd_above = frlist;
633 		}
634 
635 		if (unused < best_unused) {
636 			best_unused = unused;
637 			fnd_unused = frlist;
638 		}
639 	}
640 
641 	if (best_below == 0)
642 		return (fnd_below);
643 	if (best_above == 0)
644 		return (fnd_above);
645 	if (best_unused < ULONG_MAX)
646 		return (fnd_unused);
647 
648 	return (frlist);
649 }
650 
651 /*
652  * Nucleus data memory allocator.
653  * The granularity of the allocator is ecache_alignsize.
654  * See also comment for ndata_alloc_init().
655  */
656 void *
657 ndata_alloc(struct memlist *ndata, size_t wanted, size_t alignment)
658 {
659 	struct memlist *found;
660 	struct memlist *fnd_above;
661 	uintptr_t base;
662 	uintptr_t end;
663 	size_t below;
664 	size_t above;
665 
666 	/*
667 	 * Look for the best matching buffer, avoid memory fragmentation.
668 	 */
669 	if ((found = ndata_select_chunk(ndata, wanted, alignment)) == NULL)
670 		return (NULL);
671 
672 	/*
673 	 * Allocate the nucleus data buffer.
674 	 */
675 	base = roundup(found->address, alignment);
676 	end = roundup(base + wanted, ecache_alignsize);
677 	ASSERT(end <= found->address + found->size);
678 
679 	below = base - found->address;
680 	above = found->address + found->size - end;
681 	ASSERT(above == 0 || (above % ecache_alignsize) == 0);
682 
683 	if (below >= ecache_alignsize) {
684 		/*
685 		 * There is free memory below the allocated memory chunk.
686 		 */
687 		found->size = below - below % ecache_alignsize;
688 
689 		if (above) {
690 			fnd_above = (struct memlist *)end;
691 			fnd_above->address = end;
692 			fnd_above->size = above;
693 
694 			if ((fnd_above->next = found->next) != NULL)
695 				found->next->prev = fnd_above;
696 			fnd_above->prev = found;
697 			found->next = fnd_above;
698 		}
699 
700 		return ((void *)base);
701 	}
702 
703 	if (found->prev == NULL) {
704 		/*
705 		 * The first chunk (ndata) is selected.
706 		 */
707 		ASSERT(found == ndata);
708 		if (above) {
709 			found->address = end;
710 			found->size = above;
711 		} else if (found->next != NULL) {
712 			found->address = found->next->address;
713 			found->size = found->next->size;
714 			if ((found->next = found->next->next) != NULL)
715 				found->next->prev = found;
716 
717 			bzero((void *)found->address, sizeof (struct memlist));
718 		} else {
719 			found->address = end;
720 			found->size = 0;
721 		}
722 
723 		return ((void *)base);
724 	}
725 
726 	/*
727 	 * Not the first chunk.
728 	 */
729 	if (above) {
730 		fnd_above = (struct memlist *)end;
731 		fnd_above->address = end;
732 		fnd_above->size = above;
733 
734 		if ((fnd_above->next = found->next) != NULL)
735 			fnd_above->next->prev = fnd_above;
736 		fnd_above->prev = found->prev;
737 		found->prev->next = fnd_above;
738 
739 	} else {
740 		if ((found->prev->next = found->next) != NULL)
741 			found->next->prev = found->prev;
742 	}
743 
744 	bzero((void *)found->address, sizeof (struct memlist));
745 
746 	return ((void *)base);
747 }
748 
749 /*
750  * Size the kernel TSBs based upon the amount of physical
751  * memory in the system.
752  */
753 static void
754 calc_tsb_sizes(pgcnt_t npages)
755 {
756 	PRM_DEBUG(npages);
757 
758 	if (npages <= TSB_FREEMEM_MIN) {
759 		ktsb_szcode = TSB_128K_SZCODE;
760 		enable_bigktsb = 0;
761 	} else if (npages <= TSB_FREEMEM_LARGE / 2) {
762 		ktsb_szcode = TSB_256K_SZCODE;
763 		enable_bigktsb = 0;
764 	} else if (npages <= TSB_FREEMEM_LARGE) {
765 		ktsb_szcode = TSB_512K_SZCODE;
766 		enable_bigktsb = 0;
767 	} else if (npages <= TSB_FREEMEM_LARGE * 2 ||
768 	    enable_bigktsb == 0) {
769 		ktsb_szcode = TSB_1M_SZCODE;
770 		enable_bigktsb = 0;
771 	} else {
772 		ktsb_szcode = highbit(npages - 1);
773 		ktsb_szcode -= TSB_START_SIZE;
774 		ktsb_szcode = MAX(ktsb_szcode, MIN_BIGKTSB_SZCODE);
775 		ktsb_szcode = MIN(ktsb_szcode, MAX_BIGKTSB_SZCODE);
776 	}
777 
778 	/*
779 	 * We choose the TSB to hold kernel 4M mappings to have twice
780 	 * the reach as the primary kernel TSB since this TSB will
781 	 * potentially (currently) be shared by both mappings to all of
782 	 * physical memory plus user TSBs. If this TSB has to be in nucleus
783 	 * (only for Spitfire and Cheetah) limit its size to 64K.
784 	 */
785 	ktsb4m_szcode = highbit((2 * npages) / TTEPAGES(TTE4M) - 1);
786 	ktsb4m_szcode -= TSB_START_SIZE;
787 	ktsb4m_szcode = MAX(ktsb4m_szcode, TSB_MIN_SZCODE);
788 	ktsb4m_szcode = MIN(ktsb4m_szcode, TSB_SOFTSZ_MASK);
789 	if ((enable_bigktsb == 0 || ktsb_phys == 0) && ktsb4m_szcode >
790 	    TSB_64K_SZCODE) {
791 		ktsb4m_szcode = TSB_64K_SZCODE;
792 		max_bootlp_tteszc = TTE8K;
793 	}
794 
795 	ktsb_sz = TSB_BYTES(ktsb_szcode);	/* kernel 8K tsb size */
796 	ktsb4m_sz = TSB_BYTES(ktsb4m_szcode);	/* kernel 4M tsb size */
797 }
798 
799 /*
800  * Allocate kernel TSBs from nucleus data memory.
801  * The function return 0 on success and -1 on failure.
802  */
803 int
804 ndata_alloc_tsbs(struct memlist *ndata, pgcnt_t npages)
805 {
806 	/*
807 	 * Set ktsb_phys to 1 if the processor supports ASI_QUAD_LDD_PHYS.
808 	 */
809 	sfmmu_setup_4lp();
810 
811 	/*
812 	 * Size the kernel TSBs based upon the amount of physical
813 	 * memory in the system.
814 	 */
815 	calc_tsb_sizes(npages);
816 
817 	/*
818 	 * Allocate the 8K kernel TSB if it belongs inside the nucleus.
819 	 */
820 	if (enable_bigktsb == 0) {
821 		if ((ktsb_base = ndata_alloc(ndata, ktsb_sz, ktsb_sz)) == NULL)
822 			return (-1);
823 		ASSERT(!((uintptr_t)ktsb_base & (ktsb_sz - 1)));
824 
825 		PRM_DEBUG(ktsb_base);
826 		PRM_DEBUG(ktsb_sz);
827 		PRM_DEBUG(ktsb_szcode);
828 	}
829 
830 	/*
831 	 * Next, allocate 4M kernel TSB from the nucleus since it's small.
832 	 */
833 	if (ktsb4m_szcode <= TSB_64K_SZCODE) {
834 
835 		ktsb4m_base = ndata_alloc(ndata, ktsb4m_sz, ktsb4m_sz);
836 		if (ktsb4m_base == NULL)
837 			return (-1);
838 		ASSERT(!((uintptr_t)ktsb4m_base & (ktsb4m_sz - 1)));
839 
840 		PRM_DEBUG(ktsb4m_base);
841 		PRM_DEBUG(ktsb4m_sz);
842 		PRM_DEBUG(ktsb4m_szcode);
843 	}
844 
845 	return (0);
846 }
847 
848 size_t
849 calc_hmehash_sz(pgcnt_t npages)
850 {
851 	ulong_t hme_buckets;
852 
853 	/*
854 	 * The number of buckets in the hme hash tables
855 	 * is a power of 2 such that the average hash chain length is
856 	 * HMENT_HASHAVELEN.  The number of buckets for the user hash is
857 	 * a function of physical memory and a predefined overmapping factor.
858 	 * The number of buckets for the kernel hash is a function of
859 	 * physical memory only.
860 	 */
861 	hme_buckets = (npages * HMEHASH_FACTOR) /
862 	    (HMENT_HASHAVELEN * (HMEBLK_SPAN(TTE8K) >> MMU_PAGESHIFT));
863 
864 	uhmehash_num = (int)MIN(hme_buckets, MAX_UHME_BUCKETS);
865 
866 	if (uhmehash_num > USER_BUCKETS_THRESHOLD) {
867 		/*
868 		 * if uhmehash_num is not power of 2 round it down to the
869 		 *  next power of 2.
870 		 */
871 		uint_t align = 1 << (highbit(uhmehash_num - 1) - 1);
872 		uhmehash_num = P2ALIGN(uhmehash_num, align);
873 	} else
874 		uhmehash_num = 1 << highbit(uhmehash_num - 1);
875 
876 	hme_buckets = npages / (HMEBLK_SPAN(TTE8K) >> MMU_PAGESHIFT);
877 	khmehash_num = (int)MIN(hme_buckets, MAX_KHME_BUCKETS);
878 	khmehash_num = 1 << highbit(khmehash_num - 1);
879 	khmehash_num = MAX(khmehash_num, MIN_KHME_BUCKETS);
880 
881 	return ((uhmehash_num + khmehash_num) * sizeof (struct hmehash_bucket));
882 }
883 
884 caddr_t
885 alloc_hmehash(caddr_t alloc_base)
886 {
887 	size_t khmehash_sz, uhmehash_sz;
888 
889 	khme_hash = (struct hmehash_bucket *)alloc_base;
890 	khmehash_sz = khmehash_num * sizeof (struct hmehash_bucket);
891 	alloc_base += khmehash_sz;
892 
893 	uhme_hash = (struct hmehash_bucket *)alloc_base;
894 	uhmehash_sz = uhmehash_num * sizeof (struct hmehash_bucket);
895 	alloc_base += uhmehash_sz;
896 
897 	PRM_DEBUG(khme_hash);
898 	PRM_DEBUG(uhme_hash);
899 
900 	return (alloc_base);
901 }
902 
903 /*
904  * Allocate hat structs from the nucleus data memory.
905  */
906 int
907 ndata_alloc_hat(struct memlist *ndata, pgcnt_t npages)
908 {
909 	size_t	mml_alloc_sz;
910 	size_t	cb_alloc_sz;
911 
912 	/*
913 	 * For the page mapping list mutex array we allocate one mutex
914 	 * for every 128 pages (1 MB) with a minimum of 64 entries and
915 	 * a maximum of 8K entries. For the initial computation npages
916 	 * is rounded up (ie. 1 << highbit(npages * 1.5 / 128))
917 	 *
918 	 * mml_shift is roughly log2(mml_table_sz) + 3 for MLIST_HASH
919 	 */
920 	mml_table_sz = 1 << highbit((npages * 3) / 256);
921 	if (mml_table_sz < 64)
922 		mml_table_sz = 64;
923 	else if (mml_table_sz > 8192)
924 		mml_table_sz = 8192;
925 	mml_shift = highbit(mml_table_sz) + 3;
926 
927 	PRM_DEBUG(mml_table_sz);
928 	PRM_DEBUG(mml_shift);
929 
930 	mml_alloc_sz = mml_table_sz * sizeof (kmutex_t);
931 
932 	mml_table = ndata_alloc(ndata, mml_alloc_sz, ecache_alignsize);
933 	if (mml_table == NULL)
934 		return (-1);
935 	PRM_DEBUG(mml_table);
936 
937 	cb_alloc_sz = sfmmu_max_cb_id * sizeof (struct sfmmu_callback);
938 	PRM_DEBUG(cb_alloc_sz);
939 	sfmmu_cb_table = ndata_alloc(ndata, cb_alloc_sz, ecache_alignsize);
940 	if (sfmmu_cb_table == NULL)
941 		return (-1);
942 	PRM_DEBUG(sfmmu_cb_table);
943 
944 	return (0);
945 }
946 
947 int
948 ndata_alloc_kpm(struct memlist *ndata, pgcnt_t kpm_npages)
949 {
950 	size_t	kpmp_alloc_sz;
951 
952 	/*
953 	 * For the kpm_page mutex array we allocate one mutex every 16
954 	 * kpm pages (64MB). In smallpage mode we allocate one mutex
955 	 * every 8K pages. The minimum is set to 64 entries and the
956 	 * maximum to 8K entries.
957 	 */
958 	if (kpm_smallpages == 0) {
959 		kpmp_shift = highbit(sizeof (kpm_page_t)) - 1;
960 		kpmp_table_sz = 1 << highbit(kpm_npages / 16);
961 		kpmp_table_sz = (kpmp_table_sz < 64) ? 64 :
962 		    ((kpmp_table_sz > 8192) ? 8192 : kpmp_table_sz);
963 		kpmp_alloc_sz = kpmp_table_sz * sizeof (kpm_hlk_t);
964 
965 		kpmp_table = ndata_alloc(ndata, kpmp_alloc_sz,
966 		    ecache_alignsize);
967 		if (kpmp_table == NULL)
968 			return (-1);
969 
970 		PRM_DEBUG(kpmp_table);
971 		PRM_DEBUG(kpmp_table_sz);
972 
973 		kpmp_stable_sz = 0;
974 		kpmp_stable = NULL;
975 	} else {
976 		ASSERT(kpm_pgsz == PAGESIZE);
977 		kpmp_shift = highbit(sizeof (kpm_shlk_t)) + 1;
978 		kpmp_stable_sz = 1 << highbit(kpm_npages / 8192);
979 		kpmp_stable_sz = (kpmp_stable_sz < 64) ? 64 :
980 		    ((kpmp_stable_sz > 8192) ? 8192 : kpmp_stable_sz);
981 		kpmp_alloc_sz = kpmp_stable_sz * sizeof (kpm_shlk_t);
982 
983 		kpmp_stable = ndata_alloc(ndata, kpmp_alloc_sz,
984 		    ecache_alignsize);
985 		if (kpmp_stable == NULL)
986 			return (-1);
987 
988 		PRM_DEBUG(kpmp_stable);
989 		PRM_DEBUG(kpmp_stable_sz);
990 
991 		kpmp_table_sz = 0;
992 		kpmp_table = NULL;
993 	}
994 	PRM_DEBUG(kpmp_shift);
995 
996 	return (0);
997 }
998 
999 /*
1000  * This function bop allocs kernel TSBs.
1001  */
1002 caddr_t
1003 sfmmu_ktsb_alloc(caddr_t tsbbase)
1004 {
1005 	caddr_t vaddr;
1006 
1007 	if (enable_bigktsb) {
1008 		ktsb_base = (caddr_t)roundup((uintptr_t)tsbbase, ktsb_sz);
1009 		vaddr = prom_alloc(ktsb_base, ktsb_sz, ktsb_sz);
1010 		if (vaddr != ktsb_base)
1011 			cmn_err(CE_PANIC, "sfmmu_ktsb_alloc: can't alloc"
1012 			    " 8K bigktsb");
1013 		ktsb_base = vaddr;
1014 		tsbbase = ktsb_base + ktsb_sz;
1015 		PRM_DEBUG(ktsb_base);
1016 		PRM_DEBUG(tsbbase);
1017 	}
1018 
1019 	if (ktsb4m_szcode > TSB_64K_SZCODE) {
1020 		ASSERT(ktsb_phys && enable_bigktsb);
1021 		ktsb4m_base = (caddr_t)roundup((uintptr_t)tsbbase, ktsb4m_sz);
1022 		vaddr = (caddr_t)BOP_ALLOC(bootops, ktsb4m_base, ktsb4m_sz,
1023 		    ktsb4m_sz);
1024 		if (vaddr != ktsb4m_base)
1025 			cmn_err(CE_PANIC, "sfmmu_ktsb_alloc: can't alloc"
1026 			    " 4M bigktsb");
1027 		ktsb4m_base = vaddr;
1028 		tsbbase = ktsb4m_base + ktsb4m_sz;
1029 		PRM_DEBUG(ktsb4m_base);
1030 		PRM_DEBUG(tsbbase);
1031 	}
1032 	return (tsbbase);
1033 }
1034 
1035 /*
1036  * Moves code assembled outside of the trap table into the trap
1037  * table taking care to relocate relative branches to code outside
1038  * of the trap handler.
1039  */
1040 static void
1041 sfmmu_reloc_trap_handler(void *tablep, void *start, size_t count)
1042 {
1043 	size_t i;
1044 	uint32_t *src;
1045 	uint32_t *dst;
1046 	uint32_t inst;
1047 	int op, op2;
1048 	int32_t offset;
1049 	int disp;
1050 
1051 	src = start;
1052 	dst = tablep;
1053 	offset = src - dst;
1054 	for (src = start, i = 0; i < count; i++, src++, dst++) {
1055 		inst = *dst = *src;
1056 		op = (inst >> 30) & 0x2;
1057 		if (op == 1) {
1058 			/* call */
1059 			disp = ((int32_t)inst << 2) >> 2; /* sign-extend */
1060 			if (disp + i >= 0 && disp + i < count)
1061 				continue;
1062 			disp += offset;
1063 			inst = 0x40000000u | (disp & 0x3fffffffu);
1064 			*dst = inst;
1065 		} else if (op == 0) {
1066 			/* branch or sethi */
1067 			op2 = (inst >> 22) & 0x7;
1068 
1069 			switch (op2) {
1070 			case 0x3: /* BPr */
1071 				disp = (((inst >> 20) & 0x3) << 14) |
1072 				    (inst & 0x3fff);
1073 				disp = (disp << 16) >> 16; /* sign-extend */
1074 				if (disp + i >= 0 && disp + i < count)
1075 					continue;
1076 				disp += offset;
1077 				if (((disp << 16) >> 16) != disp)
1078 					cmn_err(CE_PANIC, "bad reloc");
1079 				inst &= ~0x303fff;
1080 				inst |= (disp & 0x3fff);
1081 				inst |= (disp & 0xc000) << 6;
1082 				break;
1083 
1084 			case 0x2: /* Bicc */
1085 				disp = ((int32_t)inst << 10) >> 10;
1086 				if (disp + i >= 0 && disp + i < count)
1087 					continue;
1088 				disp += offset;
1089 				if (((disp << 10) >> 10) != disp)
1090 					cmn_err(CE_PANIC, "bad reloc");
1091 				inst &= ~0x3fffff;
1092 				inst |= (disp & 0x3fffff);
1093 				break;
1094 
1095 			case 0x1: /* Bpcc */
1096 				disp = ((int32_t)inst << 13) >> 13;
1097 				if (disp + i >= 0 && disp + i < count)
1098 					continue;
1099 				disp += offset;
1100 				if (((disp << 13) >> 13) != disp)
1101 					cmn_err(CE_PANIC, "bad reloc");
1102 				inst &= ~0x7ffff;
1103 				inst |= (disp & 0x7ffffu);
1104 				break;
1105 			}
1106 			*dst = inst;
1107 		}
1108 	}
1109 	flush_instr_mem(tablep, count * sizeof (uint32_t));
1110 }
1111 
1112 /*
1113  * Routine to allocate a large page to use in the TSB caches.
1114  */
1115 /*ARGSUSED*/
1116 static page_t *
1117 sfmmu_tsb_page_create(void *addr, size_t size, int vmflag, void *arg)
1118 {
1119 	int pgflags;
1120 
1121 	pgflags = PG_EXCL;
1122 	if ((vmflag & VM_NOSLEEP) == 0)
1123 		pgflags |= PG_WAIT;
1124 	if (vmflag & VM_PANIC)
1125 		pgflags |= PG_PANIC;
1126 	if (vmflag & VM_PUSHPAGE)
1127 		pgflags |= PG_PUSHPAGE;
1128 
1129 	return (page_create_va_large(&kvp, (u_offset_t)(uintptr_t)addr, size,
1130 	    pgflags, &kvseg, addr, arg));
1131 }
1132 
1133 /*
1134  * Allocate a large page to back the virtual address range
1135  * [addr, addr + size).  If addr is NULL, allocate the virtual address
1136  * space as well.
1137  */
1138 static void *
1139 sfmmu_tsb_xalloc(vmem_t *vmp, void *inaddr, size_t size, int vmflag,
1140     uint_t attr, page_t *(*page_create_func)(void *, size_t, int, void *),
1141     void *pcarg)
1142 {
1143 	page_t *ppl;
1144 	page_t *rootpp;
1145 	caddr_t addr = inaddr;
1146 	pgcnt_t npages = btopr(size);
1147 	page_t **ppa;
1148 	int i = 0;
1149 
1150 	/*
1151 	 * Assuming that only TSBs will call this with size > PAGESIZE
1152 	 * There is no reason why this couldn't be expanded to 8k pages as
1153 	 * well, or other page sizes in the future .... but for now, we
1154 	 * only support fixed sized page requests.
1155 	 */
1156 	if ((inaddr == NULL) && ((addr = vmem_xalloc(vmp, size, size, 0, 0,
1157 	    NULL, NULL, vmflag)) == NULL))
1158 		return (NULL);
1159 
1160 	if (page_resv(npages, vmflag & VM_KMFLAGS) == 0) {
1161 		if (inaddr == NULL)
1162 			vmem_xfree(vmp, addr, size);
1163 		return (NULL);
1164 	}
1165 
1166 	ppl = page_create_func(addr, size, vmflag, pcarg);
1167 	if (ppl == NULL) {
1168 		if (inaddr == NULL)
1169 			vmem_xfree(vmp, addr, size);
1170 		page_unresv(npages);
1171 		return (NULL);
1172 	}
1173 
1174 	rootpp = ppl;
1175 	ppa = kmem_zalloc(npages * sizeof (page_t *), KM_SLEEP);
1176 	while (ppl != NULL) {
1177 		page_t *pp = ppl;
1178 		ppa[i++] = pp;
1179 		page_sub(&ppl, pp);
1180 		ASSERT(page_iolock_assert(pp));
1181 		page_io_unlock(pp);
1182 	}
1183 
1184 	/*
1185 	 * Load the locked entry.  It's OK to preload the entry into
1186 	 * the TSB since we now support large mappings in the kernel TSB.
1187 	 */
1188 	hat_memload_array(kas.a_hat, (caddr_t)rootpp->p_offset, size,
1189 	    ppa, (PROT_ALL & ~PROT_USER) | HAT_NOSYNC | attr, HAT_LOAD_LOCK);
1190 
1191 	for (--i; i >= 0; --i) {
1192 		(void) page_pp_lock(ppa[i], 0, 1);
1193 		page_unlock(ppa[i]);
1194 	}
1195 
1196 	kmem_free(ppa, npages * sizeof (page_t *));
1197 	return (addr);
1198 }
1199 
1200 /* Called to import new spans into the TSB vmem arenas */
1201 void *
1202 sfmmu_tsb_segkmem_alloc(vmem_t *vmp, size_t size, int vmflag)
1203 {
1204 	lgrp_id_t lgrpid = LGRP_NONE;
1205 
1206 	if (tsb_lgrp_affinity) {
1207 		/*
1208 		 * Search for the vmp->lgrpid mapping by brute force;
1209 		 * some day vmp will have an lgrp, until then we have
1210 		 * to do this the hard way.
1211 		 */
1212 		for (lgrpid = 0; lgrpid < NLGRPS_MAX &&
1213 		    vmp != kmem_tsb_default_arena[lgrpid]; lgrpid++)
1214 			;
1215 		if (lgrpid == NLGRPS_MAX)
1216 			lgrpid = LGRP_NONE;
1217 	}
1218 
1219 	return (sfmmu_tsb_xalloc(vmp, NULL, size, vmflag, 0,
1220 	    sfmmu_tsb_page_create, lgrpid != LGRP_NONE? &lgrpid : NULL));
1221 }
1222 
1223 /* Called to free spans from the TSB vmem arenas */
1224 void
1225 sfmmu_tsb_segkmem_free(vmem_t *vmp, void *inaddr, size_t size)
1226 {
1227 	page_t *pp;
1228 	caddr_t addr = inaddr;
1229 	caddr_t eaddr;
1230 	pgcnt_t npages = btopr(size);
1231 	pgcnt_t pgs_left = npages;
1232 	page_t *rootpp = NULL;
1233 
1234 	hat_unload(kas.a_hat, addr, size, HAT_UNLOAD_UNLOCK);
1235 
1236 	for (eaddr = addr + size; addr < eaddr; addr += PAGESIZE) {
1237 		pp = page_lookup(&kvp, (u_offset_t)(uintptr_t)addr, SE_EXCL);
1238 		if (pp == NULL)
1239 			panic("sfmmu_tsb_segkmem_free: page not found");
1240 
1241 		ASSERT(PAGE_EXCL(pp));
1242 		page_pp_unlock(pp, 0, 1);
1243 
1244 		if (rootpp == NULL)
1245 			rootpp = pp;
1246 		if (--pgs_left == 0) {
1247 			/*
1248 			 * similar logic to segspt_free_pages, but we know we
1249 			 * have one large page.
1250 			 */
1251 			page_destroy_pages(rootpp);
1252 		}
1253 	}
1254 	page_unresv(npages);
1255 
1256 	if (vmp != NULL)
1257 		vmem_xfree(vmp, inaddr, size);
1258 }
1259