xref: /titanic_44/usr/src/uts/i86pc/os/startup.c (revision a0965f35d4137b1f6bb1655ae1cb8fee88dfa66f)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/t_lock.h>
31 #include <sys/param.h>
32 #include <sys/sysmacros.h>
33 #include <sys/signal.h>
34 #include <sys/systm.h>
35 #include <sys/user.h>
36 #include <sys/mman.h>
37 #include <sys/vm.h>
38 #include <sys/conf.h>
39 #include <sys/avintr.h>
40 #include <sys/autoconf.h>
41 #include <sys/disp.h>
42 #include <sys/class.h>
43 #include <sys/bitmap.h>
44 
45 #include <sys/privregs.h>
46 
47 #include <sys/proc.h>
48 #include <sys/buf.h>
49 #include <sys/kmem.h>
50 #include <sys/kstat.h>
51 
52 #include <sys/reboot.h>
53 #include <sys/uadmin.h>
54 
55 #include <sys/cred.h>
56 #include <sys/vnode.h>
57 #include <sys/file.h>
58 
59 #include <sys/procfs.h>
60 #include <sys/acct.h>
61 
62 #include <sys/vfs.h>
63 #include <sys/dnlc.h>
64 #include <sys/var.h>
65 #include <sys/cmn_err.h>
66 #include <sys/utsname.h>
67 #include <sys/debug.h>
68 #include <sys/kdi.h>
69 
70 #include <sys/dumphdr.h>
71 #include <sys/bootconf.h>
72 #include <sys/varargs.h>
73 #include <sys/promif.h>
74 #include <sys/prom_emul.h>	/* for create_prom_prop */
75 #include <sys/modctl.h>		/* for "procfs" hack */
76 
77 #include <sys/consdev.h>
78 #include <sys/frame.h>
79 
80 #include <sys/sunddi.h>
81 #include <sys/sunndi.h>
82 #include <sys/ndi_impldefs.h>
83 #include <sys/ddidmareq.h>
84 #include <sys/psw.h>
85 #include <sys/regset.h>
86 #include <sys/clock.h>
87 #include <sys/pte.h>
88 #include <sys/mmu.h>
89 #include <sys/tss.h>
90 #include <sys/stack.h>
91 #include <sys/trap.h>
92 #include <sys/pic.h>
93 #include <sys/fp.h>
94 #include <vm/anon.h>
95 #include <vm/as.h>
96 #include <vm/page.h>
97 #include <vm/seg.h>
98 #include <vm/seg_dev.h>
99 #include <vm/seg_kmem.h>
100 #include <vm/seg_kpm.h>
101 #include <vm/seg_map.h>
102 #include <vm/seg_vn.h>
103 #include <vm/seg_kp.h>
104 #include <sys/memnode.h>
105 #include <vm/vm_dep.h>
106 #include <sys/swap.h>
107 #include <sys/thread.h>
108 #include <sys/sysconf.h>
109 #include <sys/vm_machparam.h>
110 #include <sys/archsystm.h>
111 #include <sys/machsystm.h>
112 #include <vm/hat.h>
113 #include <vm/hat_i86.h>
114 #include <sys/pmem.h>
115 #include <sys/instance.h>
116 #include <sys/smp_impldefs.h>
117 #include <sys/x86_archext.h>
118 #include <sys/segments.h>
119 #include <sys/clconf.h>
120 #include <sys/kobj.h>
121 #include <sys/kobj_lex.h>
122 #include <sys/prom_emul.h>
123 #include <sys/cpc_impl.h>
124 #include <sys/chip.h>
125 #include <sys/x86_archext.h>
126 #include <sys/smbios.h>
127 
128 extern void progressbar_init(void);
129 extern void progressbar_start(void);
130 
131 /*
132  * XXX make declaration below "static" when drivers no longer use this
133  * interface.
134  */
135 extern caddr_t p0_va;	/* Virtual address for accessing physical page 0 */
136 
137 /*
138  * segkp
139  */
140 extern int segkp_fromheap;
141 
142 static void kvm_init(void);
143 static void startup_init(void);
144 static void startup_memlist(void);
145 static void startup_modules(void);
146 static void startup_bop_gone(void);
147 static void startup_vm(void);
148 static void startup_end(void);
149 
150 /*
151  * Declare these as initialized data so we can patch them.
152  */
153 pgcnt_t physmem = 0;	/* memory size in pages, patch if you want less */
154 pgcnt_t obp_pages;	/* Memory used by PROM for its text and data */
155 
156 char *kobj_file_buf;
157 int kobj_file_bufsize;	/* set in /etc/system */
158 
159 /* Global variables for MP support. Used in mp_startup */
160 caddr_t	rm_platter_va;
161 uint32_t rm_platter_pa;
162 
163 int	auto_lpg_disable = 1;
164 
165 /*
166  * Some CPUs have holes in the middle of the 64-bit virtual address range.
167  */
168 uintptr_t hole_start, hole_end;
169 
170 /*
171  * kpm mapping window
172  */
173 caddr_t kpm_vbase;
174 size_t  kpm_size;
175 static int kpm_desired = 0;		/* Do we want to try to use segkpm? */
176 
177 /*
178  * VA range that must be preserved for boot until we release all of its
179  * mappings.
180  */
181 #if defined(__amd64)
182 static void *kmem_setaside;
183 #endif
184 
185 /*
186  * Configuration parameters set at boot time.
187  */
188 
189 caddr_t econtig;		/* end of first block of contiguous kernel */
190 
191 struct bootops		*bootops = 0;	/* passed in from boot */
192 struct bootops		**bootopsp;
193 struct boot_syscalls	*sysp;		/* passed in from boot */
194 
195 char bootblock_fstype[16];
196 
197 char kern_bootargs[OBP_MAXPATHLEN];
198 
199 /*
200  * new memory fragmentations are possible in startup() due to BOP_ALLOCs. this
201  * depends on number of BOP_ALLOC calls made and requested size, memory size
202  * combination and whether boot.bin memory needs to be freed.
203  */
204 #define	POSS_NEW_FRAGMENTS	12
205 
206 /*
207  * VM data structures
208  */
209 long page_hashsz;		/* Size of page hash table (power of two) */
210 struct page *pp_base;		/* Base of initial system page struct array */
211 struct page **page_hash;	/* Page hash table */
212 struct seg ktextseg;		/* Segment used for kernel executable image */
213 struct seg kvalloc;		/* Segment used for "valloc" mapping */
214 struct seg kpseg;		/* Segment used for pageable kernel virt mem */
215 struct seg kmapseg;		/* Segment used for generic kernel mappings */
216 struct seg kdebugseg;		/* Segment used for the kernel debugger */
217 
218 struct seg *segkmap = &kmapseg;	/* Kernel generic mapping segment */
219 struct seg *segkp = &kpseg;	/* Pageable kernel virtual memory segment */
220 
221 #if defined(__amd64)
222 struct seg kvseg_core;		/* Segment used for the core heap */
223 struct seg kpmseg;		/* Segment used for physical mapping */
224 struct seg *segkpm = &kpmseg;	/* 64bit kernel physical mapping segment */
225 #else
226 struct seg *segkpm = NULL;	/* Unused on IA32 */
227 #endif
228 
229 caddr_t segkp_base;		/* Base address of segkp */
230 #if defined(__amd64)
231 pgcnt_t segkpsize = btop(SEGKPDEFSIZE);	/* size of segkp segment in pages */
232 #else
233 pgcnt_t segkpsize = 0;
234 #endif
235 
236 struct memseg *memseg_base;
237 struct vnode unused_pages_vp;
238 
239 #define	FOURGB	0x100000000LL
240 
241 struct memlist *memlist;
242 
243 caddr_t s_text;		/* start of kernel text segment */
244 caddr_t e_text;		/* end of kernel text segment */
245 caddr_t s_data;		/* start of kernel data segment */
246 caddr_t e_data;		/* end of kernel data segment */
247 caddr_t modtext;	/* start of loadable module text reserved */
248 caddr_t e_modtext;	/* end of loadable module text reserved */
249 caddr_t moddata;	/* start of loadable module data reserved */
250 caddr_t e_moddata;	/* end of loadable module data reserved */
251 
252 struct memlist *phys_install;	/* Total installed physical memory */
253 struct memlist *phys_avail;	/* Total available physical memory */
254 
255 static void memlist_add(uint64_t, uint64_t, struct memlist *,
256 	struct memlist **);
257 
258 /*
259  * kphysm_init returns the number of pages that were processed
260  */
261 static pgcnt_t kphysm_init(page_t *, struct memseg *, pgcnt_t, pgcnt_t);
262 
263 #define	IO_PROP_SIZE	64	/* device property size */
264 
265 /*
266  * a couple useful roundup macros
267  */
268 #define	ROUND_UP_PAGE(x)	\
269 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), (uintptr_t)MMU_PAGESIZE))
270 #define	ROUND_UP_LPAGE(x)	\
271 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), mmu.level_size[1]))
272 #define	ROUND_UP_4MEG(x)	\
273 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), (uintptr_t)FOURMB_PAGESIZE))
274 #define	ROUND_UP_TOPLEVEL(x)	\
275 	((uintptr_t)P2ROUNDUP((uintptr_t)(x), mmu.level_size[mmu.max_level]))
276 
277 /*
278  *	32-bit Kernel's Virtual memory layout.
279  *		+-----------------------+
280  *		|	psm 1-1 map	|
281  *		|	exec args area	|
282  * 0xFFC00000  -|-----------------------|- ARGSBASE
283  *		|	debugger	|
284  * 0xFF800000  -|-----------------------|- SEGDEBUGBASE
285  *		|      Kernel Data	|
286  * 0xFEC00000  -|-----------------------|
287  *              |      Kernel Text	|
288  * 0xFE800000  -|-----------------------|- KERNEL_TEXT
289  * 		|     LUFS sinkhole	|
290  * 0xFE000000  -|-----------------------|- lufs_addr
291  * ---         -|-----------------------|- valloc_base + valloc_sz
292  * 		|   early pp structures	|
293  * 		|   memsegs, memlists, 	|
294  * 		|   page hash, etc.	|
295  * ---	       -|-----------------------|- valloc_base (floating)
296  * 		|     ptable_va    	|
297  * 0xFDFFE000  -|-----------------------|- ekernelheap, ptable_va
298  *		|			|  (segkp is an arena under the heap)
299  *		|			|
300  *		|	kvseg		|
301  *		|			|
302  *		|			|
303  * ---         -|-----------------------|- kernelheap (floating)
304  * 		|        Segkmap	|
305  * 0xC3002000  -|-----------------------|- segkmap_start (floating)
306  *		|	Red Zone	|
307  * 0xC3000000  -|-----------------------|- kernelbase / userlimit (floating)
308  *		|			|			||
309  *		|     Shared objects	|			\/
310  *		|			|
311  *		:			:
312  *		|	user data	|
313  *		|-----------------------|
314  *		|	user text	|
315  * 0x08048000  -|-----------------------|
316  *		|	user stack	|
317  *		:			:
318  *		|	invalid		|
319  * 0x00000000	+-----------------------+
320  *
321  *
322  *		64-bit Kernel's Virtual memory layout. (assuming 64 bit app)
323  *			+-----------------------+
324  *			|	psm 1-1 map	|
325  *			|	exec args area	|
326  * 0xFFFFFFFF.FFC00000  |-----------------------|- ARGSBASE
327  *			|	debugger (?)	|
328  * 0xFFFFFFFF.FF800000  |-----------------------|- SEGDEBUGBASE
329  *			|      unused    	|
330  *			+-----------------------+
331  *			|      Kernel Data	|
332  * 0xFFFFFFFF.FBC00000  |-----------------------|
333  *			|      Kernel Text	|
334  * 0xFFFFFFFF.FB800000  |-----------------------|- KERNEL_TEXT
335  * 			|     LUFS sinkhole	|
336  * 0xFFFFFFFF.FB000000 -|-----------------------|- lufs_addr
337  * ---                  |-----------------------|- valloc_base + valloc_sz
338  * 			|   early pp structures	|
339  * 			|   memsegs, memlists, 	|
340  * 			|   page hash, etc.	|
341  * ---                  |-----------------------|- valloc_base
342  * 			|     ptable_va    	|
343  * ---                  |-----------------------|- ptable_va
344  * 			|      Core heap	| (used for loadable modules)
345  * 0xFFFFFFFF.C0000000  |-----------------------|- core_base / ekernelheap
346  *			|	 Kernel		|
347  *			|	  heap		|
348  * 0xFFFFFXXX.XXX00000  |-----------------------|- kernelheap (floating)
349  *			|	 segkmap	|
350  * 0xFFFFFXXX.XXX00000  |-----------------------|- segkmap_start (floating)
351  *			|    device mappings	|
352  * 0xFFFFFXXX.XXX00000  |-----------------------|- toxic_addr (floating)
353  *			|	  segkp		|
354  * ---                  |-----------------------|- segkp_base
355  *			|	 segkpm		|
356  * 0xFFFFFE00.00000000  |-----------------------|
357  *			|	Red Zone	|
358  * 0xFFFFFD80.00000000  |-----------------------|- KERNELBASE
359  *			|     User stack	|- User space memory
360  * 			|			|
361  * 			| shared objects, etc	|	(grows downwards)
362  *			:			:
363  * 			|			|
364  * 0xFFFF8000.00000000  |-----------------------|
365  * 			|			|
366  * 			| VA Hole / unused	|
367  * 			|			|
368  * 0x00008000.00000000  |-----------------------|
369  *			|			|
370  *			|			|
371  *			:			:
372  *			|	user heap	|	(grows upwards)
373  *			|			|
374  *			|	user data	|
375  *			|-----------------------|
376  *			|	user text	|
377  * 0x00000000.04000000  |-----------------------|
378  *			|	invalid		|
379  * 0x00000000.00000000	+-----------------------+
380  *
381  * A 32 bit app on the 64 bit kernel sees the same layout as on the 32 bit
382  * kernel, except that userlimit is raised to 0xfe000000
383  *
384  * Floating values:
385  *
386  * valloc_base: start of the kernel's memory management/tracking data
387  * structures.  This region contains page_t structures for the lowest 4GB
388  * of physical memory, memsegs, memlists, and the page hash.
389  *
390  * core_base: start of the kernel's "core" heap area on 64-bit systems.
391  * This area is intended to be used for global data as well as for module
392  * text/data that does not fit into the nucleus pages.  The core heap is
393  * restricted to a 2GB range, allowing every address within it to be
394  * accessed using rip-relative addressing
395  *
396  * ekernelheap: end of kernelheap and start of segmap.
397  *
398  * kernelheap: start of kernel heap.  On 32-bit systems, this starts right
399  * above a red zone that separates the user's address space from the
400  * kernel's.  On 64-bit systems, it sits above segkp and segkpm.
401  *
402  * segkmap_start: start of segmap. The length of segmap can be modified
403  * by changing segmapsize in /etc/system (preferred) or eeprom (deprecated).
404  * The default length is 16MB on 32-bit systems and 64MB on 64-bit systems.
405  *
406  * kernelbase: On a 32-bit kernel the default value of 0xd4000000 will be
407  * decreased by 2X the size required for page_t.  This allows the kernel
408  * heap to grow in size with physical memory.  With sizeof(page_t) == 80
409  * bytes, the following shows the values of kernelbase and kernel heap
410  * sizes for different memory configurations (assuming default segmap and
411  * segkp sizes).
412  *
413  *	mem	size for	kernelbase	kernel heap
414  *	size	page_t's			size
415  *	----	---------	----------	-----------
416  *	1gb	0x01400000	0xd1800000	684MB
417  *	2gb	0x02800000	0xcf000000	704MB
418  *	4gb	0x05000000	0xca000000	744MB
419  *	6gb	0x07800000	0xc5000000	784MB
420  *	8gb	0x0a000000	0xc0000000	824MB
421  *	16gb	0x14000000	0xac000000	984MB
422  *	32gb	0x28000000	0x84000000	1304MB
423  *	64gb	0x50000000	0x34000000	1944MB (*)
424  *
425  * kernelbase is less than the abi minimum of 0xc0000000 for memory
426  * configurations above 8gb.
427  *
428  * (*) support for memory configurations above 32gb will require manual tuning
429  * of kernelbase to balance out the need of user applications.
430  */
431 
432 void init_intr_threads(struct cpu *);
433 
434 /* real-time-clock initialization parameters */
435 long gmt_lag;		/* offset in seconds of gmt to local time */
436 extern long process_rtc_config_file(void);
437 
438 char		*final_kernelheap;
439 char		*boot_kernelheap;
440 uintptr_t	kernelbase;
441 uintptr_t	eprom_kernelbase;
442 size_t		segmapsize;
443 static uintptr_t segmap_reserved;
444 uintptr_t	segkmap_start;
445 int		segmapfreelists;
446 pgcnt_t		boot_npages;
447 pgcnt_t		npages;
448 size_t		core_size;		/* size of "core" heap */
449 uintptr_t	core_base;		/* base address of "core" heap */
450 
451 /*
452  * List of bootstrap pages. We mark these as allocated in startup.
453  * release_bootstrap() will free them when we're completely done with
454  * the bootstrap.
455  */
456 static page_t *bootpages, *rd_pages;
457 
458 struct system_hardware system_hardware;
459 
460 /*
461  * Enable some debugging messages concerning memory usage...
462  *
463  * XX64 There should only be one print routine once memlist usage between
464  * vmx and the kernel is cleaned up and there is a single memlist structure
465  * shared between kernel and boot.
466  */
467 static void
468 print_boot_memlist(char *title, struct memlist *mp)
469 {
470 	prom_printf("MEMLIST: %s:\n", title);
471 	while (mp != NULL)  {
472 		prom_printf("\tAddress 0x%" PRIx64 ", size 0x%" PRIx64 "\n",
473 		    mp->address, mp->size);
474 		mp = mp->next;
475 	}
476 }
477 
478 static void
479 print_kernel_memlist(char *title, struct memlist *mp)
480 {
481 	prom_printf("MEMLIST: %s:\n", title);
482 	while (mp != NULL)  {
483 		prom_printf("\tAddress 0x%" PRIx64 ", size 0x%" PRIx64 "\n",
484 		    mp->address, mp->size);
485 		mp = mp->next;
486 	}
487 }
488 
489 /*
490  * XX64 need a comment here.. are these just default values, surely
491  * we read the "cpuid" type information to figure this out.
492  */
493 int	l2cache_sz = 0x80000;
494 int	l2cache_linesz = 0x40;
495 int	l2cache_assoc = 1;
496 
497 /*
498  * on 64 bit we use a predifined VA range for mapping devices in the kernel
499  * on 32 bit the mappings are intermixed in the heap, so we use a bit map
500  */
501 #ifdef __amd64
502 
503 vmem_t		*device_arena;
504 uintptr_t	toxic_addr = (uintptr_t)NULL;
505 size_t		toxic_size = 1 * 1024 * 1024 * 1024; /* Sparc uses 1 gig too */
506 
507 #else	/* __i386 */
508 
509 ulong_t		*toxic_bit_map;	/* one bit for each 4k of VA in heap_arena */
510 size_t		toxic_bit_map_len = 0;	/* in bits */
511 
512 #endif	/* __i386 */
513 
514 /*
515  * Simple boot time debug facilities
516  */
517 static char *prm_dbg_str[] = {
518 	"%s:%d: '%s' is 0x%x\n",
519 	"%s:%d: '%s' is 0x%llx\n"
520 };
521 
522 int prom_debug;
523 
524 #define	PRM_DEBUG(q)	if (prom_debug) 	\
525 	prom_printf(prm_dbg_str[sizeof (q) >> 3], "startup.c", __LINE__, #q, q);
526 #define	PRM_POINT(q)	if (prom_debug) 	\
527 	prom_printf("%s:%d: %s\n", "startup.c", __LINE__, q);
528 
529 /*
530  * This structure is used to keep track of the intial allocations
531  * done in startup_memlist(). The value of NUM_ALLOCATIONS needs to
532  * be >= the number of ADD_TO_ALLOCATIONS() executed in the code.
533  */
534 #define	NUM_ALLOCATIONS 7
535 int num_allocations = 0;
536 struct {
537 	void **al_ptr;
538 	size_t al_size;
539 } allocations[NUM_ALLOCATIONS];
540 size_t valloc_sz = 0;
541 uintptr_t valloc_base;
542 extern uintptr_t ptable_va;
543 extern size_t ptable_sz;
544 
545 #define	ADD_TO_ALLOCATIONS(ptr, size) {					\
546 		size = ROUND_UP_PAGE(size);		 		\
547 		if (num_allocations == NUM_ALLOCATIONS)			\
548 			panic("too many ADD_TO_ALLOCATIONS()");		\
549 		allocations[num_allocations].al_ptr = (void**)&ptr;	\
550 		allocations[num_allocations].al_size = size;		\
551 		valloc_sz += size;					\
552 		++num_allocations;				 	\
553 	}
554 
555 static void
556 perform_allocations(void)
557 {
558 	caddr_t mem;
559 	int i;
560 
561 	mem = BOP_ALLOC(bootops, (caddr_t)valloc_base, valloc_sz, BO_NO_ALIGN);
562 	if (mem != (caddr_t)valloc_base)
563 		panic("BOP_ALLOC() failed");
564 	bzero(mem, valloc_sz);
565 	for (i = 0; i < num_allocations; ++i) {
566 		*allocations[i].al_ptr = (void *)mem;
567 		mem += allocations[i].al_size;
568 	}
569 }
570 
571 /*
572  * Our world looks like this at startup time.
573  *
574  * In a 32-bit OS, boot loads the kernel text at 0xfe800000 and kernel data
575  * at 0xfec00000.  On a 64-bit OS, kernel text and data are loaded at
576  * 0xffffffff.fe800000 and 0xffffffff.fec00000 respectively.  Those
577  * addresses are fixed in the binary at link time.
578  *
579  * On the text page:
580  * unix/genunix/krtld/module text loads.
581  *
582  * On the data page:
583  * unix/genunix/krtld/module data loads and space for page_t's.
584  */
585 /*
586  * Machine-dependent startup code
587  */
588 void
589 startup(void)
590 {
591 	extern void startup_bios_disk();
592 	/*
593 	 * Make sure that nobody tries to use sekpm until we have
594 	 * initialized it properly.
595 	 */
596 #if defined(__amd64)
597 	kpm_desired = kpm_enable;
598 #endif
599 	kpm_enable = 0;
600 
601 	progressbar_init();
602 	startup_init();
603 	startup_memlist();
604 	startup_modules();
605 	startup_bios_disk();
606 	startup_bop_gone();
607 	startup_vm();
608 	startup_end();
609 	progressbar_start();
610 }
611 
612 static void
613 startup_init()
614 {
615 	PRM_POINT("startup_init() starting...");
616 
617 	/*
618 	 * Complete the extraction of cpuid data
619 	 */
620 	cpuid_pass2(CPU);
621 
622 	(void) check_boot_version(BOP_GETVERSION(bootops));
623 
624 	/*
625 	 * Check for prom_debug in boot environment
626 	 */
627 	if (BOP_GETPROPLEN(bootops, "prom_debug") >= 0) {
628 		++prom_debug;
629 		PRM_POINT("prom_debug found in boot enviroment");
630 	}
631 
632 	/*
633 	 * Collect node, cpu and memory configuration information.
634 	 */
635 	get_system_configuration();
636 
637 	/*
638 	 * Halt if this is an unsupported processor.
639 	 */
640 	if (x86_type == X86_TYPE_486 || x86_type == X86_TYPE_CYRIX_486) {
641 		printf("\n486 processor (\"%s\") detected.\n",
642 		    CPU->cpu_brandstr);
643 		halt("This processor is not supported by this release "
644 		    "of Solaris.");
645 	}
646 
647 	PRM_POINT("startup_init() done");
648 }
649 
650 /*
651  * Callback for copy_memlist_filter() to filter nucleus, kadb/kmdb, (ie.
652  * everything mapped above KERNEL_TEXT) pages from phys_avail. Note it
653  * also filters out physical page zero.  There is some reliance on the
654  * boot loader allocating only a few contiguous physical memory chunks.
655  */
656 static void
657 avail_filter(uint64_t *addr, uint64_t *size)
658 {
659 	uintptr_t va;
660 	uintptr_t next_va;
661 	pfn_t pfn;
662 	uint64_t pfn_addr;
663 	uint64_t pfn_eaddr;
664 	uint_t prot;
665 	size_t len;
666 	uint_t change;
667 
668 	if (prom_debug)
669 		prom_printf("\tFilter: in: a=%" PRIx64 ", s=%" PRIx64 "\n",
670 		    *addr, *size);
671 
672 	/*
673 	 * page zero is required for BIOS.. never make it available
674 	 */
675 	if (*addr == 0) {
676 		*addr += MMU_PAGESIZE;
677 		*size -= MMU_PAGESIZE;
678 	}
679 
680 	/*
681 	 * First we trim from the front of the range. Since hat_boot_probe()
682 	 * walks ranges in virtual order, but addr/size are physical, we need
683 	 * to the list until no changes are seen.  This deals with the case
684 	 * where page "p" is mapped at v, page "p + PAGESIZE" is mapped at w
685 	 * but w < v.
686 	 */
687 	do {
688 		change = 0;
689 		for (va = KERNEL_TEXT;
690 		    *size > 0 && hat_boot_probe(&va, &len, &pfn, &prot) != 0;
691 		    va = next_va) {
692 
693 			next_va = va + len;
694 			pfn_addr = ptob((uint64_t)pfn);
695 			pfn_eaddr = pfn_addr + len;
696 
697 			if (pfn_addr <= *addr && pfn_eaddr > *addr) {
698 				change = 1;
699 				while (*size > 0 && len > 0) {
700 					*addr += MMU_PAGESIZE;
701 					*size -= MMU_PAGESIZE;
702 					len -= MMU_PAGESIZE;
703 				}
704 			}
705 		}
706 		if (change && prom_debug)
707 			prom_printf("\t\ttrim: a=%" PRIx64 ", s=%" PRIx64 "\n",
708 			    *addr, *size);
709 	} while (change);
710 
711 	/*
712 	 * Trim pages from the end of the range.
713 	 */
714 	for (va = KERNEL_TEXT;
715 	    *size > 0 && hat_boot_probe(&va, &len, &pfn, &prot) != 0;
716 	    va = next_va) {
717 
718 		next_va = va + len;
719 		pfn_addr = ptob((uint64_t)pfn);
720 
721 		if (pfn_addr >= *addr && pfn_addr < *addr + *size)
722 			*size = pfn_addr - *addr;
723 	}
724 
725 	if (prom_debug)
726 		prom_printf("\tFilter out: a=%" PRIx64 ", s=%" PRIx64 "\n",
727 		    *addr, *size);
728 }
729 
730 static void
731 kpm_init()
732 {
733 	struct segkpm_crargs b;
734 	uintptr_t start, end;
735 	struct memlist	*pmem;
736 
737 	/*
738 	 * These variables were all designed for sfmmu in which segkpm is
739 	 * mapped using a single pagesize - either 8KB or 4MB.  On x86, we
740 	 * might use 2+ page sizes on a single machine, so none of these
741 	 * variables have a single correct value.  They are set up as if we
742 	 * always use a 4KB pagesize, which should do no harm.  In the long
743 	 * run, we should get rid of KPM's assumption that only a single
744 	 * pagesize is used.
745 	 */
746 	kpm_pgshft = MMU_PAGESHIFT;
747 	kpm_pgsz =  MMU_PAGESIZE;
748 	kpm_pgoff = MMU_PAGEOFFSET;
749 	kpmp2pshft = 0;
750 	kpmpnpgs = 1;
751 	ASSERT(((uintptr_t)kpm_vbase & (kpm_pgsz - 1)) == 0);
752 
753 	PRM_POINT("about to create segkpm");
754 	rw_enter(&kas.a_lock, RW_WRITER);
755 
756 	if (seg_attach(&kas, kpm_vbase, kpm_size, segkpm) < 0)
757 		panic("cannot attach segkpm");
758 
759 	b.prot = PROT_READ | PROT_WRITE;
760 	b.nvcolors = 1;
761 
762 	if (segkpm_create(segkpm, (caddr_t)&b) != 0)
763 		panic("segkpm_create segkpm");
764 
765 	rw_exit(&kas.a_lock);
766 
767 	/*
768 	 * Map each of the memsegs into the kpm segment, coalesing adjacent
769 	 * memsegs to allow mapping with the largest possible pages.
770 	 */
771 	pmem = phys_install;
772 	start = pmem->address;
773 	end = start + pmem->size;
774 	for (;;) {
775 		if (pmem == NULL || pmem->address > end) {
776 			hat_devload(kas.a_hat, kpm_vbase + start,
777 			    end - start, mmu_btop(start),
778 			    PROT_READ | PROT_WRITE,
779 			    HAT_LOAD | HAT_LOAD_LOCK | HAT_LOAD_NOCONSIST);
780 			if (pmem == NULL)
781 				break;
782 			start = pmem->address;
783 		}
784 		end = pmem->address + pmem->size;
785 		pmem = pmem->next;
786 	}
787 }
788 
789 /*
790  * The purpose of startup memlist is to get the system to the
791  * point where it can use kmem_alloc()'s that operate correctly
792  * relying on BOP_ALLOC(). This includes allocating page_ts,
793  * page hash table, vmem initialized, etc.
794  *
795  * Boot's versions of physinstalled and physavail are insufficient for
796  * the kernel's purposes. Specifically we don't know which pages that
797  * are not in physavail can be reclaimed after boot is gone.
798  *
799  * This code solves the problem by dividing the address space
800  * into 3 regions as it takes over the MMU from the booter.
801  *
802  * 1) Any (non-nucleus) pages that are mapped at addresses above KERNEL_TEXT
803  * can not be used by the kernel.
804  *
805  * 2) Any free page that happens to be mapped below kernelbase
806  * is protected until the boot loader is released, but will then be reclaimed.
807  *
808  * 3) Boot shouldn't use any address in the remaining area between kernelbase
809  * and KERNEL_TEXT.
810  *
811  * In the case of multiple mappings to the same page, region 1 has precedence
812  * over region 2.
813  */
814 static void
815 startup_memlist(void)
816 {
817 	size_t memlist_sz;
818 	size_t memseg_sz;
819 	size_t pagehash_sz;
820 	size_t pp_sz;
821 	uintptr_t va;
822 	size_t len;
823 	uint_t prot;
824 	pfn_t pfn;
825 	int memblocks;
826 	caddr_t pagecolor_mem;
827 	size_t pagecolor_memsz;
828 	caddr_t page_ctrs_mem;
829 	size_t page_ctrs_size;
830 	struct memlist *current;
831 	extern void startup_build_mem_nodes(struct memlist *);
832 
833 	/* XX64 fix these - they should be in include files */
834 	extern ulong_t cr4_value;
835 	extern size_t page_coloring_init(uint_t, int, int);
836 	extern void page_coloring_setup(caddr_t);
837 
838 	PRM_POINT("startup_memlist() starting...");
839 
840 	/*
841 	 * Take the most current snapshot we can by calling mem-update.
842 	 * For this to work properly, we first have to ask boot for its
843 	 * end address.
844 	 */
845 	if (BOP_GETPROPLEN(bootops, "memory-update") == 0)
846 		(void) BOP_GETPROP(bootops, "memory-update", NULL);
847 
848 	/*
849 	 * find if the kernel is mapped on a large page
850 	 */
851 	va = KERNEL_TEXT;
852 	if (hat_boot_probe(&va, &len, &pfn, &prot) == 0)
853 		panic("Couldn't find kernel text boot mapping");
854 
855 	/*
856 	 * Use leftover large page nucleus text/data space for loadable modules.
857 	 * Use at most MODTEXT/MODDATA.
858 	 */
859 	if (len > MMU_PAGESIZE) {
860 
861 		moddata = (caddr_t)ROUND_UP_PAGE(e_data);
862 		e_moddata = (caddr_t)ROUND_UP_4MEG(e_data);
863 		if (e_moddata - moddata > MODDATA)
864 			e_moddata = moddata + MODDATA;
865 
866 		modtext = (caddr_t)ROUND_UP_PAGE(e_text);
867 		e_modtext = (caddr_t)ROUND_UP_4MEG(e_text);
868 		if (e_modtext - modtext > MODTEXT)
869 			e_modtext = modtext + MODTEXT;
870 
871 
872 	} else {
873 
874 		PRM_POINT("Kernel NOT loaded on Large Page!");
875 		e_moddata = moddata = (caddr_t)ROUND_UP_PAGE(e_data);
876 		e_modtext = modtext = (caddr_t)ROUND_UP_PAGE(e_text);
877 
878 	}
879 	econtig = e_moddata;
880 
881 	PRM_DEBUG(modtext);
882 	PRM_DEBUG(e_modtext);
883 	PRM_DEBUG(moddata);
884 	PRM_DEBUG(e_moddata);
885 	PRM_DEBUG(econtig);
886 
887 	/*
888 	 * For MP machines cr4_value must be set or the non-boot
889 	 * CPUs will not be able to start.
890 	 */
891 	if (x86_feature & X86_LARGEPAGE)
892 		cr4_value = getcr4();
893 	PRM_DEBUG(cr4_value);
894 
895 	/*
896 	 * Examine the boot loaders physical memory map to find out:
897 	 * - total memory in system - physinstalled
898 	 * - the max physical address - physmax
899 	 * - the number of segments the intsalled memory comes in
900 	 */
901 	if (prom_debug)
902 		print_boot_memlist("boot physinstalled",
903 		    bootops->boot_mem->physinstalled);
904 	installed_top_size(bootops->boot_mem->physinstalled, &physmax,
905 	    &physinstalled, &memblocks);
906 	PRM_DEBUG(physmax);
907 	PRM_DEBUG(physinstalled);
908 	PRM_DEBUG(memblocks);
909 
910 	if (prom_debug)
911 		print_boot_memlist("boot physavail",
912 		    bootops->boot_mem->physavail);
913 
914 	/*
915 	 * Initialize hat's mmu parameters.
916 	 * Check for enforce-prot-exec in boot environment. It's used to
917 	 * enable/disable support for the page table entry NX bit.
918 	 * The default is to enforce PROT_EXEC on processors that support NX.
919 	 * Boot seems to round up the "len", but 8 seems to be big enough.
920 	 */
921 	mmu_init();
922 
923 #ifdef	__i386
924 	/*
925 	 * physmax is lowered if there is more memory than can be
926 	 * physically addressed in 32 bit (PAE/non-PAE) modes.
927 	 */
928 	if (mmu.pae_hat) {
929 		if (PFN_ABOVE64G(physmax)) {
930 			physinstalled -= (physmax - (PFN_64G - 1));
931 			physmax = PFN_64G - 1;
932 		}
933 	} else {
934 		if (PFN_ABOVE4G(physmax)) {
935 			physinstalled -= (physmax - (PFN_4G - 1));
936 			physmax = PFN_4G - 1;
937 		}
938 	}
939 #endif
940 
941 	startup_build_mem_nodes(bootops->boot_mem->physinstalled);
942 
943 	if (BOP_GETPROPLEN(bootops, "enforce-prot-exec") >= 0) {
944 		int len = BOP_GETPROPLEN(bootops, "enforce-prot-exec");
945 		char value[8];
946 
947 		if (len < 8)
948 			(void) BOP_GETPROP(bootops, "enforce-prot-exec", value);
949 		else
950 			(void) strcpy(value, "");
951 		if (strcmp(value, "off") == 0)
952 			mmu.pt_nx = 0;
953 	}
954 	PRM_DEBUG(mmu.pt_nx);
955 
956 	/*
957 	 * We will need page_t's for every page in the system, except for
958 	 * memory mapped at or above above the start of the kernel text segment.
959 	 *
960 	 * pages above e_modtext are attributed to kernel debugger (obp_pages)
961 	 */
962 	npages = physinstalled - 1; /* avail_filter() skips page 0, so "- 1" */
963 	obp_pages = 0;
964 	va = KERNEL_TEXT;
965 	while (hat_boot_probe(&va, &len, &pfn, &prot) != 0) {
966 		npages -= len >> MMU_PAGESHIFT;
967 		if (va >= (uintptr_t)e_moddata)
968 			obp_pages += len >> MMU_PAGESHIFT;
969 		va += len;
970 	}
971 	PRM_DEBUG(npages);
972 	PRM_DEBUG(obp_pages);
973 
974 	/*
975 	 * If physmem is patched to be non-zero, use it instead of
976 	 * the computed value unless it is larger than the real
977 	 * amount of memory on hand.
978 	 */
979 	if (physmem == 0 || physmem > npages)
980 		physmem = npages;
981 	else
982 		npages = physmem;
983 	PRM_DEBUG(physmem);
984 
985 	/*
986 	 * We now compute the sizes of all the  initial allocations for
987 	 * structures the kernel needs in order do kmem_alloc(). These
988 	 * include:
989 	 *	memsegs
990 	 *	memlists
991 	 *	page hash table
992 	 *	page_t's
993 	 *	page coloring data structs
994 	 */
995 	memseg_sz = sizeof (struct memseg) * (memblocks + POSS_NEW_FRAGMENTS);
996 	ADD_TO_ALLOCATIONS(memseg_base, memseg_sz);
997 	PRM_DEBUG(memseg_sz);
998 
999 	/*
1000 	 * Reserve space for phys_avail/phys_install memlists.
1001 	 * There's no real good way to know exactly how much room we'll need,
1002 	 * but this should be a good upper bound.
1003 	 */
1004 	memlist_sz = ROUND_UP_PAGE(2 * sizeof (struct memlist) *
1005 	    (memblocks + POSS_NEW_FRAGMENTS));
1006 	ADD_TO_ALLOCATIONS(memlist, memlist_sz);
1007 	PRM_DEBUG(memlist_sz);
1008 
1009 	/*
1010 	 * The page structure hash table size is a power of 2
1011 	 * such that the average hash chain length is PAGE_HASHAVELEN.
1012 	 */
1013 	page_hashsz = npages / PAGE_HASHAVELEN;
1014 	page_hashsz = 1 << highbit(page_hashsz);
1015 	pagehash_sz = sizeof (struct page *) * page_hashsz;
1016 	ADD_TO_ALLOCATIONS(page_hash, pagehash_sz);
1017 	PRM_DEBUG(pagehash_sz);
1018 
1019 	/*
1020 	 * Set aside room for the page structures themselves.  Note: on
1021 	 * 64-bit systems we don't allocate page_t's for every page here.
1022 	 * We just allocate enough to map the lowest 4GB of physical
1023 	 * memory, minus those pages that are used for the "nucleus" kernel
1024 	 * text and data.  The remaining pages are allocated once we can
1025 	 * map around boot.
1026 	 *
1027 	 * boot_npages is used to allocate an area big enough for our
1028 	 * initial page_t's. kphym_init may use less than that.
1029 	 */
1030 	boot_npages = npages;
1031 #if defined(__amd64)
1032 	if (npages > mmu_btop(FOURGB - (econtig - s_text)))
1033 		boot_npages = mmu_btop(FOURGB - (econtig - s_text));
1034 #endif
1035 	PRM_DEBUG(boot_npages);
1036 	pp_sz = sizeof (struct page) * boot_npages;
1037 	ADD_TO_ALLOCATIONS(pp_base, pp_sz);
1038 	PRM_DEBUG(pp_sz);
1039 
1040 	/*
1041 	 * determine l2 cache info and memory size for page coloring
1042 	 */
1043 	(void) getl2cacheinfo(CPU,
1044 	    &l2cache_sz, &l2cache_linesz, &l2cache_assoc);
1045 	pagecolor_memsz =
1046 	    page_coloring_init(l2cache_sz, l2cache_linesz, l2cache_assoc);
1047 	ADD_TO_ALLOCATIONS(pagecolor_mem, pagecolor_memsz);
1048 	PRM_DEBUG(pagecolor_memsz);
1049 
1050 	page_ctrs_size = page_ctrs_sz();
1051 	ADD_TO_ALLOCATIONS(page_ctrs_mem, page_ctrs_size);
1052 	PRM_DEBUG(page_ctrs_size);
1053 
1054 	/*
1055 	 * valloc_base will be below kernel text
1056 	 * The extra pages are for the HAT and kmdb to map page tables.
1057 	 */
1058 	valloc_sz = ROUND_UP_LPAGE(valloc_sz);
1059 	valloc_base = KERNEL_TEXT - valloc_sz;
1060 	PRM_DEBUG(valloc_base);
1061 	ptable_va = valloc_base - ptable_sz;
1062 
1063 #if defined(__amd64)
1064 	if (eprom_kernelbase && eprom_kernelbase != KERNELBASE)
1065 		cmn_err(CE_NOTE, "!kernelbase cannot be changed on 64-bit "
1066 		    "systems.");
1067 	kernelbase = (uintptr_t)KERNELBASE;
1068 	core_base = (uintptr_t)COREHEAP_BASE;
1069 	core_size = ptable_va - core_base;
1070 #else	/* __i386 */
1071 	/*
1072 	 * We configure kernelbase based on:
1073 	 *
1074 	 * 1. user specified kernelbase via eeprom command. Value cannot exceed
1075 	 *    KERNELBASE_MAX. we large page align eprom_kernelbase
1076 	 *
1077 	 * 2. Default to KERNELBASE and adjust to 2X less the size for page_t.
1078 	 *    On large memory systems we must lower kernelbase to allow
1079 	 *    enough room for page_t's for all of memory.
1080 	 *
1081 	 * The value set here, might be changed a little later.
1082 	 */
1083 	if (eprom_kernelbase) {
1084 		kernelbase = eprom_kernelbase & mmu.level_mask[1];
1085 		if (kernelbase > KERNELBASE_MAX)
1086 			kernelbase = KERNELBASE_MAX;
1087 	} else {
1088 		kernelbase = (uintptr_t)KERNELBASE;
1089 		kernelbase -= ROUND_UP_4MEG(2 * valloc_sz);
1090 	}
1091 	ASSERT((kernelbase & mmu.level_offset[1]) == 0);
1092 	core_base = ptable_va;
1093 	core_size = 0;
1094 #endif
1095 
1096 	PRM_DEBUG(kernelbase);
1097 	PRM_DEBUG(core_base);
1098 	PRM_DEBUG(core_size);
1099 
1100 	/*
1101 	 * At this point, we can only use a portion of the kernelheap that
1102 	 * will be available after we boot.  Both 32-bit and 64-bit systems
1103 	 * have this limitation, although the reasons are completely
1104 	 * different.
1105 	 *
1106 	 * On 64-bit systems, the booter only supports allocations in the
1107 	 * upper 4GB of memory, so we have to work with a reduced kernel
1108 	 * heap until we take over all allocations.  The booter also sits
1109 	 * in the lower portion of that 4GB range, so we have to raise the
1110 	 * bottom of the heap even further.
1111 	 *
1112 	 * On 32-bit systems we have to leave room to place segmap below
1113 	 * the heap.  We don't yet know how large segmap will be, so we
1114 	 * have to be very conservative.
1115 	 */
1116 #if defined(__amd64)
1117 	/*
1118 	 * XX64: For now, we let boot have the lower 2GB of the top 4GB
1119 	 * address range.  In the long run, that should be fixed.  It's
1120 	 * insane for a booter to need 2 2GB address ranges.
1121 	 */
1122 	boot_kernelheap = (caddr_t)(BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE);
1123 	segmap_reserved = 0;
1124 
1125 #else	/* __i386 */
1126 	segkp_fromheap = 1;
1127 	segmap_reserved = ROUND_UP_LPAGE(MAX(segmapsize, SEGMAPMAX));
1128 	boot_kernelheap = (caddr_t)(ROUND_UP_LPAGE(kernelbase) +
1129 	    segmap_reserved);
1130 #endif
1131 	PRM_DEBUG(boot_kernelheap);
1132 	kernelheap = boot_kernelheap;
1133 	ekernelheap = (char *)core_base;
1134 
1135 	/*
1136 	 * If segmap is too large we can push the bottom of the kernel heap
1137 	 * higher than the base.  Or worse, it could exceed the top of the
1138 	 * VA space entirely, causing it to wrap around.
1139 	 */
1140 	if (kernelheap >= ekernelheap || (uintptr_t)kernelheap < kernelbase)
1141 		panic("too little memory available for kernelheap,"
1142 			    " use a different kernelbase");
1143 
1144 	/*
1145 	 * Now that we know the real value of kernelbase,
1146 	 * update variables that were initialized with a value of
1147 	 * KERNELBASE (in common/conf/param.c).
1148 	 *
1149 	 * XXX	The problem with this sort of hackery is that the
1150 	 *	compiler just may feel like putting the const declarations
1151 	 *	(in param.c) into the .text section.  Perhaps they should
1152 	 *	just be declared as variables there?
1153 	 */
1154 
1155 #if defined(__amd64)
1156 	ASSERT(_kernelbase == KERNELBASE);
1157 	ASSERT(_userlimit == USERLIMIT);
1158 	/*
1159 	 * As one final sanity check, verify that the "red zone" between
1160 	 * kernel and userspace is exactly the size we expected.
1161 	 */
1162 	ASSERT(_kernelbase == (_userlimit + (2 * 1024 * 1024)));
1163 #else
1164 	*(uintptr_t *)&_kernelbase = kernelbase;
1165 	*(uintptr_t *)&_userlimit = kernelbase;
1166 	*(uintptr_t *)&_userlimit32 = _userlimit;
1167 #endif
1168 	PRM_DEBUG(_kernelbase);
1169 	PRM_DEBUG(_userlimit);
1170 	PRM_DEBUG(_userlimit32);
1171 
1172 	/*
1173 	 * do all the initial allocations
1174 	 */
1175 	perform_allocations();
1176 
1177 	/*
1178 	 * Initialize the kernel heap. Note 3rd argument must be > 1st.
1179 	 */
1180 	kernelheap_init(kernelheap, ekernelheap, kernelheap + MMU_PAGESIZE,
1181 	    (void *)core_base, (void *)ptable_va);
1182 
1183 	/*
1184 	 * Build phys_install and phys_avail in kernel memspace.
1185 	 * - phys_install should be all memory in the system.
1186 	 * - phys_avail is phys_install minus any memory mapped before this
1187 	 *    point above KERNEL_TEXT.
1188 	 */
1189 	current = phys_install = memlist;
1190 	copy_memlist_filter(bootops->boot_mem->physinstalled, &current, NULL);
1191 	if ((caddr_t)current > (caddr_t)memlist + memlist_sz)
1192 		panic("physinstalled was too big!");
1193 	if (prom_debug)
1194 		print_kernel_memlist("phys_install", phys_install);
1195 
1196 	phys_avail = current;
1197 	PRM_POINT("Building phys_avail:\n");
1198 	copy_memlist_filter(bootops->boot_mem->physinstalled, &current,
1199 	    avail_filter);
1200 	if ((caddr_t)current > (caddr_t)memlist + memlist_sz)
1201 		panic("physavail was too big!");
1202 	if (prom_debug)
1203 		print_kernel_memlist("phys_avail", phys_avail);
1204 
1205 	/*
1206 	 * setup page coloring
1207 	 */
1208 	page_coloring_setup(pagecolor_mem);
1209 	page_lock_init();	/* currently a no-op */
1210 
1211 	/*
1212 	 * free page list counters
1213 	 */
1214 	(void) page_ctrs_alloc(page_ctrs_mem);
1215 
1216 	/*
1217 	 * Initialize the page structures from the memory lists.
1218 	 */
1219 	availrmem_initial = availrmem = freemem = 0;
1220 	PRM_POINT("Calling kphysm_init()...");
1221 	boot_npages = kphysm_init(pp_base, memseg_base, 0, boot_npages);
1222 	PRM_POINT("kphysm_init() done");
1223 	PRM_DEBUG(boot_npages);
1224 
1225 	/*
1226 	 * Now that page_t's have been initialized, remove all the
1227 	 * initial allocation pages from the kernel free page lists.
1228 	 */
1229 	boot_mapin((caddr_t)valloc_base, valloc_sz);
1230 
1231 	/*
1232 	 * Initialize kernel memory allocator.
1233 	 */
1234 	kmem_init();
1235 
1236 	/*
1237 	 * print this out early so that we know what's going on
1238 	 */
1239 	cmn_err(CE_CONT, "?features: %b\n", x86_feature, FMT_X86_FEATURE);
1240 
1241 	/*
1242 	 * Initialize bp_mapin().
1243 	 */
1244 	bp_init(MMU_PAGESIZE, HAT_STORECACHING_OK);
1245 
1246 #if defined(__i386)
1247 	if (eprom_kernelbase && (eprom_kernelbase != kernelbase))
1248 		cmn_err(CE_WARN, "kernelbase value, User specified 0x%lx, "
1249 		    "System using 0x%lx",
1250 		    (uintptr_t)eprom_kernelbase, (uintptr_t)kernelbase);
1251 #endif
1252 
1253 #ifdef	KERNELBASE_ABI_MIN
1254 	if (kernelbase < (uintptr_t)KERNELBASE_ABI_MIN) {
1255 		cmn_err(CE_NOTE, "!kernelbase set to 0x%lx, system is not "
1256 		    "i386 ABI compliant.", (uintptr_t)kernelbase);
1257 	}
1258 #endif
1259 
1260 	PRM_POINT("startup_memlist() done");
1261 }
1262 
1263 static void
1264 startup_modules(void)
1265 {
1266 	unsigned int i;
1267 	extern void impl_setup_ddi(void);
1268 	extern void prom_setup(void);
1269 
1270 	PRM_POINT("startup_modules() starting...");
1271 	/*
1272 	 * Initialize ten-micro second timer so that drivers will
1273 	 * not get short changed in their init phase. This was
1274 	 * not getting called until clkinit which, on fast cpu's
1275 	 * caused the drv_usecwait to be way too short.
1276 	 */
1277 	microfind();
1278 
1279 	/*
1280 	 * Read the GMT lag from /etc/rtc_config.
1281 	 */
1282 	gmt_lag = process_rtc_config_file();
1283 
1284 	/*
1285 	 * Calculate default settings of system parameters based upon
1286 	 * maxusers, yet allow to be overridden via the /etc/system file.
1287 	 */
1288 	param_calc(0);
1289 
1290 	mod_setup();
1291 
1292 	/*
1293 	 * Setup machine check architecture on P6
1294 	 */
1295 	setup_mca();
1296 
1297 	/*
1298 	 * Initialize system parameters.
1299 	 */
1300 	param_init();
1301 
1302 	/*
1303 	 * maxmem is the amount of physical memory we're playing with.
1304 	 */
1305 	maxmem = physmem;
1306 
1307 	/*
1308 	 * Initialize the hat layer.
1309 	 */
1310 	hat_init();
1311 
1312 	/*
1313 	 * Initialize segment management stuff.
1314 	 */
1315 	seg_init();
1316 
1317 	if (modload("fs", "specfs") == -1)
1318 		halt("Can't load specfs");
1319 
1320 	if (modload("fs", "devfs") == -1)
1321 		halt("Can't load devfs");
1322 
1323 	dispinit();
1324 
1325 	/*
1326 	 * This is needed here to initialize hw_serial[] for cluster booting.
1327 	 */
1328 	if ((i = modload("misc", "sysinit")) != (unsigned int)-1)
1329 		(void) modunload(i);
1330 	else
1331 		cmn_err(CE_CONT, "sysinit load failed");
1332 
1333 	/* Read cluster configuration data. */
1334 	clconf_init();
1335 
1336 	/*
1337 	 * Create a kernel device tree. First, create rootnex and
1338 	 * then invoke bus specific code to probe devices.
1339 	 */
1340 	setup_ddi();
1341 	impl_setup_ddi();
1342 	/*
1343 	 * Fake a prom tree such that /dev/openprom continues to work
1344 	 */
1345 	prom_setup();
1346 
1347 	/*
1348 	 * Load all platform specific modules
1349 	 */
1350 	psm_modload();
1351 
1352 	PRM_POINT("startup_modules() done");
1353 }
1354 
1355 static void
1356 startup_bop_gone(void)
1357 {
1358 	PRM_POINT("startup_bop_gone() starting...");
1359 
1360 	/*
1361 	 * Do final allocations of HAT data structures that need to
1362 	 * be allocated before quiescing the boot loader.
1363 	 */
1364 	PRM_POINT("Calling hat_kern_alloc()...");
1365 	hat_kern_alloc();
1366 	PRM_POINT("hat_kern_alloc() done");
1367 
1368 	/*
1369 	 * Setup MTRR (Memory type range registers)
1370 	 */
1371 	setup_mtrr();
1372 	PRM_POINT("startup_bop_gone() done");
1373 }
1374 
1375 /*
1376  * Walk through the pagetables looking for pages mapped in by boot.  If the
1377  * setaside flag is set the pages are expected to be returned to the
1378  * kernel later in boot, so we add them to the bootpages list.
1379  */
1380 static void
1381 protect_boot_range(uintptr_t low, uintptr_t high, int setaside)
1382 {
1383 	uintptr_t va = low;
1384 	size_t len;
1385 	uint_t prot;
1386 	pfn_t pfn;
1387 	page_t *pp;
1388 	pgcnt_t boot_protect_cnt = 0;
1389 
1390 	while (hat_boot_probe(&va, &len, &pfn, &prot) != 0 && va < high) {
1391 		if (va + len >= high)
1392 			panic("0x%lx byte mapping at 0x%p exceeds boot's "
1393 			    "legal range.", len, (void *)va);
1394 
1395 		while (len > 0) {
1396 			pp = page_numtopp_alloc(pfn);
1397 			if (pp != NULL) {
1398 				if (setaside == 0)
1399 					panic("Unexpected mapping by boot.  "
1400 					    "addr=%p pfn=%lx\n",
1401 					    (void *)va, pfn);
1402 
1403 				pp->p_next = bootpages;
1404 				bootpages = pp;
1405 				++boot_protect_cnt;
1406 			}
1407 
1408 			++pfn;
1409 			len -= MMU_PAGESIZE;
1410 			va += MMU_PAGESIZE;
1411 		}
1412 	}
1413 	PRM_DEBUG(boot_protect_cnt);
1414 }
1415 
1416 static void
1417 startup_vm(void)
1418 {
1419 	struct segmap_crargs a;
1420 	extern void hat_kern_setup(void);
1421 	pgcnt_t pages_left;
1422 
1423 	extern int exec_lpg_disable, use_brk_lpg, use_stk_lpg, use_zmap_lpg;
1424 	extern pgcnt_t auto_lpg_min_physmem;
1425 
1426 	PRM_POINT("startup_vm() starting...");
1427 
1428 	/*
1429 	 * The next two loops are done in distinct steps in order
1430 	 * to be sure that any page that is doubly mapped (both above
1431 	 * KERNEL_TEXT and below kernelbase) is dealt with correctly.
1432 	 * Note this may never happen, but it might someday.
1433 	 */
1434 
1435 	bootpages = NULL;
1436 	PRM_POINT("Protecting boot pages");
1437 	/*
1438 	 * Protect any pages mapped above KERNEL_TEXT that somehow have
1439 	 * page_t's. This can only happen if something weird allocated
1440 	 * in this range (like kadb/kmdb).
1441 	 */
1442 	protect_boot_range(KERNEL_TEXT, (uintptr_t)-1, 0);
1443 
1444 	/*
1445 	 * Before we can take over memory allocation/mapping from the boot
1446 	 * loader we must remove from our free page lists any boot pages that
1447 	 * will stay mapped until release_bootstrap().
1448 	 */
1449 	protect_boot_range(0, kernelbase, 1);
1450 #if defined(__amd64)
1451 	protect_boot_range(BOOT_DOUBLEMAP_BASE,
1452 	    BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE, 0);
1453 #endif
1454 
1455 	/*
1456 	 * Copy in boot's page tables, set up extra page tables for the kernel,
1457 	 * and switch to the kernel's context.
1458 	 */
1459 	PRM_POINT("Calling hat_kern_setup()...");
1460 	hat_kern_setup();
1461 
1462 	/*
1463 	 * It is no longer safe to call BOP_ALLOC(), so make sure we don't.
1464 	 */
1465 	bootops->bsys_alloc = NULL;
1466 	PRM_POINT("hat_kern_setup() done");
1467 
1468 	hat_cpu_online(CPU);
1469 
1470 	/*
1471 	 * Before we call kvm_init(), we need to establish the final size
1472 	 * of the kernel's heap.  So, we need to figure out how much space
1473 	 * to set aside for segkp, segkpm, and segmap.
1474 	 */
1475 	final_kernelheap = (caddr_t)ROUND_UP_LPAGE(kernelbase);
1476 #if defined(__amd64)
1477 	if (kpm_desired) {
1478 		/*
1479 		 * Segkpm appears at the bottom of the kernel's address
1480 		 * range.  To detect accidental overruns of the user
1481 		 * address space, we leave a "red zone" of unmapped memory
1482 		 * between kernelbase and the beginning of segkpm.
1483 		 */
1484 		kpm_vbase = final_kernelheap + KERNEL_REDZONE_SIZE;
1485 		kpm_size = mmu_ptob(physmax);
1486 		PRM_DEBUG(kpm_vbase);
1487 		PRM_DEBUG(kpm_size);
1488 		final_kernelheap =
1489 		    (caddr_t)ROUND_UP_TOPLEVEL(kpm_vbase + kpm_size);
1490 	}
1491 
1492 	if (!segkp_fromheap) {
1493 		size_t sz = mmu_ptob(segkpsize);
1494 
1495 		/*
1496 		 * determine size of segkp and adjust the bottom of the
1497 		 * kernel's heap.
1498 		 */
1499 		if (sz < SEGKPMINSIZE || sz > SEGKPMAXSIZE) {
1500 			sz = SEGKPDEFSIZE;
1501 			cmn_err(CE_WARN, "!Illegal value for segkpsize. "
1502 			    "segkpsize has been reset to %ld pages",
1503 			    mmu_btop(sz));
1504 		}
1505 		sz = MIN(sz, MAX(SEGKPMINSIZE, mmu_ptob(physmem)));
1506 
1507 		segkpsize = mmu_btop(ROUND_UP_LPAGE(sz));
1508 		segkp_base = final_kernelheap;
1509 		PRM_DEBUG(segkpsize);
1510 		PRM_DEBUG(segkp_base);
1511 		final_kernelheap = segkp_base + mmu_ptob(segkpsize);
1512 		PRM_DEBUG(final_kernelheap);
1513 	}
1514 
1515 	/*
1516 	 * put the range of VA for device mappings next
1517 	 */
1518 	toxic_addr = (uintptr_t)final_kernelheap;
1519 	PRM_DEBUG(toxic_addr);
1520 	final_kernelheap = (char *)toxic_addr + toxic_size;
1521 #endif
1522 	PRM_DEBUG(final_kernelheap);
1523 	ASSERT(final_kernelheap < boot_kernelheap);
1524 
1525 	/*
1526 	 * Users can change segmapsize through eeprom or /etc/system.
1527 	 * If the variable is tuned through eeprom, there is no upper
1528 	 * bound on the size of segmap.  If it is tuned through
1529 	 * /etc/system on 32-bit systems, it must be no larger than we
1530 	 * planned for in startup_memlist().
1531 	 */
1532 	segmapsize = MAX(ROUND_UP_LPAGE(segmapsize), SEGMAPDEFAULT);
1533 	segkmap_start = ROUND_UP_LPAGE((uintptr_t)final_kernelheap);
1534 
1535 #if defined(__i386)
1536 	if (segmapsize > segmap_reserved) {
1537 		cmn_err(CE_NOTE, "!segmapsize may not be set > 0x%lx in "
1538 		    "/etc/system.  Use eeprom.", (long)SEGMAPMAX);
1539 		segmapsize = segmap_reserved;
1540 	}
1541 	/*
1542 	 * 32-bit systems don't have segkpm or segkp, so segmap appears at
1543 	 * the bottom of the kernel's address range.  Set aside space for a
1544 	 * red zone just below the start of segmap.
1545 	 */
1546 	segkmap_start += KERNEL_REDZONE_SIZE;
1547 	segmapsize -= KERNEL_REDZONE_SIZE;
1548 #endif
1549 	final_kernelheap = (char *)(segkmap_start + segmapsize);
1550 
1551 	PRM_DEBUG(segkmap_start);
1552 	PRM_DEBUG(segmapsize);
1553 	PRM_DEBUG(final_kernelheap);
1554 
1555 	/*
1556 	 * Initialize VM system
1557 	 */
1558 	PRM_POINT("Calling kvm_init()...");
1559 	kvm_init();
1560 	PRM_POINT("kvm_init() done");
1561 
1562 	/*
1563 	 * Tell kmdb that the VM system is now working
1564 	 */
1565 	if (boothowto & RB_DEBUG)
1566 		kdi_dvec_vmready();
1567 
1568 	/*
1569 	 * Mangle the brand string etc.
1570 	 */
1571 	cpuid_pass3(CPU);
1572 
1573 	PRM_DEBUG(final_kernelheap);
1574 
1575 	/*
1576 	 * Now that we can use memory outside the top 4GB (on 64-bit
1577 	 * systems) and we know the size of segmap, we can set the final
1578 	 * size of the kernel's heap.  Note: on 64-bit systems we still
1579 	 * can't touch anything in the bottom half of the top 4GB range
1580 	 * because boot still has pages mapped there.
1581 	 */
1582 	if (final_kernelheap < boot_kernelheap) {
1583 		kernelheap_extend(final_kernelheap, boot_kernelheap);
1584 #if defined(__amd64)
1585 		kmem_setaside = vmem_xalloc(heap_arena, BOOT_DOUBLEMAP_SIZE,
1586 		    MMU_PAGESIZE, 0, 0, (void *)(BOOT_DOUBLEMAP_BASE),
1587 		    (void *)(BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE),
1588 		    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
1589 		PRM_DEBUG(kmem_setaside);
1590 		if (kmem_setaside == NULL)
1591 			panic("Could not protect boot's memory");
1592 #endif
1593 	}
1594 	/*
1595 	 * Now that the kernel heap may have grown significantly, we need
1596 	 * to make all the remaining page_t's available to back that memory.
1597 	 *
1598 	 * XX64 this should probably wait till after release boot-strap too.
1599 	 */
1600 	pages_left = npages - boot_npages;
1601 	if (pages_left > 0) {
1602 		PRM_DEBUG(pages_left);
1603 		(void) kphysm_init(NULL, memseg_base, boot_npages, pages_left);
1604 	}
1605 
1606 #if defined(__amd64)
1607 
1608 	/*
1609 	 * Create the device arena for toxic (to dtrace/kmdb) mappings.
1610 	 */
1611 	device_arena = vmem_create("device", (void *)toxic_addr,
1612 	    toxic_size, MMU_PAGESIZE, NULL, NULL, NULL, 0, VM_SLEEP);
1613 
1614 #else	/* __i386 */
1615 
1616 	/*
1617 	 * allocate the bit map that tracks toxic pages
1618 	 */
1619 	toxic_bit_map_len = btop((ulong_t)(ptable_va - kernelbase));
1620 	PRM_DEBUG(toxic_bit_map_len);
1621 	toxic_bit_map =
1622 	    kmem_zalloc(BT_SIZEOFMAP(toxic_bit_map_len), KM_NOSLEEP);
1623 	ASSERT(toxic_bit_map != NULL);
1624 	PRM_DEBUG(toxic_bit_map);
1625 
1626 #endif	/* __i386 */
1627 
1628 
1629 	/*
1630 	 * Now that we've got more VA, as well as the ability to allocate from
1631 	 * it, tell the debugger.
1632 	 */
1633 	if (boothowto & RB_DEBUG)
1634 		kdi_dvec_memavail();
1635 
1636 	/*
1637 	 * The following code installs a special page fault handler (#pf)
1638 	 * to work around a pentium bug.
1639 	 */
1640 #if !defined(__amd64)
1641 	if (x86_type == X86_TYPE_P5) {
1642 		gate_desc_t *newidt;
1643 		desctbr_t    newidt_r;
1644 
1645 		if ((newidt = kmem_zalloc(MMU_PAGESIZE, KM_NOSLEEP)) == NULL)
1646 			panic("failed to install pentium_pftrap");
1647 
1648 		bcopy(idt0, newidt, sizeof (idt0));
1649 		set_gatesegd(&newidt[T_PGFLT], &pentium_pftrap,
1650 		    KCS_SEL, 0, SDT_SYSIGT, SEL_KPL);
1651 
1652 		(void) as_setprot(&kas, (caddr_t)newidt, MMU_PAGESIZE,
1653 		    PROT_READ|PROT_EXEC);
1654 
1655 		newidt_r.dtr_limit = sizeof (idt0) - 1;
1656 		newidt_r.dtr_base = (uintptr_t)newidt;
1657 		CPU->cpu_idt = newidt;
1658 		wr_idtr(&newidt_r);
1659 	}
1660 #endif	/* !__amd64 */
1661 
1662 	/*
1663 	 * Map page pfn=0 for drivers, such as kd, that need to pick up
1664 	 * parameters left there by controllers/BIOS.
1665 	 */
1666 	PRM_POINT("setup up p0_va");
1667 	p0_va = i86devmap(0, 1, PROT_READ);
1668 	PRM_DEBUG(p0_va);
1669 
1670 	/*
1671 	 * If the following is true, someone has patched phsymem to be less
1672 	 * than the number of pages that the system actually has.  Remove
1673 	 * pages until system memory is limited to the requested amount.
1674 	 * Since we have allocated page structures for all pages, we
1675 	 * correct the amount of memory we want to remove by the size of
1676 	 * the memory used to hold page structures for the non-used pages.
1677 	 */
1678 	if (physmem < npages) {
1679 		uint_t diff;
1680 		offset_t off;
1681 		struct page *pp;
1682 		caddr_t rand_vaddr;
1683 		struct seg kseg;
1684 
1685 		cmn_err(CE_WARN, "limiting physmem to %lu pages", physmem);
1686 
1687 		off = 0;
1688 		diff = npages - physmem;
1689 		diff -= mmu_btopr(diff * sizeof (struct page));
1690 		kseg.s_as = &kas;
1691 		while (diff--) {
1692 			rand_vaddr = (caddr_t)
1693 			    (((uintptr_t)&unused_pages_vp >> 7) ^
1694 			    (uintptr_t)((u_offset_t)off >> MMU_PAGESHIFT));
1695 			pp = page_create_va(&unused_pages_vp, off, MMU_PAGESIZE,
1696 				PG_WAIT | PG_EXCL, &kseg, rand_vaddr);
1697 			if (pp == NULL) {
1698 				panic("limited physmem too much!");
1699 				/*NOTREACHED*/
1700 			}
1701 			page_io_unlock(pp);
1702 			page_downgrade(pp);
1703 			availrmem--;
1704 			off += MMU_PAGESIZE;
1705 		}
1706 	}
1707 
1708 	cmn_err(CE_CONT, "?mem = %luK (0x%lx)\n",
1709 	    physinstalled << (MMU_PAGESHIFT - 10), ptob(physinstalled));
1710 
1711 	/*
1712 	 * disable automatic large pages for small memory systems or
1713 	 * when the disable flag is set.
1714 	 */
1715 	if (physmem < auto_lpg_min_physmem || auto_lpg_disable) {
1716 		exec_lpg_disable = 1;
1717 		use_brk_lpg = 0;
1718 		use_stk_lpg = 0;
1719 		use_zmap_lpg = 0;
1720 	}
1721 
1722 	PRM_POINT("Calling hat_init_finish()...");
1723 	hat_init_finish();
1724 	PRM_POINT("hat_init_finish() done");
1725 
1726 	/*
1727 	 * Initialize the segkp segment type.
1728 	 */
1729 	rw_enter(&kas.a_lock, RW_WRITER);
1730 	if (!segkp_fromheap) {
1731 		if (seg_attach(&kas, (caddr_t)segkp_base, mmu_ptob(segkpsize),
1732 		    segkp) < 0) {
1733 			panic("startup: cannot attach segkp");
1734 			/*NOTREACHED*/
1735 		}
1736 	} else {
1737 		/*
1738 		 * For 32 bit x86 systems, we will have segkp under the heap.
1739 		 * There will not be a segkp segment.  We do, however, need
1740 		 * to fill in the seg structure.
1741 		 */
1742 		segkp->s_as = &kas;
1743 	}
1744 	if (segkp_create(segkp) != 0) {
1745 		panic("startup: segkp_create failed");
1746 		/*NOTREACHED*/
1747 	}
1748 	PRM_DEBUG(segkp);
1749 	rw_exit(&kas.a_lock);
1750 
1751 	/*
1752 	 * kpm segment
1753 	 */
1754 	segmap_kpm = 0;
1755 	if (kpm_desired) {
1756 		kpm_init();
1757 		kpm_enable = 1;
1758 	}
1759 
1760 	/*
1761 	 * Now create segmap segment.
1762 	 */
1763 	rw_enter(&kas.a_lock, RW_WRITER);
1764 	if (seg_attach(&kas, (caddr_t)segkmap_start, segmapsize, segkmap) < 0) {
1765 		panic("cannot attach segkmap");
1766 		/*NOTREACHED*/
1767 	}
1768 	PRM_DEBUG(segkmap);
1769 
1770 	/*
1771 	 * The 64 bit HAT permanently maps only segmap's page tables.
1772 	 * The 32 bit HAT maps the heap's page tables too.
1773 	 */
1774 #if defined(__amd64)
1775 	hat_kmap_init(segkmap_start, segmapsize);
1776 #else /* __i386 */
1777 	ASSERT(segkmap_start + segmapsize == (uintptr_t)final_kernelheap);
1778 	hat_kmap_init(segkmap_start, (uintptr_t)ekernelheap - segkmap_start);
1779 #endif /* __i386 */
1780 
1781 	a.prot = PROT_READ | PROT_WRITE;
1782 	a.shmsize = 0;
1783 	a.nfreelist = segmapfreelists;
1784 
1785 	if (segmap_create(segkmap, (caddr_t)&a) != 0)
1786 		panic("segmap_create segkmap");
1787 	rw_exit(&kas.a_lock);
1788 
1789 	setup_vaddr_for_ppcopy(CPU);
1790 
1791 	segdev_init();
1792 	pmem_init();
1793 	PRM_POINT("startup_vm() done");
1794 }
1795 
1796 static void
1797 startup_end(void)
1798 {
1799 	extern void setx86isalist(void);
1800 
1801 	PRM_POINT("startup_end() starting...");
1802 
1803 	/*
1804 	 * Perform tasks that get done after most of the VM
1805 	 * initialization has been done but before the clock
1806 	 * and other devices get started.
1807 	 */
1808 	kern_setup1();
1809 
1810 	/*
1811 	 * Perform CPC initialization for this CPU.
1812 	 */
1813 	kcpc_hw_init(CPU);
1814 
1815 #if defined(__amd64)
1816 	/*
1817 	 * Validate support for syscall/sysret
1818 	 * XX64 -- include SSE, SSE2, etc. here too?
1819 	 */
1820 	if ((x86_feature & X86_ASYSC) == 0) {
1821 		cmn_err(CE_WARN,
1822 		    "cpu%d does not support syscall/sysret", CPU->cpu_id);
1823 	}
1824 #endif
1825 	/*
1826 	 * Configure the system.
1827 	 */
1828 	PRM_POINT("Calling configure()...");
1829 	configure();		/* set up devices */
1830 	PRM_POINT("configure() done");
1831 
1832 	/*
1833 	 * Set the isa_list string to the defined instruction sets we
1834 	 * support.
1835 	 */
1836 	setx86isalist();
1837 	init_intr_threads(CPU);
1838 	psm_install();
1839 
1840 	/*
1841 	 * We're done with bootops.  We don't unmap the bootstrap yet because
1842 	 * we're still using bootsvcs.
1843 	 */
1844 	PRM_POINT("zeroing out bootops");
1845 	*bootopsp = (struct bootops *)0;
1846 	bootops = (struct bootops *)NULL;
1847 
1848 	PRM_POINT("Enabling interrupts");
1849 	(*picinitf)();
1850 	sti();
1851 
1852 	(void) add_avsoftintr((void *)&softlevel1_hdl, 1, softlevel1,
1853 		"softlevel1", NULL, NULL); /* XXX to be moved later */
1854 
1855 	PRM_POINT("startup_end() done");
1856 }
1857 
1858 extern char hw_serial[];
1859 char *_hs1107 = hw_serial;
1860 ulong_t  _bdhs34;
1861 
1862 void
1863 post_startup(void)
1864 {
1865 	/*
1866 	 * Set the system wide, processor-specific flags to be passed
1867 	 * to userland via the aux vector for performance hints and
1868 	 * instruction set extensions.
1869 	 */
1870 	bind_hwcap();
1871 
1872 	/*
1873 	 * Load the System Management BIOS into the global ksmbios handle,
1874 	 * if an SMBIOS is present on this system.
1875 	 */
1876 	ksmbios = smbios_open(NULL, SMB_VERSION, ksmbios_flags, NULL);
1877 
1878 	/*
1879 	 * Startup memory scrubber.
1880 	 */
1881 	memscrub_init();
1882 
1883 	/*
1884 	 * Perform forceloading tasks for /etc/system.
1885 	 */
1886 	(void) mod_sysctl(SYS_FORCELOAD, NULL);
1887 
1888 	/*
1889 	 * ON4.0: Force /proc module in until clock interrupt handle fixed
1890 	 * ON4.0: This must be fixed or restated in /etc/systems.
1891 	 */
1892 	(void) modload("fs", "procfs");
1893 
1894 #if defined(__i386)
1895 	/*
1896 	 * Check for required functional Floating Point hardware,
1897 	 * unless FP hardware explicitly disabled.
1898 	 */
1899 	if (fpu_exists && (fpu_pentium_fdivbug || fp_kind == FP_NO))
1900 		halt("No working FP hardware found");
1901 #endif
1902 
1903 	maxmem = freemem;
1904 
1905 	add_cpunode2devtree(CPU->cpu_id, CPU->cpu_m.mcpu_cpi);
1906 
1907 	/*
1908 	 * Perform the formal initialization of the boot chip,
1909 	 * and associate the boot cpu with it.
1910 	 * This must be done after the cpu node for CPU has been
1911 	 * added to the device tree, when the necessary probing to
1912 	 * know the chip type and chip "id" is performed.
1913 	 */
1914 	chip_cpu_init(CPU);
1915 	chip_cpu_assign(CPU);
1916 }
1917 
1918 static int
1919 pp_in_ramdisk(page_t *pp)
1920 {
1921 	extern uint64_t ramdisk_start, ramdisk_end;
1922 
1923 	return ((pp->p_pagenum >= btop(ramdisk_start)) &&
1924 	    (pp->p_pagenum < btopr(ramdisk_end)));
1925 }
1926 
1927 void
1928 release_bootstrap(void)
1929 {
1930 	int root_is_ramdisk;
1931 	pfn_t pfn;
1932 	page_t *pp;
1933 	extern void kobj_boot_unmountroot(void);
1934 	extern dev_t rootdev;
1935 
1936 	/* unmount boot ramdisk and release kmem usage */
1937 	kobj_boot_unmountroot();
1938 
1939 	/*
1940 	 * We're finished using the boot loader so free its pages.
1941 	 */
1942 	PRM_POINT("Unmapping lower boot pages");
1943 	clear_boot_mappings(0, kernelbase);
1944 #if defined(__amd64)
1945 	PRM_POINT("Unmapping upper boot pages");
1946 	clear_boot_mappings(BOOT_DOUBLEMAP_BASE,
1947 	    BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE);
1948 #endif
1949 
1950 	/*
1951 	 * If root isn't on ramdisk, destroy the hardcoded
1952 	 * ramdisk node now and release the memory. Else,
1953 	 * ramdisk memory is kept in rd_pages.
1954 	 */
1955 	root_is_ramdisk = (getmajor(rootdev) == ddi_name_to_major("ramdisk"));
1956 	if (!root_is_ramdisk) {
1957 		dev_info_t *dip = ddi_find_devinfo("ramdisk", -1, 0);
1958 		ASSERT(dip && ddi_get_parent(dip) == ddi_root_node());
1959 		ndi_rele_devi(dip);	/* held from ddi_find_devinfo */
1960 		(void) ddi_remove_child(dip, 0);
1961 	}
1962 
1963 	PRM_POINT("Releasing boot pages");
1964 	while (bootpages) {
1965 		pp = bootpages;
1966 		bootpages = pp->p_next;
1967 		if (root_is_ramdisk && pp_in_ramdisk(pp)) {
1968 			pp->p_next = rd_pages;
1969 			rd_pages = pp;
1970 			continue;
1971 		}
1972 		pp->p_next = (struct page *)0;
1973 		page_free(pp, 1);
1974 	}
1975 
1976 	/*
1977 	 * Find 1 page below 1 MB so that other processors can boot up.
1978 	 * Make sure it has a kernel VA as well as a 1:1 mapping.
1979 	 * We should have just free'd one up.
1980 	 */
1981 	if (use_mp) {
1982 		for (pfn = 1; pfn < btop(1*1024*1024); pfn++) {
1983 			if (page_numtopp_alloc(pfn) == NULL)
1984 				continue;
1985 			rm_platter_va = i86devmap(pfn, 1,
1986 			    PROT_READ | PROT_WRITE | PROT_EXEC);
1987 			rm_platter_pa = ptob(pfn);
1988 			hat_devload(kas.a_hat,
1989 			    (caddr_t)(uintptr_t)rm_platter_pa, MMU_PAGESIZE,
1990 			    pfn, PROT_READ | PROT_WRITE | PROT_EXEC,
1991 			    HAT_LOAD_NOCONSIST);
1992 			break;
1993 		}
1994 		if (pfn == btop(1*1024*1024))
1995 			panic("No page available for starting "
1996 			    "other processors");
1997 	}
1998 
1999 #if defined(__amd64)
2000 	PRM_POINT("Returning boot's VA space to kernel heap");
2001 	if (kmem_setaside != NULL)
2002 		vmem_free(heap_arena, kmem_setaside, BOOT_DOUBLEMAP_SIZE);
2003 #endif
2004 }
2005 
2006 /*
2007  * Initialize the platform-specific parts of a page_t.
2008  */
2009 void
2010 add_physmem_cb(page_t *pp, pfn_t pnum)
2011 {
2012 	pp->p_pagenum = pnum;
2013 	pp->p_mapping = NULL;
2014 	pp->p_embed = 0;
2015 	pp->p_share = 0;
2016 	pp->p_mlentry = 0;
2017 }
2018 
2019 /*
2020  * kphysm_init() initializes physical memory.
2021  */
2022 static pgcnt_t
2023 kphysm_init(
2024 	page_t *inpp,
2025 	struct memseg *memsegp,
2026 	pgcnt_t start,
2027 	pgcnt_t npages)
2028 {
2029 	struct memlist	*pmem;
2030 	struct memseg	*cur_memseg;
2031 	struct memseg	**memsegpp;
2032 	pfn_t		base_pfn;
2033 	pgcnt_t		num;
2034 	pgcnt_t		total_skipped = 0;
2035 	pgcnt_t		skipping = 0;
2036 	pgcnt_t		pages_done = 0;
2037 	pgcnt_t		largepgcnt;
2038 	uint64_t	addr;
2039 	uint64_t	size;
2040 	page_t		*pp = inpp;
2041 	int		dobreak = 0;
2042 	extern pfn_t	ddiphysmin;
2043 
2044 	ASSERT(page_hash != NULL && page_hashsz != 0);
2045 
2046 	for (cur_memseg = memsegp; cur_memseg->pages != NULL; cur_memseg++);
2047 	ASSERT(cur_memseg == memsegp || start > 0);
2048 
2049 	for (pmem = phys_avail; pmem && npages; pmem = pmem->next) {
2050 		/*
2051 		 * In a 32 bit kernel can't use higher memory if we're
2052 		 * not booting in PAE mode. This check takes care of that.
2053 		 */
2054 		addr = pmem->address;
2055 		size = pmem->size;
2056 		if (btop(addr) > physmax)
2057 			continue;
2058 
2059 		/*
2060 		 * align addr and size - they may not be at page boundaries
2061 		 */
2062 		if ((addr & MMU_PAGEOFFSET) != 0) {
2063 			addr += MMU_PAGEOFFSET;
2064 			addr &= ~(uint64_t)MMU_PAGEOFFSET;
2065 			size -= addr - pmem->address;
2066 		}
2067 
2068 		/* only process pages below or equal to physmax */
2069 		if ((btop(addr + size) - 1) > physmax)
2070 			size = ptob(physmax - btop(addr) + 1);
2071 
2072 		num = btop(size);
2073 		if (num == 0)
2074 			continue;
2075 
2076 		if (total_skipped < start) {
2077 			if (start - total_skipped > num) {
2078 				total_skipped += num;
2079 				continue;
2080 			}
2081 			skipping = start - total_skipped;
2082 			num -= skipping;
2083 			addr += (MMU_PAGESIZE * skipping);
2084 			total_skipped = start;
2085 		}
2086 		if (num == 0)
2087 			continue;
2088 
2089 		if (num > npages)
2090 			num = npages;
2091 
2092 		npages -= num;
2093 		pages_done += num;
2094 		base_pfn = btop(addr);
2095 
2096 		/*
2097 		 * If the caller didn't provide space for the page
2098 		 * structures, carve them out of the memseg they will
2099 		 * represent.
2100 		 */
2101 		if (pp == NULL) {
2102 			pgcnt_t pp_pgs;
2103 
2104 			if (num <= 1)
2105 				continue;
2106 
2107 			/*
2108 			 * Compute how many of the pages we need to use for
2109 			 * page_ts
2110 			 */
2111 			pp_pgs = (num * sizeof (page_t)) / MMU_PAGESIZE + 1;
2112 			while (mmu_ptob(pp_pgs - 1) / sizeof (page_t) >=
2113 			    num - pp_pgs + 1)
2114 				--pp_pgs;
2115 			PRM_DEBUG(pp_pgs);
2116 
2117 			pp = vmem_alloc(heap_arena, mmu_ptob(pp_pgs),
2118 			    VM_NOSLEEP);
2119 			if (pp == NULL) {
2120 				cmn_err(CE_WARN, "Unable to add %ld pages to "
2121 				    "the system.", num);
2122 				continue;
2123 			}
2124 
2125 			hat_devload(kas.a_hat, (void *)pp, mmu_ptob(pp_pgs),
2126 			    base_pfn, PROT_READ | PROT_WRITE | HAT_UNORDERED_OK,
2127 			    HAT_LOAD | HAT_LOAD_LOCK | HAT_LOAD_NOCONSIST);
2128 			bzero(pp, mmu_ptob(pp_pgs));
2129 			num -= pp_pgs;
2130 			base_pfn += pp_pgs;
2131 		}
2132 
2133 		if (prom_debug)
2134 			prom_printf("MEMSEG addr=0x%" PRIx64
2135 			    " pgs=0x%lx pfn 0x%lx-0x%lx\n",
2136 			    addr, num, base_pfn, base_pfn + num);
2137 
2138 		/*
2139 		 * drop pages below ddiphysmin to simplify ddi memory
2140 		 * allocation with non-zero addr_lo requests.
2141 		 */
2142 		if (base_pfn < ddiphysmin) {
2143 			if (base_pfn + num <= ddiphysmin) {
2144 				/* drop entire range below ddiphysmin */
2145 				continue;
2146 			}
2147 			/* adjust range to ddiphysmin */
2148 			pp += (ddiphysmin - base_pfn);
2149 			num -= (ddiphysmin - base_pfn);
2150 			base_pfn = ddiphysmin;
2151 		}
2152 		/*
2153 		 * Build the memsegs entry
2154 		 */
2155 		cur_memseg->pages = pp;
2156 		cur_memseg->epages = pp + num;
2157 		cur_memseg->pages_base = base_pfn;
2158 		cur_memseg->pages_end = base_pfn + num;
2159 
2160 		/*
2161 		 * insert in memseg list in decreasing pfn range order.
2162 		 * Low memory is typically more fragmented such that this
2163 		 * ordering keeps the larger ranges at the front of the list
2164 		 * for code that searches memseg.
2165 		 */
2166 		memsegpp = &memsegs;
2167 		for (;;) {
2168 			if (*memsegpp == NULL) {
2169 				/* empty memsegs */
2170 				memsegs = cur_memseg;
2171 				break;
2172 			}
2173 			/* check for continuity with start of memsegpp */
2174 			if (cur_memseg->pages_end == (*memsegpp)->pages_base) {
2175 				if (cur_memseg->epages == (*memsegpp)->pages) {
2176 					/*
2177 					 * contiguous pfn and page_t's. Merge
2178 					 * cur_memseg into *memsegpp. Drop
2179 					 * cur_memseg
2180 					 */
2181 					(*memsegpp)->pages_base =
2182 					    cur_memseg->pages_base;
2183 					(*memsegpp)->pages =
2184 					    cur_memseg->pages;
2185 					/*
2186 					 * check if contiguous with the end of
2187 					 * the next memseg.
2188 					 */
2189 					if ((*memsegpp)->next &&
2190 					    ((*memsegpp)->pages_base ==
2191 					    (*memsegpp)->next->pages_end)) {
2192 						cur_memseg = *memsegpp;
2193 						memsegpp = &((*memsegpp)->next);
2194 						dobreak = 1;
2195 					} else {
2196 						break;
2197 					}
2198 				} else {
2199 					/*
2200 					 * contiguous pfn but not page_t's.
2201 					 * drop last pfn/page_t in cur_memseg
2202 					 * to prevent creation of large pages
2203 					 * with noncontiguous page_t's if not
2204 					 * aligned to largest page boundary.
2205 					 */
2206 					largepgcnt = page_get_pagecnt(
2207 					    page_num_pagesizes() - 1);
2208 
2209 					if (cur_memseg->pages_end &
2210 					    (largepgcnt - 1)) {
2211 						num--;
2212 						cur_memseg->epages--;
2213 						cur_memseg->pages_end--;
2214 					}
2215 				}
2216 			}
2217 
2218 			/* check for continuity with end of memsegpp */
2219 			if (cur_memseg->pages_base == (*memsegpp)->pages_end) {
2220 				if (cur_memseg->pages == (*memsegpp)->epages) {
2221 					/*
2222 					 * contiguous pfn and page_t's. Merge
2223 					 * cur_memseg into *memsegpp. Drop
2224 					 * cur_memseg.
2225 					 */
2226 					if (dobreak) {
2227 						/* merge previously done */
2228 						cur_memseg->pages =
2229 						    (*memsegpp)->pages;
2230 						cur_memseg->pages_base =
2231 						    (*memsegpp)->pages_base;
2232 						cur_memseg->next =
2233 						    (*memsegpp)->next;
2234 					} else {
2235 						(*memsegpp)->pages_end =
2236 						    cur_memseg->pages_end;
2237 						(*memsegpp)->epages =
2238 						    cur_memseg->epages;
2239 					}
2240 					break;
2241 				}
2242 				/*
2243 				 * contiguous pfn but not page_t's.
2244 				 * drop first pfn/page_t in cur_memseg
2245 				 * to prevent creation of large pages
2246 				 * with noncontiguous page_t's if not
2247 				 * aligned to largest page boundary.
2248 				 */
2249 				largepgcnt = page_get_pagecnt(
2250 				    page_num_pagesizes() - 1);
2251 				if (base_pfn & (largepgcnt - 1)) {
2252 					num--;
2253 					base_pfn++;
2254 					cur_memseg->pages++;
2255 					cur_memseg->pages_base++;
2256 					pp = cur_memseg->pages;
2257 				}
2258 				if (dobreak)
2259 					break;
2260 			}
2261 
2262 			if (cur_memseg->pages_base >=
2263 			    (*memsegpp)->pages_end) {
2264 				cur_memseg->next = *memsegpp;
2265 				*memsegpp = cur_memseg;
2266 				break;
2267 			}
2268 			if ((*memsegpp)->next == NULL) {
2269 				cur_memseg->next = NULL;
2270 				(*memsegpp)->next = cur_memseg;
2271 				break;
2272 			}
2273 			memsegpp = &((*memsegpp)->next);
2274 			ASSERT(*memsegpp != NULL);
2275 		}
2276 
2277 		/*
2278 		 * add_physmem() initializes the PSM part of the page
2279 		 * struct by calling the PSM back with add_physmem_cb().
2280 		 * In addition it coalesces pages into larger pages as
2281 		 * it initializes them.
2282 		 */
2283 		add_physmem(pp, num, base_pfn);
2284 		cur_memseg++;
2285 		availrmem_initial += num;
2286 		availrmem += num;
2287 
2288 		/*
2289 		 * If the caller provided the page frames to us, then
2290 		 * advance in that list.  Otherwise, prepare to allocate
2291 		 * our own page frames for the next memseg.
2292 		 */
2293 		pp = (inpp == NULL) ? NULL : pp + num;
2294 	}
2295 
2296 	PRM_DEBUG(availrmem_initial);
2297 	PRM_DEBUG(availrmem);
2298 	PRM_DEBUG(freemem);
2299 	build_pfn_hash();
2300 	return (pages_done);
2301 }
2302 
2303 /*
2304  * Kernel VM initialization.
2305  */
2306 static void
2307 kvm_init(void)
2308 {
2309 #ifdef DEBUG
2310 	extern void _start();
2311 
2312 	ASSERT((caddr_t)_start == s_text);
2313 #endif
2314 	ASSERT((((uintptr_t)s_text) & MMU_PAGEOFFSET) == 0);
2315 
2316 	/*
2317 	 * Put the kernel segments in kernel address space.
2318 	 */
2319 	rw_enter(&kas.a_lock, RW_WRITER);
2320 	as_avlinit(&kas);
2321 
2322 	(void) seg_attach(&kas, s_text, e_moddata - s_text, &ktextseg);
2323 	(void) segkmem_create(&ktextseg);
2324 
2325 	(void) seg_attach(&kas, (caddr_t)valloc_base, valloc_sz, &kvalloc);
2326 	(void) segkmem_create(&kvalloc);
2327 
2328 	/*
2329 	 * We're about to map out /boot.  This is the beginning of the
2330 	 * system resource management transition. We can no longer
2331 	 * call into /boot for I/O or memory allocations.
2332 	 *
2333 	 * XX64 - Is this still correct with kernelheap_extend() being called
2334 	 * later than this????
2335 	 */
2336 	(void) seg_attach(&kas, final_kernelheap,
2337 	    ekernelheap - final_kernelheap, &kvseg);
2338 	(void) segkmem_create(&kvseg);
2339 
2340 #if defined(__amd64)
2341 	(void) seg_attach(&kas, (caddr_t)core_base, core_size, &kvseg_core);
2342 	(void) segkmem_create(&kvseg_core);
2343 #endif
2344 
2345 	(void) seg_attach(&kas, (caddr_t)SEGDEBUGBASE, (size_t)SEGDEBUGSIZE,
2346 	    &kdebugseg);
2347 	(void) segkmem_create(&kdebugseg);
2348 
2349 	rw_exit(&kas.a_lock);
2350 
2351 	/*
2352 	 * Ensure that the red zone at kernelbase is never accessible.
2353 	 */
2354 	(void) as_setprot(&kas, (caddr_t)kernelbase, KERNEL_REDZONE_SIZE, 0);
2355 
2356 	/*
2357 	 * Make the text writable so that it can be hot patched by DTrace.
2358 	 */
2359 	(void) as_setprot(&kas, s_text, e_modtext - s_text,
2360 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2361 
2362 	/*
2363 	 * Make data writable until end.
2364 	 */
2365 	(void) as_setprot(&kas, s_data, e_moddata - s_data,
2366 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2367 }
2368 
2369 /*
2370  * These are MTTR registers supported by P6
2371  */
2372 static struct	mtrrvar	mtrrphys_arr[MAX_MTRRVAR];
2373 static uint64_t mtrr64k, mtrr16k1, mtrr16k2;
2374 static uint64_t mtrr4k1, mtrr4k2, mtrr4k3;
2375 static uint64_t mtrr4k4, mtrr4k5, mtrr4k6;
2376 static uint64_t mtrr4k7, mtrr4k8, mtrrcap;
2377 uint64_t mtrrdef, pat_attr_reg;
2378 
2379 /*
2380  * Disable reprogramming of MTRRs by default.
2381  */
2382 int	enable_relaxed_mtrr = 0;
2383 
2384 /*
2385  * These must serve for Pentium, Pentium Pro (P6/Pentium II/Pentium III)
2386  * and Pentium 4, and yes, they are named 0, 1, 2, 4, 3 in ascending
2387  * address order (starting from 0x400).  The Pentium 4 only implements
2388  * 4 sets, and while they are named 0-3 in the doc, the corresponding
2389  * names for P6 are 0,1,2,4.  So define these arrays in address order
2390  * so that they work for both pre-Pentium4 and Pentium 4 processors.
2391  */
2392 
2393 static uint_t	mci_ctl[] = {REG_MC0_CTL, REG_MC1_CTL, REG_MC2_CTL,
2394 		    REG_MC4_CTL, REG_MC3_CTL};
2395 static uint_t	mci_status[] = {REG_MC0_STATUS, REG_MC1_STATUS, REG_MC2_STATUS,
2396 		    REG_MC4_STATUS, REG_MC3_STATUS};
2397 static uint_t	mci_addr[] = {REG_MC0_ADDR, REG_MC1_ADDR, REG_MC2_ADDR,
2398 		    REG_MC4_ADDR, REG_MC3_ADDR};
2399 static int	mca_cnt;
2400 
2401 
2402 void
2403 setup_mca()
2404 {
2405 	int 		i;
2406 	uint64_t	mca_cap;
2407 
2408 	if (!(x86_feature & X86_MCA))
2409 		return;
2410 	mca_cap = rdmsr(REG_MCG_CAP);
2411 	if (mca_cap & MCG_CAP_CTL_P)
2412 		wrmsr(REG_MCG_CTL, -1ULL);	/* all ones */
2413 	mca_cnt = mca_cap & MCG_CAP_COUNT_MASK;
2414 	if (mca_cnt > P6_MCG_CAP_COUNT)
2415 		mca_cnt = P6_MCG_CAP_COUNT;
2416 	for (i = 1; i < mca_cnt; i++)
2417 		wrmsr(mci_ctl[i], -1ULL);	/* all ones */
2418 	for (i = 0; i < mca_cnt; i++)
2419 		wrmsr(mci_status[i], 0ULL);
2420 	setcr4(getcr4() | CR4_MCE);
2421 
2422 }
2423 
2424 int
2425 mca_exception(struct regs *rp)
2426 {
2427 	uint64_t	status, addr;
2428 	int		i, ret = 1, errcode, mserrcode;
2429 
2430 	status = rdmsr(REG_MCG_STATUS);
2431 	if (status & MCG_STATUS_RIPV)
2432 		ret = 0;
2433 	if (status & MCG_STATUS_EIPV)
2434 		cmn_err(CE_WARN, "MCE at 0x%lx", rp->r_pc);
2435 	wrmsr(REG_MCG_STATUS, 0ULL);
2436 	for (i = 0; i < mca_cnt; i++) {
2437 		status = rdmsr(mci_status[i]);
2438 		/*
2439 		 * If status register not valid skip this bank
2440 		 */
2441 		if (!(status & MCI_STATUS_VAL))
2442 			continue;
2443 		errcode = status & MCI_STATUS_ERRCODE;
2444 		mserrcode = (status  >> MSERRCODE_SHFT) & MCI_STATUS_ERRCODE;
2445 		if (status & MCI_STATUS_ADDRV) {
2446 			/*
2447 			 * If mci_addr contains the address where
2448 			 * error occurred, display the address
2449 			 */
2450 			addr = rdmsr(mci_addr[i]);
2451 			cmn_err(CE_WARN, "MCE: Bank %d: error code 0x%x:"\
2452 			    "addr = 0x%" PRIx64 ", model errcode = 0x%x", i,
2453 			    errcode, addr, mserrcode);
2454 		} else {
2455 			cmn_err(CE_WARN,
2456 			    "MCE: Bank %d: error code 0x%x, mserrcode = 0x%x",
2457 			    i, errcode, mserrcode);
2458 		}
2459 		wrmsr(mci_status[i], 0ULL);
2460 	}
2461 	return (ret);
2462 }
2463 
2464 void
2465 setup_mtrr()
2466 {
2467 	int i, ecx;
2468 	int vcnt;
2469 	struct	mtrrvar	*mtrrphys;
2470 
2471 	if (!(x86_feature & X86_MTRR))
2472 		return;
2473 
2474 	mtrrcap = rdmsr(REG_MTRRCAP);
2475 	mtrrdef = rdmsr(REG_MTRRDEF);
2476 	if (mtrrcap & MTRRCAP_FIX) {
2477 		mtrr64k = rdmsr(REG_MTRR64K);
2478 		mtrr16k1 = rdmsr(REG_MTRR16K1);
2479 		mtrr16k2 = rdmsr(REG_MTRR16K2);
2480 		mtrr4k1 = rdmsr(REG_MTRR4K1);
2481 		mtrr4k2 = rdmsr(REG_MTRR4K2);
2482 		mtrr4k3 = rdmsr(REG_MTRR4K3);
2483 		mtrr4k4 = rdmsr(REG_MTRR4K4);
2484 		mtrr4k5 = rdmsr(REG_MTRR4K5);
2485 		mtrr4k6 = rdmsr(REG_MTRR4K6);
2486 		mtrr4k7 = rdmsr(REG_MTRR4K7);
2487 		mtrr4k8 = rdmsr(REG_MTRR4K8);
2488 	}
2489 	if ((vcnt = (mtrrcap & MTRRCAP_VCNTMASK)) > MAX_MTRRVAR)
2490 		vcnt = MAX_MTRRVAR;
2491 
2492 	for (i = 0, ecx = REG_MTRRPHYSBASE0, mtrrphys = mtrrphys_arr;
2493 		i <  vcnt - 1; i++, ecx += 2, mtrrphys++) {
2494 		mtrrphys->mtrrphys_base = rdmsr(ecx);
2495 		mtrrphys->mtrrphys_mask = rdmsr(ecx + 1);
2496 		if ((x86_feature & X86_PAT) && enable_relaxed_mtrr) {
2497 			mtrrphys->mtrrphys_mask &= ~MTRRPHYSMASK_V;
2498 		}
2499 	}
2500 	if (x86_feature & X86_PAT) {
2501 		if (enable_relaxed_mtrr)
2502 			mtrrdef = MTRR_TYPE_WB|MTRRDEF_FE|MTRRDEF_E;
2503 		pat_attr_reg = PAT_DEFAULT_ATTRIBUTE;
2504 	}
2505 
2506 	mtrr_sync();
2507 }
2508 
2509 /*
2510  * Sync current cpu mtrr with the incore copy of mtrr.
2511  * This function has to be invoked with interrupts disabled
2512  * Currently we do not capture other cpu's. This is invoked on cpu0
2513  * just after reading /etc/system.
2514  * On other cpu's its invoked from mp_startup().
2515  */
2516 void
2517 mtrr_sync()
2518 {
2519 	uint_t	crvalue, cr0_orig;
2520 	int	vcnt, i, ecx;
2521 	struct	mtrrvar	*mtrrphys;
2522 
2523 	cr0_orig = crvalue = getcr0();
2524 	crvalue |= CR0_CD;
2525 	crvalue &= ~CR0_NW;
2526 	setcr0(crvalue);
2527 	invalidate_cache();
2528 	setcr3(getcr3());
2529 
2530 	if (x86_feature & X86_PAT)
2531 		wrmsr(REG_MTRRPAT, pat_attr_reg);
2532 
2533 	wrmsr(REG_MTRRDEF, rdmsr(REG_MTRRDEF) &
2534 	    ~((uint64_t)(uintptr_t)MTRRDEF_E));
2535 
2536 	if (mtrrcap & MTRRCAP_FIX) {
2537 		wrmsr(REG_MTRR64K, mtrr64k);
2538 		wrmsr(REG_MTRR16K1, mtrr16k1);
2539 		wrmsr(REG_MTRR16K2, mtrr16k2);
2540 		wrmsr(REG_MTRR4K1, mtrr4k1);
2541 		wrmsr(REG_MTRR4K2, mtrr4k2);
2542 		wrmsr(REG_MTRR4K3, mtrr4k3);
2543 		wrmsr(REG_MTRR4K4, mtrr4k4);
2544 		wrmsr(REG_MTRR4K5, mtrr4k5);
2545 		wrmsr(REG_MTRR4K6, mtrr4k6);
2546 		wrmsr(REG_MTRR4K7, mtrr4k7);
2547 		wrmsr(REG_MTRR4K8, mtrr4k8);
2548 	}
2549 	if ((vcnt = (mtrrcap & MTRRCAP_VCNTMASK)) > MAX_MTRRVAR)
2550 		vcnt = MAX_MTRRVAR;
2551 	for (i = 0, ecx = REG_MTRRPHYSBASE0, mtrrphys = mtrrphys_arr;
2552 	    i <  vcnt - 1; i++, ecx += 2, mtrrphys++) {
2553 		wrmsr(ecx, mtrrphys->mtrrphys_base);
2554 		wrmsr(ecx + 1, mtrrphys->mtrrphys_mask);
2555 	}
2556 	wrmsr(REG_MTRRDEF, mtrrdef);
2557 	setcr3(getcr3());
2558 	invalidate_cache();
2559 	setcr0(cr0_orig);
2560 }
2561 
2562 /*
2563  * resync mtrr so that BIOS is happy. Called from mdboot
2564  */
2565 void
2566 mtrr_resync()
2567 {
2568 	if ((x86_feature & X86_PAT) && enable_relaxed_mtrr) {
2569 		/*
2570 		 * We could have changed the default mtrr definition.
2571 		 * Put it back to uncached which is what it is at power on
2572 		 */
2573 		mtrrdef = MTRR_TYPE_UC|MTRRDEF_FE|MTRRDEF_E;
2574 		mtrr_sync();
2575 	}
2576 }
2577 
2578 void
2579 get_system_configuration()
2580 {
2581 	char	prop[32];
2582 	u_longlong_t nodes_ll, cpus_pernode_ll, lvalue;
2583 
2584 	if (((BOP_GETPROPLEN(bootops, "nodes") > sizeof (prop)) ||
2585 		(BOP_GETPROP(bootops, "nodes", prop) < 0) 	||
2586 		(kobj_getvalue(prop, &nodes_ll) == -1) ||
2587 		(nodes_ll > MAXNODES))			   ||
2588 	    ((BOP_GETPROPLEN(bootops, "cpus_pernode") > sizeof (prop)) ||
2589 		(BOP_GETPROP(bootops, "cpus_pernode", prop) < 0) ||
2590 		(kobj_getvalue(prop, &cpus_pernode_ll) == -1))) {
2591 
2592 		system_hardware.hd_nodes = 1;
2593 		system_hardware.hd_cpus_per_node = 0;
2594 	} else {
2595 		system_hardware.hd_nodes = (int)nodes_ll;
2596 		system_hardware.hd_cpus_per_node = (int)cpus_pernode_ll;
2597 	}
2598 	if ((BOP_GETPROPLEN(bootops, "kernelbase") > sizeof (prop)) ||
2599 		(BOP_GETPROP(bootops, "kernelbase", prop) < 0) 	||
2600 		(kobj_getvalue(prop, &lvalue) == -1))
2601 			eprom_kernelbase = NULL;
2602 	else
2603 			eprom_kernelbase = (uintptr_t)lvalue;
2604 
2605 	if ((BOP_GETPROPLEN(bootops, "segmapsize") > sizeof (prop)) ||
2606 	    (BOP_GETPROP(bootops, "segmapsize", prop) < 0) ||
2607 	    (kobj_getvalue(prop, &lvalue) == -1)) {
2608 		segmapsize = SEGMAPDEFAULT;
2609 	} else {
2610 		segmapsize = (uintptr_t)lvalue;
2611 	}
2612 
2613 	if ((BOP_GETPROPLEN(bootops, "segmapfreelists") > sizeof (prop)) ||
2614 	    (BOP_GETPROP(bootops, "segmapfreelists", prop) < 0) ||
2615 	    (kobj_getvalue(prop, &lvalue) == -1)) {
2616 		segmapfreelists = 0;	/* use segmap driver default */
2617 	} else {
2618 		segmapfreelists = (int)lvalue;
2619 	}
2620 }
2621 
2622 /*
2623  * Add to a memory list.
2624  * start = start of new memory segment
2625  * len = length of new memory segment in bytes
2626  * new = pointer to a new struct memlist
2627  * memlistp = memory list to which to add segment.
2628  */
2629 static void
2630 memlist_add(
2631 	uint64_t start,
2632 	uint64_t len,
2633 	struct memlist *new,
2634 	struct memlist **memlistp)
2635 {
2636 	struct memlist *cur;
2637 	uint64_t end = start + len;
2638 
2639 	new->address = start;
2640 	new->size = len;
2641 
2642 	cur = *memlistp;
2643 
2644 	while (cur) {
2645 		if (cur->address >= end) {
2646 			new->next = cur;
2647 			*memlistp = new;
2648 			new->prev = cur->prev;
2649 			cur->prev = new;
2650 			return;
2651 		}
2652 		ASSERT(cur->address + cur->size <= start);
2653 		if (cur->next == NULL) {
2654 			cur->next = new;
2655 			new->prev = cur;
2656 			new->next = NULL;
2657 			return;
2658 		}
2659 		memlistp = &cur->next;
2660 		cur = cur->next;
2661 	}
2662 }
2663 
2664 void
2665 kobj_vmem_init(vmem_t **text_arena, vmem_t **data_arena)
2666 {
2667 	size_t tsize = e_modtext - modtext;
2668 	size_t dsize = e_moddata - moddata;
2669 
2670 	*text_arena = vmem_create("module_text", tsize ? modtext : NULL, tsize,
2671 	    1, segkmem_alloc, segkmem_free, heaptext_arena, 0, VM_SLEEP);
2672 	*data_arena = vmem_create("module_data", dsize ? moddata : NULL, dsize,
2673 	    1, segkmem_alloc, segkmem_free, heap32_arena, 0, VM_SLEEP);
2674 }
2675 
2676 caddr_t
2677 kobj_text_alloc(vmem_t *arena, size_t size)
2678 {
2679 	return (vmem_alloc(arena, size, VM_SLEEP | VM_BESTFIT));
2680 }
2681 
2682 /*ARGSUSED*/
2683 caddr_t
2684 kobj_texthole_alloc(caddr_t addr, size_t size)
2685 {
2686 	panic("unexpected call to kobj_texthole_alloc()");
2687 	/*NOTREACHED*/
2688 	return (0);
2689 }
2690 
2691 /*ARGSUSED*/
2692 void
2693 kobj_texthole_free(caddr_t addr, size_t size)
2694 {
2695 	panic("unexpected call to kobj_texthole_free()");
2696 }
2697 
2698 /*
2699  * This is called just after configure() in startup().
2700  *
2701  * The ISALIST concept is a bit hopeless on Intel, because
2702  * there's no guarantee of an ever-more-capable processor
2703  * given that various parts of the instruction set may appear
2704  * and disappear between different implementations.
2705  *
2706  * While it would be possible to correct it and even enhance
2707  * it somewhat, the explicit hardware capability bitmask allows
2708  * more flexibility.
2709  *
2710  * So, we just leave this alone.
2711  */
2712 void
2713 setx86isalist(void)
2714 {
2715 	char *tp;
2716 	size_t len;
2717 	extern char *isa_list;
2718 
2719 #define	TBUFSIZE	1024
2720 
2721 	tp = kmem_alloc(TBUFSIZE, KM_SLEEP);
2722 	*tp = '\0';
2723 
2724 #if defined(__amd64)
2725 	(void) strcpy(tp, "amd64 ");
2726 #endif
2727 
2728 	switch (x86_vendor) {
2729 	case X86_VENDOR_Intel:
2730 	case X86_VENDOR_AMD:
2731 	case X86_VENDOR_TM:
2732 		if (x86_feature & X86_CMOV) {
2733 			/*
2734 			 * Pentium Pro or later
2735 			 */
2736 			(void) strcat(tp, "pentium_pro");
2737 			(void) strcat(tp, x86_feature & X86_MMX ?
2738 			    "+mmx pentium_pro " : " ");
2739 		}
2740 		/*FALLTHROUGH*/
2741 	case X86_VENDOR_Cyrix:
2742 		/*
2743 		 * The Cyrix 6x86 does not have any Pentium features
2744 		 * accessible while not at privilege level 0.
2745 		 */
2746 		if (x86_feature & X86_CPUID) {
2747 			(void) strcat(tp, "pentium");
2748 			(void) strcat(tp, x86_feature & X86_MMX ?
2749 			    "+mmx pentium " : " ");
2750 		}
2751 		break;
2752 	default:
2753 		break;
2754 	}
2755 	(void) strcat(tp, "i486 i386 i86");
2756 	len = strlen(tp) + 1;   /* account for NULL at end of string */
2757 	isa_list = strcpy(kmem_alloc(len, KM_SLEEP), tp);
2758 	kmem_free(tp, TBUFSIZE);
2759 
2760 #undef TBUFSIZE
2761 }
2762 
2763 
2764 #ifdef __amd64
2765 
2766 void *
2767 device_arena_alloc(size_t size, int vm_flag)
2768 {
2769 	return (vmem_alloc(device_arena, size, vm_flag));
2770 }
2771 
2772 void
2773 device_arena_free(void *vaddr, size_t size)
2774 {
2775 	vmem_free(device_arena, vaddr, size);
2776 }
2777 
2778 #else
2779 
2780 void *
2781 device_arena_alloc(size_t size, int vm_flag)
2782 {
2783 	caddr_t	vaddr;
2784 	uintptr_t v;
2785 	size_t	start;
2786 	size_t	end;
2787 
2788 	vaddr = vmem_alloc(heap_arena, size, vm_flag);
2789 	if (vaddr == NULL)
2790 		return (NULL);
2791 
2792 	v = (uintptr_t)vaddr;
2793 	ASSERT(v >= kernelbase);
2794 	ASSERT(v + size <= ptable_va);
2795 
2796 	start = btop(v - kernelbase);
2797 	end = btop(v + size - 1 - kernelbase);
2798 	ASSERT(start < toxic_bit_map_len);
2799 	ASSERT(end < toxic_bit_map_len);
2800 
2801 	while (start <= end) {
2802 		BT_ATOMIC_SET(toxic_bit_map, start);
2803 		++start;
2804 	}
2805 	return (vaddr);
2806 }
2807 
2808 void
2809 device_arena_free(void *vaddr, size_t size)
2810 {
2811 	uintptr_t v = (uintptr_t)vaddr;
2812 	size_t	start;
2813 	size_t	end;
2814 
2815 	ASSERT(v >= kernelbase);
2816 	ASSERT(v + size <= ptable_va);
2817 
2818 	start = btop(v - kernelbase);
2819 	end = btop(v + size - 1 - kernelbase);
2820 	ASSERT(start < toxic_bit_map_len);
2821 	ASSERT(end < toxic_bit_map_len);
2822 
2823 	while (start <= end) {
2824 		ASSERT(BT_TEST(toxic_bit_map, start) != 0);
2825 		BT_ATOMIC_CLEAR(toxic_bit_map, start);
2826 		++start;
2827 	}
2828 	vmem_free(heap_arena, vaddr, size);
2829 }
2830 
2831 /*
2832  * returns 1st address in range that is in device arena, or NULL
2833  * if len is not NULL it returns the length of the toxic range
2834  */
2835 void *
2836 device_arena_contains(void *vaddr, size_t size, size_t *len)
2837 {
2838 	uintptr_t v = (uintptr_t)vaddr;
2839 	uintptr_t eaddr = v + size;
2840 	size_t start;
2841 	size_t end;
2842 
2843 	/*
2844 	 * if called very early by kmdb, just return NULL
2845 	 */
2846 	if (toxic_bit_map == NULL)
2847 		return (NULL);
2848 
2849 	/*
2850 	 * First check if we're completely outside the bitmap range.
2851 	 */
2852 	if (v >= ptable_va || eaddr < kernelbase)
2853 		return (NULL);
2854 
2855 	/*
2856 	 * Trim ends of search to look at only what the bitmap covers.
2857 	 */
2858 	if (v < kernelbase)
2859 		v = kernelbase;
2860 	start = btop(v - kernelbase);
2861 	end = btop(eaddr - kernelbase);
2862 	if (end >= toxic_bit_map_len)
2863 		end = toxic_bit_map_len;
2864 
2865 	if (bt_range(toxic_bit_map, &start, &end, end) == 0)
2866 		return (NULL);
2867 
2868 	v = kernelbase + ptob(start);
2869 	if (len != NULL)
2870 		*len = ptob(end - start);
2871 	return ((void *)v);
2872 }
2873 
2874 #endif
2875