xref: /freebsd-13-stable/sys/i386/i386/machdep.c (revision 19eed0321ccf17cdbc9cd1c5b75466ef27a2db34)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 2018 The FreeBSD Foundation
5  * Copyright (c) 1992 Terrence R. Lambert.
6  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * William Jolitz.
11  *
12  * Portions of this software were developed by A. Joseph Koshy under
13  * sponsorship from the FreeBSD Foundation and Google, Inc.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. All advertising materials mentioning features or use of this software
24  *    must display the following acknowledgement:
25  *	This product includes software developed by the University of
26  *	California, Berkeley and its contributors.
27  * 4. Neither the name of the University nor the names of its contributors
28  *    may be used to endorse or promote products derived from this software
29  *    without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  *
43  *	from: @(#)machdep.c	7.4 (Berkeley) 6/3/91
44  */
45 
46 #include <sys/cdefs.h>
47 #include "opt_apic.h"
48 #include "opt_atpic.h"
49 #include "opt_cpu.h"
50 #include "opt_ddb.h"
51 #include "opt_inet.h"
52 #include "opt_isa.h"
53 #include "opt_kstack_pages.h"
54 #include "opt_maxmem.h"
55 #include "opt_mp_watchdog.h"
56 #include "opt_perfmon.h"
57 #include "opt_platform.h"
58 
59 #include <sys/param.h>
60 #include <sys/proc.h>
61 #include <sys/systm.h>
62 #include <sys/bio.h>
63 #include <sys/buf.h>
64 #include <sys/bus.h>
65 #include <sys/callout.h>
66 #include <sys/cons.h>
67 #include <sys/cpu.h>
68 #include <sys/eventhandler.h>
69 #include <sys/exec.h>
70 #include <sys/imgact.h>
71 #include <sys/kdb.h>
72 #include <sys/kernel.h>
73 #include <sys/ktr.h>
74 #include <sys/linker.h>
75 #include <sys/lock.h>
76 #include <sys/malloc.h>
77 #include <sys/memrange.h>
78 #include <sys/msgbuf.h>
79 #include <sys/mutex.h>
80 #include <sys/pcpu.h>
81 #include <sys/ptrace.h>
82 #include <sys/reboot.h>
83 #include <sys/reg.h>
84 #include <sys/rwlock.h>
85 #include <sys/sched.h>
86 #include <sys/signalvar.h>
87 #include <sys/smp.h>
88 #include <sys/syscallsubr.h>
89 #include <sys/sysctl.h>
90 #include <sys/sysent.h>
91 #include <sys/sysproto.h>
92 #include <sys/ucontext.h>
93 #include <sys/vmmeter.h>
94 
95 #include <vm/vm.h>
96 #include <vm/vm_param.h>
97 #include <vm/vm_extern.h>
98 #include <vm/vm_kern.h>
99 #include <vm/vm_page.h>
100 #include <vm/vm_map.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_pager.h>
103 #include <vm/vm_phys.h>
104 #include <vm/vm_dumpset.h>
105 
106 #ifdef DDB
107 #ifndef KDB
108 #error KDB must be enabled in order for DDB to work!
109 #endif
110 #include <ddb/ddb.h>
111 #include <ddb/db_sym.h>
112 #endif
113 
114 #include <isa/rtc.h>
115 
116 #include <net/netisr.h>
117 
118 #include <machine/bootinfo.h>
119 #include <machine/clock.h>
120 #include <machine/cpu.h>
121 #include <machine/cputypes.h>
122 #include <machine/intr_machdep.h>
123 #include <x86/mca.h>
124 #include <machine/md_var.h>
125 #include <machine/metadata.h>
126 #include <machine/mp_watchdog.h>
127 #include <machine/pc/bios.h>
128 #include <machine/pcb.h>
129 #include <machine/pcb_ext.h>
130 #include <machine/proc.h>
131 #include <machine/sigframe.h>
132 #include <machine/specialreg.h>
133 #include <machine/sysarch.h>
134 #include <machine/trap.h>
135 #include <x86/ucode.h>
136 #include <machine/vm86.h>
137 #include <x86/init.h>
138 #ifdef PERFMON
139 #include <machine/perfmon.h>
140 #endif
141 #ifdef SMP
142 #include <machine/smp.h>
143 #endif
144 #ifdef FDT
145 #include <x86/fdt.h>
146 #endif
147 
148 #ifdef DEV_APIC
149 #include <x86/apicvar.h>
150 #endif
151 
152 #ifdef DEV_ISA
153 #include <x86/isa/icu.h>
154 #endif
155 
156 /* Sanity check for __curthread() */
157 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
158 
159 register_t init386(int first);
160 void dblfault_handler(void);
161 void identify_cpu(void);
162 
163 static void cpu_startup(void *);
164 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
165 
166 /* Intel ICH registers */
167 #define ICH_PMBASE	0x400
168 #define ICH_SMI_EN	ICH_PMBASE + 0x30
169 
170 int	_udatasel, _ucodesel;
171 u_int	basemem;
172 static int above4g_allow = 1;
173 static int above24g_allow = 0;
174 
175 int cold = 1;
176 
177 long Maxmem = 0;
178 long realmem = 0;
179 
180 #ifdef PAE
181 FEATURE(pae, "Physical Address Extensions");
182 #endif
183 
184 struct kva_md_info kmi;
185 
186 static struct trapframe proc0_tf;
187 struct pcpu __pcpu[MAXCPU];
188 
189 static void i386_clock_source_init(void);
190 
191 struct mtx icu_lock;
192 
193 struct mem_range_softc mem_range_softc;
194 
195 extern char start_exceptions[], end_exceptions[];
196 
197 extern struct sysentvec elf32_freebsd_sysvec;
198 
199 /* Default init_ops implementation. */
200 struct init_ops init_ops = {
201 	.early_clock_source_init =	i386_clock_source_init,
202 	.early_delay =			i8254_delay,
203 #ifdef DEV_APIC
204 	.msi_init =			msi_init,
205 #endif
206 };
207 
208 static void
i386_clock_source_init(void)209 i386_clock_source_init(void)
210 {
211 	i8254_init();
212 	tsc_init();
213 }
214 
215 static void
cpu_startup(void * dummy)216 cpu_startup(void *dummy)
217 {
218 	uintmax_t memsize;
219 	char *sysenv;
220 
221 	/*
222 	 * On MacBooks, we need to disallow the legacy USB circuit to
223 	 * generate an SMI# because this can cause several problems,
224 	 * namely: incorrect CPU frequency detection and failure to
225 	 * start the APs.
226 	 * We do this by disabling a bit in the SMI_EN (SMI Control and
227 	 * Enable register) of the Intel ICH LPC Interface Bridge.
228 	 */
229 	sysenv = kern_getenv("smbios.system.product");
230 	if (sysenv != NULL) {
231 		if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
232 		    strncmp(sysenv, "MacBook3,1", 10) == 0 ||
233 		    strncmp(sysenv, "MacBook4,1", 10) == 0 ||
234 		    strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
235 		    strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
236 		    strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
237 		    strncmp(sysenv, "MacBookPro4,1", 13) == 0 ||
238 		    strncmp(sysenv, "Macmini1,1", 10) == 0) {
239 			if (bootverbose)
240 				printf("Disabling LEGACY_USB_EN bit on "
241 				    "Intel ICH.\n");
242 			outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
243 		}
244 		freeenv(sysenv);
245 	}
246 
247 	/*
248 	 * Good {morning,afternoon,evening,night}.
249 	 */
250 	startrtclock();
251 	printcpuinfo();
252 	panicifcpuunsupported();
253 #ifdef PERFMON
254 	perfmon_init();
255 #endif
256 
257 	/*
258 	 * Display physical memory if SMBIOS reports reasonable amount.
259 	 */
260 	memsize = 0;
261 	sysenv = kern_getenv("smbios.memory.enabled");
262 	if (sysenv != NULL) {
263 		memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
264 		freeenv(sysenv);
265 	}
266 	if (memsize < ptoa((uintmax_t)vm_free_count()))
267 		memsize = ptoa((uintmax_t)Maxmem);
268 	printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
269 	realmem = atop(memsize);
270 
271 	/*
272 	 * Display any holes after the first chunk of extended memory.
273 	 */
274 	if (bootverbose) {
275 		int indx;
276 
277 		printf("Physical memory chunk(s):\n");
278 		for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
279 			vm_paddr_t size;
280 
281 			size = phys_avail[indx + 1] - phys_avail[indx];
282 			printf(
283 			    "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
284 			    (uintmax_t)phys_avail[indx],
285 			    (uintmax_t)phys_avail[indx + 1] - 1,
286 			    (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
287 		}
288 	}
289 
290 	vm_ksubmap_init(&kmi);
291 
292 	printf("avail memory = %ju (%ju MB)\n",
293 	    ptoa((uintmax_t)vm_free_count()),
294 	    ptoa((uintmax_t)vm_free_count()) / 1048576);
295 
296 	/*
297 	 * Set up buffers, so they can be used to read disk labels.
298 	 */
299 	bufinit();
300 	vm_pager_bufferinit();
301 	cpu_setregs();
302 }
303 
304 void
cpu_setregs(void)305 cpu_setregs(void)
306 {
307 	unsigned int cr0;
308 
309 	cr0 = rcr0();
310 
311 	/*
312 	 * CR0_MP, CR0_NE and CR0_TS are set for NPX (FPU) support:
313 	 *
314 	 * Prepare to trap all ESC (i.e., NPX) instructions and all WAIT
315 	 * instructions.  We must set the CR0_MP bit and use the CR0_TS
316 	 * bit to control the trap, because setting the CR0_EM bit does
317 	 * not cause WAIT instructions to trap.  It's important to trap
318 	 * WAIT instructions - otherwise the "wait" variants of no-wait
319 	 * control instructions would degenerate to the "no-wait" variants
320 	 * after FP context switches but work correctly otherwise.  It's
321 	 * particularly important to trap WAITs when there is no NPX -
322 	 * otherwise the "wait" variants would always degenerate.
323 	 *
324 	 * Try setting CR0_NE to get correct error reporting on 486DX's.
325 	 * Setting it should fail or do nothing on lesser processors.
326 	 */
327 	cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
328 	load_cr0(cr0);
329 	load_gs(_udatasel);
330 }
331 
332 u_long bootdev;		/* not a struct cdev *- encoding is different */
333 SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
334 	CTLFLAG_RD, &bootdev, 0, "Maybe the Boot device (not in struct cdev *format)");
335 
336 static char bootmethod[16] = "BIOS";
337 SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
338     "System firmware boot method");
339 
340 /*
341  * Initialize 386 and configure to run kernel
342  */
343 
344 /*
345  * Initialize segments & interrupt table
346  */
347 
348 int _default_ldt;
349 
350 struct mtx dt_lock;			/* lock for GDT and LDT */
351 
352 union descriptor gdt0[NGDT];	/* initial global descriptor table */
353 union descriptor *gdt = gdt0;	/* global descriptor table */
354 
355 union descriptor *ldt;		/* local descriptor table */
356 
357 static struct gate_descriptor idt0[NIDT];
358 struct gate_descriptor *idt = &idt0[0];	/* interrupt descriptor table */
359 
360 static struct i386tss *dblfault_tss;
361 static char *dblfault_stack;
362 
363 static struct i386tss common_tss0;
364 
365 vm_offset_t proc0kstack;
366 
367 /*
368  * software prototypes -- in more palatable form.
369  *
370  * GCODE_SEL through GUDATA_SEL must be in this order for syscall/sysret
371  * GUFS_SEL and GUGS_SEL must be in this order (swtch.s knows it)
372  */
373 struct soft_segment_descriptor gdt_segs[] = {
374 /* GNULL_SEL	0 Null Descriptor */
375 {	.ssd_base = 0x0,
376 	.ssd_limit = 0x0,
377 	.ssd_type = 0,
378 	.ssd_dpl = SEL_KPL,
379 	.ssd_p = 0,
380 	.ssd_xx = 0, .ssd_xx1 = 0,
381 	.ssd_def32 = 0,
382 	.ssd_gran = 0		},
383 /* GPRIV_SEL	1 SMP Per-Processor Private Data Descriptor */
384 {	.ssd_base = 0x0,
385 	.ssd_limit = 0xfffff,
386 	.ssd_type = SDT_MEMRWA,
387 	.ssd_dpl = SEL_KPL,
388 	.ssd_p = 1,
389 	.ssd_xx = 0, .ssd_xx1 = 0,
390 	.ssd_def32 = 1,
391 	.ssd_gran = 1		},
392 /* GUFS_SEL	2 %fs Descriptor for user */
393 {	.ssd_base = 0x0,
394 	.ssd_limit = 0xfffff,
395 	.ssd_type = SDT_MEMRWA,
396 	.ssd_dpl = SEL_UPL,
397 	.ssd_p = 1,
398 	.ssd_xx = 0, .ssd_xx1 = 0,
399 	.ssd_def32 = 1,
400 	.ssd_gran = 1		},
401 /* GUGS_SEL	3 %gs Descriptor for user */
402 {	.ssd_base = 0x0,
403 	.ssd_limit = 0xfffff,
404 	.ssd_type = SDT_MEMRWA,
405 	.ssd_dpl = SEL_UPL,
406 	.ssd_p = 1,
407 	.ssd_xx = 0, .ssd_xx1 = 0,
408 	.ssd_def32 = 1,
409 	.ssd_gran = 1		},
410 /* GCODE_SEL	4 Code Descriptor for kernel */
411 {	.ssd_base = 0x0,
412 	.ssd_limit = 0xfffff,
413 	.ssd_type = SDT_MEMERA,
414 	.ssd_dpl = SEL_KPL,
415 	.ssd_p = 1,
416 	.ssd_xx = 0, .ssd_xx1 = 0,
417 	.ssd_def32 = 1,
418 	.ssd_gran = 1		},
419 /* GDATA_SEL	5 Data Descriptor for kernel */
420 {	.ssd_base = 0x0,
421 	.ssd_limit = 0xfffff,
422 	.ssd_type = SDT_MEMRWA,
423 	.ssd_dpl = SEL_KPL,
424 	.ssd_p = 1,
425 	.ssd_xx = 0, .ssd_xx1 = 0,
426 	.ssd_def32 = 1,
427 	.ssd_gran = 1		},
428 /* GUCODE_SEL	6 Code Descriptor for user */
429 {	.ssd_base = 0x0,
430 	.ssd_limit = 0xfffff,
431 	.ssd_type = SDT_MEMERA,
432 	.ssd_dpl = SEL_UPL,
433 	.ssd_p = 1,
434 	.ssd_xx = 0, .ssd_xx1 = 0,
435 	.ssd_def32 = 1,
436 	.ssd_gran = 1		},
437 /* GUDATA_SEL	7 Data Descriptor for user */
438 {	.ssd_base = 0x0,
439 	.ssd_limit = 0xfffff,
440 	.ssd_type = SDT_MEMRWA,
441 	.ssd_dpl = SEL_UPL,
442 	.ssd_p = 1,
443 	.ssd_xx = 0, .ssd_xx1 = 0,
444 	.ssd_def32 = 1,
445 	.ssd_gran = 1		},
446 /* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
447 {	.ssd_base = 0x400,
448 	.ssd_limit = 0xfffff,
449 	.ssd_type = SDT_MEMRWA,
450 	.ssd_dpl = SEL_KPL,
451 	.ssd_p = 1,
452 	.ssd_xx = 0, .ssd_xx1 = 0,
453 	.ssd_def32 = 1,
454 	.ssd_gran = 1		},
455 /* GPROC0_SEL	9 Proc 0 Tss Descriptor */
456 {
457 	.ssd_base = 0x0,
458 	.ssd_limit = sizeof(struct i386tss)-1,
459 	.ssd_type = SDT_SYS386TSS,
460 	.ssd_dpl = 0,
461 	.ssd_p = 1,
462 	.ssd_xx = 0, .ssd_xx1 = 0,
463 	.ssd_def32 = 0,
464 	.ssd_gran = 0		},
465 /* GLDT_SEL	10 LDT Descriptor */
466 {	.ssd_base = 0,
467 	.ssd_limit = sizeof(union descriptor) * NLDT - 1,
468 	.ssd_type = SDT_SYSLDT,
469 	.ssd_dpl = SEL_UPL,
470 	.ssd_p = 1,
471 	.ssd_xx = 0, .ssd_xx1 = 0,
472 	.ssd_def32 = 0,
473 	.ssd_gran = 0		},
474 /* GUSERLDT_SEL	11 User LDT Descriptor per process */
475 {	.ssd_base = 0,
476 	.ssd_limit = (512 * sizeof(union descriptor)-1),
477 	.ssd_type = SDT_SYSLDT,
478 	.ssd_dpl = 0,
479 	.ssd_p = 1,
480 	.ssd_xx = 0, .ssd_xx1 = 0,
481 	.ssd_def32 = 0,
482 	.ssd_gran = 0		},
483 /* GPANIC_SEL	12 Panic Tss Descriptor */
484 {	.ssd_base = 0,
485 	.ssd_limit = sizeof(struct i386tss)-1,
486 	.ssd_type = SDT_SYS386TSS,
487 	.ssd_dpl = 0,
488 	.ssd_p = 1,
489 	.ssd_xx = 0, .ssd_xx1 = 0,
490 	.ssd_def32 = 0,
491 	.ssd_gran = 0		},
492 /* GBIOSCODE32_SEL 13 BIOS 32-bit interface (32bit Code) */
493 {	.ssd_base = 0,
494 	.ssd_limit = 0xfffff,
495 	.ssd_type = SDT_MEMERA,
496 	.ssd_dpl = 0,
497 	.ssd_p = 1,
498 	.ssd_xx = 0, .ssd_xx1 = 0,
499 	.ssd_def32 = 0,
500 	.ssd_gran = 1		},
501 /* GBIOSCODE16_SEL 14 BIOS 32-bit interface (16bit Code) */
502 {	.ssd_base = 0,
503 	.ssd_limit = 0xfffff,
504 	.ssd_type = SDT_MEMERA,
505 	.ssd_dpl = 0,
506 	.ssd_p = 1,
507 	.ssd_xx = 0, .ssd_xx1 = 0,
508 	.ssd_def32 = 0,
509 	.ssd_gran = 1		},
510 /* GBIOSDATA_SEL 15 BIOS 32-bit interface (Data) */
511 {	.ssd_base = 0,
512 	.ssd_limit = 0xfffff,
513 	.ssd_type = SDT_MEMRWA,
514 	.ssd_dpl = 0,
515 	.ssd_p = 1,
516 	.ssd_xx = 0, .ssd_xx1 = 0,
517 	.ssd_def32 = 1,
518 	.ssd_gran = 1		},
519 /* GBIOSUTIL_SEL 16 BIOS 16-bit interface (Utility) */
520 {	.ssd_base = 0,
521 	.ssd_limit = 0xfffff,
522 	.ssd_type = SDT_MEMRWA,
523 	.ssd_dpl = 0,
524 	.ssd_p = 1,
525 	.ssd_xx = 0, .ssd_xx1 = 0,
526 	.ssd_def32 = 0,
527 	.ssd_gran = 1		},
528 /* GBIOSARGS_SEL 17 BIOS 16-bit interface (Arguments) */
529 {	.ssd_base = 0,
530 	.ssd_limit = 0xfffff,
531 	.ssd_type = SDT_MEMRWA,
532 	.ssd_dpl = 0,
533 	.ssd_p = 1,
534 	.ssd_xx = 0, .ssd_xx1 = 0,
535 	.ssd_def32 = 0,
536 	.ssd_gran = 1		},
537 /* GNDIS_SEL	18 NDIS Descriptor */
538 {	.ssd_base = 0x0,
539 	.ssd_limit = 0x0,
540 	.ssd_type = 0,
541 	.ssd_dpl = 0,
542 	.ssd_p = 0,
543 	.ssd_xx = 0, .ssd_xx1 = 0,
544 	.ssd_def32 = 0,
545 	.ssd_gran = 0		},
546 };
547 
548 static struct soft_segment_descriptor ldt_segs[] = {
549 	/* Null Descriptor - overwritten by call gate */
550 {	.ssd_base = 0x0,
551 	.ssd_limit = 0x0,
552 	.ssd_type = 0,
553 	.ssd_dpl = 0,
554 	.ssd_p = 0,
555 	.ssd_xx = 0, .ssd_xx1 = 0,
556 	.ssd_def32 = 0,
557 	.ssd_gran = 0		},
558 	/* Null Descriptor - overwritten by call gate */
559 {	.ssd_base = 0x0,
560 	.ssd_limit = 0x0,
561 	.ssd_type = 0,
562 	.ssd_dpl = 0,
563 	.ssd_p = 0,
564 	.ssd_xx = 0, .ssd_xx1 = 0,
565 	.ssd_def32 = 0,
566 	.ssd_gran = 0		},
567 	/* Null Descriptor - overwritten by call gate */
568 {	.ssd_base = 0x0,
569 	.ssd_limit = 0x0,
570 	.ssd_type = 0,
571 	.ssd_dpl = 0,
572 	.ssd_p = 0,
573 	.ssd_xx = 0, .ssd_xx1 = 0,
574 	.ssd_def32 = 0,
575 	.ssd_gran = 0		},
576 	/* Code Descriptor for user */
577 {	.ssd_base = 0x0,
578 	.ssd_limit = 0xfffff,
579 	.ssd_type = SDT_MEMERA,
580 	.ssd_dpl = SEL_UPL,
581 	.ssd_p = 1,
582 	.ssd_xx = 0, .ssd_xx1 = 0,
583 	.ssd_def32 = 1,
584 	.ssd_gran = 1		},
585 	/* Null Descriptor - overwritten by call gate */
586 {	.ssd_base = 0x0,
587 	.ssd_limit = 0x0,
588 	.ssd_type = 0,
589 	.ssd_dpl = 0,
590 	.ssd_p = 0,
591 	.ssd_xx = 0, .ssd_xx1 = 0,
592 	.ssd_def32 = 0,
593 	.ssd_gran = 0		},
594 	/* Data Descriptor for user */
595 {	.ssd_base = 0x0,
596 	.ssd_limit = 0xfffff,
597 	.ssd_type = SDT_MEMRWA,
598 	.ssd_dpl = SEL_UPL,
599 	.ssd_p = 1,
600 	.ssd_xx = 0, .ssd_xx1 = 0,
601 	.ssd_def32 = 1,
602 	.ssd_gran = 1		},
603 };
604 
605 size_t setidt_disp;
606 
607 void
setidt(int idx,inthand_t * func,int typ,int dpl,int selec)608 setidt(int idx, inthand_t *func, int typ, int dpl, int selec)
609 {
610 	uintptr_t off;
611 
612 	off = func != NULL ? (uintptr_t)func + setidt_disp : 0;
613 	setidt_nodisp(idx, off, typ, dpl, selec);
614 }
615 
616 void
setidt_nodisp(int idx,uintptr_t off,int typ,int dpl,int selec)617 setidt_nodisp(int idx, uintptr_t off, int typ, int dpl, int selec)
618 {
619 	struct gate_descriptor *ip;
620 
621 	ip = idt + idx;
622 	ip->gd_looffset = off;
623 	ip->gd_selector = selec;
624 	ip->gd_stkcpy = 0;
625 	ip->gd_xx = 0;
626 	ip->gd_type = typ;
627 	ip->gd_dpl = dpl;
628 	ip->gd_p = 1;
629 	ip->gd_hioffset = ((u_int)off) >> 16 ;
630 }
631 
632 extern inthand_t
633 	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
634 	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
635 	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
636 	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
637 	IDTVEC(xmm),
638 #ifdef KDTRACE_HOOKS
639 	IDTVEC(dtrace_ret),
640 #endif
641 #ifdef XENHVM
642 	IDTVEC(xen_intr_upcall),
643 #endif
644 	IDTVEC(int0x80_syscall);
645 
646 #ifdef DDB
647 /*
648  * Display the index and function name of any IDT entries that don't use
649  * the default 'rsvd' entry point.
650  */
DB_SHOW_COMMAND(idt,db_show_idt)651 DB_SHOW_COMMAND(idt, db_show_idt)
652 {
653 	struct gate_descriptor *ip;
654 	int idx;
655 	uintptr_t func, func_trm;
656 	bool trm;
657 
658 	ip = idt;
659 	for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
660 		if (ip->gd_type == SDT_SYSTASKGT) {
661 			db_printf("%3d\t<TASK>\n", idx);
662 		} else {
663 			func = (ip->gd_hioffset << 16 | ip->gd_looffset);
664 			if (func >= PMAP_TRM_MIN_ADDRESS) {
665 				func_trm = func;
666 				func -= setidt_disp;
667 				trm = true;
668 			} else
669 				trm = false;
670 			if (func != (uintptr_t)&IDTVEC(rsvd)) {
671 				db_printf("%3d\t", idx);
672 				db_printsym(func, DB_STGY_PROC);
673 				if (trm)
674 					db_printf(" (trampoline %#x)",
675 					    func_trm);
676 				db_printf("\n");
677 			}
678 		}
679 		ip++;
680 	}
681 }
682 
683 /* Show privileged registers. */
DB_SHOW_COMMAND(sysregs,db_show_sysregs)684 DB_SHOW_COMMAND(sysregs, db_show_sysregs)
685 {
686 	uint64_t idtr, gdtr;
687 
688 	idtr = ridt();
689 	db_printf("idtr\t0x%08x/%04x\n",
690 	    (u_int)(idtr >> 16), (u_int)idtr & 0xffff);
691 	gdtr = rgdt();
692 	db_printf("gdtr\t0x%08x/%04x\n",
693 	    (u_int)(gdtr >> 16), (u_int)gdtr & 0xffff);
694 	db_printf("ldtr\t0x%04x\n", rldt());
695 	db_printf("tr\t0x%04x\n", rtr());
696 	db_printf("cr0\t0x%08x\n", rcr0());
697 	db_printf("cr2\t0x%08x\n", rcr2());
698 	db_printf("cr3\t0x%08x\n", rcr3());
699 	db_printf("cr4\t0x%08x\n", rcr4());
700 	if (rcr4() & CR4_XSAVE)
701 		db_printf("xcr0\t0x%016llx\n", rxcr(0));
702 	if (amd_feature & (AMDID_NX | AMDID_LM))
703 		db_printf("EFER\t0x%016llx\n", rdmsr(MSR_EFER));
704 	if (cpu_feature2 & (CPUID2_VMX | CPUID2_SMX))
705 		db_printf("FEATURES_CTL\t0x%016llx\n",
706 		    rdmsr(MSR_IA32_FEATURE_CONTROL));
707 	if (((cpu_vendor_id == CPU_VENDOR_INTEL ||
708 	    cpu_vendor_id == CPU_VENDOR_AMD) && CPUID_TO_FAMILY(cpu_id) >= 6) ||
709 	    cpu_vendor_id == CPU_VENDOR_HYGON)
710 		db_printf("DEBUG_CTL\t0x%016llx\n", rdmsr(MSR_DEBUGCTLMSR));
711 	if (cpu_feature & CPUID_PAT)
712 		db_printf("PAT\t0x%016llx\n", rdmsr(MSR_PAT));
713 }
714 
DB_SHOW_COMMAND(dbregs,db_show_dbregs)715 DB_SHOW_COMMAND(dbregs, db_show_dbregs)
716 {
717 
718 	db_printf("dr0\t0x%08x\n", rdr0());
719 	db_printf("dr1\t0x%08x\n", rdr1());
720 	db_printf("dr2\t0x%08x\n", rdr2());
721 	db_printf("dr3\t0x%08x\n", rdr3());
722 	db_printf("dr6\t0x%08x\n", rdr6());
723 	db_printf("dr7\t0x%08x\n", rdr7());
724 }
725 
DB_SHOW_COMMAND(frame,db_show_frame)726 DB_SHOW_COMMAND(frame, db_show_frame)
727 {
728 	struct trapframe *frame;
729 
730 	frame = have_addr ? (struct trapframe *)addr : curthread->td_frame;
731 	printf("ss %#x esp %#x efl %#x cs %#x eip %#x\n",
732 	    frame->tf_ss, frame->tf_esp, frame->tf_eflags, frame->tf_cs,
733 	    frame->tf_eip);
734 	printf("err %#x trapno %d\n", frame->tf_err, frame->tf_trapno);
735 	printf("ds %#x es %#x fs %#x\n",
736 	    frame->tf_ds, frame->tf_es, frame->tf_fs);
737 	printf("eax %#x ecx %#x edx %#x ebx %#x\n",
738 	    frame->tf_eax, frame->tf_ecx, frame->tf_edx, frame->tf_ebx);
739 	printf("ebp %#x esi %#x edi %#x\n",
740 	    frame->tf_ebp, frame->tf_esi, frame->tf_edi);
741 
742 }
743 #endif
744 
745 void
sdtossd(struct segment_descriptor * sd,struct soft_segment_descriptor * ssd)746 sdtossd(struct segment_descriptor *sd, struct soft_segment_descriptor *ssd)
747 {
748 	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
749 	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
750 	ssd->ssd_type  = sd->sd_type;
751 	ssd->ssd_dpl   = sd->sd_dpl;
752 	ssd->ssd_p     = sd->sd_p;
753 	ssd->ssd_def32 = sd->sd_def32;
754 	ssd->ssd_gran  = sd->sd_gran;
755 }
756 
757 static int
add_physmap_entry(uint64_t base,uint64_t length,vm_paddr_t * physmap,int * physmap_idxp)758 add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
759     int *physmap_idxp)
760 {
761 	uint64_t lim, ign;
762 	int i, insert_idx, physmap_idx;
763 
764 	physmap_idx = *physmap_idxp;
765 
766 	if (length == 0)
767 		return (1);
768 
769 	lim = 0x100000000;					/*  4G */
770 	if (pae_mode && above4g_allow)
771 		lim = above24g_allow ? -1ULL : 0x600000000;	/* 24G */
772 	if (base >= lim) {
773 		printf("%uK of memory above %uGB ignored, pae %d "
774 		    "above4g_allow %d above24g_allow %d\n",
775 		    (u_int)(length / 1024), (u_int)(lim >> 30), pae_mode,
776 		    above4g_allow, above24g_allow);
777 		return (1);
778 	}
779 	if (base + length >= lim) {
780 		ign = base + length - lim;
781 		length -= ign;
782 		printf("%uK of memory above %uGB ignored, pae %d "
783 		    "above4g_allow %d above24g_allow %d\n",
784 		    (u_int)(ign / 1024), (u_int)(lim >> 30), pae_mode,
785 		    above4g_allow, above24g_allow);
786 	}
787 
788 	/*
789 	 * Find insertion point while checking for overlap.  Start off by
790 	 * assuming the new entry will be added to the end.
791 	 */
792 	insert_idx = physmap_idx + 2;
793 	for (i = 0; i <= physmap_idx; i += 2) {
794 		if (base < physmap[i + 1]) {
795 			if (base + length <= physmap[i]) {
796 				insert_idx = i;
797 				break;
798 			}
799 			if (boothowto & RB_VERBOSE)
800 				printf(
801 		    "Overlapping memory regions, ignoring second region\n");
802 			return (1);
803 		}
804 	}
805 
806 	/* See if we can prepend to the next entry. */
807 	if (insert_idx <= physmap_idx && base + length == physmap[insert_idx]) {
808 		physmap[insert_idx] = base;
809 		return (1);
810 	}
811 
812 	/* See if we can append to the previous entry. */
813 	if (insert_idx > 0 && base == physmap[insert_idx - 1]) {
814 		physmap[insert_idx - 1] += length;
815 		return (1);
816 	}
817 
818 	physmap_idx += 2;
819 	*physmap_idxp = physmap_idx;
820 	if (physmap_idx == PHYS_AVAIL_ENTRIES) {
821 		printf(
822 		"Too many segments in the physical address map, giving up\n");
823 		return (0);
824 	}
825 
826 	/*
827 	 * Move the last 'N' entries down to make room for the new
828 	 * entry if needed.
829 	 */
830 	for (i = physmap_idx; i > insert_idx; i -= 2) {
831 		physmap[i] = physmap[i - 2];
832 		physmap[i + 1] = physmap[i - 1];
833 	}
834 
835 	/* Insert the new entry. */
836 	physmap[insert_idx] = base;
837 	physmap[insert_idx + 1] = base + length;
838 	return (1);
839 }
840 
841 static int
add_smap_entry(struct bios_smap * smap,vm_paddr_t * physmap,int * physmap_idxp)842 add_smap_entry(struct bios_smap *smap, vm_paddr_t *physmap, int *physmap_idxp)
843 {
844 	if (boothowto & RB_VERBOSE)
845 		printf("SMAP type=%02x base=%016llx len=%016llx\n",
846 		    smap->type, smap->base, smap->length);
847 
848 	if (smap->type != SMAP_TYPE_MEMORY)
849 		return (1);
850 
851 	return (add_physmap_entry(smap->base, smap->length, physmap,
852 	    physmap_idxp));
853 }
854 
855 static void
add_smap_entries(struct bios_smap * smapbase,vm_paddr_t * physmap,int * physmap_idxp)856 add_smap_entries(struct bios_smap *smapbase, vm_paddr_t *physmap,
857     int *physmap_idxp)
858 {
859 	struct bios_smap *smap, *smapend;
860 	u_int32_t smapsize;
861 	/*
862 	 * Memory map from INT 15:E820.
863 	 *
864 	 * subr_module.c says:
865 	 * "Consumer may safely assume that size value precedes data."
866 	 * ie: an int32_t immediately precedes SMAP.
867 	 */
868 	smapsize = *((u_int32_t *)smapbase - 1);
869 	smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
870 
871 	for (smap = smapbase; smap < smapend; smap++)
872 		if (!add_smap_entry(smap, physmap, physmap_idxp))
873 			break;
874 }
875 
876 static void
basemem_setup(void)877 basemem_setup(void)
878 {
879 
880 	if (basemem > 640) {
881 		printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
882 			basemem);
883 		basemem = 640;
884 	}
885 
886 	pmap_basemem_setup(basemem);
887 }
888 
889 /*
890  * Populate the (physmap) array with base/bound pairs describing the
891  * available physical memory in the system, then test this memory and
892  * build the phys_avail array describing the actually-available memory.
893  *
894  * If we cannot accurately determine the physical memory map, then use
895  * value from the 0xE801 call, and failing that, the RTC.
896  *
897  * Total memory size may be set by the kernel environment variable
898  * hw.physmem or the compile-time define MAXMEM.
899  *
900  * XXX first should be vm_paddr_t.
901  */
902 static void
getmemsize(int first)903 getmemsize(int first)
904 {
905 	int has_smap, off, physmap_idx, pa_indx, da_indx;
906 	u_long memtest;
907 	vm_paddr_t physmap[PHYS_AVAIL_ENTRIES];
908 	quad_t dcons_addr, dcons_size, physmem_tunable;
909 	int hasbrokenint12, i, res;
910 	u_int extmem;
911 	struct vm86frame vmf;
912 	struct vm86context vmc;
913 	vm_paddr_t pa;
914 	struct bios_smap *smap, *smapbase;
915 	caddr_t kmdp;
916 
917 	has_smap = 0;
918 	bzero(&vmf, sizeof(vmf));
919 	bzero(physmap, sizeof(physmap));
920 	basemem = 0;
921 
922 	/*
923 	 * Tell the physical memory allocator about pages used to store
924 	 * the kernel and preloaded data.  See kmem_bootstrap_free().
925 	 */
926 	vm_phys_early_add_seg((vm_paddr_t)KERNLOAD, trunc_page(first));
927 
928 	TUNABLE_INT_FETCH("hw.above4g_allow", &above4g_allow);
929 	TUNABLE_INT_FETCH("hw.above24g_allow", &above24g_allow);
930 
931 	/*
932 	 * Check if the loader supplied an SMAP memory map.  If so,
933 	 * use that and do not make any VM86 calls.
934 	 */
935 	physmap_idx = 0;
936 	kmdp = preload_search_by_type("elf kernel");
937 	if (kmdp == NULL)
938 		kmdp = preload_search_by_type("elf32 kernel");
939 	smapbase = (struct bios_smap *)preload_search_info(kmdp,
940 	    MODINFO_METADATA | MODINFOMD_SMAP);
941 	if (smapbase != NULL) {
942 		add_smap_entries(smapbase, physmap, &physmap_idx);
943 		has_smap = 1;
944 		goto have_smap;
945 	}
946 
947 	/*
948 	 * Some newer BIOSes have a broken INT 12H implementation
949 	 * which causes a kernel panic immediately.  In this case, we
950 	 * need use the SMAP to determine the base memory size.
951 	 */
952 	hasbrokenint12 = 0;
953 	TUNABLE_INT_FETCH("hw.hasbrokenint12", &hasbrokenint12);
954 	if (hasbrokenint12 == 0) {
955 		/* Use INT12 to determine base memory size. */
956 		vm86_intcall(0x12, &vmf);
957 		basemem = vmf.vmf_ax;
958 		basemem_setup();
959 	}
960 
961 	/*
962 	 * Fetch the memory map with INT 15:E820.  Map page 1 R/W into
963 	 * the kernel page table so we can use it as a buffer.  The
964 	 * kernel will unmap this page later.
965 	 */
966 	vmc.npages = 0;
967 	smap = (void *)vm86_addpage(&vmc, 1, PMAP_MAP_LOW + ptoa(1));
968 	res = vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
969 	KASSERT(res != 0, ("vm86_getptr() failed: address not found"));
970 
971 	vmf.vmf_ebx = 0;
972 	do {
973 		vmf.vmf_eax = 0xE820;
974 		vmf.vmf_edx = SMAP_SIG;
975 		vmf.vmf_ecx = sizeof(struct bios_smap);
976 		i = vm86_datacall(0x15, &vmf, &vmc);
977 		if (i || vmf.vmf_eax != SMAP_SIG)
978 			break;
979 		has_smap = 1;
980 		if (!add_smap_entry(smap, physmap, &physmap_idx))
981 			break;
982 	} while (vmf.vmf_ebx != 0);
983 
984 have_smap:
985 	/*
986 	 * If we didn't fetch the "base memory" size from INT12,
987 	 * figure it out from the SMAP (or just guess).
988 	 */
989 	if (basemem == 0) {
990 		for (i = 0; i <= physmap_idx; i += 2) {
991 			if (physmap[i] == 0x00000000) {
992 				basemem = physmap[i + 1] / 1024;
993 				break;
994 			}
995 		}
996 
997 		/* XXX: If we couldn't find basemem from SMAP, just guess. */
998 		if (basemem == 0)
999 			basemem = 640;
1000 		basemem_setup();
1001 	}
1002 
1003 	if (physmap[1] != 0)
1004 		goto physmap_done;
1005 
1006 	/*
1007 	 * If we failed to find an SMAP, figure out the extended
1008 	 * memory size.  We will then build a simple memory map with
1009 	 * two segments, one for "base memory" and the second for
1010 	 * "extended memory".  Note that "extended memory" starts at a
1011 	 * physical address of 1MB and that both basemem and extmem
1012 	 * are in units of 1KB.
1013 	 *
1014 	 * First, try to fetch the extended memory size via INT 15:E801.
1015 	 */
1016 	vmf.vmf_ax = 0xE801;
1017 	if (vm86_intcall(0x15, &vmf) == 0) {
1018 		extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
1019 	} else {
1020 		/*
1021 		 * If INT15:E801 fails, this is our last ditch effort
1022 		 * to determine the extended memory size.  Currently
1023 		 * we prefer the RTC value over INT15:88.
1024 		 */
1025 #if 0
1026 		vmf.vmf_ah = 0x88;
1027 		vm86_intcall(0x15, &vmf);
1028 		extmem = vmf.vmf_ax;
1029 #else
1030 		extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
1031 #endif
1032 	}
1033 
1034 	/*
1035 	 * Special hack for chipsets that still remap the 384k hole when
1036 	 * there's 16MB of memory - this really confuses people that
1037 	 * are trying to use bus mastering ISA controllers with the
1038 	 * "16MB limit"; they only have 16MB, but the remapping puts
1039 	 * them beyond the limit.
1040 	 *
1041 	 * If extended memory is between 15-16MB (16-17MB phys address range),
1042 	 *	chop it to 15MB.
1043 	 */
1044 	if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
1045 		extmem = 15 * 1024;
1046 
1047 	physmap[0] = 0;
1048 	physmap[1] = basemem * 1024;
1049 	physmap_idx = 2;
1050 	physmap[physmap_idx] = 0x100000;
1051 	physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1052 
1053 physmap_done:
1054 	/*
1055 	 * Now, physmap contains a map of physical memory.
1056 	 */
1057 
1058 #ifdef SMP
1059 	/* make hole for AP bootstrap code */
1060 	alloc_ap_trampoline(physmap, &physmap_idx);
1061 #endif
1062 
1063 	/*
1064 	 * Maxmem isn't the "maximum memory", it's one larger than the
1065 	 * highest page of the physical address space.  It should be
1066 	 * called something like "Maxphyspage".  We may adjust this
1067 	 * based on ``hw.physmem'' and the results of the memory test.
1068 	 *
1069 	 * This is especially confusing when it is much larger than the
1070 	 * memory size and is displayed as "realmem".
1071 	 */
1072 	Maxmem = atop(physmap[physmap_idx + 1]);
1073 
1074 #ifdef MAXMEM
1075 	Maxmem = MAXMEM / 4;
1076 #endif
1077 
1078 	if (TUNABLE_QUAD_FETCH("hw.physmem", &physmem_tunable))
1079 		Maxmem = atop(physmem_tunable);
1080 
1081 	/*
1082 	 * If we have an SMAP, don't allow MAXMEM or hw.physmem to extend
1083 	 * the amount of memory in the system.
1084 	 */
1085 	if (has_smap && Maxmem > atop(physmap[physmap_idx + 1]))
1086 		Maxmem = atop(physmap[physmap_idx + 1]);
1087 
1088 	/*
1089 	 * The boot memory test is disabled by default, as it takes a
1090 	 * significant amount of time on large-memory systems, and is
1091 	 * unfriendly to virtual machines as it unnecessarily touches all
1092 	 * pages.
1093 	 *
1094 	 * A general name is used as the code may be extended to support
1095 	 * additional tests beyond the current "page present" test.
1096 	 */
1097 	memtest = 0;
1098 	TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
1099 
1100 	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1101 	    (boothowto & RB_VERBOSE))
1102 		printf("Physical memory use set to %ldK\n", Maxmem * 4);
1103 
1104 	/*
1105 	 * If Maxmem has been increased beyond what the system has detected,
1106 	 * extend the last memory segment to the new limit.
1107 	 */
1108 	if (atop(physmap[physmap_idx + 1]) < Maxmem)
1109 		physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
1110 
1111 	/* call pmap initialization to make new kernel address space */
1112 	pmap_bootstrap(first);
1113 
1114 	/*
1115 	 * Size up each available chunk of physical memory.
1116 	 */
1117 	physmap[0] = PAGE_SIZE;		/* mask off page 0 */
1118 	pa_indx = 0;
1119 	da_indx = 1;
1120 	phys_avail[pa_indx++] = physmap[0];
1121 	phys_avail[pa_indx] = physmap[0];
1122 	dump_avail[da_indx] = physmap[0];
1123 
1124 	/*
1125 	 * Get dcons buffer address
1126 	 */
1127 	if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
1128 	    getenv_quad("dcons.size", &dcons_size) == 0)
1129 		dcons_addr = 0;
1130 
1131 	/*
1132 	 * physmap is in bytes, so when converting to page boundaries,
1133 	 * round up the start address and round down the end address.
1134 	 */
1135 	for (i = 0; i <= physmap_idx; i += 2) {
1136 		vm_paddr_t end;
1137 
1138 		end = ptoa((vm_paddr_t)Maxmem);
1139 		if (physmap[i + 1] < end)
1140 			end = trunc_page(physmap[i + 1]);
1141 		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1142 			int *ptr;
1143 			int tmp;
1144 			bool full, page_bad;
1145 
1146 			full = false;
1147 			/*
1148 			 * block out kernel memory as not available.
1149 			 */
1150 			if (pa >= KERNLOAD && pa < first)
1151 				goto do_dump_avail;
1152 
1153 			/*
1154 			 * block out dcons buffer
1155 			 */
1156 			if (dcons_addr > 0
1157 			    && pa >= trunc_page(dcons_addr)
1158 			    && pa < dcons_addr + dcons_size)
1159 				goto do_dump_avail;
1160 
1161 			page_bad = false;
1162 			if (memtest == 0)
1163 				goto skip_memtest;
1164 
1165 			/*
1166 			 * map page into kernel: valid, read/write,non-cacheable
1167 			 */
1168 			ptr = (int *)pmap_cmap3(pa, PG_V | PG_RW | PG_N);
1169 
1170 			tmp = *(int *)ptr;
1171 			/*
1172 			 * Test for alternating 1's and 0's
1173 			 */
1174 			*(volatile int *)ptr = 0xaaaaaaaa;
1175 			if (*(volatile int *)ptr != 0xaaaaaaaa)
1176 				page_bad = true;
1177 			/*
1178 			 * Test for alternating 0's and 1's
1179 			 */
1180 			*(volatile int *)ptr = 0x55555555;
1181 			if (*(volatile int *)ptr != 0x55555555)
1182 				page_bad = true;
1183 			/*
1184 			 * Test for all 1's
1185 			 */
1186 			*(volatile int *)ptr = 0xffffffff;
1187 			if (*(volatile int *)ptr != 0xffffffff)
1188 				page_bad = true;
1189 			/*
1190 			 * Test for all 0's
1191 			 */
1192 			*(volatile int *)ptr = 0x0;
1193 			if (*(volatile int *)ptr != 0x0)
1194 				page_bad = true;
1195 			/*
1196 			 * Restore original value.
1197 			 */
1198 			*(int *)ptr = tmp;
1199 
1200 skip_memtest:
1201 			/*
1202 			 * Adjust array of valid/good pages.
1203 			 */
1204 			if (page_bad == true)
1205 				continue;
1206 			/*
1207 			 * If this good page is a continuation of the
1208 			 * previous set of good pages, then just increase
1209 			 * the end pointer. Otherwise start a new chunk.
1210 			 * Note that "end" points one higher than end,
1211 			 * making the range >= start and < end.
1212 			 * If we're also doing a speculative memory
1213 			 * test and we at or past the end, bump up Maxmem
1214 			 * so that we keep going. The first bad page
1215 			 * will terminate the loop.
1216 			 */
1217 			if (phys_avail[pa_indx] == pa) {
1218 				phys_avail[pa_indx] += PAGE_SIZE;
1219 			} else {
1220 				pa_indx++;
1221 				if (pa_indx == PHYS_AVAIL_ENTRIES) {
1222 					printf(
1223 		"Too many holes in the physical address space, giving up\n");
1224 					pa_indx--;
1225 					full = true;
1226 					goto do_dump_avail;
1227 				}
1228 				phys_avail[pa_indx++] = pa;	/* start */
1229 				phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1230 			}
1231 			physmem++;
1232 do_dump_avail:
1233 			if (dump_avail[da_indx] == pa) {
1234 				dump_avail[da_indx] += PAGE_SIZE;
1235 			} else {
1236 				da_indx++;
1237 				if (da_indx == PHYS_AVAIL_ENTRIES) {
1238 					da_indx--;
1239 					goto do_next;
1240 				}
1241 				dump_avail[da_indx++] = pa;	/* start */
1242 				dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1243 			}
1244 do_next:
1245 			if (full)
1246 				break;
1247 		}
1248 	}
1249 	pmap_cmap3(0, 0);
1250 
1251 	/*
1252 	 * XXX
1253 	 * The last chunk must contain at least one page plus the message
1254 	 * buffer to avoid complicating other code (message buffer address
1255 	 * calculation, etc.).
1256 	 */
1257 	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1258 	    round_page(msgbufsize) >= phys_avail[pa_indx]) {
1259 		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1260 		phys_avail[pa_indx--] = 0;
1261 		phys_avail[pa_indx--] = 0;
1262 	}
1263 
1264 	Maxmem = atop(phys_avail[pa_indx]);
1265 
1266 	/* Trim off space for the message buffer. */
1267 	phys_avail[pa_indx] -= round_page(msgbufsize);
1268 
1269 	/* Map the message buffer. */
1270 	for (off = 0; off < round_page(msgbufsize); off += PAGE_SIZE)
1271 		pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
1272 		    off);
1273 }
1274 
1275 static void
i386_kdb_init(void)1276 i386_kdb_init(void)
1277 {
1278 #ifdef DDB
1279 	db_fetch_ksymtab(bootinfo.bi_symtab, bootinfo.bi_esymtab, 0);
1280 #endif
1281 	kdb_init();
1282 #ifdef KDB
1283 	if (boothowto & RB_KDB)
1284 		kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
1285 #endif
1286 }
1287 
1288 static void
fixup_idt(void)1289 fixup_idt(void)
1290 {
1291 	struct gate_descriptor *ip;
1292 	uintptr_t off;
1293 	int x;
1294 
1295 	for (x = 0; x < NIDT; x++) {
1296 		ip = &idt[x];
1297 		if (ip->gd_type != SDT_SYS386IGT &&
1298 		    ip->gd_type != SDT_SYS386TGT)
1299 			continue;
1300 		off = ip->gd_looffset + (((u_int)ip->gd_hioffset) << 16);
1301 		KASSERT(off >= (uintptr_t)start_exceptions &&
1302 		    off < (uintptr_t)end_exceptions,
1303 		    ("IDT[%d] type %d off %#x", x, ip->gd_type, off));
1304 		off += setidt_disp;
1305 		MPASS(off >= PMAP_TRM_MIN_ADDRESS &&
1306 		    off < PMAP_TRM_MAX_ADDRESS);
1307 		ip->gd_looffset = off;
1308 		ip->gd_hioffset = off >> 16;
1309 	}
1310 }
1311 
1312 static void
i386_setidt1(void)1313 i386_setidt1(void)
1314 {
1315 	int x;
1316 
1317 	/* exceptions */
1318 	for (x = 0; x < NIDT; x++)
1319 		setidt(x, &IDTVEC(rsvd), SDT_SYS386IGT, SEL_KPL,
1320 		    GSEL(GCODE_SEL, SEL_KPL));
1321 	setidt(IDT_DE, &IDTVEC(div), SDT_SYS386IGT, SEL_KPL,
1322 	    GSEL(GCODE_SEL, SEL_KPL));
1323 	setidt(IDT_DB, &IDTVEC(dbg), SDT_SYS386IGT, SEL_KPL,
1324 	    GSEL(GCODE_SEL, SEL_KPL));
1325 	setidt(IDT_NMI, &IDTVEC(nmi), SDT_SYS386IGT, SEL_KPL,
1326 	    GSEL(GCODE_SEL, SEL_KPL));
1327 	setidt(IDT_BP, &IDTVEC(bpt), SDT_SYS386IGT, SEL_UPL,
1328 	    GSEL(GCODE_SEL, SEL_KPL));
1329 	setidt(IDT_OF, &IDTVEC(ofl), SDT_SYS386IGT, SEL_UPL,
1330 	    GSEL(GCODE_SEL, SEL_KPL));
1331 	setidt(IDT_BR, &IDTVEC(bnd), SDT_SYS386IGT, SEL_KPL,
1332 	    GSEL(GCODE_SEL, SEL_KPL));
1333 	setidt(IDT_UD, &IDTVEC(ill), SDT_SYS386IGT, SEL_KPL,
1334 	    GSEL(GCODE_SEL, SEL_KPL));
1335 	setidt(IDT_NM, &IDTVEC(dna), SDT_SYS386IGT, SEL_KPL,
1336 	    GSEL(GCODE_SEL, SEL_KPL));
1337 	setidt(IDT_DF, 0, SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL,
1338 	    SEL_KPL));
1339 	setidt(IDT_FPUGP, &IDTVEC(fpusegm), SDT_SYS386IGT,
1340 	    SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1341 	setidt(IDT_TS, &IDTVEC(tss), SDT_SYS386IGT, SEL_KPL,
1342 	    GSEL(GCODE_SEL, SEL_KPL));
1343 	setidt(IDT_NP, &IDTVEC(missing), SDT_SYS386IGT, SEL_KPL,
1344 	    GSEL(GCODE_SEL, SEL_KPL));
1345 	setidt(IDT_SS, &IDTVEC(stk), SDT_SYS386IGT, SEL_KPL,
1346 	    GSEL(GCODE_SEL, SEL_KPL));
1347 	setidt(IDT_GP, &IDTVEC(prot), SDT_SYS386IGT, SEL_KPL,
1348 	    GSEL(GCODE_SEL, SEL_KPL));
1349 	setidt(IDT_PF, &IDTVEC(page), SDT_SYS386IGT, SEL_KPL,
1350 	    GSEL(GCODE_SEL, SEL_KPL));
1351 	setidt(IDT_MF, &IDTVEC(fpu), SDT_SYS386IGT, SEL_KPL,
1352 	    GSEL(GCODE_SEL, SEL_KPL));
1353 	setidt(IDT_AC, &IDTVEC(align), SDT_SYS386IGT, SEL_KPL,
1354 	    GSEL(GCODE_SEL, SEL_KPL));
1355 	setidt(IDT_MC, &IDTVEC(mchk), SDT_SYS386IGT, SEL_KPL,
1356 	    GSEL(GCODE_SEL, SEL_KPL));
1357 	setidt(IDT_XF, &IDTVEC(xmm), SDT_SYS386IGT, SEL_KPL,
1358 	    GSEL(GCODE_SEL, SEL_KPL));
1359 	setidt(IDT_SYSCALL, &IDTVEC(int0x80_syscall),
1360 	    SDT_SYS386IGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1361 #ifdef KDTRACE_HOOKS
1362 	setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret),
1363 	    SDT_SYS386IGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1364 #endif
1365 #ifdef XENHVM
1366 	setidt(IDT_EVTCHN, &IDTVEC(xen_intr_upcall),
1367 	    SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1368 #endif
1369 }
1370 
1371 static void
i386_setidt2(void)1372 i386_setidt2(void)
1373 {
1374 
1375 	setidt(IDT_UD, &IDTVEC(ill), SDT_SYS386IGT, SEL_KPL,
1376 	    GSEL(GCODE_SEL, SEL_KPL));
1377 	setidt(IDT_GP, &IDTVEC(prot), SDT_SYS386IGT, SEL_KPL,
1378 	    GSEL(GCODE_SEL, SEL_KPL));
1379 }
1380 
1381 #if defined(DEV_ISA) && !defined(DEV_ATPIC)
1382 static void
i386_setidt3(void)1383 i386_setidt3(void)
1384 {
1385 
1386 	setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint),
1387 	    SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1388 	setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint),
1389 	    SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1390 }
1391 #endif
1392 
1393 register_t
init386(int first)1394 init386(int first)
1395 {
1396 	struct region_descriptor r_gdt, r_idt;	/* table descriptors */
1397 	int gsel_tss, metadata_missing, x, pa;
1398 	struct pcpu *pc;
1399 	struct xstate_hdr *xhdr;
1400 	caddr_t kmdp;
1401 	vm_offset_t addend;
1402 	size_t ucode_len;
1403 	int late_console;
1404 
1405 	thread0.td_kstack = proc0kstack;
1406 	thread0.td_kstack_pages = TD0_KSTACK_PAGES;
1407 
1408 	/*
1409  	 * This may be done better later if it gets more high level
1410  	 * components in it. If so just link td->td_proc here.
1411 	 */
1412 	proc_linkup0(&proc0, &thread0);
1413 
1414 	if (bootinfo.bi_modulep) {
1415 		metadata_missing = 0;
1416 		addend = (vm_paddr_t)bootinfo.bi_modulep < KERNBASE ?
1417 		    PMAP_MAP_LOW : 0;
1418 		preload_metadata = (caddr_t)bootinfo.bi_modulep + addend;
1419 		preload_bootstrap_relocate(addend);
1420 	} else {
1421 		metadata_missing = 1;
1422 	}
1423 
1424 	if (bootinfo.bi_envp != 0) {
1425 		addend = (vm_paddr_t)bootinfo.bi_envp < KERNBASE ?
1426 		    PMAP_MAP_LOW : 0;
1427 		init_static_kenv((char *)bootinfo.bi_envp + addend, 0);
1428 	} else {
1429 		init_static_kenv(NULL, 0);
1430 	}
1431 
1432 	/*
1433 	 * Re-evaluate CPU features if we loaded a microcode update.
1434 	 */
1435 	ucode_len = ucode_load_bsp(first);
1436 	if (ucode_len != 0) {
1437 		identify_cpu();
1438 		first = roundup2(first + ucode_len, PAGE_SIZE);
1439 	}
1440 
1441 	identify_hypervisor();
1442 
1443 	/* Init basic tunables, hz etc */
1444 	init_param1();
1445 
1446 	/*
1447 	 * Make gdt memory segments.  All segments cover the full 4GB
1448 	 * of address space and permissions are enforced at page level.
1449 	 */
1450 	gdt_segs[GCODE_SEL].ssd_limit = atop(0 - 1);
1451 	gdt_segs[GDATA_SEL].ssd_limit = atop(0 - 1);
1452 	gdt_segs[GUCODE_SEL].ssd_limit = atop(0 - 1);
1453 	gdt_segs[GUDATA_SEL].ssd_limit = atop(0 - 1);
1454 	gdt_segs[GUFS_SEL].ssd_limit = atop(0 - 1);
1455 	gdt_segs[GUGS_SEL].ssd_limit = atop(0 - 1);
1456 
1457 	pc = &__pcpu[0];
1458 	gdt_segs[GPRIV_SEL].ssd_limit = atop(0 - 1);
1459 	gdt_segs[GPRIV_SEL].ssd_base = (int)pc;
1460 	gdt_segs[GPROC0_SEL].ssd_base = (int)&common_tss0;
1461 
1462 	for (x = 0; x < NGDT; x++)
1463 		ssdtosd(&gdt_segs[x], &gdt0[x].sd);
1464 
1465 	r_gdt.rd_limit = NGDT * sizeof(gdt0[0]) - 1;
1466 	r_gdt.rd_base =  (int)gdt0;
1467 	mtx_init(&dt_lock, "descriptor tables", NULL, MTX_SPIN);
1468 	lgdt(&r_gdt);
1469 
1470 	pcpu_init(pc, 0, sizeof(struct pcpu));
1471 	for (pa = first; pa < first + DPCPU_SIZE; pa += PAGE_SIZE)
1472 		pmap_kenter(pa, pa);
1473 	dpcpu_init((void *)first, 0);
1474 	first += DPCPU_SIZE;
1475 	PCPU_SET(prvspace, pc);
1476 	PCPU_SET(curthread, &thread0);
1477 	/* Non-late cninit() and printf() can be moved up to here. */
1478 
1479 	/*
1480 	 * Initialize mutexes.
1481 	 *
1482 	 * icu_lock: in order to allow an interrupt to occur in a critical
1483 	 * 	     section, to set pcpu->ipending (etc...) properly, we
1484 	 *	     must be able to get the icu lock, so it can't be
1485 	 *	     under witness.
1486 	 */
1487 	mutex_init();
1488 	mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS | MTX_NOPROFILE);
1489 
1490 	i386_setidt1();
1491 
1492 	r_idt.rd_limit = sizeof(idt0) - 1;
1493 	r_idt.rd_base = (int) idt;
1494 	lidt(&r_idt);
1495 
1496 	finishidentcpu();	/* Final stage of CPU initialization */
1497 
1498 	/*
1499 	 * Initialize the clock before the console so that console
1500 	 * initialization can use DELAY().
1501 	 */
1502 	clock_init();
1503 
1504 	i386_setidt2();
1505 	pmap_set_nx();
1506 	initializecpu();	/* Initialize CPU registers */
1507 	initializecpucache();
1508 
1509 	/* pointer to selector slot for %fs/%gs */
1510 	PCPU_SET(fsgs_gdt, &gdt[GUFS_SEL].sd);
1511 
1512 	/* Initialize the tss (except for the final esp0) early for vm86. */
1513 	common_tss0.tss_esp0 = thread0.td_kstack + thread0.td_kstack_pages *
1514 	    PAGE_SIZE - VM86_STACK_SPACE;
1515 	common_tss0.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
1516 	common_tss0.tss_ioopt = sizeof(struct i386tss) << 16;
1517 	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1518 	PCPU_SET(tss_gdt, &gdt[GPROC0_SEL].sd);
1519 	PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
1520 	ltr(gsel_tss);
1521 
1522 	/* Initialize the PIC early for vm86 calls. */
1523 #ifdef DEV_ISA
1524 #ifdef DEV_ATPIC
1525 	elcr_probe();
1526 	atpic_startup();
1527 #else
1528 	/* Reset and mask the atpics and leave them shut down. */
1529 	atpic_reset();
1530 
1531 	/*
1532 	 * Point the ICU spurious interrupt vectors at the APIC spurious
1533 	 * interrupt handler.
1534 	 */
1535 	i386_setidt3();
1536 #endif
1537 #endif
1538 
1539 	/*
1540 	 * The console and kdb should be initialized even earlier than here,
1541 	 * but some console drivers don't work until after getmemsize().
1542 	 * Default to late console initialization to support these drivers.
1543 	 * This loses mainly printf()s in getmemsize() and early debugging.
1544 	 */
1545 	late_console = 1;
1546 	TUNABLE_INT_FETCH("debug.late_console", &late_console);
1547 	if (!late_console) {
1548 		cninit();
1549 		i386_kdb_init();
1550 	}
1551 
1552 	if (cpu_fxsr && (cpu_feature2 & CPUID2_XSAVE) != 0) {
1553 		use_xsave = 1;
1554 		TUNABLE_INT_FETCH("hw.use_xsave", &use_xsave);
1555 	}
1556 
1557 	kmdp = preload_search_by_type("elf kernel");
1558 	link_elf_ireloc(kmdp);
1559 
1560 	vm86_initialize();
1561 	getmemsize(first);
1562 	init_param2(physmem);
1563 
1564 	/* now running on new page tables, configured,and u/iom is accessible */
1565 
1566 	if (late_console)
1567 		cninit();
1568 
1569 	if (metadata_missing)
1570 		printf("WARNING: loader(8) metadata is missing!\n");
1571 
1572 	if (late_console)
1573 		i386_kdb_init();
1574 
1575 	msgbufinit(msgbufp, msgbufsize);
1576 	npxinit(true);
1577 
1578 	/*
1579 	 * Set up thread0 pcb after npxinit calculated pcb + fpu save
1580 	 * area size.  Zero out the extended state header in fpu save
1581 	 * area.
1582 	 */
1583 	thread0.td_pcb = get_pcb_td(&thread0);
1584 	thread0.td_pcb->pcb_save = get_pcb_user_save_td(&thread0);
1585 	bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
1586 	if (use_xsave) {
1587 		xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
1588 		    1);
1589 		xhdr->xstate_bv = xsave_mask;
1590 	}
1591 	PCPU_SET(curpcb, thread0.td_pcb);
1592 	/* Move esp0 in the tss to its final place. */
1593 	/* Note: -16 is so we can grow the trapframe if we came from vm86 */
1594 	common_tss0.tss_esp0 = (vm_offset_t)thread0.td_pcb - VM86_STACK_SPACE;
1595 	PCPU_SET(kesp0, common_tss0.tss_esp0);
1596 	gdt[GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;	/* clear busy bit */
1597 	ltr(gsel_tss);
1598 
1599 	/* transfer to user mode */
1600 
1601 	_ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
1602 	_udatasel = GSEL(GUDATA_SEL, SEL_UPL);
1603 
1604 	/* setup proc 0's pcb */
1605 	thread0.td_pcb->pcb_flags = 0;
1606 	thread0.td_pcb->pcb_cr3 = pmap_get_kcr3();
1607 	thread0.td_pcb->pcb_ext = 0;
1608 	thread0.td_frame = &proc0_tf;
1609 
1610 #ifdef FDT
1611 	x86_init_fdt();
1612 #endif
1613 
1614 	/* Location of kernel stack for locore */
1615 	return ((register_t)thread0.td_pcb);
1616 }
1617 
1618 static void
machdep_init_trampoline(void)1619 machdep_init_trampoline(void)
1620 {
1621 	struct region_descriptor r_gdt, r_idt;
1622 	struct i386tss *tss;
1623 	char *copyout_buf, *trampoline, *tramp_stack_base;
1624 	int x;
1625 
1626 	gdt = pmap_trm_alloc(sizeof(union descriptor) * NGDT * mp_ncpus,
1627 	    M_NOWAIT | M_ZERO);
1628 	bcopy(gdt0, gdt, sizeof(union descriptor) * NGDT);
1629 	r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1630 	r_gdt.rd_base = (int)gdt;
1631 	lgdt(&r_gdt);
1632 
1633 	tss = pmap_trm_alloc(sizeof(struct i386tss) * mp_ncpus,
1634 	    M_NOWAIT | M_ZERO);
1635 	bcopy(&common_tss0, tss, sizeof(struct i386tss));
1636 	gdt[GPROC0_SEL].sd.sd_lobase = (int)tss;
1637 	gdt[GPROC0_SEL].sd.sd_hibase = (u_int)tss >> 24;
1638 	gdt[GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
1639 
1640 	PCPU_SET(fsgs_gdt, &gdt[GUFS_SEL].sd);
1641 	PCPU_SET(tss_gdt, &gdt[GPROC0_SEL].sd);
1642 	PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
1643 	PCPU_SET(common_tssp, tss);
1644 	ltr(GSEL(GPROC0_SEL, SEL_KPL));
1645 
1646 	trampoline = pmap_trm_alloc(end_exceptions - start_exceptions,
1647 	    M_NOWAIT);
1648 	bcopy(start_exceptions, trampoline, end_exceptions - start_exceptions);
1649 	tramp_stack_base = pmap_trm_alloc(TRAMP_STACK_SZ, M_NOWAIT);
1650 	PCPU_SET(trampstk, (uintptr_t)tramp_stack_base + TRAMP_STACK_SZ -
1651 	    VM86_STACK_SPACE);
1652 	tss[0].tss_esp0 = PCPU_GET(trampstk);
1653 
1654 	idt = pmap_trm_alloc(sizeof(idt0), M_NOWAIT | M_ZERO);
1655 	bcopy(idt0, idt, sizeof(idt0));
1656 
1657 	/* Re-initialize new IDT since the handlers were relocated */
1658 	setidt_disp = trampoline - start_exceptions;
1659 	if (bootverbose)
1660 		printf("Trampoline disposition %#zx\n", setidt_disp);
1661 	fixup_idt();
1662 
1663 	r_idt.rd_limit = sizeof(struct gate_descriptor) * NIDT - 1;
1664 	r_idt.rd_base = (int)idt;
1665 	lidt(&r_idt);
1666 
1667 	/* dblfault TSS */
1668 	dblfault_tss = pmap_trm_alloc(sizeof(struct i386tss), M_NOWAIT | M_ZERO);
1669 	dblfault_stack = pmap_trm_alloc(PAGE_SIZE, M_NOWAIT);
1670 	dblfault_tss->tss_esp = dblfault_tss->tss_esp0 =
1671 	    dblfault_tss->tss_esp1 = dblfault_tss->tss_esp2 =
1672 	    (int)dblfault_stack + PAGE_SIZE;
1673 	dblfault_tss->tss_ss = dblfault_tss->tss_ss0 = dblfault_tss->tss_ss1 =
1674 	    dblfault_tss->tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1675 	dblfault_tss->tss_cr3 = pmap_get_kcr3();
1676 	dblfault_tss->tss_eip = (int)dblfault_handler;
1677 	dblfault_tss->tss_eflags = PSL_KERNEL;
1678 	dblfault_tss->tss_ds = dblfault_tss->tss_es =
1679 	    dblfault_tss->tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1680 	dblfault_tss->tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1681 	dblfault_tss->tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1682 	dblfault_tss->tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1683 	gdt[GPANIC_SEL].sd.sd_lobase = (int)dblfault_tss;
1684 	gdt[GPANIC_SEL].sd.sd_hibase = (u_int)dblfault_tss >> 24;
1685 
1686 	/* make ldt memory segments */
1687 	ldt = pmap_trm_alloc(sizeof(union descriptor) * NLDT,
1688 	    M_NOWAIT | M_ZERO);
1689 	gdt[GLDT_SEL].sd.sd_lobase = (int)ldt;
1690 	gdt[GLDT_SEL].sd.sd_hibase = (u_int)ldt >> 24;
1691 	ldt_segs[LUCODE_SEL].ssd_limit = atop(0 - 1);
1692 	ldt_segs[LUDATA_SEL].ssd_limit = atop(0 - 1);
1693 	for (x = 0; x < nitems(ldt_segs); x++)
1694 		ssdtosd(&ldt_segs[x], &ldt[x].sd);
1695 
1696 	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1697 	lldt(_default_ldt);
1698 	PCPU_SET(currentldt, _default_ldt);
1699 
1700 	copyout_buf = pmap_trm_alloc(TRAMP_COPYOUT_SZ, M_NOWAIT);
1701 	PCPU_SET(copyout_buf, copyout_buf);
1702 	copyout_init_tramp();
1703 }
1704 SYSINIT(vm_mem, SI_SUB_VM, SI_ORDER_SECOND, machdep_init_trampoline, NULL);
1705 
1706 #ifdef COMPAT_43
1707 static void
i386_setup_lcall_gate(void)1708 i386_setup_lcall_gate(void)
1709 {
1710 	struct sysentvec *sv;
1711 	struct user_segment_descriptor desc;
1712 	u_int lcall_addr;
1713 
1714 	sv = &elf32_freebsd_sysvec;
1715 	lcall_addr = (uintptr_t)sv->sv_psstrings - sz_lcall_tramp;
1716 
1717 	bzero(&desc, sizeof(desc));
1718 	desc.sd_type = SDT_MEMERA;
1719 	desc.sd_dpl = SEL_UPL;
1720 	desc.sd_p = 1;
1721 	desc.sd_def32 = 1;
1722 	desc.sd_gran = 1;
1723 	desc.sd_lolimit = 0xffff;
1724 	desc.sd_hilimit = 0xf;
1725 	desc.sd_lobase = lcall_addr;
1726 	desc.sd_hibase = lcall_addr >> 24;
1727 	bcopy(&desc, &ldt[LSYS5CALLS_SEL], sizeof(desc));
1728 }
1729 SYSINIT(elf32, SI_SUB_EXEC, SI_ORDER_ANY, i386_setup_lcall_gate, NULL);
1730 #endif
1731 
1732 void
cpu_pcpu_init(struct pcpu * pcpu,int cpuid,size_t size)1733 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
1734 {
1735 
1736 	pcpu->pc_acpi_id = 0xffffffff;
1737 }
1738 
1739 static int
smap_sysctl_handler(SYSCTL_HANDLER_ARGS)1740 smap_sysctl_handler(SYSCTL_HANDLER_ARGS)
1741 {
1742 	struct bios_smap *smapbase;
1743 	struct bios_smap_xattr smap;
1744 	caddr_t kmdp;
1745 	uint32_t *smapattr;
1746 	int count, error, i;
1747 
1748 	/* Retrieve the system memory map from the loader. */
1749 	kmdp = preload_search_by_type("elf kernel");
1750 	if (kmdp == NULL)
1751 		kmdp = preload_search_by_type("elf32 kernel");
1752 	smapbase = (struct bios_smap *)preload_search_info(kmdp,
1753 	    MODINFO_METADATA | MODINFOMD_SMAP);
1754 	if (smapbase == NULL)
1755 		return (0);
1756 	smapattr = (uint32_t *)preload_search_info(kmdp,
1757 	    MODINFO_METADATA | MODINFOMD_SMAP_XATTR);
1758 	count = *((u_int32_t *)smapbase - 1) / sizeof(*smapbase);
1759 	error = 0;
1760 	for (i = 0; i < count; i++) {
1761 		smap.base = smapbase[i].base;
1762 		smap.length = smapbase[i].length;
1763 		smap.type = smapbase[i].type;
1764 		if (smapattr != NULL)
1765 			smap.xattr = smapattr[i];
1766 		else
1767 			smap.xattr = 0;
1768 		error = SYSCTL_OUT(req, &smap, sizeof(smap));
1769 	}
1770 	return (error);
1771 }
1772 SYSCTL_PROC(_machdep, OID_AUTO, smap,
1773     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1774     smap_sysctl_handler, "S,bios_smap_xattr",
1775     "Raw BIOS SMAP data");
1776 
1777 void
spinlock_enter(void)1778 spinlock_enter(void)
1779 {
1780 	struct thread *td;
1781 	register_t flags;
1782 
1783 	td = curthread;
1784 	if (td->td_md.md_spinlock_count == 0) {
1785 		flags = intr_disable();
1786 		td->td_md.md_spinlock_count = 1;
1787 		td->td_md.md_saved_flags = flags;
1788 		critical_enter();
1789 	} else
1790 		td->td_md.md_spinlock_count++;
1791 }
1792 
1793 void
spinlock_exit(void)1794 spinlock_exit(void)
1795 {
1796 	struct thread *td;
1797 	register_t flags;
1798 
1799 	td = curthread;
1800 	flags = td->td_md.md_saved_flags;
1801 	td->td_md.md_spinlock_count--;
1802 	if (td->td_md.md_spinlock_count == 0) {
1803 		critical_exit();
1804 		intr_restore(flags);
1805 	}
1806 }
1807 
1808 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
1809 static void f00f_hack(void *unused);
1810 SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
1811 
1812 static void
f00f_hack(void * unused)1813 f00f_hack(void *unused)
1814 {
1815 	struct region_descriptor r_idt;
1816 	struct gate_descriptor *new_idt;
1817 	vm_offset_t tmp;
1818 
1819 	if (!has_f00f_bug)
1820 		return;
1821 
1822 	GIANT_REQUIRED;
1823 
1824 	printf("Intel Pentium detected, installing workaround for F00F bug\n");
1825 
1826 	tmp = (vm_offset_t)pmap_trm_alloc(PAGE_SIZE * 3, M_NOWAIT | M_ZERO);
1827 	if (tmp == 0)
1828 		panic("kmem_malloc returned 0");
1829 	tmp = round_page(tmp);
1830 
1831 	/* Put the problematic entry (#6) at the end of the lower page. */
1832 	new_idt = (struct gate_descriptor *)
1833 	    (tmp + PAGE_SIZE - 7 * sizeof(struct gate_descriptor));
1834 	bcopy(idt, new_idt, sizeof(idt0));
1835 	r_idt.rd_base = (u_int)new_idt;
1836 	r_idt.rd_limit = sizeof(idt0) - 1;
1837 	lidt(&r_idt);
1838 	/* SMP machines do not need the F00F hack. */
1839 	idt = new_idt;
1840 	pmap_protect(kernel_pmap, tmp, tmp + PAGE_SIZE, VM_PROT_READ);
1841 }
1842 #endif /* defined(I586_CPU) && !NO_F00F_HACK */
1843 
1844 /*
1845  * Construct a PCB from a trapframe. This is called from kdb_trap() where
1846  * we want to start a backtrace from the function that caused us to enter
1847  * the debugger. We have the context in the trapframe, but base the trace
1848  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
1849  * enough for a backtrace.
1850  */
1851 void
makectx(struct trapframe * tf,struct pcb * pcb)1852 makectx(struct trapframe *tf, struct pcb *pcb)
1853 {
1854 
1855 	pcb->pcb_edi = tf->tf_edi;
1856 	pcb->pcb_esi = tf->tf_esi;
1857 	pcb->pcb_ebp = tf->tf_ebp;
1858 	pcb->pcb_ebx = tf->tf_ebx;
1859 	pcb->pcb_eip = tf->tf_eip;
1860 	pcb->pcb_esp = (ISPL(tf->tf_cs)) ? tf->tf_esp : (int)(tf + 1) - 8;
1861 	pcb->pcb_gs = rgs();
1862 }
1863 
1864 #ifdef KDB
1865 
1866 /*
1867  * Provide inb() and outb() as functions.  They are normally only available as
1868  * inline functions, thus cannot be called from the debugger.
1869  */
1870 
1871 /* silence compiler warnings */
1872 u_char inb_(u_short);
1873 void outb_(u_short, u_char);
1874 
1875 u_char
inb_(u_short port)1876 inb_(u_short port)
1877 {
1878 	return inb(port);
1879 }
1880 
1881 void
outb_(u_short port,u_char data)1882 outb_(u_short port, u_char data)
1883 {
1884 	outb(port, data);
1885 }
1886 
1887 #endif /* KDB */
1888