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