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