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