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