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