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