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