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