xref: /freebsd/sys/x86/x86/cpu_machdep.c (revision 6be3386466ab79a84b48429ae66244f21526d3df)
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 char bootmethod[16];
115 SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
116     "System firmware boot method");
117 
118 struct msr_op_arg {
119 	u_int msr;
120 	int op;
121 	uint64_t arg1;
122 };
123 
124 static void
125 x86_msr_op_one(void *argp)
126 {
127 	struct msr_op_arg *a;
128 	uint64_t v;
129 
130 	a = argp;
131 	switch (a->op) {
132 	case MSR_OP_ANDNOT:
133 		v = rdmsr(a->msr);
134 		v &= ~a->arg1;
135 		wrmsr(a->msr, v);
136 		break;
137 	case MSR_OP_OR:
138 		v = rdmsr(a->msr);
139 		v |= a->arg1;
140 		wrmsr(a->msr, v);
141 		break;
142 	case MSR_OP_WRITE:
143 		wrmsr(a->msr, a->arg1);
144 		break;
145 	}
146 }
147 
148 #define	MSR_OP_EXMODE_MASK	0xf0000000
149 #define	MSR_OP_OP_MASK		0x000000ff
150 
151 void
152 x86_msr_op(u_int msr, u_int op, uint64_t arg1)
153 {
154 	struct thread *td;
155 	struct msr_op_arg a;
156 	u_int exmode;
157 	int bound_cpu, i, is_bound;
158 
159 	a.op = op & MSR_OP_OP_MASK;
160 	MPASS(a.op == MSR_OP_ANDNOT || a.op == MSR_OP_OR ||
161 	    a.op == MSR_OP_WRITE);
162 	exmode = op & MSR_OP_EXMODE_MASK;
163 	MPASS(exmode == MSR_OP_LOCAL || exmode == MSR_OP_SCHED ||
164 	    exmode == MSR_OP_RENDEZVOUS);
165 	a.msr = msr;
166 	a.arg1 = arg1;
167 	switch (exmode) {
168 	case MSR_OP_LOCAL:
169 		x86_msr_op_one(&a);
170 		break;
171 	case MSR_OP_SCHED:
172 		td = curthread;
173 		thread_lock(td);
174 		is_bound = sched_is_bound(td);
175 		bound_cpu = td->td_oncpu;
176 		CPU_FOREACH(i) {
177 			sched_bind(td, i);
178 			x86_msr_op_one(&a);
179 		}
180 		if (is_bound)
181 			sched_bind(td, bound_cpu);
182 		else
183 			sched_unbind(td);
184 		thread_unlock(td);
185 		break;
186 	case MSR_OP_RENDEZVOUS:
187 		smp_rendezvous(NULL, x86_msr_op_one, NULL, &a);
188 		break;
189 	}
190 }
191 
192 /*
193  * Automatically initialized per CPU errata in cpu_idle_tun below.
194  */
195 bool mwait_cpustop_broken = false;
196 SYSCTL_BOOL(_machdep, OID_AUTO, mwait_cpustop_broken, CTLFLAG_RDTUN,
197     &mwait_cpustop_broken, 0,
198     "Can not reliably wake MONITOR/MWAIT cpus without interrupts");
199 
200 /*
201  * Flush the D-cache for non-DMA I/O so that the I-cache can
202  * be made coherent later.
203  */
204 void
205 cpu_flush_dcache(void *ptr, size_t len)
206 {
207 	/* Not applicable */
208 }
209 
210 void
211 acpi_cpu_c1(void)
212 {
213 
214 	__asm __volatile("sti; hlt");
215 }
216 
217 /*
218  * Use mwait to pause execution while waiting for an interrupt or
219  * another thread to signal that there is more work.
220  *
221  * NOTE: Interrupts will cause a wakeup; however, this function does
222  * not enable interrupt handling. The caller is responsible to enable
223  * interrupts.
224  */
225 void
226 acpi_cpu_idle_mwait(uint32_t mwait_hint)
227 {
228 	int *state;
229 	uint64_t v;
230 
231 	/*
232 	 * A comment in Linux patch claims that 'CPUs run faster with
233 	 * speculation protection disabled. All CPU threads in a core
234 	 * must disable speculation protection for it to be
235 	 * disabled. Disable it while we are idle so the other
236 	 * hyperthread can run fast.'
237 	 *
238 	 * XXXKIB.  Software coordination mode should be supported,
239 	 * but all Intel CPUs provide hardware coordination.
240 	 */
241 
242 	state = &PCPU_PTR(monitorbuf)->idle_state;
243 	KASSERT(atomic_load_int(state) == STATE_SLEEPING,
244 	    ("cpu_mwait_cx: wrong monitorbuf state"));
245 	atomic_store_int(state, STATE_MWAIT);
246 	if (PCPU_GET(ibpb_set) || hw_ssb_active) {
247 		v = rdmsr(MSR_IA32_SPEC_CTRL);
248 		wrmsr(MSR_IA32_SPEC_CTRL, v & ~(IA32_SPEC_CTRL_IBRS |
249 		    IA32_SPEC_CTRL_STIBP | IA32_SPEC_CTRL_SSBD));
250 	} else {
251 		v = 0;
252 	}
253 	cpu_monitor(state, 0, 0);
254 	if (atomic_load_int(state) == STATE_MWAIT)
255 		cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
256 
257 	/*
258 	 * SSB cannot be disabled while we sleep, or rather, if it was
259 	 * disabled, the sysctl thread will bind to our cpu to tweak
260 	 * MSR.
261 	 */
262 	if (v != 0)
263 		wrmsr(MSR_IA32_SPEC_CTRL, v);
264 
265 	/*
266 	 * We should exit on any event that interrupts mwait, because
267 	 * that event might be a wanted interrupt.
268 	 */
269 	atomic_store_int(state, STATE_RUNNING);
270 }
271 
272 /* Get current clock frequency for the given cpu id. */
273 int
274 cpu_est_clockrate(int cpu_id, uint64_t *rate)
275 {
276 	uint64_t tsc1, tsc2;
277 	uint64_t acnt, mcnt, perf;
278 	register_t reg;
279 
280 	if (pcpu_find(cpu_id) == NULL || rate == NULL)
281 		return (EINVAL);
282 #ifdef __i386__
283 	if ((cpu_feature & CPUID_TSC) == 0)
284 		return (EOPNOTSUPP);
285 #endif
286 
287 	/*
288 	 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
289 	 * DELAY(9) based logic fails.
290 	 */
291 	if (tsc_is_invariant && !tsc_perf_stat)
292 		return (EOPNOTSUPP);
293 
294 #ifdef SMP
295 	if (smp_cpus > 1) {
296 		/* Schedule ourselves on the indicated cpu. */
297 		thread_lock(curthread);
298 		sched_bind(curthread, cpu_id);
299 		thread_unlock(curthread);
300 	}
301 #endif
302 
303 	/* Calibrate by measuring a short delay. */
304 	reg = intr_disable();
305 	if (tsc_is_invariant) {
306 		wrmsr(MSR_MPERF, 0);
307 		wrmsr(MSR_APERF, 0);
308 		tsc1 = rdtsc();
309 		DELAY(1000);
310 		mcnt = rdmsr(MSR_MPERF);
311 		acnt = rdmsr(MSR_APERF);
312 		tsc2 = rdtsc();
313 		intr_restore(reg);
314 		perf = 1000 * acnt / mcnt;
315 		*rate = (tsc2 - tsc1) * perf;
316 	} else {
317 		tsc1 = rdtsc();
318 		DELAY(1000);
319 		tsc2 = rdtsc();
320 		intr_restore(reg);
321 		*rate = (tsc2 - tsc1) * 1000;
322 	}
323 
324 #ifdef SMP
325 	if (smp_cpus > 1) {
326 		thread_lock(curthread);
327 		sched_unbind(curthread);
328 		thread_unlock(curthread);
329 	}
330 #endif
331 
332 	return (0);
333 }
334 
335 /*
336  * Shutdown the CPU as much as possible
337  */
338 void
339 cpu_halt(void)
340 {
341 	for (;;)
342 		halt();
343 }
344 
345 static void
346 cpu_reset_real(void)
347 {
348 	struct region_descriptor null_idt;
349 	int b;
350 
351 	disable_intr();
352 #ifdef CPU_ELAN
353 	if (elan_mmcr != NULL)
354 		elan_mmcr->RESCFG = 1;
355 #endif
356 #ifdef __i386__
357 	if (cpu == CPU_GEODE1100) {
358 		/* Attempt Geode's own reset */
359 		outl(0xcf8, 0x80009044ul);
360 		outl(0xcfc, 0xf);
361 	}
362 #endif
363 #if !defined(BROKEN_KEYBOARD_RESET)
364 	/*
365 	 * Attempt to do a CPU reset via the keyboard controller,
366 	 * do not turn off GateA20, as any machine that fails
367 	 * to do the reset here would then end up in no man's land.
368 	 */
369 	outb(IO_KBD + 4, 0xFE);
370 	DELAY(500000);	/* wait 0.5 sec to see if that did it */
371 #endif
372 
373 	/*
374 	 * Attempt to force a reset via the Reset Control register at
375 	 * I/O port 0xcf9.  Bit 2 forces a system reset when it
376 	 * transitions from 0 to 1.  Bit 1 selects the type of reset
377 	 * to attempt: 0 selects a "soft" reset, and 1 selects a
378 	 * "hard" reset.  We try a "hard" reset.  The first write sets
379 	 * bit 1 to select a "hard" reset and clears bit 2.  The
380 	 * second write forces a 0 -> 1 transition in bit 2 to trigger
381 	 * a reset.
382 	 */
383 	outb(0xcf9, 0x2);
384 	outb(0xcf9, 0x6);
385 	DELAY(500000);  /* wait 0.5 sec to see if that did it */
386 
387 	/*
388 	 * Attempt to force a reset via the Fast A20 and Init register
389 	 * at I/O port 0x92.  Bit 1 serves as an alternate A20 gate.
390 	 * Bit 0 asserts INIT# when set to 1.  We are careful to only
391 	 * preserve bit 1 while setting bit 0.  We also must clear bit
392 	 * 0 before setting it if it isn't already clear.
393 	 */
394 	b = inb(0x92);
395 	if (b != 0xff) {
396 		if ((b & 0x1) != 0)
397 			outb(0x92, b & 0xfe);
398 		outb(0x92, b | 0x1);
399 		DELAY(500000);  /* wait 0.5 sec to see if that did it */
400 	}
401 
402 	printf("No known reset method worked, attempting CPU shutdown\n");
403 	DELAY(1000000); /* wait 1 sec for printf to complete */
404 
405 	/* Wipe the IDT. */
406 	null_idt.rd_limit = 0;
407 	null_idt.rd_base = 0;
408 	lidt(&null_idt);
409 
410 	/* "good night, sweet prince .... <THUNK!>" */
411 	breakpoint();
412 
413 	/* NOTREACHED */
414 	while(1);
415 }
416 
417 #ifdef SMP
418 static void
419 cpu_reset_proxy(void)
420 {
421 
422 	cpu_reset_proxy_active = 1;
423 	while (cpu_reset_proxy_active == 1)
424 		ia32_pause(); /* Wait for other cpu to see that we've started */
425 
426 	printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
427 	DELAY(1000000);
428 	cpu_reset_real();
429 }
430 #endif
431 
432 void
433 cpu_reset(void)
434 {
435 #ifdef SMP
436 	struct monitorbuf *mb;
437 	cpuset_t map;
438 	u_int cnt;
439 
440 	if (smp_started) {
441 		map = all_cpus;
442 		CPU_CLR(PCPU_GET(cpuid), &map);
443 		CPU_ANDNOT(&map, &stopped_cpus);
444 		if (!CPU_EMPTY(&map)) {
445 			printf("cpu_reset: Stopping other CPUs\n");
446 			stop_cpus(map);
447 		}
448 
449 		if (PCPU_GET(cpuid) != 0) {
450 			cpu_reset_proxyid = PCPU_GET(cpuid);
451 			cpustop_restartfunc = cpu_reset_proxy;
452 			cpu_reset_proxy_active = 0;
453 			printf("cpu_reset: Restarting BSP\n");
454 
455 			/* Restart CPU #0. */
456 			CPU_SETOF(0, &started_cpus);
457 			mb = &pcpu_find(0)->pc_monitorbuf;
458 			atomic_store_int(&mb->stop_state,
459 			    MONITOR_STOPSTATE_RUNNING);
460 
461 			cnt = 0;
462 			while (cpu_reset_proxy_active == 0 && cnt < 10000000) {
463 				ia32_pause();
464 				cnt++;	/* Wait for BSP to announce restart */
465 			}
466 			if (cpu_reset_proxy_active == 0) {
467 				printf("cpu_reset: Failed to restart BSP\n");
468 			} else {
469 				cpu_reset_proxy_active = 2;
470 				while (1)
471 					ia32_pause();
472 				/* NOTREACHED */
473 			}
474 		}
475 
476 		DELAY(1000000);
477 	}
478 #endif
479 	cpu_reset_real();
480 	/* NOTREACHED */
481 }
482 
483 bool
484 cpu_mwait_usable(void)
485 {
486 
487 	return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
488 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
489 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
490 }
491 
492 void (*cpu_idle_hook)(sbintime_t) = NULL;	/* ACPI idle hook. */
493 
494 int cpu_amdc1e_bug = 0;			/* AMD C1E APIC workaround required. */
495 
496 static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
497 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
498     0, "Use MONITOR/MWAIT for short idle");
499 
500 static void
501 cpu_idle_acpi(sbintime_t sbt)
502 {
503 	int *state;
504 
505 	state = &PCPU_PTR(monitorbuf)->idle_state;
506 	atomic_store_int(state, STATE_SLEEPING);
507 
508 	/* See comments in cpu_idle_hlt(). */
509 	disable_intr();
510 	if (sched_runnable())
511 		enable_intr();
512 	else if (cpu_idle_hook)
513 		cpu_idle_hook(sbt);
514 	else
515 		acpi_cpu_c1();
516 	atomic_store_int(state, STATE_RUNNING);
517 }
518 
519 static void
520 cpu_idle_hlt(sbintime_t sbt)
521 {
522 	int *state;
523 
524 	state = &PCPU_PTR(monitorbuf)->idle_state;
525 	atomic_store_int(state, STATE_SLEEPING);
526 
527 	/*
528 	 * Since we may be in a critical section from cpu_idle(), if
529 	 * an interrupt fires during that critical section we may have
530 	 * a pending preemption.  If the CPU halts, then that thread
531 	 * may not execute until a later interrupt awakens the CPU.
532 	 * To handle this race, check for a runnable thread after
533 	 * disabling interrupts and immediately return if one is
534 	 * found.  Also, we must absolutely guarentee that hlt is
535 	 * the next instruction after sti.  This ensures that any
536 	 * interrupt that fires after the call to disable_intr() will
537 	 * immediately awaken the CPU from hlt.  Finally, please note
538 	 * that on x86 this works fine because of interrupts enabled only
539 	 * after the instruction following sti takes place, while IF is set
540 	 * to 1 immediately, allowing hlt instruction to acknowledge the
541 	 * interrupt.
542 	 */
543 	disable_intr();
544 	if (sched_runnable())
545 		enable_intr();
546 	else
547 		acpi_cpu_c1();
548 	atomic_store_int(state, STATE_RUNNING);
549 }
550 
551 static void
552 cpu_idle_mwait(sbintime_t sbt)
553 {
554 	int *state;
555 
556 	state = &PCPU_PTR(monitorbuf)->idle_state;
557 	atomic_store_int(state, STATE_MWAIT);
558 
559 	/* See comments in cpu_idle_hlt(). */
560 	disable_intr();
561 	if (sched_runnable()) {
562 		atomic_store_int(state, STATE_RUNNING);
563 		enable_intr();
564 		return;
565 	}
566 
567 	cpu_monitor(state, 0, 0);
568 	if (atomic_load_int(state) == STATE_MWAIT)
569 		__asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
570 	else
571 		enable_intr();
572 	atomic_store_int(state, STATE_RUNNING);
573 }
574 
575 static void
576 cpu_idle_spin(sbintime_t sbt)
577 {
578 	int *state;
579 	int i;
580 
581 	state = &PCPU_PTR(monitorbuf)->idle_state;
582 	atomic_store_int(state, STATE_RUNNING);
583 
584 	/*
585 	 * The sched_runnable() call is racy but as long as there is
586 	 * a loop missing it one time will have just a little impact if any
587 	 * (and it is much better than missing the check at all).
588 	 */
589 	for (i = 0; i < 1000; i++) {
590 		if (sched_runnable())
591 			return;
592 		cpu_spinwait();
593 	}
594 }
595 
596 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
597 
598 void
599 cpu_idle(int busy)
600 {
601 	uint64_t msr;
602 	sbintime_t sbt = -1;
603 
604 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
605 	    busy, curcpu);
606 #ifdef MP_WATCHDOG
607 	ap_watchdog(PCPU_GET(cpuid));
608 #endif
609 
610 	/* If we are busy - try to use fast methods. */
611 	if (busy) {
612 		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
613 			cpu_idle_mwait(busy);
614 			goto out;
615 		}
616 	}
617 
618 	/* If we have time - switch timers into idle mode. */
619 	if (!busy) {
620 		critical_enter();
621 		sbt = cpu_idleclock();
622 	}
623 
624 	/* Apply AMD APIC timer C1E workaround. */
625 	if (cpu_amdc1e_bug && cpu_disable_c3_sleep) {
626 		msr = rdmsr(MSR_AMDK8_IPM);
627 		if ((msr & (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)) != 0)
628 			wrmsr(MSR_AMDK8_IPM, msr & ~(AMDK8_SMIONCMPHALT |
629 			    AMDK8_C1EONCMPHALT));
630 	}
631 
632 	/* Call main idle method. */
633 	cpu_idle_fn(sbt);
634 
635 	/* Switch timers back into active mode. */
636 	if (!busy) {
637 		cpu_activeclock();
638 		critical_exit();
639 	}
640 out:
641 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
642 	    busy, curcpu);
643 }
644 
645 static int cpu_idle_apl31_workaround;
646 SYSCTL_INT(_machdep, OID_AUTO, idle_apl31, CTLFLAG_RW,
647     &cpu_idle_apl31_workaround, 0,
648     "Apollo Lake APL31 MWAIT bug workaround");
649 
650 int
651 cpu_idle_wakeup(int cpu)
652 {
653 	struct monitorbuf *mb;
654 	int *state;
655 
656 	mb = &pcpu_find(cpu)->pc_monitorbuf;
657 	state = &mb->idle_state;
658 	switch (atomic_load_int(state)) {
659 	case STATE_SLEEPING:
660 		return (0);
661 	case STATE_MWAIT:
662 		atomic_store_int(state, STATE_RUNNING);
663 		return (cpu_idle_apl31_workaround ? 0 : 1);
664 	case STATE_RUNNING:
665 		return (1);
666 	default:
667 		panic("bad monitor state");
668 		return (1);
669 	}
670 }
671 
672 /*
673  * Ordered by speed/power consumption.
674  */
675 static struct {
676 	void	*id_fn;
677 	char	*id_name;
678 	int	id_cpuid2_flag;
679 } idle_tbl[] = {
680 	{ .id_fn = cpu_idle_spin, .id_name = "spin" },
681 	{ .id_fn = cpu_idle_mwait, .id_name = "mwait",
682 	    .id_cpuid2_flag = CPUID2_MON },
683 	{ .id_fn = cpu_idle_hlt, .id_name = "hlt" },
684 	{ .id_fn = cpu_idle_acpi, .id_name = "acpi" },
685 };
686 
687 static int
688 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
689 {
690 	char *avail, *p;
691 	int error;
692 	int i;
693 
694 	avail = malloc(256, M_TEMP, M_WAITOK);
695 	p = avail;
696 	for (i = 0; i < nitems(idle_tbl); i++) {
697 		if (idle_tbl[i].id_cpuid2_flag != 0 &&
698 		    (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
699 			continue;
700 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
701 		    cpu_idle_hook == NULL)
702 			continue;
703 		p += sprintf(p, "%s%s", p != avail ? ", " : "",
704 		    idle_tbl[i].id_name);
705 	}
706 	error = sysctl_handle_string(oidp, avail, 0, req);
707 	free(avail, M_TEMP);
708 	return (error);
709 }
710 
711 SYSCTL_PROC(_machdep, OID_AUTO, idle_available,
712     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
713     0, 0, idle_sysctl_available, "A",
714     "list of available idle functions");
715 
716 static bool
717 cpu_idle_selector(const char *new_idle_name)
718 {
719 	int i;
720 
721 	for (i = 0; i < nitems(idle_tbl); i++) {
722 		if (idle_tbl[i].id_cpuid2_flag != 0 &&
723 		    (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
724 			continue;
725 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
726 		    cpu_idle_hook == NULL)
727 			continue;
728 		if (strcmp(idle_tbl[i].id_name, new_idle_name))
729 			continue;
730 		cpu_idle_fn = idle_tbl[i].id_fn;
731 		if (bootverbose)
732 			printf("CPU idle set to %s\n", idle_tbl[i].id_name);
733 		return (true);
734 	}
735 	return (false);
736 }
737 
738 static int
739 cpu_idle_sysctl(SYSCTL_HANDLER_ARGS)
740 {
741 	char buf[16], *p;
742 	int error, i;
743 
744 	p = "unknown";
745 	for (i = 0; i < nitems(idle_tbl); i++) {
746 		if (idle_tbl[i].id_fn == cpu_idle_fn) {
747 			p = idle_tbl[i].id_name;
748 			break;
749 		}
750 	}
751 	strncpy(buf, p, sizeof(buf));
752 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
753 	if (error != 0 || req->newptr == NULL)
754 		return (error);
755 	return (cpu_idle_selector(buf) ? 0 : EINVAL);
756 }
757 
758 SYSCTL_PROC(_machdep, OID_AUTO, idle,
759     CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
760     0, 0, cpu_idle_sysctl, "A",
761     "currently selected idle function");
762 
763 static void
764 cpu_idle_tun(void *unused __unused)
765 {
766 	char tunvar[16];
767 
768 	if (TUNABLE_STR_FETCH("machdep.idle", tunvar, sizeof(tunvar)))
769 		cpu_idle_selector(tunvar);
770 	else if (cpu_vendor_id == CPU_VENDOR_AMD &&
771 	    CPUID_TO_FAMILY(cpu_id) == 0x17 && CPUID_TO_MODEL(cpu_id) == 0x1) {
772 		/* Ryzen erratas 1057, 1109. */
773 		cpu_idle_selector("hlt");
774 		idle_mwait = 0;
775 		mwait_cpustop_broken = true;
776 	}
777 
778 	if (cpu_vendor_id == CPU_VENDOR_INTEL && cpu_id == 0x506c9) {
779 		/*
780 		 * Apollo Lake errata APL31 (public errata APL30).
781 		 * Stores to the armed address range may not trigger
782 		 * MWAIT to resume execution.  OS needs to use
783 		 * interrupts to wake processors from MWAIT-induced
784 		 * sleep states.
785 		 */
786 		cpu_idle_apl31_workaround = 1;
787 		mwait_cpustop_broken = true;
788 	}
789 	TUNABLE_INT_FETCH("machdep.idle_apl31", &cpu_idle_apl31_workaround);
790 }
791 SYSINIT(cpu_idle_tun, SI_SUB_CPU, SI_ORDER_MIDDLE, cpu_idle_tun, NULL);
792 
793 static int panic_on_nmi = 0xff;
794 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
795     &panic_on_nmi, 0,
796     "Panic on NMI: 1 = H/W failure; 2 = unknown; 0xff = all");
797 int nmi_is_broadcast = 1;
798 SYSCTL_INT(_machdep, OID_AUTO, nmi_is_broadcast, CTLFLAG_RWTUN,
799     &nmi_is_broadcast, 0,
800     "Chipset NMI is broadcast");
801 int (*apei_nmi)(void);
802 
803 void
804 nmi_call_kdb(u_int cpu, u_int type, struct trapframe *frame)
805 {
806 	bool claimed = false;
807 
808 #ifdef DEV_ISA
809 	/* machine/parity/power fail/"kitchen sink" faults */
810 	if (isa_nmi(frame->tf_err)) {
811 		claimed = true;
812 		if ((panic_on_nmi & 1) != 0)
813 			panic("NMI indicates hardware failure");
814 	}
815 #endif /* DEV_ISA */
816 
817 	/* ACPI Platform Error Interfaces callback. */
818 	if (apei_nmi != NULL && (*apei_nmi)())
819 		claimed = true;
820 
821 	/*
822 	 * NMIs can be useful for debugging.  They can be hooked up to a
823 	 * pushbutton, usually on an ISA, PCI, or PCIe card.  They can also be
824 	 * generated by an IPMI BMC, either manually or in response to a
825 	 * watchdog timeout.  For example, see the "power diag" command in
826 	 * ports/sysutils/ipmitool.  They can also be generated by a
827 	 * hypervisor; see "bhyvectl --inject-nmi".
828 	 */
829 
830 #ifdef KDB
831 	if (!claimed && (panic_on_nmi & 2) != 0) {
832 		if (debugger_on_panic) {
833 			printf("NMI/cpu%d ... going to debugger\n", cpu);
834 			claimed = kdb_trap(type, 0, frame);
835 		}
836 	}
837 #endif /* KDB */
838 
839 	if (!claimed && panic_on_nmi != 0)
840 		panic("NMI");
841 }
842 
843 void
844 nmi_handle_intr(u_int type, struct trapframe *frame)
845 {
846 
847 #ifdef SMP
848 	if (nmi_is_broadcast) {
849 		nmi_call_kdb_smp(type, frame);
850 		return;
851 	}
852 #endif
853 	nmi_call_kdb(PCPU_GET(cpuid), type, frame);
854 }
855 
856 static int hw_ibrs_active;
857 int hw_ibrs_ibpb_active;
858 int hw_ibrs_disable = 1;
859 
860 SYSCTL_INT(_hw, OID_AUTO, ibrs_active, CTLFLAG_RD, &hw_ibrs_active, 0,
861     "Indirect Branch Restricted Speculation active");
862 
863 SYSCTL_NODE(_machdep_mitigations, OID_AUTO, ibrs,
864     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
865     "Indirect Branch Restricted Speculation active");
866 
867 SYSCTL_INT(_machdep_mitigations_ibrs, OID_AUTO, active, CTLFLAG_RD,
868     &hw_ibrs_active, 0, "Indirect Branch Restricted Speculation active");
869 
870 void
871 hw_ibrs_recalculate(bool for_all_cpus)
872 {
873 	if ((cpu_ia32_arch_caps & IA32_ARCH_CAP_IBRS_ALL) != 0) {
874 		x86_msr_op(MSR_IA32_SPEC_CTRL, (for_all_cpus ?
875 		    MSR_OP_RENDEZVOUS : MSR_OP_LOCAL) |
876 		    (hw_ibrs_disable != 0 ? MSR_OP_ANDNOT : MSR_OP_OR),
877 		    IA32_SPEC_CTRL_IBRS);
878 		hw_ibrs_active = hw_ibrs_disable == 0;
879 		hw_ibrs_ibpb_active = 0;
880 	} else {
881 		hw_ibrs_active = hw_ibrs_ibpb_active = (cpu_stdext_feature3 &
882 		    CPUID_STDEXT3_IBPB) != 0 && !hw_ibrs_disable;
883 	}
884 }
885 
886 static int
887 hw_ibrs_disable_handler(SYSCTL_HANDLER_ARGS)
888 {
889 	int error, val;
890 
891 	val = hw_ibrs_disable;
892 	error = sysctl_handle_int(oidp, &val, 0, req);
893 	if (error != 0 || req->newptr == NULL)
894 		return (error);
895 	hw_ibrs_disable = val != 0;
896 	hw_ibrs_recalculate(true);
897 	return (0);
898 }
899 SYSCTL_PROC(_hw, OID_AUTO, ibrs_disable, CTLTYPE_INT | CTLFLAG_RWTUN |
900     CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0, hw_ibrs_disable_handler, "I",
901     "Disable Indirect Branch Restricted Speculation");
902 
903 SYSCTL_PROC(_machdep_mitigations_ibrs, OID_AUTO, disable, CTLTYPE_INT |
904     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
905     hw_ibrs_disable_handler, "I",
906     "Disable Indirect Branch Restricted Speculation");
907 
908 int hw_ssb_active;
909 int hw_ssb_disable;
910 
911 SYSCTL_INT(_hw, OID_AUTO, spec_store_bypass_disable_active, CTLFLAG_RD,
912     &hw_ssb_active, 0,
913     "Speculative Store Bypass Disable active");
914 
915 SYSCTL_NODE(_machdep_mitigations, OID_AUTO, ssb,
916     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
917     "Speculative Store Bypass Disable active");
918 
919 SYSCTL_INT(_machdep_mitigations_ssb, OID_AUTO, active, CTLFLAG_RD,
920     &hw_ssb_active, 0, "Speculative Store Bypass Disable active");
921 
922 static void
923 hw_ssb_set(bool enable, bool for_all_cpus)
924 {
925 
926 	if ((cpu_stdext_feature3 & CPUID_STDEXT3_SSBD) == 0) {
927 		hw_ssb_active = 0;
928 		return;
929 	}
930 	hw_ssb_active = enable;
931 	x86_msr_op(MSR_IA32_SPEC_CTRL,
932 	    (enable ? MSR_OP_OR : MSR_OP_ANDNOT) |
933 	    (for_all_cpus ? MSR_OP_SCHED : MSR_OP_LOCAL), IA32_SPEC_CTRL_SSBD);
934 }
935 
936 void
937 hw_ssb_recalculate(bool all_cpus)
938 {
939 
940 	switch (hw_ssb_disable) {
941 	default:
942 		hw_ssb_disable = 0;
943 		/* FALLTHROUGH */
944 	case 0: /* off */
945 		hw_ssb_set(false, all_cpus);
946 		break;
947 	case 1: /* on */
948 		hw_ssb_set(true, all_cpus);
949 		break;
950 	case 2: /* auto */
951 		hw_ssb_set((cpu_ia32_arch_caps & IA32_ARCH_CAP_SSB_NO) != 0 ?
952 		    false : true, all_cpus);
953 		break;
954 	}
955 }
956 
957 static int
958 hw_ssb_disable_handler(SYSCTL_HANDLER_ARGS)
959 {
960 	int error, val;
961 
962 	val = hw_ssb_disable;
963 	error = sysctl_handle_int(oidp, &val, 0, req);
964 	if (error != 0 || req->newptr == NULL)
965 		return (error);
966 	hw_ssb_disable = val;
967 	hw_ssb_recalculate(true);
968 	return (0);
969 }
970 SYSCTL_PROC(_hw, OID_AUTO, spec_store_bypass_disable, CTLTYPE_INT |
971     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
972     hw_ssb_disable_handler, "I",
973     "Speculative Store Bypass Disable (0 - off, 1 - on, 2 - auto");
974 
975 SYSCTL_PROC(_machdep_mitigations_ssb, OID_AUTO, disable, CTLTYPE_INT |
976     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
977     hw_ssb_disable_handler, "I",
978     "Speculative Store Bypass Disable (0 - off, 1 - on, 2 - auto");
979 
980 int hw_mds_disable;
981 
982 /*
983  * Handler for Microarchitectural Data Sampling issues.  Really not a
984  * pointer to C function: on amd64 the code must not change any CPU
985  * architectural state except possibly %rflags. Also, it is always
986  * called with interrupts disabled.
987  */
988 void mds_handler_void(void);
989 void mds_handler_verw(void);
990 void mds_handler_ivb(void);
991 void mds_handler_bdw(void);
992 void mds_handler_skl_sse(void);
993 void mds_handler_skl_avx(void);
994 void mds_handler_skl_avx512(void);
995 void mds_handler_silvermont(void);
996 void (*mds_handler)(void) = mds_handler_void;
997 
998 static int
999 sysctl_hw_mds_disable_state_handler(SYSCTL_HANDLER_ARGS)
1000 {
1001 	const char *state;
1002 
1003 	if (mds_handler == mds_handler_void)
1004 		state = "inactive";
1005 	else if (mds_handler == mds_handler_verw)
1006 		state = "VERW";
1007 	else if (mds_handler == mds_handler_ivb)
1008 		state = "software IvyBridge";
1009 	else if (mds_handler == mds_handler_bdw)
1010 		state = "software Broadwell";
1011 	else if (mds_handler == mds_handler_skl_sse)
1012 		state = "software Skylake SSE";
1013 	else if (mds_handler == mds_handler_skl_avx)
1014 		state = "software Skylake AVX";
1015 	else if (mds_handler == mds_handler_skl_avx512)
1016 		state = "software Skylake AVX512";
1017 	else if (mds_handler == mds_handler_silvermont)
1018 		state = "software Silvermont";
1019 	else
1020 		state = "unknown";
1021 	return (SYSCTL_OUT(req, state, strlen(state)));
1022 }
1023 
1024 SYSCTL_PROC(_hw, OID_AUTO, mds_disable_state,
1025     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1026     sysctl_hw_mds_disable_state_handler, "A",
1027     "Microarchitectural Data Sampling Mitigation state");
1028 
1029 SYSCTL_NODE(_machdep_mitigations, OID_AUTO, mds,
1030     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1031     "Microarchitectural Data Sampling Mitigation state");
1032 
1033 SYSCTL_PROC(_machdep_mitigations_mds, OID_AUTO, state,
1034     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1035     sysctl_hw_mds_disable_state_handler, "A",
1036     "Microarchitectural Data Sampling Mitigation state");
1037 
1038 _Static_assert(__offsetof(struct pcpu, pc_mds_tmp) % 64 == 0, "MDS AVX512");
1039 
1040 void
1041 hw_mds_recalculate(void)
1042 {
1043 	struct pcpu *pc;
1044 	vm_offset_t b64;
1045 	u_long xcr0;
1046 	int i;
1047 
1048 	/*
1049 	 * Allow user to force VERW variant even if MD_CLEAR is not
1050 	 * reported.  For instance, hypervisor might unknowingly
1051 	 * filter the cap out.
1052 	 * For the similar reasons, and for testing, allow to enable
1053 	 * mitigation even when MDS_NO cap is set.
1054 	 */
1055 	if (cpu_vendor_id != CPU_VENDOR_INTEL || hw_mds_disable == 0 ||
1056 	    ((cpu_ia32_arch_caps & IA32_ARCH_CAP_MDS_NO) != 0 &&
1057 	    hw_mds_disable == 3)) {
1058 		mds_handler = mds_handler_void;
1059 	} else if (((cpu_stdext_feature3 & CPUID_STDEXT3_MD_CLEAR) != 0 &&
1060 	    hw_mds_disable == 3) || hw_mds_disable == 1) {
1061 		mds_handler = mds_handler_verw;
1062 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1063 	    (CPUID_TO_MODEL(cpu_id) == 0x2e || CPUID_TO_MODEL(cpu_id) == 0x1e ||
1064 	    CPUID_TO_MODEL(cpu_id) == 0x1f || CPUID_TO_MODEL(cpu_id) == 0x1a ||
1065 	    CPUID_TO_MODEL(cpu_id) == 0x2f || CPUID_TO_MODEL(cpu_id) == 0x25 ||
1066 	    CPUID_TO_MODEL(cpu_id) == 0x2c || CPUID_TO_MODEL(cpu_id) == 0x2d ||
1067 	    CPUID_TO_MODEL(cpu_id) == 0x2a || CPUID_TO_MODEL(cpu_id) == 0x3e ||
1068 	    CPUID_TO_MODEL(cpu_id) == 0x3a) &&
1069 	    (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1070 		/*
1071 		 * Nehalem, SandyBridge, IvyBridge
1072 		 */
1073 		CPU_FOREACH(i) {
1074 			pc = pcpu_find(i);
1075 			if (pc->pc_mds_buf == NULL) {
1076 				pc->pc_mds_buf = malloc_domainset(672, M_TEMP,
1077 				    DOMAINSET_PREF(pc->pc_domain), M_WAITOK);
1078 				bzero(pc->pc_mds_buf, 16);
1079 			}
1080 		}
1081 		mds_handler = mds_handler_ivb;
1082 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1083 	    (CPUID_TO_MODEL(cpu_id) == 0x3f || CPUID_TO_MODEL(cpu_id) == 0x3c ||
1084 	    CPUID_TO_MODEL(cpu_id) == 0x45 || CPUID_TO_MODEL(cpu_id) == 0x46 ||
1085 	    CPUID_TO_MODEL(cpu_id) == 0x56 || CPUID_TO_MODEL(cpu_id) == 0x4f ||
1086 	    CPUID_TO_MODEL(cpu_id) == 0x47 || CPUID_TO_MODEL(cpu_id) == 0x3d) &&
1087 	    (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1088 		/*
1089 		 * Haswell, Broadwell
1090 		 */
1091 		CPU_FOREACH(i) {
1092 			pc = pcpu_find(i);
1093 			if (pc->pc_mds_buf == NULL) {
1094 				pc->pc_mds_buf = malloc_domainset(1536, M_TEMP,
1095 				    DOMAINSET_PREF(pc->pc_domain), M_WAITOK);
1096 				bzero(pc->pc_mds_buf, 16);
1097 			}
1098 		}
1099 		mds_handler = mds_handler_bdw;
1100 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1101 	    ((CPUID_TO_MODEL(cpu_id) == 0x55 && (cpu_id &
1102 	    CPUID_STEPPING) <= 5) ||
1103 	    CPUID_TO_MODEL(cpu_id) == 0x4e || CPUID_TO_MODEL(cpu_id) == 0x5e ||
1104 	    (CPUID_TO_MODEL(cpu_id) == 0x8e && (cpu_id &
1105 	    CPUID_STEPPING) <= 0xb) ||
1106 	    (CPUID_TO_MODEL(cpu_id) == 0x9e && (cpu_id &
1107 	    CPUID_STEPPING) <= 0xc)) &&
1108 	    (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1109 		/*
1110 		 * Skylake, KabyLake, CoffeeLake, WhiskeyLake,
1111 		 * CascadeLake
1112 		 */
1113 		CPU_FOREACH(i) {
1114 			pc = pcpu_find(i);
1115 			if (pc->pc_mds_buf == NULL) {
1116 				pc->pc_mds_buf = malloc_domainset(6 * 1024,
1117 				    M_TEMP, DOMAINSET_PREF(pc->pc_domain),
1118 				    M_WAITOK);
1119 				b64 = (vm_offset_t)malloc_domainset(64 + 63,
1120 				    M_TEMP, DOMAINSET_PREF(pc->pc_domain),
1121 				    M_WAITOK);
1122 				pc->pc_mds_buf64 = (void *)roundup2(b64, 64);
1123 				bzero(pc->pc_mds_buf64, 64);
1124 			}
1125 		}
1126 		xcr0 = rxcr(0);
1127 		if ((xcr0 & XFEATURE_ENABLED_ZMM_HI256) != 0 &&
1128 		    (cpu_stdext_feature & CPUID_STDEXT_AVX512DQ) != 0)
1129 			mds_handler = mds_handler_skl_avx512;
1130 		else if ((xcr0 & XFEATURE_ENABLED_AVX) != 0 &&
1131 		    (cpu_feature2 & CPUID2_AVX) != 0)
1132 			mds_handler = mds_handler_skl_avx;
1133 		else
1134 			mds_handler = mds_handler_skl_sse;
1135 	} else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1136 	    ((CPUID_TO_MODEL(cpu_id) == 0x37 ||
1137 	    CPUID_TO_MODEL(cpu_id) == 0x4a ||
1138 	    CPUID_TO_MODEL(cpu_id) == 0x4c ||
1139 	    CPUID_TO_MODEL(cpu_id) == 0x4d ||
1140 	    CPUID_TO_MODEL(cpu_id) == 0x5a ||
1141 	    CPUID_TO_MODEL(cpu_id) == 0x5d ||
1142 	    CPUID_TO_MODEL(cpu_id) == 0x6e ||
1143 	    CPUID_TO_MODEL(cpu_id) == 0x65 ||
1144 	    CPUID_TO_MODEL(cpu_id) == 0x75 ||
1145 	    CPUID_TO_MODEL(cpu_id) == 0x1c ||
1146 	    CPUID_TO_MODEL(cpu_id) == 0x26 ||
1147 	    CPUID_TO_MODEL(cpu_id) == 0x27 ||
1148 	    CPUID_TO_MODEL(cpu_id) == 0x35 ||
1149 	    CPUID_TO_MODEL(cpu_id) == 0x36 ||
1150 	    CPUID_TO_MODEL(cpu_id) == 0x7a))) {
1151 		/* Silvermont, Airmont */
1152 		CPU_FOREACH(i) {
1153 			pc = pcpu_find(i);
1154 			if (pc->pc_mds_buf == NULL)
1155 				pc->pc_mds_buf = malloc(256, M_TEMP, M_WAITOK);
1156 		}
1157 		mds_handler = mds_handler_silvermont;
1158 	} else {
1159 		hw_mds_disable = 0;
1160 		mds_handler = mds_handler_void;
1161 	}
1162 }
1163 
1164 static void
1165 hw_mds_recalculate_boot(void *arg __unused)
1166 {
1167 
1168 	hw_mds_recalculate();
1169 }
1170 SYSINIT(mds_recalc, SI_SUB_SMP, SI_ORDER_ANY, hw_mds_recalculate_boot, NULL);
1171 
1172 static int
1173 sysctl_mds_disable_handler(SYSCTL_HANDLER_ARGS)
1174 {
1175 	int error, val;
1176 
1177 	val = hw_mds_disable;
1178 	error = sysctl_handle_int(oidp, &val, 0, req);
1179 	if (error != 0 || req->newptr == NULL)
1180 		return (error);
1181 	if (val < 0 || val > 3)
1182 		return (EINVAL);
1183 	hw_mds_disable = val;
1184 	hw_mds_recalculate();
1185 	return (0);
1186 }
1187 
1188 SYSCTL_PROC(_hw, OID_AUTO, mds_disable, CTLTYPE_INT |
1189     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1190     sysctl_mds_disable_handler, "I",
1191     "Microarchitectural Data Sampling Mitigation "
1192     "(0 - off, 1 - on VERW, 2 - on SW, 3 - on AUTO");
1193 
1194 SYSCTL_PROC(_machdep_mitigations_mds, OID_AUTO, disable, CTLTYPE_INT |
1195     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1196     sysctl_mds_disable_handler, "I",
1197     "Microarchitectural Data Sampling Mitigation "
1198     "(0 - off, 1 - on VERW, 2 - on SW, 3 - on AUTO");
1199 
1200 /*
1201  * Intel Transactional Memory Asynchronous Abort Mitigation
1202  * CVE-2019-11135
1203  */
1204 int x86_taa_enable;
1205 int x86_taa_state;
1206 enum {
1207 	TAA_NONE	= 0,	/* No mitigation enabled */
1208 	TAA_TSX_DISABLE	= 1,	/* Disable TSX via MSR */
1209 	TAA_VERW	= 2,	/* Use VERW mitigation */
1210 	TAA_AUTO	= 3,	/* Automatically select the mitigation */
1211 
1212 	/* The states below are not selectable by the operator */
1213 
1214 	TAA_TAA_UC	= 4,	/* Mitigation present in microcode */
1215 	TAA_NOT_PRESENT	= 5	/* TSX is not present */
1216 };
1217 
1218 static void
1219 taa_set(bool enable, bool all)
1220 {
1221 
1222 	x86_msr_op(MSR_IA32_TSX_CTRL,
1223 	    (enable ? MSR_OP_OR : MSR_OP_ANDNOT) |
1224 	    (all ? MSR_OP_RENDEZVOUS : MSR_OP_LOCAL),
1225 	    IA32_TSX_CTRL_RTM_DISABLE | IA32_TSX_CTRL_TSX_CPUID_CLEAR);
1226 }
1227 
1228 void
1229 x86_taa_recalculate(void)
1230 {
1231 	static int taa_saved_mds_disable = 0;
1232 	int taa_need = 0, taa_state = 0;
1233 	int mds_disable = 0, need_mds_recalc = 0;
1234 
1235 	/* Check CPUID.07h.EBX.HLE and RTM for the presence of TSX */
1236 	if ((cpu_stdext_feature & CPUID_STDEXT_HLE) == 0 ||
1237 	    (cpu_stdext_feature & CPUID_STDEXT_RTM) == 0) {
1238 		/* TSX is not present */
1239 		x86_taa_state = TAA_NOT_PRESENT;
1240 		return;
1241 	}
1242 
1243 	/* Check to see what mitigation options the CPU gives us */
1244 	if (cpu_ia32_arch_caps & IA32_ARCH_CAP_TAA_NO) {
1245 		/* CPU is not suseptible to TAA */
1246 		taa_need = TAA_TAA_UC;
1247 	} else if (cpu_ia32_arch_caps & IA32_ARCH_CAP_TSX_CTRL) {
1248 		/*
1249 		 * CPU can turn off TSX.  This is the next best option
1250 		 * if TAA_NO hardware mitigation isn't present
1251 		 */
1252 		taa_need = TAA_TSX_DISABLE;
1253 	} else {
1254 		/* No TSX/TAA specific remedies are available. */
1255 		if (x86_taa_enable == TAA_TSX_DISABLE) {
1256 			if (bootverbose)
1257 				printf("TSX control not available\n");
1258 			return;
1259 		} else
1260 			taa_need = TAA_VERW;
1261 	}
1262 
1263 	/* Can we automatically take action, or are we being forced? */
1264 	if (x86_taa_enable == TAA_AUTO)
1265 		taa_state = taa_need;
1266 	else
1267 		taa_state = x86_taa_enable;
1268 
1269 	/* No state change, nothing to do */
1270 	if (taa_state == x86_taa_state) {
1271 		if (bootverbose)
1272 			printf("No TSX change made\n");
1273 		return;
1274 	}
1275 
1276 	/* Does the MSR need to be turned on or off? */
1277 	if (taa_state == TAA_TSX_DISABLE)
1278 		taa_set(true, true);
1279 	else if (x86_taa_state == TAA_TSX_DISABLE)
1280 		taa_set(false, true);
1281 
1282 	/* Does MDS need to be set to turn on VERW? */
1283 	if (taa_state == TAA_VERW) {
1284 		taa_saved_mds_disable = hw_mds_disable;
1285 		mds_disable = hw_mds_disable = 1;
1286 		need_mds_recalc = 1;
1287 	} else if (x86_taa_state == TAA_VERW) {
1288 		mds_disable = hw_mds_disable = taa_saved_mds_disable;
1289 		need_mds_recalc = 1;
1290 	}
1291 	if (need_mds_recalc) {
1292 		hw_mds_recalculate();
1293 		if (mds_disable != hw_mds_disable) {
1294 			if (bootverbose)
1295 				printf("Cannot change MDS state for TAA\n");
1296 			/* Don't update our state */
1297 			return;
1298 		}
1299 	}
1300 
1301 	x86_taa_state = taa_state;
1302 	return;
1303 }
1304 
1305 static void
1306 taa_recalculate_boot(void * arg __unused)
1307 {
1308 
1309 	x86_taa_recalculate();
1310 }
1311 SYSINIT(taa_recalc, SI_SUB_SMP, SI_ORDER_ANY, taa_recalculate_boot, NULL);
1312 
1313 SYSCTL_NODE(_machdep_mitigations, OID_AUTO, taa,
1314     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1315     "TSX Asynchronous Abort Mitigation");
1316 
1317 static int
1318 sysctl_taa_handler(SYSCTL_HANDLER_ARGS)
1319 {
1320 	int error, val;
1321 
1322 	val = x86_taa_enable;
1323 	error = sysctl_handle_int(oidp, &val, 0, req);
1324 	if (error != 0 || req->newptr == NULL)
1325 		return (error);
1326 	if (val < TAA_NONE || val > TAA_AUTO)
1327 		return (EINVAL);
1328 	x86_taa_enable = val;
1329 	x86_taa_recalculate();
1330 	return (0);
1331 }
1332 
1333 SYSCTL_PROC(_machdep_mitigations_taa, OID_AUTO, enable, CTLTYPE_INT |
1334     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1335     sysctl_taa_handler, "I",
1336     "TAA Mitigation enablement control "
1337     "(0 - off, 1 - disable TSX, 2 - VERW, 3 - on AUTO");
1338 
1339 static int
1340 sysctl_taa_state_handler(SYSCTL_HANDLER_ARGS)
1341 {
1342 	const char *state;
1343 
1344 	switch (x86_taa_state) {
1345 	case TAA_NONE:
1346 		state = "inactive";
1347 		break;
1348 	case TAA_TSX_DISABLE:
1349 		state = "TSX disabled";
1350 		break;
1351 	case TAA_VERW:
1352 		state = "VERW";
1353 		break;
1354 	case TAA_TAA_UC:
1355 		state = "Mitigated in microcode";
1356 		break;
1357 	case TAA_NOT_PRESENT:
1358 		state = "TSX not present";
1359 		break;
1360 	default:
1361 		state = "unknown";
1362 	}
1363 
1364 	return (SYSCTL_OUT(req, state, strlen(state)));
1365 }
1366 
1367 SYSCTL_PROC(_machdep_mitigations_taa, OID_AUTO, state,
1368     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1369     sysctl_taa_state_handler, "A",
1370     "TAA Mitigation state");
1371 
1372 int __read_frequently cpu_flush_rsb_ctxsw;
1373 SYSCTL_INT(_machdep_mitigations, OID_AUTO, flush_rsb_ctxsw,
1374     CTLFLAG_RW | CTLFLAG_NOFETCH, &cpu_flush_rsb_ctxsw, 0,
1375     "Flush Return Stack Buffer on context switch");
1376 
1377 SYSCTL_NODE(_machdep_mitigations, OID_AUTO, rngds,
1378     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1379     "MCU Optimization, disable RDSEED mitigation");
1380 
1381 int x86_rngds_mitg_enable = 1;
1382 void
1383 x86_rngds_mitg_recalculate(bool all_cpus)
1384 {
1385 	if ((cpu_stdext_feature3 & CPUID_STDEXT3_MCUOPT) == 0)
1386 		return;
1387 	x86_msr_op(MSR_IA32_MCU_OPT_CTRL,
1388 	    (x86_rngds_mitg_enable ? MSR_OP_OR : MSR_OP_ANDNOT) |
1389 	    (all_cpus ? MSR_OP_RENDEZVOUS : MSR_OP_LOCAL),
1390 	    IA32_RNGDS_MITG_DIS);
1391 }
1392 
1393 static int
1394 sysctl_rngds_mitg_enable_handler(SYSCTL_HANDLER_ARGS)
1395 {
1396 	int error, val;
1397 
1398 	val = x86_rngds_mitg_enable;
1399 	error = sysctl_handle_int(oidp, &val, 0, req);
1400 	if (error != 0 || req->newptr == NULL)
1401 		return (error);
1402 	x86_rngds_mitg_enable = val;
1403 	x86_rngds_mitg_recalculate(true);
1404 	return (0);
1405 }
1406 SYSCTL_PROC(_machdep_mitigations_rngds, OID_AUTO, enable, CTLTYPE_INT |
1407     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1408     sysctl_rngds_mitg_enable_handler, "I",
1409     "MCU Optimization, disabling RDSEED mitigation control "
1410     "(0 - mitigation disabled (RDSEED optimized), 1 - mitigation enabled");
1411 
1412 static int
1413 sysctl_rngds_state_handler(SYSCTL_HANDLER_ARGS)
1414 {
1415 	const char *state;
1416 
1417 	if ((cpu_stdext_feature3 & CPUID_STDEXT3_MCUOPT) == 0) {
1418 		state = "Not applicable";
1419 	} else if (x86_rngds_mitg_enable == 0) {
1420 		state = "RDSEED not serialized";
1421 	} else {
1422 		state = "Mitigated";
1423 	}
1424 	return (SYSCTL_OUT(req, state, strlen(state)));
1425 }
1426 SYSCTL_PROC(_machdep_mitigations_rngds, OID_AUTO, state,
1427     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1428     sysctl_rngds_state_handler, "A",
1429     "MCU Optimization state");
1430 
1431 /*
1432  * Enable and restore kernel text write permissions.
1433  * Callers must ensure that disable_wp()/restore_wp() are executed
1434  * without rescheduling on the same core.
1435  */
1436 bool
1437 disable_wp(void)
1438 {
1439 	u_int cr0;
1440 
1441 	cr0 = rcr0();
1442 	if ((cr0 & CR0_WP) == 0)
1443 		return (false);
1444 	load_cr0(cr0 & ~CR0_WP);
1445 	return (true);
1446 }
1447 
1448 void
1449 restore_wp(bool old_wp)
1450 {
1451 
1452 	if (old_wp)
1453 		load_cr0(rcr0() | CR0_WP);
1454 }
1455 
1456 bool
1457 acpi_get_fadt_bootflags(uint16_t *flagsp)
1458 {
1459 #ifdef DEV_ACPI
1460 	ACPI_TABLE_FADT *fadt;
1461 	vm_paddr_t physaddr;
1462 
1463 	physaddr = acpi_find_table(ACPI_SIG_FADT);
1464 	if (physaddr == 0)
1465 		return (false);
1466 	fadt = acpi_map_table(physaddr, ACPI_SIG_FADT);
1467 	if (fadt == NULL)
1468 		return (false);
1469 	*flagsp = fadt->BootFlags;
1470 	acpi_unmap_table(fadt);
1471 	return (true);
1472 #else
1473 	return (false);
1474 #endif
1475 }
1476