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