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