xref: /titanic_41/usr/src/uts/i86pc/os/startup.c (revision 9a0e82381c494d655823a54fc713a8c2a571131c)
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 	pgcnt_t		num;
2329 	pgcnt_t		pages_done = 0;
2330 	uint64_t	addr;
2331 	uint64_t	size;
2332 	extern pfn_t	ddiphysmin;
2333 
2334 	ASSERT(page_hash != NULL && page_hashsz != 0);
2335 
2336 	cur_memseg = memseg_base;
2337 	for (pmem = phys_avail; pmem && npages; pmem = pmem->next) {
2338 		/*
2339 		 * In a 32 bit kernel can't use higher memory if we're
2340 		 * not booting in PAE mode. This check takes care of that.
2341 		 */
2342 		addr = pmem->address;
2343 		size = pmem->size;
2344 		if (btop(addr) > physmax)
2345 			continue;
2346 
2347 		/*
2348 		 * align addr and size - they may not be at page boundaries
2349 		 */
2350 		if ((addr & MMU_PAGEOFFSET) != 0) {
2351 			addr += MMU_PAGEOFFSET;
2352 			addr &= ~(uint64_t)MMU_PAGEOFFSET;
2353 			size -= addr - pmem->address;
2354 		}
2355 
2356 		/* only process pages below or equal to physmax */
2357 		if ((btop(addr + size) - 1) > physmax)
2358 			size = ptob(physmax - btop(addr) + 1);
2359 
2360 		num = btop(size);
2361 		if (num == 0)
2362 			continue;
2363 
2364 		if (num > npages)
2365 			num = npages;
2366 
2367 		npages -= num;
2368 		pages_done += num;
2369 		base_pfn = btop(addr);
2370 
2371 		if (prom_debug)
2372 			prom_printf("MEMSEG addr=0x%" PRIx64
2373 			    " pgs=0x%lx pfn 0x%lx-0x%lx\n",
2374 			    addr, num, base_pfn, base_pfn + num);
2375 
2376 		/*
2377 		 * Ignore pages below ddiphysmin to simplify ddi memory
2378 		 * allocation with non-zero addr_lo requests.
2379 		 */
2380 		if (base_pfn < ddiphysmin) {
2381 			if (base_pfn + num <= ddiphysmin)
2382 				continue;
2383 			pp += (ddiphysmin - base_pfn);
2384 			num -= (ddiphysmin - base_pfn);
2385 			base_pfn = ddiphysmin;
2386 		}
2387 
2388 		/*
2389 		 * Build the memsegs entry
2390 		 */
2391 		cur_memseg->pages = pp;
2392 		cur_memseg->epages = pp + num;
2393 		cur_memseg->pages_base = base_pfn;
2394 		cur_memseg->pages_end = base_pfn + num;
2395 
2396 		/*
2397 		 * Insert into memseg list in decreasing pfn range order.
2398 		 * Low memory is typically more fragmented such that this
2399 		 * ordering keeps the larger ranges at the front of the list
2400 		 * for code that searches memseg.
2401 		 * This ASSERTS that the memsegs coming in from boot are in
2402 		 * increasing physical address order and not contiguous.
2403 		 */
2404 		if (memsegs != NULL) {
2405 			ASSERT(cur_memseg->pages_base >= memsegs->pages_end);
2406 			cur_memseg->next = memsegs;
2407 		}
2408 		memsegs = cur_memseg;
2409 
2410 		/*
2411 		 * add_physmem() initializes the PSM part of the page
2412 		 * struct by calling the PSM back with add_physmem_cb().
2413 		 * In addition it coalesces pages into larger pages as
2414 		 * it initializes them.
2415 		 */
2416 		add_physmem(pp, num, base_pfn);
2417 		cur_memseg++;
2418 		availrmem_initial += num;
2419 		availrmem += num;
2420 
2421 		pp += num;
2422 	}
2423 
2424 	PRM_DEBUG(availrmem_initial);
2425 	PRM_DEBUG(availrmem);
2426 	PRM_DEBUG(freemem);
2427 	build_pfn_hash();
2428 	return (pages_done);
2429 }
2430 
2431 /*
2432  * Kernel VM initialization.
2433  */
2434 static void
2435 kvm_init(void)
2436 {
2437 	ASSERT((((uintptr_t)s_text) & MMU_PAGEOFFSET) == 0);
2438 
2439 	/*
2440 	 * Put the kernel segments in kernel address space.
2441 	 */
2442 	rw_enter(&kas.a_lock, RW_WRITER);
2443 	as_avlinit(&kas);
2444 
2445 	(void) seg_attach(&kas, s_text, e_moddata - s_text, &ktextseg);
2446 	(void) segkmem_create(&ktextseg);
2447 
2448 	(void) seg_attach(&kas, (caddr_t)valloc_base, valloc_sz, &kvalloc);
2449 	(void) segkmem_create(&kvalloc);
2450 
2451 	(void) seg_attach(&kas, kernelheap,
2452 	    ekernelheap - kernelheap, &kvseg);
2453 	(void) segkmem_create(&kvseg);
2454 
2455 	if (core_size > 0) {
2456 		PRM_POINT("attaching kvseg_core");
2457 		(void) seg_attach(&kas, (caddr_t)core_base, core_size,
2458 		    &kvseg_core);
2459 		(void) segkmem_create(&kvseg_core);
2460 	}
2461 
2462 	if (segziosize > 0) {
2463 		PRM_POINT("attaching segzio");
2464 		(void) seg_attach(&kas, segzio_base, mmu_ptob(segziosize),
2465 		    &kzioseg);
2466 		(void) segkmem_zio_create(&kzioseg);
2467 
2468 		/* create zio area covering new segment */
2469 		segkmem_zio_init(segzio_base, mmu_ptob(segziosize));
2470 	}
2471 
2472 	(void) seg_attach(&kas, kdi_segdebugbase, kdi_segdebugsize, &kdebugseg);
2473 	(void) segkmem_create(&kdebugseg);
2474 
2475 	rw_exit(&kas.a_lock);
2476 
2477 	/*
2478 	 * Ensure that the red zone at kernelbase is never accessible.
2479 	 */
2480 	PRM_POINT("protecting redzone");
2481 	(void) as_setprot(&kas, (caddr_t)kernelbase, KERNEL_REDZONE_SIZE, 0);
2482 
2483 	/*
2484 	 * Make the text writable so that it can be hot patched by DTrace.
2485 	 */
2486 	(void) as_setprot(&kas, s_text, e_modtext - s_text,
2487 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2488 
2489 	/*
2490 	 * Make data writable until end.
2491 	 */
2492 	(void) as_setprot(&kas, s_data, e_moddata - s_data,
2493 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2494 }
2495 
2496 #ifndef __xpv
2497 /*
2498  * Solaris adds an entry for Write Combining caching to the PAT
2499  */
2500 static uint64_t pat_attr_reg = PAT_DEFAULT_ATTRIBUTE;
2501 
2502 void
2503 pat_sync(void)
2504 {
2505 	ulong_t	cr0, cr0_orig, cr4;
2506 
2507 	if (!(x86_feature & X86_PAT))
2508 		return;
2509 	cr0_orig = cr0 = getcr0();
2510 	cr4 = getcr4();
2511 
2512 	/* disable caching and flush all caches and TLBs */
2513 	cr0 |= CR0_CD;
2514 	cr0 &= ~CR0_NW;
2515 	setcr0(cr0);
2516 	invalidate_cache();
2517 	if (cr4 & CR4_PGE) {
2518 		setcr4(cr4 & ~(ulong_t)CR4_PGE);
2519 		setcr4(cr4);
2520 	} else {
2521 		reload_cr3();
2522 	}
2523 
2524 	/* add our entry to the PAT */
2525 	wrmsr(REG_PAT, pat_attr_reg);
2526 
2527 	/* flush TLBs and cache again, then reenable cr0 caching */
2528 	if (cr4 & CR4_PGE) {
2529 		setcr4(cr4 & ~(ulong_t)CR4_PGE);
2530 		setcr4(cr4);
2531 	} else {
2532 		reload_cr3();
2533 	}
2534 	invalidate_cache();
2535 	setcr0(cr0_orig);
2536 }
2537 
2538 #endif /* !__xpv */
2539 
2540 #if defined(_SOFT_HOSTID)
2541 /*
2542  * On platforms that do not have a hardware serial number, attempt
2543  * to set one based on the contents of /etc/hostid.  If this file does
2544  * not exist, assume that we are to generate a new hostid and set
2545  * it in the kernel, for subsequent saving by a userland process
2546  * once the system is up and the root filesystem is mounted r/w.
2547  *
2548  * In order to gracefully support upgrade on OpenSolaris, if
2549  * /etc/hostid does not exist, we will attempt to get a serial number
2550  * using the legacy method (/kernel/misc/sysinit).
2551  *
2552  * In an attempt to make the hostid less prone to abuse
2553  * (for license circumvention, etc), we store it in /etc/hostid
2554  * in rot47 format.
2555  */
2556 extern volatile unsigned long tenmicrodata;
2557 static int atoi(char *);
2558 
2559 static int32_t
2560 set_soft_hostid(void)
2561 {
2562 	struct _buf *file;
2563 	char tokbuf[MAXNAMELEN];
2564 	token_t token;
2565 	int done = 0;
2566 	u_longlong_t tmp;
2567 	int i;
2568 	int32_t hostid = (int32_t)HW_INVALID_HOSTID;
2569 	unsigned char *c;
2570 	hrtime_t tsc;
2571 
2572 	/*
2573 	 * If /etc/hostid file not found, we'd like to get a pseudo
2574 	 * random number to use at the hostid.  A nice way to do this
2575 	 * is to read the real time clock.  To remain xen-compatible,
2576 	 * we can't poke the real hardware, so we use tsc_read() to
2577 	 * read the real time clock.  However, there is an ominous
2578 	 * warning in tsc_read that says it can return zero, so we
2579 	 * deal with that possibility by falling back to using the
2580 	 * (hopefully random enough) value in tenmicrodata.
2581 	 */
2582 
2583 	if ((file = kobj_open_file(hostid_file)) == (struct _buf *)-1) {
2584 		/*
2585 		 * hostid file not found - try to load sysinit module
2586 		 * and see if it has a nonzero hostid value...use that
2587 		 * instead of generating a new hostid here if so.
2588 		 */
2589 		if ((i = modload("misc", "sysinit")) != -1) {
2590 			if (strlen(hw_serial) > 0)
2591 				hostid = (int32_t)atoi(hw_serial);
2592 			(void) modunload(i);
2593 		}
2594 		if (hostid == HW_INVALID_HOSTID) {
2595 			tsc = tsc_read();
2596 			if (tsc == 0)	/* tsc_read can return zero sometimes */
2597 				hostid = (int32_t)tenmicrodata & 0x0CFFFFF;
2598 			else
2599 				hostid = (int32_t)tsc & 0x0CFFFFF;
2600 		}
2601 	} else {
2602 		/* hostid file found */
2603 		while (!done) {
2604 			token = kobj_lex(file, tokbuf, sizeof (tokbuf));
2605 
2606 			switch (token) {
2607 			case POUND:
2608 				/*
2609 				 * skip comments
2610 				 */
2611 				kobj_find_eol(file);
2612 				break;
2613 			case STRING:
2614 				/*
2615 				 * un-rot47 - obviously this
2616 				 * nonsense is ascii-specific
2617 				 */
2618 				for (c = (unsigned char *)tokbuf;
2619 				    *c != '\0'; c++) {
2620 					*c += 47;
2621 					if (*c > '~')
2622 						*c -= 94;
2623 					else if (*c < '!')
2624 						*c += 94;
2625 				}
2626 				/*
2627 				 * now we should have a real number
2628 				 */
2629 
2630 				if (kobj_getvalue(tokbuf, &tmp) != 0)
2631 					kobj_file_err(CE_WARN, file,
2632 					    "Bad value %s for hostid",
2633 					    tokbuf);
2634 				else
2635 					hostid = (int32_t)tmp;
2636 
2637 				break;
2638 			case EOF:
2639 				done = 1;
2640 				/* FALLTHROUGH */
2641 			case NEWLINE:
2642 				kobj_newline(file);
2643 				break;
2644 			default:
2645 				break;
2646 
2647 			}
2648 		}
2649 		if (hostid == HW_INVALID_HOSTID) /* didn't find a hostid */
2650 			kobj_file_err(CE_WARN, file,
2651 			    "hostid missing or corrupt");
2652 
2653 		kobj_close_file(file);
2654 	}
2655 	/*
2656 	 * hostid is now the value read from /etc/hostid, or the
2657 	 * new hostid we generated in this routine or HW_INVALID_HOSTID if not
2658 	 * set.
2659 	 */
2660 	return (hostid);
2661 }
2662 
2663 static int
2664 atoi(char *p)
2665 {
2666 	int i = 0;
2667 
2668 	while (*p != '\0')
2669 		i = 10 * i + (*p++ - '0');
2670 
2671 	return (i);
2672 }
2673 
2674 #endif /* _SOFT_HOSTID */
2675 
2676 void
2677 get_system_configuration(void)
2678 {
2679 	char	prop[32];
2680 	u_longlong_t nodes_ll, cpus_pernode_ll, lvalue;
2681 
2682 	if (BOP_GETPROPLEN(bootops, "nodes") > sizeof (prop) ||
2683 	    BOP_GETPROP(bootops, "nodes", prop) < 0 ||
2684 	    kobj_getvalue(prop, &nodes_ll) == -1 ||
2685 	    nodes_ll > MAXNODES ||
2686 	    BOP_GETPROPLEN(bootops, "cpus_pernode") > sizeof (prop) ||
2687 	    BOP_GETPROP(bootops, "cpus_pernode", prop) < 0 ||
2688 	    kobj_getvalue(prop, &cpus_pernode_ll) == -1) {
2689 		system_hardware.hd_nodes = 1;
2690 		system_hardware.hd_cpus_per_node = 0;
2691 	} else {
2692 		system_hardware.hd_nodes = (int)nodes_ll;
2693 		system_hardware.hd_cpus_per_node = (int)cpus_pernode_ll;
2694 	}
2695 
2696 	if (BOP_GETPROPLEN(bootops, "kernelbase") > sizeof (prop) ||
2697 	    BOP_GETPROP(bootops, "kernelbase", prop) < 0 ||
2698 	    kobj_getvalue(prop, &lvalue) == -1)
2699 		eprom_kernelbase = NULL;
2700 	else
2701 		eprom_kernelbase = (uintptr_t)lvalue;
2702 
2703 	if (BOP_GETPROPLEN(bootops, "segmapsize") > sizeof (prop) ||
2704 	    BOP_GETPROP(bootops, "segmapsize", prop) < 0 ||
2705 	    kobj_getvalue(prop, &lvalue) == -1)
2706 		segmapsize = SEGMAPDEFAULT;
2707 	else
2708 		segmapsize = (uintptr_t)lvalue;
2709 
2710 	if (BOP_GETPROPLEN(bootops, "segmapfreelists") > sizeof (prop) ||
2711 	    BOP_GETPROP(bootops, "segmapfreelists", prop) < 0 ||
2712 	    kobj_getvalue(prop, &lvalue) == -1)
2713 		segmapfreelists = 0;	/* use segmap driver default */
2714 	else
2715 		segmapfreelists = (int)lvalue;
2716 
2717 	/* physmem used to be here, but moved much earlier to fakebop.c */
2718 }
2719 
2720 /*
2721  * Add to a memory list.
2722  * start = start of new memory segment
2723  * len = length of new memory segment in bytes
2724  * new = pointer to a new struct memlist
2725  * memlistp = memory list to which to add segment.
2726  */
2727 void
2728 memlist_add(
2729 	uint64_t start,
2730 	uint64_t len,
2731 	struct memlist *new,
2732 	struct memlist **memlistp)
2733 {
2734 	struct memlist *cur;
2735 	uint64_t end = start + len;
2736 
2737 	new->address = start;
2738 	new->size = len;
2739 
2740 	cur = *memlistp;
2741 
2742 	while (cur) {
2743 		if (cur->address >= end) {
2744 			new->next = cur;
2745 			*memlistp = new;
2746 			new->prev = cur->prev;
2747 			cur->prev = new;
2748 			return;
2749 		}
2750 		ASSERT(cur->address + cur->size <= start);
2751 		if (cur->next == NULL) {
2752 			cur->next = new;
2753 			new->prev = cur;
2754 			new->next = NULL;
2755 			return;
2756 		}
2757 		memlistp = &cur->next;
2758 		cur = cur->next;
2759 	}
2760 }
2761 
2762 void
2763 kobj_vmem_init(vmem_t **text_arena, vmem_t **data_arena)
2764 {
2765 	size_t tsize = e_modtext - modtext;
2766 	size_t dsize = e_moddata - moddata;
2767 
2768 	*text_arena = vmem_create("module_text", tsize ? modtext : NULL, tsize,
2769 	    1, segkmem_alloc, segkmem_free, heaptext_arena, 0, VM_SLEEP);
2770 	*data_arena = vmem_create("module_data", dsize ? moddata : NULL, dsize,
2771 	    1, segkmem_alloc, segkmem_free, heap32_arena, 0, VM_SLEEP);
2772 }
2773 
2774 caddr_t
2775 kobj_text_alloc(vmem_t *arena, size_t size)
2776 {
2777 	return (vmem_alloc(arena, size, VM_SLEEP | VM_BESTFIT));
2778 }
2779 
2780 /*ARGSUSED*/
2781 caddr_t
2782 kobj_texthole_alloc(caddr_t addr, size_t size)
2783 {
2784 	panic("unexpected call to kobj_texthole_alloc()");
2785 	/*NOTREACHED*/
2786 	return (0);
2787 }
2788 
2789 /*ARGSUSED*/
2790 void
2791 kobj_texthole_free(caddr_t addr, size_t size)
2792 {
2793 	panic("unexpected call to kobj_texthole_free()");
2794 }
2795 
2796 /*
2797  * This is called just after configure() in startup().
2798  *
2799  * The ISALIST concept is a bit hopeless on Intel, because
2800  * there's no guarantee of an ever-more-capable processor
2801  * given that various parts of the instruction set may appear
2802  * and disappear between different implementations.
2803  *
2804  * While it would be possible to correct it and even enhance
2805  * it somewhat, the explicit hardware capability bitmask allows
2806  * more flexibility.
2807  *
2808  * So, we just leave this alone.
2809  */
2810 void
2811 setx86isalist(void)
2812 {
2813 	char *tp;
2814 	size_t len;
2815 	extern char *isa_list;
2816 
2817 #define	TBUFSIZE	1024
2818 
2819 	tp = kmem_alloc(TBUFSIZE, KM_SLEEP);
2820 	*tp = '\0';
2821 
2822 #if defined(__amd64)
2823 	(void) strcpy(tp, "amd64 ");
2824 #endif
2825 
2826 	switch (x86_vendor) {
2827 	case X86_VENDOR_Intel:
2828 	case X86_VENDOR_AMD:
2829 	case X86_VENDOR_TM:
2830 		if (x86_feature & X86_CMOV) {
2831 			/*
2832 			 * Pentium Pro or later
2833 			 */
2834 			(void) strcat(tp, "pentium_pro");
2835 			(void) strcat(tp, x86_feature & X86_MMX ?
2836 			    "+mmx pentium_pro " : " ");
2837 		}
2838 		/*FALLTHROUGH*/
2839 	case X86_VENDOR_Cyrix:
2840 		/*
2841 		 * The Cyrix 6x86 does not have any Pentium features
2842 		 * accessible while not at privilege level 0.
2843 		 */
2844 		if (x86_feature & X86_CPUID) {
2845 			(void) strcat(tp, "pentium");
2846 			(void) strcat(tp, x86_feature & X86_MMX ?
2847 			    "+mmx pentium " : " ");
2848 		}
2849 		break;
2850 	default:
2851 		break;
2852 	}
2853 	(void) strcat(tp, "i486 i386 i86");
2854 	len = strlen(tp) + 1;   /* account for NULL at end of string */
2855 	isa_list = strcpy(kmem_alloc(len, KM_SLEEP), tp);
2856 	kmem_free(tp, TBUFSIZE);
2857 
2858 #undef TBUFSIZE
2859 }
2860 
2861 
2862 #ifdef __amd64
2863 
2864 void *
2865 device_arena_alloc(size_t size, int vm_flag)
2866 {
2867 	return (vmem_alloc(device_arena, size, vm_flag));
2868 }
2869 
2870 void
2871 device_arena_free(void *vaddr, size_t size)
2872 {
2873 	vmem_free(device_arena, vaddr, size);
2874 }
2875 
2876 #else /* __i386 */
2877 
2878 void *
2879 device_arena_alloc(size_t size, int vm_flag)
2880 {
2881 	caddr_t	vaddr;
2882 	uintptr_t v;
2883 	size_t	start;
2884 	size_t	end;
2885 
2886 	vaddr = vmem_alloc(heap_arena, size, vm_flag);
2887 	if (vaddr == NULL)
2888 		return (NULL);
2889 
2890 	v = (uintptr_t)vaddr;
2891 	ASSERT(v >= kernelbase);
2892 	ASSERT(v + size <= valloc_base);
2893 
2894 	start = btop(v - kernelbase);
2895 	end = btop(v + size - 1 - kernelbase);
2896 	ASSERT(start < toxic_bit_map_len);
2897 	ASSERT(end < toxic_bit_map_len);
2898 
2899 	while (start <= end) {
2900 		BT_ATOMIC_SET(toxic_bit_map, start);
2901 		++start;
2902 	}
2903 	return (vaddr);
2904 }
2905 
2906 void
2907 device_arena_free(void *vaddr, size_t size)
2908 {
2909 	uintptr_t v = (uintptr_t)vaddr;
2910 	size_t	start;
2911 	size_t	end;
2912 
2913 	ASSERT(v >= kernelbase);
2914 	ASSERT(v + size <= valloc_base);
2915 
2916 	start = btop(v - kernelbase);
2917 	end = btop(v + size - 1 - kernelbase);
2918 	ASSERT(start < toxic_bit_map_len);
2919 	ASSERT(end < toxic_bit_map_len);
2920 
2921 	while (start <= end) {
2922 		ASSERT(BT_TEST(toxic_bit_map, start) != 0);
2923 		BT_ATOMIC_CLEAR(toxic_bit_map, start);
2924 		++start;
2925 	}
2926 	vmem_free(heap_arena, vaddr, size);
2927 }
2928 
2929 /*
2930  * returns 1st address in range that is in device arena, or NULL
2931  * if len is not NULL it returns the length of the toxic range
2932  */
2933 void *
2934 device_arena_contains(void *vaddr, size_t size, size_t *len)
2935 {
2936 	uintptr_t v = (uintptr_t)vaddr;
2937 	uintptr_t eaddr = v + size;
2938 	size_t start;
2939 	size_t end;
2940 
2941 	/*
2942 	 * if called very early by kmdb, just return NULL
2943 	 */
2944 	if (toxic_bit_map == NULL)
2945 		return (NULL);
2946 
2947 	/*
2948 	 * First check if we're completely outside the bitmap range.
2949 	 */
2950 	if (v >= valloc_base || eaddr < kernelbase)
2951 		return (NULL);
2952 
2953 	/*
2954 	 * Trim ends of search to look at only what the bitmap covers.
2955 	 */
2956 	if (v < kernelbase)
2957 		v = kernelbase;
2958 	start = btop(v - kernelbase);
2959 	end = btop(eaddr - kernelbase);
2960 	if (end >= toxic_bit_map_len)
2961 		end = toxic_bit_map_len;
2962 
2963 	if (bt_range(toxic_bit_map, &start, &end, end) == 0)
2964 		return (NULL);
2965 
2966 	v = kernelbase + ptob(start);
2967 	if (len != NULL)
2968 		*len = ptob(end - start);
2969 	return ((void *)v);
2970 }
2971 
2972 #endif	/* __i386 */
2973