xref: /titanic_52/usr/src/uts/i86pc/os/startup.c (revision 3c112a2b34403220c06c3e2fcac403358cfba168)
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  * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 /*
25  * Copyright (c) 2010, Intel Corporation.
26  * All rights reserved.
27  */
28 
29 #include <sys/types.h>
30 #include <sys/t_lock.h>
31 #include <sys/param.h>
32 #include <sys/sysmacros.h>
33 #include <sys/signal.h>
34 #include <sys/systm.h>
35 #include <sys/user.h>
36 #include <sys/mman.h>
37 #include <sys/vm.h>
38 #include <sys/conf.h>
39 #include <sys/avintr.h>
40 #include <sys/autoconf.h>
41 #include <sys/disp.h>
42 #include <sys/class.h>
43 #include <sys/bitmap.h>
44 
45 #include <sys/privregs.h>
46 
47 #include <sys/proc.h>
48 #include <sys/buf.h>
49 #include <sys/kmem.h>
50 #include <sys/mem.h>
51 #include <sys/kstat.h>
52 
53 #include <sys/reboot.h>
54 
55 #include <sys/cred.h>
56 #include <sys/vnode.h>
57 #include <sys/file.h>
58 
59 #include <sys/procfs.h>
60 
61 #include <sys/vfs.h>
62 #include <sys/cmn_err.h>
63 #include <sys/utsname.h>
64 #include <sys/debug.h>
65 #include <sys/kdi.h>
66 
67 #include <sys/dumphdr.h>
68 #include <sys/bootconf.h>
69 #include <sys/memlist_plat.h>
70 #include <sys/varargs.h>
71 #include <sys/promif.h>
72 #include <sys/modctl.h>
73 
74 #include <sys/sunddi.h>
75 #include <sys/sunndi.h>
76 #include <sys/ndi_impldefs.h>
77 #include <sys/ddidmareq.h>
78 #include <sys/psw.h>
79 #include <sys/regset.h>
80 #include <sys/clock.h>
81 #include <sys/pte.h>
82 #include <sys/tss.h>
83 #include <sys/stack.h>
84 #include <sys/trap.h>
85 #include <sys/fp.h>
86 #include <vm/kboot_mmu.h>
87 #include <vm/anon.h>
88 #include <vm/as.h>
89 #include <vm/page.h>
90 #include <vm/seg.h>
91 #include <vm/seg_dev.h>
92 #include <vm/seg_kmem.h>
93 #include <vm/seg_kpm.h>
94 #include <vm/seg_map.h>
95 #include <vm/seg_vn.h>
96 #include <vm/seg_kp.h>
97 #include <sys/memnode.h>
98 #include <vm/vm_dep.h>
99 #include <sys/thread.h>
100 #include <sys/sysconf.h>
101 #include <sys/vm_machparam.h>
102 #include <sys/archsystm.h>
103 #include <sys/machsystm.h>
104 #include <vm/hat.h>
105 #include <vm/hat_i86.h>
106 #include <sys/pmem.h>
107 #include <sys/smp_impldefs.h>
108 #include <sys/x86_archext.h>
109 #include <sys/cpuvar.h>
110 #include <sys/segments.h>
111 #include <sys/clconf.h>
112 #include <sys/kobj.h>
113 #include <sys/kobj_lex.h>
114 #include <sys/cpc_impl.h>
115 #include <sys/cpu_module.h>
116 #include <sys/smbios.h>
117 #include <sys/debug_info.h>
118 #include <sys/bootinfo.h>
119 #include <sys/ddi_timer.h>
120 #include <sys/systeminfo.h>
121 #include <sys/multiboot.h>
122 
123 #ifdef	__xpv
124 
125 #include <sys/hypervisor.h>
126 #include <sys/xen_mmu.h>
127 #include <sys/evtchn_impl.h>
128 #include <sys/gnttab.h>
129 #include <sys/xpv_panic.h>
130 #include <xen/sys/xenbus_comms.h>
131 #include <xen/public/physdev.h>
132 
133 extern void xen_late_startup(void);
134 
135 struct xen_evt_data cpu0_evt_data;
136 
137 #else	/* __xpv */
138 #include <sys/memlist_impl.h>
139 
140 extern void mem_config_init(void);
141 #endif /* __xpv */
142 
143 extern void progressbar_init(void);
144 extern void brand_init(void);
145 extern void pcf_init(void);
146 extern void pg_init(void);
147 
148 extern int size_pse_array(pgcnt_t, int);
149 
150 #if defined(_SOFT_HOSTID)
151 
152 #include <sys/rtc.h>
153 
154 static int32_t set_soft_hostid(void);
155 static char hostid_file[] = "/etc/hostid";
156 
157 #endif
158 
159 void *gfx_devinfo_list;
160 
161 #if defined(__amd64) && !defined(__xpv)
162 extern void immu_startup(void);
163 #endif
164 
165 /*
166  * XXX make declaration below "static" when drivers no longer use this
167  * interface.
168  */
169 extern caddr_t p0_va;	/* Virtual address for accessing physical page 0 */
170 
171 /*
172  * segkp
173  */
174 extern int segkp_fromheap;
175 
176 static void kvm_init(void);
177 static void startup_init(void);
178 static void startup_memlist(void);
179 static void startup_kmem(void);
180 static void startup_modules(void);
181 static void startup_vm(void);
182 static void startup_end(void);
183 static void layout_kernel_va(void);
184 
185 /*
186  * Declare these as initialized data so we can patch them.
187  */
188 #ifdef __i386
189 
190 /*
191  * Due to virtual address space limitations running in 32 bit mode, restrict
192  * the amount of physical memory configured to a max of PHYSMEM pages (16g).
193  *
194  * If the physical max memory size of 64g were allowed to be configured, the
195  * size of user virtual address space will be less than 1g. A limited user
196  * address space greatly reduces the range of applications that can run.
197  *
198  * If more physical memory than PHYSMEM is required, users should preferably
199  * run in 64 bit mode which has far looser virtual address space limitations.
200  *
201  * If 64 bit mode is not available (as in IA32) and/or more physical memory
202  * than PHYSMEM is required in 32 bit mode, physmem can be set to the desired
203  * value or to 0 (to configure all available memory) via eeprom(1M). kernelbase
204  * should also be carefully tuned to balance out the need of the user
205  * application while minimizing the risk of kernel heap exhaustion due to
206  * kernelbase being set too high.
207  */
208 #define	PHYSMEM	0x400000
209 
210 #else /* __amd64 */
211 
212 /*
213  * For now we can handle memory with physical addresses up to about
214  * 64 Terabytes. This keeps the kernel above the VA hole, leaving roughly
215  * half the VA space for seg_kpm. When systems get bigger than 64TB this
216  * code will need revisiting. There is an implicit assumption that there
217  * are no *huge* holes in the physical address space too.
218  */
219 #define	TERABYTE		(1ul << 40)
220 #define	PHYSMEM_MAX64		mmu_btop(64 * TERABYTE)
221 #define	PHYSMEM			PHYSMEM_MAX64
222 #define	AMD64_VA_HOLE_END	0xFFFF800000000000ul
223 
224 #endif /* __amd64 */
225 
226 pgcnt_t physmem = PHYSMEM;
227 pgcnt_t obp_pages;	/* Memory used by PROM for its text and data */
228 
229 char *kobj_file_buf;
230 int kobj_file_bufsize;	/* set in /etc/system */
231 
232 /* Global variables for MP support. Used in mp_startup */
233 caddr_t	rm_platter_va = 0;
234 uint32_t rm_platter_pa;
235 
236 int	auto_lpg_disable = 1;
237 
238 /*
239  * Some CPUs have holes in the middle of the 64-bit virtual address range.
240  */
241 uintptr_t hole_start, hole_end;
242 
243 /*
244  * kpm mapping window
245  */
246 caddr_t kpm_vbase;
247 size_t  kpm_size;
248 static int kpm_desired;
249 #ifdef __amd64
250 static uintptr_t segkpm_base = (uintptr_t)SEGKPM_BASE;
251 #endif
252 
253 /*
254  * Configuration parameters set at boot time.
255  */
256 
257 caddr_t econtig;		/* end of first block of contiguous kernel */
258 
259 struct bootops		*bootops = 0;	/* passed in from boot */
260 struct bootops		**bootopsp;
261 struct boot_syscalls	*sysp;		/* passed in from boot */
262 
263 char bootblock_fstype[16];
264 
265 char kern_bootargs[OBP_MAXPATHLEN];
266 char kern_bootfile[OBP_MAXPATHLEN];
267 
268 /*
269  * ZFS zio segment.  This allows us to exclude large portions of ZFS data that
270  * gets cached in kmem caches on the heap.  If this is set to zero, we allocate
271  * zio buffers from their own segment, otherwise they are allocated from the
272  * heap.  The optimization of allocating zio buffers from their own segment is
273  * only valid on 64-bit kernels.
274  */
275 #if defined(__amd64)
276 int segzio_fromheap = 0;
277 #else
278 int segzio_fromheap = 1;
279 #endif
280 
281 /*
282  * new memory fragmentations are possible in startup() due to BOP_ALLOCs. this
283  * depends on number of BOP_ALLOC calls made and requested size, memory size
284  * combination and whether boot.bin memory needs to be freed.
285  */
286 #define	POSS_NEW_FRAGMENTS	12
287 
288 /*
289  * VM data structures
290  */
291 long page_hashsz;		/* Size of page hash table (power of two) */
292 unsigned int page_hashsz_shift;	/* log2(page_hashsz) */
293 struct page *pp_base;		/* Base of initial system page struct array */
294 struct page **page_hash;	/* Page hash table */
295 pad_mutex_t *pse_mutex;		/* Locks protecting pp->p_selock */
296 size_t pse_table_size;		/* Number of mutexes in pse_mutex[] */
297 int pse_shift;			/* log2(pse_table_size) */
298 struct seg ktextseg;		/* Segment used for kernel executable image */
299 struct seg kvalloc;		/* Segment used for "valloc" mapping */
300 struct seg kpseg;		/* Segment used for pageable kernel virt mem */
301 struct seg kmapseg;		/* Segment used for generic kernel mappings */
302 struct seg kdebugseg;		/* Segment used for the kernel debugger */
303 
304 struct seg *segkmap = &kmapseg;	/* Kernel generic mapping segment */
305 static struct seg *segmap = &kmapseg;	/* easier to use name for in here */
306 
307 struct seg *segkp = &kpseg;	/* Pageable kernel virtual memory segment */
308 
309 #if defined(__amd64)
310 struct seg kvseg_core;		/* Segment used for the core heap */
311 struct seg kpmseg;		/* Segment used for physical mapping */
312 struct seg *segkpm = &kpmseg;	/* 64bit kernel physical mapping segment */
313 #else
314 struct seg *segkpm = NULL;	/* Unused on IA32 */
315 #endif
316 
317 caddr_t segkp_base;		/* Base address of segkp */
318 caddr_t segzio_base;		/* Base address of segzio */
319 #if defined(__amd64)
320 pgcnt_t segkpsize = btop(SEGKPDEFSIZE);	/* size of segkp segment in pages */
321 #else
322 pgcnt_t segkpsize = 0;
323 #endif
324 pgcnt_t segziosize = 0;		/* size of zio segment in pages */
325 
326 /*
327  * A static DR page_t VA map is reserved that can map the page structures
328  * for a domain's entire RA space. The pages that back this space are
329  * dynamically allocated and need not be physically contiguous.  The DR
330  * map size is derived from KPM size.
331  * This mechanism isn't used by x86 yet, so just stubs here.
332  */
333 int ppvm_enable = 0;		/* Static virtual map for page structs */
334 page_t *ppvm_base = NULL;	/* Base of page struct map */
335 pgcnt_t ppvm_size = 0;		/* Size of page struct map */
336 
337 /*
338  * VA range available to the debugger
339  */
340 const caddr_t kdi_segdebugbase = (const caddr_t)SEGDEBUGBASE;
341 const size_t kdi_segdebugsize = SEGDEBUGSIZE;
342 
343 struct memseg *memseg_base;
344 struct vnode unused_pages_vp;
345 
346 #define	FOURGB	0x100000000LL
347 
348 struct memlist *memlist;
349 
350 caddr_t s_text;		/* start of kernel text segment */
351 caddr_t e_text;		/* end of kernel text segment */
352 caddr_t s_data;		/* start of kernel data segment */
353 caddr_t e_data;		/* end of kernel data segment */
354 caddr_t modtext;	/* start of loadable module text reserved */
355 caddr_t e_modtext;	/* end of loadable module text reserved */
356 caddr_t moddata;	/* start of loadable module data reserved */
357 caddr_t e_moddata;	/* end of loadable module data reserved */
358 
359 struct memlist *phys_install;	/* Total installed physical memory */
360 struct memlist *phys_avail;	/* Total available physical memory */
361 struct memlist *bios_rsvd;	/* Bios reserved memory */
362 
363 /*
364  * kphysm_init returns the number of pages that were processed
365  */
366 static pgcnt_t kphysm_init(page_t *, pgcnt_t);
367 
368 #define	IO_PROP_SIZE	64	/* device property size */
369 
370 /*
371  * a couple useful roundup macros
372  */
373 #define	ROUND_UP_PAGE(x)	\
374 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), (uintptr_t)MMU_PAGESIZE))
375 #define	ROUND_UP_LPAGE(x)	\
376 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), mmu.level_size[1]))
377 #define	ROUND_UP_4MEG(x)	\
378 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), (uintptr_t)FOUR_MEG))
379 #define	ROUND_UP_TOPLEVEL(x)	\
380 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), mmu.level_size[mmu.max_level]))
381 
382 /*
383  *	32-bit Kernel's Virtual memory layout.
384  *		+-----------------------+
385  *		|			|
386  * 0xFFC00000  -|-----------------------|- ARGSBASE
387  *		|	debugger	|
388  * 0xFF800000  -|-----------------------|- SEGDEBUGBASE
389  *		|      Kernel Data	|
390  * 0xFEC00000  -|-----------------------|
391  *              |      Kernel Text	|
392  * 0xFE800000  -|-----------------------|- KERNEL_TEXT (0xFB400000 on Xen)
393  *		|---       GDT       ---|- GDT page (GDT_VA)
394  *		|---    debug info   ---|- debug info (DEBUG_INFO_VA)
395  *		|			|
396  * 		|   page_t structures	|
397  * 		|   memsegs, memlists, 	|
398  * 		|   page hash, etc.	|
399  * ---	       -|-----------------------|- ekernelheap, valloc_base (floating)
400  *		|			|  (segkp is just an arena in the heap)
401  *		|			|
402  *		|	kvseg		|
403  *		|			|
404  *		|			|
405  * ---         -|-----------------------|- kernelheap (floating)
406  * 		|        Segkmap	|
407  * 0xC3002000  -|-----------------------|- segmap_start (floating)
408  *		|	Red Zone	|
409  * 0xC3000000  -|-----------------------|- kernelbase / userlimit (floating)
410  *		|			|			||
411  *		|     Shared objects	|			\/
412  *		|			|
413  *		:			:
414  *		|	user data	|
415  *		|-----------------------|
416  *		|	user text	|
417  * 0x08048000  -|-----------------------|
418  *		|	user stack	|
419  *		:			:
420  *		|	invalid		|
421  * 0x00000000	+-----------------------+
422  *
423  *
424  *		64-bit Kernel's Virtual memory layout. (assuming 64 bit app)
425  *			+-----------------------+
426  *			|			|
427  * 0xFFFFFFFF.FFC00000  |-----------------------|- ARGSBASE
428  *			|	debugger (?)	|
429  * 0xFFFFFFFF.FF800000  |-----------------------|- SEGDEBUGBASE
430  *			|      unused    	|
431  *			+-----------------------+
432  *			|      Kernel Data	|
433  * 0xFFFFFFFF.FBC00000  |-----------------------|
434  *			|      Kernel Text	|
435  * 0xFFFFFFFF.FB800000  |-----------------------|- KERNEL_TEXT
436  *			|---       GDT       ---|- GDT page (GDT_VA)
437  *			|---    debug info   ---|- debug info (DEBUG_INFO_VA)
438  *			|			|
439  * 			|      Core heap	| (used for loadable modules)
440  * 0xFFFFFFFF.C0000000  |-----------------------|- core_base / ekernelheap
441  *			|	 Kernel		|
442  *			|	  heap		|
443  * 0xFFFFFXXX.XXX00000  |-----------------------|- kernelheap (floating)
444  *			|	 segmap		|
445  * 0xFFFFFXXX.XXX00000  |-----------------------|- segmap_start (floating)
446  *			|    device mappings	|
447  * 0xFFFFFXXX.XXX00000  |-----------------------|- toxic_addr (floating)
448  *			|	  segzio	|
449  * 0xFFFFFXXX.XXX00000  |-----------------------|- segzio_base (floating)
450  *			|	  segkp		|
451  * ---                  |-----------------------|- segkp_base (floating)
452  * 			|   page_t structures	|  valloc_base + valloc_sz
453  * 			|   memsegs, memlists, 	|
454  * 			|   page hash, etc.	|
455  * 0xFFFFFF00.00000000  |-----------------------|- valloc_base (lower if > 1TB)
456  *			|	 segkpm		|
457  * 0xFFFFFE00.00000000  |-----------------------|
458  *			|	Red Zone	|
459  * 0xFFFFFD80.00000000  |-----------------------|- KERNELBASE (lower if > 1TB)
460  *			|     User stack	|- User space memory
461  * 			|			|
462  * 			| shared objects, etc	|	(grows downwards)
463  *			:			:
464  * 			|			|
465  * 0xFFFF8000.00000000  |-----------------------|
466  * 			|			|
467  * 			| VA Hole / unused	|
468  * 			|			|
469  * 0x00008000.00000000  |-----------------------|
470  *			|			|
471  *			|			|
472  *			:			:
473  *			|	user heap	|	(grows upwards)
474  *			|			|
475  *			|	user data	|
476  *			|-----------------------|
477  *			|	user text	|
478  * 0x00000000.04000000  |-----------------------|
479  *			|	invalid		|
480  * 0x00000000.00000000	+-----------------------+
481  *
482  * A 32 bit app on the 64 bit kernel sees the same layout as on the 32 bit
483  * kernel, except that userlimit is raised to 0xfe000000
484  *
485  * Floating values:
486  *
487  * valloc_base: start of the kernel's memory management/tracking data
488  * structures.  This region contains page_t structures for
489  * physical memory, memsegs, memlists, and the page hash.
490  *
491  * core_base: start of the kernel's "core" heap area on 64-bit systems.
492  * This area is intended to be used for global data as well as for module
493  * text/data that does not fit into the nucleus pages.  The core heap is
494  * restricted to a 2GB range, allowing every address within it to be
495  * accessed using rip-relative addressing
496  *
497  * ekernelheap: end of kernelheap and start of segmap.
498  *
499  * kernelheap: start of kernel heap.  On 32-bit systems, this starts right
500  * above a red zone that separates the user's address space from the
501  * kernel's.  On 64-bit systems, it sits above segkp and segkpm.
502  *
503  * segmap_start: start of segmap. The length of segmap can be modified
504  * through eeprom. The default length is 16MB on 32-bit systems and 64MB
505  * on 64-bit systems.
506  *
507  * kernelbase: On a 32-bit kernel the default value of 0xd4000000 will be
508  * decreased by 2X the size required for page_t.  This allows the kernel
509  * heap to grow in size with physical memory.  With sizeof(page_t) == 80
510  * bytes, the following shows the values of kernelbase and kernel heap
511  * sizes for different memory configurations (assuming default segmap and
512  * segkp sizes).
513  *
514  *	mem	size for	kernelbase	kernel heap
515  *	size	page_t's			size
516  *	----	---------	----------	-----------
517  *	1gb	0x01400000	0xd1800000	684MB
518  *	2gb	0x02800000	0xcf000000	704MB
519  *	4gb	0x05000000	0xca000000	744MB
520  *	6gb	0x07800000	0xc5000000	784MB
521  *	8gb	0x0a000000	0xc0000000	824MB
522  *	16gb	0x14000000	0xac000000	984MB
523  *	32gb	0x28000000	0x84000000	1304MB
524  *	64gb	0x50000000	0x34000000	1944MB (*)
525  *
526  * kernelbase is less than the abi minimum of 0xc0000000 for memory
527  * configurations above 8gb.
528  *
529  * (*) support for memory configurations above 32gb will require manual tuning
530  * of kernelbase to balance out the need of user applications.
531  */
532 
533 /* real-time-clock initialization parameters */
534 extern time_t process_rtc_config_file(void);
535 
536 uintptr_t	kernelbase;
537 uintptr_t	postbootkernelbase;	/* not set till boot loader is gone */
538 uintptr_t	eprom_kernelbase;
539 size_t		segmapsize;
540 uintptr_t	segmap_start;
541 int		segmapfreelists;
542 pgcnt_t		npages;
543 pgcnt_t		orig_npages;
544 size_t		core_size;		/* size of "core" heap */
545 uintptr_t	core_base;		/* base address of "core" heap */
546 
547 /*
548  * List of bootstrap pages. We mark these as allocated in startup.
549  * release_bootstrap() will free them when we're completely done with
550  * the bootstrap.
551  */
552 static page_t *bootpages;
553 
554 /*
555  * boot time pages that have a vnode from the ramdisk will keep that forever.
556  */
557 static page_t *rd_pages;
558 
559 /*
560  * Lower 64K
561  */
562 static page_t *lower_pages = NULL;
563 static int lower_pages_count = 0;
564 
565 struct system_hardware system_hardware;
566 
567 /*
568  * Enable some debugging messages concerning memory usage...
569  */
570 static void
571 print_memlist(char *title, struct memlist *mp)
572 {
573 	prom_printf("MEMLIST: %s:\n", title);
574 	while (mp != NULL)  {
575 		prom_printf("\tAddress 0x%" PRIx64 ", size 0x%" PRIx64 "\n",
576 		    mp->ml_address, mp->ml_size);
577 		mp = mp->ml_next;
578 	}
579 }
580 
581 /*
582  * XX64 need a comment here.. are these just default values, surely
583  * we read the "cpuid" type information to figure this out.
584  */
585 int	l2cache_sz = 0x80000;
586 int	l2cache_linesz = 0x40;
587 int	l2cache_assoc = 1;
588 
589 static size_t	textrepl_min_gb = 10;
590 
591 /*
592  * on 64 bit we use a predifined VA range for mapping devices in the kernel
593  * on 32 bit the mappings are intermixed in the heap, so we use a bit map
594  */
595 #ifdef __amd64
596 
597 vmem_t		*device_arena;
598 uintptr_t	toxic_addr = (uintptr_t)NULL;
599 size_t		toxic_size = 1024 * 1024 * 1024; /* Sparc uses 1 gig too */
600 
601 #else	/* __i386 */
602 
603 ulong_t		*toxic_bit_map;	/* one bit for each 4k of VA in heap_arena */
604 size_t		toxic_bit_map_len = 0;	/* in bits */
605 
606 #endif	/* __i386 */
607 
608 /*
609  * Simple boot time debug facilities
610  */
611 static char *prm_dbg_str[] = {
612 	"%s:%d: '%s' is 0x%x\n",
613 	"%s:%d: '%s' is 0x%llx\n"
614 };
615 
616 int prom_debug;
617 
618 #define	PRM_DEBUG(q)	if (prom_debug) 	\
619 	prom_printf(prm_dbg_str[sizeof (q) >> 3], "startup.c", __LINE__, #q, q);
620 #define	PRM_POINT(q)	if (prom_debug) 	\
621 	prom_printf("%s:%d: %s\n", "startup.c", __LINE__, q);
622 
623 /*
624  * This structure is used to keep track of the intial allocations
625  * done in startup_memlist(). The value of NUM_ALLOCATIONS needs to
626  * be >= the number of ADD_TO_ALLOCATIONS() executed in the code.
627  */
628 #define	NUM_ALLOCATIONS 8
629 int num_allocations = 0;
630 struct {
631 	void **al_ptr;
632 	size_t al_size;
633 } allocations[NUM_ALLOCATIONS];
634 size_t valloc_sz = 0;
635 uintptr_t valloc_base;
636 
637 #define	ADD_TO_ALLOCATIONS(ptr, size) {					\
638 		size = ROUND_UP_PAGE(size);		 		\
639 		if (num_allocations == NUM_ALLOCATIONS)			\
640 			panic("too many ADD_TO_ALLOCATIONS()");		\
641 		allocations[num_allocations].al_ptr = (void**)&ptr;	\
642 		allocations[num_allocations].al_size = size;		\
643 		valloc_sz += size;					\
644 		++num_allocations;				 	\
645 	}
646 
647 /*
648  * Allocate all the initial memory needed by the page allocator.
649  */
650 static void
651 perform_allocations(void)
652 {
653 	caddr_t mem;
654 	int i;
655 	int valloc_align;
656 
657 	PRM_DEBUG(valloc_base);
658 	PRM_DEBUG(valloc_sz);
659 	valloc_align = mmu.level_size[mmu.max_page_level > 0];
660 	mem = BOP_ALLOC(bootops, (caddr_t)valloc_base, valloc_sz, valloc_align);
661 	if (mem != (caddr_t)valloc_base)
662 		panic("BOP_ALLOC() failed");
663 	bzero(mem, valloc_sz);
664 	for (i = 0; i < num_allocations; ++i) {
665 		*allocations[i].al_ptr = (void *)mem;
666 		mem += allocations[i].al_size;
667 	}
668 }
669 
670 /*
671  * Our world looks like this at startup time.
672  *
673  * In a 32-bit OS, boot loads the kernel text at 0xfe800000 and kernel data
674  * at 0xfec00000.  On a 64-bit OS, kernel text and data are loaded at
675  * 0xffffffff.fe800000 and 0xffffffff.fec00000 respectively.  Those
676  * addresses are fixed in the binary at link time.
677  *
678  * On the text page:
679  * unix/genunix/krtld/module text loads.
680  *
681  * On the data page:
682  * unix/genunix/krtld/module data loads.
683  *
684  * Machine-dependent startup code
685  */
686 void
687 startup(void)
688 {
689 #if !defined(__xpv)
690 	extern void startup_pci_bios(void);
691 #endif
692 	extern cpuset_t cpu_ready_set;
693 
694 	/*
695 	 * Make sure that nobody tries to use sekpm until we have
696 	 * initialized it properly.
697 	 */
698 #if defined(__amd64)
699 	kpm_desired = 1;
700 #endif
701 	kpm_enable = 0;
702 	CPUSET_ONLY(cpu_ready_set, 0);	/* cpu 0 is boot cpu */
703 
704 #if defined(__xpv)	/* XXPV fix me! */
705 	{
706 		extern int segvn_use_regions;
707 		segvn_use_regions = 0;
708 	}
709 #endif
710 	progressbar_init();
711 	startup_init();
712 #if defined(__xpv)
713 	startup_xen_version();
714 #endif
715 	startup_memlist();
716 	startup_kmem();
717 	startup_vm();
718 #if !defined(__xpv)
719 	/*
720 	 * Note we need to do this even on fast reboot in order to access
721 	 * the irq routing table (used for pci labels).
722 	 */
723 	startup_pci_bios();
724 #endif
725 #if defined(__xpv)
726 	startup_xen_mca();
727 #endif
728 	startup_modules();
729 
730 	startup_end();
731 }
732 
733 static void
734 startup_init()
735 {
736 	PRM_POINT("startup_init() starting...");
737 
738 	/*
739 	 * Complete the extraction of cpuid data
740 	 */
741 	cpuid_pass2(CPU);
742 
743 	(void) check_boot_version(BOP_GETVERSION(bootops));
744 
745 	/*
746 	 * Check for prom_debug in boot environment
747 	 */
748 	if (BOP_GETPROPLEN(bootops, "prom_debug") >= 0) {
749 		++prom_debug;
750 		PRM_POINT("prom_debug found in boot enviroment");
751 	}
752 
753 	/*
754 	 * Collect node, cpu and memory configuration information.
755 	 */
756 	get_system_configuration();
757 
758 	/*
759 	 * Halt if this is an unsupported processor.
760 	 */
761 	if (x86_type == X86_TYPE_486 || x86_type == X86_TYPE_CYRIX_486) {
762 		printf("\n486 processor (\"%s\") detected.\n",
763 		    CPU->cpu_brandstr);
764 		halt("This processor is not supported by this release "
765 		    "of Solaris.");
766 	}
767 
768 	PRM_POINT("startup_init() done");
769 }
770 
771 /*
772  * Callback for copy_memlist_filter() to filter nucleus, kadb/kmdb, (ie.
773  * everything mapped above KERNEL_TEXT) pages from phys_avail. Note it
774  * also filters out physical page zero.  There is some reliance on the
775  * boot loader allocating only a few contiguous physical memory chunks.
776  */
777 static void
778 avail_filter(uint64_t *addr, uint64_t *size)
779 {
780 	uintptr_t va;
781 	uintptr_t next_va;
782 	pfn_t pfn;
783 	uint64_t pfn_addr;
784 	uint64_t pfn_eaddr;
785 	uint_t prot;
786 	size_t len;
787 	uint_t change;
788 
789 	if (prom_debug)
790 		prom_printf("\tFilter: in: a=%" PRIx64 ", s=%" PRIx64 "\n",
791 		    *addr, *size);
792 
793 	/*
794 	 * page zero is required for BIOS.. never make it available
795 	 */
796 	if (*addr == 0) {
797 		*addr += MMU_PAGESIZE;
798 		*size -= MMU_PAGESIZE;
799 	}
800 
801 	/*
802 	 * First we trim from the front of the range. Since kbm_probe()
803 	 * walks ranges in virtual order, but addr/size are physical, we need
804 	 * to the list until no changes are seen.  This deals with the case
805 	 * where page "p" is mapped at v, page "p + PAGESIZE" is mapped at w
806 	 * but w < v.
807 	 */
808 	do {
809 		change = 0;
810 		for (va = KERNEL_TEXT;
811 		    *size > 0 && kbm_probe(&va, &len, &pfn, &prot) != 0;
812 		    va = next_va) {
813 
814 			next_va = va + len;
815 			pfn_addr = pfn_to_pa(pfn);
816 			pfn_eaddr = pfn_addr + len;
817 
818 			if (pfn_addr <= *addr && pfn_eaddr > *addr) {
819 				change = 1;
820 				while (*size > 0 && len > 0) {
821 					*addr += MMU_PAGESIZE;
822 					*size -= MMU_PAGESIZE;
823 					len -= MMU_PAGESIZE;
824 				}
825 			}
826 		}
827 		if (change && prom_debug)
828 			prom_printf("\t\ttrim: a=%" PRIx64 ", s=%" PRIx64 "\n",
829 			    *addr, *size);
830 	} while (change);
831 
832 	/*
833 	 * Trim pages from the end of the range.
834 	 */
835 	for (va = KERNEL_TEXT;
836 	    *size > 0 && kbm_probe(&va, &len, &pfn, &prot) != 0;
837 	    va = next_va) {
838 
839 		next_va = va + len;
840 		pfn_addr = pfn_to_pa(pfn);
841 
842 		if (pfn_addr >= *addr && pfn_addr < *addr + *size)
843 			*size = pfn_addr - *addr;
844 	}
845 
846 	if (prom_debug)
847 		prom_printf("\tFilter out: a=%" PRIx64 ", s=%" PRIx64 "\n",
848 		    *addr, *size);
849 }
850 
851 static void
852 kpm_init()
853 {
854 	struct segkpm_crargs b;
855 
856 	/*
857 	 * These variables were all designed for sfmmu in which segkpm is
858 	 * mapped using a single pagesize - either 8KB or 4MB.  On x86, we
859 	 * might use 2+ page sizes on a single machine, so none of these
860 	 * variables have a single correct value.  They are set up as if we
861 	 * always use a 4KB pagesize, which should do no harm.  In the long
862 	 * run, we should get rid of KPM's assumption that only a single
863 	 * pagesize is used.
864 	 */
865 	kpm_pgshft = MMU_PAGESHIFT;
866 	kpm_pgsz =  MMU_PAGESIZE;
867 	kpm_pgoff = MMU_PAGEOFFSET;
868 	kpmp2pshft = 0;
869 	kpmpnpgs = 1;
870 	ASSERT(((uintptr_t)kpm_vbase & (kpm_pgsz - 1)) == 0);
871 
872 	PRM_POINT("about to create segkpm");
873 	rw_enter(&kas.a_lock, RW_WRITER);
874 
875 	if (seg_attach(&kas, kpm_vbase, kpm_size, segkpm) < 0)
876 		panic("cannot attach segkpm");
877 
878 	b.prot = PROT_READ | PROT_WRITE;
879 	b.nvcolors = 1;
880 
881 	if (segkpm_create(segkpm, (caddr_t)&b) != 0)
882 		panic("segkpm_create segkpm");
883 
884 	rw_exit(&kas.a_lock);
885 }
886 
887 /*
888  * The debug info page provides enough information to allow external
889  * inspectors (e.g. when running under a hypervisor) to bootstrap
890  * themselves into allowing full-blown kernel debugging.
891  */
892 static void
893 init_debug_info(void)
894 {
895 	caddr_t mem;
896 	debug_info_t *di;
897 
898 #ifndef __lint
899 	ASSERT(sizeof (debug_info_t) < MMU_PAGESIZE);
900 #endif
901 
902 	mem = BOP_ALLOC(bootops, (caddr_t)DEBUG_INFO_VA, MMU_PAGESIZE,
903 	    MMU_PAGESIZE);
904 
905 	if (mem != (caddr_t)DEBUG_INFO_VA)
906 		panic("BOP_ALLOC() failed");
907 	bzero(mem, MMU_PAGESIZE);
908 
909 	di = (debug_info_t *)mem;
910 
911 	di->di_magic = DEBUG_INFO_MAGIC;
912 	di->di_version = DEBUG_INFO_VERSION;
913 	di->di_modules = (uintptr_t)&modules;
914 	di->di_s_text = (uintptr_t)s_text;
915 	di->di_e_text = (uintptr_t)e_text;
916 	di->di_s_data = (uintptr_t)s_data;
917 	di->di_e_data = (uintptr_t)e_data;
918 	di->di_hat_htable_off = offsetof(hat_t, hat_htable);
919 	di->di_ht_pfn_off = offsetof(htable_t, ht_pfn);
920 }
921 
922 /*
923  * Build the memlists and other kernel essential memory system data structures.
924  * This is everything at valloc_base.
925  */
926 static void
927 startup_memlist(void)
928 {
929 	size_t memlist_sz;
930 	size_t memseg_sz;
931 	size_t pagehash_sz;
932 	size_t pp_sz;
933 	uintptr_t va;
934 	size_t len;
935 	uint_t prot;
936 	pfn_t pfn;
937 	int memblocks;
938 	pfn_t rsvd_high_pfn;
939 	pgcnt_t rsvd_pgcnt;
940 	size_t rsvdmemlist_sz;
941 	int rsvdmemblocks;
942 	caddr_t pagecolor_mem;
943 	size_t pagecolor_memsz;
944 	caddr_t page_ctrs_mem;
945 	size_t page_ctrs_size;
946 	size_t pse_table_alloc_size;
947 	struct memlist *current;
948 	extern void startup_build_mem_nodes(struct memlist *);
949 
950 	/* XX64 fix these - they should be in include files */
951 	extern size_t page_coloring_init(uint_t, int, int);
952 	extern void page_coloring_setup(caddr_t);
953 
954 	PRM_POINT("startup_memlist() starting...");
955 
956 	/*
957 	 * Use leftover large page nucleus text/data space for loadable modules.
958 	 * Use at most MODTEXT/MODDATA.
959 	 */
960 	len = kbm_nucleus_size;
961 	ASSERT(len > MMU_PAGESIZE);
962 
963 	moddata = (caddr_t)ROUND_UP_PAGE(e_data);
964 	e_moddata = (caddr_t)P2ROUNDUP((uintptr_t)e_data, (uintptr_t)len);
965 	if (e_moddata - moddata > MODDATA)
966 		e_moddata = moddata + MODDATA;
967 
968 	modtext = (caddr_t)ROUND_UP_PAGE(e_text);
969 	e_modtext = (caddr_t)P2ROUNDUP((uintptr_t)e_text, (uintptr_t)len);
970 	if (e_modtext - modtext > MODTEXT)
971 		e_modtext = modtext + MODTEXT;
972 
973 	econtig = e_moddata;
974 
975 	PRM_DEBUG(modtext);
976 	PRM_DEBUG(e_modtext);
977 	PRM_DEBUG(moddata);
978 	PRM_DEBUG(e_moddata);
979 	PRM_DEBUG(econtig);
980 
981 	/*
982 	 * Examine the boot loader physical memory map to find out:
983 	 * - total memory in system - physinstalled
984 	 * - the max physical address - physmax
985 	 * - the number of discontiguous segments of memory.
986 	 */
987 	if (prom_debug)
988 		print_memlist("boot physinstalled",
989 		    bootops->boot_mem->physinstalled);
990 	installed_top_size_ex(bootops->boot_mem->physinstalled, &physmax,
991 	    &physinstalled, &memblocks);
992 	PRM_DEBUG(physmax);
993 	PRM_DEBUG(physinstalled);
994 	PRM_DEBUG(memblocks);
995 
996 	/*
997 	 * Compute maximum physical address for memory DR operations.
998 	 * Memory DR operations are unsupported on xpv or 32bit OSes.
999 	 */
1000 #ifdef	__amd64
1001 	if (plat_dr_support_memory()) {
1002 		if (plat_dr_physmax == 0) {
1003 			uint_t pabits = UINT_MAX;
1004 
1005 			cpuid_get_addrsize(CPU, &pabits, NULL);
1006 			plat_dr_physmax = btop(1ULL << pabits);
1007 		}
1008 		if (plat_dr_physmax > PHYSMEM_MAX64)
1009 			plat_dr_physmax = PHYSMEM_MAX64;
1010 	} else
1011 #endif
1012 		plat_dr_physmax = 0;
1013 
1014 	/*
1015 	 * Examine the bios reserved memory to find out:
1016 	 * - the number of discontiguous segments of memory.
1017 	 */
1018 	if (prom_debug)
1019 		print_memlist("boot reserved mem",
1020 		    bootops->boot_mem->rsvdmem);
1021 	installed_top_size_ex(bootops->boot_mem->rsvdmem, &rsvd_high_pfn,
1022 	    &rsvd_pgcnt, &rsvdmemblocks);
1023 	PRM_DEBUG(rsvd_high_pfn);
1024 	PRM_DEBUG(rsvd_pgcnt);
1025 	PRM_DEBUG(rsvdmemblocks);
1026 
1027 	/*
1028 	 * Initialize hat's mmu parameters.
1029 	 * Check for enforce-prot-exec in boot environment. It's used to
1030 	 * enable/disable support for the page table entry NX bit.
1031 	 * The default is to enforce PROT_EXEC on processors that support NX.
1032 	 * Boot seems to round up the "len", but 8 seems to be big enough.
1033 	 */
1034 	mmu_init();
1035 
1036 #ifdef	__i386
1037 	/*
1038 	 * physmax is lowered if there is more memory than can be
1039 	 * physically addressed in 32 bit (PAE/non-PAE) modes.
1040 	 */
1041 	if (mmu.pae_hat) {
1042 		if (PFN_ABOVE64G(physmax)) {
1043 			physinstalled -= (physmax - (PFN_64G - 1));
1044 			physmax = PFN_64G - 1;
1045 		}
1046 	} else {
1047 		if (PFN_ABOVE4G(physmax)) {
1048 			physinstalled -= (physmax - (PFN_4G - 1));
1049 			physmax = PFN_4G - 1;
1050 		}
1051 	}
1052 #endif
1053 
1054 	startup_build_mem_nodes(bootops->boot_mem->physinstalled);
1055 
1056 	if (BOP_GETPROPLEN(bootops, "enforce-prot-exec") >= 0) {
1057 		int len = BOP_GETPROPLEN(bootops, "enforce-prot-exec");
1058 		char value[8];
1059 
1060 		if (len < 8)
1061 			(void) BOP_GETPROP(bootops, "enforce-prot-exec", value);
1062 		else
1063 			(void) strcpy(value, "");
1064 		if (strcmp(value, "off") == 0)
1065 			mmu.pt_nx = 0;
1066 	}
1067 	PRM_DEBUG(mmu.pt_nx);
1068 
1069 	/*
1070 	 * We will need page_t's for every page in the system, except for
1071 	 * memory mapped at or above above the start of the kernel text segment.
1072 	 *
1073 	 * pages above e_modtext are attributed to kernel debugger (obp_pages)
1074 	 */
1075 	npages = physinstalled - 1; /* avail_filter() skips page 0, so "- 1" */
1076 	obp_pages = 0;
1077 	va = KERNEL_TEXT;
1078 	while (kbm_probe(&va, &len, &pfn, &prot) != 0) {
1079 		npages -= len >> MMU_PAGESHIFT;
1080 		if (va >= (uintptr_t)e_moddata)
1081 			obp_pages += len >> MMU_PAGESHIFT;
1082 		va += len;
1083 	}
1084 	PRM_DEBUG(npages);
1085 	PRM_DEBUG(obp_pages);
1086 
1087 	/*
1088 	 * If physmem is patched to be non-zero, use it instead of the computed
1089 	 * value unless it is larger than the actual amount of memory on hand.
1090 	 */
1091 	if (physmem == 0 || physmem > npages) {
1092 		physmem = npages;
1093 	} else if (physmem < npages) {
1094 		orig_npages = npages;
1095 		npages = physmem;
1096 	}
1097 	PRM_DEBUG(physmem);
1098 
1099 	/*
1100 	 * We now compute the sizes of all the  initial allocations for
1101 	 * structures the kernel needs in order do kmem_alloc(). These
1102 	 * include:
1103 	 *	memsegs
1104 	 *	memlists
1105 	 *	page hash table
1106 	 *	page_t's
1107 	 *	page coloring data structs
1108 	 */
1109 	memseg_sz = sizeof (struct memseg) * (memblocks + POSS_NEW_FRAGMENTS);
1110 	ADD_TO_ALLOCATIONS(memseg_base, memseg_sz);
1111 	PRM_DEBUG(memseg_sz);
1112 
1113 	/*
1114 	 * Reserve space for memlists. There's no real good way to know exactly
1115 	 * how much room we'll need, but this should be a good upper bound.
1116 	 */
1117 	memlist_sz = ROUND_UP_PAGE(2 * sizeof (struct memlist) *
1118 	    (memblocks + POSS_NEW_FRAGMENTS));
1119 	ADD_TO_ALLOCATIONS(memlist, memlist_sz);
1120 	PRM_DEBUG(memlist_sz);
1121 
1122 	/*
1123 	 * Reserve space for bios reserved memlists.
1124 	 */
1125 	rsvdmemlist_sz = ROUND_UP_PAGE(2 * sizeof (struct memlist) *
1126 	    (rsvdmemblocks + POSS_NEW_FRAGMENTS));
1127 	ADD_TO_ALLOCATIONS(bios_rsvd, rsvdmemlist_sz);
1128 	PRM_DEBUG(rsvdmemlist_sz);
1129 
1130 	/* LINTED */
1131 	ASSERT(P2SAMEHIGHBIT((1 << PP_SHIFT), sizeof (struct page)));
1132 	/*
1133 	 * The page structure hash table size is a power of 2
1134 	 * such that the average hash chain length is PAGE_HASHAVELEN.
1135 	 */
1136 	page_hashsz = npages / PAGE_HASHAVELEN;
1137 	page_hashsz_shift = highbit(page_hashsz);
1138 	page_hashsz = 1 << page_hashsz_shift;
1139 	pagehash_sz = sizeof (struct page *) * page_hashsz;
1140 	ADD_TO_ALLOCATIONS(page_hash, pagehash_sz);
1141 	PRM_DEBUG(pagehash_sz);
1142 
1143 	/*
1144 	 * Set aside room for the page structures themselves.
1145 	 */
1146 	PRM_DEBUG(npages);
1147 	pp_sz = sizeof (struct page) * npages;
1148 	ADD_TO_ALLOCATIONS(pp_base, pp_sz);
1149 	PRM_DEBUG(pp_sz);
1150 
1151 	/*
1152 	 * determine l2 cache info and memory size for page coloring
1153 	 */
1154 	(void) getl2cacheinfo(CPU,
1155 	    &l2cache_sz, &l2cache_linesz, &l2cache_assoc);
1156 	pagecolor_memsz =
1157 	    page_coloring_init(l2cache_sz, l2cache_linesz, l2cache_assoc);
1158 	ADD_TO_ALLOCATIONS(pagecolor_mem, pagecolor_memsz);
1159 	PRM_DEBUG(pagecolor_memsz);
1160 
1161 	page_ctrs_size = page_ctrs_sz();
1162 	ADD_TO_ALLOCATIONS(page_ctrs_mem, page_ctrs_size);
1163 	PRM_DEBUG(page_ctrs_size);
1164 
1165 	/*
1166 	 * Allocate the array that protects pp->p_selock.
1167 	 */
1168 	pse_shift = size_pse_array(physmem, max_ncpus);
1169 	pse_table_size = 1 << pse_shift;
1170 	pse_table_alloc_size = pse_table_size * sizeof (pad_mutex_t);
1171 	ADD_TO_ALLOCATIONS(pse_mutex, pse_table_alloc_size);
1172 
1173 #if defined(__amd64)
1174 	valloc_sz = ROUND_UP_LPAGE(valloc_sz);
1175 	valloc_base = VALLOC_BASE;
1176 
1177 	/*
1178 	 * The default values of VALLOC_BASE and SEGKPM_BASE should work
1179 	 * for values of physmax up to 1 Terabyte. They need adjusting when
1180 	 * memory is at addresses above 1 TB. When adjusted, segkpm_base must
1181 	 * be aligned on KERNEL_REDZONE_SIZE boundary (span of top level pte).
1182 	 */
1183 	if (physmax + 1 > mmu_btop(TERABYTE) ||
1184 	    plat_dr_physmax > mmu_btop(TERABYTE)) {
1185 		uint64_t kpm_resv_amount = mmu_ptob(physmax + 1);
1186 
1187 		if (kpm_resv_amount < mmu_ptob(plat_dr_physmax)) {
1188 			kpm_resv_amount = mmu_ptob(plat_dr_physmax);
1189 		}
1190 
1191 		segkpm_base = -(P2ROUNDUP((2 * kpm_resv_amount),
1192 		    KERNEL_REDZONE_SIZE));	/* down from top VA */
1193 
1194 		/* make sure we leave some space for user apps above hole */
1195 		segkpm_base = MAX(segkpm_base, AMD64_VA_HOLE_END + TERABYTE);
1196 		if (segkpm_base > SEGKPM_BASE)
1197 			segkpm_base = SEGKPM_BASE;
1198 		PRM_DEBUG(segkpm_base);
1199 
1200 		valloc_base = segkpm_base + P2ROUNDUP(kpm_resv_amount, ONE_GIG);
1201 		if (valloc_base < segkpm_base)
1202 			panic("not enough kernel VA to support memory size");
1203 		PRM_DEBUG(valloc_base);
1204 	}
1205 #else	/* __i386 */
1206 	valloc_base = (uintptr_t)(MISC_VA_BASE - valloc_sz);
1207 	valloc_base = P2ALIGN(valloc_base, mmu.level_size[1]);
1208 	PRM_DEBUG(valloc_base);
1209 #endif	/* __i386 */
1210 
1211 	/*
1212 	 * do all the initial allocations
1213 	 */
1214 	perform_allocations();
1215 
1216 	/*
1217 	 * Build phys_install and phys_avail in kernel memspace.
1218 	 * - phys_install should be all memory in the system.
1219 	 * - phys_avail is phys_install minus any memory mapped before this
1220 	 *    point above KERNEL_TEXT.
1221 	 */
1222 	current = phys_install = memlist;
1223 	copy_memlist_filter(bootops->boot_mem->physinstalled, &current, NULL);
1224 	if ((caddr_t)current > (caddr_t)memlist + memlist_sz)
1225 		panic("physinstalled was too big!");
1226 	if (prom_debug)
1227 		print_memlist("phys_install", phys_install);
1228 
1229 	phys_avail = current;
1230 	PRM_POINT("Building phys_avail:\n");
1231 	copy_memlist_filter(bootops->boot_mem->physinstalled, &current,
1232 	    avail_filter);
1233 	if ((caddr_t)current > (caddr_t)memlist + memlist_sz)
1234 		panic("physavail was too big!");
1235 	if (prom_debug)
1236 		print_memlist("phys_avail", phys_avail);
1237 #ifndef	__xpv
1238 	/*
1239 	 * Free unused memlist items, which may be used by memory DR driver
1240 	 * at runtime.
1241 	 */
1242 	if ((caddr_t)current < (caddr_t)memlist + memlist_sz) {
1243 		memlist_free_block((caddr_t)current,
1244 		    (caddr_t)memlist + memlist_sz - (caddr_t)current);
1245 	}
1246 #endif
1247 
1248 	/*
1249 	 * Build bios reserved memspace
1250 	 */
1251 	current = bios_rsvd;
1252 	copy_memlist_filter(bootops->boot_mem->rsvdmem, &current, NULL);
1253 	if ((caddr_t)current > (caddr_t)bios_rsvd + rsvdmemlist_sz)
1254 		panic("bios_rsvd was too big!");
1255 	if (prom_debug)
1256 		print_memlist("bios_rsvd", bios_rsvd);
1257 #ifndef	__xpv
1258 	/*
1259 	 * Free unused memlist items, which may be used by memory DR driver
1260 	 * at runtime.
1261 	 */
1262 	if ((caddr_t)current < (caddr_t)bios_rsvd + rsvdmemlist_sz) {
1263 		memlist_free_block((caddr_t)current,
1264 		    (caddr_t)bios_rsvd + rsvdmemlist_sz - (caddr_t)current);
1265 	}
1266 #endif
1267 
1268 	/*
1269 	 * setup page coloring
1270 	 */
1271 	page_coloring_setup(pagecolor_mem);
1272 	page_lock_init();	/* currently a no-op */
1273 
1274 	/*
1275 	 * free page list counters
1276 	 */
1277 	(void) page_ctrs_alloc(page_ctrs_mem);
1278 
1279 	/*
1280 	 * Size the pcf array based on the number of cpus in the box at
1281 	 * boot time.
1282 	 */
1283 
1284 	pcf_init();
1285 
1286 	/*
1287 	 * Initialize the page structures from the memory lists.
1288 	 */
1289 	availrmem_initial = availrmem = freemem = 0;
1290 	PRM_POINT("Calling kphysm_init()...");
1291 	npages = kphysm_init(pp_base, npages);
1292 	PRM_POINT("kphysm_init() done");
1293 	PRM_DEBUG(npages);
1294 
1295 	init_debug_info();
1296 
1297 	/*
1298 	 * Now that page_t's have been initialized, remove all the
1299 	 * initial allocation pages from the kernel free page lists.
1300 	 */
1301 	boot_mapin((caddr_t)valloc_base, valloc_sz);
1302 	boot_mapin((caddr_t)MISC_VA_BASE, MISC_VA_SIZE);
1303 	PRM_POINT("startup_memlist() done");
1304 
1305 	PRM_DEBUG(valloc_sz);
1306 
1307 #if defined(__amd64)
1308 	if ((availrmem >> (30 - MMU_PAGESHIFT)) >=
1309 	    textrepl_min_gb && l2cache_sz <= 2 << 20) {
1310 		extern size_t textrepl_size_thresh;
1311 		textrepl_size_thresh = (16 << 20) - 1;
1312 	}
1313 #endif
1314 }
1315 
1316 /*
1317  * Layout the kernel's part of address space and initialize kmem allocator.
1318  */
1319 static void
1320 startup_kmem(void)
1321 {
1322 	extern void page_set_colorequiv_arr(void);
1323 	const char *fmt = "?features: %b\n";
1324 
1325 	PRM_POINT("startup_kmem() starting...");
1326 
1327 #if defined(__amd64)
1328 	if (eprom_kernelbase && eprom_kernelbase != KERNELBASE)
1329 		cmn_err(CE_NOTE, "!kernelbase cannot be changed on 64-bit "
1330 		    "systems.");
1331 	kernelbase = segkpm_base - KERNEL_REDZONE_SIZE;
1332 	core_base = (uintptr_t)COREHEAP_BASE;
1333 	core_size = (size_t)MISC_VA_BASE - COREHEAP_BASE;
1334 #else	/* __i386 */
1335 	/*
1336 	 * We configure kernelbase based on:
1337 	 *
1338 	 * 1. user specified kernelbase via eeprom command. Value cannot exceed
1339 	 *    KERNELBASE_MAX. we large page align eprom_kernelbase
1340 	 *
1341 	 * 2. Default to KERNELBASE and adjust to 2X less the size for page_t.
1342 	 *    On large memory systems we must lower kernelbase to allow
1343 	 *    enough room for page_t's for all of memory.
1344 	 *
1345 	 * The value set here, might be changed a little later.
1346 	 */
1347 	if (eprom_kernelbase) {
1348 		kernelbase = eprom_kernelbase & mmu.level_mask[1];
1349 		if (kernelbase > KERNELBASE_MAX)
1350 			kernelbase = KERNELBASE_MAX;
1351 	} else {
1352 		kernelbase = (uintptr_t)KERNELBASE;
1353 		kernelbase -= ROUND_UP_4MEG(2 * valloc_sz);
1354 	}
1355 	ASSERT((kernelbase & mmu.level_offset[1]) == 0);
1356 	core_base = valloc_base;
1357 	core_size = 0;
1358 #endif	/* __i386 */
1359 
1360 	PRM_DEBUG(core_base);
1361 	PRM_DEBUG(core_size);
1362 	PRM_DEBUG(kernelbase);
1363 
1364 #if defined(__i386)
1365 	segkp_fromheap = 1;
1366 #endif	/* __i386 */
1367 
1368 	ekernelheap = (char *)core_base;
1369 	PRM_DEBUG(ekernelheap);
1370 
1371 	/*
1372 	 * Now that we know the real value of kernelbase,
1373 	 * update variables that were initialized with a value of
1374 	 * KERNELBASE (in common/conf/param.c).
1375 	 *
1376 	 * XXX	The problem with this sort of hackery is that the
1377 	 *	compiler just may feel like putting the const declarations
1378 	 *	(in param.c) into the .text section.  Perhaps they should
1379 	 *	just be declared as variables there?
1380 	 */
1381 
1382 	*(uintptr_t *)&_kernelbase = kernelbase;
1383 	*(uintptr_t *)&_userlimit = kernelbase;
1384 #if defined(__amd64)
1385 	*(uintptr_t *)&_userlimit -= KERNELBASE - USERLIMIT;
1386 #else
1387 	*(uintptr_t *)&_userlimit32 = _userlimit;
1388 #endif
1389 	PRM_DEBUG(_kernelbase);
1390 	PRM_DEBUG(_userlimit);
1391 	PRM_DEBUG(_userlimit32);
1392 
1393 	layout_kernel_va();
1394 
1395 #if defined(__i386)
1396 	/*
1397 	 * If segmap is too large we can push the bottom of the kernel heap
1398 	 * higher than the base.  Or worse, it could exceed the top of the
1399 	 * VA space entirely, causing it to wrap around.
1400 	 */
1401 	if (kernelheap >= ekernelheap || (uintptr_t)kernelheap < kernelbase)
1402 		panic("too little address space available for kernelheap,"
1403 		    " use eeprom for lower kernelbase or smaller segmapsize");
1404 #endif	/* __i386 */
1405 
1406 	/*
1407 	 * Initialize the kernel heap. Note 3rd argument must be > 1st.
1408 	 */
1409 	kernelheap_init(kernelheap, ekernelheap,
1410 	    kernelheap + MMU_PAGESIZE,
1411 	    (void *)core_base, (void *)(core_base + core_size));
1412 
1413 #if defined(__xpv)
1414 	/*
1415 	 * Link pending events struct into cpu struct
1416 	 */
1417 	CPU->cpu_m.mcpu_evt_pend = &cpu0_evt_data;
1418 #endif
1419 	/*
1420 	 * Initialize kernel memory allocator.
1421 	 */
1422 	kmem_init();
1423 
1424 	/*
1425 	 * Factor in colorequiv to check additional 'equivalent' bins
1426 	 */
1427 	page_set_colorequiv_arr();
1428 
1429 	/*
1430 	 * print this out early so that we know what's going on
1431 	 */
1432 	cmn_err(CE_CONT, fmt, x86_feature, FMT_X86_FEATURE);
1433 
1434 	/*
1435 	 * Initialize bp_mapin().
1436 	 */
1437 	bp_init(MMU_PAGESIZE, HAT_STORECACHING_OK);
1438 
1439 	/*
1440 	 * orig_npages is non-zero if physmem has been configured for less
1441 	 * than the available memory.
1442 	 */
1443 	if (orig_npages) {
1444 		cmn_err(CE_WARN, "!%slimiting physmem to 0x%lx of 0x%lx pages",
1445 		    (npages == PHYSMEM ? "Due to virtual address space " : ""),
1446 		    npages, orig_npages);
1447 	}
1448 #if defined(__i386)
1449 	if (eprom_kernelbase && (eprom_kernelbase != kernelbase))
1450 		cmn_err(CE_WARN, "kernelbase value, User specified 0x%lx, "
1451 		    "System using 0x%lx",
1452 		    (uintptr_t)eprom_kernelbase, (uintptr_t)kernelbase);
1453 #endif
1454 
1455 #ifdef	KERNELBASE_ABI_MIN
1456 	if (kernelbase < (uintptr_t)KERNELBASE_ABI_MIN) {
1457 		cmn_err(CE_NOTE, "!kernelbase set to 0x%lx, system is not "
1458 		    "i386 ABI compliant.", (uintptr_t)kernelbase);
1459 	}
1460 #endif
1461 
1462 #ifndef __xpv
1463 	if (plat_dr_support_memory()) {
1464 		mem_config_init();
1465 	}
1466 #else	/* __xpv */
1467 	/*
1468 	 * Some of the xen start information has to be relocated up
1469 	 * into the kernel's permanent address space.
1470 	 */
1471 	PRM_POINT("calling xen_relocate_start_info()");
1472 	xen_relocate_start_info();
1473 	PRM_POINT("xen_relocate_start_info() done");
1474 
1475 	/*
1476 	 * (Update the vcpu pointer in our cpu structure to point into
1477 	 * the relocated shared info.)
1478 	 */
1479 	CPU->cpu_m.mcpu_vcpu_info =
1480 	    &HYPERVISOR_shared_info->vcpu_info[CPU->cpu_id];
1481 #endif	/* __xpv */
1482 
1483 	PRM_POINT("startup_kmem() done");
1484 }
1485 
1486 #ifndef __xpv
1487 /*
1488  * If we have detected that we are running in an HVM environment, we need
1489  * to prepend the PV driver directory to the module search path.
1490  */
1491 #define	HVM_MOD_DIR "/platform/i86hvm/kernel"
1492 static void
1493 update_default_path()
1494 {
1495 	char *current, *newpath;
1496 	int newlen;
1497 
1498 	/*
1499 	 * We are about to resync with krtld.  krtld will reset its
1500 	 * internal module search path iff Solaris has set default_path.
1501 	 * We want to be sure we're prepending this new directory to the
1502 	 * right search path.
1503 	 */
1504 	current = (default_path == NULL) ? kobj_module_path : default_path;
1505 
1506 	newlen = strlen(HVM_MOD_DIR) + strlen(current) + 2;
1507 	newpath = kmem_alloc(newlen, KM_SLEEP);
1508 	(void) strcpy(newpath, HVM_MOD_DIR);
1509 	(void) strcat(newpath, " ");
1510 	(void) strcat(newpath, current);
1511 
1512 	default_path = newpath;
1513 }
1514 #endif
1515 
1516 static void
1517 startup_modules(void)
1518 {
1519 	int cnt;
1520 	extern void prom_setup(void);
1521 	int32_t v, h;
1522 	char d[11];
1523 	char *cp;
1524 	cmi_hdl_t hdl;
1525 
1526 	PRM_POINT("startup_modules() starting...");
1527 
1528 #ifndef __xpv
1529 	/*
1530 	 * Initialize ten-micro second timer so that drivers will
1531 	 * not get short changed in their init phase. This was
1532 	 * not getting called until clkinit which, on fast cpu's
1533 	 * caused the drv_usecwait to be way too short.
1534 	 */
1535 	microfind();
1536 
1537 	if (get_hwenv() == HW_XEN_HVM)
1538 		update_default_path();
1539 #endif
1540 
1541 	/*
1542 	 * Read the GMT lag from /etc/rtc_config.
1543 	 */
1544 	sgmtl(process_rtc_config_file());
1545 
1546 	/*
1547 	 * Calculate default settings of system parameters based upon
1548 	 * maxusers, yet allow to be overridden via the /etc/system file.
1549 	 */
1550 	param_calc(0);
1551 
1552 	mod_setup();
1553 
1554 	/*
1555 	 * Initialize system parameters.
1556 	 */
1557 	param_init();
1558 
1559 	/*
1560 	 * Initialize the default brands
1561 	 */
1562 	brand_init();
1563 
1564 	/*
1565 	 * maxmem is the amount of physical memory we're playing with.
1566 	 */
1567 	maxmem = physmem;
1568 
1569 	/*
1570 	 * Initialize segment management stuff.
1571 	 */
1572 	seg_init();
1573 
1574 	if (modload("fs", "specfs") == -1)
1575 		halt("Can't load specfs");
1576 
1577 	if (modload("fs", "devfs") == -1)
1578 		halt("Can't load devfs");
1579 
1580 	if (modload("fs", "dev") == -1)
1581 		halt("Can't load dev");
1582 
1583 	if (modload("fs", "procfs") == -1)
1584 		halt("Can't load procfs");
1585 
1586 	(void) modloadonly("sys", "lbl_edition");
1587 
1588 	dispinit();
1589 
1590 	/*
1591 	 * This is needed here to initialize hw_serial[] for cluster booting.
1592 	 */
1593 	if ((h = set_soft_hostid()) == HW_INVALID_HOSTID) {
1594 		cmn_err(CE_WARN, "Unable to set hostid");
1595 	} else {
1596 		for (v = h, cnt = 0; cnt < 10; cnt++) {
1597 			d[cnt] = (char)(v % 10);
1598 			v /= 10;
1599 			if (v == 0)
1600 				break;
1601 		}
1602 		for (cp = hw_serial; cnt >= 0; cnt--)
1603 			*cp++ = d[cnt] + '0';
1604 		*cp = 0;
1605 	}
1606 
1607 	/* Read cluster configuration data. */
1608 	clconf_init();
1609 
1610 #if defined(__xpv)
1611 	(void) ec_init();
1612 	gnttab_init();
1613 	(void) xs_early_init();
1614 #endif /* __xpv */
1615 
1616 	/*
1617 	 * Create a kernel device tree. First, create rootnex and
1618 	 * then invoke bus specific code to probe devices.
1619 	 */
1620 	setup_ddi();
1621 
1622 #ifdef __xpv
1623 	if (DOMAIN_IS_INITDOMAIN(xen_info))
1624 #endif
1625 	{
1626 		/*
1627 		 * Load the System Management BIOS into the global ksmbios
1628 		 * handle, if an SMBIOS is present on this system.
1629 		 */
1630 		ksmbios = smbios_open(NULL, SMB_VERSION, ksmbios_flags, NULL);
1631 	}
1632 
1633 
1634 	/*
1635 	 * Set up the CPU module subsystem for the boot cpu in the native
1636 	 * case, and all physical cpu resource in the xpv dom0 case.
1637 	 * Modifies the device tree, so this must be done after
1638 	 * setup_ddi().
1639 	 */
1640 #ifdef __xpv
1641 	/*
1642 	 * If paravirtualized and on dom0 then we initialize all physical
1643 	 * cpu handles now;  if paravirtualized on a domU then do not
1644 	 * initialize.
1645 	 */
1646 	if (DOMAIN_IS_INITDOMAIN(xen_info)) {
1647 		xen_mc_lcpu_cookie_t cpi;
1648 
1649 		for (cpi = xen_physcpu_next(NULL); cpi != NULL;
1650 		    cpi = xen_physcpu_next(cpi)) {
1651 			if ((hdl = cmi_init(CMI_HDL_SOLARIS_xVM_MCA,
1652 			    xen_physcpu_chipid(cpi), xen_physcpu_coreid(cpi),
1653 			    xen_physcpu_strandid(cpi))) != NULL &&
1654 			    (x86_feature & X86_MCA))
1655 				cmi_mca_init(hdl);
1656 		}
1657 	}
1658 #else
1659 	/*
1660 	 * Initialize a handle for the boot cpu - others will initialize
1661 	 * as they startup.  Do not do this if we know we are in an HVM domU.
1662 	 */
1663 	if ((get_hwenv() != HW_XEN_HVM) &&
1664 	    (hdl = cmi_init(CMI_HDL_NATIVE, cmi_ntv_hwchipid(CPU),
1665 	    cmi_ntv_hwcoreid(CPU), cmi_ntv_hwstrandid(CPU))) != NULL &&
1666 	    (x86_feature & X86_MCA)) {
1667 			cmi_mca_init(hdl);
1668 			CPU->cpu_m.mcpu_cmi_hdl = hdl;
1669 	}
1670 #endif	/* __xpv */
1671 
1672 	/*
1673 	 * Fake a prom tree such that /dev/openprom continues to work
1674 	 */
1675 	PRM_POINT("startup_modules: calling prom_setup...");
1676 	prom_setup();
1677 	PRM_POINT("startup_modules: done");
1678 
1679 	/*
1680 	 * Load all platform specific modules
1681 	 */
1682 	PRM_POINT("startup_modules: calling psm_modload...");
1683 	psm_modload();
1684 
1685 	PRM_POINT("startup_modules() done");
1686 }
1687 
1688 /*
1689  * claim a "setaside" boot page for use in the kernel
1690  */
1691 page_t *
1692 boot_claim_page(pfn_t pfn)
1693 {
1694 	page_t *pp;
1695 
1696 	pp = page_numtopp_nolock(pfn);
1697 	ASSERT(pp != NULL);
1698 
1699 	if (PP_ISBOOTPAGES(pp)) {
1700 		if (pp->p_next != NULL)
1701 			pp->p_next->p_prev = pp->p_prev;
1702 		if (pp->p_prev == NULL)
1703 			bootpages = pp->p_next;
1704 		else
1705 			pp->p_prev->p_next = pp->p_next;
1706 	} else {
1707 		/*
1708 		 * htable_attach() expects a base pagesize page
1709 		 */
1710 		if (pp->p_szc != 0)
1711 			page_boot_demote(pp);
1712 		pp = page_numtopp(pfn, SE_EXCL);
1713 	}
1714 	return (pp);
1715 }
1716 
1717 /*
1718  * Walk through the pagetables looking for pages mapped in by boot.  If the
1719  * setaside flag is set the pages are expected to be returned to the
1720  * kernel later in boot, so we add them to the bootpages list.
1721  */
1722 static void
1723 protect_boot_range(uintptr_t low, uintptr_t high, int setaside)
1724 {
1725 	uintptr_t va = low;
1726 	size_t len;
1727 	uint_t prot;
1728 	pfn_t pfn;
1729 	page_t *pp;
1730 	pgcnt_t boot_protect_cnt = 0;
1731 
1732 	while (kbm_probe(&va, &len, &pfn, &prot) != 0 && va < high) {
1733 		if (va + len >= high)
1734 			panic("0x%lx byte mapping at 0x%p exceeds boot's "
1735 			    "legal range.", len, (void *)va);
1736 
1737 		while (len > 0) {
1738 			pp = page_numtopp_alloc(pfn);
1739 			if (pp != NULL) {
1740 				if (setaside == 0)
1741 					panic("Unexpected mapping by boot.  "
1742 					    "addr=%p pfn=%lx\n",
1743 					    (void *)va, pfn);
1744 
1745 				pp->p_next = bootpages;
1746 				pp->p_prev = NULL;
1747 				PP_SETBOOTPAGES(pp);
1748 				if (bootpages != NULL) {
1749 					bootpages->p_prev = pp;
1750 				}
1751 				bootpages = pp;
1752 				++boot_protect_cnt;
1753 			}
1754 
1755 			++pfn;
1756 			len -= MMU_PAGESIZE;
1757 			va += MMU_PAGESIZE;
1758 		}
1759 	}
1760 	PRM_DEBUG(boot_protect_cnt);
1761 }
1762 
1763 /*
1764  *
1765  */
1766 static void
1767 layout_kernel_va(void)
1768 {
1769 	PRM_POINT("layout_kernel_va() starting...");
1770 	/*
1771 	 * Establish the final size of the kernel's heap, size of segmap,
1772 	 * segkp, etc.
1773 	 */
1774 
1775 #if defined(__amd64)
1776 
1777 	kpm_vbase = (caddr_t)segkpm_base;
1778 	if (physmax + 1 < plat_dr_physmax) {
1779 		kpm_size = ROUND_UP_LPAGE(mmu_ptob(plat_dr_physmax));
1780 	} else {
1781 		kpm_size = ROUND_UP_LPAGE(mmu_ptob(physmax + 1));
1782 	}
1783 	if ((uintptr_t)kpm_vbase + kpm_size > (uintptr_t)valloc_base)
1784 		panic("not enough room for kpm!");
1785 	PRM_DEBUG(kpm_size);
1786 	PRM_DEBUG(kpm_vbase);
1787 
1788 	/*
1789 	 * By default we create a seg_kp in 64 bit kernels, it's a little
1790 	 * faster to access than embedding it in the heap.
1791 	 */
1792 	segkp_base = (caddr_t)valloc_base + valloc_sz;
1793 	if (!segkp_fromheap) {
1794 		size_t sz = mmu_ptob(segkpsize);
1795 
1796 		/*
1797 		 * determine size of segkp
1798 		 */
1799 		if (sz < SEGKPMINSIZE || sz > SEGKPMAXSIZE) {
1800 			sz = SEGKPDEFSIZE;
1801 			cmn_err(CE_WARN, "!Illegal value for segkpsize. "
1802 			    "segkpsize has been reset to %ld pages",
1803 			    mmu_btop(sz));
1804 		}
1805 		sz = MIN(sz, MAX(SEGKPMINSIZE, mmu_ptob(physmem)));
1806 
1807 		segkpsize = mmu_btop(ROUND_UP_LPAGE(sz));
1808 	}
1809 	PRM_DEBUG(segkp_base);
1810 	PRM_DEBUG(segkpsize);
1811 
1812 	/*
1813 	 * segzio is used for ZFS cached data. It uses a distinct VA
1814 	 * segment (from kernel heap) so that we can easily tell not to
1815 	 * include it in kernel crash dumps on 64 bit kernels. The trick is
1816 	 * to give it lots of VA, but not constrain the kernel heap.
1817 	 * We scale the size of segzio linearly with physmem up to
1818 	 * SEGZIOMAXSIZE. Above that amount it scales at 50% of physmem.
1819 	 */
1820 	segzio_base = segkp_base + mmu_ptob(segkpsize);
1821 	if (segzio_fromheap) {
1822 		segziosize = 0;
1823 	} else {
1824 		size_t physmem_size = mmu_ptob(physmem);
1825 		size_t size = (segziosize == 0) ?
1826 		    physmem_size : mmu_ptob(segziosize);
1827 
1828 		if (size < SEGZIOMINSIZE)
1829 			size = SEGZIOMINSIZE;
1830 		if (size > SEGZIOMAXSIZE) {
1831 			size = SEGZIOMAXSIZE;
1832 			if (physmem_size > size)
1833 				size += (physmem_size - size) / 2;
1834 		}
1835 		segziosize = mmu_btop(ROUND_UP_LPAGE(size));
1836 	}
1837 	PRM_DEBUG(segziosize);
1838 	PRM_DEBUG(segzio_base);
1839 
1840 	/*
1841 	 * Put the range of VA for device mappings next, kmdb knows to not
1842 	 * grep in this range of addresses.
1843 	 */
1844 	toxic_addr =
1845 	    ROUND_UP_LPAGE((uintptr_t)segzio_base + mmu_ptob(segziosize));
1846 	PRM_DEBUG(toxic_addr);
1847 	segmap_start = ROUND_UP_LPAGE(toxic_addr + toxic_size);
1848 #else /* __i386 */
1849 	segmap_start = ROUND_UP_LPAGE(kernelbase);
1850 #endif /* __i386 */
1851 	PRM_DEBUG(segmap_start);
1852 
1853 	/*
1854 	 * Users can change segmapsize through eeprom. If the variable
1855 	 * is tuned through eeprom, there is no upper bound on the
1856 	 * size of segmap.
1857 	 */
1858 	segmapsize = MAX(ROUND_UP_LPAGE(segmapsize), SEGMAPDEFAULT);
1859 
1860 #if defined(__i386)
1861 	/*
1862 	 * 32-bit systems don't have segkpm or segkp, so segmap appears at
1863 	 * the bottom of the kernel's address range.  Set aside space for a
1864 	 * small red zone just below the start of segmap.
1865 	 */
1866 	segmap_start += KERNEL_REDZONE_SIZE;
1867 	segmapsize -= KERNEL_REDZONE_SIZE;
1868 #endif
1869 
1870 	PRM_DEBUG(segmap_start);
1871 	PRM_DEBUG(segmapsize);
1872 	kernelheap = (caddr_t)ROUND_UP_LPAGE(segmap_start + segmapsize);
1873 	PRM_DEBUG(kernelheap);
1874 	PRM_POINT("layout_kernel_va() done...");
1875 }
1876 
1877 /*
1878  * Finish initializing the VM system, now that we are no longer
1879  * relying on the boot time memory allocators.
1880  */
1881 static void
1882 startup_vm(void)
1883 {
1884 	struct segmap_crargs a;
1885 
1886 	extern int use_brk_lpg, use_stk_lpg;
1887 
1888 	PRM_POINT("startup_vm() starting...");
1889 
1890 	/*
1891 	 * Initialize the hat layer.
1892 	 */
1893 	hat_init();
1894 
1895 	/*
1896 	 * Do final allocations of HAT data structures that need to
1897 	 * be allocated before quiescing the boot loader.
1898 	 */
1899 	PRM_POINT("Calling hat_kern_alloc()...");
1900 	hat_kern_alloc((caddr_t)segmap_start, segmapsize, ekernelheap);
1901 	PRM_POINT("hat_kern_alloc() done");
1902 
1903 #ifndef __xpv
1904 	/*
1905 	 * Setup Page Attribute Table
1906 	 */
1907 	pat_sync();
1908 #endif
1909 
1910 	/*
1911 	 * The next two loops are done in distinct steps in order
1912 	 * to be sure that any page that is doubly mapped (both above
1913 	 * KERNEL_TEXT and below kernelbase) is dealt with correctly.
1914 	 * Note this may never happen, but it might someday.
1915 	 */
1916 	bootpages = NULL;
1917 	PRM_POINT("Protecting boot pages");
1918 
1919 	/*
1920 	 * Protect any pages mapped above KERNEL_TEXT that somehow have
1921 	 * page_t's. This can only happen if something weird allocated
1922 	 * in this range (like kadb/kmdb).
1923 	 */
1924 	protect_boot_range(KERNEL_TEXT, (uintptr_t)-1, 0);
1925 
1926 	/*
1927 	 * Before we can take over memory allocation/mapping from the boot
1928 	 * loader we must remove from our free page lists any boot allocated
1929 	 * pages that stay mapped until release_bootstrap().
1930 	 */
1931 	protect_boot_range(0, kernelbase, 1);
1932 
1933 
1934 	/*
1935 	 * Switch to running on regular HAT (not boot_mmu)
1936 	 */
1937 	PRM_POINT("Calling hat_kern_setup()...");
1938 	hat_kern_setup();
1939 
1940 	/*
1941 	 * It is no longer safe to call BOP_ALLOC(), so make sure we don't.
1942 	 */
1943 	bop_no_more_mem();
1944 
1945 	PRM_POINT("hat_kern_setup() done");
1946 
1947 	hat_cpu_online(CPU);
1948 
1949 	/*
1950 	 * Initialize VM system
1951 	 */
1952 	PRM_POINT("Calling kvm_init()...");
1953 	kvm_init();
1954 	PRM_POINT("kvm_init() done");
1955 
1956 	/*
1957 	 * Tell kmdb that the VM system is now working
1958 	 */
1959 	if (boothowto & RB_DEBUG)
1960 		kdi_dvec_vmready();
1961 
1962 #if defined(__xpv)
1963 	/*
1964 	 * Populate the I/O pool on domain 0
1965 	 */
1966 	if (DOMAIN_IS_INITDOMAIN(xen_info)) {
1967 		extern long populate_io_pool(void);
1968 		long init_io_pool_cnt;
1969 
1970 		PRM_POINT("Populating reserve I/O page pool");
1971 		init_io_pool_cnt = populate_io_pool();
1972 		PRM_DEBUG(init_io_pool_cnt);
1973 	}
1974 #endif
1975 	/*
1976 	 * Mangle the brand string etc.
1977 	 */
1978 	cpuid_pass3(CPU);
1979 
1980 #if defined(__amd64)
1981 
1982 	/*
1983 	 * Create the device arena for toxic (to dtrace/kmdb) mappings.
1984 	 */
1985 	device_arena = vmem_create("device", (void *)toxic_addr,
1986 	    toxic_size, MMU_PAGESIZE, NULL, NULL, NULL, 0, VM_SLEEP);
1987 
1988 #else	/* __i386 */
1989 
1990 	/*
1991 	 * allocate the bit map that tracks toxic pages
1992 	 */
1993 	toxic_bit_map_len = btop((ulong_t)(valloc_base - kernelbase));
1994 	PRM_DEBUG(toxic_bit_map_len);
1995 	toxic_bit_map =
1996 	    kmem_zalloc(BT_SIZEOFMAP(toxic_bit_map_len), KM_NOSLEEP);
1997 	ASSERT(toxic_bit_map != NULL);
1998 	PRM_DEBUG(toxic_bit_map);
1999 
2000 #endif	/* __i386 */
2001 
2002 
2003 	/*
2004 	 * Now that we've got more VA, as well as the ability to allocate from
2005 	 * it, tell the debugger.
2006 	 */
2007 	if (boothowto & RB_DEBUG)
2008 		kdi_dvec_memavail();
2009 
2010 	/*
2011 	 * The following code installs a special page fault handler (#pf)
2012 	 * to work around a pentium bug.
2013 	 */
2014 #if !defined(__amd64) && !defined(__xpv)
2015 	if (x86_type == X86_TYPE_P5) {
2016 		desctbr_t idtr;
2017 		gate_desc_t *newidt;
2018 
2019 		if ((newidt = kmem_zalloc(MMU_PAGESIZE, KM_NOSLEEP)) == NULL)
2020 			panic("failed to install pentium_pftrap");
2021 
2022 		bcopy(idt0, newidt, NIDT * sizeof (*idt0));
2023 		set_gatesegd(&newidt[T_PGFLT], &pentium_pftrap,
2024 		    KCS_SEL, SDT_SYSIGT, TRP_KPL, 0);
2025 
2026 		(void) as_setprot(&kas, (caddr_t)newidt, MMU_PAGESIZE,
2027 		    PROT_READ | PROT_EXEC);
2028 
2029 		CPU->cpu_idt = newidt;
2030 		idtr.dtr_base = (uintptr_t)CPU->cpu_idt;
2031 		idtr.dtr_limit = (NIDT * sizeof (*idt0)) - 1;
2032 		wr_idtr(&idtr);
2033 	}
2034 #endif	/* !__amd64 */
2035 
2036 #if !defined(__xpv)
2037 	/*
2038 	 * Map page pfn=0 for drivers, such as kd, that need to pick up
2039 	 * parameters left there by controllers/BIOS.
2040 	 */
2041 	PRM_POINT("setup up p0_va");
2042 	p0_va = i86devmap(0, 1, PROT_READ);
2043 	PRM_DEBUG(p0_va);
2044 #endif
2045 
2046 	cmn_err(CE_CONT, "?mem = %luK (0x%lx)\n",
2047 	    physinstalled << (MMU_PAGESHIFT - 10), ptob(physinstalled));
2048 
2049 	/*
2050 	 * disable automatic large pages for small memory systems or
2051 	 * when the disable flag is set.
2052 	 *
2053 	 * Do not yet consider page sizes larger than 2m/4m.
2054 	 */
2055 	if (!auto_lpg_disable && mmu.max_page_level > 0) {
2056 		max_uheap_lpsize = LEVEL_SIZE(1);
2057 		max_ustack_lpsize = LEVEL_SIZE(1);
2058 		max_privmap_lpsize = LEVEL_SIZE(1);
2059 		max_uidata_lpsize = LEVEL_SIZE(1);
2060 		max_utext_lpsize = LEVEL_SIZE(1);
2061 		max_shm_lpsize = LEVEL_SIZE(1);
2062 	}
2063 	if (physmem < privm_lpg_min_physmem || mmu.max_page_level == 0 ||
2064 	    auto_lpg_disable) {
2065 		use_brk_lpg = 0;
2066 		use_stk_lpg = 0;
2067 	}
2068 	mcntl0_lpsize = LEVEL_SIZE(mmu.umax_page_level);
2069 
2070 	PRM_POINT("Calling hat_init_finish()...");
2071 	hat_init_finish();
2072 	PRM_POINT("hat_init_finish() done");
2073 
2074 	/*
2075 	 * Initialize the segkp segment type.
2076 	 */
2077 	rw_enter(&kas.a_lock, RW_WRITER);
2078 	PRM_POINT("Attaching segkp");
2079 	if (segkp_fromheap) {
2080 		segkp->s_as = &kas;
2081 	} else if (seg_attach(&kas, (caddr_t)segkp_base, mmu_ptob(segkpsize),
2082 	    segkp) < 0) {
2083 		panic("startup: cannot attach segkp");
2084 		/*NOTREACHED*/
2085 	}
2086 	PRM_POINT("Doing segkp_create()");
2087 	if (segkp_create(segkp) != 0) {
2088 		panic("startup: segkp_create failed");
2089 		/*NOTREACHED*/
2090 	}
2091 	PRM_DEBUG(segkp);
2092 	rw_exit(&kas.a_lock);
2093 
2094 	/*
2095 	 * kpm segment
2096 	 */
2097 	segmap_kpm = 0;
2098 	if (kpm_desired) {
2099 		kpm_init();
2100 		kpm_enable = 1;
2101 	}
2102 
2103 	/*
2104 	 * Now create segmap segment.
2105 	 */
2106 	rw_enter(&kas.a_lock, RW_WRITER);
2107 	if (seg_attach(&kas, (caddr_t)segmap_start, segmapsize, segmap) < 0) {
2108 		panic("cannot attach segmap");
2109 		/*NOTREACHED*/
2110 	}
2111 	PRM_DEBUG(segmap);
2112 
2113 	a.prot = PROT_READ | PROT_WRITE;
2114 	a.shmsize = 0;
2115 	a.nfreelist = segmapfreelists;
2116 
2117 	if (segmap_create(segmap, (caddr_t)&a) != 0)
2118 		panic("segmap_create segmap");
2119 	rw_exit(&kas.a_lock);
2120 
2121 	setup_vaddr_for_ppcopy(CPU);
2122 
2123 	segdev_init();
2124 #if defined(__xpv)
2125 	if (DOMAIN_IS_INITDOMAIN(xen_info))
2126 #endif
2127 		pmem_init();
2128 
2129 	PRM_POINT("startup_vm() done");
2130 }
2131 
2132 /*
2133  * Load a tod module for the non-standard tod part found on this system.
2134  */
2135 static void
2136 load_tod_module(char *todmod)
2137 {
2138 	if (modload("tod", todmod) == -1)
2139 		halt("Can't load TOD module");
2140 }
2141 
2142 static void
2143 startup_end(void)
2144 {
2145 	int i;
2146 	extern void setx86isalist(void);
2147 	extern void cpu_event_init(void);
2148 
2149 	PRM_POINT("startup_end() starting...");
2150 
2151 	/*
2152 	 * Perform tasks that get done after most of the VM
2153 	 * initialization has been done but before the clock
2154 	 * and other devices get started.
2155 	 */
2156 	kern_setup1();
2157 
2158 	/*
2159 	 * Perform CPC initialization for this CPU.
2160 	 */
2161 	kcpc_hw_init(CPU);
2162 
2163 	/*
2164 	 * Initialize cpu event framework.
2165 	 */
2166 	cpu_event_init();
2167 
2168 #if defined(OPTERON_WORKAROUND_6323525)
2169 	if (opteron_workaround_6323525)
2170 		patch_workaround_6323525();
2171 #endif
2172 	/*
2173 	 * If needed, load TOD module now so that ddi_get_time(9F) etc. work
2174 	 * (For now, "needed" is defined as set tod_module_name in /etc/system)
2175 	 */
2176 	if (tod_module_name != NULL) {
2177 		PRM_POINT("load_tod_module()");
2178 		load_tod_module(tod_module_name);
2179 	}
2180 
2181 #if defined(__xpv)
2182 	/*
2183 	 * Forceload interposing TOD module for the hypervisor.
2184 	 */
2185 	PRM_POINT("load_tod_module()");
2186 	load_tod_module("xpvtod");
2187 #endif
2188 
2189 	/*
2190 	 * Configure the system.
2191 	 */
2192 	PRM_POINT("Calling configure()...");
2193 	configure();		/* set up devices */
2194 	PRM_POINT("configure() done");
2195 
2196 	/*
2197 	 * Set the isa_list string to the defined instruction sets we
2198 	 * support.
2199 	 */
2200 	setx86isalist();
2201 	cpu_intr_alloc(CPU, NINTR_THREADS);
2202 	psm_install();
2203 
2204 	/*
2205 	 * We're done with bootops.  We don't unmap the bootstrap yet because
2206 	 * we're still using bootsvcs.
2207 	 */
2208 	PRM_POINT("NULLing out bootops");
2209 	*bootopsp = (struct bootops *)NULL;
2210 	bootops = (struct bootops *)NULL;
2211 
2212 #if defined(__xpv)
2213 	ec_init_debug_irq();
2214 	xs_domu_init();
2215 #endif
2216 
2217 #if defined(__amd64) && !defined(__xpv)
2218 	/*
2219 	 * Intel IOMMU has been setup/initialized in ddi_impl.c
2220 	 * Start it up now.
2221 	 */
2222 	immu_startup();
2223 #endif
2224 
2225 	PRM_POINT("Enabling interrupts");
2226 	(*picinitf)();
2227 	sti();
2228 #if defined(__xpv)
2229 	ASSERT(CPU->cpu_m.mcpu_vcpu_info->evtchn_upcall_mask == 0);
2230 	xen_late_startup();
2231 #endif
2232 
2233 	(void) add_avsoftintr((void *)&softlevel1_hdl, 1, softlevel1,
2234 	    "softlevel1", NULL, NULL); /* XXX to be moved later */
2235 
2236 	/*
2237 	 * Register these software interrupts for ddi timer.
2238 	 * Software interrupts up to the level 10 are supported.
2239 	 */
2240 	for (i = DDI_IPL_1; i <= DDI_IPL_10; i++) {
2241 		char name[sizeof ("timer_softintr") + 2];
2242 		(void) sprintf(name, "timer_softintr%02d", i);
2243 		(void) add_avsoftintr((void *)&softlevel_hdl[i-1], i,
2244 		    (avfunc)timer_softintr, name, (caddr_t)(uintptr_t)i, NULL);
2245 	}
2246 
2247 #if !defined(__xpv)
2248 	if (modload("drv", "amd_iommu") < 0) {
2249 		PRM_POINT("No AMD IOMMU present\n");
2250 	} else if (ddi_hold_installed_driver(ddi_name_to_major(
2251 	    "amd_iommu")) == NULL) {
2252 		prom_printf("ERROR: failed to attach AMD IOMMU\n");
2253 	}
2254 #endif
2255 	post_startup_cpu_fixups();
2256 
2257 	PRM_POINT("startup_end() done");
2258 }
2259 
2260 /*
2261  * Don't remove the following 2 variables.  They are necessary
2262  * for reading the hostid from the legacy file (/kernel/misc/sysinit).
2263  */
2264 char *_hs1107 = hw_serial;
2265 ulong_t  _bdhs34;
2266 
2267 void
2268 post_startup(void)
2269 {
2270 	extern void cpupm_init(cpu_t *);
2271 	extern void cpu_event_init_cpu(cpu_t *);
2272 
2273 	/*
2274 	 * Set the system wide, processor-specific flags to be passed
2275 	 * to userland via the aux vector for performance hints and
2276 	 * instruction set extensions.
2277 	 */
2278 	bind_hwcap();
2279 
2280 #ifdef __xpv
2281 	if (DOMAIN_IS_INITDOMAIN(xen_info))
2282 #endif
2283 	{
2284 #if defined(__xpv)
2285 		xpv_panic_init();
2286 #else
2287 		/*
2288 		 * Startup the memory scrubber.
2289 		 * XXPV	This should be running somewhere ..
2290 		 */
2291 		if (get_hwenv() != HW_XEN_HVM)
2292 			memscrub_init();
2293 #endif
2294 	}
2295 
2296 	/*
2297 	 * Complete CPU module initialization
2298 	 */
2299 	cmi_post_startup();
2300 
2301 	/*
2302 	 * Perform forceloading tasks for /etc/system.
2303 	 */
2304 	(void) mod_sysctl(SYS_FORCELOAD, NULL);
2305 
2306 	/*
2307 	 * ON4.0: Force /proc module in until clock interrupt handle fixed
2308 	 * ON4.0: This must be fixed or restated in /etc/systems.
2309 	 */
2310 	(void) modload("fs", "procfs");
2311 
2312 	(void) i_ddi_attach_hw_nodes("pit_beep");
2313 
2314 #if defined(__i386)
2315 	/*
2316 	 * Check for required functional Floating Point hardware,
2317 	 * unless FP hardware explicitly disabled.
2318 	 */
2319 	if (fpu_exists && (fpu_pentium_fdivbug || fp_kind == FP_NO))
2320 		halt("No working FP hardware found");
2321 #endif
2322 
2323 	maxmem = freemem;
2324 
2325 	cpu_event_init_cpu(CPU);
2326 	cpupm_init(CPU);
2327 	(void) mach_cpu_create_device_node(CPU, NULL);
2328 
2329 	pg_init();
2330 }
2331 
2332 static int
2333 pp_in_range(page_t *pp, uint64_t low_addr, uint64_t high_addr)
2334 {
2335 	return ((pp->p_pagenum >= btop(low_addr)) &&
2336 	    (pp->p_pagenum < btopr(high_addr)));
2337 }
2338 
2339 void
2340 release_bootstrap(void)
2341 {
2342 	int root_is_ramdisk;
2343 	page_t *pp;
2344 	extern void kobj_boot_unmountroot(void);
2345 	extern dev_t rootdev;
2346 #if !defined(__xpv)
2347 	pfn_t	pfn;
2348 #endif
2349 
2350 	/* unmount boot ramdisk and release kmem usage */
2351 	kobj_boot_unmountroot();
2352 
2353 	/*
2354 	 * We're finished using the boot loader so free its pages.
2355 	 */
2356 	PRM_POINT("Unmapping lower boot pages");
2357 
2358 	clear_boot_mappings(0, _userlimit);
2359 
2360 	postbootkernelbase = kernelbase;
2361 
2362 	/*
2363 	 * If root isn't on ramdisk, destroy the hardcoded
2364 	 * ramdisk node now and release the memory. Else,
2365 	 * ramdisk memory is kept in rd_pages.
2366 	 */
2367 	root_is_ramdisk = (getmajor(rootdev) == ddi_name_to_major("ramdisk"));
2368 	if (!root_is_ramdisk) {
2369 		dev_info_t *dip = ddi_find_devinfo("ramdisk", -1, 0);
2370 		ASSERT(dip && ddi_get_parent(dip) == ddi_root_node());
2371 		ndi_rele_devi(dip);	/* held from ddi_find_devinfo */
2372 		(void) ddi_remove_child(dip, 0);
2373 	}
2374 
2375 	PRM_POINT("Releasing boot pages");
2376 	while (bootpages) {
2377 		extern uint64_t ramdisk_start, ramdisk_end;
2378 		pp = bootpages;
2379 		bootpages = pp->p_next;
2380 
2381 
2382 		/* Keep pages for the lower 64K */
2383 		if (pp_in_range(pp, 0, 0x40000)) {
2384 			pp->p_next = lower_pages;
2385 			lower_pages = pp;
2386 			lower_pages_count++;
2387 			continue;
2388 		}
2389 
2390 
2391 		if (root_is_ramdisk && pp_in_range(pp, ramdisk_start,
2392 		    ramdisk_end)) {
2393 			pp->p_next = rd_pages;
2394 			rd_pages = pp;
2395 			continue;
2396 		}
2397 		pp->p_next = (struct page *)0;
2398 		pp->p_prev = (struct page *)0;
2399 		PP_CLRBOOTPAGES(pp);
2400 		page_free(pp, 1);
2401 	}
2402 	PRM_POINT("Boot pages released");
2403 
2404 #if !defined(__xpv)
2405 /* XXPV -- note this following bunch of code needs to be revisited in Xen 3.0 */
2406 	/*
2407 	 * Find 1 page below 1 MB so that other processors can boot up or
2408 	 * so that any processor can resume.
2409 	 * Make sure it has a kernel VA as well as a 1:1 mapping.
2410 	 * We should have just free'd one up.
2411 	 */
2412 
2413 	/*
2414 	 * 0x10 pages is 64K.  Leave the bottom 64K alone
2415 	 * for BIOS.
2416 	 */
2417 	for (pfn = 0x10; pfn < btop(1*1024*1024); pfn++) {
2418 		if (page_numtopp_alloc(pfn) == NULL)
2419 			continue;
2420 		rm_platter_va = i86devmap(pfn, 1,
2421 		    PROT_READ | PROT_WRITE | PROT_EXEC);
2422 		rm_platter_pa = ptob(pfn);
2423 		break;
2424 	}
2425 	if (pfn == btop(1*1024*1024) && use_mp)
2426 		panic("No page below 1M available for starting "
2427 		    "other processors or for resuming from system-suspend");
2428 #endif	/* !__xpv */
2429 }
2430 
2431 /*
2432  * Initialize the platform-specific parts of a page_t.
2433  */
2434 void
2435 add_physmem_cb(page_t *pp, pfn_t pnum)
2436 {
2437 	pp->p_pagenum = pnum;
2438 	pp->p_mapping = NULL;
2439 	pp->p_embed = 0;
2440 	pp->p_share = 0;
2441 	pp->p_mlentry = 0;
2442 }
2443 
2444 /*
2445  * kphysm_init() initializes physical memory.
2446  */
2447 static pgcnt_t
2448 kphysm_init(
2449 	page_t *pp,
2450 	pgcnt_t npages)
2451 {
2452 	struct memlist	*pmem;
2453 	struct memseg	*cur_memseg;
2454 	pfn_t		base_pfn;
2455 	pfn_t		end_pfn;
2456 	pgcnt_t		num;
2457 	pgcnt_t		pages_done = 0;
2458 	uint64_t	addr;
2459 	uint64_t	size;
2460 	extern pfn_t	ddiphysmin;
2461 	extern int	mnode_xwa;
2462 	int		ms = 0, me = 0;
2463 
2464 	ASSERT(page_hash != NULL && page_hashsz != 0);
2465 
2466 	cur_memseg = memseg_base;
2467 	for (pmem = phys_avail; pmem && npages; pmem = pmem->ml_next) {
2468 		/*
2469 		 * In a 32 bit kernel can't use higher memory if we're
2470 		 * not booting in PAE mode. This check takes care of that.
2471 		 */
2472 		addr = pmem->ml_address;
2473 		size = pmem->ml_size;
2474 		if (btop(addr) > physmax)
2475 			continue;
2476 
2477 		/*
2478 		 * align addr and size - they may not be at page boundaries
2479 		 */
2480 		if ((addr & MMU_PAGEOFFSET) != 0) {
2481 			addr += MMU_PAGEOFFSET;
2482 			addr &= ~(uint64_t)MMU_PAGEOFFSET;
2483 			size -= addr - pmem->ml_address;
2484 		}
2485 
2486 		/* only process pages below or equal to physmax */
2487 		if ((btop(addr + size) - 1) > physmax)
2488 			size = ptob(physmax - btop(addr) + 1);
2489 
2490 		num = btop(size);
2491 		if (num == 0)
2492 			continue;
2493 
2494 		if (num > npages)
2495 			num = npages;
2496 
2497 		npages -= num;
2498 		pages_done += num;
2499 		base_pfn = btop(addr);
2500 
2501 		if (prom_debug)
2502 			prom_printf("MEMSEG addr=0x%" PRIx64
2503 			    " pgs=0x%lx pfn 0x%lx-0x%lx\n",
2504 			    addr, num, base_pfn, base_pfn + num);
2505 
2506 		/*
2507 		 * Ignore pages below ddiphysmin to simplify ddi memory
2508 		 * allocation with non-zero addr_lo requests.
2509 		 */
2510 		if (base_pfn < ddiphysmin) {
2511 			if (base_pfn + num <= ddiphysmin)
2512 				continue;
2513 			pp += (ddiphysmin - base_pfn);
2514 			num -= (ddiphysmin - base_pfn);
2515 			base_pfn = ddiphysmin;
2516 		}
2517 
2518 		/*
2519 		 * mnode_xwa is greater than 1 when large pages regions can
2520 		 * cross memory node boundaries. To prevent the formation
2521 		 * of these large pages, configure the memsegs based on the
2522 		 * memory node ranges which had been made non-contiguous.
2523 		 */
2524 		if (mnode_xwa > 1) {
2525 
2526 			end_pfn = base_pfn + num - 1;
2527 			ms = PFN_2_MEM_NODE(base_pfn);
2528 			me = PFN_2_MEM_NODE(end_pfn);
2529 
2530 			if (ms != me) {
2531 				/*
2532 				 * current range spans more than 1 memory node.
2533 				 * Set num to only the pfn range in the start
2534 				 * memory node.
2535 				 */
2536 				num = mem_node_config[ms].physmax - base_pfn
2537 				    + 1;
2538 				ASSERT(end_pfn > mem_node_config[ms].physmax);
2539 			}
2540 		}
2541 
2542 		for (;;) {
2543 			/*
2544 			 * Build the memsegs entry
2545 			 */
2546 			cur_memseg->pages = pp;
2547 			cur_memseg->epages = pp + num;
2548 			cur_memseg->pages_base = base_pfn;
2549 			cur_memseg->pages_end = base_pfn + num;
2550 
2551 			/*
2552 			 * Insert into memseg list in decreasing pfn range
2553 			 * order. Low memory is typically more fragmented such
2554 			 * that this ordering keeps the larger ranges at the
2555 			 * front of the list for code that searches memseg.
2556 			 * This ASSERTS that the memsegs coming in from boot
2557 			 * are in increasing physical address order and not
2558 			 * contiguous.
2559 			 */
2560 			if (memsegs != NULL) {
2561 				ASSERT(cur_memseg->pages_base >=
2562 				    memsegs->pages_end);
2563 				cur_memseg->next = memsegs;
2564 			}
2565 			memsegs = cur_memseg;
2566 
2567 			/*
2568 			 * add_physmem() initializes the PSM part of the page
2569 			 * struct by calling the PSM back with add_physmem_cb().
2570 			 * In addition it coalesces pages into larger pages as
2571 			 * it initializes them.
2572 			 */
2573 			add_physmem(pp, num, base_pfn);
2574 			cur_memseg++;
2575 			availrmem_initial += num;
2576 			availrmem += num;
2577 
2578 			pp += num;
2579 			if (ms >= me)
2580 				break;
2581 
2582 			/* process next memory node range */
2583 			ms++;
2584 			base_pfn = mem_node_config[ms].physbase;
2585 			num = MIN(mem_node_config[ms].physmax,
2586 			    end_pfn) - base_pfn + 1;
2587 		}
2588 	}
2589 
2590 	PRM_DEBUG(availrmem_initial);
2591 	PRM_DEBUG(availrmem);
2592 	PRM_DEBUG(freemem);
2593 	build_pfn_hash();
2594 	return (pages_done);
2595 }
2596 
2597 /*
2598  * Kernel VM initialization.
2599  */
2600 static void
2601 kvm_init(void)
2602 {
2603 	ASSERT((((uintptr_t)s_text) & MMU_PAGEOFFSET) == 0);
2604 
2605 	/*
2606 	 * Put the kernel segments in kernel address space.
2607 	 */
2608 	rw_enter(&kas.a_lock, RW_WRITER);
2609 	as_avlinit(&kas);
2610 
2611 	(void) seg_attach(&kas, s_text, e_moddata - s_text, &ktextseg);
2612 	(void) segkmem_create(&ktextseg);
2613 
2614 	(void) seg_attach(&kas, (caddr_t)valloc_base, valloc_sz, &kvalloc);
2615 	(void) segkmem_create(&kvalloc);
2616 
2617 	(void) seg_attach(&kas, kernelheap,
2618 	    ekernelheap - kernelheap, &kvseg);
2619 	(void) segkmem_create(&kvseg);
2620 
2621 	if (core_size > 0) {
2622 		PRM_POINT("attaching kvseg_core");
2623 		(void) seg_attach(&kas, (caddr_t)core_base, core_size,
2624 		    &kvseg_core);
2625 		(void) segkmem_create(&kvseg_core);
2626 	}
2627 
2628 	if (segziosize > 0) {
2629 		PRM_POINT("attaching segzio");
2630 		(void) seg_attach(&kas, segzio_base, mmu_ptob(segziosize),
2631 		    &kzioseg);
2632 		(void) segkmem_zio_create(&kzioseg);
2633 
2634 		/* create zio area covering new segment */
2635 		segkmem_zio_init(segzio_base, mmu_ptob(segziosize));
2636 	}
2637 
2638 	(void) seg_attach(&kas, kdi_segdebugbase, kdi_segdebugsize, &kdebugseg);
2639 	(void) segkmem_create(&kdebugseg);
2640 
2641 	rw_exit(&kas.a_lock);
2642 
2643 	/*
2644 	 * Ensure that the red zone at kernelbase is never accessible.
2645 	 */
2646 	PRM_POINT("protecting redzone");
2647 	(void) as_setprot(&kas, (caddr_t)kernelbase, KERNEL_REDZONE_SIZE, 0);
2648 
2649 	/*
2650 	 * Make the text writable so that it can be hot patched by DTrace.
2651 	 */
2652 	(void) as_setprot(&kas, s_text, e_modtext - s_text,
2653 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2654 
2655 	/*
2656 	 * Make data writable until end.
2657 	 */
2658 	(void) as_setprot(&kas, s_data, e_moddata - s_data,
2659 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2660 }
2661 
2662 #ifndef __xpv
2663 /*
2664  * Solaris adds an entry for Write Combining caching to the PAT
2665  */
2666 static uint64_t pat_attr_reg = PAT_DEFAULT_ATTRIBUTE;
2667 
2668 void
2669 pat_sync(void)
2670 {
2671 	ulong_t	cr0, cr0_orig, cr4;
2672 
2673 	if (!(x86_feature & X86_PAT))
2674 		return;
2675 	cr0_orig = cr0 = getcr0();
2676 	cr4 = getcr4();
2677 
2678 	/* disable caching and flush all caches and TLBs */
2679 	cr0 |= CR0_CD;
2680 	cr0 &= ~CR0_NW;
2681 	setcr0(cr0);
2682 	invalidate_cache();
2683 	if (cr4 & CR4_PGE) {
2684 		setcr4(cr4 & ~(ulong_t)CR4_PGE);
2685 		setcr4(cr4);
2686 	} else {
2687 		reload_cr3();
2688 	}
2689 
2690 	/* add our entry to the PAT */
2691 	wrmsr(REG_PAT, pat_attr_reg);
2692 
2693 	/* flush TLBs and cache again, then reenable cr0 caching */
2694 	if (cr4 & CR4_PGE) {
2695 		setcr4(cr4 & ~(ulong_t)CR4_PGE);
2696 		setcr4(cr4);
2697 	} else {
2698 		reload_cr3();
2699 	}
2700 	invalidate_cache();
2701 	setcr0(cr0_orig);
2702 }
2703 
2704 #endif /* !__xpv */
2705 
2706 #if defined(_SOFT_HOSTID)
2707 /*
2708  * On platforms that do not have a hardware serial number, attempt
2709  * to set one based on the contents of /etc/hostid.  If this file does
2710  * not exist, assume that we are to generate a new hostid and set
2711  * it in the kernel, for subsequent saving by a userland process
2712  * once the system is up and the root filesystem is mounted r/w.
2713  *
2714  * In order to gracefully support upgrade on OpenSolaris, if
2715  * /etc/hostid does not exist, we will attempt to get a serial number
2716  * using the legacy method (/kernel/misc/sysinit).
2717  *
2718  * In an attempt to make the hostid less prone to abuse
2719  * (for license circumvention, etc), we store it in /etc/hostid
2720  * in rot47 format.
2721  */
2722 extern volatile unsigned long tenmicrodata;
2723 static int atoi(char *);
2724 
2725 static int32_t
2726 set_soft_hostid(void)
2727 {
2728 	struct _buf *file;
2729 	char tokbuf[MAXNAMELEN];
2730 	token_t token;
2731 	int done = 0;
2732 	u_longlong_t tmp;
2733 	int i;
2734 	int32_t hostid = (int32_t)HW_INVALID_HOSTID;
2735 	unsigned char *c;
2736 	hrtime_t tsc;
2737 
2738 	/*
2739 	 * If /etc/hostid file not found, we'd like to get a pseudo
2740 	 * random number to use at the hostid.  A nice way to do this
2741 	 * is to read the real time clock.  To remain xen-compatible,
2742 	 * we can't poke the real hardware, so we use tsc_read() to
2743 	 * read the real time clock.  However, there is an ominous
2744 	 * warning in tsc_read that says it can return zero, so we
2745 	 * deal with that possibility by falling back to using the
2746 	 * (hopefully random enough) value in tenmicrodata.
2747 	 */
2748 
2749 	if ((file = kobj_open_file(hostid_file)) == (struct _buf *)-1) {
2750 		/*
2751 		 * hostid file not found - try to load sysinit module
2752 		 * and see if it has a nonzero hostid value...use that
2753 		 * instead of generating a new hostid here if so.
2754 		 */
2755 		if ((i = modload("misc", "sysinit")) != -1) {
2756 			if (strlen(hw_serial) > 0)
2757 				hostid = (int32_t)atoi(hw_serial);
2758 			(void) modunload(i);
2759 		}
2760 		if (hostid == HW_INVALID_HOSTID) {
2761 			tsc = tsc_read();
2762 			if (tsc == 0)	/* tsc_read can return zero sometimes */
2763 				hostid = (int32_t)tenmicrodata & 0x0CFFFFF;
2764 			else
2765 				hostid = (int32_t)tsc & 0x0CFFFFF;
2766 		}
2767 	} else {
2768 		/* hostid file found */
2769 		while (!done) {
2770 			token = kobj_lex(file, tokbuf, sizeof (tokbuf));
2771 
2772 			switch (token) {
2773 			case POUND:
2774 				/*
2775 				 * skip comments
2776 				 */
2777 				kobj_find_eol(file);
2778 				break;
2779 			case STRING:
2780 				/*
2781 				 * un-rot47 - obviously this
2782 				 * nonsense is ascii-specific
2783 				 */
2784 				for (c = (unsigned char *)tokbuf;
2785 				    *c != '\0'; c++) {
2786 					*c += 47;
2787 					if (*c > '~')
2788 						*c -= 94;
2789 					else if (*c < '!')
2790 						*c += 94;
2791 				}
2792 				/*
2793 				 * now we should have a real number
2794 				 */
2795 
2796 				if (kobj_getvalue(tokbuf, &tmp) != 0)
2797 					kobj_file_err(CE_WARN, file,
2798 					    "Bad value %s for hostid",
2799 					    tokbuf);
2800 				else
2801 					hostid = (int32_t)tmp;
2802 
2803 				break;
2804 			case EOF:
2805 				done = 1;
2806 				/* FALLTHROUGH */
2807 			case NEWLINE:
2808 				kobj_newline(file);
2809 				break;
2810 			default:
2811 				break;
2812 
2813 			}
2814 		}
2815 		if (hostid == HW_INVALID_HOSTID) /* didn't find a hostid */
2816 			kobj_file_err(CE_WARN, file,
2817 			    "hostid missing or corrupt");
2818 
2819 		kobj_close_file(file);
2820 	}
2821 	/*
2822 	 * hostid is now the value read from /etc/hostid, or the
2823 	 * new hostid we generated in this routine or HW_INVALID_HOSTID if not
2824 	 * set.
2825 	 */
2826 	return (hostid);
2827 }
2828 
2829 static int
2830 atoi(char *p)
2831 {
2832 	int i = 0;
2833 
2834 	while (*p != '\0')
2835 		i = 10 * i + (*p++ - '0');
2836 
2837 	return (i);
2838 }
2839 
2840 #endif /* _SOFT_HOSTID */
2841 
2842 void
2843 get_system_configuration(void)
2844 {
2845 	char	prop[32];
2846 	u_longlong_t nodes_ll, cpus_pernode_ll, lvalue;
2847 
2848 	if (BOP_GETPROPLEN(bootops, "nodes") > sizeof (prop) ||
2849 	    BOP_GETPROP(bootops, "nodes", prop) < 0 ||
2850 	    kobj_getvalue(prop, &nodes_ll) == -1 ||
2851 	    nodes_ll > MAXNODES ||
2852 	    BOP_GETPROPLEN(bootops, "cpus_pernode") > sizeof (prop) ||
2853 	    BOP_GETPROP(bootops, "cpus_pernode", prop) < 0 ||
2854 	    kobj_getvalue(prop, &cpus_pernode_ll) == -1) {
2855 		system_hardware.hd_nodes = 1;
2856 		system_hardware.hd_cpus_per_node = 0;
2857 	} else {
2858 		system_hardware.hd_nodes = (int)nodes_ll;
2859 		system_hardware.hd_cpus_per_node = (int)cpus_pernode_ll;
2860 	}
2861 
2862 	if (BOP_GETPROPLEN(bootops, "kernelbase") > sizeof (prop) ||
2863 	    BOP_GETPROP(bootops, "kernelbase", prop) < 0 ||
2864 	    kobj_getvalue(prop, &lvalue) == -1)
2865 		eprom_kernelbase = NULL;
2866 	else
2867 		eprom_kernelbase = (uintptr_t)lvalue;
2868 
2869 	if (BOP_GETPROPLEN(bootops, "segmapsize") > sizeof (prop) ||
2870 	    BOP_GETPROP(bootops, "segmapsize", prop) < 0 ||
2871 	    kobj_getvalue(prop, &lvalue) == -1)
2872 		segmapsize = SEGMAPDEFAULT;
2873 	else
2874 		segmapsize = (uintptr_t)lvalue;
2875 
2876 	if (BOP_GETPROPLEN(bootops, "segmapfreelists") > sizeof (prop) ||
2877 	    BOP_GETPROP(bootops, "segmapfreelists", prop) < 0 ||
2878 	    kobj_getvalue(prop, &lvalue) == -1)
2879 		segmapfreelists = 0;	/* use segmap driver default */
2880 	else
2881 		segmapfreelists = (int)lvalue;
2882 
2883 	/* physmem used to be here, but moved much earlier to fakebop.c */
2884 }
2885 
2886 /*
2887  * Add to a memory list.
2888  * start = start of new memory segment
2889  * len = length of new memory segment in bytes
2890  * new = pointer to a new struct memlist
2891  * memlistp = memory list to which to add segment.
2892  */
2893 void
2894 memlist_add(
2895 	uint64_t start,
2896 	uint64_t len,
2897 	struct memlist *new,
2898 	struct memlist **memlistp)
2899 {
2900 	struct memlist *cur;
2901 	uint64_t end = start + len;
2902 
2903 	new->ml_address = start;
2904 	new->ml_size = len;
2905 
2906 	cur = *memlistp;
2907 
2908 	while (cur) {
2909 		if (cur->ml_address >= end) {
2910 			new->ml_next = cur;
2911 			*memlistp = new;
2912 			new->ml_prev = cur->ml_prev;
2913 			cur->ml_prev = new;
2914 			return;
2915 		}
2916 		ASSERT(cur->ml_address + cur->ml_size <= start);
2917 		if (cur->ml_next == NULL) {
2918 			cur->ml_next = new;
2919 			new->ml_prev = cur;
2920 			new->ml_next = NULL;
2921 			return;
2922 		}
2923 		memlistp = &cur->ml_next;
2924 		cur = cur->ml_next;
2925 	}
2926 }
2927 
2928 void
2929 kobj_vmem_init(vmem_t **text_arena, vmem_t **data_arena)
2930 {
2931 	size_t tsize = e_modtext - modtext;
2932 	size_t dsize = e_moddata - moddata;
2933 
2934 	*text_arena = vmem_create("module_text", tsize ? modtext : NULL, tsize,
2935 	    1, segkmem_alloc, segkmem_free, heaptext_arena, 0, VM_SLEEP);
2936 	*data_arena = vmem_create("module_data", dsize ? moddata : NULL, dsize,
2937 	    1, segkmem_alloc, segkmem_free, heap32_arena, 0, VM_SLEEP);
2938 }
2939 
2940 caddr_t
2941 kobj_text_alloc(vmem_t *arena, size_t size)
2942 {
2943 	return (vmem_alloc(arena, size, VM_SLEEP | VM_BESTFIT));
2944 }
2945 
2946 /*ARGSUSED*/
2947 caddr_t
2948 kobj_texthole_alloc(caddr_t addr, size_t size)
2949 {
2950 	panic("unexpected call to kobj_texthole_alloc()");
2951 	/*NOTREACHED*/
2952 	return (0);
2953 }
2954 
2955 /*ARGSUSED*/
2956 void
2957 kobj_texthole_free(caddr_t addr, size_t size)
2958 {
2959 	panic("unexpected call to kobj_texthole_free()");
2960 }
2961 
2962 /*
2963  * This is called just after configure() in startup().
2964  *
2965  * The ISALIST concept is a bit hopeless on Intel, because
2966  * there's no guarantee of an ever-more-capable processor
2967  * given that various parts of the instruction set may appear
2968  * and disappear between different implementations.
2969  *
2970  * While it would be possible to correct it and even enhance
2971  * it somewhat, the explicit hardware capability bitmask allows
2972  * more flexibility.
2973  *
2974  * So, we just leave this alone.
2975  */
2976 void
2977 setx86isalist(void)
2978 {
2979 	char *tp;
2980 	size_t len;
2981 	extern char *isa_list;
2982 
2983 #define	TBUFSIZE	1024
2984 
2985 	tp = kmem_alloc(TBUFSIZE, KM_SLEEP);
2986 	*tp = '\0';
2987 
2988 #if defined(__amd64)
2989 	(void) strcpy(tp, "amd64 ");
2990 #endif
2991 
2992 	switch (x86_vendor) {
2993 	case X86_VENDOR_Intel:
2994 	case X86_VENDOR_AMD:
2995 	case X86_VENDOR_TM:
2996 		if (x86_feature & X86_CMOV) {
2997 			/*
2998 			 * Pentium Pro or later
2999 			 */
3000 			(void) strcat(tp, "pentium_pro");
3001 			(void) strcat(tp, x86_feature & X86_MMX ?
3002 			    "+mmx pentium_pro " : " ");
3003 		}
3004 		/*FALLTHROUGH*/
3005 	case X86_VENDOR_Cyrix:
3006 		/*
3007 		 * The Cyrix 6x86 does not have any Pentium features
3008 		 * accessible while not at privilege level 0.
3009 		 */
3010 		if (x86_feature & X86_CPUID) {
3011 			(void) strcat(tp, "pentium");
3012 			(void) strcat(tp, x86_feature & X86_MMX ?
3013 			    "+mmx pentium " : " ");
3014 		}
3015 		break;
3016 	default:
3017 		break;
3018 	}
3019 	(void) strcat(tp, "i486 i386 i86");
3020 	len = strlen(tp) + 1;   /* account for NULL at end of string */
3021 	isa_list = strcpy(kmem_alloc(len, KM_SLEEP), tp);
3022 	kmem_free(tp, TBUFSIZE);
3023 
3024 #undef TBUFSIZE
3025 }
3026 
3027 
3028 #ifdef __amd64
3029 
3030 void *
3031 device_arena_alloc(size_t size, int vm_flag)
3032 {
3033 	return (vmem_alloc(device_arena, size, vm_flag));
3034 }
3035 
3036 void
3037 device_arena_free(void *vaddr, size_t size)
3038 {
3039 	vmem_free(device_arena, vaddr, size);
3040 }
3041 
3042 #else /* __i386 */
3043 
3044 void *
3045 device_arena_alloc(size_t size, int vm_flag)
3046 {
3047 	caddr_t	vaddr;
3048 	uintptr_t v;
3049 	size_t	start;
3050 	size_t	end;
3051 
3052 	vaddr = vmem_alloc(heap_arena, size, vm_flag);
3053 	if (vaddr == NULL)
3054 		return (NULL);
3055 
3056 	v = (uintptr_t)vaddr;
3057 	ASSERT(v >= kernelbase);
3058 	ASSERT(v + size <= valloc_base);
3059 
3060 	start = btop(v - kernelbase);
3061 	end = btop(v + size - 1 - kernelbase);
3062 	ASSERT(start < toxic_bit_map_len);
3063 	ASSERT(end < toxic_bit_map_len);
3064 
3065 	while (start <= end) {
3066 		BT_ATOMIC_SET(toxic_bit_map, start);
3067 		++start;
3068 	}
3069 	return (vaddr);
3070 }
3071 
3072 void
3073 device_arena_free(void *vaddr, size_t size)
3074 {
3075 	uintptr_t v = (uintptr_t)vaddr;
3076 	size_t	start;
3077 	size_t	end;
3078 
3079 	ASSERT(v >= kernelbase);
3080 	ASSERT(v + size <= valloc_base);
3081 
3082 	start = btop(v - kernelbase);
3083 	end = btop(v + size - 1 - kernelbase);
3084 	ASSERT(start < toxic_bit_map_len);
3085 	ASSERT(end < toxic_bit_map_len);
3086 
3087 	while (start <= end) {
3088 		ASSERT(BT_TEST(toxic_bit_map, start) != 0);
3089 		BT_ATOMIC_CLEAR(toxic_bit_map, start);
3090 		++start;
3091 	}
3092 	vmem_free(heap_arena, vaddr, size);
3093 }
3094 
3095 /*
3096  * returns 1st address in range that is in device arena, or NULL
3097  * if len is not NULL it returns the length of the toxic range
3098  */
3099 void *
3100 device_arena_contains(void *vaddr, size_t size, size_t *len)
3101 {
3102 	uintptr_t v = (uintptr_t)vaddr;
3103 	uintptr_t eaddr = v + size;
3104 	size_t start;
3105 	size_t end;
3106 
3107 	/*
3108 	 * if called very early by kmdb, just return NULL
3109 	 */
3110 	if (toxic_bit_map == NULL)
3111 		return (NULL);
3112 
3113 	/*
3114 	 * First check if we're completely outside the bitmap range.
3115 	 */
3116 	if (v >= valloc_base || eaddr < kernelbase)
3117 		return (NULL);
3118 
3119 	/*
3120 	 * Trim ends of search to look at only what the bitmap covers.
3121 	 */
3122 	if (v < kernelbase)
3123 		v = kernelbase;
3124 	start = btop(v - kernelbase);
3125 	end = btop(eaddr - kernelbase);
3126 	if (end >= toxic_bit_map_len)
3127 		end = toxic_bit_map_len;
3128 
3129 	if (bt_range(toxic_bit_map, &start, &end, end) == 0)
3130 		return (NULL);
3131 
3132 	v = kernelbase + ptob(start);
3133 	if (len != NULL)
3134 		*len = ptob(end - start);
3135 	return ((void *)v);
3136 }
3137 
3138 #endif	/* __i386 */
3139