]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/x86/cpu_machdep.c
Fix panic from Intel CPU vulnerability mitigation.
[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_atpic.h"
45 #include "opt_compat.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_perfmon.h"
55 #include "opt_platform.h"
56 #ifdef __i386__
57 #include "opt_apic.h"
58 #include "opt_xbox.h"
59 #endif
60
61 #include <sys/param.h>
62 #include <sys/proc.h>
63 #include <sys/systm.h>
64 #include <sys/bus.h>
65 #include <sys/cpu.h>
66 #include <sys/kdb.h>
67 #include <sys/kernel.h>
68 #include <sys/ktr.h>
69 #include <sys/lock.h>
70 #include <sys/malloc.h>
71 #include <sys/mutex.h>
72 #include <sys/pcpu.h>
73 #include <sys/rwlock.h>
74 #include <sys/sched.h>
75 #include <sys/smp.h>
76 #include <sys/sysctl.h>
77
78 #include <machine/clock.h>
79 #include <machine/cpu.h>
80 #include <machine/cputypes.h>
81 #include <machine/specialreg.h>
82 #include <machine/md_var.h>
83 #include <machine/mp_watchdog.h>
84 #ifdef PERFMON
85 #include <machine/perfmon.h>
86 #endif
87 #include <machine/tss.h>
88 #ifdef SMP
89 #include <machine/smp.h>
90 #endif
91 #ifdef CPU_ELAN
92 #include <machine/elan_mmcr.h>
93 #endif
94 #include <x86/acpica_machdep.h>
95
96 #include <vm/vm.h>
97 #include <vm/vm_extern.h>
98 #include <vm/vm_kern.h>
99 #include <vm/vm_page.h>
100 #include <vm/vm_map.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_pager.h>
103 #include <vm/vm_param.h>
104
105 #ifndef PC98
106 #include <isa/isareg.h>
107 #endif
108
109 #define STATE_RUNNING   0x0
110 #define STATE_MWAIT     0x1
111 #define STATE_SLEEPING  0x2
112
113 #ifdef SMP
114 static u_int    cpu_reset_proxyid;
115 static volatile u_int   cpu_reset_proxy_active;
116 #endif
117
118
119 /*
120  * Machine dependent boot() routine
121  *
122  * I haven't seen anything to put here yet
123  * Possibly some stuff might be grafted back here from boot()
124  */
125 void
126 cpu_boot(int howto)
127 {
128 }
129
130 /*
131  * Flush the D-cache for non-DMA I/O so that the I-cache can
132  * be made coherent later.
133  */
134 void
135 cpu_flush_dcache(void *ptr, size_t len)
136 {
137         /* Not applicable */
138 }
139
140 void
141 acpi_cpu_c1(void)
142 {
143
144         __asm __volatile("sti; hlt");
145 }
146
147 /*
148  * Use mwait to pause execution while waiting for an interrupt or
149  * another thread to signal that there is more work.
150  *
151  * NOTE: Interrupts will cause a wakeup; however, this function does
152  * not enable interrupt handling. The caller is responsible to enable
153  * interrupts.
154  */
155 void
156 acpi_cpu_idle_mwait(uint32_t mwait_hint)
157 {
158         int *state;
159         uint64_t v;
160
161         /*
162          * A comment in Linux patch claims that 'CPUs run faster with
163          * speculation protection disabled. All CPU threads in a core
164          * must disable speculation protection for it to be
165          * disabled. Disable it while we are idle so the other
166          * hyperthread can run fast.'
167          *
168          * XXXKIB.  Software coordination mode should be supported,
169          * but all Intel CPUs provide hardware coordination.
170          */
171
172         state = (int *)PCPU_PTR(monitorbuf);
173         KASSERT(atomic_load_int(state) == STATE_SLEEPING,
174             ("cpu_mwait_cx: wrong monitorbuf state"));
175         atomic_store_int(state, STATE_MWAIT);
176         if (PCPU_GET(ibpb_set) || hw_ssb_active) {
177                 v = rdmsr(MSR_IA32_SPEC_CTRL);
178                 wrmsr(MSR_IA32_SPEC_CTRL, v & ~(IA32_SPEC_CTRL_IBRS |
179                     IA32_SPEC_CTRL_STIBP | IA32_SPEC_CTRL_SSBD));
180         } else {
181                 v = 0;
182         }
183         cpu_monitor(state, 0, 0);
184         if (atomic_load_int(state) == STATE_MWAIT)
185                 cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
186
187         /*
188          * SSB cannot be disabled while we sleep, or rather, if it was
189          * disabled, the sysctl thread will bind to our cpu to tweak
190          * MSR.
191          */
192         if (v != 0)
193                 wrmsr(MSR_IA32_SPEC_CTRL, v);
194
195         /*
196          * We should exit on any event that interrupts mwait, because
197          * that event might be a wanted interrupt.
198          */
199         atomic_store_int(state, STATE_RUNNING);
200 }
201
202 /* Get current clock frequency for the given cpu id. */
203 int
204 cpu_est_clockrate(int cpu_id, uint64_t *rate)
205 {
206         uint64_t tsc1, tsc2;
207         uint64_t acnt, mcnt, perf;
208         register_t reg;
209
210         if (pcpu_find(cpu_id) == NULL || rate == NULL)
211                 return (EINVAL);
212 #ifdef __i386__
213         if ((cpu_feature & CPUID_TSC) == 0)
214                 return (EOPNOTSUPP);
215 #endif
216
217         /*
218          * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
219          * DELAY(9) based logic fails.
220          */
221         if (tsc_is_invariant && !tsc_perf_stat)
222                 return (EOPNOTSUPP);
223
224 #ifdef SMP
225         if (smp_cpus > 1) {
226                 /* Schedule ourselves on the indicated cpu. */
227                 thread_lock(curthread);
228                 sched_bind(curthread, cpu_id);
229                 thread_unlock(curthread);
230         }
231 #endif
232
233         /* Calibrate by measuring a short delay. */
234         reg = intr_disable();
235         if (tsc_is_invariant) {
236                 wrmsr(MSR_MPERF, 0);
237                 wrmsr(MSR_APERF, 0);
238                 tsc1 = rdtsc();
239                 DELAY(1000);
240                 mcnt = rdmsr(MSR_MPERF);
241                 acnt = rdmsr(MSR_APERF);
242                 tsc2 = rdtsc();
243                 intr_restore(reg);
244                 perf = 1000 * acnt / mcnt;
245                 *rate = (tsc2 - tsc1) * perf;
246         } else {
247                 tsc1 = rdtsc();
248                 DELAY(1000);
249                 tsc2 = rdtsc();
250                 intr_restore(reg);
251                 *rate = (tsc2 - tsc1) * 1000;
252         }
253
254 #ifdef SMP
255         if (smp_cpus > 1) {
256                 thread_lock(curthread);
257                 sched_unbind(curthread);
258                 thread_unlock(curthread);
259         }
260 #endif
261
262         return (0);
263 }
264
265 /*
266  * Shutdown the CPU as much as possible
267  */
268 void
269 cpu_halt(void)
270 {
271         for (;;)
272                 halt();
273 }
274
275 static void
276 cpu_reset_real(void)
277 {
278         struct region_descriptor null_idt;
279 #ifndef PC98
280         int b;
281 #endif
282
283         disable_intr();
284 #ifdef CPU_ELAN
285         if (elan_mmcr != NULL)
286                 elan_mmcr->RESCFG = 1;
287 #endif
288 #ifdef __i386__
289         if (cpu == CPU_GEODE1100) {
290                 /* Attempt Geode's own reset */
291                 outl(0xcf8, 0x80009044ul);
292                 outl(0xcfc, 0xf);
293         }
294 #endif
295 #ifdef PC98
296         /*
297          * Attempt to do a CPU reset via CPU reset port.
298          */
299         if ((inb(0x35) & 0xa0) != 0xa0) {
300                 outb(0x37, 0x0f);               /* SHUT0 = 0. */
301                 outb(0x37, 0x0b);               /* SHUT1 = 0. */
302         }
303         outb(0xf0, 0x00);                       /* Reset. */
304 #else
305 #if !defined(BROKEN_KEYBOARD_RESET)
306         /*
307          * Attempt to do a CPU reset via the keyboard controller,
308          * do not turn off GateA20, as any machine that fails
309          * to do the reset here would then end up in no man's land.
310          */
311         outb(IO_KBD + 4, 0xFE);
312         DELAY(500000);  /* wait 0.5 sec to see if that did it */
313 #endif
314
315         /*
316          * Attempt to force a reset via the Reset Control register at
317          * I/O port 0xcf9.  Bit 2 forces a system reset when it
318          * transitions from 0 to 1.  Bit 1 selects the type of reset
319          * to attempt: 0 selects a "soft" reset, and 1 selects a
320          * "hard" reset.  We try a "hard" reset.  The first write sets
321          * bit 1 to select a "hard" reset and clears bit 2.  The
322          * second write forces a 0 -> 1 transition in bit 2 to trigger
323          * a reset.
324          */
325         outb(0xcf9, 0x2);
326         outb(0xcf9, 0x6);
327         DELAY(500000);  /* wait 0.5 sec to see if that did it */
328
329         /*
330          * Attempt to force a reset via the Fast A20 and Init register
331          * at I/O port 0x92.  Bit 1 serves as an alternate A20 gate.
332          * Bit 0 asserts INIT# when set to 1.  We are careful to only
333          * preserve bit 1 while setting bit 0.  We also must clear bit
334          * 0 before setting it if it isn't already clear.
335          */
336         b = inb(0x92);
337         if (b != 0xff) {
338                 if ((b & 0x1) != 0)
339                         outb(0x92, b & 0xfe);
340                 outb(0x92, b | 0x1);
341                 DELAY(500000);  /* wait 0.5 sec to see if that did it */
342         }
343 #endif /* PC98 */
344
345         printf("No known reset method worked, attempting CPU shutdown\n");
346         DELAY(1000000); /* wait 1 sec for printf to complete */
347
348         /* Wipe the IDT. */
349         null_idt.rd_limit = 0;
350         null_idt.rd_base = 0;
351         lidt(&null_idt);
352
353         /* "good night, sweet prince .... <THUNK!>" */
354         breakpoint();
355
356         /* NOTREACHED */
357         while(1);
358 }
359
360 #ifdef SMP
361 static void
362 cpu_reset_proxy(void)
363 {
364
365         cpu_reset_proxy_active = 1;
366         while (cpu_reset_proxy_active == 1)
367                 ia32_pause(); /* Wait for other cpu to see that we've started */
368
369         printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
370         DELAY(1000000);
371         cpu_reset_real();
372 }
373 #endif
374
375 void
376 cpu_reset(void)
377 {
378 #ifdef SMP
379         cpuset_t map;
380         u_int cnt;
381
382         if (smp_started) {
383                 map = all_cpus;
384                 CPU_CLR(PCPU_GET(cpuid), &map);
385                 CPU_NAND(&map, &stopped_cpus);
386                 if (!CPU_EMPTY(&map)) {
387                         printf("cpu_reset: Stopping other CPUs\n");
388                         stop_cpus(map);
389                 }
390
391                 if (PCPU_GET(cpuid) != 0) {
392                         cpu_reset_proxyid = PCPU_GET(cpuid);
393                         cpustop_restartfunc = cpu_reset_proxy;
394                         cpu_reset_proxy_active = 0;
395                         printf("cpu_reset: Restarting BSP\n");
396
397                         /* Restart CPU #0. */
398                         CPU_SETOF(0, &started_cpus);
399                         wmb();
400
401                         cnt = 0;
402                         while (cpu_reset_proxy_active == 0 && cnt < 10000000) {
403                                 ia32_pause();
404                                 cnt++;  /* Wait for BSP to announce restart */
405                         }
406                         if (cpu_reset_proxy_active == 0) {
407                                 printf("cpu_reset: Failed to restart BSP\n");
408                         } else {
409                                 cpu_reset_proxy_active = 2;
410                                 while (1)
411                                         ia32_pause();
412                                 /* NOTREACHED */
413                         }
414                 }
415
416                 DELAY(1000000);
417         }
418 #endif
419         cpu_reset_real();
420         /* NOTREACHED */
421 }
422
423 bool
424 cpu_mwait_usable(void)
425 {
426
427         return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
428             (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
429             (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
430 }
431
432 void (*cpu_idle_hook)(sbintime_t) = NULL;       /* ACPI idle hook. */
433 static int      cpu_ident_amdc1e = 0;   /* AMD C1E supported. */
434 static int      idle_mwait = 1;         /* Use MONITOR/MWAIT for short idle. */
435 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
436     0, "Use MONITOR/MWAIT for short idle");
437
438 #ifndef PC98
439 static void
440 cpu_idle_acpi(sbintime_t sbt)
441 {
442         int *state;
443
444         state = (int *)PCPU_PTR(monitorbuf);
445         atomic_store_int(state, STATE_SLEEPING);
446
447         /* See comments in cpu_idle_hlt(). */
448         disable_intr();
449         if (sched_runnable())
450                 enable_intr();
451         else if (cpu_idle_hook)
452                 cpu_idle_hook(sbt);
453         else
454                 acpi_cpu_c1();
455         atomic_store_int(state, STATE_RUNNING);
456 }
457 #endif /* !PC98 */
458
459 static void
460 cpu_idle_hlt(sbintime_t sbt)
461 {
462         int *state;
463
464         state = (int *)PCPU_PTR(monitorbuf);
465         atomic_store_int(state, STATE_SLEEPING);
466
467         /*
468          * Since we may be in a critical section from cpu_idle(), if
469          * an interrupt fires during that critical section we may have
470          * a pending preemption.  If the CPU halts, then that thread
471          * may not execute until a later interrupt awakens the CPU.
472          * To handle this race, check for a runnable thread after
473          * disabling interrupts and immediately return if one is
474          * found.  Also, we must absolutely guarentee that hlt is
475          * the next instruction after sti.  This ensures that any
476          * interrupt that fires after the call to disable_intr() will
477          * immediately awaken the CPU from hlt.  Finally, please note
478          * that on x86 this works fine because of interrupts enabled only
479          * after the instruction following sti takes place, while IF is set
480          * to 1 immediately, allowing hlt instruction to acknowledge the
481          * interrupt.
482          */
483         disable_intr();
484         if (sched_runnable())
485                 enable_intr();
486         else
487                 acpi_cpu_c1();
488         atomic_store_int(state, STATE_RUNNING);
489 }
490
491 static void
492 cpu_idle_mwait(sbintime_t sbt)
493 {
494         int *state;
495
496         state = (int *)PCPU_PTR(monitorbuf);
497         atomic_store_int(state, STATE_MWAIT);
498
499         /* See comments in cpu_idle_hlt(). */
500         disable_intr();
501         if (sched_runnable()) {
502                 atomic_store_int(state, STATE_RUNNING);
503                 enable_intr();
504                 return;
505         }
506
507         cpu_monitor(state, 0, 0);
508         if (atomic_load_int(state) == STATE_MWAIT)
509                 __asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
510         else
511                 enable_intr();
512         atomic_store_int(state, STATE_RUNNING);
513 }
514
515 static void
516 cpu_idle_spin(sbintime_t sbt)
517 {
518         int *state;
519         int i;
520
521         state = (int *)PCPU_PTR(monitorbuf);
522         atomic_store_int(state, STATE_RUNNING);
523
524         /*
525          * The sched_runnable() call is racy but as long as there is
526          * a loop missing it one time will have just a little impact if any 
527          * (and it is much better than missing the check at all).
528          */
529         for (i = 0; i < 1000; i++) {
530                 if (sched_runnable())
531                         return;
532                 cpu_spinwait();
533         }
534 }
535
536 /*
537  * C1E renders the local APIC timer dead, so we disable it by
538  * reading the Interrupt Pending Message register and clearing
539  * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
540  * 
541  * Reference:
542  *   "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
543  *   #32559 revision 3.00+
544  */
545 #define MSR_AMDK8_IPM           0xc0010055
546 #define AMDK8_SMIONCMPHALT      (1ULL << 27)
547 #define AMDK8_C1EONCMPHALT      (1ULL << 28)
548 #define AMDK8_CMPHALT           (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
549
550 void
551 cpu_probe_amdc1e(void)
552 {
553
554         /*
555          * Detect the presence of C1E capability mostly on latest
556          * dual-cores (or future) k8 family.
557          */
558         if (cpu_vendor_id == CPU_VENDOR_AMD &&
559             (cpu_id & 0x00000f00) == 0x00000f00 &&
560             (cpu_id & 0x0fff0000) >=  0x00040000) {
561                 cpu_ident_amdc1e = 1;
562         }
563 }
564
565 #if defined(__i386__) && defined(PC98)
566 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_hlt;
567 #else
568 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
569 #endif
570
571 void
572 cpu_idle(int busy)
573 {
574         uint64_t msr;
575         sbintime_t sbt = -1;
576
577         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
578             busy, curcpu);
579 #ifdef MP_WATCHDOG
580         ap_watchdog(PCPU_GET(cpuid));
581 #endif
582
583         /* If we are busy - try to use fast methods. */
584         if (busy) {
585                 if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
586                         cpu_idle_mwait(busy);
587                         goto out;
588                 }
589         }
590
591         /* If we have time - switch timers into idle mode. */
592         if (!busy) {
593                 critical_enter();
594                 sbt = cpu_idleclock();
595         }
596
597         /* Apply AMD APIC timer C1E workaround. */
598         if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
599                 msr = rdmsr(MSR_AMDK8_IPM);
600                 if (msr & AMDK8_CMPHALT)
601                         wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
602         }
603
604         /* Call main idle method. */
605         cpu_idle_fn(sbt);
606
607         /* Switch timers back into active mode. */
608         if (!busy) {
609                 cpu_activeclock();
610                 critical_exit();
611         }
612 out:
613         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
614             busy, curcpu);
615 }
616
617 static int cpu_idle_apl31_workaround;
618 SYSCTL_INT(_machdep, OID_AUTO, idle_apl31, CTLFLAG_RW,
619     &cpu_idle_apl31_workaround, 0,
620     "Apollo Lake APL31 MWAIT bug workaround");
621
622 int
623 cpu_idle_wakeup(int cpu)
624 {
625         int *state;
626
627         state = (int *)pcpu_find(cpu)->pc_monitorbuf;
628         switch (atomic_load_int(state)) {
629         case STATE_SLEEPING:
630                 return (0);
631         case STATE_MWAIT:
632                 atomic_store_int(state, STATE_RUNNING);
633                 return (cpu_idle_apl31_workaround ? 0 : 1);
634         case STATE_RUNNING:
635                 return (1);
636         default:
637                 panic("bad monitor state");
638                 return (1);
639         }
640 }
641
642 /*
643  * Ordered by speed/power consumption.
644  */
645 static struct {
646         void    *id_fn;
647         char    *id_name;
648         int     id_cpuid2_flag;
649 } idle_tbl[] = {
650         { .id_fn = cpu_idle_spin, .id_name = "spin" },
651         { .id_fn = cpu_idle_mwait, .id_name = "mwait",
652             .id_cpuid2_flag = CPUID2_MON },
653         { .id_fn = cpu_idle_hlt, .id_name = "hlt" },
654 #if !defined(__i386__) || !defined(PC98)
655         { .id_fn = cpu_idle_acpi, .id_name = "acpi" },
656 #endif
657 };
658
659 static int
660 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
661 {
662         char *avail, *p;
663         int error;
664         int i;
665
666         avail = malloc(256, M_TEMP, M_WAITOK);
667         p = avail;
668         for (i = 0; i < nitems(idle_tbl); i++) {
669                 if (idle_tbl[i].id_cpuid2_flag != 0 &&
670                     (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
671                         continue;
672 #if !defined(__i386__) || !defined(PC98)
673                 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
674                     cpu_idle_hook == NULL)
675                         continue;
676 #endif
677                 p += sprintf(p, "%s%s", p != avail ? ", " : "",
678                     idle_tbl[i].id_name);
679         }
680         error = sysctl_handle_string(oidp, avail, 0, req);
681         free(avail, M_TEMP);
682         return (error);
683 }
684
685 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
686     0, 0, idle_sysctl_available, "A", "list of available idle functions");
687
688 static bool
689 cpu_idle_selector(const char *new_idle_name)
690 {
691         int i;
692
693         for (i = 0; i < nitems(idle_tbl); i++) {
694                 if (idle_tbl[i].id_cpuid2_flag != 0 &&
695                     (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
696                         continue;
697 #if !defined(__i386__) || !defined(PC98)
698                 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
699                     cpu_idle_hook == NULL)
700                         continue;
701 #endif
702                 if (strcmp(idle_tbl[i].id_name, new_idle_name))
703                         continue;
704                 cpu_idle_fn = idle_tbl[i].id_fn;
705                 if (bootverbose)
706                         printf("CPU idle set to %s\n", idle_tbl[i].id_name);
707                 return (true);
708         }
709         return (false);
710 }
711
712 static int
713 cpu_idle_sysctl(SYSCTL_HANDLER_ARGS)
714 {
715         char buf[16], *p;
716         int error, i;
717
718         p = "unknown";
719         for (i = 0; i < nitems(idle_tbl); i++) {
720                 if (idle_tbl[i].id_fn == cpu_idle_fn) {
721                         p = idle_tbl[i].id_name;
722                         break;
723                 }
724         }
725         strncpy(buf, p, sizeof(buf));
726         error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
727         if (error != 0 || req->newptr == NULL)
728                 return (error);
729         return (cpu_idle_selector(buf) ? 0 : EINVAL);
730 }
731
732 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
733     cpu_idle_sysctl, "A", "currently selected idle function");
734
735 static void
736 cpu_idle_tun(void *unused __unused)
737 {
738         char tunvar[16];
739
740         if (TUNABLE_STR_FETCH("machdep.idle", tunvar, sizeof(tunvar)))
741                 cpu_idle_selector(tunvar);
742         else if (cpu_vendor_id == CPU_VENDOR_AMD &&
743             CPUID_TO_FAMILY(cpu_id) == 0x17 && CPUID_TO_MODEL(cpu_id) == 0x1) {
744                 /* Ryzen erratas 1057, 1109. */
745                 cpu_idle_selector("hlt");
746                 idle_mwait = 0;
747         }
748
749         if (cpu_vendor_id == CPU_VENDOR_INTEL && cpu_id == 0x506c9) {
750                 /*
751                  * Apollo Lake errata APL31 (public errata APL30).
752                  * Stores to the armed address range may not trigger
753                  * MWAIT to resume execution.  OS needs to use
754                  * interrupts to wake processors from MWAIT-induced
755                  * sleep states.
756                  */
757                 cpu_idle_apl31_workaround = 1;
758         }
759         TUNABLE_INT_FETCH("machdep.idle_apl31", &cpu_idle_apl31_workaround);
760 }
761 SYSINIT(cpu_idle_tun, SI_SUB_CPU, SI_ORDER_MIDDLE, cpu_idle_tun, NULL);
762
763 static int panic_on_nmi = 1;
764 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
765     &panic_on_nmi, 0,
766     "Panic on NMI raised by hardware failure");
767 int nmi_is_broadcast = 1;
768 SYSCTL_INT(_machdep, OID_AUTO, nmi_is_broadcast, CTLFLAG_RWTUN,
769     &nmi_is_broadcast, 0,
770     "Chipset NMI is broadcast");
771 #ifdef KDB
772 int kdb_on_nmi = 1;
773 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
774     &kdb_on_nmi, 0,
775     "Go to KDB on NMI with unknown source");
776 #endif
777
778 void
779 nmi_call_kdb(u_int cpu, u_int type, struct trapframe *frame)
780 {
781         bool claimed = false;
782
783 #ifdef DEV_ISA
784         /* machine/parity/power fail/"kitchen sink" faults */
785         if (isa_nmi(frame->tf_err)) {
786                 claimed = true;
787                 if (panic_on_nmi)
788                         panic("NMI indicates hardware failure");
789         }
790 #endif /* DEV_ISA */
791 #ifdef KDB
792         if (!claimed && kdb_on_nmi) {
793                 /*
794                  * NMI can be hooked up to a pushbutton for debugging.
795                  */
796                 printf("NMI/cpu%d ... going to debugger\n", cpu);
797                 kdb_trap(type, 0, frame);
798         }
799 #endif /* KDB */
800 }
801
802 void
803 nmi_handle_intr(u_int type, struct trapframe *frame)
804 {
805
806 #ifdef SMP
807         if (nmi_is_broadcast) {
808                 nmi_call_kdb_smp(type, frame);
809                 return;
810         }
811 #endif
812         nmi_call_kdb(PCPU_GET(cpuid), type, frame);
813 }
814
815 int hw_ibrs_active;
816 int hw_ibrs_disable = 1;
817
818 SYSCTL_INT(_hw, OID_AUTO, ibrs_active, CTLFLAG_RD, &hw_ibrs_active, 0,
819     "Indirect Branch Restricted Speculation active");
820
821 void
822 hw_ibrs_recalculate(void)
823 {
824         uint64_t v;
825
826         if ((cpu_ia32_arch_caps & IA32_ARCH_CAP_IBRS_ALL) != 0) {
827                 if (hw_ibrs_disable) {
828                         v = rdmsr(MSR_IA32_SPEC_CTRL);
829                         v &= ~(uint64_t)IA32_SPEC_CTRL_IBRS;
830                         wrmsr(MSR_IA32_SPEC_CTRL, v);
831                 } else {
832                         v = rdmsr(MSR_IA32_SPEC_CTRL);
833                         v |= IA32_SPEC_CTRL_IBRS;
834                         wrmsr(MSR_IA32_SPEC_CTRL, v);
835                 }
836                 return;
837         }
838         hw_ibrs_active = (cpu_stdext_feature3 & CPUID_STDEXT3_IBPB) != 0 &&
839             !hw_ibrs_disable;
840 }
841
842 static int
843 hw_ibrs_disable_handler(SYSCTL_HANDLER_ARGS)
844 {
845         int error, val;
846
847         val = hw_ibrs_disable;
848         error = sysctl_handle_int(oidp, &val, 0, req);
849         if (error != 0 || req->newptr == NULL)
850                 return (error);
851         hw_ibrs_disable = val != 0;
852         hw_ibrs_recalculate();
853         return (0);
854 }
855 SYSCTL_PROC(_hw, OID_AUTO, ibrs_disable, CTLTYPE_INT | CTLFLAG_RWTUN |
856     CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0, hw_ibrs_disable_handler, "I",
857     "Disable Indirect Branch Restricted Speculation");
858
859 int hw_ssb_active;
860 int hw_ssb_disable;
861
862 SYSCTL_INT(_hw, OID_AUTO, spec_store_bypass_disable_active, CTLFLAG_RD,
863     &hw_ssb_active, 0,
864     "Speculative Store Bypass Disable active");
865
866 static void
867 hw_ssb_set_one(bool enable)
868 {
869         uint64_t v;
870
871         v = rdmsr(MSR_IA32_SPEC_CTRL);
872         if (enable)
873                 v |= (uint64_t)IA32_SPEC_CTRL_SSBD;
874         else
875                 v &= ~(uint64_t)IA32_SPEC_CTRL_SSBD;
876         wrmsr(MSR_IA32_SPEC_CTRL, v);
877 }
878
879 static void
880 hw_ssb_set(bool enable, bool for_all_cpus)
881 {
882         struct thread *td;
883         int bound_cpu, i, is_bound;
884
885         if ((cpu_stdext_feature3 & CPUID_STDEXT3_SSBD) == 0) {
886                 hw_ssb_active = 0;
887                 return;
888         }
889         hw_ssb_active = enable;
890         if (for_all_cpus) {
891                 td = curthread;
892                 thread_lock(td);
893                 is_bound = sched_is_bound(td);
894                 bound_cpu = td->td_oncpu;
895                 CPU_FOREACH(i) {
896                         sched_bind(td, i);
897                         hw_ssb_set_one(enable);
898                 }
899                 if (is_bound)
900                         sched_bind(td, bound_cpu);
901                 else
902                         sched_unbind(td);
903                 thread_unlock(td);
904         } else {
905                 hw_ssb_set_one(enable);
906         }
907 }
908
909 void
910 hw_ssb_recalculate(bool all_cpus)
911 {
912
913         switch (hw_ssb_disable) {
914         default:
915                 hw_ssb_disable = 0;
916                 /* FALLTHROUGH */
917         case 0: /* off */
918                 hw_ssb_set(false, all_cpus);
919                 break;
920         case 1: /* on */
921                 hw_ssb_set(true, all_cpus);
922                 break;
923         case 2: /* auto */
924                 hw_ssb_set((cpu_ia32_arch_caps & IA32_ARCH_CAP_SSB_NO) != 0 ?
925                     false : true, all_cpus);
926                 break;
927         }
928 }
929
930 static int
931 hw_ssb_disable_handler(SYSCTL_HANDLER_ARGS)
932 {
933         int error, val;
934
935         val = hw_ssb_disable;
936         error = sysctl_handle_int(oidp, &val, 0, req);
937         if (error != 0 || req->newptr == NULL)
938                 return (error);
939         hw_ssb_disable = val;
940         hw_ssb_recalculate(true);
941         return (0);
942 }
943 SYSCTL_PROC(_hw, OID_AUTO, spec_store_bypass_disable, CTLTYPE_INT |
944     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
945     hw_ssb_disable_handler, "I",
946     "Speculative Store Bypass Disable (0 - off, 1 - on, 2 - auto");
947
948 int hw_mds_disable;
949
950 /*
951  * Handler for Microarchitectural Data Sampling issues.  Really not a
952  * pointer to C function: on amd64 the code must not change any CPU
953  * architectural state except possibly %rflags. Also, it is always
954  * called with interrupts disabled.
955  */
956 void mds_handler_void(void);
957 void mds_handler_verw(void);
958 void mds_handler_ivb(void);
959 void mds_handler_bdw(void);
960 void mds_handler_skl_sse(void);
961 void mds_handler_skl_avx(void);
962 void mds_handler_skl_avx512(void);
963 void mds_handler_silvermont(void);
964 void (*mds_handler)(void) = mds_handler_void;
965
966 static int
967 sysctl_hw_mds_disable_state_handler(SYSCTL_HANDLER_ARGS)
968 {
969         const char *state;
970
971         if (mds_handler == mds_handler_void)
972                 state = "inactive";
973         else if (mds_handler == mds_handler_verw)
974                 state = "VERW";
975         else if (mds_handler == mds_handler_ivb)
976                 state = "software IvyBridge";
977         else if (mds_handler == mds_handler_bdw)
978                 state = "software Broadwell";
979         else if (mds_handler == mds_handler_skl_sse)
980                 state = "software Skylake SSE";
981         else if (mds_handler == mds_handler_skl_avx)
982                 state = "software Skylake AVX";
983         else if (mds_handler == mds_handler_skl_avx512)
984                 state = "software Skylake AVX512";
985         else if (mds_handler == mds_handler_silvermont)
986                 state = "software Silvermont";
987         else
988                 state = "unknown";
989         return (SYSCTL_OUT(req, state, strlen(state)));
990 }
991
992 SYSCTL_PROC(_hw, OID_AUTO, mds_disable_state,
993     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
994     sysctl_hw_mds_disable_state_handler, "A",
995     "Microarchitectural Data Sampling Mitigation state");
996
997 _Static_assert(__offsetof(struct pcpu, pc_mds_tmp) % 64 == 0, "MDS AVX512");
998
999 void
1000 hw_mds_recalculate(void)
1001 {
1002         struct pcpu *pc;
1003         vm_offset_t b64;
1004         u_long xcr0;
1005         int i;
1006
1007         /*
1008          * Allow user to force VERW variant even if MD_CLEAR is not
1009          * reported.  For instance, hypervisor might unknowingly
1010          * filter the cap out.
1011          * For the similar reasons, and for testing, allow to enable
1012          * mitigation even for RDCL_NO or MDS_NO caps.
1013          */
1014         if (cpu_vendor_id != CPU_VENDOR_INTEL || hw_mds_disable == 0 ||
1015             ((cpu_ia32_arch_caps & (IA32_ARCH_CAP_RDCL_NO |
1016             IA32_ARCH_CAP_MDS_NO)) != 0 && hw_mds_disable == 3)) {
1017                 mds_handler = mds_handler_void;
1018         } else if (((cpu_stdext_feature3 & CPUID_STDEXT3_MD_CLEAR) != 0 &&
1019             hw_mds_disable == 3) || hw_mds_disable == 1) {
1020                 mds_handler = mds_handler_verw;
1021         } else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1022             (CPUID_TO_MODEL(cpu_id) == 0x2e || CPUID_TO_MODEL(cpu_id) == 0x1e ||
1023             CPUID_TO_MODEL(cpu_id) == 0x1f || CPUID_TO_MODEL(cpu_id) == 0x1a ||
1024             CPUID_TO_MODEL(cpu_id) == 0x2f || CPUID_TO_MODEL(cpu_id) == 0x25 ||
1025             CPUID_TO_MODEL(cpu_id) == 0x2c || CPUID_TO_MODEL(cpu_id) == 0x2d ||
1026             CPUID_TO_MODEL(cpu_id) == 0x2a || CPUID_TO_MODEL(cpu_id) == 0x3e ||
1027             CPUID_TO_MODEL(cpu_id) == 0x3a) &&
1028             (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1029                 /*
1030                  * Nehalem, SandyBridge, IvyBridge
1031                  */
1032                 CPU_FOREACH(i) {
1033                         pc = pcpu_find(i);
1034                         if (pc->pc_mds_buf == NULL) {
1035                                 pc->pc_mds_buf = malloc(672, M_TEMP,
1036                                     M_WAITOK);
1037                                 bzero(pc->pc_mds_buf, 16);
1038                         }
1039                 }
1040                 mds_handler = mds_handler_ivb;
1041         } else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1042             (CPUID_TO_MODEL(cpu_id) == 0x3f || CPUID_TO_MODEL(cpu_id) == 0x3c ||
1043             CPUID_TO_MODEL(cpu_id) == 0x45 || CPUID_TO_MODEL(cpu_id) == 0x46 ||
1044             CPUID_TO_MODEL(cpu_id) == 0x56 || CPUID_TO_MODEL(cpu_id) == 0x4f ||
1045             CPUID_TO_MODEL(cpu_id) == 0x47 || CPUID_TO_MODEL(cpu_id) == 0x3d) &&
1046             (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1047                 /*
1048                  * Haswell, Broadwell
1049                  */
1050                 CPU_FOREACH(i) {
1051                         pc = pcpu_find(i);
1052                         if (pc->pc_mds_buf == NULL) {
1053                                 pc->pc_mds_buf = malloc(1536, M_TEMP,
1054                                     M_WAITOK);
1055                                 bzero(pc->pc_mds_buf, 16);
1056                         }
1057                 }
1058                 mds_handler = mds_handler_bdw;
1059         } else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1060             ((CPUID_TO_MODEL(cpu_id) == 0x55 && (cpu_id &
1061             CPUID_STEPPING) <= 5) ||
1062             CPUID_TO_MODEL(cpu_id) == 0x4e || CPUID_TO_MODEL(cpu_id) == 0x5e ||
1063             (CPUID_TO_MODEL(cpu_id) == 0x8e && (cpu_id &
1064             CPUID_STEPPING) <= 0xb) ||
1065             (CPUID_TO_MODEL(cpu_id) == 0x9e && (cpu_id &
1066             CPUID_STEPPING) <= 0xc)) &&
1067             (hw_mds_disable == 2 || hw_mds_disable == 3)) {
1068                 /*
1069                  * Skylake, KabyLake, CoffeeLake, WhiskeyLake,
1070                  * CascadeLake
1071                  */
1072                 CPU_FOREACH(i) {
1073                         pc = pcpu_find(i);
1074                         if (pc->pc_mds_buf == NULL) {
1075                                 pc->pc_mds_buf = malloc(6 * 1024,
1076                                     M_TEMP, M_WAITOK);
1077                                 b64 = (vm_offset_t)malloc(64 + 63,
1078                                     M_TEMP, M_WAITOK);
1079                                 pc->pc_mds_buf64 = (void *)roundup2(b64, 64);
1080                                 bzero(pc->pc_mds_buf64, 64);
1081                         }
1082                 }
1083                 xcr0 = rxcr(0);
1084                 if ((xcr0 & XFEATURE_ENABLED_ZMM_HI256) != 0 &&
1085                     (cpu_stdext_feature2 & CPUID_STDEXT_AVX512DQ) != 0)
1086                         mds_handler = mds_handler_skl_avx512;
1087                 else if ((xcr0 & XFEATURE_ENABLED_AVX) != 0 &&
1088                     (cpu_feature2 & CPUID2_AVX) != 0)
1089                         mds_handler = mds_handler_skl_avx;
1090                 else
1091                         mds_handler = mds_handler_skl_sse;
1092         } else if (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1093             ((CPUID_TO_MODEL(cpu_id) == 0x37 ||
1094             CPUID_TO_MODEL(cpu_id) == 0x4a ||
1095             CPUID_TO_MODEL(cpu_id) == 0x4c ||
1096             CPUID_TO_MODEL(cpu_id) == 0x4d ||
1097             CPUID_TO_MODEL(cpu_id) == 0x5a ||
1098             CPUID_TO_MODEL(cpu_id) == 0x5d ||
1099             CPUID_TO_MODEL(cpu_id) == 0x6e ||
1100             CPUID_TO_MODEL(cpu_id) == 0x65 ||
1101             CPUID_TO_MODEL(cpu_id) == 0x75 ||
1102             CPUID_TO_MODEL(cpu_id) == 0x1c ||
1103             CPUID_TO_MODEL(cpu_id) == 0x26 ||
1104             CPUID_TO_MODEL(cpu_id) == 0x27 ||
1105             CPUID_TO_MODEL(cpu_id) == 0x35 ||
1106             CPUID_TO_MODEL(cpu_id) == 0x36 ||
1107             CPUID_TO_MODEL(cpu_id) == 0x7a))) {
1108                 /* Silvermont, Airmont */
1109                 CPU_FOREACH(i) {
1110                         pc = pcpu_find(i);
1111                         if (pc->pc_mds_buf == NULL)
1112                                 pc->pc_mds_buf = malloc(256, M_TEMP, M_WAITOK);
1113                 }
1114                 mds_handler = mds_handler_silvermont;
1115         } else {
1116                 hw_mds_disable = 0;
1117                 mds_handler = mds_handler_void;
1118         }
1119 }
1120
1121 static void
1122 hw_mds_recalculate_boot(void *arg __unused)
1123 {
1124
1125         hw_mds_recalculate();
1126 }
1127 SYSINIT(mds_recalc, SI_SUB_SMP, SI_ORDER_ANY, hw_mds_recalculate_boot, NULL);
1128
1129 static int
1130 sysctl_mds_disable_handler(SYSCTL_HANDLER_ARGS)
1131 {
1132         int error, val;
1133
1134         val = hw_mds_disable;
1135         error = sysctl_handle_int(oidp, &val, 0, req);
1136         if (error != 0 || req->newptr == NULL)
1137                 return (error);
1138         if (val < 0 || val > 3)
1139                 return (EINVAL);
1140         hw_mds_disable = val;
1141         hw_mds_recalculate();
1142         return (0);
1143 }
1144
1145 SYSCTL_PROC(_hw, OID_AUTO, mds_disable, CTLTYPE_INT |
1146     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1147     sysctl_mds_disable_handler, "I",
1148     "Microarchitectural Data Sampling Mitigation "
1149     "(0 - off, 1 - on VERW, 2 - on SW, 3 - on AUTO");
1150