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