xref: /titanic_41/usr/src/uts/i86pc/os/startup.c (revision 70025d765b044c6d8594bb965a2247a61e991a99)
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 prom_setup(void);
1268 
1269 	PRM_POINT("startup_modules() starting...");
1270 	/*
1271 	 * Initialize ten-micro second timer so that drivers will
1272 	 * not get short changed in their init phase. This was
1273 	 * not getting called until clkinit which, on fast cpu's
1274 	 * caused the drv_usecwait to be way too short.
1275 	 */
1276 	microfind();
1277 
1278 	/*
1279 	 * Read the GMT lag from /etc/rtc_config.
1280 	 */
1281 	gmt_lag = process_rtc_config_file();
1282 
1283 	/*
1284 	 * Calculate default settings of system parameters based upon
1285 	 * maxusers, yet allow to be overridden via the /etc/system file.
1286 	 */
1287 	param_calc(0);
1288 
1289 	mod_setup();
1290 
1291 	/*
1292 	 * Setup machine check architecture on P6
1293 	 */
1294 	setup_mca();
1295 
1296 	/*
1297 	 * Initialize system parameters.
1298 	 */
1299 	param_init();
1300 
1301 	/*
1302 	 * maxmem is the amount of physical memory we're playing with.
1303 	 */
1304 	maxmem = physmem;
1305 
1306 	/*
1307 	 * Initialize the hat layer.
1308 	 */
1309 	hat_init();
1310 
1311 	/*
1312 	 * Initialize segment management stuff.
1313 	 */
1314 	seg_init();
1315 
1316 	if (modload("fs", "specfs") == -1)
1317 		halt("Can't load specfs");
1318 
1319 	if (modload("fs", "devfs") == -1)
1320 		halt("Can't load devfs");
1321 
1322 	dispinit();
1323 
1324 	/*
1325 	 * This is needed here to initialize hw_serial[] for cluster booting.
1326 	 */
1327 	if ((i = modload("misc", "sysinit")) != (unsigned int)-1)
1328 		(void) modunload(i);
1329 	else
1330 		cmn_err(CE_CONT, "sysinit load failed");
1331 
1332 	/* Read cluster configuration data. */
1333 	clconf_init();
1334 
1335 	/*
1336 	 * Create a kernel device tree. First, create rootnex and
1337 	 * then invoke bus specific code to probe devices.
1338 	 */
1339 	setup_ddi();
1340 	/*
1341 	 * Fake a prom tree such that /dev/openprom continues to work
1342 	 */
1343 	prom_setup();
1344 
1345 	/*
1346 	 * Load all platform specific modules
1347 	 */
1348 	psm_modload();
1349 
1350 	PRM_POINT("startup_modules() done");
1351 }
1352 
1353 static void
1354 startup_bop_gone(void)
1355 {
1356 	PRM_POINT("startup_bop_gone() starting...");
1357 
1358 	/*
1359 	 * Do final allocations of HAT data structures that need to
1360 	 * be allocated before quiescing the boot loader.
1361 	 */
1362 	PRM_POINT("Calling hat_kern_alloc()...");
1363 	hat_kern_alloc();
1364 	PRM_POINT("hat_kern_alloc() done");
1365 
1366 	/*
1367 	 * Setup MTRR (Memory type range registers)
1368 	 */
1369 	setup_mtrr();
1370 	PRM_POINT("startup_bop_gone() done");
1371 }
1372 
1373 /*
1374  * Walk through the pagetables looking for pages mapped in by boot.  If the
1375  * setaside flag is set the pages are expected to be returned to the
1376  * kernel later in boot, so we add them to the bootpages list.
1377  */
1378 static void
1379 protect_boot_range(uintptr_t low, uintptr_t high, int setaside)
1380 {
1381 	uintptr_t va = low;
1382 	size_t len;
1383 	uint_t prot;
1384 	pfn_t pfn;
1385 	page_t *pp;
1386 	pgcnt_t boot_protect_cnt = 0;
1387 
1388 	while (hat_boot_probe(&va, &len, &pfn, &prot) != 0 && va < high) {
1389 		if (va + len >= high)
1390 			panic("0x%lx byte mapping at 0x%p exceeds boot's "
1391 			    "legal range.", len, (void *)va);
1392 
1393 		while (len > 0) {
1394 			pp = page_numtopp_alloc(pfn);
1395 			if (pp != NULL) {
1396 				if (setaside == 0)
1397 					panic("Unexpected mapping by boot.  "
1398 					    "addr=%p pfn=%lx\n",
1399 					    (void *)va, pfn);
1400 
1401 				pp->p_next = bootpages;
1402 				bootpages = pp;
1403 				++boot_protect_cnt;
1404 			}
1405 
1406 			++pfn;
1407 			len -= MMU_PAGESIZE;
1408 			va += MMU_PAGESIZE;
1409 		}
1410 	}
1411 	PRM_DEBUG(boot_protect_cnt);
1412 }
1413 
1414 static void
1415 startup_vm(void)
1416 {
1417 	struct segmap_crargs a;
1418 	extern void hat_kern_setup(void);
1419 	pgcnt_t pages_left;
1420 
1421 	extern int exec_lpg_disable, use_brk_lpg, use_stk_lpg, use_zmap_lpg;
1422 	extern pgcnt_t auto_lpg_min_physmem;
1423 
1424 	PRM_POINT("startup_vm() starting...");
1425 
1426 	/*
1427 	 * The next two loops are done in distinct steps in order
1428 	 * to be sure that any page that is doubly mapped (both above
1429 	 * KERNEL_TEXT and below kernelbase) is dealt with correctly.
1430 	 * Note this may never happen, but it might someday.
1431 	 */
1432 
1433 	bootpages = NULL;
1434 	PRM_POINT("Protecting boot pages");
1435 	/*
1436 	 * Protect any pages mapped above KERNEL_TEXT that somehow have
1437 	 * page_t's. This can only happen if something weird allocated
1438 	 * in this range (like kadb/kmdb).
1439 	 */
1440 	protect_boot_range(KERNEL_TEXT, (uintptr_t)-1, 0);
1441 
1442 	/*
1443 	 * Before we can take over memory allocation/mapping from the boot
1444 	 * loader we must remove from our free page lists any boot pages that
1445 	 * will stay mapped until release_bootstrap().
1446 	 */
1447 	protect_boot_range(0, kernelbase, 1);
1448 #if defined(__amd64)
1449 	protect_boot_range(BOOT_DOUBLEMAP_BASE,
1450 	    BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE, 0);
1451 #endif
1452 
1453 	/*
1454 	 * Copy in boot's page tables, set up extra page tables for the kernel,
1455 	 * and switch to the kernel's context.
1456 	 */
1457 	PRM_POINT("Calling hat_kern_setup()...");
1458 	hat_kern_setup();
1459 
1460 	/*
1461 	 * It is no longer safe to call BOP_ALLOC(), so make sure we don't.
1462 	 */
1463 	bootops->bsys_alloc = NULL;
1464 	PRM_POINT("hat_kern_setup() done");
1465 
1466 	hat_cpu_online(CPU);
1467 
1468 	/*
1469 	 * Before we call kvm_init(), we need to establish the final size
1470 	 * of the kernel's heap.  So, we need to figure out how much space
1471 	 * to set aside for segkp, segkpm, and segmap.
1472 	 */
1473 	final_kernelheap = (caddr_t)ROUND_UP_LPAGE(kernelbase);
1474 #if defined(__amd64)
1475 	if (kpm_desired) {
1476 		/*
1477 		 * Segkpm appears at the bottom of the kernel's address
1478 		 * range.  To detect accidental overruns of the user
1479 		 * address space, we leave a "red zone" of unmapped memory
1480 		 * between kernelbase and the beginning of segkpm.
1481 		 */
1482 		kpm_vbase = final_kernelheap + KERNEL_REDZONE_SIZE;
1483 		kpm_size = mmu_ptob(physmax);
1484 		PRM_DEBUG(kpm_vbase);
1485 		PRM_DEBUG(kpm_size);
1486 		final_kernelheap =
1487 		    (caddr_t)ROUND_UP_TOPLEVEL(kpm_vbase + kpm_size);
1488 	}
1489 
1490 	if (!segkp_fromheap) {
1491 		size_t sz = mmu_ptob(segkpsize);
1492 
1493 		/*
1494 		 * determine size of segkp and adjust the bottom of the
1495 		 * kernel's heap.
1496 		 */
1497 		if (sz < SEGKPMINSIZE || sz > SEGKPMAXSIZE) {
1498 			sz = SEGKPDEFSIZE;
1499 			cmn_err(CE_WARN, "!Illegal value for segkpsize. "
1500 			    "segkpsize has been reset to %ld pages",
1501 			    mmu_btop(sz));
1502 		}
1503 		sz = MIN(sz, MAX(SEGKPMINSIZE, mmu_ptob(physmem)));
1504 
1505 		segkpsize = mmu_btop(ROUND_UP_LPAGE(sz));
1506 		segkp_base = final_kernelheap;
1507 		PRM_DEBUG(segkpsize);
1508 		PRM_DEBUG(segkp_base);
1509 		final_kernelheap = segkp_base + mmu_ptob(segkpsize);
1510 		PRM_DEBUG(final_kernelheap);
1511 	}
1512 
1513 	/*
1514 	 * put the range of VA for device mappings next
1515 	 */
1516 	toxic_addr = (uintptr_t)final_kernelheap;
1517 	PRM_DEBUG(toxic_addr);
1518 	final_kernelheap = (char *)toxic_addr + toxic_size;
1519 #endif
1520 	PRM_DEBUG(final_kernelheap);
1521 	ASSERT(final_kernelheap < boot_kernelheap);
1522 
1523 	/*
1524 	 * Users can change segmapsize through eeprom or /etc/system.
1525 	 * If the variable is tuned through eeprom, there is no upper
1526 	 * bound on the size of segmap.  If it is tuned through
1527 	 * /etc/system on 32-bit systems, it must be no larger than we
1528 	 * planned for in startup_memlist().
1529 	 */
1530 	segmapsize = MAX(ROUND_UP_LPAGE(segmapsize), SEGMAPDEFAULT);
1531 	segkmap_start = ROUND_UP_LPAGE((uintptr_t)final_kernelheap);
1532 
1533 #if defined(__i386)
1534 	if (segmapsize > segmap_reserved) {
1535 		cmn_err(CE_NOTE, "!segmapsize may not be set > 0x%lx in "
1536 		    "/etc/system.  Use eeprom.", (long)SEGMAPMAX);
1537 		segmapsize = segmap_reserved;
1538 	}
1539 	/*
1540 	 * 32-bit systems don't have segkpm or segkp, so segmap appears at
1541 	 * the bottom of the kernel's address range.  Set aside space for a
1542 	 * red zone just below the start of segmap.
1543 	 */
1544 	segkmap_start += KERNEL_REDZONE_SIZE;
1545 	segmapsize -= KERNEL_REDZONE_SIZE;
1546 #endif
1547 	final_kernelheap = (char *)(segkmap_start + segmapsize);
1548 
1549 	PRM_DEBUG(segkmap_start);
1550 	PRM_DEBUG(segmapsize);
1551 	PRM_DEBUG(final_kernelheap);
1552 
1553 	/*
1554 	 * Initialize VM system
1555 	 */
1556 	PRM_POINT("Calling kvm_init()...");
1557 	kvm_init();
1558 	PRM_POINT("kvm_init() done");
1559 
1560 	/*
1561 	 * Tell kmdb that the VM system is now working
1562 	 */
1563 	if (boothowto & RB_DEBUG)
1564 		kdi_dvec_vmready();
1565 
1566 	/*
1567 	 * Mangle the brand string etc.
1568 	 */
1569 	cpuid_pass3(CPU);
1570 
1571 	PRM_DEBUG(final_kernelheap);
1572 
1573 	/*
1574 	 * Now that we can use memory outside the top 4GB (on 64-bit
1575 	 * systems) and we know the size of segmap, we can set the final
1576 	 * size of the kernel's heap.  Note: on 64-bit systems we still
1577 	 * can't touch anything in the bottom half of the top 4GB range
1578 	 * because boot still has pages mapped there.
1579 	 */
1580 	if (final_kernelheap < boot_kernelheap) {
1581 		kernelheap_extend(final_kernelheap, boot_kernelheap);
1582 #if defined(__amd64)
1583 		kmem_setaside = vmem_xalloc(heap_arena, BOOT_DOUBLEMAP_SIZE,
1584 		    MMU_PAGESIZE, 0, 0, (void *)(BOOT_DOUBLEMAP_BASE),
1585 		    (void *)(BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE),
1586 		    VM_NOSLEEP | VM_BESTFIT | VM_PANIC);
1587 		PRM_DEBUG(kmem_setaside);
1588 		if (kmem_setaside == NULL)
1589 			panic("Could not protect boot's memory");
1590 #endif
1591 	}
1592 	/*
1593 	 * Now that the kernel heap may have grown significantly, we need
1594 	 * to make all the remaining page_t's available to back that memory.
1595 	 *
1596 	 * XX64 this should probably wait till after release boot-strap too.
1597 	 */
1598 	pages_left = npages - boot_npages;
1599 	if (pages_left > 0) {
1600 		PRM_DEBUG(pages_left);
1601 		(void) kphysm_init(NULL, memseg_base, boot_npages, pages_left);
1602 	}
1603 
1604 #if defined(__amd64)
1605 
1606 	/*
1607 	 * Create the device arena for toxic (to dtrace/kmdb) mappings.
1608 	 */
1609 	device_arena = vmem_create("device", (void *)toxic_addr,
1610 	    toxic_size, MMU_PAGESIZE, NULL, NULL, NULL, 0, VM_SLEEP);
1611 
1612 #else	/* __i386 */
1613 
1614 	/*
1615 	 * allocate the bit map that tracks toxic pages
1616 	 */
1617 	toxic_bit_map_len = btop((ulong_t)(ptable_va - kernelbase));
1618 	PRM_DEBUG(toxic_bit_map_len);
1619 	toxic_bit_map =
1620 	    kmem_zalloc(BT_SIZEOFMAP(toxic_bit_map_len), KM_NOSLEEP);
1621 	ASSERT(toxic_bit_map != NULL);
1622 	PRM_DEBUG(toxic_bit_map);
1623 
1624 #endif	/* __i386 */
1625 
1626 
1627 	/*
1628 	 * Now that we've got more VA, as well as the ability to allocate from
1629 	 * it, tell the debugger.
1630 	 */
1631 	if (boothowto & RB_DEBUG)
1632 		kdi_dvec_memavail();
1633 
1634 	/*
1635 	 * The following code installs a special page fault handler (#pf)
1636 	 * to work around a pentium bug.
1637 	 */
1638 #if !defined(__amd64)
1639 	if (x86_type == X86_TYPE_P5) {
1640 		gate_desc_t *newidt;
1641 		desctbr_t    newidt_r;
1642 
1643 		if ((newidt = kmem_zalloc(MMU_PAGESIZE, KM_NOSLEEP)) == NULL)
1644 			panic("failed to install pentium_pftrap");
1645 
1646 		bcopy(idt0, newidt, sizeof (idt0));
1647 		set_gatesegd(&newidt[T_PGFLT], &pentium_pftrap,
1648 		    KCS_SEL, 0, SDT_SYSIGT, SEL_KPL);
1649 
1650 		(void) as_setprot(&kas, (caddr_t)newidt, MMU_PAGESIZE,
1651 		    PROT_READ|PROT_EXEC);
1652 
1653 		newidt_r.dtr_limit = sizeof (idt0) - 1;
1654 		newidt_r.dtr_base = (uintptr_t)newidt;
1655 		CPU->cpu_idt = newidt;
1656 		wr_idtr(&newidt_r);
1657 	}
1658 #endif	/* !__amd64 */
1659 
1660 	/*
1661 	 * Map page pfn=0 for drivers, such as kd, that need to pick up
1662 	 * parameters left there by controllers/BIOS.
1663 	 */
1664 	PRM_POINT("setup up p0_va");
1665 	p0_va = i86devmap(0, 1, PROT_READ);
1666 	PRM_DEBUG(p0_va);
1667 
1668 	/*
1669 	 * If the following is true, someone has patched phsymem to be less
1670 	 * than the number of pages that the system actually has.  Remove
1671 	 * pages until system memory is limited to the requested amount.
1672 	 * Since we have allocated page structures for all pages, we
1673 	 * correct the amount of memory we want to remove by the size of
1674 	 * the memory used to hold page structures for the non-used pages.
1675 	 */
1676 	if (physmem < npages) {
1677 		uint_t diff;
1678 		offset_t off;
1679 		struct page *pp;
1680 		caddr_t rand_vaddr;
1681 		struct seg kseg;
1682 
1683 		cmn_err(CE_WARN, "limiting physmem to %lu pages", physmem);
1684 
1685 		off = 0;
1686 		diff = npages - physmem;
1687 		diff -= mmu_btopr(diff * sizeof (struct page));
1688 		kseg.s_as = &kas;
1689 		while (diff--) {
1690 			rand_vaddr = (caddr_t)
1691 			    (((uintptr_t)&unused_pages_vp >> 7) ^
1692 			    (uintptr_t)((u_offset_t)off >> MMU_PAGESHIFT));
1693 			pp = page_create_va(&unused_pages_vp, off, MMU_PAGESIZE,
1694 				PG_WAIT | PG_EXCL, &kseg, rand_vaddr);
1695 			if (pp == NULL) {
1696 				panic("limited physmem too much!");
1697 				/*NOTREACHED*/
1698 			}
1699 			page_io_unlock(pp);
1700 			page_downgrade(pp);
1701 			availrmem--;
1702 			off += MMU_PAGESIZE;
1703 		}
1704 	}
1705 
1706 	cmn_err(CE_CONT, "?mem = %luK (0x%lx)\n",
1707 	    physinstalled << (MMU_PAGESHIFT - 10), ptob(physinstalled));
1708 
1709 	/*
1710 	 * disable automatic large pages for small memory systems or
1711 	 * when the disable flag is set.
1712 	 */
1713 	if (physmem < auto_lpg_min_physmem || auto_lpg_disable) {
1714 		exec_lpg_disable = 1;
1715 		use_brk_lpg = 0;
1716 		use_stk_lpg = 0;
1717 		use_zmap_lpg = 0;
1718 	}
1719 
1720 	PRM_POINT("Calling hat_init_finish()...");
1721 	hat_init_finish();
1722 	PRM_POINT("hat_init_finish() done");
1723 
1724 	/*
1725 	 * Initialize the segkp segment type.
1726 	 */
1727 	rw_enter(&kas.a_lock, RW_WRITER);
1728 	if (!segkp_fromheap) {
1729 		if (seg_attach(&kas, (caddr_t)segkp_base, mmu_ptob(segkpsize),
1730 		    segkp) < 0) {
1731 			panic("startup: cannot attach segkp");
1732 			/*NOTREACHED*/
1733 		}
1734 	} else {
1735 		/*
1736 		 * For 32 bit x86 systems, we will have segkp under the heap.
1737 		 * There will not be a segkp segment.  We do, however, need
1738 		 * to fill in the seg structure.
1739 		 */
1740 		segkp->s_as = &kas;
1741 	}
1742 	if (segkp_create(segkp) != 0) {
1743 		panic("startup: segkp_create failed");
1744 		/*NOTREACHED*/
1745 	}
1746 	PRM_DEBUG(segkp);
1747 	rw_exit(&kas.a_lock);
1748 
1749 	/*
1750 	 * kpm segment
1751 	 */
1752 	segmap_kpm = 0;
1753 	if (kpm_desired) {
1754 		kpm_init();
1755 		kpm_enable = 1;
1756 	}
1757 
1758 	/*
1759 	 * Now create segmap segment.
1760 	 */
1761 	rw_enter(&kas.a_lock, RW_WRITER);
1762 	if (seg_attach(&kas, (caddr_t)segkmap_start, segmapsize, segkmap) < 0) {
1763 		panic("cannot attach segkmap");
1764 		/*NOTREACHED*/
1765 	}
1766 	PRM_DEBUG(segkmap);
1767 
1768 	/*
1769 	 * The 64 bit HAT permanently maps only segmap's page tables.
1770 	 * The 32 bit HAT maps the heap's page tables too.
1771 	 */
1772 #if defined(__amd64)
1773 	hat_kmap_init(segkmap_start, segmapsize);
1774 #else /* __i386 */
1775 	ASSERT(segkmap_start + segmapsize == (uintptr_t)final_kernelheap);
1776 	hat_kmap_init(segkmap_start, (uintptr_t)ekernelheap - segkmap_start);
1777 #endif /* __i386 */
1778 
1779 	a.prot = PROT_READ | PROT_WRITE;
1780 	a.shmsize = 0;
1781 	a.nfreelist = segmapfreelists;
1782 
1783 	if (segmap_create(segkmap, (caddr_t)&a) != 0)
1784 		panic("segmap_create segkmap");
1785 	rw_exit(&kas.a_lock);
1786 
1787 	setup_vaddr_for_ppcopy(CPU);
1788 
1789 	segdev_init();
1790 	pmem_init();
1791 	PRM_POINT("startup_vm() done");
1792 }
1793 
1794 static void
1795 startup_end(void)
1796 {
1797 	extern void setx86isalist(void);
1798 
1799 	PRM_POINT("startup_end() starting...");
1800 
1801 	/*
1802 	 * Perform tasks that get done after most of the VM
1803 	 * initialization has been done but before the clock
1804 	 * and other devices get started.
1805 	 */
1806 	kern_setup1();
1807 
1808 	/*
1809 	 * Perform CPC initialization for this CPU.
1810 	 */
1811 	kcpc_hw_init(CPU);
1812 
1813 #if defined(__amd64)
1814 	/*
1815 	 * Validate support for syscall/sysret
1816 	 * XX64 -- include SSE, SSE2, etc. here too?
1817 	 */
1818 	if ((x86_feature & X86_ASYSC) == 0) {
1819 		cmn_err(CE_WARN,
1820 		    "cpu%d does not support syscall/sysret", CPU->cpu_id);
1821 	}
1822 #endif
1823 	/*
1824 	 * Configure the system.
1825 	 */
1826 	PRM_POINT("Calling configure()...");
1827 	configure();		/* set up devices */
1828 	PRM_POINT("configure() done");
1829 
1830 	/*
1831 	 * Set the isa_list string to the defined instruction sets we
1832 	 * support.
1833 	 */
1834 	setx86isalist();
1835 	init_intr_threads(CPU);
1836 	psm_install();
1837 
1838 	/*
1839 	 * We're done with bootops.  We don't unmap the bootstrap yet because
1840 	 * we're still using bootsvcs.
1841 	 */
1842 	PRM_POINT("zeroing out bootops");
1843 	*bootopsp = (struct bootops *)0;
1844 	bootops = (struct bootops *)NULL;
1845 
1846 	PRM_POINT("Enabling interrupts");
1847 	(*picinitf)();
1848 	sti();
1849 
1850 	(void) add_avsoftintr((void *)&softlevel1_hdl, 1, softlevel1,
1851 		"softlevel1", NULL, NULL); /* XXX to be moved later */
1852 
1853 	PRM_POINT("startup_end() done");
1854 }
1855 
1856 extern char hw_serial[];
1857 char *_hs1107 = hw_serial;
1858 ulong_t  _bdhs34;
1859 
1860 void
1861 post_startup(void)
1862 {
1863 	/*
1864 	 * Set the system wide, processor-specific flags to be passed
1865 	 * to userland via the aux vector for performance hints and
1866 	 * instruction set extensions.
1867 	 */
1868 	bind_hwcap();
1869 
1870 	/*
1871 	 * Load the System Management BIOS into the global ksmbios handle,
1872 	 * if an SMBIOS is present on this system.
1873 	 */
1874 	ksmbios = smbios_open(NULL, SMB_VERSION, ksmbios_flags, NULL);
1875 
1876 	/*
1877 	 * Startup memory scrubber.
1878 	 */
1879 	memscrub_init();
1880 
1881 	/*
1882 	 * Perform forceloading tasks for /etc/system.
1883 	 */
1884 	(void) mod_sysctl(SYS_FORCELOAD, NULL);
1885 
1886 	/*
1887 	 * ON4.0: Force /proc module in until clock interrupt handle fixed
1888 	 * ON4.0: This must be fixed or restated in /etc/systems.
1889 	 */
1890 	(void) modload("fs", "procfs");
1891 
1892 #if defined(__i386)
1893 	/*
1894 	 * Check for required functional Floating Point hardware,
1895 	 * unless FP hardware explicitly disabled.
1896 	 */
1897 	if (fpu_exists && (fpu_pentium_fdivbug || fp_kind == FP_NO))
1898 		halt("No working FP hardware found");
1899 #endif
1900 
1901 	maxmem = freemem;
1902 
1903 	add_cpunode2devtree(CPU->cpu_id, CPU->cpu_m.mcpu_cpi);
1904 
1905 	/*
1906 	 * Perform the formal initialization of the boot chip,
1907 	 * and associate the boot cpu with it.
1908 	 * This must be done after the cpu node for CPU has been
1909 	 * added to the device tree, when the necessary probing to
1910 	 * know the chip type and chip "id" is performed.
1911 	 */
1912 	chip_cpu_init(CPU);
1913 	chip_cpu_assign(CPU);
1914 }
1915 
1916 static int
1917 pp_in_ramdisk(page_t *pp)
1918 {
1919 	extern uint64_t ramdisk_start, ramdisk_end;
1920 
1921 	return ((pp->p_pagenum >= btop(ramdisk_start)) &&
1922 	    (pp->p_pagenum < btopr(ramdisk_end)));
1923 }
1924 
1925 void
1926 release_bootstrap(void)
1927 {
1928 	int root_is_ramdisk;
1929 	pfn_t pfn;
1930 	page_t *pp;
1931 	extern void kobj_boot_unmountroot(void);
1932 	extern dev_t rootdev;
1933 
1934 	/* unmount boot ramdisk and release kmem usage */
1935 	kobj_boot_unmountroot();
1936 
1937 	/*
1938 	 * We're finished using the boot loader so free its pages.
1939 	 */
1940 	PRM_POINT("Unmapping lower boot pages");
1941 	clear_boot_mappings(0, kernelbase);
1942 #if defined(__amd64)
1943 	PRM_POINT("Unmapping upper boot pages");
1944 	clear_boot_mappings(BOOT_DOUBLEMAP_BASE,
1945 	    BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE);
1946 #endif
1947 
1948 	/*
1949 	 * If root isn't on ramdisk, destroy the hardcoded
1950 	 * ramdisk node now and release the memory. Else,
1951 	 * ramdisk memory is kept in rd_pages.
1952 	 */
1953 	root_is_ramdisk = (getmajor(rootdev) == ddi_name_to_major("ramdisk"));
1954 	if (!root_is_ramdisk) {
1955 		dev_info_t *dip = ddi_find_devinfo("ramdisk", -1, 0);
1956 		ASSERT(dip && ddi_get_parent(dip) == ddi_root_node());
1957 		ndi_rele_devi(dip);	/* held from ddi_find_devinfo */
1958 		(void) ddi_remove_child(dip, 0);
1959 	}
1960 
1961 	PRM_POINT("Releasing boot pages");
1962 	while (bootpages) {
1963 		pp = bootpages;
1964 		bootpages = pp->p_next;
1965 		if (root_is_ramdisk && pp_in_ramdisk(pp)) {
1966 			pp->p_next = rd_pages;
1967 			rd_pages = pp;
1968 			continue;
1969 		}
1970 		pp->p_next = (struct page *)0;
1971 		page_free(pp, 1);
1972 	}
1973 
1974 	/*
1975 	 * Find 1 page below 1 MB so that other processors can boot up.
1976 	 * Make sure it has a kernel VA as well as a 1:1 mapping.
1977 	 * We should have just free'd one up.
1978 	 */
1979 	if (use_mp) {
1980 		for (pfn = 1; pfn < btop(1*1024*1024); pfn++) {
1981 			if (page_numtopp_alloc(pfn) == NULL)
1982 				continue;
1983 			rm_platter_va = i86devmap(pfn, 1,
1984 			    PROT_READ | PROT_WRITE | PROT_EXEC);
1985 			rm_platter_pa = ptob(pfn);
1986 			hat_devload(kas.a_hat,
1987 			    (caddr_t)(uintptr_t)rm_platter_pa, MMU_PAGESIZE,
1988 			    pfn, PROT_READ | PROT_WRITE | PROT_EXEC,
1989 			    HAT_LOAD_NOCONSIST);
1990 			break;
1991 		}
1992 		if (pfn == btop(1*1024*1024))
1993 			panic("No page available for starting "
1994 			    "other processors");
1995 	}
1996 
1997 #if defined(__amd64)
1998 	PRM_POINT("Returning boot's VA space to kernel heap");
1999 	if (kmem_setaside != NULL)
2000 		vmem_free(heap_arena, kmem_setaside, BOOT_DOUBLEMAP_SIZE);
2001 #endif
2002 }
2003 
2004 /*
2005  * Initialize the platform-specific parts of a page_t.
2006  */
2007 void
2008 add_physmem_cb(page_t *pp, pfn_t pnum)
2009 {
2010 	pp->p_pagenum = pnum;
2011 	pp->p_mapping = NULL;
2012 	pp->p_embed = 0;
2013 	pp->p_share = 0;
2014 	pp->p_mlentry = 0;
2015 }
2016 
2017 /*
2018  * kphysm_init() initializes physical memory.
2019  */
2020 static pgcnt_t
2021 kphysm_init(
2022 	page_t *inpp,
2023 	struct memseg *memsegp,
2024 	pgcnt_t start,
2025 	pgcnt_t npages)
2026 {
2027 	struct memlist	*pmem;
2028 	struct memseg	*cur_memseg;
2029 	struct memseg	**memsegpp;
2030 	pfn_t		base_pfn;
2031 	pgcnt_t		num;
2032 	pgcnt_t		total_skipped = 0;
2033 	pgcnt_t		skipping = 0;
2034 	pgcnt_t		pages_done = 0;
2035 	pgcnt_t		largepgcnt;
2036 	uint64_t	addr;
2037 	uint64_t	size;
2038 	page_t		*pp = inpp;
2039 	int		dobreak = 0;
2040 	extern pfn_t	ddiphysmin;
2041 
2042 	ASSERT(page_hash != NULL && page_hashsz != 0);
2043 
2044 	for (cur_memseg = memsegp; cur_memseg->pages != NULL; cur_memseg++);
2045 	ASSERT(cur_memseg == memsegp || start > 0);
2046 
2047 	for (pmem = phys_avail; pmem && npages; pmem = pmem->next) {
2048 		/*
2049 		 * In a 32 bit kernel can't use higher memory if we're
2050 		 * not booting in PAE mode. This check takes care of that.
2051 		 */
2052 		addr = pmem->address;
2053 		size = pmem->size;
2054 		if (btop(addr) > physmax)
2055 			continue;
2056 
2057 		/*
2058 		 * align addr and size - they may not be at page boundaries
2059 		 */
2060 		if ((addr & MMU_PAGEOFFSET) != 0) {
2061 			addr += MMU_PAGEOFFSET;
2062 			addr &= ~(uint64_t)MMU_PAGEOFFSET;
2063 			size -= addr - pmem->address;
2064 		}
2065 
2066 		/* only process pages below or equal to physmax */
2067 		if ((btop(addr + size) - 1) > physmax)
2068 			size = ptob(physmax - btop(addr) + 1);
2069 
2070 		num = btop(size);
2071 		if (num == 0)
2072 			continue;
2073 
2074 		if (total_skipped < start) {
2075 			if (start - total_skipped > num) {
2076 				total_skipped += num;
2077 				continue;
2078 			}
2079 			skipping = start - total_skipped;
2080 			num -= skipping;
2081 			addr += (MMU_PAGESIZE * skipping);
2082 			total_skipped = start;
2083 		}
2084 		if (num == 0)
2085 			continue;
2086 
2087 		if (num > npages)
2088 			num = npages;
2089 
2090 		npages -= num;
2091 		pages_done += num;
2092 		base_pfn = btop(addr);
2093 
2094 		/*
2095 		 * If the caller didn't provide space for the page
2096 		 * structures, carve them out of the memseg they will
2097 		 * represent.
2098 		 */
2099 		if (pp == NULL) {
2100 			pgcnt_t pp_pgs;
2101 
2102 			if (num <= 1)
2103 				continue;
2104 
2105 			/*
2106 			 * Compute how many of the pages we need to use for
2107 			 * page_ts
2108 			 */
2109 			pp_pgs = (num * sizeof (page_t)) / MMU_PAGESIZE + 1;
2110 			while (mmu_ptob(pp_pgs - 1) / sizeof (page_t) >=
2111 			    num - pp_pgs + 1)
2112 				--pp_pgs;
2113 			PRM_DEBUG(pp_pgs);
2114 
2115 			pp = vmem_alloc(heap_arena, mmu_ptob(pp_pgs),
2116 			    VM_NOSLEEP);
2117 			if (pp == NULL) {
2118 				cmn_err(CE_WARN, "Unable to add %ld pages to "
2119 				    "the system.", num);
2120 				continue;
2121 			}
2122 
2123 			hat_devload(kas.a_hat, (void *)pp, mmu_ptob(pp_pgs),
2124 			    base_pfn, PROT_READ | PROT_WRITE | HAT_UNORDERED_OK,
2125 			    HAT_LOAD | HAT_LOAD_LOCK | HAT_LOAD_NOCONSIST);
2126 			bzero(pp, mmu_ptob(pp_pgs));
2127 			num -= pp_pgs;
2128 			base_pfn += pp_pgs;
2129 		}
2130 
2131 		if (prom_debug)
2132 			prom_printf("MEMSEG addr=0x%" PRIx64
2133 			    " pgs=0x%lx pfn 0x%lx-0x%lx\n",
2134 			    addr, num, base_pfn, base_pfn + num);
2135 
2136 		/*
2137 		 * drop pages below ddiphysmin to simplify ddi memory
2138 		 * allocation with non-zero addr_lo requests.
2139 		 */
2140 		if (base_pfn < ddiphysmin) {
2141 			if (base_pfn + num <= ddiphysmin) {
2142 				/* drop entire range below ddiphysmin */
2143 				continue;
2144 			}
2145 			/* adjust range to ddiphysmin */
2146 			pp += (ddiphysmin - base_pfn);
2147 			num -= (ddiphysmin - base_pfn);
2148 			base_pfn = ddiphysmin;
2149 		}
2150 		/*
2151 		 * Build the memsegs entry
2152 		 */
2153 		cur_memseg->pages = pp;
2154 		cur_memseg->epages = pp + num;
2155 		cur_memseg->pages_base = base_pfn;
2156 		cur_memseg->pages_end = base_pfn + num;
2157 
2158 		/*
2159 		 * insert in memseg list in decreasing pfn range order.
2160 		 * Low memory is typically more fragmented such that this
2161 		 * ordering keeps the larger ranges at the front of the list
2162 		 * for code that searches memseg.
2163 		 */
2164 		memsegpp = &memsegs;
2165 		for (;;) {
2166 			if (*memsegpp == NULL) {
2167 				/* empty memsegs */
2168 				memsegs = cur_memseg;
2169 				break;
2170 			}
2171 			/* check for continuity with start of memsegpp */
2172 			if (cur_memseg->pages_end == (*memsegpp)->pages_base) {
2173 				if (cur_memseg->epages == (*memsegpp)->pages) {
2174 					/*
2175 					 * contiguous pfn and page_t's. Merge
2176 					 * cur_memseg into *memsegpp. Drop
2177 					 * cur_memseg
2178 					 */
2179 					(*memsegpp)->pages_base =
2180 					    cur_memseg->pages_base;
2181 					(*memsegpp)->pages =
2182 					    cur_memseg->pages;
2183 					/*
2184 					 * check if contiguous with the end of
2185 					 * the next memseg.
2186 					 */
2187 					if ((*memsegpp)->next &&
2188 					    ((*memsegpp)->pages_base ==
2189 					    (*memsegpp)->next->pages_end)) {
2190 						cur_memseg = *memsegpp;
2191 						memsegpp = &((*memsegpp)->next);
2192 						dobreak = 1;
2193 					} else {
2194 						break;
2195 					}
2196 				} else {
2197 					/*
2198 					 * contiguous pfn but not page_t's.
2199 					 * drop last pfn/page_t in cur_memseg
2200 					 * to prevent creation of large pages
2201 					 * with noncontiguous page_t's if not
2202 					 * aligned to largest page boundary.
2203 					 */
2204 					largepgcnt = page_get_pagecnt(
2205 					    page_num_pagesizes() - 1);
2206 
2207 					if (cur_memseg->pages_end &
2208 					    (largepgcnt - 1)) {
2209 						num--;
2210 						cur_memseg->epages--;
2211 						cur_memseg->pages_end--;
2212 					}
2213 				}
2214 			}
2215 
2216 			/* check for continuity with end of memsegpp */
2217 			if (cur_memseg->pages_base == (*memsegpp)->pages_end) {
2218 				if (cur_memseg->pages == (*memsegpp)->epages) {
2219 					/*
2220 					 * contiguous pfn and page_t's. Merge
2221 					 * cur_memseg into *memsegpp. Drop
2222 					 * cur_memseg.
2223 					 */
2224 					if (dobreak) {
2225 						/* merge previously done */
2226 						cur_memseg->pages =
2227 						    (*memsegpp)->pages;
2228 						cur_memseg->pages_base =
2229 						    (*memsegpp)->pages_base;
2230 						cur_memseg->next =
2231 						    (*memsegpp)->next;
2232 					} else {
2233 						(*memsegpp)->pages_end =
2234 						    cur_memseg->pages_end;
2235 						(*memsegpp)->epages =
2236 						    cur_memseg->epages;
2237 					}
2238 					break;
2239 				}
2240 				/*
2241 				 * contiguous pfn but not page_t's.
2242 				 * drop first pfn/page_t in cur_memseg
2243 				 * to prevent creation of large pages
2244 				 * with noncontiguous page_t's if not
2245 				 * aligned to largest page boundary.
2246 				 */
2247 				largepgcnt = page_get_pagecnt(
2248 				    page_num_pagesizes() - 1);
2249 				if (base_pfn & (largepgcnt - 1)) {
2250 					num--;
2251 					base_pfn++;
2252 					cur_memseg->pages++;
2253 					cur_memseg->pages_base++;
2254 					pp = cur_memseg->pages;
2255 				}
2256 				if (dobreak)
2257 					break;
2258 			}
2259 
2260 			if (cur_memseg->pages_base >=
2261 			    (*memsegpp)->pages_end) {
2262 				cur_memseg->next = *memsegpp;
2263 				*memsegpp = cur_memseg;
2264 				break;
2265 			}
2266 			if ((*memsegpp)->next == NULL) {
2267 				cur_memseg->next = NULL;
2268 				(*memsegpp)->next = cur_memseg;
2269 				break;
2270 			}
2271 			memsegpp = &((*memsegpp)->next);
2272 			ASSERT(*memsegpp != NULL);
2273 		}
2274 
2275 		/*
2276 		 * add_physmem() initializes the PSM part of the page
2277 		 * struct by calling the PSM back with add_physmem_cb().
2278 		 * In addition it coalesces pages into larger pages as
2279 		 * it initializes them.
2280 		 */
2281 		add_physmem(pp, num, base_pfn);
2282 		cur_memseg++;
2283 		availrmem_initial += num;
2284 		availrmem += num;
2285 
2286 		/*
2287 		 * If the caller provided the page frames to us, then
2288 		 * advance in that list.  Otherwise, prepare to allocate
2289 		 * our own page frames for the next memseg.
2290 		 */
2291 		pp = (inpp == NULL) ? NULL : pp + num;
2292 	}
2293 
2294 	PRM_DEBUG(availrmem_initial);
2295 	PRM_DEBUG(availrmem);
2296 	PRM_DEBUG(freemem);
2297 	build_pfn_hash();
2298 	return (pages_done);
2299 }
2300 
2301 /*
2302  * Kernel VM initialization.
2303  */
2304 static void
2305 kvm_init(void)
2306 {
2307 #ifdef DEBUG
2308 	extern void _start();
2309 
2310 	ASSERT((caddr_t)_start == s_text);
2311 #endif
2312 	ASSERT((((uintptr_t)s_text) & MMU_PAGEOFFSET) == 0);
2313 
2314 	/*
2315 	 * Put the kernel segments in kernel address space.
2316 	 */
2317 	rw_enter(&kas.a_lock, RW_WRITER);
2318 	as_avlinit(&kas);
2319 
2320 	(void) seg_attach(&kas, s_text, e_moddata - s_text, &ktextseg);
2321 	(void) segkmem_create(&ktextseg);
2322 
2323 	(void) seg_attach(&kas, (caddr_t)valloc_base, valloc_sz, &kvalloc);
2324 	(void) segkmem_create(&kvalloc);
2325 
2326 	/*
2327 	 * We're about to map out /boot.  This is the beginning of the
2328 	 * system resource management transition. We can no longer
2329 	 * call into /boot for I/O or memory allocations.
2330 	 *
2331 	 * XX64 - Is this still correct with kernelheap_extend() being called
2332 	 * later than this????
2333 	 */
2334 	(void) seg_attach(&kas, final_kernelheap,
2335 	    ekernelheap - final_kernelheap, &kvseg);
2336 	(void) segkmem_create(&kvseg);
2337 
2338 #if defined(__amd64)
2339 	(void) seg_attach(&kas, (caddr_t)core_base, core_size, &kvseg_core);
2340 	(void) segkmem_create(&kvseg_core);
2341 #endif
2342 
2343 	(void) seg_attach(&kas, (caddr_t)SEGDEBUGBASE, (size_t)SEGDEBUGSIZE,
2344 	    &kdebugseg);
2345 	(void) segkmem_create(&kdebugseg);
2346 
2347 	rw_exit(&kas.a_lock);
2348 
2349 	/*
2350 	 * Ensure that the red zone at kernelbase is never accessible.
2351 	 */
2352 	(void) as_setprot(&kas, (caddr_t)kernelbase, KERNEL_REDZONE_SIZE, 0);
2353 
2354 	/*
2355 	 * Make the text writable so that it can be hot patched by DTrace.
2356 	 */
2357 	(void) as_setprot(&kas, s_text, e_modtext - s_text,
2358 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2359 
2360 	/*
2361 	 * Make data writable until end.
2362 	 */
2363 	(void) as_setprot(&kas, s_data, e_moddata - s_data,
2364 	    PROT_READ | PROT_WRITE | PROT_EXEC);
2365 }
2366 
2367 /*
2368  * These are MTTR registers supported by P6
2369  */
2370 static struct	mtrrvar	mtrrphys_arr[MAX_MTRRVAR];
2371 static uint64_t mtrr64k, mtrr16k1, mtrr16k2;
2372 static uint64_t mtrr4k1, mtrr4k2, mtrr4k3;
2373 static uint64_t mtrr4k4, mtrr4k5, mtrr4k6;
2374 static uint64_t mtrr4k7, mtrr4k8, mtrrcap;
2375 uint64_t mtrrdef, pat_attr_reg;
2376 
2377 /*
2378  * Disable reprogramming of MTRRs by default.
2379  */
2380 int	enable_relaxed_mtrr = 0;
2381 
2382 /*
2383  * These must serve for Pentium, Pentium Pro (P6/Pentium II/Pentium III)
2384  * and Pentium 4, and yes, they are named 0, 1, 2, 4, 3 in ascending
2385  * address order (starting from 0x400).  The Pentium 4 only implements
2386  * 4 sets, and while they are named 0-3 in the doc, the corresponding
2387  * names for P6 are 0,1,2,4.  So define these arrays in address order
2388  * so that they work for both pre-Pentium4 and Pentium 4 processors.
2389  */
2390 
2391 static uint_t	mci_ctl[] = {REG_MC0_CTL, REG_MC1_CTL, REG_MC2_CTL,
2392 		    REG_MC4_CTL, REG_MC3_CTL};
2393 static uint_t	mci_status[] = {REG_MC0_STATUS, REG_MC1_STATUS, REG_MC2_STATUS,
2394 		    REG_MC4_STATUS, REG_MC3_STATUS};
2395 static uint_t	mci_addr[] = {REG_MC0_ADDR, REG_MC1_ADDR, REG_MC2_ADDR,
2396 		    REG_MC4_ADDR, REG_MC3_ADDR};
2397 static int	mca_cnt;
2398 
2399 
2400 void
2401 setup_mca()
2402 {
2403 	int 		i;
2404 	uint64_t	mca_cap;
2405 
2406 	if (!(x86_feature & X86_MCA))
2407 		return;
2408 	mca_cap = rdmsr(REG_MCG_CAP);
2409 	if (mca_cap & MCG_CAP_CTL_P)
2410 		wrmsr(REG_MCG_CTL, -1ULL);	/* all ones */
2411 	mca_cnt = mca_cap & MCG_CAP_COUNT_MASK;
2412 	if (mca_cnt > P6_MCG_CAP_COUNT)
2413 		mca_cnt = P6_MCG_CAP_COUNT;
2414 	for (i = 1; i < mca_cnt; i++)
2415 		wrmsr(mci_ctl[i], -1ULL);	/* all ones */
2416 	for (i = 0; i < mca_cnt; i++)
2417 		wrmsr(mci_status[i], 0ULL);
2418 	setcr4(getcr4() | CR4_MCE);
2419 
2420 }
2421 
2422 int
2423 mca_exception(struct regs *rp)
2424 {
2425 	uint64_t	status, addr;
2426 	int		i, ret = 1, errcode, mserrcode;
2427 
2428 	status = rdmsr(REG_MCG_STATUS);
2429 	if (status & MCG_STATUS_RIPV)
2430 		ret = 0;
2431 	if (status & MCG_STATUS_EIPV)
2432 		cmn_err(CE_WARN, "MCE at 0x%lx", rp->r_pc);
2433 	wrmsr(REG_MCG_STATUS, 0ULL);
2434 	for (i = 0; i < mca_cnt; i++) {
2435 		status = rdmsr(mci_status[i]);
2436 		/*
2437 		 * If status register not valid skip this bank
2438 		 */
2439 		if (!(status & MCI_STATUS_VAL))
2440 			continue;
2441 		errcode = status & MCI_STATUS_ERRCODE;
2442 		mserrcode = (status  >> MSERRCODE_SHFT) & MCI_STATUS_ERRCODE;
2443 		if (status & MCI_STATUS_ADDRV) {
2444 			/*
2445 			 * If mci_addr contains the address where
2446 			 * error occurred, display the address
2447 			 */
2448 			addr = rdmsr(mci_addr[i]);
2449 			cmn_err(CE_WARN, "MCE: Bank %d: error code 0x%x:"\
2450 			    "addr = 0x%" PRIx64 ", model errcode = 0x%x", i,
2451 			    errcode, addr, mserrcode);
2452 		} else {
2453 			cmn_err(CE_WARN,
2454 			    "MCE: Bank %d: error code 0x%x, mserrcode = 0x%x",
2455 			    i, errcode, mserrcode);
2456 		}
2457 		wrmsr(mci_status[i], 0ULL);
2458 	}
2459 	return (ret);
2460 }
2461 
2462 void
2463 setup_mtrr()
2464 {
2465 	int i, ecx;
2466 	int vcnt;
2467 	struct	mtrrvar	*mtrrphys;
2468 
2469 	if (!(x86_feature & X86_MTRR))
2470 		return;
2471 
2472 	mtrrcap = rdmsr(REG_MTRRCAP);
2473 	mtrrdef = rdmsr(REG_MTRRDEF);
2474 	if (mtrrcap & MTRRCAP_FIX) {
2475 		mtrr64k = rdmsr(REG_MTRR64K);
2476 		mtrr16k1 = rdmsr(REG_MTRR16K1);
2477 		mtrr16k2 = rdmsr(REG_MTRR16K2);
2478 		mtrr4k1 = rdmsr(REG_MTRR4K1);
2479 		mtrr4k2 = rdmsr(REG_MTRR4K2);
2480 		mtrr4k3 = rdmsr(REG_MTRR4K3);
2481 		mtrr4k4 = rdmsr(REG_MTRR4K4);
2482 		mtrr4k5 = rdmsr(REG_MTRR4K5);
2483 		mtrr4k6 = rdmsr(REG_MTRR4K6);
2484 		mtrr4k7 = rdmsr(REG_MTRR4K7);
2485 		mtrr4k8 = rdmsr(REG_MTRR4K8);
2486 	}
2487 	if ((vcnt = (mtrrcap & MTRRCAP_VCNTMASK)) > MAX_MTRRVAR)
2488 		vcnt = MAX_MTRRVAR;
2489 
2490 	for (i = 0, ecx = REG_MTRRPHYSBASE0, mtrrphys = mtrrphys_arr;
2491 		i <  vcnt - 1; i++, ecx += 2, mtrrphys++) {
2492 		mtrrphys->mtrrphys_base = rdmsr(ecx);
2493 		mtrrphys->mtrrphys_mask = rdmsr(ecx + 1);
2494 		if ((x86_feature & X86_PAT) && enable_relaxed_mtrr) {
2495 			mtrrphys->mtrrphys_mask &= ~MTRRPHYSMASK_V;
2496 		}
2497 	}
2498 	if (x86_feature & X86_PAT) {
2499 		if (enable_relaxed_mtrr)
2500 			mtrrdef = MTRR_TYPE_WB|MTRRDEF_FE|MTRRDEF_E;
2501 		pat_attr_reg = PAT_DEFAULT_ATTRIBUTE;
2502 	}
2503 
2504 	mtrr_sync();
2505 }
2506 
2507 /*
2508  * Sync current cpu mtrr with the incore copy of mtrr.
2509  * This function has to be invoked with interrupts disabled
2510  * Currently we do not capture other cpu's. This is invoked on cpu0
2511  * just after reading /etc/system.
2512  * On other cpu's its invoked from mp_startup().
2513  */
2514 void
2515 mtrr_sync()
2516 {
2517 	uint_t	crvalue, cr0_orig;
2518 	int	vcnt, i, ecx;
2519 	struct	mtrrvar	*mtrrphys;
2520 
2521 	cr0_orig = crvalue = getcr0();
2522 	crvalue |= CR0_CD;
2523 	crvalue &= ~CR0_NW;
2524 	setcr0(crvalue);
2525 	invalidate_cache();
2526 	setcr3(getcr3());
2527 
2528 	if (x86_feature & X86_PAT)
2529 		wrmsr(REG_MTRRPAT, pat_attr_reg);
2530 
2531 	wrmsr(REG_MTRRDEF, rdmsr(REG_MTRRDEF) &
2532 	    ~((uint64_t)(uintptr_t)MTRRDEF_E));
2533 
2534 	if (mtrrcap & MTRRCAP_FIX) {
2535 		wrmsr(REG_MTRR64K, mtrr64k);
2536 		wrmsr(REG_MTRR16K1, mtrr16k1);
2537 		wrmsr(REG_MTRR16K2, mtrr16k2);
2538 		wrmsr(REG_MTRR4K1, mtrr4k1);
2539 		wrmsr(REG_MTRR4K2, mtrr4k2);
2540 		wrmsr(REG_MTRR4K3, mtrr4k3);
2541 		wrmsr(REG_MTRR4K4, mtrr4k4);
2542 		wrmsr(REG_MTRR4K5, mtrr4k5);
2543 		wrmsr(REG_MTRR4K6, mtrr4k6);
2544 		wrmsr(REG_MTRR4K7, mtrr4k7);
2545 		wrmsr(REG_MTRR4K8, mtrr4k8);
2546 	}
2547 	if ((vcnt = (mtrrcap & MTRRCAP_VCNTMASK)) > MAX_MTRRVAR)
2548 		vcnt = MAX_MTRRVAR;
2549 	for (i = 0, ecx = REG_MTRRPHYSBASE0, mtrrphys = mtrrphys_arr;
2550 	    i <  vcnt - 1; i++, ecx += 2, mtrrphys++) {
2551 		wrmsr(ecx, mtrrphys->mtrrphys_base);
2552 		wrmsr(ecx + 1, mtrrphys->mtrrphys_mask);
2553 	}
2554 	wrmsr(REG_MTRRDEF, mtrrdef);
2555 	setcr3(getcr3());
2556 	invalidate_cache();
2557 	setcr0(cr0_orig);
2558 }
2559 
2560 /*
2561  * resync mtrr so that BIOS is happy. Called from mdboot
2562  */
2563 void
2564 mtrr_resync()
2565 {
2566 	if ((x86_feature & X86_PAT) && enable_relaxed_mtrr) {
2567 		/*
2568 		 * We could have changed the default mtrr definition.
2569 		 * Put it back to uncached which is what it is at power on
2570 		 */
2571 		mtrrdef = MTRR_TYPE_UC|MTRRDEF_FE|MTRRDEF_E;
2572 		mtrr_sync();
2573 	}
2574 }
2575 
2576 void
2577 get_system_configuration()
2578 {
2579 	char	prop[32];
2580 	u_longlong_t nodes_ll, cpus_pernode_ll, lvalue;
2581 
2582 	if (((BOP_GETPROPLEN(bootops, "nodes") > sizeof (prop)) ||
2583 		(BOP_GETPROP(bootops, "nodes", prop) < 0) 	||
2584 		(kobj_getvalue(prop, &nodes_ll) == -1) ||
2585 		(nodes_ll > MAXNODES))			   ||
2586 	    ((BOP_GETPROPLEN(bootops, "cpus_pernode") > sizeof (prop)) ||
2587 		(BOP_GETPROP(bootops, "cpus_pernode", prop) < 0) ||
2588 		(kobj_getvalue(prop, &cpus_pernode_ll) == -1))) {
2589 
2590 		system_hardware.hd_nodes = 1;
2591 		system_hardware.hd_cpus_per_node = 0;
2592 	} else {
2593 		system_hardware.hd_nodes = (int)nodes_ll;
2594 		system_hardware.hd_cpus_per_node = (int)cpus_pernode_ll;
2595 	}
2596 	if ((BOP_GETPROPLEN(bootops, "kernelbase") > sizeof (prop)) ||
2597 		(BOP_GETPROP(bootops, "kernelbase", prop) < 0) 	||
2598 		(kobj_getvalue(prop, &lvalue) == -1))
2599 			eprom_kernelbase = NULL;
2600 	else
2601 			eprom_kernelbase = (uintptr_t)lvalue;
2602 
2603 	if ((BOP_GETPROPLEN(bootops, "segmapsize") > sizeof (prop)) ||
2604 	    (BOP_GETPROP(bootops, "segmapsize", prop) < 0) ||
2605 	    (kobj_getvalue(prop, &lvalue) == -1)) {
2606 		segmapsize = SEGMAPDEFAULT;
2607 	} else {
2608 		segmapsize = (uintptr_t)lvalue;
2609 	}
2610 
2611 	if ((BOP_GETPROPLEN(bootops, "segmapfreelists") > sizeof (prop)) ||
2612 	    (BOP_GETPROP(bootops, "segmapfreelists", prop) < 0) ||
2613 	    (kobj_getvalue(prop, &lvalue) == -1)) {
2614 		segmapfreelists = 0;	/* use segmap driver default */
2615 	} else {
2616 		segmapfreelists = (int)lvalue;
2617 	}
2618 }
2619 
2620 /*
2621  * Add to a memory list.
2622  * start = start of new memory segment
2623  * len = length of new memory segment in bytes
2624  * new = pointer to a new struct memlist
2625  * memlistp = memory list to which to add segment.
2626  */
2627 static void
2628 memlist_add(
2629 	uint64_t start,
2630 	uint64_t len,
2631 	struct memlist *new,
2632 	struct memlist **memlistp)
2633 {
2634 	struct memlist *cur;
2635 	uint64_t end = start + len;
2636 
2637 	new->address = start;
2638 	new->size = len;
2639 
2640 	cur = *memlistp;
2641 
2642 	while (cur) {
2643 		if (cur->address >= end) {
2644 			new->next = cur;
2645 			*memlistp = new;
2646 			new->prev = cur->prev;
2647 			cur->prev = new;
2648 			return;
2649 		}
2650 		ASSERT(cur->address + cur->size <= start);
2651 		if (cur->next == NULL) {
2652 			cur->next = new;
2653 			new->prev = cur;
2654 			new->next = NULL;
2655 			return;
2656 		}
2657 		memlistp = &cur->next;
2658 		cur = cur->next;
2659 	}
2660 }
2661 
2662 void
2663 kobj_vmem_init(vmem_t **text_arena, vmem_t **data_arena)
2664 {
2665 	size_t tsize = e_modtext - modtext;
2666 	size_t dsize = e_moddata - moddata;
2667 
2668 	*text_arena = vmem_create("module_text", tsize ? modtext : NULL, tsize,
2669 	    1, segkmem_alloc, segkmem_free, heaptext_arena, 0, VM_SLEEP);
2670 	*data_arena = vmem_create("module_data", dsize ? moddata : NULL, dsize,
2671 	    1, segkmem_alloc, segkmem_free, heap32_arena, 0, VM_SLEEP);
2672 }
2673 
2674 caddr_t
2675 kobj_text_alloc(vmem_t *arena, size_t size)
2676 {
2677 	return (vmem_alloc(arena, size, VM_SLEEP | VM_BESTFIT));
2678 }
2679 
2680 /*ARGSUSED*/
2681 caddr_t
2682 kobj_texthole_alloc(caddr_t addr, size_t size)
2683 {
2684 	panic("unexpected call to kobj_texthole_alloc()");
2685 	/*NOTREACHED*/
2686 	return (0);
2687 }
2688 
2689 /*ARGSUSED*/
2690 void
2691 kobj_texthole_free(caddr_t addr, size_t size)
2692 {
2693 	panic("unexpected call to kobj_texthole_free()");
2694 }
2695 
2696 /*
2697  * This is called just after configure() in startup().
2698  *
2699  * The ISALIST concept is a bit hopeless on Intel, because
2700  * there's no guarantee of an ever-more-capable processor
2701  * given that various parts of the instruction set may appear
2702  * and disappear between different implementations.
2703  *
2704  * While it would be possible to correct it and even enhance
2705  * it somewhat, the explicit hardware capability bitmask allows
2706  * more flexibility.
2707  *
2708  * So, we just leave this alone.
2709  */
2710 void
2711 setx86isalist(void)
2712 {
2713 	char *tp;
2714 	size_t len;
2715 	extern char *isa_list;
2716 
2717 #define	TBUFSIZE	1024
2718 
2719 	tp = kmem_alloc(TBUFSIZE, KM_SLEEP);
2720 	*tp = '\0';
2721 
2722 #if defined(__amd64)
2723 	(void) strcpy(tp, "amd64 ");
2724 #endif
2725 
2726 	switch (x86_vendor) {
2727 	case X86_VENDOR_Intel:
2728 	case X86_VENDOR_AMD:
2729 	case X86_VENDOR_TM:
2730 		if (x86_feature & X86_CMOV) {
2731 			/*
2732 			 * Pentium Pro or later
2733 			 */
2734 			(void) strcat(tp, "pentium_pro");
2735 			(void) strcat(tp, x86_feature & X86_MMX ?
2736 			    "+mmx pentium_pro " : " ");
2737 		}
2738 		/*FALLTHROUGH*/
2739 	case X86_VENDOR_Cyrix:
2740 		/*
2741 		 * The Cyrix 6x86 does not have any Pentium features
2742 		 * accessible while not at privilege level 0.
2743 		 */
2744 		if (x86_feature & X86_CPUID) {
2745 			(void) strcat(tp, "pentium");
2746 			(void) strcat(tp, x86_feature & X86_MMX ?
2747 			    "+mmx pentium " : " ");
2748 		}
2749 		break;
2750 	default:
2751 		break;
2752 	}
2753 	(void) strcat(tp, "i486 i386 i86");
2754 	len = strlen(tp) + 1;   /* account for NULL at end of string */
2755 	isa_list = strcpy(kmem_alloc(len, KM_SLEEP), tp);
2756 	kmem_free(tp, TBUFSIZE);
2757 
2758 #undef TBUFSIZE
2759 }
2760 
2761 
2762 #ifdef __amd64
2763 
2764 void *
2765 device_arena_alloc(size_t size, int vm_flag)
2766 {
2767 	return (vmem_alloc(device_arena, size, vm_flag));
2768 }
2769 
2770 void
2771 device_arena_free(void *vaddr, size_t size)
2772 {
2773 	vmem_free(device_arena, vaddr, size);
2774 }
2775 
2776 #else
2777 
2778 void *
2779 device_arena_alloc(size_t size, int vm_flag)
2780 {
2781 	caddr_t	vaddr;
2782 	uintptr_t v;
2783 	size_t	start;
2784 	size_t	end;
2785 
2786 	vaddr = vmem_alloc(heap_arena, size, vm_flag);
2787 	if (vaddr == NULL)
2788 		return (NULL);
2789 
2790 	v = (uintptr_t)vaddr;
2791 	ASSERT(v >= kernelbase);
2792 	ASSERT(v + size <= ptable_va);
2793 
2794 	start = btop(v - kernelbase);
2795 	end = btop(v + size - 1 - kernelbase);
2796 	ASSERT(start < toxic_bit_map_len);
2797 	ASSERT(end < toxic_bit_map_len);
2798 
2799 	while (start <= end) {
2800 		BT_ATOMIC_SET(toxic_bit_map, start);
2801 		++start;
2802 	}
2803 	return (vaddr);
2804 }
2805 
2806 void
2807 device_arena_free(void *vaddr, size_t size)
2808 {
2809 	uintptr_t v = (uintptr_t)vaddr;
2810 	size_t	start;
2811 	size_t	end;
2812 
2813 	ASSERT(v >= kernelbase);
2814 	ASSERT(v + size <= ptable_va);
2815 
2816 	start = btop(v - kernelbase);
2817 	end = btop(v + size - 1 - kernelbase);
2818 	ASSERT(start < toxic_bit_map_len);
2819 	ASSERT(end < toxic_bit_map_len);
2820 
2821 	while (start <= end) {
2822 		ASSERT(BT_TEST(toxic_bit_map, start) != 0);
2823 		BT_ATOMIC_CLEAR(toxic_bit_map, start);
2824 		++start;
2825 	}
2826 	vmem_free(heap_arena, vaddr, size);
2827 }
2828 
2829 /*
2830  * returns 1st address in range that is in device arena, or NULL
2831  * if len is not NULL it returns the length of the toxic range
2832  */
2833 void *
2834 device_arena_contains(void *vaddr, size_t size, size_t *len)
2835 {
2836 	uintptr_t v = (uintptr_t)vaddr;
2837 	uintptr_t eaddr = v + size;
2838 	size_t start;
2839 	size_t end;
2840 
2841 	/*
2842 	 * if called very early by kmdb, just return NULL
2843 	 */
2844 	if (toxic_bit_map == NULL)
2845 		return (NULL);
2846 
2847 	/*
2848 	 * First check if we're completely outside the bitmap range.
2849 	 */
2850 	if (v >= ptable_va || eaddr < kernelbase)
2851 		return (NULL);
2852 
2853 	/*
2854 	 * Trim ends of search to look at only what the bitmap covers.
2855 	 */
2856 	if (v < kernelbase)
2857 		v = kernelbase;
2858 	start = btop(v - kernelbase);
2859 	end = btop(eaddr - kernelbase);
2860 	if (end >= toxic_bit_map_len)
2861 		end = toxic_bit_map_len;
2862 
2863 	if (bt_range(toxic_bit_map, &start, &end, end) == 0)
2864 		return (NULL);
2865 
2866 	v = kernelbase + ptob(start);
2867 	if (len != NULL)
2868 		*len = ptob(end - start);
2869 	return ((void *)v);
2870 }
2871 
2872 #endif
2873