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