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