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