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