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