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