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