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