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