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 #include "opt_acpi.h"
43 #include "opt_atpic.h"
44 #include "opt_cpu.h"
45 #include "opt_ddb.h"
46 #include "opt_inet.h"
47 #include "opt_isa.h"
48 #include "opt_kdb.h"
49 #include "opt_kstack_pages.h"
50 #include "opt_maxmem.h"
51 #include "opt_mp_watchdog.h"
52 #include "opt_platform.h"
53 #include "opt_sched.h"
54 #ifdef __i386__
55 #include "opt_apic.h"
56 #endif
57
58 #include <sys/param.h>
59 #include <sys/proc.h>
60 #include <sys/systm.h>
61 #include <sys/bus.h>
62 #include <sys/cpu.h>
63 #include <sys/domainset.h>
64 #include <sys/kdb.h>
65 #include <sys/kernel.h>
66 #include <sys/ktr.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mutex.h>
70 #include <sys/pcpu.h>
71 #include <sys/rwlock.h>
72 #include <sys/sched.h>
73 #include <sys/smp.h>
74 #include <sys/sysctl.h>
75
76 #include <machine/clock.h>
77 #include <machine/cpu.h>
78 #include <machine/cpufunc.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 #include <x86/ifunc.h>
92
93 #include <vm/vm.h>
94 #include <vm/vm_extern.h>
95 #include <vm/vm_kern.h>
96 #include <vm/vm_page.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_object.h>
99 #include <vm/vm_pager.h>
100 #include <vm/vm_param.h>
101
102 #include <isa/isareg.h>
103
104 #include <contrib/dev/acpica/include/acpi.h>
105
106 #define STATE_RUNNING 0x0
107 #define STATE_MWAIT 0x1
108 #define STATE_SLEEPING 0x2
109
110 #ifdef SMP
111 static u_int cpu_reset_proxyid;
112 static volatile u_int cpu_reset_proxy_active;
113 #endif
114
115 struct msr_op_arg {
116 u_int msr;
117 int op;
118 uint64_t arg1;
119 uint64_t *res;
120 };
121
122 static void
x86_msr_op_one(void * argp)123 x86_msr_op_one(void *argp)
124 {
125 struct msr_op_arg *a;
126 uint64_t v;
127
128 a = argp;
129 switch (a->op) {
130 case MSR_OP_ANDNOT:
131 v = rdmsr(a->msr);
132 v &= ~a->arg1;
133 wrmsr(a->msr, v);
134 break;
135 case MSR_OP_OR:
136 v = rdmsr(a->msr);
137 v |= a->arg1;
138 wrmsr(a->msr, v);
139 break;
140 case MSR_OP_WRITE:
141 wrmsr(a->msr, a->arg1);
142 break;
143 case MSR_OP_READ:
144 v = rdmsr(a->msr);
145 *a->res = v;
146 break;
147 }
148 }
149
150 #define MSR_OP_EXMODE_MASK 0xf0000000
151 #define MSR_OP_OP_MASK 0x000000ff
152 #define MSR_OP_GET_CPUID(x) (((x) & ~MSR_OP_EXMODE_MASK) >> 8)
153
154 void
x86_msr_op(u_int msr,u_int op,uint64_t arg1,uint64_t * res)155 x86_msr_op(u_int msr, u_int op, uint64_t arg1, uint64_t *res)
156 {
157 struct thread *td;
158 struct msr_op_arg a;
159 cpuset_t set;
160 u_int exmode;
161 int bound_cpu, cpu, i, is_bound;
162
163 a.op = op & MSR_OP_OP_MASK;
164 MPASS(a.op == MSR_OP_ANDNOT || a.op == MSR_OP_OR ||
165 a.op == MSR_OP_WRITE || a.op == MSR_OP_READ);
166 exmode = op & MSR_OP_EXMODE_MASK;
167 MPASS(exmode == MSR_OP_LOCAL || exmode == MSR_OP_SCHED_ALL ||
168 exmode == MSR_OP_SCHED_ONE || exmode == MSR_OP_RENDEZVOUS_ALL ||
169 exmode == MSR_OP_RENDEZVOUS_ONE);
170 a.msr = msr;
171 a.arg1 = arg1;
172 a.res = res;
173 switch (exmode) {
174 case MSR_OP_LOCAL:
175 x86_msr_op_one(&a);
176 break;
177 case MSR_OP_SCHED_ALL:
178 td = curthread;
179 thread_lock(td);
180 is_bound = sched_is_bound(td);
181 bound_cpu = td->td_oncpu;
182 CPU_FOREACH(i) {
183 sched_bind(td, i);
184 x86_msr_op_one(&a);
185 }
186 if (is_bound)
187 sched_bind(td, bound_cpu);
188 else
189 sched_unbind(td);
190 thread_unlock(td);
191 break;
192 case MSR_OP_SCHED_ONE:
193 td = curthread;
194 cpu = MSR_OP_GET_CPUID(op);
195 thread_lock(td);
196 is_bound = sched_is_bound(td);
197 bound_cpu = td->td_oncpu;
198 if (!is_bound || bound_cpu != cpu)
199 sched_bind(td, cpu);
200 x86_msr_op_one(&a);
201 if (is_bound) {
202 if (bound_cpu != cpu)
203 sched_bind(td, bound_cpu);
204 } else {
205 sched_unbind(td);
206 }
207 thread_unlock(td);
208 break;
209 case MSR_OP_RENDEZVOUS_ALL:
210 smp_rendezvous(smp_no_rendezvous_barrier, x86_msr_op_one,
211 smp_no_rendezvous_barrier, &a);
212 break;
213 case MSR_OP_RENDEZVOUS_ONE:
214 cpu = MSR_OP_GET_CPUID(op);
215 CPU_SETOF(cpu, &set);
216 smp_rendezvous_cpus(set, smp_no_rendezvous_barrier,
217 x86_msr_op_one, smp_no_rendezvous_barrier, &a);
218 break;
219 }
220 }
221
222 /*
223 * Automatically initialized per CPU errata in cpu_idle_tun below.
224 */
225 bool mwait_cpustop_broken = false;
226 SYSCTL_BOOL(_machdep, OID_AUTO, mwait_cpustop_broken, CTLFLAG_RDTUN,
227 &mwait_cpustop_broken, 0,
228 "Can not reliably wake MONITOR/MWAIT cpus without interrupts");
229
230 /*
231 * Flush the D-cache for non-DMA I/O so that the I-cache can
232 * be made coherent later.
233 */
234 void
cpu_flush_dcache(void * ptr,size_t len)235 cpu_flush_dcache(void *ptr, size_t len)
236 {
237 /* Not applicable */
238 }
239
240 void
acpi_cpu_c1(void)241 acpi_cpu_c1(void)
242 {
243
244 __asm __volatile("sti; hlt");
245 }
246
247 /*
248 * Use mwait to pause execution while waiting for an interrupt or
249 * another thread to signal that there is more work.
250 *
251 * NOTE: Interrupts will cause a wakeup; however, this function does
252 * not enable interrupt handling. The caller is responsible to enable
253 * interrupts.
254 */
255 void
acpi_cpu_idle_mwait(uint32_t mwait_hint)256 acpi_cpu_idle_mwait(uint32_t mwait_hint)
257 {
258 int *state;
259 uint64_t v;
260
261 /*
262 * A comment in Linux patch claims that 'CPUs run faster with
263 * speculation protection disabled. All CPU threads in a core
264 * must disable speculation protection for it to be
265 * disabled. Disable it while we are idle so the other
266 * hyperthread can run fast.'
267 *
268 * XXXKIB. Software coordination mode should be supported,
269 * but all Intel CPUs provide hardware coordination.
270 */
271
272 state = &PCPU_PTR(monitorbuf)->idle_state;
273 KASSERT(atomic_load_int(state) == STATE_SLEEPING,
274 ("cpu_mwait_cx: wrong monitorbuf state"));
275 atomic_store_int(state, STATE_MWAIT);
276 if (PCPU_GET(ibpb_set) || hw_ssb_active) {
277 v = rdmsr(MSR_IA32_SPEC_CTRL);
278 wrmsr(MSR_IA32_SPEC_CTRL, v & ~(IA32_SPEC_CTRL_IBRS |
279 IA32_SPEC_CTRL_STIBP | IA32_SPEC_CTRL_SSBD));
280 } else {
281 v = 0;
282 }
283 cpu_monitor(state, 0, 0);
284 if (atomic_load_int(state) == STATE_MWAIT)
285 cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
286
287 /*
288 * SSB cannot be disabled while we sleep, or rather, if it was
289 * disabled, the sysctl thread will bind to our cpu to tweak
290 * MSR.
291 */
292 if (v != 0)
293 wrmsr(MSR_IA32_SPEC_CTRL, v);
294
295 /*
296 * We should exit on any event that interrupts mwait, because
297 * that event might be a wanted interrupt.
298 */
299 atomic_store_int(state, STATE_RUNNING);
300 }
301
302 /* Get current clock frequency for the given cpu id. */
303 int
cpu_est_clockrate(int cpu_id,uint64_t * rate)304 cpu_est_clockrate(int cpu_id, uint64_t *rate)
305 {
306 uint64_t tsc1, tsc2;
307 uint64_t acnt, mcnt, perf;
308 register_t reg;
309
310 if (pcpu_find(cpu_id) == NULL || rate == NULL)
311 return (EINVAL);
312 #ifdef __i386__
313 if ((cpu_feature & CPUID_TSC) == 0)
314 return (EOPNOTSUPP);
315 #endif
316
317 /*
318 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
319 * DELAY(9) based logic fails.
320 */
321 if (tsc_is_invariant && !tsc_perf_stat)
322 return (EOPNOTSUPP);
323
324 #ifdef SMP
325 if (smp_cpus > 1) {
326 /* Schedule ourselves on the indicated cpu. */
327 thread_lock(curthread);
328 sched_bind(curthread, cpu_id);
329 thread_unlock(curthread);
330 }
331 #endif
332
333 /* Calibrate by measuring a short delay. */
334 reg = intr_disable();
335 if (tsc_is_invariant) {
336 wrmsr(MSR_MPERF, 0);
337 wrmsr(MSR_APERF, 0);
338 tsc1 = rdtsc();
339 DELAY(1000);
340 mcnt = rdmsr(MSR_MPERF);
341 acnt = rdmsr(MSR_APERF);
342 tsc2 = rdtsc();
343 intr_restore(reg);
344 perf = 1000 * acnt / mcnt;
345 *rate = (tsc2 - tsc1) * perf;
346 } else {
347 tsc1 = rdtsc();
348 DELAY(1000);
349 tsc2 = rdtsc();
350 intr_restore(reg);
351 *rate = (tsc2 - tsc1) * 1000;
352 }
353
354 #ifdef SMP
355 if (smp_cpus > 1) {
356 thread_lock(curthread);
357 sched_unbind(curthread);
358 thread_unlock(curthread);
359 }
360 #endif
361
362 return (0);
363 }
364
365 /*
366 * Shutdown the CPU as much as possible
367 */
368 void
cpu_halt(void)369 cpu_halt(void)
370 {
371 for (;;)
372 halt();
373 }
374
375 static void
cpu_reset_real(void)376 cpu_reset_real(void)
377 {
378 struct region_descriptor null_idt;
379 int b;
380
381 disable_intr();
382 #ifdef CPU_ELAN
383 if (elan_mmcr != NULL)
384 elan_mmcr->RESCFG = 1;
385 #endif
386 #ifdef __i386__
387 if (cpu == CPU_GEODE1100) {
388 /* Attempt Geode's own reset */
389 outl(0xcf8, 0x80009044ul);
390 outl(0xcfc, 0xf);
391 }
392 #endif
393 #if !defined(BROKEN_KEYBOARD_RESET)
394 /*
395 * Attempt to do a CPU reset via the keyboard controller,
396 * do not turn off GateA20, as any machine that fails
397 * to do the reset here would then end up in no man's land.
398 */
399 outb(IO_KBD + 4, 0xFE);
400 DELAY(500000); /* wait 0.5 sec to see if that did it */
401 #endif
402
403 /*
404 * Attempt to force a reset via the Reset Control register at
405 * I/O port 0xcf9. Bit 2 forces a system reset when it
406 * transitions from 0 to 1. Bit 1 selects the type of reset
407 * to attempt: 0 selects a "soft" reset, and 1 selects a
408 * "hard" reset. We try a "hard" reset. The first write sets
409 * bit 1 to select a "hard" reset and clears bit 2. The
410 * second write forces a 0 -> 1 transition in bit 2 to trigger
411 * a reset.
412 */
413 outb(0xcf9, 0x2);
414 outb(0xcf9, 0x6);
415 DELAY(500000); /* wait 0.5 sec to see if that did it */
416
417 /*
418 * Attempt to force a reset via the Fast A20 and Init register
419 * at I/O port 0x92. Bit 1 serves as an alternate A20 gate.
420 * Bit 0 asserts INIT# when set to 1. We are careful to only
421 * preserve bit 1 while setting bit 0. We also must clear bit
422 * 0 before setting it if it isn't already clear.
423 */
424 b = inb(0x92);
425 if (b != 0xff) {
426 if ((b & 0x1) != 0)
427 outb(0x92, b & 0xfe);
428 outb(0x92, b | 0x1);
429 DELAY(500000); /* wait 0.5 sec to see if that did it */
430 }
431
432 printf("No known reset method worked, attempting CPU shutdown\n");
433 DELAY(1000000); /* wait 1 sec for printf to complete */
434
435 /* Wipe the IDT. */
436 null_idt.rd_limit = 0;
437 null_idt.rd_base = 0;
438 lidt(&null_idt);
439
440 /* "good night, sweet prince .... <THUNK!>" */
441 breakpoint();
442
443 /* NOTREACHED */
444 while(1);
445 }
446
447 #ifdef SMP
448 static void
cpu_reset_proxy(void)449 cpu_reset_proxy(void)
450 {
451
452 cpu_reset_proxy_active = 1;
453 while (cpu_reset_proxy_active == 1)
454 ia32_pause(); /* Wait for other cpu to see that we've started */
455
456 printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
457 DELAY(1000000);
458 cpu_reset_real();
459 }
460 #endif
461
462 void
cpu_reset(void)463 cpu_reset(void)
464 {
465 #ifdef SMP
466 struct monitorbuf *mb;
467 cpuset_t map;
468 u_int cnt;
469
470 if (smp_started) {
471 map = all_cpus;
472 CPU_CLR(PCPU_GET(cpuid), &map);
473 CPU_ANDNOT(&map, &map, &stopped_cpus);
474 if (!CPU_EMPTY(&map)) {
475 printf("cpu_reset: Stopping other CPUs\n");
476 stop_cpus(map);
477 }
478
479 if (PCPU_GET(cpuid) != 0) {
480 cpu_reset_proxyid = PCPU_GET(cpuid);
481 cpustop_restartfunc = cpu_reset_proxy;
482 cpu_reset_proxy_active = 0;
483 printf("cpu_reset: Restarting BSP\n");
484
485 /* Restart CPU #0. */
486 CPU_SETOF(0, &started_cpus);
487 mb = &pcpu_find(0)->pc_monitorbuf;
488 atomic_store_int(&mb->stop_state,
489 MONITOR_STOPSTATE_RUNNING);
490
491 cnt = 0;
492 while (cpu_reset_proxy_active == 0 && cnt < 10000000) {
493 ia32_pause();
494 cnt++; /* Wait for BSP to announce restart */
495 }
496 if (cpu_reset_proxy_active == 0) {
497 printf("cpu_reset: Failed to restart BSP\n");
498 } else {
499 cpu_reset_proxy_active = 2;
500 while (1)
501 ia32_pause();
502 /* NOTREACHED */
503 }
504 }
505
506 DELAY(1000000);
507 }
508 #endif
509 cpu_reset_real();
510 /* NOTREACHED */
511 }
512
513 bool
cpu_mwait_usable(void)514 cpu_mwait_usable(void)
515 {
516
517 return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
518 (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
519 (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
520 }
521
522 void (*cpu_idle_hook)(sbintime_t) = NULL; /* ACPI idle hook. */
523
524 int cpu_amdc1e_bug = 0; /* AMD C1E APIC workaround required. */
525
526 static int idle_mwait = 1; /* Use MONITOR/MWAIT for short idle. */
527 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
528 0, "Use MONITOR/MWAIT for short idle");
529
530 static bool
cpu_idle_enter(int * statep,int newstate)531 cpu_idle_enter(int *statep, int newstate)
532 {
533 KASSERT(atomic_load_int(statep) == STATE_RUNNING,
534 ("%s: state %d", __func__, atomic_load_int(statep)));
535
536 /*
537 * A fence is needed to prevent reordering of the load in
538 * sched_runnable() with this store to the idle state word. Without it,
539 * cpu_idle_wakeup() can observe the state as STATE_RUNNING after having
540 * added load to the queue, and elide an IPI. Then, sched_runnable()
541 * can observe tdq_load == 0, so the CPU ends up idling with pending
542 * work. tdq_notify() similarly ensures that a prior update to tdq_load
543 * is visible before calling cpu_idle_wakeup().
544 */
545 atomic_store_int(statep, newstate);
546 #if defined(SCHED_ULE) && defined(SMP)
547 atomic_thread_fence_seq_cst();
548 #endif
549
550 /*
551 * Since we may be in a critical section from cpu_idle(), if
552 * an interrupt fires during that critical section we may have
553 * a pending preemption. If the CPU halts, then that thread
554 * may not execute until a later interrupt awakens the CPU.
555 * To handle this race, check for a runnable thread after
556 * disabling interrupts and immediately return if one is
557 * found. Also, we must absolutely guarentee that hlt is
558 * the next instruction after sti. This ensures that any
559 * interrupt that fires after the call to disable_intr() will
560 * immediately awaken the CPU from hlt. Finally, please note
561 * that on x86 this works fine because of interrupts enabled only
562 * after the instruction following sti takes place, while IF is set
563 * to 1 immediately, allowing hlt instruction to acknowledge the
564 * interrupt.
565 */
566 disable_intr();
567 if (sched_runnable()) {
568 enable_intr();
569 atomic_store_int(statep, STATE_RUNNING);
570 return (false);
571 } else {
572 return (true);
573 }
574 }
575
576 static void
cpu_idle_exit(int * statep)577 cpu_idle_exit(int *statep)
578 {
579 atomic_store_int(statep, STATE_RUNNING);
580 }
581
582 static void
cpu_idle_acpi(sbintime_t sbt)583 cpu_idle_acpi(sbintime_t sbt)
584 {
585 int *state;
586
587 state = &PCPU_PTR(monitorbuf)->idle_state;
588 if (cpu_idle_enter(state, STATE_SLEEPING)) {
589 if (cpu_idle_hook)
590 cpu_idle_hook(sbt);
591 else
592 acpi_cpu_c1();
593 cpu_idle_exit(state);
594 }
595 }
596
597 static void
cpu_idle_hlt(sbintime_t sbt)598 cpu_idle_hlt(sbintime_t sbt)
599 {
600 int *state;
601
602 state = &PCPU_PTR(monitorbuf)->idle_state;
603 if (cpu_idle_enter(state, STATE_SLEEPING)) {
604 acpi_cpu_c1();
605 atomic_store_int(state, STATE_RUNNING);
606 }
607 }
608
609 static void
cpu_idle_mwait(sbintime_t sbt)610 cpu_idle_mwait(sbintime_t sbt)
611 {
612 int *state;
613
614 state = &PCPU_PTR(monitorbuf)->idle_state;
615 if (cpu_idle_enter(state, STATE_MWAIT)) {
616 cpu_monitor(state, 0, 0);
617 if (atomic_load_int(state) == STATE_MWAIT)
618 __asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
619 else
620 enable_intr();
621 cpu_idle_exit(state);
622 }
623 }
624
625 static void
cpu_idle_spin(sbintime_t sbt)626 cpu_idle_spin(sbintime_t sbt)
627 {
628 int *state;
629 int i;
630
631 state = &PCPU_PTR(monitorbuf)->idle_state;
632 atomic_store_int(state, STATE_RUNNING);
633
634 /*
635 * The sched_runnable() call is racy but as long as there is
636 * a loop missing it one time will have just a little impact if any
637 * (and it is much better than missing the check at all).
638 */
639 for (i = 0; i < 1000; i++) {
640 if (sched_runnable())
641 return;
642 cpu_spinwait();
643 }
644 }
645
646 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
647
648 void
cpu_idle(int busy)649 cpu_idle(int busy)
650 {
651 uint64_t msr;
652 sbintime_t sbt = -1;
653
654 CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
655 busy, curcpu);
656 #ifdef MP_WATCHDOG
657 ap_watchdog(PCPU_GET(cpuid));
658 #endif
659
660 /* If we are busy - try to use fast methods. */
661 if (busy) {
662 if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
663 cpu_idle_mwait(busy);
664 goto out;
665 }
666 }
667
668 /* If we have time - switch timers into idle mode. */
669 if (!busy) {
670 critical_enter();
671 sbt = cpu_idleclock();
672 }
673
674 /* Apply AMD APIC timer C1E workaround. */
675 if (cpu_amdc1e_bug && cpu_disable_c3_sleep) {
676 msr = rdmsr(MSR_AMDK8_IPM);
677 if ((msr & (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)) != 0)
678 wrmsr(MSR_AMDK8_IPM, msr & ~(AMDK8_SMIONCMPHALT |
679 AMDK8_C1EONCMPHALT));
680 }
681
682 /* Call main idle method. */
683 cpu_idle_fn(sbt);
684
685 /* Switch timers back into active mode. */
686 if (!busy) {
687 cpu_activeclock();
688 critical_exit();
689 }
690 out:
691 CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
692 busy, curcpu);
693 }
694
695 static int cpu_idle_apl31_workaround;
696 SYSCTL_INT(_machdep, OID_AUTO, idle_apl31, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
697 &cpu_idle_apl31_workaround, 0,
698 "Apollo Lake APL31 MWAIT bug workaround");
699
700 int
cpu_idle_wakeup(int cpu)701 cpu_idle_wakeup(int cpu)
702 {
703 struct monitorbuf *mb;
704 int *state;
705
706 mb = &pcpu_find(cpu)->pc_monitorbuf;
707 state = &mb->idle_state;
708 switch (atomic_load_int(state)) {
709 case STATE_SLEEPING:
710 return (0);
711 case STATE_MWAIT:
712 atomic_store_int(state, STATE_RUNNING);
713 return (cpu_idle_apl31_workaround ? 0 : 1);
714 case STATE_RUNNING:
715 return (1);
716 default:
717 panic("bad monitor state");
718 return (1);
719 }
720 }
721
722 /*
723 * Ordered by speed/power consumption.
724 */
725 static const struct {
726 void *id_fn;
727 const char *id_name;
728 int id_cpuid2_flag;
729 } idle_tbl[] = {
730 { .id_fn = cpu_idle_spin, .id_name = "spin" },
731 { .id_fn = cpu_idle_mwait, .id_name = "mwait",
732 .id_cpuid2_flag = CPUID2_MON },
733 { .id_fn = cpu_idle_hlt, .id_name = "hlt" },
734 { .id_fn = cpu_idle_acpi, .id_name = "acpi" },
735 };
736
737 static int
idle_sysctl_available(SYSCTL_HANDLER_ARGS)738 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
739 {
740 char *avail, *p;
741 int error;
742 int i;
743
744 avail = malloc(256, M_TEMP, M_WAITOK);
745 p = avail;
746 for (i = 0; i < nitems(idle_tbl); i++) {
747 if (idle_tbl[i].id_cpuid2_flag != 0 &&
748 (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
749 continue;
750 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
751 cpu_idle_hook == NULL)
752 continue;
753 p += sprintf(p, "%s%s", p != avail ? ", " : "",
754 idle_tbl[i].id_name);
755 }
756 error = sysctl_handle_string(oidp, avail, 0, req);
757 free(avail, M_TEMP);
758 return (error);
759 }
760
761 SYSCTL_PROC(_machdep, OID_AUTO, idle_available,
762 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
763 0, 0, idle_sysctl_available, "A",
764 "list of available idle functions");
765
766 static bool
cpu_idle_selector(const char * new_idle_name)767 cpu_idle_selector(const char *new_idle_name)
768 {
769 int i;
770
771 for (i = 0; i < nitems(idle_tbl); i++) {
772 if (idle_tbl[i].id_cpuid2_flag != 0 &&
773 (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
774 continue;
775 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
776 cpu_idle_hook == NULL)
777 continue;
778 if (strcmp(idle_tbl[i].id_name, new_idle_name))
779 continue;
780 cpu_idle_fn = idle_tbl[i].id_fn;
781 if (bootverbose)
782 printf("CPU idle set to %s\n", idle_tbl[i].id_name);
783 return (true);
784 }
785 return (false);
786 }
787
788 static int
cpu_idle_sysctl(SYSCTL_HANDLER_ARGS)789 cpu_idle_sysctl(SYSCTL_HANDLER_ARGS)
790 {
791 char buf[16];
792 const char *p;
793 int error, i;
794
795 p = "unknown";
796 for (i = 0; i < nitems(idle_tbl); i++) {
797 if (idle_tbl[i].id_fn == cpu_idle_fn) {
798 p = idle_tbl[i].id_name;
799 break;
800 }
801 }
802 strncpy(buf, p, sizeof(buf));
803 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
804 if (error != 0 || req->newptr == NULL)
805 return (error);
806 return (cpu_idle_selector(buf) ? 0 : EINVAL);
807 }
808
809 SYSCTL_PROC(_machdep, OID_AUTO, idle,
810 CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE,
811 0, 0, cpu_idle_sysctl, "A",
812 "currently selected idle function");
813
814 static void
cpu_idle_tun(void * unused __unused)815 cpu_idle_tun(void *unused __unused)
816 {
817 char tunvar[16];
818
819 if (TUNABLE_STR_FETCH("machdep.idle", tunvar, sizeof(tunvar)))
820 cpu_idle_selector(tunvar);
821 else if (cpu_vendor_id == CPU_VENDOR_AMD &&
822 CPUID_TO_FAMILY(cpu_id) == 0x17 && CPUID_TO_MODEL(cpu_id) == 0x1) {
823 /* Ryzen erratas 1057, 1109. */
824 cpu_idle_selector("hlt");
825 idle_mwait = 0;
826 mwait_cpustop_broken = true;
827 }
828
829 if (cpu_vendor_id == CPU_VENDOR_INTEL &&
830 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x5c) {
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
nmi_call_kdb(u_int cpu,u_int type,struct trapframe * frame)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
nmi_handle_intr(u_int type,struct trapframe * frame)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
hw_ibrs_recalculate(bool for_all_cpus)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
hw_ibrs_disable_handler(SYSCTL_HANDLER_ARGS)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
hw_ssb_set(bool enable,bool for_all_cpus)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
hw_ssb_recalculate(bool all_cpus)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
hw_ssb_disable_handler(SYSCTL_HANDLER_ARGS)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
sysctl_hw_mds_disable_state_handler(SYSCTL_HANDLER_ARGS)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
hw_mds_recalculate(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
hw_mds_recalculate_boot(void * arg __unused)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
sysctl_mds_disable_handler(SYSCTL_HANDLER_ARGS)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
taa_set(bool enable,bool all)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
x86_taa_recalculate(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
taa_recalculate_boot(void * arg __unused)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
sysctl_taa_handler(SYSCTL_HANDLER_ARGS)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
sysctl_taa_state_handler(SYSCTL_HANDLER_ARGS)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
x86_rngds_mitg_recalculate(bool all_cpus)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
sysctl_rngds_mitg_enable_handler(SYSCTL_HANDLER_ARGS)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
sysctl_rngds_state_handler(SYSCTL_HANDLER_ARGS)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 /*
1487 * Zenbleed.
1488 *
1489 * No corresponding errata is publicly listed. AMD has issued a security
1490 * bulletin (AMD-SB-7008), entitled "Cross-Process Information Leak". This
1491 * document lists (as of August 2023) platform firmware's availability target
1492 * dates, with most being November/December 2023. It will then be up to
1493 * motherboard manufacturers to produce corresponding BIOS updates, which will
1494 * happen with an inevitable lag. Additionally, for a variety of reasons,
1495 * operators might not be able to apply them everywhere due. On the side of
1496 * standalone CPU microcodes, no plans for availability have been published so
1497 * far. However, a developer appearing to be an AMD employee has hardcoded in
1498 * Linux revision numbers of future microcodes that are presumed to fix the
1499 * vulnerability.
1500 *
1501 * Given the stability issues encountered with early microcode releases for Rome
1502 * (the only microcode publicly released so far) and the absence of official
1503 * communication on standalone CPU microcodes, we have opted instead for
1504 * matching by default all AMD Zen2 processors which, according to the
1505 * vulnerability's discoverer, are all affected (see
1506 * https://lock.cmpxchg8b.com/zenbleed.html). This policy, also adopted by
1507 * OpenBSD, may be overriden using the tunable/sysctl
1508 * 'machdep.mitigations.zenbleed.enable'. We might revise it later depending on
1509 * official statements, microcode updates' public availability and community
1510 * assessment that they actually fix the vulnerability without any instability
1511 * side effects.
1512 */
1513
1514 SYSCTL_NODE(_machdep_mitigations, OID_AUTO, zenbleed,
1515 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1516 "Zenbleed OS-triggered prevention (via chicken bit)");
1517
1518 /* 2 is auto, see below. */
1519 int zenbleed_enable = 2;
1520
1521 void
zenbleed_sanitize_enable(void)1522 zenbleed_sanitize_enable(void)
1523 {
1524 /* Default to auto (2). */
1525 if (zenbleed_enable < 0 || zenbleed_enable > 2)
1526 zenbleed_enable = 2;
1527 }
1528
1529 static bool
zenbleed_chicken_bit_applicable(void)1530 zenbleed_chicken_bit_applicable(void)
1531 {
1532 /* Concerns only bare-metal AMD Zen2 processors. */
1533 return (cpu_vendor_id == CPU_VENDOR_AMD &&
1534 CPUID_TO_FAMILY(cpu_id) == 0x17 &&
1535 CPUID_TO_MODEL(cpu_id) >= 0x30 &&
1536 vm_guest == VM_GUEST_NO);
1537 }
1538
1539 static bool
zenbleed_chicken_bit_should_enable(void)1540 zenbleed_chicken_bit_should_enable(void)
1541 {
1542 /*
1543 * Obey tunable/sysctl.
1544 *
1545 * As explained above, currently, the automatic setting (2) and the "on"
1546 * one (1) have the same effect. In the future, we might additionally
1547 * check for specific microcode revisions as part of the automatic
1548 * determination.
1549 */
1550 return (zenbleed_enable != 0);
1551 }
1552
1553 void
zenbleed_check_and_apply(bool all_cpus)1554 zenbleed_check_and_apply(bool all_cpus)
1555 {
1556 bool set;
1557
1558 if (!zenbleed_chicken_bit_applicable())
1559 return;
1560
1561 set = zenbleed_chicken_bit_should_enable();
1562
1563 x86_msr_op(MSR_DE_CFG,
1564 (set ? MSR_OP_OR : MSR_OP_ANDNOT) |
1565 (all_cpus ? MSR_OP_RENDEZVOUS_ALL : MSR_OP_LOCAL),
1566 DE_CFG_ZEN2_FP_BACKUP_FIX_BIT, NULL);
1567 }
1568
1569 static int
sysctl_zenbleed_enable_handler(SYSCTL_HANDLER_ARGS)1570 sysctl_zenbleed_enable_handler(SYSCTL_HANDLER_ARGS)
1571 {
1572 int error, val;
1573
1574 val = zenbleed_enable;
1575 error = sysctl_handle_int(oidp, &val, 0, req);
1576 if (error != 0 || req->newptr == NULL)
1577 return (error);
1578 zenbleed_enable = val;
1579 zenbleed_sanitize_enable();
1580 zenbleed_check_and_apply(true);
1581 return (0);
1582 }
1583 SYSCTL_PROC(_machdep_mitigations_zenbleed, OID_AUTO, enable, CTLTYPE_INT |
1584 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1585 sysctl_zenbleed_enable_handler, "I",
1586 "Enable Zenbleed OS-triggered mitigation (chicken bit) "
1587 "(0: Force disable, 1: Force enable, 2: Automatic determination)");
1588
1589 static int
sysctl_zenbleed_state_handler(SYSCTL_HANDLER_ARGS)1590 sysctl_zenbleed_state_handler(SYSCTL_HANDLER_ARGS)
1591 {
1592 const char *state;
1593
1594 if (!zenbleed_chicken_bit_applicable())
1595 state = "Not applicable";
1596 else if (zenbleed_chicken_bit_should_enable())
1597 state = "Mitigation enabled";
1598 else
1599 state = "Mitigation disabled";
1600 return (SYSCTL_OUT(req, state, strlen(state)));
1601 }
1602 SYSCTL_PROC(_machdep_mitigations_zenbleed, OID_AUTO, state,
1603 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1604 sysctl_zenbleed_state_handler, "A",
1605 "Zenbleed OS-triggered mitigation (chicken bit) state");
1606
1607
1608 /*
1609 * Enable and restore kernel text write permissions.
1610 * Callers must ensure that disable_wp()/restore_wp() are executed
1611 * without rescheduling on the same core.
1612 */
1613 bool
disable_wp(void)1614 disable_wp(void)
1615 {
1616 u_int cr0;
1617
1618 cr0 = rcr0();
1619 if ((cr0 & CR0_WP) == 0)
1620 return (false);
1621 load_cr0(cr0 & ~CR0_WP);
1622 return (true);
1623 }
1624
1625 void
restore_wp(bool old_wp)1626 restore_wp(bool old_wp)
1627 {
1628
1629 if (old_wp)
1630 load_cr0(rcr0() | CR0_WP);
1631 }
1632
1633 bool
acpi_get_fadt_bootflags(uint16_t * flagsp)1634 acpi_get_fadt_bootflags(uint16_t *flagsp)
1635 {
1636 #ifdef DEV_ACPI
1637 ACPI_TABLE_FADT *fadt;
1638 vm_paddr_t physaddr;
1639
1640 physaddr = acpi_find_table(ACPI_SIG_FADT);
1641 if (physaddr == 0)
1642 return (false);
1643 fadt = acpi_map_table(physaddr, ACPI_SIG_FADT);
1644 if (fadt == NULL)
1645 return (false);
1646 *flagsp = fadt->BootFlags;
1647 acpi_unmap_table(fadt);
1648 return (true);
1649 #else
1650 return (false);
1651 #endif
1652 }
1653
1654 DEFINE_IFUNC(, uint64_t, rdtsc_ordered, (void))
1655 {
1656 bool cpu_is_amd = cpu_vendor_id == CPU_VENDOR_AMD ||
1657 cpu_vendor_id == CPU_VENDOR_HYGON;
1658
1659 if ((amd_feature & AMDID_RDTSCP) != 0)
1660 return (rdtscp);
1661 else if ((cpu_feature & CPUID_SSE2) != 0)
1662 return (cpu_is_amd ? rdtsc_ordered_mfence :
1663 rdtsc_ordered_lfence);
1664 else
1665 return (rdtsc);
1666 }
1667