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