xref: /titanic_44/usr/src/uts/sun4/os/startup.c (revision 8339b41da2395f0525c46ceedfeb01961893ec44)
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 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 #include <sys/machsystm.h>
27 #include <sys/archsystm.h>
28 #include <sys/vm.h>
29 #include <sys/cpu.h>
30 #include <sys/atomic.h>
31 #include <sys/reboot.h>
32 #include <sys/kdi.h>
33 #include <sys/bootconf.h>
34 #include <sys/memlist_plat.h>
35 #include <sys/memlist_impl.h>
36 #include <sys/prom_plat.h>
37 #include <sys/prom_isa.h>
38 #include <sys/autoconf.h>
39 #include <sys/ivintr.h>
40 #include <sys/fpu/fpusystm.h>
41 #include <sys/iommutsb.h>
42 #include <vm/vm_dep.h>
43 #include <vm/seg_dev.h>
44 #include <vm/seg_kmem.h>
45 #include <vm/seg_kpm.h>
46 #include <vm/seg_map.h>
47 #include <vm/seg_kp.h>
48 #include <sys/sysconf.h>
49 #include <vm/hat_sfmmu.h>
50 #include <sys/kobj.h>
51 #include <sys/sun4asi.h>
52 #include <sys/clconf.h>
53 #include <sys/platform_module.h>
54 #include <sys/panic.h>
55 #include <sys/cpu_sgnblk_defs.h>
56 #include <sys/clock.h>
57 #include <sys/cmn_err.h>
58 #include <sys/promif.h>
59 #include <sys/prom_debug.h>
60 #include <sys/traptrace.h>
61 #include <sys/memnode.h>
62 #include <sys/mem_cage.h>
63 #include <sys/mmu.h>
64 #include <sys/swap.h>
65 
66 extern void setup_trap_table(void);
67 extern int cpu_intrq_setup(struct cpu *);
68 extern void cpu_intrq_register(struct cpu *);
69 extern void contig_mem_init(void);
70 extern caddr_t contig_mem_prealloc(caddr_t, pgcnt_t);
71 extern void mach_dump_buffer_init(void);
72 extern void mach_descrip_init(void);
73 extern void mach_descrip_startup_fini(void);
74 extern void mach_memscrub(void);
75 extern void mach_fpras(void);
76 extern void mach_cpu_halt_idle(void);
77 extern void mach_hw_copy_limit(void);
78 extern void load_mach_drivers(void);
79 extern void load_tod_module(void);
80 #pragma weak load_tod_module
81 
82 extern int ndata_alloc_mmfsa(struct memlist *ndata);
83 #pragma weak ndata_alloc_mmfsa
84 
85 extern void cif_init(void);
86 #pragma weak cif_init
87 
88 extern void parse_idprom(void);
89 extern void add_vx_handler(char *, int, void (*)(cell_t *));
90 extern void mem_config_init(void);
91 extern void memseg_remap_init(void);
92 
93 extern void mach_kpm_init(void);
94 extern void pcf_init();
95 extern int size_pse_array(pgcnt_t, int);
96 extern void pg_init();
97 
98 /*
99  * External Data:
100  */
101 extern int vac_size;	/* cache size in bytes */
102 extern uint_t vac_mask;	/* VAC alignment consistency mask */
103 extern uint_t vac_colors;
104 
105 /*
106  * Global Data Definitions:
107  */
108 
109 /*
110  * XXX - Don't port this to new architectures
111  * A 3rd party volume manager driver (vxdm) depends on the symbol romp.
112  * 'romp' has no use with a prom with an IEEE 1275 client interface.
113  * The driver doesn't use the value, but it depends on the symbol.
114  */
115 void *romp;		/* veritas driver won't load without romp 4154976 */
116 /*
117  * Declare these as initialized data so we can patch them.
118  */
119 pgcnt_t physmem = 0;	/* memory size in pages, patch if you want less */
120 pgcnt_t segkpsize =
121     btop(SEGKPDEFSIZE);	/* size of segkp segment in pages */
122 uint_t segmap_percent = 6; /* Size of segmap segment */
123 
124 int use_cache = 1;		/* cache not reliable (605 bugs) with MP */
125 int vac_copyback = 1;
126 char *cache_mode = NULL;
127 int use_mix = 1;
128 int prom_debug = 0;
129 
130 caddr_t boot_tba;		/* %tba at boot - used by kmdb */
131 uint_t	tba_taken_over = 0;
132 
133 caddr_t s_text;			/* start of kernel text segment */
134 caddr_t e_text;			/* end of kernel text segment */
135 caddr_t s_data;			/* start of kernel data segment */
136 caddr_t e_data;			/* end of kernel data segment */
137 
138 caddr_t modtext;		/* beginning of module text */
139 size_t	modtext_sz;		/* size of module text */
140 caddr_t moddata;		/* beginning of module data reserve */
141 caddr_t e_moddata;		/* end of module data reserve */
142 
143 /*
144  * End of first block of contiguous kernel in 32-bit virtual address space
145  */
146 caddr_t		econtig32;	/* end of first blk of contiguous kernel */
147 
148 caddr_t		ncbase;		/* beginning of non-cached segment */
149 caddr_t		ncend;		/* end of non-cached segment */
150 
151 size_t	ndata_remain_sz;	/* bytes from end of data to 4MB boundary */
152 caddr_t	nalloc_base;		/* beginning of nucleus allocation */
153 caddr_t nalloc_end;		/* end of nucleus allocatable memory */
154 caddr_t valloc_base;		/* beginning of kvalloc segment	*/
155 
156 caddr_t kmem64_base;		/* base of kernel mem segment in 64-bit space */
157 caddr_t kmem64_end;		/* end of kernel mem segment in 64-bit space */
158 size_t	kmem64_sz;		/* bytes in kernel mem segment, 64-bit space */
159 caddr_t kmem64_aligned_end;	/* end of large page, overmaps 64-bit space */
160 int	kmem64_szc;		/* page size code */
161 uint64_t kmem64_pabase = (uint64_t)-1;	/* physical address of kmem64_base */
162 
163 uintptr_t shm_alignment;	/* VAC address consistency modulus */
164 struct memlist *phys_install;	/* Total installed physical memory */
165 struct memlist *phys_avail;	/* Available (unreserved) physical memory */
166 struct memlist *virt_avail;	/* Available (unmapped?) virtual memory */
167 struct memlist *nopp_list;	/* pages with no backing page structs */
168 struct memlist ndata;		/* memlist of nucleus allocatable memory */
169 int memexp_flag;		/* memory expansion card flag */
170 uint64_t ecache_flushaddr;	/* physical address used for flushing E$ */
171 pgcnt_t obp_pages;		/* Physical pages used by OBP */
172 
173 /*
174  * VM data structures
175  */
176 long page_hashsz;		/* Size of page hash table (power of two) */
177 unsigned int page_hashsz_shift;	/* log2(page_hashsz) */
178 struct page *pp_base;		/* Base of system page struct array */
179 size_t pp_sz;			/* Size in bytes of page struct array */
180 struct page **page_hash;	/* Page hash table */
181 pad_mutex_t *pse_mutex;		/* Locks protecting pp->p_selock */
182 size_t pse_table_size;		/* Number of mutexes in pse_mutex[] */
183 int pse_shift;			/* log2(pse_table_size) */
184 struct seg ktextseg;		/* Segment used for kernel executable image */
185 struct seg kvalloc;		/* Segment used for "valloc" mapping */
186 struct seg kpseg;		/* Segment used for pageable kernel virt mem */
187 struct seg ktexthole;		/* Segment used for nucleus text hole */
188 struct seg kmapseg;		/* Segment used for generic kernel mappings */
189 struct seg kpmseg;		/* Segment used for physical mapping */
190 struct seg kdebugseg;		/* Segment used for the kernel debugger */
191 
192 void *kpm_pp_base;		/* Base of system kpm_page array */
193 size_t	kpm_pp_sz;		/* Size of system kpm_page array */
194 pgcnt_t	kpm_npages;		/* How many kpm pages are managed */
195 
196 struct seg *segkp = &kpseg;	/* Pageable kernel virtual memory segment */
197 struct seg *segkmap = &kmapseg;	/* Kernel generic mapping segment */
198 struct seg *segkpm = &kpmseg;	/* 64bit kernel physical mapping segment */
199 
200 int segzio_fromheap = 0;	/* zio allocations occur from heap */
201 caddr_t segzio_base;		/* Base address of segzio */
202 pgcnt_t segziosize = 0;		/* size of zio segment in pages */
203 
204 /*
205  * A static DR page_t VA map is reserved that can map the page structures
206  * for a domain's entire RA space. The pages that backs this space are
207  * dynamically allocated and need not be physically contiguous.  The DR
208  * map size is derived from KPM size.
209  */
210 int ppvm_enable = 0;		/* Static virtual map for page structs */
211 page_t *ppvm_base;		/* Base of page struct map */
212 pgcnt_t ppvm_size = 0;		/* Size of page struct map */
213 
214 /*
215  * debugger pages (if allocated)
216  */
217 struct vnode kdebugvp;
218 
219 /*
220  * VA range available to the debugger
221  */
222 const caddr_t kdi_segdebugbase = (const caddr_t)SEGDEBUGBASE;
223 const size_t kdi_segdebugsize = SEGDEBUGSIZE;
224 
225 /*
226  * Segment for relocated kernel structures in 64-bit large RAM kernels
227  */
228 struct seg kmem64;
229 
230 struct memseg *memseg_free;
231 
232 struct vnode unused_pages_vp;
233 
234 /*
235  * VM data structures allocated early during boot.
236  */
237 size_t pagehash_sz;
238 uint64_t memlist_sz;
239 
240 char tbr_wr_addr_inited = 0;
241 
242 caddr_t	mpo_heap32_buf = NULL;
243 size_t	mpo_heap32_bufsz = 0;
244 
245 /*
246  * Static Routines:
247  */
248 static int ndata_alloc_memseg(struct memlist *, size_t);
249 static void memlist_new(uint64_t, uint64_t, struct memlist **);
250 static void memlist_add(uint64_t, uint64_t,
251 	struct memlist **, struct memlist **);
252 static void kphysm_init(void);
253 static void kvm_init(void);
254 static void install_kmem64_tte(void);
255 
256 static void startup_init(void);
257 static void startup_memlist(void);
258 static void startup_modules(void);
259 static void startup_bop_gone(void);
260 static void startup_vm(void);
261 static void startup_end(void);
262 static void setup_cage_params(void);
263 static void startup_create_io_node(void);
264 
265 static pgcnt_t npages;
266 static struct memlist *memlist;
267 void *memlist_end;
268 
269 static pgcnt_t bop_alloc_pages;
270 static caddr_t hblk_base;
271 uint_t hblk_alloc_dynamic = 0;
272 uint_t hblk1_min = H1MIN;
273 
274 
275 /*
276  * Hooks for unsupported platforms and down-rev firmware
277  */
278 int iam_positron(void);
279 #pragma weak iam_positron
280 static void do_prom_version_check(void);
281 
282 /*
283  * After receiving a thermal interrupt, this is the number of seconds
284  * to delay before shutting off the system, assuming
285  * shutdown fails.  Use /etc/system to change the delay if this isn't
286  * large enough.
287  */
288 int thermal_powerdown_delay = 1200;
289 
290 /*
291  * Used to hold off page relocations into the cage until OBP has completed
292  * its boot-time handoff of its resources to the kernel.
293  */
294 int page_relocate_ready = 0;
295 
296 /*
297  * Indicate if kmem64 allocation was done in small chunks
298  */
299 int kmem64_smchunks = 0;
300 
301 /*
302  * Enable some debugging messages concerning memory usage...
303  */
304 #ifdef  DEBUGGING_MEM
305 static int debugging_mem;
306 static void
307 printmemlist(char *title, struct memlist *list)
308 {
309 	if (!debugging_mem)
310 		return;
311 
312 	printf("%s\n", title);
313 
314 	while (list) {
315 		prom_printf("\taddr = 0x%x %8x, size = 0x%x %8x\n",
316 		    (uint32_t)(list->ml_address >> 32),
317 		    (uint32_t)list->ml_address,
318 		    (uint32_t)(list->ml_size >> 32),
319 		    (uint32_t)(list->ml_size));
320 		list = list->ml_next;
321 	}
322 }
323 
324 void
325 printmemseg(struct memseg *memseg)
326 {
327 	if (!debugging_mem)
328 		return;
329 
330 	printf("memseg\n");
331 
332 	while (memseg) {
333 		prom_printf("\tpage = 0x%p, epage = 0x%p, "
334 		    "pfn = 0x%x, epfn = 0x%x\n",
335 		    memseg->pages, memseg->epages,
336 		    memseg->pages_base, memseg->pages_end);
337 		memseg = memseg->next;
338 	}
339 }
340 
341 #define	debug_pause(str)	halt((str))
342 #define	MPRINTF(str)		if (debugging_mem) prom_printf((str))
343 #define	MPRINTF1(str, a)	if (debugging_mem) prom_printf((str), (a))
344 #define	MPRINTF2(str, a, b)	if (debugging_mem) prom_printf((str), (a), (b))
345 #define	MPRINTF3(str, a, b, c) \
346 	if (debugging_mem) prom_printf((str), (a), (b), (c))
347 #else	/* DEBUGGING_MEM */
348 #define	MPRINTF(str)
349 #define	MPRINTF1(str, a)
350 #define	MPRINTF2(str, a, b)
351 #define	MPRINTF3(str, a, b, c)
352 #endif	/* DEBUGGING_MEM */
353 
354 
355 /*
356  *
357  *                    Kernel's Virtual Memory Layout.
358  *                       /-----------------------\
359  * 0xFFFFFFFF.FFFFFFFF  -|                       |-
360  *                       |   OBP's virtual page  |
361  *                       |        tables         |
362  * 0xFFFFFFFC.00000000  -|-----------------------|-
363  *                       :                       :
364  *                       :                       :
365  *                      -|-----------------------|-
366  *                       |       segzio          | (base and size vary)
367  * 0xFFFFFE00.00000000  -|-----------------------|-
368  *                       |                       |  Ultrasparc I/II support
369  *                       |    segkpm segment     |  up to 2TB of physical
370  *                       | (64-bit kernel ONLY)  |  memory, VAC has 2 colors
371  *                       |                       |
372  * 0xFFFFFA00.00000000  -|-----------------------|- 2TB segkpm alignment
373  *                       :                       :
374  *                       :                       :
375  * 0xFFFFF810.00000000  -|-----------------------|- hole_end
376  *                       |                       |      ^
377  *                       |  UltraSPARC I/II call |      |
378  *                       | bug requires an extra |      |
379  *                       | 4 GB of space between |      |
380  *                       |   hole and used RAM   |	|
381  *                       |                       |      |
382  * 0xFFFFF800.00000000  -|-----------------------|-     |
383  *                       |                       |      |
384  *                       | Virtual Address Hole  |   UltraSPARC
385  *                       |  on UltraSPARC I/II   |  I/II * ONLY *
386  *                       |                       |      |
387  * 0x00000800.00000000  -|-----------------------|-     |
388  *                       |                       |      |
389  *                       |  UltraSPARC I/II call |      |
390  *                       | bug requires an extra |      |
391  *                       | 4 GB of space between |      |
392  *                       |   hole and used RAM   |      |
393  *                       |                       |      v
394  * 0x000007FF.00000000  -|-----------------------|- hole_start -----
395  *                       :                       :		   ^
396  *                       :                       :		   |
397  *                       |-----------------------|                 |
398  *                       |                       |                 |
399  *                       |  ecache flush area    |                 |
400  *                       |  (twice largest e$)   |                 |
401  *                       |                       |                 |
402  * 0x00000XXX.XXX00000  -|-----------------------|- kmem64_	   |
403  *                       | overmapped area       |   alignend_end  |
404  *                       | (kmem64_alignsize     |		   |
405  *                       |  boundary)            |		   |
406  * 0x00000XXX.XXXXXXXX  -|-----------------------|- kmem64_end	   |
407  *                       |                       |		   |
408  *                       |   64-bit kernel ONLY  |		   |
409  *                       |                       |		   |
410  *                       |    kmem64 segment     |		   |
411  *                       |                       |		   |
412  *                       | (Relocated extra HME  |	     Approximately
413  *                       |   block allocations,  |	    1 TB of virtual
414  *                       |   memnode freelists,  |	     address space
415  *                       |    HME hash buckets,  |		   |
416  *                       | mml_table, kpmp_table,|		   |
417  *                       |  page_t array and     |		   |
418  *                       |  hashblock pool to    |		   |
419  *                       |   avoid hard-coded    |		   |
420  *                       |     32-bit vaddr      |		   |
421  *                       |     limitations)      |		   |
422  *                       |                       |		   v
423  * 0x00000700.00000000  -|-----------------------|- SYSLIMIT (kmem64_base)
424  *                       |                       |
425  *                       |  segkmem segment      | (SYSLIMIT - SYSBASE = 4TB)
426  *                       |                       |
427  * 0x00000300.00000000  -|-----------------------|- SYSBASE
428  *                       :                       :
429  *                       :                       :
430  *                      -|-----------------------|-
431  *                       |                       |
432  *                       |  segmap segment       |   SEGMAPSIZE (1/8th physmem,
433  *                       |                       |               256G MAX)
434  * 0x000002a7.50000000  -|-----------------------|- SEGMAPBASE
435  *                       :                       :
436  *                       :                       :
437  *                      -|-----------------------|-
438  *                       |                       |
439  *                       |       segkp           |    SEGKPSIZE (2GB)
440  *                       |                       |
441  *                       |                       |
442  * 0x000002a1.00000000  -|-----------------------|- SEGKPBASE
443  *                       |                       |
444  * 0x000002a0.00000000  -|-----------------------|- MEMSCRUBBASE
445  *                       |                       |       (SEGKPBASE - 0x400000)
446  * 0x0000029F.FFE00000  -|-----------------------|- ARGSBASE
447  *                       |                       |       (MEMSCRUBBASE - NCARGS)
448  * 0x0000029F.FFD80000  -|-----------------------|- PPMAPBASE
449  *                       |                       |       (ARGSBASE - PPMAPSIZE)
450  * 0x0000029F.FFD00000  -|-----------------------|- PPMAP_FAST_BASE
451  *                       |                       |
452  * 0x0000029F.FF980000  -|-----------------------|- PIOMAPBASE
453  *                       |                       |
454  * 0x0000029F.FF580000  -|-----------------------|- NARG_BASE
455  *                       :                       :
456  *                       :                       :
457  * 0x00000000.FFFFFFFF  -|-----------------------|- OFW_END_ADDR
458  *                       |                       |
459  *                       |         OBP           |
460  *                       |                       |
461  * 0x00000000.F0000000  -|-----------------------|- OFW_START_ADDR
462  *                       |         kmdb          |
463  * 0x00000000.EDD00000  -|-----------------------|- SEGDEBUGBASE
464  *                       :                       :
465  *                       :                       :
466  * 0x00000000.7c000000  -|-----------------------|- SYSLIMIT32
467  *                       |                       |
468  *                       |  segkmem32 segment    | (SYSLIMIT32 - SYSBASE32 =
469  *                       |                       |    ~64MB)
470  *			-|-----------------------|
471  *			 |	IVSIZE		 |
472  * 0x00000000.70004000  -|-----------------------|
473  *                       |     panicbuf          |
474  * 0x00000000.70002000	-|-----------------------|
475  *			 |	PAGESIZE	 |
476  * 0x00000000.70000000  -|-----------------------|- SYSBASE32
477  *                       |       boot-time       |
478  *                       |    temporary space    |
479  * 0x00000000.4C000000  -|-----------------------|- BOOTTMPBASE
480  *                       :                       :
481  *                       :                       :
482  *                       |                       |
483  *                       |-----------------------|- econtig32
484  *                       |    vm structures      |
485  * 0x00000000.01C00000   |-----------------------|- nalloc_end
486  *                       |         TSBs          |
487  *                       |-----------------------|- end/nalloc_base
488  *                       |   kernel data & bss   |
489  * 0x00000000.01800000  -|-----------------------|
490  *                       :   nucleus text hole   :
491  * 0x00000000.01400000  -|-----------------------|
492  *                       :                       :
493  *                       |-----------------------|
494  *                       |      module text      |
495  *                       |-----------------------|- e_text/modtext
496  *                       |      kernel text      |
497  *                       |-----------------------|
498  *                       |    trap table (48k)   |
499  * 0x00000000.01000000  -|-----------------------|- KERNELBASE
500  *                       | reserved for trapstat |} TSTAT_TOTAL_SIZE
501  *                       |-----------------------|
502  *                       |                       |
503  *                       |        invalid        |
504  *                       |                       |
505  * 0x00000000.00000000  _|_______________________|
506  *
507  *
508  *
509  *                   32-bit User Virtual Memory Layout.
510  *                       /-----------------------\
511  *                       |                       |
512  *                       |        invalid        |
513  *                       |                       |
514  *          0xFFC00000  -|-----------------------|- USERLIMIT
515  *                       |       user stack      |
516  *                       :                       :
517  *                       :                       :
518  *                       :                       :
519  *                       |       user data       |
520  *                      -|-----------------------|-
521  *                       |       user text       |
522  *          0x00002000  -|-----------------------|-
523  *                       |       invalid         |
524  *          0x00000000  _|_______________________|
525  *
526  *
527  *
528  *                   64-bit User Virtual Memory Layout.
529  *                       /-----------------------\
530  *                       |                       |
531  *                       |        invalid        |
532  *                       |                       |
533  *  0xFFFFFFFF.80000000 -|-----------------------|- USERLIMIT
534  *                       |       user stack      |
535  *                       :                       :
536  *                       :                       :
537  *                       :                       :
538  *                       |       user data       |
539  *                      -|-----------------------|-
540  *                       |       user text       |
541  *  0x00000000.01000000 -|-----------------------|-
542  *                       |       invalid         |
543  *  0x00000000.00000000 _|_______________________|
544  */
545 
546 extern caddr_t ecache_init_scrub_flush_area(caddr_t alloc_base);
547 extern uint64_t ecache_flush_address(void);
548 
549 #pragma weak load_platform_modules
550 #pragma weak plat_startup_memlist
551 #pragma weak ecache_init_scrub_flush_area
552 #pragma weak ecache_flush_address
553 
554 
555 /*
556  * By default the DR Cage is enabled for maximum OS
557  * MPSS performance.  Users needing to disable the cage mechanism
558  * can set this variable to zero via /etc/system.
559  * Disabling the cage on systems supporting Dynamic Reconfiguration (DR)
560  * will result in loss of DR functionality.
561  * Platforms wishing to disable kernel Cage by default
562  * should do so in their set_platform_defaults() routine.
563  */
564 int	kernel_cage_enable = 1;
565 
566 static void
567 setup_cage_params(void)
568 {
569 	void (*func)(void);
570 
571 	func = (void (*)(void))kobj_getsymvalue("set_platform_cage_params", 0);
572 	if (func != NULL) {
573 		(*func)();
574 		return;
575 	}
576 
577 	if (kernel_cage_enable == 0) {
578 		return;
579 	}
580 	kcage_range_init(phys_avail, KCAGE_DOWN, total_pages / 256);
581 
582 	if (kcage_on) {
583 		cmn_err(CE_NOTE, "!Kernel Cage is ENABLED");
584 	} else {
585 		cmn_err(CE_NOTE, "!Kernel Cage is DISABLED");
586 	}
587 
588 }
589 
590 /*
591  * Machine-dependent startup code
592  */
593 void
594 startup(void)
595 {
596 	startup_init();
597 	if (&startup_platform)
598 		startup_platform();
599 	startup_memlist();
600 	startup_modules();
601 	setup_cage_params();
602 	startup_bop_gone();
603 	startup_vm();
604 	startup_end();
605 }
606 
607 struct regs sync_reg_buf;
608 uint64_t sync_tt;
609 
610 void
611 sync_handler(void)
612 {
613 	struct  panic_trap_info 	ti;
614 	int i;
615 
616 	/*
617 	 * Prevent trying to talk to the other CPUs since they are
618 	 * sitting in the prom and won't reply.
619 	 */
620 	for (i = 0; i < NCPU; i++) {
621 		if ((i != CPU->cpu_id) && CPU_XCALL_READY(i)) {
622 			cpu[i]->cpu_flags &= ~CPU_READY;
623 			cpu[i]->cpu_flags |= CPU_QUIESCED;
624 			CPUSET_DEL(cpu_ready_set, cpu[i]->cpu_id);
625 		}
626 	}
627 
628 	/*
629 	 * We've managed to get here without going through the
630 	 * normal panic code path. Try and save some useful
631 	 * information.
632 	 */
633 	if (!panicstr && (curthread->t_panic_trap == NULL)) {
634 		ti.trap_type = sync_tt;
635 		ti.trap_regs = &sync_reg_buf;
636 		ti.trap_addr = NULL;
637 		ti.trap_mmu_fsr = 0x0;
638 
639 		curthread->t_panic_trap = &ti;
640 	}
641 
642 	/*
643 	 * If we're re-entering the panic path, update the signature
644 	 * block so that the SC knows we're in the second part of panic.
645 	 */
646 	if (panicstr)
647 		CPU_SIGNATURE(OS_SIG, SIGST_EXIT, SIGSUBST_DUMP, -1);
648 
649 	nopanicdebug = 1; /* do not perform debug_enter() prior to dump */
650 	panic("sync initiated");
651 }
652 
653 
654 static void
655 startup_init(void)
656 {
657 	/*
658 	 * We want to save the registers while we're still in OBP
659 	 * so that we know they haven't been fiddled with since.
660 	 * (In principle, OBP can't change them just because it
661 	 * makes a callback, but we'd rather not depend on that
662 	 * behavior.)
663 	 */
664 	char		sync_str[] =
665 	    "warning @ warning off : sync "
666 	    "%%tl-c %%tstate h# %p x! "
667 	    "%%g1 h# %p x! %%g2 h# %p x! %%g3 h# %p x! "
668 	    "%%g4 h# %p x! %%g5 h# %p x! %%g6 h# %p x! "
669 	    "%%g7 h# %p x! %%o0 h# %p x! %%o1 h# %p x! "
670 	    "%%o2 h# %p x! %%o3 h# %p x! %%o4 h# %p x! "
671 	    "%%o5 h# %p x! %%o6 h# %p x! %%o7 h# %p x! "
672 	    "%%tl-c %%tpc h# %p x! %%tl-c %%tnpc h# %p x! "
673 	    "%%y h# %p l! %%tl-c %%tt h# %p x! "
674 	    "sync ; warning !";
675 
676 	/*
677 	 * 20 == num of %p substrings
678 	 * 16 == max num of chars %p will expand to.
679 	 */
680 	char 		bp[sizeof (sync_str) + 16 * 20];
681 
682 	/*
683 	 * Initialize ptl1 stack for the 1st CPU.
684 	 */
685 	ptl1_init_cpu(&cpu0);
686 
687 	/*
688 	 * Initialize the address map for cache consistent mappings
689 	 * to random pages; must be done after vac_size is set.
690 	 */
691 	ppmapinit();
692 
693 	/*
694 	 * Initialize the PROM callback handler.
695 	 */
696 	init_vx_handler();
697 
698 	/*
699 	 * have prom call sync_callback() to handle the sync and
700 	 * save some useful information which will be stored in the
701 	 * core file later.
702 	 */
703 	(void) sprintf((char *)bp, sync_str,
704 	    (void *)&sync_reg_buf.r_tstate, (void *)&sync_reg_buf.r_g1,
705 	    (void *)&sync_reg_buf.r_g2, (void *)&sync_reg_buf.r_g3,
706 	    (void *)&sync_reg_buf.r_g4, (void *)&sync_reg_buf.r_g5,
707 	    (void *)&sync_reg_buf.r_g6, (void *)&sync_reg_buf.r_g7,
708 	    (void *)&sync_reg_buf.r_o0, (void *)&sync_reg_buf.r_o1,
709 	    (void *)&sync_reg_buf.r_o2, (void *)&sync_reg_buf.r_o3,
710 	    (void *)&sync_reg_buf.r_o4, (void *)&sync_reg_buf.r_o5,
711 	    (void *)&sync_reg_buf.r_o6, (void *)&sync_reg_buf.r_o7,
712 	    (void *)&sync_reg_buf.r_pc, (void *)&sync_reg_buf.r_npc,
713 	    (void *)&sync_reg_buf.r_y, (void *)&sync_tt);
714 	prom_interpret(bp, 0, 0, 0, 0, 0);
715 	add_vx_handler("sync", 1, (void (*)(cell_t *))sync_handler);
716 }
717 
718 
719 size_t
720 calc_pp_sz(pgcnt_t npages)
721 {
722 
723 	return (npages * sizeof (struct page));
724 }
725 
726 size_t
727 calc_kpmpp_sz(pgcnt_t npages)
728 {
729 
730 	kpm_pgshft = (kpm_smallpages == 0) ? MMU_PAGESHIFT4M : MMU_PAGESHIFT;
731 	kpm_pgsz = 1ull << kpm_pgshft;
732 	kpm_pgoff = kpm_pgsz - 1;
733 	kpmp2pshft = kpm_pgshft - PAGESHIFT;
734 	kpmpnpgs = 1 << kpmp2pshft;
735 
736 	if (kpm_smallpages == 0) {
737 		/*
738 		 * Avoid fragmentation problems in kphysm_init()
739 		 * by allocating for all of physical memory
740 		 */
741 		kpm_npages = ptokpmpr(physinstalled);
742 		return (kpm_npages * sizeof (kpm_page_t));
743 	} else {
744 		kpm_npages = npages;
745 		return (kpm_npages * sizeof (kpm_spage_t));
746 	}
747 }
748 
749 size_t
750 calc_pagehash_sz(pgcnt_t npages)
751 {
752 	/* LINTED */
753 	ASSERT(P2SAMEHIGHBIT((1 << PP_SHIFT), (sizeof (struct page))));
754 	/*
755 	 * The page structure hash table size is a power of 2
756 	 * such that the average hash chain length is PAGE_HASHAVELEN.
757 	 */
758 	page_hashsz = npages / PAGE_HASHAVELEN;
759 	page_hashsz_shift = MAX((AN_VPSHIFT + VNODE_ALIGN_LOG2 + 1),
760 	    highbit(page_hashsz));
761 	page_hashsz = 1 << page_hashsz_shift;
762 	return (page_hashsz * sizeof (struct page *));
763 }
764 
765 int testkmem64_smchunks = 0;
766 
767 int
768 alloc_kmem64(caddr_t base, caddr_t end)
769 {
770 	int i;
771 	caddr_t aligned_end = NULL;
772 
773 	if (testkmem64_smchunks)
774 		return (1);
775 
776 	/*
777 	 * Make one large memory alloc after figuring out the 64-bit size. This
778 	 * will enable use of the largest page size appropriate for the system
779 	 * architecture.
780 	 */
781 	ASSERT(mmu_exported_pagesize_mask & (1 << TTE8K));
782 	ASSERT(IS_P2ALIGNED(base, TTEBYTES(max_bootlp_tteszc)));
783 	for (i = max_bootlp_tteszc; i >= TTE8K; i--) {
784 		size_t alloc_size, alignsize;
785 #if !defined(C_OBP)
786 		unsigned long long pa;
787 #endif	/* !C_OBP */
788 
789 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0)
790 			continue;
791 		alignsize = TTEBYTES(i);
792 		kmem64_szc = i;
793 
794 		/* limit page size for small memory */
795 		if (mmu_btop(alignsize) > (npages >> 2))
796 			continue;
797 
798 		aligned_end = (caddr_t)roundup((uintptr_t)end, alignsize);
799 		alloc_size = aligned_end - base;
800 #if !defined(C_OBP)
801 		if (prom_allocate_phys(alloc_size, alignsize, &pa) == 0) {
802 			if (prom_claim_virt(alloc_size, base) != (caddr_t)-1) {
803 				kmem64_pabase = pa;
804 				kmem64_aligned_end = aligned_end;
805 				install_kmem64_tte();
806 				break;
807 			} else {
808 				prom_free_phys(alloc_size, pa);
809 			}
810 		}
811 #else	/* !C_OBP */
812 		if (prom_alloc(base, alloc_size, alignsize) == base) {
813 			kmem64_pabase = va_to_pa(kmem64_base);
814 			kmem64_aligned_end = aligned_end;
815 			break;
816 		}
817 #endif	/* !C_OBP */
818 		if (i == TTE8K) {
819 #ifdef sun4v
820 			/* return failure to try small allocations */
821 			return (1);
822 #else
823 			prom_panic("kmem64 allocation failure");
824 #endif
825 		}
826 	}
827 	ASSERT(aligned_end != NULL);
828 	return (0);
829 }
830 
831 static prom_memlist_t *boot_physinstalled, *boot_physavail, *boot_virtavail;
832 static size_t boot_physinstalled_len, boot_physavail_len, boot_virtavail_len;
833 
834 #if !defined(C_OBP)
835 /*
836  * Install a temporary tte handler in OBP for kmem64 area.
837  *
838  * We map kmem64 area with large pages before the trap table is taken
839  * over. Since OBP makes 8K mappings, it can create 8K tlb entries in
840  * the same area. Duplicate tlb entries with different page sizes
841  * cause unpredicatble behavior.  To avoid this, we don't create
842  * kmem64 mappings via BOP_ALLOC (ends up as prom_alloc() call to
843  * OBP).  Instead, we manage translations with a temporary va>tte-data
844  * handler (kmem64-tte).  This handler is replaced by unix-tte when
845  * the trap table is taken over.
846  *
847  * The temporary handler knows the physical address of the kmem64
848  * area. It uses the prom's pgmap@ Forth word for other addresses.
849  *
850  * We have to use BOP_ALLOC() method for C-OBP platforms because
851  * pgmap@ is not defined in C-OBP. C-OBP is only used on serengeti
852  * sun4u platforms. On sun4u we flush tlb after trap table is taken
853  * over if we use large pages for kernel heap and kmem64. Since sun4u
854  * prom (unlike sun4v) calls va>tte-data first for client address
855  * translation prom's ttes for kmem64 can't get into TLB even if we
856  * later switch to prom's trap table again. C-OBP uses 4M pages for
857  * client mappings when possible so on all platforms we get the
858  * benefit from large mappings for kmem64 area immediately during
859  * boot.
860  *
861  * pseudo code:
862  * if (context != 0) {
863  * 	return false
864  * } else if (miss_va in range[kmem64_base, kmem64_end)) {
865  *	tte = tte_template +
866  *		(((miss_va & pagemask) - kmem64_base));
867  *	return tte, true
868  * } else {
869  *	return pgmap@ result
870  * }
871  */
872 char kmem64_obp_str[] =
873 	"h# %lx constant kmem64-base "
874 	"h# %lx constant kmem64-end "
875 	"h# %lx constant kmem64-pagemask "
876 	"h# %lx constant kmem64-template "
877 
878 	": kmem64-tte ( addr cnum -- false | tte-data true ) "
879 	"    if                                       ( addr ) "
880 	"       drop false exit then                  ( false ) "
881 	"    dup  kmem64-base kmem64-end  within  if  ( addr ) "
882 	"	kmem64-pagemask and                   ( addr' ) "
883 	"	kmem64-base -                         ( addr' ) "
884 	"	kmem64-template +                     ( tte ) "
885 	"	true                                  ( tte true ) "
886 	"    else                                     ( addr ) "
887 	"	pgmap@                                ( tte ) "
888 	"       dup 0< if true else drop false then   ( tte true  |  false ) "
889 	"    then                                     ( tte true  |  false ) "
890 	"; "
891 
892 	"' kmem64-tte is va>tte-data "
893 ;
894 
895 static void
896 install_kmem64_tte()
897 {
898 	char b[sizeof (kmem64_obp_str) + (4 * 16)];
899 	tte_t tte;
900 
901 	PRM_DEBUG(kmem64_pabase);
902 	PRM_DEBUG(kmem64_szc);
903 	sfmmu_memtte(&tte, kmem64_pabase >> MMU_PAGESHIFT,
904 	    PROC_DATA | HAT_NOSYNC, kmem64_szc);
905 	PRM_DEBUG(tte.ll);
906 	(void) sprintf(b, kmem64_obp_str,
907 	    kmem64_base, kmem64_end, TTE_PAGEMASK(kmem64_szc), tte.ll);
908 	ASSERT(strlen(b) < sizeof (b));
909 	prom_interpret(b, 0, 0, 0, 0, 0);
910 }
911 #endif	/* !C_OBP */
912 
913 /*
914  * As OBP takes up some RAM when the system boots, pages will already be "lost"
915  * to the system and reflected in npages by the time we see it.
916  *
917  * We only want to allocate kernel structures in the 64-bit virtual address
918  * space on systems with enough RAM to make the overhead of keeping track of
919  * an extra kernel memory segment worthwhile.
920  *
921  * Since OBP has already performed its memory allocations by this point, if we
922  * have more than MINMOVE_RAM_MB MB of RAM left free, go ahead and map
923  * memory in the 64-bit virtual address space; otherwise keep allocations
924  * contiguous with we've mapped so far in the 32-bit virtual address space.
925  */
926 #define	MINMOVE_RAM_MB	((size_t)1900)
927 #define	MB_TO_BYTES(mb)	((mb) * 1048576ul)
928 #define	BYTES_TO_MB(b) ((b) / 1048576ul)
929 
930 pgcnt_t	tune_npages = (pgcnt_t)
931 	(MB_TO_BYTES(MINMOVE_RAM_MB)/ (size_t)MMU_PAGESIZE);
932 
933 #pragma weak page_set_colorequiv_arr_cpu
934 extern void page_set_colorequiv_arr_cpu(void);
935 extern void page_set_colorequiv_arr(void);
936 
937 static pgcnt_t ramdisk_npages;
938 static struct memlist *old_phys_avail;
939 
940 kcage_dir_t kcage_startup_dir = KCAGE_DOWN;
941 
942 static void
943 startup_memlist(void)
944 {
945 	size_t hmehash_sz, pagelist_sz, tt_sz;
946 	size_t psetable_sz;
947 	caddr_t alloc_base;
948 	caddr_t memspace;
949 	struct memlist *cur;
950 	size_t syslimit = (size_t)SYSLIMIT;
951 	size_t sysbase = (size_t)SYSBASE;
952 
953 	/*
954 	 * Initialize enough of the system to allow kmem_alloc to work by
955 	 * calling boot to allocate its memory until the time that
956 	 * kvm_init is completed.  The page structs are allocated after
957 	 * rounding up end to the nearest page boundary; the memsegs are
958 	 * initialized and the space they use comes from the kernel heap.
959 	 * With appropriate initialization, they can be reallocated later
960 	 * to a size appropriate for the machine's configuration.
961 	 *
962 	 * At this point, memory is allocated for things that will never
963 	 * need to be freed, this used to be "valloced".  This allows a
964 	 * savings as the pages don't need page structures to describe
965 	 * them because them will not be managed by the vm system.
966 	 */
967 
968 	/*
969 	 * We're loaded by boot with the following configuration (as
970 	 * specified in the sun4u/conf/Mapfile):
971 	 *
972 	 * 	text:		4 MB chunk aligned on a 4MB boundary
973 	 * 	data & bss:	4 MB chunk aligned on a 4MB boundary
974 	 *
975 	 * These two chunks will eventually be mapped by 2 locked 4MB
976 	 * ttes and will represent the nucleus of the kernel.  This gives
977 	 * us some free space that is already allocated, some or all of
978 	 * which is made available to kernel module text.
979 	 *
980 	 * The free space in the data-bss chunk is used for nucleus
981 	 * allocatable data structures and we reserve it using the
982 	 * nalloc_base and nalloc_end variables.  This space is currently
983 	 * being used for hat data structures required for tlb miss
984 	 * handling operations.  We align nalloc_base to a l2 cache
985 	 * linesize because this is the line size the hardware uses to
986 	 * maintain cache coherency.
987 	 * 512K is carved out for module data.
988 	 */
989 
990 	moddata = (caddr_t)roundup((uintptr_t)e_data, MMU_PAGESIZE);
991 	e_moddata = moddata + MODDATA;
992 	nalloc_base = e_moddata;
993 
994 	nalloc_end = (caddr_t)roundup((uintptr_t)nalloc_base, MMU_PAGESIZE4M);
995 	valloc_base = nalloc_base;
996 
997 	/*
998 	 * Calculate the start of the data segment.
999 	 */
1000 	if (((uintptr_t)e_moddata & MMU_PAGEMASK4M) != (uintptr_t)s_data)
1001 		prom_panic("nucleus data overflow");
1002 
1003 	PRM_DEBUG(moddata);
1004 	PRM_DEBUG(nalloc_base);
1005 	PRM_DEBUG(nalloc_end);
1006 
1007 	/*
1008 	 * Remember any slop after e_text so we can give it to the modules.
1009 	 */
1010 	PRM_DEBUG(e_text);
1011 	modtext = (caddr_t)roundup((uintptr_t)e_text, MMU_PAGESIZE);
1012 	if (((uintptr_t)e_text & MMU_PAGEMASK4M) != (uintptr_t)s_text)
1013 		prom_panic("nucleus text overflow");
1014 	modtext_sz = (caddr_t)roundup((uintptr_t)modtext, MMU_PAGESIZE4M) -
1015 	    modtext;
1016 	PRM_DEBUG(modtext);
1017 	PRM_DEBUG(modtext_sz);
1018 
1019 	init_boot_memlists();
1020 	copy_boot_memlists(&boot_physinstalled, &boot_physinstalled_len,
1021 	    &boot_physavail, &boot_physavail_len,
1022 	    &boot_virtavail, &boot_virtavail_len);
1023 
1024 	/*
1025 	 * Remember what the physically available highest page is
1026 	 * so that dumpsys works properly, and find out how much
1027 	 * memory is installed.
1028 	 */
1029 	installed_top_size_memlist_array(boot_physinstalled,
1030 	    boot_physinstalled_len, &physmax, &physinstalled);
1031 	PRM_DEBUG(physinstalled);
1032 	PRM_DEBUG(physmax);
1033 
1034 	/* Fill out memory nodes config structure */
1035 	startup_build_mem_nodes(boot_physinstalled, boot_physinstalled_len);
1036 
1037 	/*
1038 	 * npages is the maximum of available physical memory possible.
1039 	 * (ie. it will never be more than this)
1040 	 *
1041 	 * When we boot from a ramdisk, the ramdisk memory isn't free, so
1042 	 * using phys_avail will underestimate what will end up being freed.
1043 	 * A better initial guess is just total memory minus the kernel text
1044 	 */
1045 	npages = physinstalled - btop(MMU_PAGESIZE4M);
1046 
1047 	/*
1048 	 * First allocate things that can go in the nucleus data page
1049 	 * (fault status, TSBs, dmv, CPUs)
1050 	 */
1051 	ndata_alloc_init(&ndata, (uintptr_t)nalloc_base, (uintptr_t)nalloc_end);
1052 
1053 	if ((&ndata_alloc_mmfsa != NULL) && (ndata_alloc_mmfsa(&ndata) != 0))
1054 		cmn_err(CE_PANIC, "no more nucleus memory after mfsa alloc");
1055 
1056 	if (ndata_alloc_tsbs(&ndata, npages) != 0)
1057 		cmn_err(CE_PANIC, "no more nucleus memory after tsbs alloc");
1058 
1059 	if (ndata_alloc_dmv(&ndata) != 0)
1060 		cmn_err(CE_PANIC, "no more nucleus memory after dmv alloc");
1061 
1062 	if (ndata_alloc_page_mutexs(&ndata) != 0)
1063 		cmn_err(CE_PANIC,
1064 		    "no more nucleus memory after page free lists alloc");
1065 
1066 	if (ndata_alloc_hat(&ndata, npages) != 0)
1067 		cmn_err(CE_PANIC, "no more nucleus memory after hat alloc");
1068 
1069 	if (ndata_alloc_memseg(&ndata, boot_physavail_len) != 0)
1070 		cmn_err(CE_PANIC, "no more nucleus memory after memseg alloc");
1071 
1072 	/*
1073 	 * WARNING WARNING WARNING WARNING WARNING WARNING WARNING
1074 	 *
1075 	 * There are comments all over the SFMMU code warning of dire
1076 	 * consequences if the TSBs are moved out of 32-bit space.  This
1077 	 * is largely because the asm code uses "sethi %hi(addr)"-type
1078 	 * instructions which will not provide the expected result if the
1079 	 * address is a 64-bit one.
1080 	 *
1081 	 * WARNING WARNING WARNING WARNING WARNING WARNING WARNING
1082 	 */
1083 	alloc_base = (caddr_t)roundup((uintptr_t)nalloc_end, MMU_PAGESIZE);
1084 	PRM_DEBUG(alloc_base);
1085 
1086 	alloc_base = sfmmu_ktsb_alloc(alloc_base);
1087 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1088 	PRM_DEBUG(alloc_base);
1089 
1090 	/*
1091 	 * Allocate IOMMU TSB array.  We do this here so that the physical
1092 	 * memory gets deducted from the PROM's physical memory list.
1093 	 */
1094 	alloc_base = iommu_tsb_init(alloc_base);
1095 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1096 	PRM_DEBUG(alloc_base);
1097 
1098 	/*
1099 	 * Allow for an early allocation of physically contiguous memory.
1100 	 */
1101 	alloc_base = contig_mem_prealloc(alloc_base, npages);
1102 
1103 	/*
1104 	 * Platforms like Starcat and OPL need special structures assigned in
1105 	 * 32-bit virtual address space because their probing routines execute
1106 	 * FCode, and FCode can't handle 64-bit virtual addresses...
1107 	 */
1108 	if (&plat_startup_memlist) {
1109 		alloc_base = plat_startup_memlist(alloc_base);
1110 		alloc_base = (caddr_t)roundup((uintptr_t)alloc_base,
1111 		    ecache_alignsize);
1112 		PRM_DEBUG(alloc_base);
1113 	}
1114 
1115 	/*
1116 	 * Save off where the contiguous allocations to date have ended
1117 	 * in econtig32.
1118 	 */
1119 	econtig32 = alloc_base;
1120 	PRM_DEBUG(econtig32);
1121 	if (econtig32 > (caddr_t)KERNEL_LIMIT32)
1122 		cmn_err(CE_PANIC, "econtig32 too big");
1123 
1124 	pp_sz = calc_pp_sz(npages);
1125 	PRM_DEBUG(pp_sz);
1126 	if (kpm_enable) {
1127 		kpm_pp_sz = calc_kpmpp_sz(npages);
1128 		PRM_DEBUG(kpm_pp_sz);
1129 	}
1130 
1131 	hmehash_sz = calc_hmehash_sz(npages);
1132 	PRM_DEBUG(hmehash_sz);
1133 
1134 	pagehash_sz = calc_pagehash_sz(npages);
1135 	PRM_DEBUG(pagehash_sz);
1136 
1137 	pagelist_sz = calc_free_pagelist_sz();
1138 	PRM_DEBUG(pagelist_sz);
1139 
1140 #ifdef	TRAPTRACE
1141 	tt_sz = calc_traptrace_sz();
1142 	PRM_DEBUG(tt_sz);
1143 #else
1144 	tt_sz = 0;
1145 #endif	/* TRAPTRACE */
1146 
1147 	/*
1148 	 * Place the array that protects pp->p_selock in the kmem64 wad.
1149 	 */
1150 	pse_shift = size_pse_array(npages, max_ncpus);
1151 	PRM_DEBUG(pse_shift);
1152 	pse_table_size = 1 << pse_shift;
1153 	PRM_DEBUG(pse_table_size);
1154 	psetable_sz = roundup(
1155 	    pse_table_size * sizeof (pad_mutex_t), ecache_alignsize);
1156 	PRM_DEBUG(psetable_sz);
1157 
1158 	/*
1159 	 * Now allocate the whole wad
1160 	 */
1161 	kmem64_sz = pp_sz + kpm_pp_sz + hmehash_sz + pagehash_sz +
1162 	    pagelist_sz + tt_sz + psetable_sz;
1163 	kmem64_sz = roundup(kmem64_sz, PAGESIZE);
1164 	kmem64_base = (caddr_t)syslimit;
1165 	kmem64_end = kmem64_base + kmem64_sz;
1166 	if (alloc_kmem64(kmem64_base, kmem64_end)) {
1167 		/*
1168 		 * Attempt for kmem64 to allocate one big
1169 		 * contiguous chunk of memory failed.
1170 		 * We get here because we are sun4v.
1171 		 * We will proceed by breaking up
1172 		 * the allocation into two attempts.
1173 		 * First, we allocate kpm_pp_sz, hmehash_sz,
1174 		 * pagehash_sz, pagelist_sz, tt_sz & psetable_sz as
1175 		 * one contiguous chunk. This is a much smaller
1176 		 * chunk and we should get it, if not we panic.
1177 		 * Note that hmehash and tt need to be physically
1178 		 * (in the real address sense) contiguous.
1179 		 * Next, we use bop_alloc_chunk() to
1180 		 * to allocate the page_t structures.
1181 		 * This will allow the page_t to be allocated
1182 		 * in multiple smaller chunks.
1183 		 * In doing so, the assumption that page_t is
1184 		 * physically contiguous no longer hold, this is ok
1185 		 * for sun4v but not for sun4u.
1186 		 */
1187 		size_t  tmp_size;
1188 		caddr_t tmp_base;
1189 
1190 		pp_sz  = roundup(pp_sz, PAGESIZE);
1191 
1192 		/*
1193 		 * Allocate kpm_pp_sz, hmehash_sz,
1194 		 * pagehash_sz, pagelist_sz, tt_sz & psetable_sz
1195 		 */
1196 		tmp_base = kmem64_base + pp_sz;
1197 		tmp_size = roundup(kpm_pp_sz + hmehash_sz + pagehash_sz +
1198 		    pagelist_sz + tt_sz + psetable_sz, PAGESIZE);
1199 		if (prom_alloc(tmp_base, tmp_size, PAGESIZE) == 0)
1200 			prom_panic("kmem64 prom_alloc contig failed");
1201 		PRM_DEBUG(tmp_base);
1202 		PRM_DEBUG(tmp_size);
1203 
1204 		/*
1205 		 * Allocate the page_ts
1206 		 */
1207 		if (bop_alloc_chunk(kmem64_base, pp_sz, PAGESIZE) == 0)
1208 			prom_panic("kmem64 bop_alloc_chunk page_t failed");
1209 		PRM_DEBUG(kmem64_base);
1210 		PRM_DEBUG(pp_sz);
1211 
1212 		kmem64_aligned_end = kmem64_base + pp_sz + tmp_size;
1213 		ASSERT(kmem64_aligned_end >= kmem64_end);
1214 
1215 		kmem64_smchunks = 1;
1216 	} else {
1217 
1218 		/*
1219 		 * We need to adjust pp_sz for the normal
1220 		 * case where kmem64 can allocate one large chunk
1221 		 */
1222 		if (kpm_smallpages == 0) {
1223 			npages -= kmem64_sz / (PAGESIZE + sizeof (struct page));
1224 		} else {
1225 			npages -= kmem64_sz / (PAGESIZE + sizeof (struct page) +
1226 			    sizeof (kpm_spage_t));
1227 		}
1228 		pp_sz = npages * sizeof (struct page);
1229 	}
1230 
1231 	if (kmem64_aligned_end > (hole_start ? hole_start : kpm_vbase))
1232 		cmn_err(CE_PANIC, "not enough kmem64 space");
1233 	PRM_DEBUG(kmem64_base);
1234 	PRM_DEBUG(kmem64_end);
1235 	PRM_DEBUG(kmem64_aligned_end);
1236 
1237 	/*
1238 	 * ... and divy it up
1239 	 */
1240 	alloc_base = kmem64_base;
1241 
1242 	pp_base = (page_t *)alloc_base;
1243 	alloc_base += pp_sz;
1244 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1245 	PRM_DEBUG(pp_base);
1246 	PRM_DEBUG(npages);
1247 
1248 	if (kpm_enable) {
1249 		kpm_pp_base = alloc_base;
1250 		if (kpm_smallpages == 0) {
1251 			/* kpm_npages based on physinstalled, don't reset */
1252 			kpm_pp_sz = kpm_npages * sizeof (kpm_page_t);
1253 		} else {
1254 			kpm_npages = ptokpmpr(npages);
1255 			kpm_pp_sz = kpm_npages * sizeof (kpm_spage_t);
1256 		}
1257 		alloc_base += kpm_pp_sz;
1258 		alloc_base =
1259 		    (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1260 		PRM_DEBUG(kpm_pp_base);
1261 	}
1262 
1263 	alloc_base = alloc_hmehash(alloc_base);
1264 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1265 	PRM_DEBUG(alloc_base);
1266 
1267 	page_hash = (page_t **)alloc_base;
1268 	alloc_base += pagehash_sz;
1269 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1270 	PRM_DEBUG(page_hash);
1271 
1272 	alloc_base = alloc_page_freelists(alloc_base);
1273 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1274 	PRM_DEBUG(alloc_base);
1275 
1276 #ifdef	TRAPTRACE
1277 	ttrace_buf = alloc_base;
1278 	alloc_base += tt_sz;
1279 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1280 	PRM_DEBUG(alloc_base);
1281 #endif	/* TRAPTRACE */
1282 
1283 	pse_mutex = (pad_mutex_t *)alloc_base;
1284 	alloc_base += psetable_sz;
1285 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, ecache_alignsize);
1286 	PRM_DEBUG(alloc_base);
1287 
1288 	/*
1289 	 * Note that if we use small chunk allocations for
1290 	 * kmem64, we need to ensure kmem64_end is the same as
1291 	 * kmem64_aligned_end to prevent subsequent logic from
1292 	 * trying to reuse the overmapping.
1293 	 * Otherwise we adjust kmem64_end to what we really allocated.
1294 	 */
1295 	if (kmem64_smchunks) {
1296 		kmem64_end = kmem64_aligned_end;
1297 	} else {
1298 		kmem64_end = (caddr_t)roundup((uintptr_t)alloc_base, PAGESIZE);
1299 	}
1300 	kmem64_sz = kmem64_end - kmem64_base;
1301 
1302 	if (&ecache_init_scrub_flush_area) {
1303 		alloc_base = ecache_init_scrub_flush_area(kmem64_aligned_end);
1304 		ASSERT(alloc_base <= (hole_start ? hole_start : kpm_vbase));
1305 	}
1306 
1307 	/*
1308 	 * If physmem is patched to be non-zero, use it instead of
1309 	 * the monitor value unless physmem is larger than the total
1310 	 * amount of memory on hand.
1311 	 */
1312 	if (physmem == 0 || physmem > npages)
1313 		physmem = npages;
1314 
1315 	/*
1316 	 * root_is_ramdisk is set via /etc/system when the ramdisk miniroot
1317 	 * is mounted as root. This memory is held down by OBP and unlike
1318 	 * the stub boot_archive is never released.
1319 	 *
1320 	 * In order to get things sized correctly on lower memory
1321 	 * machines (where the memory used by the ramdisk represents
1322 	 * a significant portion of memory), physmem is adjusted.
1323 	 *
1324 	 * This is done by subtracting the ramdisk_size which is set
1325 	 * to the size of the ramdisk (in Kb) in /etc/system at the
1326 	 * time the miniroot archive is constructed.
1327 	 */
1328 	if (root_is_ramdisk == B_TRUE) {
1329 		ramdisk_npages = (ramdisk_size * 1024) / PAGESIZE;
1330 		physmem -= ramdisk_npages;
1331 	}
1332 
1333 	if (kpm_enable && (ndata_alloc_kpm(&ndata, kpm_npages) != 0))
1334 		cmn_err(CE_PANIC, "no more nucleus memory after kpm alloc");
1335 
1336 	/*
1337 	 * Allocate space for the interrupt vector table.
1338 	 */
1339 	memspace = prom_alloc((caddr_t)intr_vec_table, IVSIZE, MMU_PAGESIZE);
1340 	if (memspace != (caddr_t)intr_vec_table)
1341 		prom_panic("interrupt vector table allocation failure");
1342 
1343 	/*
1344 	 * Between now and when we finish copying in the memory lists,
1345 	 * allocations happen so the space gets fragmented and the
1346 	 * lists longer.  Leave enough space for lists twice as
1347 	 * long as we have now; then roundup to a pagesize.
1348 	 */
1349 	memlist_sz = sizeof (struct memlist) * (prom_phys_installed_len() +
1350 	    prom_phys_avail_len() + prom_virt_avail_len());
1351 	memlist_sz *= 2;
1352 	memlist_sz = roundup(memlist_sz, PAGESIZE);
1353 	memspace = ndata_alloc(&ndata, memlist_sz, ecache_alignsize);
1354 	if (memspace == NULL)
1355 		cmn_err(CE_PANIC, "no more nucleus memory after memlist alloc");
1356 
1357 	memlist = (struct memlist *)memspace;
1358 	memlist_end = (char *)memspace + memlist_sz;
1359 	PRM_DEBUG(memlist);
1360 	PRM_DEBUG(memlist_end);
1361 
1362 	PRM_DEBUG(sysbase);
1363 	PRM_DEBUG(syslimit);
1364 	kernelheap_init((void *)sysbase, (void *)syslimit,
1365 	    (caddr_t)sysbase + PAGESIZE, NULL, NULL);
1366 
1367 	/*
1368 	 * Take the most current snapshot we can by calling mem-update.
1369 	 */
1370 	copy_boot_memlists(&boot_physinstalled, &boot_physinstalled_len,
1371 	    &boot_physavail, &boot_physavail_len,
1372 	    &boot_virtavail, &boot_virtavail_len);
1373 
1374 	/*
1375 	 * Remove the space used by prom_alloc from the kernel heap
1376 	 * plus the area actually used by the OBP (if any)
1377 	 * ignoring virtual addresses in virt_avail, above syslimit.
1378 	 */
1379 	virt_avail = memlist;
1380 	copy_memlist(boot_virtavail, boot_virtavail_len, &memlist);
1381 
1382 	for (cur = virt_avail; cur->ml_next; cur = cur->ml_next) {
1383 		uint64_t range_base, range_size;
1384 
1385 		if ((range_base = cur->ml_address + cur->ml_size) <
1386 		    (uint64_t)sysbase)
1387 			continue;
1388 		if (range_base >= (uint64_t)syslimit)
1389 			break;
1390 		/*
1391 		 * Limit the range to end at syslimit.
1392 		 */
1393 		range_size = MIN(cur->ml_next->ml_address,
1394 		    (uint64_t)syslimit) - range_base;
1395 		(void) vmem_xalloc(heap_arena, (size_t)range_size, PAGESIZE,
1396 		    0, 0, (void *)range_base, (void *)(range_base + range_size),
1397 		    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
1398 	}
1399 
1400 	phys_avail = memlist;
1401 	copy_memlist(boot_physavail, boot_physavail_len, &memlist);
1402 
1403 	/*
1404 	 * Add any extra memory at the end of the ndata region if there's at
1405 	 * least a page to add.  There might be a few more pages available in
1406 	 * the middle of the ndata region, but for now they are ignored.
1407 	 */
1408 	nalloc_base = ndata_extra_base(&ndata, MMU_PAGESIZE, nalloc_end);
1409 	if (nalloc_base == NULL)
1410 		nalloc_base = nalloc_end;
1411 	ndata_remain_sz = nalloc_end - nalloc_base;
1412 
1413 	/*
1414 	 * Copy physinstalled list into kernel space.
1415 	 */
1416 	phys_install = memlist;
1417 	copy_memlist(boot_physinstalled, boot_physinstalled_len, &memlist);
1418 
1419 	/*
1420 	 * Create list of physical addrs we don't need pp's for:
1421 	 * kernel text 4M page
1422 	 * kernel data 4M page - ndata_remain_sz
1423 	 * kmem64 pages
1424 	 *
1425 	 * NB if adding any pages here, make sure no kpm page
1426 	 * overlaps can occur (see ASSERTs in kphysm_memsegs)
1427 	 */
1428 	nopp_list = memlist;
1429 	memlist_new(va_to_pa(s_text), MMU_PAGESIZE4M, &memlist);
1430 	memlist_add(va_to_pa(s_data), MMU_PAGESIZE4M - ndata_remain_sz,
1431 	    &memlist, &nopp_list);
1432 
1433 	/* Don't add to nopp_list if kmem64 was allocated in smchunks */
1434 	if (!kmem64_smchunks)
1435 		memlist_add(kmem64_pabase, kmem64_sz, &memlist, &nopp_list);
1436 
1437 	if ((caddr_t)memlist > (memspace + memlist_sz))
1438 		prom_panic("memlist overflow");
1439 
1440 	/*
1441 	 * Size the pcf array based on the number of cpus in the box at
1442 	 * boot time.
1443 	 */
1444 	pcf_init();
1445 
1446 	/*
1447 	 * Initialize the page structures from the memory lists.
1448 	 */
1449 	kphysm_init();
1450 
1451 	availrmem_initial = availrmem = freemem;
1452 	PRM_DEBUG(availrmem);
1453 
1454 	/*
1455 	 * Some of the locks depend on page_hashsz being set!
1456 	 * kmem_init() depends on this; so, keep it here.
1457 	 */
1458 	page_lock_init();
1459 
1460 	/*
1461 	 * Initialize kernel memory allocator.
1462 	 */
1463 	kmem_init();
1464 
1465 	/*
1466 	 * Factor in colorequiv to check additional 'equivalent' bins
1467 	 */
1468 	if (&page_set_colorequiv_arr_cpu != NULL)
1469 		page_set_colorequiv_arr_cpu();
1470 	else
1471 		page_set_colorequiv_arr();
1472 
1473 	/*
1474 	 * Initialize bp_mapin().
1475 	 */
1476 	bp_init(shm_alignment, HAT_STRICTORDER);
1477 
1478 	/*
1479 	 * Reserve space for MPO mblock structs from the 32-bit heap.
1480 	 */
1481 
1482 	if (mpo_heap32_bufsz > (size_t)0) {
1483 		(void) vmem_xalloc(heap32_arena, mpo_heap32_bufsz,
1484 		    PAGESIZE, 0, 0, mpo_heap32_buf,
1485 		    mpo_heap32_buf + mpo_heap32_bufsz,
1486 		    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
1487 	}
1488 	mem_config_init();
1489 }
1490 
1491 static void
1492 startup_modules(void)
1493 {
1494 	int nhblk1, nhblk8;
1495 	size_t  nhblksz;
1496 	pgcnt_t pages_per_hblk;
1497 	size_t hme8blk_sz, hme1blk_sz;
1498 
1499 	/*
1500 	 * Let the platforms have a chance to change default
1501 	 * values before reading system file.
1502 	 */
1503 	if (&set_platform_defaults)
1504 		set_platform_defaults();
1505 
1506 	/*
1507 	 * Calculate default settings of system parameters based upon
1508 	 * maxusers, yet allow to be overridden via the /etc/system file.
1509 	 */
1510 	param_calc(0);
1511 
1512 	mod_setup();
1513 
1514 	/*
1515 	 * If this is a positron, complain and halt.
1516 	 */
1517 	if (&iam_positron && iam_positron()) {
1518 		cmn_err(CE_WARN, "This hardware platform is not supported"
1519 		    " by this release of Solaris.\n");
1520 #ifdef DEBUG
1521 		prom_enter_mon();	/* Type 'go' to resume */
1522 		cmn_err(CE_WARN, "Booting an unsupported platform.\n");
1523 		cmn_err(CE_WARN, "Booting with down-rev firmware.\n");
1524 
1525 #else /* DEBUG */
1526 		halt(0);
1527 #endif /* DEBUG */
1528 	}
1529 
1530 	/*
1531 	 * If we are running firmware that isn't 64-bit ready
1532 	 * then complain and halt.
1533 	 */
1534 	do_prom_version_check();
1535 
1536 	/*
1537 	 * Initialize system parameters
1538 	 */
1539 	param_init();
1540 
1541 	/*
1542 	 * maxmem is the amount of physical memory we're playing with.
1543 	 */
1544 	maxmem = physmem;
1545 
1546 	/* Set segkp limits. */
1547 	ncbase = kdi_segdebugbase;
1548 	ncend = kdi_segdebugbase;
1549 
1550 	/*
1551 	 * Initialize the hat layer.
1552 	 */
1553 	hat_init();
1554 
1555 	/*
1556 	 * Initialize segment management stuff.
1557 	 */
1558 	seg_init();
1559 
1560 	/*
1561 	 * Create the va>tte handler, so the prom can understand
1562 	 * kernel translations.  The handler is installed later, just
1563 	 * as we are about to take over the trap table from the prom.
1564 	 */
1565 	create_va_to_tte();
1566 
1567 	/*
1568 	 * Load the forthdebugger (optional)
1569 	 */
1570 	forthdebug_init();
1571 
1572 	/*
1573 	 * Create OBP node for console input callbacks
1574 	 * if it is needed.
1575 	 */
1576 	startup_create_io_node();
1577 
1578 	if (modloadonly("fs", "specfs") == -1)
1579 		halt("Can't load specfs");
1580 
1581 	if (modloadonly("fs", "devfs") == -1)
1582 		halt("Can't load devfs");
1583 
1584 	if (modloadonly("fs", "procfs") == -1)
1585 		halt("Can't load procfs");
1586 
1587 	if (modloadonly("misc", "swapgeneric") == -1)
1588 		halt("Can't load swapgeneric");
1589 
1590 	(void) modloadonly("sys", "lbl_edition");
1591 
1592 	dispinit();
1593 
1594 	/*
1595 	 * Infer meanings to the members of the idprom buffer.
1596 	 */
1597 	parse_idprom();
1598 
1599 	/* Read cluster configuration data. */
1600 	clconf_init();
1601 
1602 	setup_ddi();
1603 
1604 	/*
1605 	 * Lets take this opportunity to load the root device.
1606 	 */
1607 	if (loadrootmodules() != 0)
1608 		debug_enter("Can't load the root filesystem");
1609 
1610 	/*
1611 	 * Load tod driver module for the tod part found on this system.
1612 	 * Recompute the cpu frequency/delays based on tod as tod part
1613 	 * tends to keep time more accurately.
1614 	 */
1615 	if (&load_tod_module)
1616 		load_tod_module();
1617 
1618 	/*
1619 	 * Allow platforms to load modules which might
1620 	 * be needed after bootops are gone.
1621 	 */
1622 	if (&load_platform_modules)
1623 		load_platform_modules();
1624 
1625 	setcpudelay();
1626 
1627 	copy_boot_memlists(&boot_physinstalled, &boot_physinstalled_len,
1628 	    &boot_physavail, &boot_physavail_len,
1629 	    &boot_virtavail, &boot_virtavail_len);
1630 
1631 	/*
1632 	 * Calculation and allocation of hmeblks needed to remap
1633 	 * the memory allocated by PROM till now.
1634 	 * Overestimate the number of hblk1 elements by assuming
1635 	 * worst case of TTE64K mappings.
1636 	 * sfmmu_hblk_alloc will panic if this calculation is wrong.
1637 	 */
1638 	bop_alloc_pages = btopr(kmem64_end - kmem64_base);
1639 	pages_per_hblk = btop(HMEBLK_SPAN(TTE64K));
1640 	bop_alloc_pages = roundup(bop_alloc_pages, pages_per_hblk);
1641 	nhblk1 = bop_alloc_pages / pages_per_hblk + hblk1_min;
1642 
1643 	bop_alloc_pages = size_virtalloc(boot_virtavail, boot_virtavail_len);
1644 
1645 	/* sfmmu_init_nucleus_hblks expects properly aligned data structures */
1646 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
1647 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
1648 
1649 	bop_alloc_pages += btopr(nhblk1 * hme1blk_sz);
1650 
1651 	pages_per_hblk = btop(HMEBLK_SPAN(TTE8K));
1652 	nhblk8 = 0;
1653 	while (bop_alloc_pages > 1) {
1654 		bop_alloc_pages = roundup(bop_alloc_pages, pages_per_hblk);
1655 		nhblk8 += bop_alloc_pages /= pages_per_hblk;
1656 		bop_alloc_pages *= hme8blk_sz;
1657 		bop_alloc_pages = btopr(bop_alloc_pages);
1658 	}
1659 	nhblk8 += 2;
1660 
1661 	/*
1662 	 * Since hblk8's can hold up to 64k of mappings aligned on a 64k
1663 	 * boundary, the number of hblk8's needed to map the entries in the
1664 	 * boot_virtavail list needs to be adjusted to take this into
1665 	 * consideration.  Thus, we need to add additional hblk8's since it
1666 	 * is possible that an hblk8 will not have all 8 slots used due to
1667 	 * alignment constraints.  Since there were boot_virtavail_len entries
1668 	 * in that list, we need to add that many hblk8's to the number
1669 	 * already calculated to make sure we don't underestimate.
1670 	 */
1671 	nhblk8 += boot_virtavail_len;
1672 	nhblksz = nhblk8 * hme8blk_sz + nhblk1 * hme1blk_sz;
1673 
1674 	/* Allocate in pagesize chunks */
1675 	nhblksz = roundup(nhblksz, MMU_PAGESIZE);
1676 	hblk_base = kmem_zalloc(nhblksz, KM_SLEEP);
1677 	sfmmu_init_nucleus_hblks(hblk_base, nhblksz, nhblk8, nhblk1);
1678 }
1679 
1680 static void
1681 startup_bop_gone(void)
1682 {
1683 
1684 	/*
1685 	 * Destroy the MD initialized at startup
1686 	 * The startup initializes the MD framework
1687 	 * using prom and BOP alloc free it now.
1688 	 */
1689 	mach_descrip_startup_fini();
1690 
1691 	/*
1692 	 * We're done with prom allocations.
1693 	 */
1694 	bop_fini();
1695 
1696 	copy_boot_memlists(&boot_physinstalled, &boot_physinstalled_len,
1697 	    &boot_physavail, &boot_physavail_len,
1698 	    &boot_virtavail, &boot_virtavail_len);
1699 
1700 	/*
1701 	 * setup physically contiguous area twice as large as the ecache.
1702 	 * this is used while doing displacement flush of ecaches
1703 	 */
1704 	if (&ecache_flush_address) {
1705 		ecache_flushaddr = ecache_flush_address();
1706 		if (ecache_flushaddr == (uint64_t)-1) {
1707 			cmn_err(CE_PANIC,
1708 			    "startup: no memory to set ecache_flushaddr");
1709 		}
1710 	}
1711 
1712 	/*
1713 	 * Virtual available next.
1714 	 */
1715 	ASSERT(virt_avail != NULL);
1716 	memlist_free_list(virt_avail);
1717 	virt_avail = memlist;
1718 	copy_memlist(boot_virtavail, boot_virtavail_len, &memlist);
1719 
1720 }
1721 
1722 
1723 /*
1724  * startup_fixup_physavail - called from mach_sfmmu.c after the final
1725  * allocations have been performed.  We can't call it in startup_bop_gone
1726  * since later operations can cause obp to allocate more memory.
1727  */
1728 void
1729 startup_fixup_physavail(void)
1730 {
1731 	struct memlist *cur;
1732 	size_t kmem64_overmap_size = kmem64_aligned_end - kmem64_end;
1733 
1734 	PRM_DEBUG(kmem64_overmap_size);
1735 
1736 	/*
1737 	 * take the most current snapshot we can by calling mem-update
1738 	 */
1739 	copy_boot_memlists(&boot_physinstalled, &boot_physinstalled_len,
1740 	    &boot_physavail, &boot_physavail_len,
1741 	    &boot_virtavail, &boot_virtavail_len);
1742 
1743 	/*
1744 	 * Copy phys_avail list, again.
1745 	 * Both the kernel/boot and the prom have been allocating
1746 	 * from the original list we copied earlier.
1747 	 */
1748 	cur = memlist;
1749 	copy_memlist(boot_physavail, boot_physavail_len, &memlist);
1750 
1751 	/*
1752 	 * Add any unused kmem64 memory from overmapped page
1753 	 * (Note: va_to_pa does not work for kmem64_end)
1754 	 */
1755 	if (kmem64_overmap_size) {
1756 		memlist_add(kmem64_pabase + (kmem64_end - kmem64_base),
1757 		    kmem64_overmap_size, &memlist, &cur);
1758 	}
1759 
1760 	/*
1761 	 * Add any extra memory after e_data we added to the phys_avail list
1762 	 * back to the old list.
1763 	 */
1764 	if (ndata_remain_sz >= MMU_PAGESIZE)
1765 		memlist_add(va_to_pa(nalloc_base),
1766 		    (uint64_t)ndata_remain_sz, &memlist, &cur);
1767 
1768 	/*
1769 	 * There isn't any bounds checking on the memlist area
1770 	 * so ensure it hasn't overgrown.
1771 	 */
1772 	if ((caddr_t)memlist > (caddr_t)memlist_end)
1773 		cmn_err(CE_PANIC, "startup: memlist size exceeded");
1774 
1775 	/*
1776 	 * The kernel removes the pages that were allocated for it from
1777 	 * the freelist, but we now have to find any -extra- pages that
1778 	 * the prom has allocated for it's own book-keeping, and remove
1779 	 * them from the freelist too. sigh.
1780 	 */
1781 	sync_memlists(phys_avail, cur);
1782 
1783 	ASSERT(phys_avail != NULL);
1784 
1785 	old_phys_avail = phys_avail;
1786 	phys_avail = cur;
1787 }
1788 
1789 void
1790 update_kcage_ranges(uint64_t addr, uint64_t len)
1791 {
1792 	pfn_t base = btop(addr);
1793 	pgcnt_t num = btop(len);
1794 	int rv;
1795 
1796 	rv = kcage_range_add(base, num, kcage_startup_dir);
1797 
1798 	if (rv == ENOMEM) {
1799 		cmn_err(CE_WARN, "%ld megabytes not available to kernel cage",
1800 		    (len == 0 ? 0 : BYTES_TO_MB(len)));
1801 	} else if (rv != 0) {
1802 		/* catch this in debug kernels */
1803 		ASSERT(0);
1804 
1805 		cmn_err(CE_WARN, "unexpected kcage_range_add"
1806 		    " return value %d", rv);
1807 	}
1808 }
1809 
1810 static void
1811 startup_vm(void)
1812 {
1813 	size_t	i;
1814 	struct segmap_crargs a;
1815 	struct segkpm_crargs b;
1816 
1817 	uint64_t avmem;
1818 	caddr_t va;
1819 	pgcnt_t	max_phys_segkp;
1820 	int	mnode;
1821 
1822 	extern int use_brk_lpg, use_stk_lpg;
1823 
1824 	/*
1825 	 * get prom's mappings, create hments for them and switch
1826 	 * to the kernel context.
1827 	 */
1828 	hat_kern_setup();
1829 
1830 	/*
1831 	 * Take over trap table
1832 	 */
1833 	setup_trap_table();
1834 
1835 	/*
1836 	 * Install the va>tte handler, so that the prom can handle
1837 	 * misses and understand the kernel table layout in case
1838 	 * we need call into the prom.
1839 	 */
1840 	install_va_to_tte();
1841 
1842 	/*
1843 	 * Set a flag to indicate that the tba has been taken over.
1844 	 */
1845 	tba_taken_over = 1;
1846 
1847 	/* initialize MMU primary context register */
1848 	mmu_init_kcontext();
1849 
1850 	/*
1851 	 * The boot cpu can now take interrupts, x-calls, x-traps
1852 	 */
1853 	CPUSET_ADD(cpu_ready_set, CPU->cpu_id);
1854 	CPU->cpu_flags |= (CPU_READY | CPU_ENABLE | CPU_EXISTS);
1855 
1856 	/*
1857 	 * Set a flag to tell write_scb_int() that it can access V_TBR_WR_ADDR.
1858 	 */
1859 	tbr_wr_addr_inited = 1;
1860 
1861 	/*
1862 	 * Initialize VM system, and map kernel address space.
1863 	 */
1864 	kvm_init();
1865 
1866 	ASSERT(old_phys_avail != NULL && phys_avail != NULL);
1867 	if (kernel_cage_enable) {
1868 		diff_memlists(phys_avail, old_phys_avail, update_kcage_ranges);
1869 	}
1870 	memlist_free_list(old_phys_avail);
1871 
1872 	/*
1873 	 * If the following is true, someone has patched
1874 	 * phsymem to be less than the number of pages that
1875 	 * the system actually has.  Remove pages until system
1876 	 * memory is limited to the requested amount.  Since we
1877 	 * have allocated page structures for all pages, we
1878 	 * correct the amount of memory we want to remove
1879 	 * by the size of the memory used to hold page structures
1880 	 * for the non-used pages.
1881 	 */
1882 	if (physmem + ramdisk_npages < npages) {
1883 		pgcnt_t diff, off;
1884 		struct page *pp;
1885 		struct seg kseg;
1886 
1887 		cmn_err(CE_WARN, "limiting physmem to %ld pages", physmem);
1888 
1889 		off = 0;
1890 		diff = npages - (physmem + ramdisk_npages);
1891 		diff -= mmu_btopr(diff * sizeof (struct page));
1892 		kseg.s_as = &kas;
1893 		while (diff--) {
1894 			pp = page_create_va(&unused_pages_vp, (offset_t)off,
1895 			    MMU_PAGESIZE, PG_WAIT | PG_EXCL,
1896 			    &kseg, (caddr_t)off);
1897 			if (pp == NULL)
1898 				cmn_err(CE_PANIC, "limited physmem too much!");
1899 			page_io_unlock(pp);
1900 			page_downgrade(pp);
1901 			availrmem--;
1902 			off += MMU_PAGESIZE;
1903 		}
1904 	}
1905 
1906 	/*
1907 	 * When printing memory, show the total as physmem less
1908 	 * that stolen by a debugger.
1909 	 */
1910 	cmn_err(CE_CONT, "?mem = %ldK (0x%lx000)\n",
1911 	    (ulong_t)(physinstalled) << (PAGESHIFT - 10),
1912 	    (ulong_t)(physinstalled) << (PAGESHIFT - 12));
1913 
1914 	avmem = (uint64_t)freemem << PAGESHIFT;
1915 	cmn_err(CE_CONT, "?avail mem = %lld\n", (unsigned long long)avmem);
1916 
1917 	/*
1918 	 * For small memory systems disable automatic large pages.
1919 	 */
1920 	if (physmem < privm_lpg_min_physmem) {
1921 		use_brk_lpg = 0;
1922 		use_stk_lpg = 0;
1923 	}
1924 
1925 	/*
1926 	 * Perform platform specific freelist processing
1927 	 */
1928 	if (&plat_freelist_process) {
1929 		for (mnode = 0; mnode < max_mem_nodes; mnode++)
1930 			if (mem_node_config[mnode].exists)
1931 				plat_freelist_process(mnode);
1932 	}
1933 
1934 	/*
1935 	 * Initialize the segkp segment type.  We position it
1936 	 * after the configured tables and buffers (whose end
1937 	 * is given by econtig) and before V_WKBASE_ADDR.
1938 	 * Also in this area is segkmap (size SEGMAPSIZE).
1939 	 */
1940 
1941 	/* XXX - cache alignment? */
1942 	va = (caddr_t)SEGKPBASE;
1943 	ASSERT(((uintptr_t)va & PAGEOFFSET) == 0);
1944 
1945 	max_phys_segkp = (physmem * 2);
1946 
1947 	if (segkpsize < btop(SEGKPMINSIZE) || segkpsize > btop(SEGKPMAXSIZE)) {
1948 		segkpsize = btop(SEGKPDEFSIZE);
1949 		cmn_err(CE_WARN, "Illegal value for segkpsize. "
1950 		    "segkpsize has been reset to %ld pages", segkpsize);
1951 	}
1952 
1953 	i = ptob(MIN(segkpsize, max_phys_segkp));
1954 
1955 	rw_enter(&kas.a_lock, RW_WRITER);
1956 	if (seg_attach(&kas, va, i, segkp) < 0)
1957 		cmn_err(CE_PANIC, "startup: cannot attach segkp");
1958 	if (segkp_create(segkp) != 0)
1959 		cmn_err(CE_PANIC, "startup: segkp_create failed");
1960 	rw_exit(&kas.a_lock);
1961 
1962 	/*
1963 	 * kpm segment
1964 	 */
1965 	segmap_kpm = kpm_enable &&
1966 	    segmap_kpm && PAGESIZE == MAXBSIZE;
1967 
1968 	if (kpm_enable) {
1969 		rw_enter(&kas.a_lock, RW_WRITER);
1970 
1971 		/*
1972 		 * The segkpm virtual range range is larger than the
1973 		 * actual physical memory size and also covers gaps in
1974 		 * the physical address range for the following reasons:
1975 		 * . keep conversion between segkpm and physical addresses
1976 		 *   simple, cheap and unambiguous.
1977 		 * . avoid extension/shrink of the the segkpm in case of DR.
1978 		 * . avoid complexity for handling of virtual addressed
1979 		 *   caches, segkpm and the regular mapping scheme must be
1980 		 *   kept in sync wrt. the virtual color of mapped pages.
1981 		 * Any accesses to virtual segkpm ranges not backed by
1982 		 * physical memory will fall through the memseg pfn hash
1983 		 * and will be handled in segkpm_fault.
1984 		 * Additional kpm_size spaces needed for vac alias prevention.
1985 		 */
1986 		if (seg_attach(&kas, kpm_vbase, kpm_size * vac_colors,
1987 		    segkpm) < 0)
1988 			cmn_err(CE_PANIC, "cannot attach segkpm");
1989 
1990 		b.prot = PROT_READ | PROT_WRITE;
1991 		b.nvcolors = shm_alignment >> MMU_PAGESHIFT;
1992 
1993 		if (segkpm_create(segkpm, (caddr_t)&b) != 0)
1994 			panic("segkpm_create segkpm");
1995 
1996 		rw_exit(&kas.a_lock);
1997 
1998 		mach_kpm_init();
1999 	}
2000 
2001 	va = kpm_vbase + (kpm_size * vac_colors);
2002 
2003 	if (!segzio_fromheap) {
2004 		size_t size;
2005 		size_t physmem_b = mmu_ptob(physmem);
2006 
2007 		/* size is in bytes, segziosize is in pages */
2008 		if (segziosize == 0) {
2009 			size = physmem_b;
2010 		} else {
2011 			size = mmu_ptob(segziosize);
2012 		}
2013 
2014 		if (size < SEGZIOMINSIZE) {
2015 			size = SEGZIOMINSIZE;
2016 		} else if (size > SEGZIOMAXSIZE) {
2017 			size = SEGZIOMAXSIZE;
2018 			/*
2019 			 * On 64-bit x86, we only have 2TB of KVA.  This exists
2020 			 * for parity with x86.
2021 			 *
2022 			 * SEGZIOMAXSIZE is capped at 512gb so that segzio
2023 			 * doesn't consume all of KVA.  However, if we have a
2024 			 * system that has more thant 512gb of physical memory,
2025 			 * we can actually consume about half of the difference
2026 			 * between 512gb and the rest of the available physical
2027 			 * memory.
2028 			 */
2029 			if (physmem_b > SEGZIOMAXSIZE) {
2030 				size += (physmem_b - SEGZIOMAXSIZE) / 2;
2031 		}
2032 		}
2033 		segziosize = mmu_btop(roundup(size, MMU_PAGESIZE));
2034 		/* put the base of the ZIO segment after the kpm segment */
2035 		segzio_base = va;
2036 		va += mmu_ptob(segziosize);
2037 		PRM_DEBUG(segziosize);
2038 		PRM_DEBUG(segzio_base);
2039 
2040 		/*
2041 		 * On some platforms, kvm_init is called after the kpm
2042 		 * sizes have been determined.  On SPARC, kvm_init is called
2043 		 * before, so we have to attach the kzioseg after kvm is
2044 		 * initialized, otherwise we'll try to allocate from the boot
2045 		 * area since the kernel heap hasn't yet been configured.
2046 		 */
2047 		rw_enter(&kas.a_lock, RW_WRITER);
2048 
2049 		(void) seg_attach(&kas, segzio_base, mmu_ptob(segziosize),
2050 		    &kzioseg);
2051 		(void) segkmem_zio_create(&kzioseg);
2052 
2053 		/* create zio area covering new segment */
2054 		segkmem_zio_init(segzio_base, mmu_ptob(segziosize));
2055 
2056 		rw_exit(&kas.a_lock);
2057 	}
2058 
2059 	if (ppvm_enable) {
2060 		caddr_t ppvm_max;
2061 
2062 		/*
2063 		 * ppvm refers to the static VA space used to map
2064 		 * the page_t's for dynamically added memory.
2065 		 *
2066 		 * ppvm_base should not cross a potential VA hole.
2067 		 *
2068 		 * ppvm_size should be large enough to map the
2069 		 * page_t's needed to manage all of KPM range.
2070 		 */
2071 		ppvm_size =
2072 		    roundup(mmu_btop(kpm_size * vac_colors) * sizeof (page_t),
2073 		    MMU_PAGESIZE);
2074 		ppvm_max = (caddr_t)(0ull - ppvm_size);
2075 		ppvm_base = (page_t *)va;
2076 
2077 		if ((caddr_t)ppvm_base <= hole_end) {
2078 			cmn_err(CE_WARN,
2079 			    "Memory DR disabled: invalid DR map base: 0x%p\n",
2080 			    (void *)ppvm_base);
2081 			ppvm_enable = 0;
2082 		} else if ((caddr_t)ppvm_base > ppvm_max) {
2083 			uint64_t diff = (caddr_t)ppvm_base - ppvm_max;
2084 
2085 			cmn_err(CE_WARN,
2086 			    "Memory DR disabled: insufficient DR map size:"
2087 			    " 0x%lx (needed 0x%lx)\n",
2088 			    ppvm_size - diff, ppvm_size);
2089 			ppvm_enable = 0;
2090 		}
2091 		PRM_DEBUG(ppvm_size);
2092 		PRM_DEBUG(ppvm_base);
2093 	}
2094 
2095 	/*
2096 	 * Now create generic mapping segment.  This mapping
2097 	 * goes SEGMAPSIZE beyond SEGMAPBASE.  But if the total
2098 	 * virtual address is greater than the amount of free
2099 	 * memory that is available, then we trim back the
2100 	 * segment size to that amount
2101 	 */
2102 	va = (caddr_t)SEGMAPBASE;
2103 
2104 	/*
2105 	 * 1201049: segkmap base address must be MAXBSIZE aligned
2106 	 */
2107 	ASSERT(((uintptr_t)va & MAXBOFFSET) == 0);
2108 
2109 	/*
2110 	 * Set size of segmap to percentage of freemem at boot,
2111 	 * but stay within the allowable range
2112 	 * Note we take percentage  before converting from pages
2113 	 * to bytes to avoid an overflow on 32-bit kernels.
2114 	 */
2115 	i = mmu_ptob((freemem * segmap_percent) / 100);
2116 
2117 	if (i < MINMAPSIZE)
2118 		i = MINMAPSIZE;
2119 
2120 	if (i > MIN(SEGMAPSIZE, mmu_ptob(freemem)))
2121 		i = MIN(SEGMAPSIZE, mmu_ptob(freemem));
2122 
2123 	i &= MAXBMASK;	/* 1201049: segkmap size must be MAXBSIZE aligned */
2124 
2125 	rw_enter(&kas.a_lock, RW_WRITER);
2126 	if (seg_attach(&kas, va, i, segkmap) < 0)
2127 		cmn_err(CE_PANIC, "cannot attach segkmap");
2128 
2129 	a.prot = PROT_READ | PROT_WRITE;
2130 	a.shmsize = shm_alignment;
2131 	a.nfreelist = 0;	/* use segmap driver defaults */
2132 
2133 	if (segmap_create(segkmap, (caddr_t)&a) != 0)
2134 		panic("segmap_create segkmap");
2135 	rw_exit(&kas.a_lock);
2136 
2137 	segdev_init();
2138 }
2139 
2140 static void
2141 startup_end(void)
2142 {
2143 	if ((caddr_t)memlist > (caddr_t)memlist_end)
2144 		panic("memlist overflow 2");
2145 	memlist_free_block((caddr_t)memlist,
2146 	    ((caddr_t)memlist_end - (caddr_t)memlist));
2147 	memlist = NULL;
2148 
2149 	/* enable page_relocation since OBP is now done */
2150 	page_relocate_ready = 1;
2151 
2152 	/*
2153 	 * Perform tasks that get done after most of the VM
2154 	 * initialization has been done but before the clock
2155 	 * and other devices get started.
2156 	 */
2157 	kern_setup1();
2158 
2159 	/*
2160 	 * Perform CPC initialization for this CPU.
2161 	 */
2162 	kcpc_hw_init();
2163 
2164 	/*
2165 	 * Intialize the VM arenas for allocating physically
2166 	 * contiguus memory chunk for interrupt queues snd
2167 	 * allocate/register boot cpu's queues, if any and
2168 	 * allocate dump buffer for sun4v systems to store
2169 	 * extra crash information during crash dump
2170 	 */
2171 	contig_mem_init();
2172 	mach_descrip_init();
2173 
2174 	if (cpu_intrq_setup(CPU)) {
2175 		cmn_err(CE_PANIC, "cpu%d: setup failed", CPU->cpu_id);
2176 	}
2177 	cpu_intrq_register(CPU);
2178 	mach_htraptrace_setup(CPU->cpu_id);
2179 	mach_htraptrace_configure(CPU->cpu_id);
2180 	mach_dump_buffer_init();
2181 
2182 	/*
2183 	 * Initialize interrupt related stuff
2184 	 */
2185 	cpu_intr_alloc(CPU, NINTR_THREADS);
2186 
2187 	(void) splzs();			/* allow hi clock ints but not zs */
2188 
2189 	/*
2190 	 * Initialize errors.
2191 	 */
2192 	error_init();
2193 
2194 	/*
2195 	 * Note that we may have already used kernel bcopy before this
2196 	 * point - but if you really care about this, adb the use_hw_*
2197 	 * variables to 0 before rebooting.
2198 	 */
2199 	mach_hw_copy_limit();
2200 
2201 	/*
2202 	 * Install the "real" preemption guards before DDI services
2203 	 * are available.
2204 	 */
2205 	(void) prom_set_preprom(kern_preprom);
2206 	(void) prom_set_postprom(kern_postprom);
2207 	CPU->cpu_m.mutex_ready = 1;
2208 
2209 	/*
2210 	 * Initialize segnf (kernel support for non-faulting loads).
2211 	 */
2212 	segnf_init();
2213 
2214 	/*
2215 	 * Configure the root devinfo node.
2216 	 */
2217 	configure();		/* set up devices */
2218 	mach_cpu_halt_idle();
2219 }
2220 
2221 
2222 void
2223 post_startup(void)
2224 {
2225 #ifdef	PTL1_PANIC_DEBUG
2226 	extern void init_ptl1_thread(void);
2227 #endif	/* PTL1_PANIC_DEBUG */
2228 	extern void abort_sequence_init(void);
2229 
2230 	/*
2231 	 * Set the system wide, processor-specific flags to be passed
2232 	 * to userland via the aux vector for performance hints and
2233 	 * instruction set extensions.
2234 	 */
2235 	bind_hwcap();
2236 
2237 	/*
2238 	 * Startup memory scrubber (if any)
2239 	 */
2240 	mach_memscrub();
2241 
2242 	/*
2243 	 * Allocate soft interrupt to handle abort sequence.
2244 	 */
2245 	abort_sequence_init();
2246 
2247 	/*
2248 	 * Configure the rest of the system.
2249 	 * Perform forceloading tasks for /etc/system.
2250 	 */
2251 	(void) mod_sysctl(SYS_FORCELOAD, NULL);
2252 	/*
2253 	 * ON4.0: Force /proc module in until clock interrupt handle fixed
2254 	 * ON4.0: This must be fixed or restated in /etc/systems.
2255 	 */
2256 	(void) modload("fs", "procfs");
2257 
2258 	/* load machine class specific drivers */
2259 	load_mach_drivers();
2260 
2261 	/* load platform specific drivers */
2262 	if (&load_platform_drivers)
2263 		load_platform_drivers();
2264 
2265 	/* load vis simulation module, if we are running w/fpu off */
2266 	if (!fpu_exists) {
2267 		if (modload("misc", "vis") == -1)
2268 			halt("Can't load vis");
2269 	}
2270 
2271 	mach_fpras();
2272 
2273 	maxmem = freemem;
2274 
2275 	pg_init();
2276 
2277 #ifdef	PTL1_PANIC_DEBUG
2278 	init_ptl1_thread();
2279 #endif	/* PTL1_PANIC_DEBUG */
2280 }
2281 
2282 #ifdef	PTL1_PANIC_DEBUG
2283 int		ptl1_panic_test = 0;
2284 int		ptl1_panic_xc_one_test = 0;
2285 int		ptl1_panic_xc_all_test = 0;
2286 int		ptl1_panic_xt_one_test = 0;
2287 int		ptl1_panic_xt_all_test = 0;
2288 kthread_id_t	ptl1_thread_p = NULL;
2289 kcondvar_t	ptl1_cv;
2290 kmutex_t	ptl1_mutex;
2291 int		ptl1_recurse_count_threshold = 0x40;
2292 int		ptl1_recurse_trap_threshold = 0x3d;
2293 extern void	ptl1_recurse(int, int);
2294 extern void	ptl1_panic_xt(int, int);
2295 
2296 /*
2297  * Called once per second by timeout() to wake up
2298  * the ptl1_panic thread to see if it should cause
2299  * a trap to the ptl1_panic() code.
2300  */
2301 /* ARGSUSED */
2302 static void
2303 ptl1_wakeup(void *arg)
2304 {
2305 	mutex_enter(&ptl1_mutex);
2306 	cv_signal(&ptl1_cv);
2307 	mutex_exit(&ptl1_mutex);
2308 }
2309 
2310 /*
2311  * ptl1_panic cross call function:
2312  *     Needed because xc_one() and xc_some() can pass
2313  *	64 bit args but ptl1_recurse() expects ints.
2314  */
2315 static void
2316 ptl1_panic_xc(void)
2317 {
2318 	ptl1_recurse(ptl1_recurse_count_threshold,
2319 	    ptl1_recurse_trap_threshold);
2320 }
2321 
2322 /*
2323  * The ptl1 thread waits for a global flag to be set
2324  * and uses the recurse thresholds to set the stack depth
2325  * to cause a ptl1_panic() directly via a call to ptl1_recurse
2326  * or indirectly via the cross call and cross trap functions.
2327  *
2328  * This is useful testing stack overflows and normal
2329  * ptl1_panic() states with a know stack frame.
2330  *
2331  * ptl1_recurse() is an asm function in ptl1_panic.s that
2332  * sets the {In, Local, Out, and Global} registers to a
2333  * know state on the stack and just prior to causing a
2334  * test ptl1_panic trap.
2335  */
2336 static void
2337 ptl1_thread(void)
2338 {
2339 	mutex_enter(&ptl1_mutex);
2340 	while (ptl1_thread_p) {
2341 		cpuset_t	other_cpus;
2342 		int		cpu_id;
2343 		int		my_cpu_id;
2344 		int		target_cpu_id;
2345 		int		target_found;
2346 
2347 		if (ptl1_panic_test) {
2348 			ptl1_recurse(ptl1_recurse_count_threshold,
2349 			    ptl1_recurse_trap_threshold);
2350 		}
2351 
2352 		/*
2353 		 * Find potential targets for x-call and x-trap,
2354 		 * if any exist while preempt is disabled we
2355 		 * start a ptl1_panic if requested via a
2356 		 * globals.
2357 		 */
2358 		kpreempt_disable();
2359 		my_cpu_id = CPU->cpu_id;
2360 		other_cpus = cpu_ready_set;
2361 		CPUSET_DEL(other_cpus, CPU->cpu_id);
2362 		target_found = 0;
2363 		if (!CPUSET_ISNULL(other_cpus)) {
2364 			/*
2365 			 * Pick the first one
2366 			 */
2367 			for (cpu_id = 0; cpu_id < NCPU; cpu_id++) {
2368 				if (cpu_id == my_cpu_id)
2369 					continue;
2370 
2371 				if (CPU_XCALL_READY(cpu_id)) {
2372 					target_cpu_id = cpu_id;
2373 					target_found = 1;
2374 					break;
2375 				}
2376 			}
2377 			ASSERT(target_found);
2378 
2379 			if (ptl1_panic_xc_one_test) {
2380 				xc_one(target_cpu_id,
2381 				    (xcfunc_t *)ptl1_panic_xc, 0, 0);
2382 			}
2383 			if (ptl1_panic_xc_all_test) {
2384 				xc_some(other_cpus,
2385 				    (xcfunc_t *)ptl1_panic_xc, 0, 0);
2386 			}
2387 			if (ptl1_panic_xt_one_test) {
2388 				xt_one(target_cpu_id,
2389 				    (xcfunc_t *)ptl1_panic_xt, 0, 0);
2390 			}
2391 			if (ptl1_panic_xt_all_test) {
2392 				xt_some(other_cpus,
2393 				    (xcfunc_t *)ptl1_panic_xt, 0, 0);
2394 			}
2395 		}
2396 		kpreempt_enable();
2397 		(void) timeout(ptl1_wakeup, NULL, hz);
2398 		(void) cv_wait(&ptl1_cv, &ptl1_mutex);
2399 	}
2400 	mutex_exit(&ptl1_mutex);
2401 }
2402 
2403 /*
2404  * Called during early startup to create the ptl1_thread
2405  */
2406 void
2407 init_ptl1_thread(void)
2408 {
2409 	ptl1_thread_p = thread_create(NULL, 0, ptl1_thread, NULL, 0,
2410 	    &p0, TS_RUN, 0);
2411 }
2412 #endif	/* PTL1_PANIC_DEBUG */
2413 
2414 
2415 static void
2416 memlist_new(uint64_t start, uint64_t len, struct memlist **memlistp)
2417 {
2418 	struct memlist *new;
2419 
2420 	new = *memlistp;
2421 	new->ml_address = start;
2422 	new->ml_size = len;
2423 	*memlistp = new + 1;
2424 }
2425 
2426 /*
2427  * Add to a memory list.
2428  * start = start of new memory segment
2429  * len = length of new memory segment in bytes
2430  * memlistp = pointer to array of available memory segment structures
2431  * curmemlistp = memory list to which to add segment.
2432  */
2433 static void
2434 memlist_add(uint64_t start, uint64_t len, struct memlist **memlistp,
2435 	struct memlist **curmemlistp)
2436 {
2437 	struct memlist *new = *memlistp;
2438 
2439 	memlist_new(start, len, memlistp);
2440 	memlist_insert(new, curmemlistp);
2441 }
2442 
2443 static int
2444 ndata_alloc_memseg(struct memlist *ndata, size_t avail)
2445 {
2446 	int nseg;
2447 	size_t memseg_sz;
2448 	struct memseg *msp;
2449 
2450 	/*
2451 	 * The memseg list is for the chunks of physical memory that
2452 	 * will be managed by the vm system.  The number calculated is
2453 	 * a guess as boot may fragment it more when memory allocations
2454 	 * are made before kphysm_init().
2455 	 */
2456 	memseg_sz = (avail + 10) * sizeof (struct memseg);
2457 	memseg_sz = roundup(memseg_sz, PAGESIZE);
2458 	nseg = memseg_sz / sizeof (struct memseg);
2459 	msp = ndata_alloc(ndata, memseg_sz, ecache_alignsize);
2460 	if (msp == NULL)
2461 		return (1);
2462 	PRM_DEBUG(memseg_free);
2463 
2464 	while (nseg--) {
2465 		msp->next = memseg_free;
2466 		memseg_free = msp;
2467 		msp++;
2468 	}
2469 	return (0);
2470 }
2471 
2472 /*
2473  * In the case of architectures that support dynamic addition of
2474  * memory at run-time there are two cases where memsegs need to
2475  * be initialized and added to the memseg list.
2476  * 1) memsegs that are constructed at startup.
2477  * 2) memsegs that are constructed at run-time on
2478  *    hot-plug capable architectures.
2479  * This code was originally part of the function kphysm_init().
2480  */
2481 
2482 static void
2483 memseg_list_add(struct memseg *memsegp)
2484 {
2485 	struct memseg **prev_memsegp;
2486 	pgcnt_t num;
2487 
2488 	/* insert in memseg list, decreasing number of pages order */
2489 
2490 	num = MSEG_NPAGES(memsegp);
2491 
2492 	for (prev_memsegp = &memsegs; *prev_memsegp;
2493 	    prev_memsegp = &((*prev_memsegp)->next)) {
2494 		if (num > MSEG_NPAGES(*prev_memsegp))
2495 			break;
2496 	}
2497 
2498 	memsegp->next = *prev_memsegp;
2499 	*prev_memsegp = memsegp;
2500 
2501 	if (kpm_enable) {
2502 		memsegp->nextpa = (memsegp->next) ?
2503 		    va_to_pa(memsegp->next) : MSEG_NULLPTR_PA;
2504 
2505 		if (prev_memsegp != &memsegs) {
2506 			struct memseg *msp;
2507 			msp = (struct memseg *)((caddr_t)prev_memsegp -
2508 			    offsetof(struct memseg, next));
2509 			msp->nextpa = va_to_pa(memsegp);
2510 		} else {
2511 			memsegspa = va_to_pa(memsegs);
2512 		}
2513 	}
2514 }
2515 
2516 /*
2517  * PSM add_physmem_cb(). US-II and newer processors have some
2518  * flavor of the prefetch capability implemented. We exploit
2519  * this capability for optimum performance.
2520  */
2521 #define	PREFETCH_BYTES	64
2522 
2523 void
2524 add_physmem_cb(page_t *pp, pfn_t pnum)
2525 {
2526 	extern void	 prefetch_page_w(void *);
2527 
2528 	pp->p_pagenum = pnum;
2529 
2530 	/*
2531 	 * Prefetch one more page_t into E$. To prevent future
2532 	 * mishaps with the sizeof(page_t) changing on us, we
2533 	 * catch this on debug kernels if we can't bring in the
2534 	 * entire hpage with 2 PREFETCH_BYTES reads. See
2535 	 * also, sun4u/cpu/cpu_module.c
2536 	 */
2537 	/*LINTED*/
2538 	ASSERT(sizeof (page_t) <= 2*PREFETCH_BYTES);
2539 	prefetch_page_w((char *)pp);
2540 }
2541 
2542 /*
2543  * Find memseg with given pfn
2544  */
2545 static struct memseg *
2546 memseg_find(pfn_t base, pfn_t *next)
2547 {
2548 	struct memseg *seg;
2549 
2550 	if (next != NULL)
2551 		*next = LONG_MAX;
2552 	for (seg = memsegs; seg != NULL; seg = seg->next) {
2553 		if (base >= seg->pages_base && base < seg->pages_end)
2554 			return (seg);
2555 		if (next != NULL && seg->pages_base > base &&
2556 		    seg->pages_base < *next)
2557 			*next = seg->pages_base;
2558 	}
2559 	return (NULL);
2560 }
2561 
2562 /*
2563  * Put page allocated by OBP on prom_ppages
2564  */
2565 static void
2566 kphysm_erase(uint64_t addr, uint64_t len)
2567 {
2568 	struct page *pp;
2569 	struct memseg *seg;
2570 	pfn_t base = btop(addr), next;
2571 	pgcnt_t num = btop(len);
2572 
2573 	while (num != 0) {
2574 		pgcnt_t off, left;
2575 
2576 		seg = memseg_find(base, &next);
2577 		if (seg == NULL) {
2578 			if (next == LONG_MAX)
2579 				break;
2580 			left = MIN(next - base, num);
2581 			base += left, num -= left;
2582 			continue;
2583 		}
2584 		off = base - seg->pages_base;
2585 		pp = seg->pages + off;
2586 		left = num - MIN(num, (seg->pages_end - seg->pages_base) - off);
2587 		while (num != left) {
2588 			/*
2589 			 * init it, lock it, and hashin on prom_pages vp.
2590 			 *
2591 			 * Mark it as NONRELOC to let DR know the page
2592 			 * is locked long term, otherwise DR hangs when
2593 			 * trying to remove those pages.
2594 			 *
2595 			 * XXX	vnode offsets on the prom_ppages vnode
2596 			 *	are page numbers (gack) for >32 bit
2597 			 *	physical memory machines.
2598 			 */
2599 			PP_SETNORELOC(pp);
2600 			add_physmem_cb(pp, base);
2601 			if (page_trylock(pp, SE_EXCL) == 0)
2602 				cmn_err(CE_PANIC, "prom page locked");
2603 			(void) page_hashin(pp, &promvp,
2604 			    (offset_t)base, NULL);
2605 			(void) page_pp_lock(pp, 0, 1);
2606 			pp++, base++, num--;
2607 		}
2608 	}
2609 }
2610 
2611 static page_t *ppnext;
2612 static pgcnt_t ppleft;
2613 
2614 static void *kpm_ppnext;
2615 static pgcnt_t kpm_ppleft;
2616 
2617 /*
2618  * Create a memseg
2619  */
2620 static void
2621 kphysm_memseg(uint64_t addr, uint64_t len)
2622 {
2623 	pfn_t base = btop(addr);
2624 	pgcnt_t num = btop(len);
2625 	struct memseg *seg;
2626 
2627 	seg = memseg_free;
2628 	memseg_free = seg->next;
2629 	ASSERT(seg != NULL);
2630 
2631 	seg->pages = ppnext;
2632 	seg->epages = ppnext + num;
2633 	seg->pages_base = base;
2634 	seg->pages_end = base + num;
2635 	ppnext += num;
2636 	ppleft -= num;
2637 
2638 	if (kpm_enable) {
2639 		pgcnt_t kpnum = ptokpmpr(num);
2640 
2641 		if (kpnum > kpm_ppleft)
2642 			panic("kphysm_memseg: kpm_pp overflow");
2643 		seg->pagespa = va_to_pa(seg->pages);
2644 		seg->epagespa = va_to_pa(seg->epages);
2645 		seg->kpm_pbase = kpmptop(ptokpmp(base));
2646 		seg->kpm_nkpmpgs = kpnum;
2647 		/*
2648 		 * In the kpm_smallpage case, the kpm array
2649 		 * is 1-1 wrt the page array
2650 		 */
2651 		if (kpm_smallpages) {
2652 			kpm_spage_t *kpm_pp = kpm_ppnext;
2653 
2654 			kpm_ppnext = kpm_pp + kpnum;
2655 			seg->kpm_spages = kpm_pp;
2656 			seg->kpm_pagespa = va_to_pa(seg->kpm_spages);
2657 		} else {
2658 			kpm_page_t *kpm_pp = kpm_ppnext;
2659 
2660 			kpm_ppnext = kpm_pp + kpnum;
2661 			seg->kpm_pages = kpm_pp;
2662 			seg->kpm_pagespa = va_to_pa(seg->kpm_pages);
2663 			/* ASSERT no kpm overlaps */
2664 			ASSERT(
2665 			    memseg_find(base - pmodkpmp(base), NULL) == NULL);
2666 			ASSERT(memseg_find(
2667 			    roundup(base + num, kpmpnpgs) - 1, NULL) == NULL);
2668 		}
2669 		kpm_ppleft -= kpnum;
2670 	}
2671 
2672 	memseg_list_add(seg);
2673 }
2674 
2675 /*
2676  * Add range to free list
2677  */
2678 void
2679 kphysm_add(uint64_t addr, uint64_t len, int reclaim)
2680 {
2681 	struct page *pp;
2682 	struct memseg *seg;
2683 	pfn_t base = btop(addr);
2684 	pgcnt_t num = btop(len);
2685 
2686 	seg = memseg_find(base, NULL);
2687 	ASSERT(seg != NULL);
2688 	pp = seg->pages + (base - seg->pages_base);
2689 
2690 	if (reclaim) {
2691 		struct page *rpp = pp;
2692 		struct page *lpp = pp + num;
2693 
2694 		/*
2695 		 * page should be locked on prom_ppages
2696 		 * unhash and unlock it
2697 		 */
2698 		while (rpp < lpp) {
2699 			ASSERT(PAGE_EXCL(rpp) && rpp->p_vnode == &promvp);
2700 			ASSERT(PP_ISNORELOC(rpp));
2701 			PP_CLRNORELOC(rpp);
2702 			page_pp_unlock(rpp, 0, 1);
2703 			page_hashout(rpp, NULL);
2704 			page_unlock(rpp);
2705 			rpp++;
2706 		}
2707 	}
2708 
2709 	/*
2710 	 * add_physmem() initializes the PSM part of the page
2711 	 * struct by calling the PSM back with add_physmem_cb().
2712 	 * In addition it coalesces pages into larger pages as
2713 	 * it initializes them.
2714 	 */
2715 	add_physmem(pp, num, base);
2716 }
2717 
2718 /*
2719  * kphysm_init() tackles the problem of initializing physical memory.
2720  */
2721 static void
2722 kphysm_init(void)
2723 {
2724 	struct memlist *pmem;
2725 
2726 	ASSERT(page_hash != NULL && page_hashsz != 0);
2727 
2728 	ppnext = pp_base;
2729 	ppleft = npages;
2730 	kpm_ppnext = kpm_pp_base;
2731 	kpm_ppleft = kpm_npages;
2732 
2733 	/*
2734 	 * installed pages not on nopp_memlist go in memseg list
2735 	 */
2736 	diff_memlists(phys_install, nopp_list, kphysm_memseg);
2737 
2738 	/*
2739 	 * Free the avail list
2740 	 */
2741 	for (pmem = phys_avail; pmem != NULL; pmem = pmem->ml_next)
2742 		kphysm_add(pmem->ml_address, pmem->ml_size, 0);
2743 
2744 	/*
2745 	 * Erase pages that aren't available
2746 	 */
2747 	diff_memlists(phys_install, phys_avail, kphysm_erase);
2748 
2749 	build_pfn_hash();
2750 }
2751 
2752 /*
2753  * Kernel VM initialization.
2754  * Assumptions about kernel address space ordering:
2755  *	(1) gap (user space)
2756  *	(2) kernel text
2757  *	(3) kernel data/bss
2758  *	(4) gap
2759  *	(5) kernel data structures
2760  *	(6) gap
2761  *	(7) debugger (optional)
2762  *	(8) monitor
2763  *	(9) gap (possibly null)
2764  *	(10) dvma
2765  *	(11) devices
2766  */
2767 static void
2768 kvm_init(void)
2769 {
2770 	/*
2771 	 * Put the kernel segments in kernel address space.
2772 	 */
2773 	rw_enter(&kas.a_lock, RW_WRITER);
2774 	as_avlinit(&kas);
2775 
2776 	(void) seg_attach(&kas, (caddr_t)KERNELBASE,
2777 	    (size_t)(e_moddata - KERNELBASE), &ktextseg);
2778 	(void) segkmem_create(&ktextseg);
2779 
2780 	(void) seg_attach(&kas, (caddr_t)(KERNELBASE + MMU_PAGESIZE4M),
2781 	    (size_t)(MMU_PAGESIZE4M), &ktexthole);
2782 	(void) segkmem_create(&ktexthole);
2783 
2784 	(void) seg_attach(&kas, (caddr_t)valloc_base,
2785 	    (size_t)(econtig32 - valloc_base), &kvalloc);
2786 	(void) segkmem_create(&kvalloc);
2787 
2788 	if (kmem64_base) {
2789 		(void) seg_attach(&kas, (caddr_t)kmem64_base,
2790 		    (size_t)(kmem64_end - kmem64_base), &kmem64);
2791 		(void) segkmem_create(&kmem64);
2792 	}
2793 
2794 	/*
2795 	 * We're about to map out /boot.  This is the beginning of the
2796 	 * system resource management transition. We can no longer
2797 	 * call into /boot for I/O or memory allocations.
2798 	 */
2799 	(void) seg_attach(&kas, kernelheap, ekernelheap - kernelheap, &kvseg);
2800 	(void) segkmem_create(&kvseg);
2801 	hblk_alloc_dynamic = 1;
2802 
2803 	/*
2804 	 * we need to preallocate pages for DR operations before enabling large
2805 	 * page kernel heap because of memseg_remap_init() hat_unload() hack.
2806 	 */
2807 	memseg_remap_init();
2808 
2809 	/* at this point we are ready to use large page heap */
2810 	segkmem_heap_lp_init();
2811 
2812 	(void) seg_attach(&kas, (caddr_t)SYSBASE32, SYSLIMIT32 - SYSBASE32,
2813 	    &kvseg32);
2814 	(void) segkmem_create(&kvseg32);
2815 
2816 	/*
2817 	 * Create a segment for the debugger.
2818 	 */
2819 	(void) seg_attach(&kas, kdi_segdebugbase, kdi_segdebugsize, &kdebugseg);
2820 	(void) segkmem_create(&kdebugseg);
2821 
2822 	rw_exit(&kas.a_lock);
2823 }
2824 
2825 char obp_tte_str[] =
2826 	"h# %x constant MMU_PAGESHIFT "
2827 	"h# %x constant TTE8K "
2828 	"h# %x constant SFHME_SIZE "
2829 	"h# %x constant SFHME_TTE "
2830 	"h# %x constant HMEBLK_TAG "
2831 	"h# %x constant HMEBLK_NEXT "
2832 	"h# %x constant HMEBLK_MISC "
2833 	"h# %x constant HMEBLK_HME1 "
2834 	"h# %x constant NHMENTS "
2835 	"h# %x constant HBLK_SZMASK "
2836 	"h# %x constant HBLK_RANGE_SHIFT "
2837 	"h# %x constant HMEBP_HBLK "
2838 	"h# %x constant HMEBLK_ENDPA "
2839 	"h# %x constant HMEBUCKET_SIZE "
2840 	"h# %x constant HTAG_SFMMUPSZ "
2841 	"h# %x constant HTAG_BSPAGE_SHIFT "
2842 	"h# %x constant HTAG_REHASH_SHIFT "
2843 	"h# %x constant SFMMU_INVALID_SHMERID "
2844 	"h# %x constant mmu_hashcnt "
2845 	"h# %p constant uhme_hash "
2846 	"h# %p constant khme_hash "
2847 	"h# %x constant UHMEHASH_SZ "
2848 	"h# %x constant KHMEHASH_SZ "
2849 	"h# %p constant KCONTEXT "
2850 	"h# %p constant KHATID "
2851 	"h# %x constant ASI_MEM "
2852 
2853 	": PHYS-X@ ( phys -- data ) "
2854 	"   ASI_MEM spacex@ "
2855 	"; "
2856 
2857 	": PHYS-W@ ( phys -- data ) "
2858 	"   ASI_MEM spacew@ "
2859 	"; "
2860 
2861 	": PHYS-L@ ( phys -- data ) "
2862 	"   ASI_MEM spaceL@ "
2863 	"; "
2864 
2865 	": TTE_PAGE_SHIFT ( ttesz -- hmeshift ) "
2866 	"   3 * MMU_PAGESHIFT + "
2867 	"; "
2868 
2869 	": TTE_IS_VALID ( ttep -- flag ) "
2870 	"   PHYS-X@ 0< "
2871 	"; "
2872 
2873 	": HME_HASH_SHIFT ( ttesz -- hmeshift ) "
2874 	"   dup TTE8K =  if "
2875 	"      drop HBLK_RANGE_SHIFT "
2876 	"   else "
2877 	"      TTE_PAGE_SHIFT "
2878 	"   then "
2879 	"; "
2880 
2881 	": HME_HASH_BSPAGE ( addr hmeshift -- bspage ) "
2882 	"   tuck >> swap MMU_PAGESHIFT - << "
2883 	"; "
2884 
2885 	": HME_HASH_FUNCTION ( sfmmup addr hmeshift -- hmebp ) "
2886 	"   >> over xor swap                    ( hash sfmmup ) "
2887 	"   KHATID <>  if                       ( hash ) "
2888 	"      UHMEHASH_SZ and                  ( bucket ) "
2889 	"      HMEBUCKET_SIZE * uhme_hash +     ( hmebp ) "
2890 	"   else                                ( hash ) "
2891 	"      KHMEHASH_SZ and                  ( bucket ) "
2892 	"      HMEBUCKET_SIZE * khme_hash +     ( hmebp ) "
2893 	"   then                                ( hmebp ) "
2894 	"; "
2895 
2896 	": HME_HASH_TABLE_SEARCH "
2897 	"       ( sfmmup hmebp hblktag --  sfmmup null | sfmmup hmeblkp ) "
2898 	"   >r hmebp_hblk + phys-x@ begin ( sfmmup hmeblkp ) ( r: hblktag ) "
2899 	"      dup HMEBLK_ENDPA <> if     ( sfmmup hmeblkp ) ( r: hblktag ) "
2900 	"         dup hmeblk_tag + phys-x@ r@ = if ( sfmmup hmeblkp )	  "
2901 	"	     dup hmeblk_tag + 8 + phys-x@ 2 pick = if		  "
2902 	"		  true 	( sfmmup hmeblkp true ) ( r: hblktag )	  "
2903 	"	     else						  "
2904 	"	     	  hmeblk_next + phys-x@ false 			  "
2905 	"			( sfmmup hmeblkp false ) ( r: hblktag )   "
2906 	"	     then  						  "
2907 	"	  else							  "
2908 	"	     hmeblk_next + phys-x@ false 			  "
2909 	"			( sfmmup hmeblkp false ) ( r: hblktag )   "
2910 	"	  then 							  "
2911 	"      else							  "
2912 	"         drop 0 true 						  "
2913 	"      then  							  "
2914 	"   until r> drop 						  "
2915 	"; "
2916 
2917 	": HME_HASH_TAG ( sfmmup rehash addr -- hblktag ) "
2918 	"   over HME_HASH_SHIFT HME_HASH_BSPAGE  ( sfmmup rehash bspage ) "
2919 	"   HTAG_BSPAGE_SHIFT <<		 ( sfmmup rehash htag-bspage )"
2920 	"   swap HTAG_REHASH_SHIFT << or	 ( sfmmup htag-bspage-rehash )"
2921 	"   SFMMU_INVALID_SHMERID or nip	 ( hblktag ) "
2922 	"; "
2923 
2924 	": HBLK_TO_TTEP ( hmeblkp addr -- ttep ) "
2925 	"   over HMEBLK_MISC + PHYS-L@ HBLK_SZMASK and  ( hmeblkp addr ttesz ) "
2926 	"   TTE8K =  if                            ( hmeblkp addr ) "
2927 	"      MMU_PAGESHIFT >> NHMENTS 1- and     ( hmeblkp hme-index ) "
2928 	"   else                                   ( hmeblkp addr ) "
2929 	"      drop 0                              ( hmeblkp 0 ) "
2930 	"   then                                   ( hmeblkp hme-index ) "
2931 	"   SFHME_SIZE * + HMEBLK_HME1 +           ( hmep ) "
2932 	"   SFHME_TTE +                            ( ttep ) "
2933 	"; "
2934 
2935 	": unix-tte ( addr cnum -- false | tte-data true ) "
2936 	"    KCONTEXT = if                   ( addr ) "
2937 	"	KHATID                       ( addr khatid ) "
2938 	"    else                            ( addr ) "
2939 	"       drop false exit              ( false ) "
2940 	"    then "
2941 	"      ( addr khatid ) "
2942 	"      mmu_hashcnt 1+ 1  do           ( addr sfmmup ) "
2943 	"         2dup swap i HME_HASH_SHIFT  "
2944 					"( addr sfmmup sfmmup addr hmeshift ) "
2945 	"         HME_HASH_FUNCTION           ( addr sfmmup hmebp ) "
2946 	"         over i 4 pick               "
2947 				"( addr sfmmup hmebp sfmmup rehash addr ) "
2948 	"         HME_HASH_TAG                ( addr sfmmup hmebp hblktag ) "
2949 	"         HME_HASH_TABLE_SEARCH       "
2950 					"( addr sfmmup { null | hmeblkp } ) "
2951 	"         ?dup  if                    ( addr sfmmup hmeblkp ) "
2952 	"            nip swap HBLK_TO_TTEP    ( ttep ) "
2953 	"            dup TTE_IS_VALID  if     ( valid-ttep ) "
2954 	"               PHYS-X@ true          ( tte-data true ) "
2955 	"            else                     ( invalid-tte ) "
2956 	"               drop false            ( false ) "
2957 	"            then                     ( false | tte-data true ) "
2958 	"            unloop exit              ( false | tte-data true ) "
2959 	"         then                        ( addr sfmmup ) "
2960 	"      loop                           ( addr sfmmup ) "
2961 	"      2drop false                    ( false ) "
2962 	"; "
2963 ;
2964 
2965 void
2966 create_va_to_tte(void)
2967 {
2968 	char *bp;
2969 	extern int khmehash_num, uhmehash_num;
2970 	extern struct hmehash_bucket *khme_hash, *uhme_hash;
2971 
2972 #define	OFFSET(type, field)	((uintptr_t)(&((type *)0)->field))
2973 
2974 	bp = (char *)kobj_zalloc(MMU_PAGESIZE, KM_SLEEP);
2975 
2976 	/*
2977 	 * Teach obp how to parse our sw ttes.
2978 	 */
2979 	(void) sprintf(bp, obp_tte_str,
2980 	    MMU_PAGESHIFT,
2981 	    TTE8K,
2982 	    sizeof (struct sf_hment),
2983 	    OFFSET(struct sf_hment, hme_tte),
2984 	    OFFSET(struct hme_blk, hblk_tag),
2985 	    OFFSET(struct hme_blk, hblk_nextpa),
2986 	    OFFSET(struct hme_blk, hblk_misc),
2987 	    OFFSET(struct hme_blk, hblk_hme),
2988 	    NHMENTS,
2989 	    HBLK_SZMASK,
2990 	    HBLK_RANGE_SHIFT,
2991 	    OFFSET(struct hmehash_bucket, hmeh_nextpa),
2992 	    HMEBLK_ENDPA,
2993 	    sizeof (struct hmehash_bucket),
2994 	    HTAG_SFMMUPSZ,
2995 	    HTAG_BSPAGE_SHIFT,
2996 	    HTAG_REHASH_SHIFT,
2997 	    SFMMU_INVALID_SHMERID,
2998 	    mmu_hashcnt,
2999 	    (caddr_t)va_to_pa((caddr_t)uhme_hash),
3000 	    (caddr_t)va_to_pa((caddr_t)khme_hash),
3001 	    UHMEHASH_SZ,
3002 	    KHMEHASH_SZ,
3003 	    KCONTEXT,
3004 	    KHATID,
3005 	    ASI_MEM);
3006 	prom_interpret(bp, 0, 0, 0, 0, 0);
3007 
3008 	kobj_free(bp, MMU_PAGESIZE);
3009 }
3010 
3011 void
3012 install_va_to_tte(void)
3013 {
3014 	/*
3015 	 * advise prom that he can use unix-tte
3016 	 */
3017 	prom_interpret("' unix-tte is va>tte-data", 0, 0, 0, 0, 0);
3018 }
3019 
3020 /*
3021  * Here we add "device-type=console" for /os-io node, for currently
3022  * our kernel console output only supports displaying text and
3023  * performing cursor-positioning operations (through kernel framebuffer
3024  * driver) and it doesn't support other functionalities required for a
3025  * standard "display" device as specified in 1275 spec. The main missing
3026  * interface defined by the 1275 spec is "draw-logo".
3027  * also see the comments above prom_stdout_is_framebuffer().
3028  */
3029 static char *create_node =
3030 	"\" /\" find-device "
3031 	"new-device "
3032 	"\" os-io\" device-name "
3033 	"\" "OBP_DISPLAY_CONSOLE"\" device-type "
3034 	": cb-r/w  ( adr,len method$ -- #read/#written ) "
3035 	"   2>r swap 2 2r> ['] $callback  catch  if "
3036 	"      2drop 3drop 0 "
3037 	"   then "
3038 	"; "
3039 	": read ( adr,len -- #read ) "
3040 	"       \" read\" ['] cb-r/w catch  if  2drop 2drop -2 exit then "
3041 	"       ( retN ... ret1 N ) "
3042 	"       ?dup  if "
3043 	"               swap >r 1-  0  ?do  drop  loop  r> "
3044 	"       else "
3045 	"               -2 "
3046 	"       then "
3047 	";    "
3048 	": write ( adr,len -- #written ) "
3049 	"       \" write\" ['] cb-r/w catch  if  2drop 2drop 0 exit  then "
3050 	"       ( retN ... ret1 N ) "
3051 	"       ?dup  if "
3052 	"               swap >r 1-  0  ?do  drop  loop  r> "
3053 	"        else "
3054 	"               0 "
3055 	"       then "
3056 	"; "
3057 	": poll-tty ( -- ) ; "
3058 	": install-abort  ( -- )  ['] poll-tty d# 10 alarm ; "
3059 	": remove-abort ( -- )  ['] poll-tty 0 alarm ; "
3060 	": cb-give/take ( $method -- ) "
3061 	"       0 -rot ['] $callback catch  ?dup  if "
3062 	"               >r 2drop 2drop r> throw "
3063 	"       else "
3064 	"               0  ?do  drop  loop "
3065 	"       then "
3066 	"; "
3067 	": give ( -- )  \" exit-input\" cb-give/take ; "
3068 	": take ( -- )  \" enter-input\" cb-give/take ; "
3069 	": open ( -- ok? )  true ; "
3070 	": close ( -- ) ; "
3071 	"finish-device "
3072 	"device-end ";
3073 
3074 /*
3075  * Create the OBP input/output node (FCode serial driver).
3076  * It is needed for both USB console keyboard and for
3077  * the kernel terminal emulator.  It is too early to check for a
3078  * kernel console compatible framebuffer now, so we create this
3079  * so that we're ready if we need to enable kernel terminal emulation.
3080  *
3081  * When the USB software takes over the input device at the time
3082  * consconfig runs, OBP's stdin is redirected to this node.
3083  * Whenever the FORTH user interface is used after this switch,
3084  * the node will call back into the kernel for console input.
3085  * If a serial device such as ttya or a UART with a Type 5 keyboard
3086  * attached is used, OBP takes over the serial device when the system
3087  * goes to the debugger after the system is booted.  This sharing
3088  * of the relatively simple serial device is difficult but possible.
3089  * Sharing the USB host controller is impossible due its complexity.
3090  *
3091  * Similarly to USB keyboard input redirection, after consconfig_dacf
3092  * configures a kernel console framebuffer as the standard output
3093  * device, OBP's stdout is switched to to vector through the
3094  * /os-io node into the kernel terminal emulator.
3095  */
3096 static void
3097 startup_create_io_node(void)
3098 {
3099 	prom_interpret(create_node, 0, 0, 0, 0, 0);
3100 }
3101 
3102 
3103 static void
3104 do_prom_version_check(void)
3105 {
3106 	int i;
3107 	pnode_t node;
3108 	char buf[64];
3109 	static char drev[] = "Down-rev firmware detected%s\n"
3110 	    "\tPlease upgrade to the following minimum version:\n"
3111 	    "\t\t%s\n";
3112 
3113 	i = prom_version_check(buf, sizeof (buf), &node);
3114 
3115 	if (i == PROM_VER64_OK)
3116 		return;
3117 
3118 	if (i == PROM_VER64_UPGRADE) {
3119 		cmn_err(CE_WARN, drev, "", buf);
3120 
3121 #ifdef	DEBUG
3122 		prom_enter_mon();	/* Type 'go' to continue */
3123 		cmn_err(CE_WARN, "Booting with down-rev firmware\n");
3124 		return;
3125 #else
3126 		halt(0);
3127 #endif
3128 	}
3129 
3130 	/*
3131 	 * The other possibility is that this is a server running
3132 	 * good firmware, but down-rev firmware was detected on at
3133 	 * least one other cpu board. We just complain if we see
3134 	 * that.
3135 	 */
3136 	cmn_err(CE_WARN, drev, " on one or more CPU boards", buf);
3137 }
3138 
3139 
3140 /*
3141  * Must be defined in platform dependent code.
3142  */
3143 extern caddr_t modtext;
3144 extern size_t modtext_sz;
3145 extern caddr_t moddata;
3146 
3147 #define	HEAPTEXT_ARENA(addr)	\
3148 	((uintptr_t)(addr) < KERNELBASE + 2 * MMU_PAGESIZE4M ? 0 : \
3149 	(((uintptr_t)(addr) - HEAPTEXT_BASE) / \
3150 	(HEAPTEXT_MAPPED + HEAPTEXT_UNMAPPED) + 1))
3151 
3152 #define	HEAPTEXT_OVERSIZED(addr)	\
3153 	((uintptr_t)(addr) >= HEAPTEXT_BASE + HEAPTEXT_SIZE - HEAPTEXT_OVERSIZE)
3154 
3155 #define	HEAPTEXT_IN_NUCLEUSDATA(addr) \
3156 	(((uintptr_t)(addr) >= KERNELBASE + 2 * MMU_PAGESIZE4M) && \
3157 	((uintptr_t)(addr) < KERNELBASE + 3 * MMU_PAGESIZE4M))
3158 
3159 vmem_t *texthole_source[HEAPTEXT_NARENAS];
3160 vmem_t *texthole_arena[HEAPTEXT_NARENAS];
3161 kmutex_t texthole_lock;
3162 
3163 char kern_bootargs[OBP_MAXPATHLEN];
3164 char kern_bootfile[OBP_MAXPATHLEN];
3165 
3166 void
3167 kobj_vmem_init(vmem_t **text_arena, vmem_t **data_arena)
3168 {
3169 	uintptr_t addr, limit;
3170 
3171 	addr = HEAPTEXT_BASE;
3172 	limit = addr + HEAPTEXT_SIZE - HEAPTEXT_OVERSIZE;
3173 
3174 	/*
3175 	 * Before we initialize the text_arena, we want to punch holes in the
3176 	 * underlying heaptext_arena.  This guarantees that for any text
3177 	 * address we can find a text hole less than HEAPTEXT_MAPPED away.
3178 	 */
3179 	for (; addr + HEAPTEXT_UNMAPPED <= limit;
3180 	    addr += HEAPTEXT_MAPPED + HEAPTEXT_UNMAPPED) {
3181 		(void) vmem_xalloc(heaptext_arena, HEAPTEXT_UNMAPPED, PAGESIZE,
3182 		    0, 0, (void *)addr, (void *)(addr + HEAPTEXT_UNMAPPED),
3183 		    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
3184 	}
3185 
3186 	/*
3187 	 * Allocate one page at the oversize to break up the text region
3188 	 * from the oversized region.
3189 	 */
3190 	(void) vmem_xalloc(heaptext_arena, PAGESIZE, PAGESIZE, 0, 0,
3191 	    (void *)limit, (void *)(limit + PAGESIZE),
3192 	    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
3193 
3194 	*text_arena = vmem_create("module_text", modtext_sz ? modtext : NULL,
3195 	    modtext_sz, sizeof (uintptr_t), segkmem_alloc, segkmem_free,
3196 	    heaptext_arena, 0, VM_SLEEP);
3197 	*data_arena = vmem_create("module_data", moddata, MODDATA, 1,
3198 	    segkmem_alloc, segkmem_free, heap32_arena, 0, VM_SLEEP);
3199 }
3200 
3201 caddr_t
3202 kobj_text_alloc(vmem_t *arena, size_t size)
3203 {
3204 	caddr_t rval, better;
3205 
3206 	/*
3207 	 * First, try a sleeping allocation.
3208 	 */
3209 	rval = vmem_alloc(arena, size, VM_SLEEP | VM_BESTFIT);
3210 
3211 	if (size >= HEAPTEXT_MAPPED || !HEAPTEXT_OVERSIZED(rval))
3212 		return (rval);
3213 
3214 	/*
3215 	 * We didn't get the area that we wanted.  We're going to try to do an
3216 	 * allocation with explicit constraints.
3217 	 */
3218 	better = vmem_xalloc(arena, size, sizeof (uintptr_t), 0, 0, NULL,
3219 	    (void *)(HEAPTEXT_BASE + HEAPTEXT_SIZE - HEAPTEXT_OVERSIZE),
3220 	    VM_NOSLEEP | VM_BESTFIT);
3221 
3222 	if (better != NULL) {
3223 		/*
3224 		 * That worked.  Free our first attempt and return.
3225 		 */
3226 		vmem_free(arena, rval, size);
3227 		return (better);
3228 	}
3229 
3230 	/*
3231 	 * That didn't work; we'll have to return our first attempt.
3232 	 */
3233 	return (rval);
3234 }
3235 
3236 caddr_t
3237 kobj_texthole_alloc(caddr_t addr, size_t size)
3238 {
3239 	int arena = HEAPTEXT_ARENA(addr);
3240 	char c[30];
3241 	uintptr_t base;
3242 
3243 	if (HEAPTEXT_OVERSIZED(addr) || HEAPTEXT_IN_NUCLEUSDATA(addr)) {
3244 		/*
3245 		 * If this is an oversized allocation or it is allocated in
3246 		 * the nucleus data page, there is no text hole available for
3247 		 * it; return NULL.
3248 		 */
3249 		return (NULL);
3250 	}
3251 
3252 	mutex_enter(&texthole_lock);
3253 
3254 	if (texthole_arena[arena] == NULL) {
3255 		ASSERT(texthole_source[arena] == NULL);
3256 
3257 		if (arena == 0) {
3258 			texthole_source[0] = vmem_create("module_text_holesrc",
3259 			    (void *)(KERNELBASE + MMU_PAGESIZE4M),
3260 			    MMU_PAGESIZE4M, PAGESIZE, NULL, NULL, NULL,
3261 			    0, VM_SLEEP);
3262 		} else {
3263 			base = HEAPTEXT_BASE +
3264 			    (arena - 1) * (HEAPTEXT_MAPPED + HEAPTEXT_UNMAPPED);
3265 
3266 			(void) snprintf(c, sizeof (c),
3267 			    "heaptext_holesrc_%d", arena);
3268 
3269 			texthole_source[arena] = vmem_create(c, (void *)base,
3270 			    HEAPTEXT_UNMAPPED, PAGESIZE, NULL, NULL, NULL,
3271 			    0, VM_SLEEP);
3272 		}
3273 
3274 		(void) snprintf(c, sizeof (c), "heaptext_hole_%d", arena);
3275 
3276 		texthole_arena[arena] = vmem_create(c, NULL, 0,
3277 		    sizeof (uint32_t), segkmem_alloc_permanent, segkmem_free,
3278 		    texthole_source[arena], 0, VM_SLEEP);
3279 	}
3280 
3281 	mutex_exit(&texthole_lock);
3282 
3283 	ASSERT(texthole_arena[arena] != NULL);
3284 	ASSERT(arena >= 0 && arena < HEAPTEXT_NARENAS);
3285 	return (vmem_alloc(texthole_arena[arena], size,
3286 	    VM_BESTFIT | VM_NOSLEEP));
3287 }
3288 
3289 void
3290 kobj_texthole_free(caddr_t addr, size_t size)
3291 {
3292 	int arena = HEAPTEXT_ARENA(addr);
3293 
3294 	ASSERT(arena >= 0 && arena < HEAPTEXT_NARENAS);
3295 	ASSERT(texthole_arena[arena] != NULL);
3296 	vmem_free(texthole_arena[arena], addr, size);
3297 }
3298 
3299 void
3300 release_bootstrap(void)
3301 {
3302 	if (&cif_init)
3303 		cif_init();
3304 }
3305