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