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