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