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