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