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