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