xref: /freebsd/sys/x86/x86/cpu_machdep.c (revision 86aa9539fef591a363b06a0ebd3aa7a07f4c1579)
1 /*-
2  * Copyright (c) 2003 Peter Wemm.
3  * Copyright (c) 1992 Terrence R. Lambert.
4  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * William Jolitz.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	from: @(#)machdep.c	7.4 (Berkeley) 6/3/91
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_acpi.h"
45 #include "opt_atpic.h"
46 #include "opt_cpu.h"
47 #include "opt_ddb.h"
48 #include "opt_inet.h"
49 #include "opt_isa.h"
50 #include "opt_kdb.h"
51 #include "opt_kstack_pages.h"
52 #include "opt_maxmem.h"
53 #include "opt_mp_watchdog.h"
54 #include "opt_platform.h"
55 #ifdef __i386__
56 #include "opt_apic.h"
57 #endif
58 
59 #include <sys/param.h>
60 #include <sys/proc.h>
61 #include <sys/systm.h>
62 #include <sys/bus.h>
63 #include <sys/cpu.h>
64 #include <sys/domainset.h>
65 #include <sys/kdb.h>
66 #include <sys/kernel.h>
67 #include <sys/ktr.h>
68 #include <sys/lock.h>
69 #include <sys/malloc.h>
70 #include <sys/mutex.h>
71 #include <sys/pcpu.h>
72 #include <sys/rwlock.h>
73 #include <sys/sched.h>
74 #include <sys/smp.h>
75 #include <sys/sysctl.h>
76 
77 #include <machine/clock.h>
78 #include <machine/cpu.h>
79 #include <machine/cputypes.h>
80 #include <machine/specialreg.h>
81 #include <machine/md_var.h>
82 #include <machine/mp_watchdog.h>
83 #include <machine/tss.h>
84 #ifdef SMP
85 #include <machine/smp.h>
86 #endif
87 #ifdef CPU_ELAN
88 #include <machine/elan_mmcr.h>
89 #endif
90 #include <x86/acpica_machdep.h>
91 
92 #include <vm/vm.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_param.h>
100 
101 #include <isa/isareg.h>
102 
103 #include <contrib/dev/acpica/include/acpi.h>
104 
105 #define	STATE_RUNNING	0x0
106 #define	STATE_MWAIT	0x1
107 #define	STATE_SLEEPING	0x2
108 
109 #ifdef SMP
110 static u_int	cpu_reset_proxyid;
111 static volatile u_int	cpu_reset_proxy_active;
112 #endif
113 
114 /*
115  * Automatically initialized per CPU errata in cpu_idle_tun below.
116  */
117 bool mwait_cpustop_broken = false;
118 SYSCTL_BOOL(_machdep, OID_AUTO, mwait_cpustop_broken, CTLFLAG_RDTUN,
119     &mwait_cpustop_broken, 0,
120     "Can not reliably wake MONITOR/MWAIT cpus without interrupts");
121 
122 /*
123  * Machine dependent boot() routine
124  *
125  * I haven't seen anything to put here yet
126  * Possibly some stuff might be grafted back here from boot()
127  */
128 void
129 cpu_boot(int howto)
130 {
131 }
132 
133 /*
134  * Flush the D-cache for non-DMA I/O so that the I-cache can
135  * be made coherent later.
136  */
137 void
138 cpu_flush_dcache(void *ptr, size_t len)
139 {
140 	/* Not applicable */
141 }
142 
143 void
144 acpi_cpu_c1(void)
145 {
146 
147 	__asm __volatile("sti; hlt");
148 }
149 
150 /*
151  * Use mwait to pause execution while waiting for an interrupt or
152  * another thread to signal that there is more work.
153  *
154  * NOTE: Interrupts will cause a wakeup; however, this function does
155  * not enable interrupt handling. The caller is responsible to enable
156  * interrupts.
157  */
158 void
159 acpi_cpu_idle_mwait(uint32_t mwait_hint)
160 {
161 	int *state;
162 	uint64_t v;
163 
164 	/*
165 	 * A comment in Linux patch claims that 'CPUs run faster with
166 	 * speculation protection disabled. All CPU threads in a core
167 	 * must disable speculation protection for it to be
168 	 * disabled. Disable it while we are idle so the other
169 	 * hyperthread can run fast.'
170 	 *
171 	 * XXXKIB.  Software coordination mode should be supported,
172 	 * but all Intel CPUs provide hardware coordination.
173 	 */
174 
175 	state = &PCPU_PTR(monitorbuf)->idle_state;
176 	KASSERT(atomic_load_int(state) == STATE_SLEEPING,
177 	    ("cpu_mwait_cx: wrong monitorbuf state"));
178 	atomic_store_int(state, STATE_MWAIT);
179 	if (PCPU_GET(ibpb_set) || hw_ssb_active) {
180 		v = rdmsr(MSR_IA32_SPEC_CTRL);
181 		wrmsr(MSR_IA32_SPEC_CTRL, v & ~(IA32_SPEC_CTRL_IBRS |
182 		    IA32_SPEC_CTRL_STIBP | IA32_SPEC_CTRL_SSBD));
183 	} else {
184 		v = 0;
185 	}
186 	cpu_monitor(state, 0, 0);
187 	if (atomic_load_int(state) == STATE_MWAIT)
188 		cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
189 
190 	/*
191 	 * SSB cannot be disabled while we sleep, or rather, if it was
192 	 * disabled, the sysctl thread will bind to our cpu to tweak
193 	 * MSR.
194 	 */
195 	if (v != 0)
196 		wrmsr(MSR_IA32_SPEC_CTRL, v);
197 
198 	/*
199 	 * We should exit on any event that interrupts mwait, because
200 	 * that event might be a wanted interrupt.
201 	 */
202 	atomic_store_int(state, STATE_RUNNING);
203 }
204 
205 /* Get current clock frequency for the given cpu id. */
206 int
207 cpu_est_clockrate(int cpu_id, uint64_t *rate)
208 {
209 	uint64_t tsc1, tsc2;
210 	uint64_t acnt, mcnt, perf;
211 	register_t reg;
212 
213 	if (pcpu_find(cpu_id) == NULL || rate == NULL)
214 		return (EINVAL);
215 #ifdef __i386__
216 	if ((cpu_feature & CPUID_TSC) == 0)
217 		return (EOPNOTSUPP);
218 #endif
219 
220 	/*
221 	 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
222 	 * DELAY(9) based logic fails.
223 	 */
224 	if (tsc_is_invariant && !tsc_perf_stat)
225 		return (EOPNOTSUPP);
226 
227 #ifdef SMP
228 	if (smp_cpus > 1) {
229 		/* Schedule ourselves on the indicated cpu. */
230 		thread_lock(curthread);
231 		sched_bind(curthread, cpu_id);
232 		thread_unlock(curthread);
233 	}
234 #endif
235 
236 	/* Calibrate by measuring a short delay. */
237 	reg = intr_disable();
238 	if (tsc_is_invariant) {
239 		wrmsr(MSR_MPERF, 0);
240 		wrmsr(MSR_APERF, 0);
241 		tsc1 = rdtsc();
242 		DELAY(1000);
243 		mcnt = rdmsr(MSR_MPERF);
244 		acnt = rdmsr(MSR_APERF);
245 		tsc2 = rdtsc();
246 		intr_restore(reg);
247 		perf = 1000 * acnt / mcnt;
248 		*rate = (tsc2 - tsc1) * perf;
249 	} else {
250 		tsc1 = rdtsc();
251 		DELAY(1000);
252 		tsc2 = rdtsc();
253 		intr_restore(reg);
254 		*rate = (tsc2 - tsc1) * 1000;
255 	}
256 
257 #ifdef SMP
258 	if (smp_cpus > 1) {
259 		thread_lock(curthread);
260 		sched_unbind(curthread);
261 		thread_unlock(curthread);
262 	}
263 #endif
264 
265 	return (0);
266 }
267 
268 /*
269  * Shutdown the CPU as much as possible
270  */
271 void
272 cpu_halt(void)
273 {
274 	for (;;)
275 		halt();
276 }
277 
278 static void
279 cpu_reset_real(void)
280 {
281 	struct region_descriptor null_idt;
282 	int b;
283 
284 	disable_intr();
285 #ifdef CPU_ELAN
286 	if (elan_mmcr != NULL)
287 		elan_mmcr->RESCFG = 1;
288 #endif
289 #ifdef __i386__
290 	if (cpu == CPU_GEODE1100) {
291 		/* Attempt Geode's own reset */
292 		outl(0xcf8, 0x80009044ul);
293 		outl(0xcfc, 0xf);
294 	}
295 #endif
296 #if !defined(BROKEN_KEYBOARD_RESET)
297 	/*
298 	 * Attempt to do a CPU reset via the keyboard controller,
299 	 * do not turn off GateA20, as any machine that fails
300 	 * to do the reset here would then end up in no man's land.
301 	 */
302 	outb(IO_KBD + 4, 0xFE);
303 	DELAY(500000);	/* wait 0.5 sec to see if that did it */
304 #endif
305 
306 	/*
307 	 * Attempt to force a reset via the Reset Control register at
308 	 * I/O port 0xcf9.  Bit 2 forces a system reset when it
309 	 * transitions from 0 to 1.  Bit 1 selects the type of reset
310 	 * to attempt: 0 selects a "soft" reset, and 1 selects a
311 	 * "hard" reset.  We try a "hard" reset.  The first write sets
312 	 * bit 1 to select a "hard" reset and clears bit 2.  The
313 	 * second write forces a 0 -> 1 transition in bit 2 to trigger
314 	 * a reset.
315 	 */
316 	outb(0xcf9, 0x2);
317 	outb(0xcf9, 0x6);
318 	DELAY(500000);  /* wait 0.5 sec to see if that did it */
319 
320 	/*
321 	 * Attempt to force a reset via the Fast A20 and Init register
322 	 * at I/O port 0x92.  Bit 1 serves as an alternate A20 gate.
323 	 * Bit 0 asserts INIT# when set to 1.  We are careful to only
324 	 * preserve bit 1 while setting bit 0.  We also must clear bit
325 	 * 0 before setting it if it isn't already clear.
326 	 */
327 	b = inb(0x92);
328 	if (b != 0xff) {
329 		if ((b & 0x1) != 0)
330 			outb(0x92, b & 0xfe);
331 		outb(0x92, b | 0x1);
332 		DELAY(500000);  /* wait 0.5 sec to see if that did it */
333 	}
334 
335 	printf("No known reset method worked, attempting CPU shutdown\n");
336 	DELAY(1000000); /* wait 1 sec for printf to complete */
337 
338 	/* Wipe the IDT. */
339 	null_idt.rd_limit = 0;
340 	null_idt.rd_base = 0;
341 	lidt(&null_idt);
342 
343 	/* "good night, sweet prince .... <THUNK!>" */
344 	breakpoint();
345 
346 	/* NOTREACHED */
347 	while(1);
348 }
349 
350 #ifdef SMP
351 static void
352 cpu_reset_proxy(void)
353 {
354 
355 	cpu_reset_proxy_active = 1;
356 	while (cpu_reset_proxy_active == 1)
357 		ia32_pause(); /* Wait for other cpu to see that we've started */
358 
359 	printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
360 	DELAY(1000000);
361 	cpu_reset_real();
362 }
363 #endif
364 
365 void
366 cpu_reset(void)
367 {
368 #ifdef SMP
369 	struct monitorbuf *mb;
370 	cpuset_t map;
371 	u_int cnt;
372 
373 	if (smp_started) {
374 		map = all_cpus;
375 		CPU_CLR(PCPU_GET(cpuid), &map);
376 		CPU_NAND(&map, &stopped_cpus);
377 		if (!CPU_EMPTY(&map)) {
378 			printf("cpu_reset: Stopping other CPUs\n");
379 			stop_cpus(map);
380 		}
381 
382 		if (PCPU_GET(cpuid) != 0) {
383 			cpu_reset_proxyid = PCPU_GET(cpuid);
384 			cpustop_restartfunc = cpu_reset_proxy;
385 			cpu_reset_proxy_active = 0;
386 			printf("cpu_reset: Restarting BSP\n");
387 
388 			/* Restart CPU #0. */
389 			CPU_SETOF(0, &started_cpus);
390 			mb = &pcpu_find(0)->pc_monitorbuf;
391 			atomic_store_int(&mb->stop_state,
392 			    MONITOR_STOPSTATE_RUNNING);
393 			wmb();
394 
395 			cnt = 0;
396 			while (cpu_reset_proxy_active == 0 && cnt < 10000000) {
397 				ia32_pause();
398 				cnt++;	/* Wait for BSP to announce restart */
399 			}
400 			if (cpu_reset_proxy_active == 0) {
401 				printf("cpu_reset: Failed to restart BSP\n");
402 			} else {
403 				cpu_reset_proxy_active = 2;
404 				while (1)
405 					ia32_pause();
406 				/* NOTREACHED */
407 			}
408 		}
409 
410 		DELAY(1000000);
411 	}
412 #endif
413 	cpu_reset_real();
414 	/* NOTREACHED */
415 }
416 
417 bool
418 cpu_mwait_usable(void)
419 {
420 
421 	return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
422 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
423 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
424 }
425 
426 void (*cpu_idle_hook)(sbintime_t) = NULL;	/* ACPI idle hook. */
427 static int	cpu_ident_amdc1e = 0;	/* AMD C1E supported. */
428 static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
429 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
430     0, "Use MONITOR/MWAIT for short idle");
431 
432 static void
433 cpu_idle_acpi(sbintime_t sbt)
434 {
435 	int *state;
436 
437 	state = &PCPU_PTR(monitorbuf)->idle_state;
438 	atomic_store_int(state, STATE_SLEEPING);
439 
440 	/* See comments in cpu_idle_hlt(). */
441 	disable_intr();
442 	if (sched_runnable())
443 		enable_intr();
444 	else if (cpu_idle_hook)
445 		cpu_idle_hook(sbt);
446 	else
447 		acpi_cpu_c1();
448 	atomic_store_int(state, STATE_RUNNING);
449 }
450 
451 static void
452 cpu_idle_hlt(sbintime_t sbt)
453 {
454 	int *state;
455 
456 	state = &PCPU_PTR(monitorbuf)->idle_state;
457 	atomic_store_int(state, STATE_SLEEPING);
458 
459 	/*
460 	 * Since we may be in a critical section from cpu_idle(), if
461 	 * an interrupt fires during that critical section we may have
462 	 * a pending preemption.  If the CPU halts, then that thread
463 	 * may not execute until a later interrupt awakens the CPU.
464 	 * To handle this race, check for a runnable thread after
465 	 * disabling interrupts and immediately return if one is
466 	 * found.  Also, we must absolutely guarentee that hlt is
467 	 * the next instruction after sti.  This ensures that any
468 	 * interrupt that fires after the call to disable_intr() will
469 	 * immediately awaken the CPU from hlt.  Finally, please note
470 	 * that on x86 this works fine because of interrupts enabled only
471 	 * after the instruction following sti takes place, while IF is set
472 	 * to 1 immediately, allowing hlt instruction to acknowledge the
473 	 * interrupt.
474 	 */
475 	disable_intr();
476 	if (sched_runnable())
477 		enable_intr();
478 	else
479 		acpi_cpu_c1();
480 	atomic_store_int(state, STATE_RUNNING);
481 }
482 
483 static void
484 cpu_idle_mwait(sbintime_t sbt)
485 {
486 	int *state;
487 
488 	state = &PCPU_PTR(monitorbuf)->idle_state;
489 	atomic_store_int(state, STATE_MWAIT);
490 
491 	/* See comments in cpu_idle_hlt(). */
492 	disable_intr();
493 	if (sched_runnable()) {
494 		atomic_store_int(state, STATE_RUNNING);
495 		enable_intr();
496 		return;
497 	}
498 
499 	cpu_monitor(state, 0, 0);
500 	if (atomic_load_int(state) == STATE_MWAIT)
501 		__asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
502 	else
503 		enable_intr();
504 	atomic_store_int(state, STATE_RUNNING);
505 }
506 
507 static void
508 cpu_idle_spin(sbintime_t sbt)
509 {
510 	int *state;
511 	int i;
512 
513 	state = &PCPU_PTR(monitorbuf)->idle_state;
514 	atomic_store_int(state, STATE_RUNNING);
515 
516 	/*
517 	 * The sched_runnable() call is racy but as long as there is
518 	 * a loop missing it one time will have just a little impact if any
519 	 * (and it is much better than missing the check at all).
520 	 */
521 	for (i = 0; i < 1000; i++) {
522 		if (sched_runnable())
523 			return;
524 		cpu_spinwait();
525 	}
526 }
527 
528 /*
529  * C1E renders the local APIC timer dead, so we disable it by
530  * reading the Interrupt Pending Message register and clearing
531  * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
532  *
533  * Reference:
534  *   "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
535  *   #32559 revision 3.00+
536  */
537 #define	MSR_AMDK8_IPM		0xc0010055
538 #define	AMDK8_SMIONCMPHALT	(1ULL << 27)
539 #define	AMDK8_C1EONCMPHALT	(1ULL << 28)
540 #define	AMDK8_CMPHALT		(AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
541 
542 void
543 cpu_probe_amdc1e(void)
544 {
545 
546 	/*
547 	 * Detect the presence of C1E capability mostly on latest
548 	 * dual-cores (or future) k8 family.
549 	 */
550 	if (cpu_vendor_id == CPU_VENDOR_AMD &&
551 	    (cpu_id & 0x00000f00) == 0x00000f00 &&
552 	    (cpu_id & 0x0fff0000) >=  0x00040000) {
553 		cpu_ident_amdc1e = 1;
554 	}
555 }
556 
557 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
558 
559 void
560 cpu_idle(int busy)
561 {
562 	uint64_t msr;
563 	sbintime_t sbt = -1;
564 
565 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
566 	    busy, curcpu);
567 #ifdef MP_WATCHDOG
568 	ap_watchdog(PCPU_GET(cpuid));
569 #endif
570 
571 	/* If we are busy - try to use fast methods. */
572 	if (busy) {
573 		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
574 			cpu_idle_mwait(busy);
575 			goto out;
576 		}
577 	}
578 
579 	/* If we have time - switch timers into idle mode. */
580 	if (!busy) {
581 		critical_enter();
582 		sbt = cpu_idleclock();
583 	}
584 
585 	/* Apply AMD APIC timer C1E workaround. */
586 	if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
587 		msr = rdmsr(MSR_AMDK8_IPM);
588 		if (msr & AMDK8_CMPHALT)
589 			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
590 	}
591 
592 	/* Call main idle method. */
593 	cpu_idle_fn(sbt);
594 
595 	/* Switch timers back into active mode. */
596 	if (!busy) {
597 		cpu_activeclock();
598 		critical_exit();
599 	}
600 out:
601 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
602 	    busy, curcpu);
603 }
604 
605 static int cpu_idle_apl31_workaround;
606 SYSCTL_INT(_machdep, OID_AUTO, idle_apl31, CTLFLAG_RW,
607     &cpu_idle_apl31_workaround, 0,
608     "Apollo Lake APL31 MWAIT bug workaround");
609 
610 int
611 cpu_idle_wakeup(int cpu)
612 {
613 	struct monitorbuf *mb;
614 	int *state;
615 
616 	mb = &pcpu_find(cpu)->pc_monitorbuf;
617 	state = &mb->idle_state;
618 	switch (atomic_load_int(state)) {
619 	case STATE_SLEEPING:
620 		return (0);
621 	case STATE_MWAIT:
622 		atomic_store_int(state, STATE_RUNNING);
623 		return (cpu_idle_apl31_workaround ? 0 : 1);
624 	case STATE_RUNNING:
625 		return (1);
626 	default:
627 		panic("bad monitor state");
628 		return (1);
629 	}
630 }
631 
632 /*
633  * Ordered by speed/power consumption.
634  */
635 static struct {
636 	void	*id_fn;
637 	char	*id_name;
638 	int	id_cpuid2_flag;
639 } idle_tbl[] = {
640 	{ .id_fn = cpu_idle_spin, .id_name = "spin" },
641 	{ .id_fn = cpu_idle_mwait, .id_name = "mwait",
642 	    .id_cpuid2_flag = CPUID2_MON },
643 	{ .id_fn = cpu_idle_hlt, .id_name = "hlt" },
644 	{ .id_fn = cpu_idle_acpi, .id_name = "acpi" },
645 };
646 
647 static int
648 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
649 {
650 	char *avail, *p;
651 	int error;
652 	int i;
653 
654 	avail = malloc(256, M_TEMP, M_WAITOK);
655 	p = avail;
656 	for (i = 0; i < nitems(idle_tbl); i++) {
657 		if (idle_tbl[i].id_cpuid2_flag != 0 &&
658 		    (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
659 			continue;
660 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
661 		    cpu_idle_hook == NULL)
662 			continue;
663 		p += sprintf(p, "%s%s", p != avail ? ", " : "",
664 		    idle_tbl[i].id_name);
665 	}
666 	error = sysctl_handle_string(oidp, avail, 0, req);
667 	free(avail, M_TEMP);
668 	return (error);
669 }
670 
671 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
672     0, 0, idle_sysctl_available, "A", "list of available idle functions");
673 
674 static bool
675 cpu_idle_selector(const char *new_idle_name)
676 {
677 	int i;
678 
679 	for (i = 0; i < nitems(idle_tbl); i++) {
680 		if (idle_tbl[i].id_cpuid2_flag != 0 &&
681 		    (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
682 			continue;
683 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
684 		    cpu_idle_hook == NULL)
685 			continue;
686 		if (strcmp(idle_tbl[i].id_name, new_idle_name))
687 			continue;
688 		cpu_idle_fn = idle_tbl[i].id_fn;
689 		if (bootverbose)
690 			printf("CPU idle set to %s\n", idle_tbl[i].id_name);
691 		return (true);
692 	}
693 	return (false);
694 }
695 
696 static int
697 cpu_idle_sysctl(SYSCTL_HANDLER_ARGS)
698 {
699 	char buf[16], *p;
700 	int error, i;
701 
702 	p = "unknown";
703 	for (i = 0; i < nitems(idle_tbl); i++) {
704 		if (idle_tbl[i].id_fn == cpu_idle_fn) {
705 			p = idle_tbl[i].id_name;
706 			break;
707 		}
708 	}
709 	strncpy(buf, p, sizeof(buf));
710 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
711 	if (error != 0 || req->newptr == NULL)
712 		return (error);
713 	return (cpu_idle_selector(buf) ? 0 : EINVAL);
714 }
715 
716 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
717     cpu_idle_sysctl, "A", "currently selected idle function");
718 
719 static void
720 cpu_idle_tun(void *unused __unused)
721 {
722 	char tunvar[16];
723 
724 	if (TUNABLE_STR_FETCH("machdep.idle", tunvar, sizeof(tunvar)))
725 		cpu_idle_selector(tunvar);
726 	else if (cpu_vendor_id == CPU_VENDOR_AMD &&
727 	    CPUID_TO_FAMILY(cpu_id) == 0x17 && CPUID_TO_MODEL(cpu_id) == 0x1) {
728 		/* Ryzen erratas 1057, 1109. */
729 		cpu_idle_selector("hlt");
730 		idle_mwait = 0;
731 		mwait_cpustop_broken = true;
732 	}
733 
734 	if (cpu_vendor_id == CPU_VENDOR_INTEL && cpu_id == 0x506c9) {
735 		/*
736 		 * Apollo Lake errata APL31 (public errata APL30).
737 		 * Stores to the armed address range may not trigger
738 		 * MWAIT to resume execution.  OS needs to use
739 		 * interrupts to wake processors from MWAIT-induced
740 		 * sleep states.
741 		 */
742 		cpu_idle_apl31_workaround = 1;
743 		mwait_cpustop_broken = true;
744 	}
745 	TUNABLE_INT_FETCH("machdep.idle_apl31", &cpu_idle_apl31_workaround);
746 }
747 SYSINIT(cpu_idle_tun, SI_SUB_CPU, SI_ORDER_MIDDLE, cpu_idle_tun, NULL);
748 
749 static int panic_on_nmi = 1;
750 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
751     &panic_on_nmi, 0,
752     "Panic on NMI raised by hardware failure");
753 int nmi_is_broadcast = 1;
754 SYSCTL_INT(_machdep, OID_AUTO, nmi_is_broadcast, CTLFLAG_RWTUN,
755     &nmi_is_broadcast, 0,
756     "Chipset NMI is broadcast");
757 #ifdef KDB
758 int kdb_on_nmi = 1;
759 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
760     &kdb_on_nmi, 0,
761     "Go to KDB on NMI with unknown source");
762 #endif
763 
764 void
765 nmi_call_kdb(u_int cpu, u_int type, struct trapframe *frame)
766 {
767 	bool claimed = false;
768 
769 #ifdef DEV_ISA
770 	/* machine/parity/power fail/"kitchen sink" faults */
771 	if (isa_nmi(frame->tf_err)) {
772 		claimed = true;
773 		if (panic_on_nmi)
774 			panic("NMI indicates hardware failure");
775 	}
776 #endif /* DEV_ISA */
777 #ifdef KDB
778 	if (!claimed && kdb_on_nmi) {
779 		/*
780 		 * NMI can be hooked up to a pushbutton for debugging.
781 		 */
782 		printf("NMI/cpu%d ... going to debugger\n", cpu);
783 		kdb_trap(type, 0, frame);
784 	}
785 #endif /* KDB */
786 }
787 
788 void
789 nmi_handle_intr(u_int type, struct trapframe *frame)
790 {
791 
792 #ifdef SMP
793 	if (nmi_is_broadcast) {
794 		nmi_call_kdb_smp(type, frame);
795 		return;
796 	}
797 #endif
798 	nmi_call_kdb(PCPU_GET(cpuid), type, frame);
799 }
800 
801 int hw_ibrs_active;
802 int hw_ibrs_disable = 1;
803 
804 SYSCTL_INT(_hw, OID_AUTO, ibrs_active, CTLFLAG_RD, &hw_ibrs_active, 0,
805     "Indirect Branch Restricted Speculation active");
806 
807 void
808 hw_ibrs_recalculate(void)
809 {
810 	uint64_t v;
811 
812 	if ((cpu_ia32_arch_caps & IA32_ARCH_CAP_IBRS_ALL) != 0) {
813 		if (hw_ibrs_disable) {
814 			v = rdmsr(MSR_IA32_SPEC_CTRL);
815 			v &= ~(uint64_t)IA32_SPEC_CTRL_IBRS;
816 			wrmsr(MSR_IA32_SPEC_CTRL, v);
817 		} else {
818 			v = rdmsr(MSR_IA32_SPEC_CTRL);
819 			v |= IA32_SPEC_CTRL_IBRS;
820 			wrmsr(MSR_IA32_SPEC_CTRL, v);
821 		}
822 		return;
823 	}
824 	hw_ibrs_active = (cpu_stdext_feature3 & CPUID_STDEXT3_IBPB) != 0 &&
825 	    !hw_ibrs_disable;
826 }
827 
828 static int
829 hw_ibrs_disable_handler(SYSCTL_HANDLER_ARGS)
830 {
831 	int error, val;
832 
833 	val = hw_ibrs_disable;
834 	error = sysctl_handle_int(oidp, &val, 0, req);
835 	if (error != 0 || req->newptr == NULL)
836 		return (error);
837 	hw_ibrs_disable = val != 0;
838 	hw_ibrs_recalculate();
839 	return (0);
840 }
841 SYSCTL_PROC(_hw, OID_AUTO, ibrs_disable, CTLTYPE_INT | CTLFLAG_RWTUN |
842     CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0, hw_ibrs_disable_handler, "I",
843     "Disable Indirect Branch Restricted Speculation");
844 
845 int hw_ssb_active;
846 int hw_ssb_disable;
847 
848 SYSCTL_INT(_hw, OID_AUTO, spec_store_bypass_disable_active, CTLFLAG_RD,
849     &hw_ssb_active, 0,
850     "Speculative Store Bypass Disable active");
851 
852 static void
853 hw_ssb_set_one(bool enable)
854 {
855 	uint64_t v;
856 
857 	v = rdmsr(MSR_IA32_SPEC_CTRL);
858 	if (enable)
859 		v |= (uint64_t)IA32_SPEC_CTRL_SSBD;
860 	else
861 		v &= ~(uint64_t)IA32_SPEC_CTRL_SSBD;
862 	wrmsr(MSR_IA32_SPEC_CTRL, v);
863 }
864 
865 static void
866 hw_ssb_set(bool enable, bool for_all_cpus)
867 {
868 	struct thread *td;
869 	int bound_cpu, i, is_bound;
870 
871 	if ((cpu_stdext_feature3 & CPUID_STDEXT3_SSBD) == 0) {
872 		hw_ssb_active = 0;
873 		return;
874 	}
875 	hw_ssb_active = enable;
876 	if (for_all_cpus) {
877 		td = curthread;
878 		thread_lock(td);
879 		is_bound = sched_is_bound(td);
880 		bound_cpu = td->td_oncpu;
881 		CPU_FOREACH(i) {
882 			sched_bind(td, i);
883 			hw_ssb_set_one(enable);
884 		}
885 		if (is_bound)
886 			sched_bind(td, bound_cpu);
887 		else
888 			sched_unbind(td);
889 		thread_unlock(td);
890 	} else {
891 		hw_ssb_set_one(enable);
892 	}
893 }
894 
895 void
896 hw_ssb_recalculate(bool all_cpus)
897 {
898 
899 	switch (hw_ssb_disable) {
900 	default:
901 		hw_ssb_disable = 0;
902 		/* FALLTHROUGH */
903 	case 0: /* off */
904 		hw_ssb_set(false, all_cpus);
905 		break;
906 	case 1: /* on */
907 		hw_ssb_set(true, all_cpus);
908 		break;
909 	case 2: /* auto */
910 		hw_ssb_set((cpu_ia32_arch_caps & IA32_ARCH_CAP_SSB_NO) != 0 ?
911 		    false : true, all_cpus);
912 		break;
913 	}
914 }
915 
916 static int
917 hw_ssb_disable_handler(SYSCTL_HANDLER_ARGS)
918 {
919 	int error, val;
920 
921 	val = hw_ssb_disable;
922 	error = sysctl_handle_int(oidp, &val, 0, req);
923 	if (error != 0 || req->newptr == NULL)
924 		return (error);
925 	hw_ssb_disable = val;
926 	hw_ssb_recalculate(true);
927 	return (0);
928 }
929 SYSCTL_PROC(_hw, OID_AUTO, spec_store_bypass_disable, CTLTYPE_INT |
930     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
931     hw_ssb_disable_handler, "I",
932     "Speculative Store Bypass Disable (0 - off, 1 - on, 2 - auto");
933 
934 int hw_mds_disable;
935 
936 /*
937  * Handler for Microarchitectural Data Sampling issues.  Really not a
938  * pointer to C function: on amd64 the code must not change any CPU
939  * architectural state except possibly %rflags. Also, it is always
940  * called with interrupts disabled.
941  */
942 void mds_handler_void(void);
943 void mds_handler_verw(void);
944 void mds_handler_ivb(void);
945 void mds_handler_bdw(void);
946 void mds_handler_skl_sse(void);
947 void mds_handler_skl_avx(void);
948 void mds_handler_skl_avx512(void);
949 void mds_handler_silvermont(void);
950 void (*mds_handler)(void) = mds_handler_void;
951 
952 static int
953 sysctl_hw_mds_disable_state_handler(SYSCTL_HANDLER_ARGS)
954 {
955 	const char *state;
956 
957 	if (mds_handler == mds_handler_void)
958 		state = "inactive";
959 	else if (mds_handler == mds_handler_verw)
960 		state = "VERW";
961 	else if (mds_handler == mds_handler_ivb)
962 		state = "software IvyBridge";
963 	else if (mds_handler == mds_handler_bdw)
964 		state = "software Broadwell";
965 	else if (mds_handler == mds_handler_skl_sse)
966 		state = "software Skylake SSE";
967 	else if (mds_handler == mds_handler_skl_avx)
968 		state = "software Skylake AVX";
969 	else if (mds_handler == mds_handler_skl_avx512)
970 		state = "software Skylake AVX512";
971 	else if (mds_handler == mds_handler_silvermont)
972 		state = "software Silvermont";
973 	else
974 		state = "unknown";
975 	return (SYSCTL_OUT(req, state, strlen(state)));
976 }
977 
978 SYSCTL_PROC(_hw, OID_AUTO, mds_disable_state,
979     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
980     sysctl_hw_mds_disable_state_handler, "A",
981     "Microarchitectural Data Sampling Mitigation state");
982 
983 _Static_assert(__offsetof(struct pcpu, pc_mds_tmp) % 64 == 0, "MDS AVX512");
984 
985 void
986 hw_mds_recalculate(void)
987 {
988 	struct pcpu *pc;
989 	vm_offset_t b64;
990 	u_long xcr0;
991 	int i;
992 
993 	/*
994 	 * Allow user to force VERW variant even if MD_CLEAR is not
995 	 * reported.  For instance, hypervisor might unknowingly
996 	 * filter the cap out.
997 	 * For the similar reasons, and for testing, allow to enable
998 	 * mitigation even for RDCL_NO or MDS_NO caps.
999 	 */
1000 	if (cpu_vendor_id != CPU_VENDOR_INTEL || hw_mds_disable == 0 ||
1001 	    ((cpu_ia32_arch_caps & (IA32_ARCH_CAP_RDCL_NO |
1002 	    IA32_ARCH_CAP_MDS_NO)) != 0 && hw_mds_disable == 3)) {
1003 		mds_handler = mds_handler_void;
1004 	} else if (((cpu_stdext_feature3 & CPUID_STDEXT3_MD_CLEAR) != 0 &&
1005 	    hw_mds_disable == 3) || hw_mds_disable == 1) {
1006 		mds_handler = mds_handler_verw;
1007 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1008 	    (CPUID_TO_MODEL(cpu_id) == 0x2e || CPUID_TO_MODEL(cpu_id) == 0x1e ||
1009 	    CPUID_TO_MODEL(cpu_id) == 0x1f || CPUID_TO_MODEL(cpu_id) == 0x1a ||
1010 	    CPUID_TO_MODEL(cpu_id) == 0x2f || CPUID_TO_MODEL(cpu_id) == 0x25 ||
1011 	    CPUID_TO_MODEL(cpu_id) == 0x2c || CPUID_TO_MODEL(cpu_id) == 0x2d ||
1012 	    CPUID_TO_MODEL(cpu_id) == 0x2a || CPUID_TO_MODEL(cpu_id) == 0x3e ||
1013 	    CPUID_TO_MODEL(cpu_id) == 0x3a) &&
1014 	    (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1015 		/*
1016 		 * Nehalem, SandyBridge, IvyBridge
1017 		 */
1018 		CPU_FOREACH(i) {
1019 			pc = pcpu_find(i);
1020 			if (pc->pc_mds_buf == NULL) {
1021 				pc->pc_mds_buf = malloc_domainset(672, M_TEMP,
1022 				    DOMAINSET_PREF(pc->pc_domain), M_WAITOK);
1023 				bzero(pc->pc_mds_buf, 16);
1024 			}
1025 		}
1026 		mds_handler = mds_handler_ivb;
1027 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1028 	    (CPUID_TO_MODEL(cpu_id) == 0x3f || CPUID_TO_MODEL(cpu_id) == 0x3c ||
1029 	    CPUID_TO_MODEL(cpu_id) == 0x45 || CPUID_TO_MODEL(cpu_id) == 0x46 ||
1030 	    CPUID_TO_MODEL(cpu_id) == 0x56 || CPUID_TO_MODEL(cpu_id) == 0x4f ||
1031 	    CPUID_TO_MODEL(cpu_id) == 0x47 || CPUID_TO_MODEL(cpu_id) == 0x3d) &&
1032 	    (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1033 		/*
1034 		 * Haswell, Broadwell
1035 		 */
1036 		CPU_FOREACH(i) {
1037 			pc = pcpu_find(i);
1038 			if (pc->pc_mds_buf == NULL) {
1039 				pc->pc_mds_buf = malloc_domainset(1536, M_TEMP,
1040 				    DOMAINSET_PREF(pc->pc_domain), M_WAITOK);
1041 				bzero(pc->pc_mds_buf, 16);
1042 			}
1043 		}
1044 		mds_handler = mds_handler_bdw;
1045 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1046 	    ((CPUID_TO_MODEL(cpu_id) == 0x55 && (cpu_id &
1047 	    CPUID_STEPPING) <= 5) ||
1048 	    CPUID_TO_MODEL(cpu_id) == 0x4e || CPUID_TO_MODEL(cpu_id) == 0x5e ||
1049 	    (CPUID_TO_MODEL(cpu_id) == 0x8e && (cpu_id &
1050 	    CPUID_STEPPING) <= 0xb) ||
1051 	    (CPUID_TO_MODEL(cpu_id) == 0x9e && (cpu_id &
1052 	    CPUID_STEPPING) <= 0xc)) &&
1053 	    (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1054 		/*
1055 		 * Skylake, KabyLake, CoffeeLake, WhiskeyLake,
1056 		 * CascadeLake
1057 		 */
1058 		CPU_FOREACH(i) {
1059 			pc = pcpu_find(i);
1060 			if (pc->pc_mds_buf == NULL) {
1061 				pc->pc_mds_buf = malloc_domainset(6 * 1024,
1062 				    M_TEMP, DOMAINSET_PREF(pc->pc_domain),
1063 				    M_WAITOK);
1064 				b64 = (vm_offset_t)malloc_domainset(64 + 63,
1065 				    M_TEMP, DOMAINSET_PREF(pc->pc_domain),
1066 				    M_WAITOK);
1067 				pc->pc_mds_buf64 = (void *)roundup2(b64, 64);
1068 				bzero(pc->pc_mds_buf64, 64);
1069 			}
1070 		}
1071 		xcr0 = rxcr(0);
1072 		if ((xcr0 & XFEATURE_ENABLED_ZMM_HI256) != 0 &&
1073 		    (cpu_stdext_feature2 & CPUID_STDEXT_AVX512DQ) != 0)
1074 			mds_handler = mds_handler_skl_avx512;
1075 		else if ((xcr0 & XFEATURE_ENABLED_AVX) != 0 &&
1076 		    (cpu_feature2 & CPUID2_AVX) != 0)
1077 			mds_handler = mds_handler_skl_avx;
1078 		else
1079 			mds_handler = mds_handler_skl_sse;
1080 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1081 	    ((CPUID_TO_MODEL(cpu_id) == 0x37 ||
1082 	    CPUID_TO_MODEL(cpu_id) == 0x4a ||
1083 	    CPUID_TO_MODEL(cpu_id) == 0x4c ||
1084 	    CPUID_TO_MODEL(cpu_id) == 0x4d ||
1085 	    CPUID_TO_MODEL(cpu_id) == 0x5a ||
1086 	    CPUID_TO_MODEL(cpu_id) == 0x5d ||
1087 	    CPUID_TO_MODEL(cpu_id) == 0x6e ||
1088 	    CPUID_TO_MODEL(cpu_id) == 0x65 ||
1089 	    CPUID_TO_MODEL(cpu_id) == 0x75 ||
1090 	    CPUID_TO_MODEL(cpu_id) == 0x1c ||
1091 	    CPUID_TO_MODEL(cpu_id) == 0x26 ||
1092 	    CPUID_TO_MODEL(cpu_id) == 0x27 ||
1093 	    CPUID_TO_MODEL(cpu_id) == 0x35 ||
1094 	    CPUID_TO_MODEL(cpu_id) == 0x36 ||
1095 	    CPUID_TO_MODEL(cpu_id) == 0x7a))) {
1096 		/* Silvermont, Airmont */
1097 		CPU_FOREACH(i) {
1098 			pc = pcpu_find(i);
1099 			if (pc->pc_mds_buf == NULL)
1100 				pc->pc_mds_buf = malloc(256, M_TEMP, M_WAITOK);
1101 		}
1102 		mds_handler = mds_handler_silvermont;
1103 	} else {
1104 		hw_mds_disable = 0;
1105 		mds_handler = mds_handler_void;
1106 	}
1107 }
1108 
1109 static void
1110 hw_mds_recalculate_boot(void *arg __unused)
1111 {
1112 
1113 	hw_mds_recalculate();
1114 }
1115 SYSINIT(mds_recalc, SI_SUB_SMP, SI_ORDER_ANY, hw_mds_recalculate_boot, NULL);
1116 
1117 static int
1118 sysctl_mds_disable_handler(SYSCTL_HANDLER_ARGS)
1119 {
1120 	int error, val;
1121 
1122 	val = hw_mds_disable;
1123 	error = sysctl_handle_int(oidp, &val, 0, req);
1124 	if (error != 0 || req->newptr == NULL)
1125 		return (error);
1126 	if (val < 0 || val > 3)
1127 		return (EINVAL);
1128 	hw_mds_disable = val;
1129 	hw_mds_recalculate();
1130 	return (0);
1131 }
1132 
1133 SYSCTL_PROC(_hw, OID_AUTO, mds_disable, CTLTYPE_INT |
1134     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1135     sysctl_mds_disable_handler, "I",
1136     "Microarchitectural Data Sampling Mitigation "
1137     "(0 - off, 1 - on VERW, 2 - on SW, 3 - on AUTO");
1138 
1139 /*
1140  * Enable and restore kernel text write permissions.
1141  * Callers must ensure that disable_wp()/restore_wp() are executed
1142  * without rescheduling on the same core.
1143  */
1144 bool
1145 disable_wp(void)
1146 {
1147 	u_int cr0;
1148 
1149 	cr0 = rcr0();
1150 	if ((cr0 & CR0_WP) == 0)
1151 		return (false);
1152 	load_cr0(cr0 & ~CR0_WP);
1153 	return (true);
1154 }
1155 
1156 void
1157 restore_wp(bool old_wp)
1158 {
1159 
1160 	if (old_wp)
1161 		load_cr0(rcr0() | CR0_WP);
1162 }
1163 
1164 bool
1165 acpi_get_fadt_bootflags(uint16_t *flagsp)
1166 {
1167 #ifdef DEV_ACPI
1168 	ACPI_TABLE_FADT *fadt;
1169 	vm_paddr_t physaddr;
1170 
1171 	physaddr = acpi_find_table(ACPI_SIG_FADT);
1172 	if (physaddr == 0)
1173 		return (false);
1174 	fadt = acpi_map_table(physaddr, ACPI_SIG_FADT);
1175 	if (fadt == NULL)
1176 		return (false);
1177 	*flagsp = fadt->BootFlags;
1178 	acpi_unmap_table(fadt);
1179 	return (true);
1180 #else
1181 	return (false);
1182 #endif
1183 }
1184