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