xref: /freebsd/sys/x86/x86/cpu_machdep.c (revision 8a0a413e)
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 	 * XXXKIB.  Software coordination mode should be supported,
146 	 * but all Intel CPUs provide hardware coordination.
147 	 */
148 
149 	state = (int *)PCPU_PTR(monitorbuf);
150 	KASSERT(*state == STATE_SLEEPING,
151 		("cpu_mwait_cx: wrong monitorbuf state"));
152 	*state = STATE_MWAIT;
153 	cpu_monitor(state, 0, 0);
154 	if (*state == STATE_MWAIT)
155 		cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
156 
157 	/*
158 	 * We should exit on any event that interrupts mwait, because
159 	 * that event might be a wanted interrupt.
160 	 */
161 	*state = STATE_RUNNING;
162 }
163 
164 /* Get current clock frequency for the given cpu id. */
165 int
166 cpu_est_clockrate(int cpu_id, uint64_t *rate)
167 {
168 	uint64_t tsc1, tsc2;
169 	uint64_t acnt, mcnt, perf;
170 	register_t reg;
171 
172 	if (pcpu_find(cpu_id) == NULL || rate == NULL)
173 		return (EINVAL);
174 #ifdef __i386__
175 	if ((cpu_feature & CPUID_TSC) == 0)
176 		return (EOPNOTSUPP);
177 #endif
178 
179 	/*
180 	 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
181 	 * DELAY(9) based logic fails.
182 	 */
183 	if (tsc_is_invariant && !tsc_perf_stat)
184 		return (EOPNOTSUPP);
185 
186 #ifdef SMP
187 	if (smp_cpus > 1) {
188 		/* Schedule ourselves on the indicated cpu. */
189 		thread_lock(curthread);
190 		sched_bind(curthread, cpu_id);
191 		thread_unlock(curthread);
192 	}
193 #endif
194 
195 	/* Calibrate by measuring a short delay. */
196 	reg = intr_disable();
197 	if (tsc_is_invariant) {
198 		wrmsr(MSR_MPERF, 0);
199 		wrmsr(MSR_APERF, 0);
200 		tsc1 = rdtsc();
201 		DELAY(1000);
202 		mcnt = rdmsr(MSR_MPERF);
203 		acnt = rdmsr(MSR_APERF);
204 		tsc2 = rdtsc();
205 		intr_restore(reg);
206 		perf = 1000 * acnt / mcnt;
207 		*rate = (tsc2 - tsc1) * perf;
208 	} else {
209 		tsc1 = rdtsc();
210 		DELAY(1000);
211 		tsc2 = rdtsc();
212 		intr_restore(reg);
213 		*rate = (tsc2 - tsc1) * 1000;
214 	}
215 
216 #ifdef SMP
217 	if (smp_cpus > 1) {
218 		thread_lock(curthread);
219 		sched_unbind(curthread);
220 		thread_unlock(curthread);
221 	}
222 #endif
223 
224 	return (0);
225 }
226 
227 /*
228  * Shutdown the CPU as much as possible
229  */
230 void
231 cpu_halt(void)
232 {
233 	for (;;)
234 		halt();
235 }
236 
237 bool
238 cpu_mwait_usable(void)
239 {
240 
241 	return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
242 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
243 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
244 }
245 
246 void (*cpu_idle_hook)(sbintime_t) = NULL;	/* ACPI idle hook. */
247 static int	cpu_ident_amdc1e = 0;	/* AMD C1E supported. */
248 static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
249 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
250     0, "Use MONITOR/MWAIT for short idle");
251 
252 static void
253 cpu_idle_acpi(sbintime_t sbt)
254 {
255 	int *state;
256 
257 	state = (int *)PCPU_PTR(monitorbuf);
258 	*state = STATE_SLEEPING;
259 
260 	/* See comments in cpu_idle_hlt(). */
261 	disable_intr();
262 	if (sched_runnable())
263 		enable_intr();
264 	else if (cpu_idle_hook)
265 		cpu_idle_hook(sbt);
266 	else
267 		acpi_cpu_c1();
268 	*state = STATE_RUNNING;
269 }
270 
271 static void
272 cpu_idle_hlt(sbintime_t sbt)
273 {
274 	int *state;
275 
276 	state = (int *)PCPU_PTR(monitorbuf);
277 	*state = STATE_SLEEPING;
278 
279 	/*
280 	 * Since we may be in a critical section from cpu_idle(), if
281 	 * an interrupt fires during that critical section we may have
282 	 * a pending preemption.  If the CPU halts, then that thread
283 	 * may not execute until a later interrupt awakens the CPU.
284 	 * To handle this race, check for a runnable thread after
285 	 * disabling interrupts and immediately return if one is
286 	 * found.  Also, we must absolutely guarentee that hlt is
287 	 * the next instruction after sti.  This ensures that any
288 	 * interrupt that fires after the call to disable_intr() will
289 	 * immediately awaken the CPU from hlt.  Finally, please note
290 	 * that on x86 this works fine because of interrupts enabled only
291 	 * after the instruction following sti takes place, while IF is set
292 	 * to 1 immediately, allowing hlt instruction to acknowledge the
293 	 * interrupt.
294 	 */
295 	disable_intr();
296 	if (sched_runnable())
297 		enable_intr();
298 	else
299 		acpi_cpu_c1();
300 	*state = STATE_RUNNING;
301 }
302 
303 static void
304 cpu_idle_mwait(sbintime_t sbt)
305 {
306 	int *state;
307 
308 	state = (int *)PCPU_PTR(monitorbuf);
309 	*state = STATE_MWAIT;
310 
311 	/* See comments in cpu_idle_hlt(). */
312 	disable_intr();
313 	if (sched_runnable()) {
314 		enable_intr();
315 		*state = STATE_RUNNING;
316 		return;
317 	}
318 	cpu_monitor(state, 0, 0);
319 	if (*state == STATE_MWAIT)
320 		__asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
321 	else
322 		enable_intr();
323 	*state = STATE_RUNNING;
324 }
325 
326 static void
327 cpu_idle_spin(sbintime_t sbt)
328 {
329 	int *state;
330 	int i;
331 
332 	state = (int *)PCPU_PTR(monitorbuf);
333 	*state = STATE_RUNNING;
334 
335 	/*
336 	 * The sched_runnable() call is racy but as long as there is
337 	 * a loop missing it one time will have just a little impact if any
338 	 * (and it is much better than missing the check at all).
339 	 */
340 	for (i = 0; i < 1000; i++) {
341 		if (sched_runnable())
342 			return;
343 		cpu_spinwait();
344 	}
345 }
346 
347 /*
348  * C1E renders the local APIC timer dead, so we disable it by
349  * reading the Interrupt Pending Message register and clearing
350  * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
351  *
352  * Reference:
353  *   "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
354  *   #32559 revision 3.00+
355  */
356 #define	MSR_AMDK8_IPM		0xc0010055
357 #define	AMDK8_SMIONCMPHALT	(1ULL << 27)
358 #define	AMDK8_C1EONCMPHALT	(1ULL << 28)
359 #define	AMDK8_CMPHALT		(AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
360 
361 void
362 cpu_probe_amdc1e(void)
363 {
364 
365 	/*
366 	 * Detect the presence of C1E capability mostly on latest
367 	 * dual-cores (or future) k8 family.
368 	 */
369 	if (cpu_vendor_id == CPU_VENDOR_AMD &&
370 	    (cpu_id & 0x00000f00) == 0x00000f00 &&
371 	    (cpu_id & 0x0fff0000) >=  0x00040000) {
372 		cpu_ident_amdc1e = 1;
373 	}
374 }
375 
376 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
377 
378 void
379 cpu_idle(int busy)
380 {
381 	uint64_t msr;
382 	sbintime_t sbt = -1;
383 
384 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
385 	    busy, curcpu);
386 #ifdef MP_WATCHDOG
387 	ap_watchdog(PCPU_GET(cpuid));
388 #endif
389 
390 	/* If we are busy - try to use fast methods. */
391 	if (busy) {
392 		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
393 			cpu_idle_mwait(busy);
394 			goto out;
395 		}
396 	}
397 
398 	/* If we have time - switch timers into idle mode. */
399 	if (!busy) {
400 		critical_enter();
401 		sbt = cpu_idleclock();
402 	}
403 
404 	/* Apply AMD APIC timer C1E workaround. */
405 	if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
406 		msr = rdmsr(MSR_AMDK8_IPM);
407 		if (msr & AMDK8_CMPHALT)
408 			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
409 	}
410 
411 	/* Call main idle method. */
412 	cpu_idle_fn(sbt);
413 
414 	/* Switch timers back into active mode. */
415 	if (!busy) {
416 		cpu_activeclock();
417 		critical_exit();
418 	}
419 out:
420 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
421 	    busy, curcpu);
422 }
423 
424 int
425 cpu_idle_wakeup(int cpu)
426 {
427 	struct pcpu *pcpu;
428 	int *state;
429 
430 	pcpu = pcpu_find(cpu);
431 	state = (int *)pcpu->pc_monitorbuf;
432 	/*
433 	 * This doesn't need to be atomic since missing the race will
434 	 * simply result in unnecessary IPIs.
435 	 */
436 	if (*state == STATE_SLEEPING)
437 		return (0);
438 	if (*state == STATE_MWAIT)
439 		*state = STATE_RUNNING;
440 	return (1);
441 }
442 
443 /*
444  * Ordered by speed/power consumption.
445  */
446 struct {
447 	void	*id_fn;
448 	char	*id_name;
449 } idle_tbl[] = {
450 	{ cpu_idle_spin, "spin" },
451 	{ cpu_idle_mwait, "mwait" },
452 	{ cpu_idle_hlt, "hlt" },
453 	{ cpu_idle_acpi, "acpi" },
454 	{ NULL, NULL }
455 };
456 
457 static int
458 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
459 {
460 	char *avail, *p;
461 	int error;
462 	int i;
463 
464 	avail = malloc(256, M_TEMP, M_WAITOK);
465 	p = avail;
466 	for (i = 0; idle_tbl[i].id_name != NULL; i++) {
467 		if (strstr(idle_tbl[i].id_name, "mwait") &&
468 		    (cpu_feature2 & CPUID2_MON) == 0)
469 			continue;
470 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
471 		    cpu_idle_hook == NULL)
472 			continue;
473 		p += sprintf(p, "%s%s", p != avail ? ", " : "",
474 		    idle_tbl[i].id_name);
475 	}
476 	error = sysctl_handle_string(oidp, avail, 0, req);
477 	free(avail, M_TEMP);
478 	return (error);
479 }
480 
481 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
482     0, 0, idle_sysctl_available, "A", "list of available idle functions");
483 
484 static int
485 idle_sysctl(SYSCTL_HANDLER_ARGS)
486 {
487 	char buf[16];
488 	int error;
489 	char *p;
490 	int i;
491 
492 	p = "unknown";
493 	for (i = 0; idle_tbl[i].id_name != NULL; i++) {
494 		if (idle_tbl[i].id_fn == cpu_idle_fn) {
495 			p = idle_tbl[i].id_name;
496 			break;
497 		}
498 	}
499 	strncpy(buf, p, sizeof(buf));
500 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
501 	if (error != 0 || req->newptr == NULL)
502 		return (error);
503 	for (i = 0; idle_tbl[i].id_name != NULL; i++) {
504 		if (strstr(idle_tbl[i].id_name, "mwait") &&
505 		    (cpu_feature2 & CPUID2_MON) == 0)
506 			continue;
507 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
508 		    cpu_idle_hook == NULL)
509 			continue;
510 		if (strcmp(idle_tbl[i].id_name, buf))
511 			continue;
512 		cpu_idle_fn = idle_tbl[i].id_fn;
513 		return (0);
514 	}
515 	return (EINVAL);
516 }
517 
518 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
519     idle_sysctl, "A", "currently selected idle function");
520 
521 static int panic_on_nmi = 1;
522 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
523     &panic_on_nmi, 0,
524     "Panic on NMI");
525 int nmi_is_broadcast = 1;
526 SYSCTL_INT(_machdep, OID_AUTO, nmi_is_broadcast, CTLFLAG_RWTUN,
527     &nmi_is_broadcast, 0,
528     "Chipset NMI is broadcast");
529 #ifdef KDB
530 int kdb_on_nmi = 1;
531 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
532     &kdb_on_nmi, 0,
533     "Go to KDB on NMI");
534 #endif
535 
536 #ifdef DEV_ISA
537 void
538 nmi_call_kdb(u_int cpu, u_int type, struct trapframe *frame)
539 {
540 
541 	/* machine/parity/power fail/"kitchen sink" faults */
542 	if (isa_nmi(frame->tf_err) == 0) {
543 #ifdef KDB
544 		/*
545 		 * NMI can be hooked up to a pushbutton for debugging.
546 		 */
547 		if (kdb_on_nmi) {
548 			printf("NMI/cpu%d ... going to debugger\n", cpu);
549 			kdb_trap(type, 0, frame);
550 		}
551 #endif /* KDB */
552 	} else if (panic_on_nmi) {
553 		panic("NMI indicates hardware failure");
554 	}
555 }
556 #endif
557 
558 void
559 nmi_handle_intr(u_int type, struct trapframe *frame)
560 {
561 
562 #ifdef DEV_ISA
563 #ifdef SMP
564 	if (nmi_is_broadcast) {
565 		nmi_call_kdb_smp(type, frame);
566 		return;
567 	}
568 #endif
569 	nmi_call_kdb(PCPU_GET(cpuid), type, frame);
570 #endif
571 }
572