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