]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/x86/cpu_machdep.c
MFV r329799, r329800:
[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_platform.h"
55 #ifdef __i386__
56 #include "opt_apic.h"
57 #endif
58
59 #include <sys/param.h>
60 #include <sys/proc.h>
61 #include <sys/systm.h>
62 #include <sys/bus.h>
63 #include <sys/cpu.h>
64 #include <sys/kdb.h>
65 #include <sys/kernel.h>
66 #include <sys/ktr.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mutex.h>
70 #include <sys/pcpu.h>
71 #include <sys/rwlock.h>
72 #include <sys/sched.h>
73 #ifdef SMP
74 #include <sys/smp.h>
75 #endif
76 #include <sys/sysctl.h>
77
78 #include <machine/clock.h>
79 #include <machine/cpu.h>
80 #include <machine/cputypes.h>
81 #include <machine/specialreg.h>
82 #include <machine/md_var.h>
83 #include <machine/mp_watchdog.h>
84 #include <machine/tss.h>
85 #ifdef SMP
86 #include <machine/smp.h>
87 #endif
88 #include <x86/acpica_machdep.h>
89
90 #include <vm/vm.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>
98
99 #define STATE_RUNNING   0x0
100 #define STATE_MWAIT     0x1
101 #define STATE_SLEEPING  0x2
102
103 /*
104  * Machine dependent boot() routine
105  *
106  * I haven't seen anything to put here yet
107  * Possibly some stuff might be grafted back here from boot()
108  */
109 void
110 cpu_boot(int howto)
111 {
112 }
113
114 /*
115  * Flush the D-cache for non-DMA I/O so that the I-cache can
116  * be made coherent later.
117  */
118 void
119 cpu_flush_dcache(void *ptr, size_t len)
120 {
121         /* Not applicable */
122 }
123
124 void
125 acpi_cpu_c1(void)
126 {
127
128         __asm __volatile("sti; hlt");
129 }
130
131 /*
132  * Use mwait to pause execution while waiting for an interrupt or
133  * another thread to signal that there is more work.
134  *
135  * NOTE: Interrupts will cause a wakeup; however, this function does
136  * not enable interrupt handling. The caller is responsible to enable
137  * interrupts.
138  */
139 void
140 acpi_cpu_idle_mwait(uint32_t mwait_hint)
141 {
142         int *state;
143
144         /*
145          * A comment in Linux patch claims that 'CPUs run faster with
146          * speculation protection disabled. All CPU threads in a core
147          * must disable speculation protection for it to be
148          * disabled. Disable it while we are idle so the other
149          * hyperthread can run fast.'
150          *
151          * XXXKIB.  Software coordination mode should be supported,
152          * but all Intel CPUs provide hardware coordination.
153          */
154
155         state = (int *)PCPU_PTR(monitorbuf);
156         KASSERT(*state == STATE_SLEEPING,
157                 ("cpu_mwait_cx: wrong monitorbuf state"));
158         *state = STATE_MWAIT;
159         handle_ibrs_entry();
160         cpu_monitor(state, 0, 0);
161         if (*state == STATE_MWAIT)
162                 cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
163         handle_ibrs_exit();
164
165         /*
166          * We should exit on any event that interrupts mwait, because
167          * that event might be a wanted interrupt.
168          */
169         *state = STATE_RUNNING;
170 }
171
172 /* Get current clock frequency for the given cpu id. */
173 int
174 cpu_est_clockrate(int cpu_id, uint64_t *rate)
175 {
176         uint64_t tsc1, tsc2;
177         uint64_t acnt, mcnt, perf;
178         register_t reg;
179
180         if (pcpu_find(cpu_id) == NULL || rate == NULL)
181                 return (EINVAL);
182 #ifdef __i386__
183         if ((cpu_feature & CPUID_TSC) == 0)
184                 return (EOPNOTSUPP);
185 #endif
186
187         /*
188          * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
189          * DELAY(9) based logic fails.
190          */
191         if (tsc_is_invariant && !tsc_perf_stat)
192                 return (EOPNOTSUPP);
193
194 #ifdef SMP
195         if (smp_cpus > 1) {
196                 /* Schedule ourselves on the indicated cpu. */
197                 thread_lock(curthread);
198                 sched_bind(curthread, cpu_id);
199                 thread_unlock(curthread);
200         }
201 #endif
202
203         /* Calibrate by measuring a short delay. */
204         reg = intr_disable();
205         if (tsc_is_invariant) {
206                 wrmsr(MSR_MPERF, 0);
207                 wrmsr(MSR_APERF, 0);
208                 tsc1 = rdtsc();
209                 DELAY(1000);
210                 mcnt = rdmsr(MSR_MPERF);
211                 acnt = rdmsr(MSR_APERF);
212                 tsc2 = rdtsc();
213                 intr_restore(reg);
214                 perf = 1000 * acnt / mcnt;
215                 *rate = (tsc2 - tsc1) * perf;
216         } else {
217                 tsc1 = rdtsc();
218                 DELAY(1000);
219                 tsc2 = rdtsc();
220                 intr_restore(reg);
221                 *rate = (tsc2 - tsc1) * 1000;
222         }
223
224 #ifdef SMP
225         if (smp_cpus > 1) {
226                 thread_lock(curthread);
227                 sched_unbind(curthread);
228                 thread_unlock(curthread);
229         }
230 #endif
231
232         return (0);
233 }
234
235 /*
236  * Shutdown the CPU as much as possible
237  */
238 void
239 cpu_halt(void)
240 {
241         for (;;)
242                 halt();
243 }
244
245 bool
246 cpu_mwait_usable(void)
247 {
248
249         return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
250             (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
251             (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
252 }
253
254 void (*cpu_idle_hook)(sbintime_t) = NULL;       /* ACPI idle hook. */
255 static int      cpu_ident_amdc1e = 0;   /* AMD C1E supported. */
256 static int      idle_mwait = 1;         /* Use MONITOR/MWAIT for short idle. */
257 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
258     0, "Use MONITOR/MWAIT for short idle");
259
260 static void
261 cpu_idle_acpi(sbintime_t sbt)
262 {
263         int *state;
264
265         state = (int *)PCPU_PTR(monitorbuf);
266         *state = STATE_SLEEPING;
267
268         /* See comments in cpu_idle_hlt(). */
269         disable_intr();
270         if (sched_runnable())
271                 enable_intr();
272         else if (cpu_idle_hook)
273                 cpu_idle_hook(sbt);
274         else
275                 acpi_cpu_c1();
276         *state = STATE_RUNNING;
277 }
278
279 static void
280 cpu_idle_hlt(sbintime_t sbt)
281 {
282         int *state;
283
284         state = (int *)PCPU_PTR(monitorbuf);
285         *state = STATE_SLEEPING;
286
287         /*
288          * Since we may be in a critical section from cpu_idle(), if
289          * an interrupt fires during that critical section we may have
290          * a pending preemption.  If the CPU halts, then that thread
291          * may not execute until a later interrupt awakens the CPU.
292          * To handle this race, check for a runnable thread after
293          * disabling interrupts and immediately return if one is
294          * found.  Also, we must absolutely guarentee that hlt is
295          * the next instruction after sti.  This ensures that any
296          * interrupt that fires after the call to disable_intr() will
297          * immediately awaken the CPU from hlt.  Finally, please note
298          * that on x86 this works fine because of interrupts enabled only
299          * after the instruction following sti takes place, while IF is set
300          * to 1 immediately, allowing hlt instruction to acknowledge the
301          * interrupt.
302          */
303         disable_intr();
304         if (sched_runnable())
305                 enable_intr();
306         else
307                 acpi_cpu_c1();
308         *state = STATE_RUNNING;
309 }
310
311 static void
312 cpu_idle_mwait(sbintime_t sbt)
313 {
314         int *state;
315
316         state = (int *)PCPU_PTR(monitorbuf);
317         *state = STATE_MWAIT;
318
319         /* See comments in cpu_idle_hlt(). */
320         disable_intr();
321         if (sched_runnable()) {
322                 enable_intr();
323                 *state = STATE_RUNNING;
324                 return;
325         }
326         cpu_monitor(state, 0, 0);
327         if (*state == STATE_MWAIT)
328                 __asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
329         else
330                 enable_intr();
331         *state = STATE_RUNNING;
332 }
333
334 static void
335 cpu_idle_spin(sbintime_t sbt)
336 {
337         int *state;
338         int i;
339
340         state = (int *)PCPU_PTR(monitorbuf);
341         *state = STATE_RUNNING;
342
343         /*
344          * The sched_runnable() call is racy but as long as there is
345          * a loop missing it one time will have just a little impact if any 
346          * (and it is much better than missing the check at all).
347          */
348         for (i = 0; i < 1000; i++) {
349                 if (sched_runnable())
350                         return;
351                 cpu_spinwait();
352         }
353 }
354
355 /*
356  * C1E renders the local APIC timer dead, so we disable it by
357  * reading the Interrupt Pending Message register and clearing
358  * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
359  * 
360  * Reference:
361  *   "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
362  *   #32559 revision 3.00+
363  */
364 #define MSR_AMDK8_IPM           0xc0010055
365 #define AMDK8_SMIONCMPHALT      (1ULL << 27)
366 #define AMDK8_C1EONCMPHALT      (1ULL << 28)
367 #define AMDK8_CMPHALT           (AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
368
369 void
370 cpu_probe_amdc1e(void)
371 {
372
373         /*
374          * Detect the presence of C1E capability mostly on latest
375          * dual-cores (or future) k8 family.
376          */
377         if (cpu_vendor_id == CPU_VENDOR_AMD &&
378             (cpu_id & 0x00000f00) == 0x00000f00 &&
379             (cpu_id & 0x0fff0000) >=  0x00040000) {
380                 cpu_ident_amdc1e = 1;
381         }
382 }
383
384 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
385
386 void
387 cpu_idle(int busy)
388 {
389         uint64_t msr;
390         sbintime_t sbt = -1;
391
392         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
393             busy, curcpu);
394 #ifdef MP_WATCHDOG
395         ap_watchdog(PCPU_GET(cpuid));
396 #endif
397
398         /* If we are busy - try to use fast methods. */
399         if (busy) {
400                 if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
401                         cpu_idle_mwait(busy);
402                         goto out;
403                 }
404         }
405
406         /* If we have time - switch timers into idle mode. */
407         if (!busy) {
408                 critical_enter();
409                 sbt = cpu_idleclock();
410         }
411
412         /* Apply AMD APIC timer C1E workaround. */
413         if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
414                 msr = rdmsr(MSR_AMDK8_IPM);
415                 if (msr & AMDK8_CMPHALT)
416                         wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
417         }
418
419         /* Call main idle method. */
420         cpu_idle_fn(sbt);
421
422         /* Switch timers back into active mode. */
423         if (!busy) {
424                 cpu_activeclock();
425                 critical_exit();
426         }
427 out:
428         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
429             busy, curcpu);
430 }
431
432 int
433 cpu_idle_wakeup(int cpu)
434 {
435         struct pcpu *pcpu;
436         int *state;
437
438         pcpu = pcpu_find(cpu);
439         state = (int *)pcpu->pc_monitorbuf;
440         /*
441          * This doesn't need to be atomic since missing the race will
442          * simply result in unnecessary IPIs.
443          */
444         if (*state == STATE_SLEEPING)
445                 return (0);
446         if (*state == STATE_MWAIT)
447                 *state = STATE_RUNNING;
448         return (1);
449 }
450
451 /*
452  * Ordered by speed/power consumption.
453  */
454 struct {
455         void    *id_fn;
456         char    *id_name;
457 } idle_tbl[] = {
458         { cpu_idle_spin, "spin" },
459         { cpu_idle_mwait, "mwait" },
460         { cpu_idle_hlt, "hlt" },
461         { cpu_idle_acpi, "acpi" },
462         { NULL, NULL }
463 };
464
465 static int
466 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
467 {
468         char *avail, *p;
469         int error;
470         int i;
471
472         avail = malloc(256, M_TEMP, M_WAITOK);
473         p = avail;
474         for (i = 0; idle_tbl[i].id_name != NULL; i++) {
475                 if (strstr(idle_tbl[i].id_name, "mwait") &&
476                     (cpu_feature2 & CPUID2_MON) == 0)
477                         continue;
478                 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
479                     cpu_idle_hook == NULL)
480                         continue;
481                 p += sprintf(p, "%s%s", p != avail ? ", " : "",
482                     idle_tbl[i].id_name);
483         }
484         error = sysctl_handle_string(oidp, avail, 0, req);
485         free(avail, M_TEMP);
486         return (error);
487 }
488
489 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
490     0, 0, idle_sysctl_available, "A", "list of available idle functions");
491
492 static int
493 idle_sysctl(SYSCTL_HANDLER_ARGS)
494 {
495         char buf[16];
496         int error;
497         char *p;
498         int i;
499
500         p = "unknown";
501         for (i = 0; idle_tbl[i].id_name != NULL; i++) {
502                 if (idle_tbl[i].id_fn == cpu_idle_fn) {
503                         p = idle_tbl[i].id_name;
504                         break;
505                 }
506         }
507         strncpy(buf, p, sizeof(buf));
508         error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
509         if (error != 0 || req->newptr == NULL)
510                 return (error);
511         for (i = 0; idle_tbl[i].id_name != NULL; i++) {
512                 if (strstr(idle_tbl[i].id_name, "mwait") &&
513                     (cpu_feature2 & CPUID2_MON) == 0)
514                         continue;
515                 if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
516                     cpu_idle_hook == NULL)
517                         continue;
518                 if (strcmp(idle_tbl[i].id_name, buf))
519                         continue;
520                 cpu_idle_fn = idle_tbl[i].id_fn;
521                 return (0);
522         }
523         return (EINVAL);
524 }
525
526 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
527     idle_sysctl, "A", "currently selected idle function");
528
529 static int panic_on_nmi = 1;
530 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
531     &panic_on_nmi, 0,
532     "Panic on NMI");
533 int nmi_is_broadcast = 1;
534 SYSCTL_INT(_machdep, OID_AUTO, nmi_is_broadcast, CTLFLAG_RWTUN,
535     &nmi_is_broadcast, 0,
536     "Chipset NMI is broadcast");
537 #ifdef KDB
538 int kdb_on_nmi = 1;
539 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
540     &kdb_on_nmi, 0,
541     "Go to KDB on NMI");
542 #endif
543
544 #ifdef DEV_ISA
545 void
546 nmi_call_kdb(u_int cpu, u_int type, struct trapframe *frame)
547 {
548
549         /* machine/parity/power fail/"kitchen sink" faults */
550         if (isa_nmi(frame->tf_err) == 0) {
551 #ifdef KDB
552                 /*
553                  * NMI can be hooked up to a pushbutton for debugging.
554                  */
555                 if (kdb_on_nmi) {
556                         printf("NMI/cpu%d ... going to debugger\n", cpu);
557                         kdb_trap(type, 0, frame);
558                 }
559 #endif /* KDB */
560         } else if (panic_on_nmi) {
561                 panic("NMI indicates hardware failure");
562         }
563 }
564 #endif
565
566 void
567 nmi_handle_intr(u_int type, struct trapframe *frame)
568 {
569
570 #ifdef DEV_ISA
571 #ifdef SMP
572         if (nmi_is_broadcast) {
573                 nmi_call_kdb_smp(type, frame);
574                 return;
575         }
576 #endif
577         nmi_call_kdb(PCPU_GET(cpuid), type, frame);
578 #endif
579 }
580
581 int hw_ibrs_active;
582 int hw_ibrs_disable = 1;
583
584 SYSCTL_INT(_hw, OID_AUTO, ibrs_active, CTLFLAG_RD, &hw_ibrs_active, 0,
585     "Indirect Branch Restricted Speculation active");
586
587 void
588 hw_ibrs_recalculate(void)
589 {
590         uint64_t v;
591
592         if ((cpu_ia32_arch_caps & IA32_ARCH_CAP_IBRS_ALL) != 0) {
593                 if (hw_ibrs_disable) {
594                         v= rdmsr(MSR_IA32_SPEC_CTRL);
595                         v &= ~(uint64_t)IA32_SPEC_CTRL_IBRS;
596                         wrmsr(MSR_IA32_SPEC_CTRL, v);
597                 } else {
598                         v= rdmsr(MSR_IA32_SPEC_CTRL);
599                         v |= IA32_SPEC_CTRL_IBRS;
600                         wrmsr(MSR_IA32_SPEC_CTRL, v);
601                 }
602                 return;
603         }
604         hw_ibrs_active = (cpu_stdext_feature3 & CPUID_STDEXT3_IBPB) != 0 &&
605             !hw_ibrs_disable;
606 }
607
608 static int
609 hw_ibrs_disable_handler(SYSCTL_HANDLER_ARGS)
610 {
611         int error, val;
612
613         val = hw_ibrs_disable;
614         error = sysctl_handle_int(oidp, &val, 0, req);
615         if (error != 0 || req->newptr == NULL)
616                 return (error);
617         hw_ibrs_disable = val != 0;
618         hw_ibrs_recalculate();
619         return (0);
620 }
621 SYSCTL_PROC(_hw, OID_AUTO, ibrs_disable, CTLTYPE_INT | CTLFLAG_RWTUN |
622     CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0, hw_ibrs_disable_handler, "I",
623     "Disable Indirect Branch Restricted Speculation");