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.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
38 * from: @(#)machdep.c 7.4 (Berkeley) 6/3/91
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
44 #include "opt_atpic.h"
50 #include "opt_kstack_pages.h"
51 #include "opt_maxmem.h"
52 #include "opt_mp_watchdog.h"
53 #include "opt_platform.h"
58 #include <sys/param.h>
60 #include <sys/systm.h>
64 #include <sys/kernel.h>
67 #include <sys/malloc.h>
68 #include <sys/mutex.h>
70 #include <sys/rwlock.h>
71 #include <sys/sched.h>
73 #include <sys/sysctl.h>
75 #include <machine/clock.h>
76 #include <machine/cpu.h>
77 #include <machine/cputypes.h>
78 #include <machine/specialreg.h>
79 #include <machine/md_var.h>
80 #include <machine/mp_watchdog.h>
81 #include <machine/tss.h>
83 #include <machine/smp.h>
86 #include <machine/elan_mmcr.h>
88 #include <x86/acpica_machdep.h>
91 #include <vm/vm_extern.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_map.h>
95 #include <vm/vm_object.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vm_param.h>
99 #include <isa/isareg.h>
101 #define STATE_RUNNING 0x0
102 #define STATE_MWAIT 0x1
103 #define STATE_SLEEPING 0x2
106 static u_int cpu_reset_proxyid;
107 static volatile u_int cpu_reset_proxy_active;
112 * Machine dependent boot() routine
114 * I haven't seen anything to put here yet
115 * Possibly some stuff might be grafted back here from boot()
123 * Flush the D-cache for non-DMA I/O so that the I-cache can
124 * be made coherent later.
127 cpu_flush_dcache(void *ptr, size_t len)
136 __asm __volatile("sti; hlt");
140 * Use mwait to pause execution while waiting for an interrupt or
141 * another thread to signal that there is more work.
143 * NOTE: Interrupts will cause a wakeup; however, this function does
144 * not enable interrupt handling. The caller is responsible to enable
148 acpi_cpu_idle_mwait(uint32_t mwait_hint)
154 * A comment in Linux patch claims that 'CPUs run faster with
155 * speculation protection disabled. All CPU threads in a core
156 * must disable speculation protection for it to be
157 * disabled. Disable it while we are idle so the other
158 * hyperthread can run fast.'
160 * XXXKIB. Software coordination mode should be supported,
161 * but all Intel CPUs provide hardware coordination.
164 state = (int *)PCPU_PTR(monitorbuf);
165 KASSERT(atomic_load_int(state) == STATE_SLEEPING,
166 ("cpu_mwait_cx: wrong monitorbuf state"));
167 atomic_store_int(state, STATE_MWAIT);
168 if (PCPU_GET(ibpb_set) || hw_ssb_active) {
169 v = rdmsr(MSR_IA32_SPEC_CTRL);
170 wrmsr(MSR_IA32_SPEC_CTRL, v & ~(IA32_SPEC_CTRL_IBRS |
171 IA32_SPEC_CTRL_STIBP | IA32_SPEC_CTRL_SSBD));
175 cpu_monitor(state, 0, 0);
176 if (atomic_load_int(state) == STATE_MWAIT)
177 cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
180 * SSB cannot be disabled while we sleep, or rather, if it was
181 * disabled, the sysctl thread will bind to our cpu to tweak
185 wrmsr(MSR_IA32_SPEC_CTRL, v);
188 * We should exit on any event that interrupts mwait, because
189 * that event might be a wanted interrupt.
191 atomic_store_int(state, STATE_RUNNING);
194 /* Get current clock frequency for the given cpu id. */
196 cpu_est_clockrate(int cpu_id, uint64_t *rate)
199 uint64_t acnt, mcnt, perf;
202 if (pcpu_find(cpu_id) == NULL || rate == NULL)
205 if ((cpu_feature & CPUID_TSC) == 0)
210 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
211 * DELAY(9) based logic fails.
213 if (tsc_is_invariant && !tsc_perf_stat)
218 /* Schedule ourselves on the indicated cpu. */
219 thread_lock(curthread);
220 sched_bind(curthread, cpu_id);
221 thread_unlock(curthread);
225 /* Calibrate by measuring a short delay. */
226 reg = intr_disable();
227 if (tsc_is_invariant) {
232 mcnt = rdmsr(MSR_MPERF);
233 acnt = rdmsr(MSR_APERF);
236 perf = 1000 * acnt / mcnt;
237 *rate = (tsc2 - tsc1) * perf;
243 *rate = (tsc2 - tsc1) * 1000;
248 thread_lock(curthread);
249 sched_unbind(curthread);
250 thread_unlock(curthread);
258 * Shutdown the CPU as much as possible
270 struct region_descriptor null_idt;
275 if (elan_mmcr != NULL)
276 elan_mmcr->RESCFG = 1;
279 if (cpu == CPU_GEODE1100) {
280 /* Attempt Geode's own reset */
281 outl(0xcf8, 0x80009044ul);
285 #if !defined(BROKEN_KEYBOARD_RESET)
287 * Attempt to do a CPU reset via the keyboard controller,
288 * do not turn off GateA20, as any machine that fails
289 * to do the reset here would then end up in no man's land.
291 outb(IO_KBD + 4, 0xFE);
292 DELAY(500000); /* wait 0.5 sec to see if that did it */
296 * Attempt to force a reset via the Reset Control register at
297 * I/O port 0xcf9. Bit 2 forces a system reset when it
298 * transitions from 0 to 1. Bit 1 selects the type of reset
299 * to attempt: 0 selects a "soft" reset, and 1 selects a
300 * "hard" reset. We try a "hard" reset. The first write sets
301 * bit 1 to select a "hard" reset and clears bit 2. The
302 * second write forces a 0 -> 1 transition in bit 2 to trigger
307 DELAY(500000); /* wait 0.5 sec to see if that did it */
310 * Attempt to force a reset via the Fast A20 and Init register
311 * at I/O port 0x92. Bit 1 serves as an alternate A20 gate.
312 * Bit 0 asserts INIT# when set to 1. We are careful to only
313 * preserve bit 1 while setting bit 0. We also must clear bit
314 * 0 before setting it if it isn't already clear.
319 outb(0x92, b & 0xfe);
321 DELAY(500000); /* wait 0.5 sec to see if that did it */
324 printf("No known reset method worked, attempting CPU shutdown\n");
325 DELAY(1000000); /* wait 1 sec for printf to complete */
328 null_idt.rd_limit = 0;
329 null_idt.rd_base = 0;
332 /* "good night, sweet prince .... <THUNK!>" */
341 cpu_reset_proxy(void)
344 cpu_reset_proxy_active = 1;
345 while (cpu_reset_proxy_active == 1)
346 ia32_pause(); /* Wait for other cpu to see that we've started */
348 printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
363 CPU_CLR(PCPU_GET(cpuid), &map);
364 CPU_NAND(&map, &stopped_cpus);
365 if (!CPU_EMPTY(&map)) {
366 printf("cpu_reset: Stopping other CPUs\n");
370 if (PCPU_GET(cpuid) != 0) {
371 cpu_reset_proxyid = PCPU_GET(cpuid);
372 cpustop_restartfunc = cpu_reset_proxy;
373 cpu_reset_proxy_active = 0;
374 printf("cpu_reset: Restarting BSP\n");
376 /* Restart CPU #0. */
377 CPU_SETOF(0, &started_cpus);
381 while (cpu_reset_proxy_active == 0 && cnt < 10000000) {
383 cnt++; /* Wait for BSP to announce restart */
385 if (cpu_reset_proxy_active == 0) {
386 printf("cpu_reset: Failed to restart BSP\n");
388 cpu_reset_proxy_active = 2;
403 cpu_mwait_usable(void)
406 return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
407 (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
408 (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
411 void (*cpu_idle_hook)(sbintime_t) = NULL; /* ACPI idle hook. */
412 static int cpu_ident_amdc1e = 0; /* AMD C1E supported. */
413 static int idle_mwait = 1; /* Use MONITOR/MWAIT for short idle. */
414 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
415 0, "Use MONITOR/MWAIT for short idle");
418 cpu_idle_acpi(sbintime_t sbt)
422 state = (int *)PCPU_PTR(monitorbuf);
423 atomic_store_int(state, STATE_SLEEPING);
425 /* See comments in cpu_idle_hlt(). */
427 if (sched_runnable())
429 else if (cpu_idle_hook)
433 atomic_store_int(state, STATE_RUNNING);
437 cpu_idle_hlt(sbintime_t sbt)
441 state = (int *)PCPU_PTR(monitorbuf);
442 atomic_store_int(state, STATE_SLEEPING);
445 * Since we may be in a critical section from cpu_idle(), if
446 * an interrupt fires during that critical section we may have
447 * a pending preemption. If the CPU halts, then that thread
448 * may not execute until a later interrupt awakens the CPU.
449 * To handle this race, check for a runnable thread after
450 * disabling interrupts and immediately return if one is
451 * found. Also, we must absolutely guarentee that hlt is
452 * the next instruction after sti. This ensures that any
453 * interrupt that fires after the call to disable_intr() will
454 * immediately awaken the CPU from hlt. Finally, please note
455 * that on x86 this works fine because of interrupts enabled only
456 * after the instruction following sti takes place, while IF is set
457 * to 1 immediately, allowing hlt instruction to acknowledge the
461 if (sched_runnable())
465 atomic_store_int(state, STATE_RUNNING);
469 cpu_idle_mwait(sbintime_t sbt)
473 state = (int *)PCPU_PTR(monitorbuf);
474 atomic_store_int(state, STATE_MWAIT);
476 /* See comments in cpu_idle_hlt(). */
478 if (sched_runnable()) {
479 atomic_store_int(state, STATE_RUNNING);
484 cpu_monitor(state, 0, 0);
485 if (atomic_load_int(state) == STATE_MWAIT)
486 __asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
489 atomic_store_int(state, STATE_RUNNING);
493 cpu_idle_spin(sbintime_t sbt)
498 state = (int *)PCPU_PTR(monitorbuf);
499 atomic_store_int(state, STATE_RUNNING);
502 * The sched_runnable() call is racy but as long as there is
503 * a loop missing it one time will have just a little impact if any
504 * (and it is much better than missing the check at all).
506 for (i = 0; i < 1000; i++) {
507 if (sched_runnable())
514 * C1E renders the local APIC timer dead, so we disable it by
515 * reading the Interrupt Pending Message register and clearing
516 * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
519 * "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
520 * #32559 revision 3.00+
522 #define MSR_AMDK8_IPM 0xc0010055
523 #define AMDK8_SMIONCMPHALT (1ULL << 27)
524 #define AMDK8_C1EONCMPHALT (1ULL << 28)
525 #define AMDK8_CMPHALT (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
528 cpu_probe_amdc1e(void)
532 * Detect the presence of C1E capability mostly on latest
533 * dual-cores (or future) k8 family.
535 if (cpu_vendor_id == CPU_VENDOR_AMD &&
536 (cpu_id & 0x00000f00) == 0x00000f00 &&
537 (cpu_id & 0x0fff0000) >= 0x00040000) {
538 cpu_ident_amdc1e = 1;
542 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
550 CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
553 ap_watchdog(PCPU_GET(cpuid));
556 /* If we are busy - try to use fast methods. */
558 if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
559 cpu_idle_mwait(busy);
564 /* If we have time - switch timers into idle mode. */
567 sbt = cpu_idleclock();
570 /* Apply AMD APIC timer C1E workaround. */
571 if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
572 msr = rdmsr(MSR_AMDK8_IPM);
573 if (msr & AMDK8_CMPHALT)
574 wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
577 /* Call main idle method. */
580 /* Switch timers back into active mode. */
586 CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
590 static int cpu_idle_apl31_workaround;
591 SYSCTL_INT(_machdep, OID_AUTO, idle_apl31, CTLFLAG_RW,
592 &cpu_idle_apl31_workaround, 0,
593 "Apollo Lake APL31 MWAIT bug workaround");
596 cpu_idle_wakeup(int cpu)
600 state = (int *)pcpu_find(cpu)->pc_monitorbuf;
601 switch (atomic_load_int(state)) {
605 atomic_store_int(state, STATE_RUNNING);
606 return (cpu_idle_apl31_workaround ? 0 : 1);
610 panic("bad monitor state");
616 * Ordered by speed/power consumption.
623 { .id_fn = cpu_idle_spin, .id_name = "spin" },
624 { .id_fn = cpu_idle_mwait, .id_name = "mwait",
625 .id_cpuid2_flag = CPUID2_MON },
626 { .id_fn = cpu_idle_hlt, .id_name = "hlt" },
627 { .id_fn = cpu_idle_acpi, .id_name = "acpi" },
631 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
637 avail = malloc(256, M_TEMP, M_WAITOK);
639 for (i = 0; i < nitems(idle_tbl); i++) {
640 if (idle_tbl[i].id_cpuid2_flag != 0 &&
641 (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
643 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
644 cpu_idle_hook == NULL)
646 p += sprintf(p, "%s%s", p != avail ? ", " : "",
647 idle_tbl[i].id_name);
649 error = sysctl_handle_string(oidp, avail, 0, req);
654 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
655 0, 0, idle_sysctl_available, "A", "list of available idle functions");
658 cpu_idle_selector(const char *new_idle_name)
662 for (i = 0; i < nitems(idle_tbl); i++) {
663 if (idle_tbl[i].id_cpuid2_flag != 0 &&
664 (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
666 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
667 cpu_idle_hook == NULL)
669 if (strcmp(idle_tbl[i].id_name, new_idle_name))
671 cpu_idle_fn = idle_tbl[i].id_fn;
673 printf("CPU idle set to %s\n", idle_tbl[i].id_name);
680 cpu_idle_sysctl(SYSCTL_HANDLER_ARGS)
686 for (i = 0; i < nitems(idle_tbl); i++) {
687 if (idle_tbl[i].id_fn == cpu_idle_fn) {
688 p = idle_tbl[i].id_name;
692 strncpy(buf, p, sizeof(buf));
693 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
694 if (error != 0 || req->newptr == NULL)
696 return (cpu_idle_selector(buf) ? 0 : EINVAL);
699 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
700 cpu_idle_sysctl, "A", "currently selected idle function");
703 cpu_idle_tun(void *unused __unused)
707 if (TUNABLE_STR_FETCH("machdep.idle", tunvar, sizeof(tunvar)))
708 cpu_idle_selector(tunvar);
709 if (cpu_vendor_id == CPU_VENDOR_INTEL && cpu_id == 0x506c9) {
711 * Apollo Lake errata APL31 (public errata APL30).
712 * Stores to the armed address range may not trigger
713 * MWAIT to resume execution. OS needs to use
714 * interrupts to wake processors from MWAIT-induced
717 cpu_idle_apl31_workaround = 1;
719 TUNABLE_INT_FETCH("machdep.idle_apl31", &cpu_idle_apl31_workaround);
721 SYSINIT(cpu_idle_tun, SI_SUB_CPU, SI_ORDER_MIDDLE, cpu_idle_tun, NULL);
723 static int panic_on_nmi = 1;
724 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
726 "Panic on NMI raised by hardware failure");
727 int nmi_is_broadcast = 1;
728 SYSCTL_INT(_machdep, OID_AUTO, nmi_is_broadcast, CTLFLAG_RWTUN,
729 &nmi_is_broadcast, 0,
730 "Chipset NMI is broadcast");
733 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
735 "Go to KDB on NMI with unknown source");
740 nmi_call_kdb(u_int cpu, u_int type, struct trapframe *frame)
743 /* machine/parity/power fail/"kitchen sink" faults */
744 if (isa_nmi(frame->tf_err) == 0) {
747 * NMI can be hooked up to a pushbutton for debugging.
750 printf("NMI/cpu%d ... going to debugger\n", cpu);
751 kdb_trap(type, 0, frame);
754 } else if (panic_on_nmi) {
755 panic("NMI indicates hardware failure");
761 nmi_handle_intr(u_int type, struct trapframe *frame)
766 if (nmi_is_broadcast) {
767 nmi_call_kdb_smp(type, frame);
771 nmi_call_kdb(PCPU_GET(cpuid), type, frame);
776 int hw_ibrs_disable = 1;
778 SYSCTL_INT(_hw, OID_AUTO, ibrs_active, CTLFLAG_RD, &hw_ibrs_active, 0,
779 "Indirect Branch Restricted Speculation active");
782 hw_ibrs_recalculate(void)
786 if ((cpu_ia32_arch_caps & IA32_ARCH_CAP_IBRS_ALL) != 0) {
787 if (hw_ibrs_disable) {
788 v = rdmsr(MSR_IA32_SPEC_CTRL);
789 v &= ~(uint64_t)IA32_SPEC_CTRL_IBRS;
790 wrmsr(MSR_IA32_SPEC_CTRL, v);
792 v = rdmsr(MSR_IA32_SPEC_CTRL);
793 v |= IA32_SPEC_CTRL_IBRS;
794 wrmsr(MSR_IA32_SPEC_CTRL, v);
798 hw_ibrs_active = (cpu_stdext_feature3 & CPUID_STDEXT3_IBPB) != 0 &&
803 hw_ibrs_disable_handler(SYSCTL_HANDLER_ARGS)
807 val = hw_ibrs_disable;
808 error = sysctl_handle_int(oidp, &val, 0, req);
809 if (error != 0 || req->newptr == NULL)
811 hw_ibrs_disable = val != 0;
812 hw_ibrs_recalculate();
815 SYSCTL_PROC(_hw, OID_AUTO, ibrs_disable, CTLTYPE_INT | CTLFLAG_RWTUN |
816 CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0, hw_ibrs_disable_handler, "I",
817 "Disable Indirect Branch Restricted Speculation");
822 SYSCTL_INT(_hw, OID_AUTO, spec_store_bypass_disable_active, CTLFLAG_RD,
824 "Speculative Store Bypass Disable active");
827 hw_ssb_set_one(bool enable)
831 v = rdmsr(MSR_IA32_SPEC_CTRL);
833 v |= (uint64_t)IA32_SPEC_CTRL_SSBD;
835 v &= ~(uint64_t)IA32_SPEC_CTRL_SSBD;
836 wrmsr(MSR_IA32_SPEC_CTRL, v);
840 hw_ssb_set(bool enable, bool for_all_cpus)
843 int bound_cpu, i, is_bound;
845 if ((cpu_stdext_feature3 & CPUID_STDEXT3_SSBD) == 0) {
849 hw_ssb_active = enable;
853 is_bound = sched_is_bound(td);
854 bound_cpu = td->td_oncpu;
857 hw_ssb_set_one(enable);
860 sched_bind(td, bound_cpu);
865 hw_ssb_set_one(enable);
870 hw_ssb_recalculate(bool all_cpus)
873 switch (hw_ssb_disable) {
878 hw_ssb_set(false, all_cpus);
881 hw_ssb_set(true, all_cpus);
884 hw_ssb_set((cpu_ia32_arch_caps & IA32_ARCH_CAP_SSBD_NO) != 0 ?
885 false : true, all_cpus);
891 hw_ssb_disable_handler(SYSCTL_HANDLER_ARGS)
895 val = hw_ssb_disable;
896 error = sysctl_handle_int(oidp, &val, 0, req);
897 if (error != 0 || req->newptr == NULL)
899 hw_ssb_disable = val;
900 hw_ssb_recalculate(true);
903 SYSCTL_PROC(_hw, OID_AUTO, spec_store_bypass_disable, CTLTYPE_INT |
904 CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
905 hw_ssb_disable_handler, "I",
906 "Speculative Store Bypass Disable (0 - off, 1 - on, 2 - auto");
909 * Enable and restore kernel text write permissions.
910 * Callers must ensure that disable_wp()/restore_wp() are executed
911 * without rescheduling on the same core.
919 if ((cr0 & CR0_WP) == 0)
921 load_cr0(cr0 & ~CR0_WP);
926 restore_wp(bool old_wp)
930 load_cr0(rcr0() | CR0_WP);