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