xref: /freebsd/sys/x86/x86/cpu_machdep.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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_acpi.h"
45 #include "opt_atpic.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 #include <sys/smp.h>
74 #include <sys/sysctl.h>
75 
76 #include <machine/clock.h>
77 #include <machine/cpu.h>
78 #include <machine/cputypes.h>
79 #include <machine/specialreg.h>
80 #include <machine/md_var.h>
81 #include <machine/mp_watchdog.h>
82 #include <machine/tss.h>
83 #ifdef SMP
84 #include <machine/smp.h>
85 #endif
86 #ifdef CPU_ELAN
87 #include <machine/elan_mmcr.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 #include <isa/isareg.h>
101 
102 #include <contrib/dev/acpica/include/acpi.h>
103 
104 #define	STATE_RUNNING	0x0
105 #define	STATE_MWAIT	0x1
106 #define	STATE_SLEEPING	0x2
107 
108 #ifdef SMP
109 static u_int	cpu_reset_proxyid;
110 static volatile u_int	cpu_reset_proxy_active;
111 #endif
112 
113 
114 /*
115  * Machine dependent boot() routine
116  *
117  * I haven't seen anything to put here yet
118  * Possibly some stuff might be grafted back here from boot()
119  */
120 void
121 cpu_boot(int howto)
122 {
123 }
124 
125 /*
126  * Flush the D-cache for non-DMA I/O so that the I-cache can
127  * be made coherent later.
128  */
129 void
130 cpu_flush_dcache(void *ptr, size_t len)
131 {
132 	/* Not applicable */
133 }
134 
135 void
136 acpi_cpu_c1(void)
137 {
138 
139 	__asm __volatile("sti; hlt");
140 }
141 
142 /*
143  * Use mwait to pause execution while waiting for an interrupt or
144  * another thread to signal that there is more work.
145  *
146  * NOTE: Interrupts will cause a wakeup; however, this function does
147  * not enable interrupt handling. The caller is responsible to enable
148  * interrupts.
149  */
150 void
151 acpi_cpu_idle_mwait(uint32_t mwait_hint)
152 {
153 	int *state;
154 	uint64_t v;
155 
156 	/*
157 	 * A comment in Linux patch claims that 'CPUs run faster with
158 	 * speculation protection disabled. All CPU threads in a core
159 	 * must disable speculation protection for it to be
160 	 * disabled. Disable it while we are idle so the other
161 	 * hyperthread can run fast.'
162 	 *
163 	 * XXXKIB.  Software coordination mode should be supported,
164 	 * but all Intel CPUs provide hardware coordination.
165 	 */
166 
167 	state = (int *)PCPU_PTR(monitorbuf);
168 	KASSERT(atomic_load_int(state) == STATE_SLEEPING,
169 	    ("cpu_mwait_cx: wrong monitorbuf state"));
170 	atomic_store_int(state, STATE_MWAIT);
171 	if (PCPU_GET(ibpb_set) || hw_ssb_active) {
172 		v = rdmsr(MSR_IA32_SPEC_CTRL);
173 		wrmsr(MSR_IA32_SPEC_CTRL, v & ~(IA32_SPEC_CTRL_IBRS |
174 		    IA32_SPEC_CTRL_STIBP | IA32_SPEC_CTRL_SSBD));
175 	} else {
176 		v = 0;
177 	}
178 	cpu_monitor(state, 0, 0);
179 	if (atomic_load_int(state) == STATE_MWAIT)
180 		cpu_mwait(MWAIT_INTRBREAK, mwait_hint);
181 
182 	/*
183 	 * SSB cannot be disabled while we sleep, or rather, if it was
184 	 * disabled, the sysctl thread will bind to our cpu to tweak
185 	 * MSR.
186 	 */
187 	if (v != 0)
188 		wrmsr(MSR_IA32_SPEC_CTRL, v);
189 
190 	/*
191 	 * We should exit on any event that interrupts mwait, because
192 	 * that event might be a wanted interrupt.
193 	 */
194 	atomic_store_int(state, STATE_RUNNING);
195 }
196 
197 /* Get current clock frequency for the given cpu id. */
198 int
199 cpu_est_clockrate(int cpu_id, uint64_t *rate)
200 {
201 	uint64_t tsc1, tsc2;
202 	uint64_t acnt, mcnt, perf;
203 	register_t reg;
204 
205 	if (pcpu_find(cpu_id) == NULL || rate == NULL)
206 		return (EINVAL);
207 #ifdef __i386__
208 	if ((cpu_feature & CPUID_TSC) == 0)
209 		return (EOPNOTSUPP);
210 #endif
211 
212 	/*
213 	 * If TSC is P-state invariant and APERF/MPERF MSRs do not exist,
214 	 * DELAY(9) based logic fails.
215 	 */
216 	if (tsc_is_invariant && !tsc_perf_stat)
217 		return (EOPNOTSUPP);
218 
219 #ifdef SMP
220 	if (smp_cpus > 1) {
221 		/* Schedule ourselves on the indicated cpu. */
222 		thread_lock(curthread);
223 		sched_bind(curthread, cpu_id);
224 		thread_unlock(curthread);
225 	}
226 #endif
227 
228 	/* Calibrate by measuring a short delay. */
229 	reg = intr_disable();
230 	if (tsc_is_invariant) {
231 		wrmsr(MSR_MPERF, 0);
232 		wrmsr(MSR_APERF, 0);
233 		tsc1 = rdtsc();
234 		DELAY(1000);
235 		mcnt = rdmsr(MSR_MPERF);
236 		acnt = rdmsr(MSR_APERF);
237 		tsc2 = rdtsc();
238 		intr_restore(reg);
239 		perf = 1000 * acnt / mcnt;
240 		*rate = (tsc2 - tsc1) * perf;
241 	} else {
242 		tsc1 = rdtsc();
243 		DELAY(1000);
244 		tsc2 = rdtsc();
245 		intr_restore(reg);
246 		*rate = (tsc2 - tsc1) * 1000;
247 	}
248 
249 #ifdef SMP
250 	if (smp_cpus > 1) {
251 		thread_lock(curthread);
252 		sched_unbind(curthread);
253 		thread_unlock(curthread);
254 	}
255 #endif
256 
257 	return (0);
258 }
259 
260 /*
261  * Shutdown the CPU as much as possible
262  */
263 void
264 cpu_halt(void)
265 {
266 	for (;;)
267 		halt();
268 }
269 
270 static void
271 cpu_reset_real(void)
272 {
273 	struct region_descriptor null_idt;
274 	int b;
275 
276 	disable_intr();
277 #ifdef CPU_ELAN
278 	if (elan_mmcr != NULL)
279 		elan_mmcr->RESCFG = 1;
280 #endif
281 #ifdef __i386__
282 	if (cpu == CPU_GEODE1100) {
283 		/* Attempt Geode's own reset */
284 		outl(0xcf8, 0x80009044ul);
285 		outl(0xcfc, 0xf);
286 	}
287 #endif
288 #if !defined(BROKEN_KEYBOARD_RESET)
289 	/*
290 	 * Attempt to do a CPU reset via the keyboard controller,
291 	 * do not turn off GateA20, as any machine that fails
292 	 * to do the reset here would then end up in no man's land.
293 	 */
294 	outb(IO_KBD + 4, 0xFE);
295 	DELAY(500000);	/* wait 0.5 sec to see if that did it */
296 #endif
297 
298 	/*
299 	 * Attempt to force a reset via the Reset Control register at
300 	 * I/O port 0xcf9.  Bit 2 forces a system reset when it
301 	 * transitions from 0 to 1.  Bit 1 selects the type of reset
302 	 * to attempt: 0 selects a "soft" reset, and 1 selects a
303 	 * "hard" reset.  We try a "hard" reset.  The first write sets
304 	 * bit 1 to select a "hard" reset and clears bit 2.  The
305 	 * second write forces a 0 -> 1 transition in bit 2 to trigger
306 	 * a reset.
307 	 */
308 	outb(0xcf9, 0x2);
309 	outb(0xcf9, 0x6);
310 	DELAY(500000);  /* wait 0.5 sec to see if that did it */
311 
312 	/*
313 	 * Attempt to force a reset via the Fast A20 and Init register
314 	 * at I/O port 0x92.  Bit 1 serves as an alternate A20 gate.
315 	 * Bit 0 asserts INIT# when set to 1.  We are careful to only
316 	 * preserve bit 1 while setting bit 0.  We also must clear bit
317 	 * 0 before setting it if it isn't already clear.
318 	 */
319 	b = inb(0x92);
320 	if (b != 0xff) {
321 		if ((b & 0x1) != 0)
322 			outb(0x92, b & 0xfe);
323 		outb(0x92, b | 0x1);
324 		DELAY(500000);  /* wait 0.5 sec to see if that did it */
325 	}
326 
327 	printf("No known reset method worked, attempting CPU shutdown\n");
328 	DELAY(1000000); /* wait 1 sec for printf to complete */
329 
330 	/* Wipe the IDT. */
331 	null_idt.rd_limit = 0;
332 	null_idt.rd_base = 0;
333 	lidt(&null_idt);
334 
335 	/* "good night, sweet prince .... <THUNK!>" */
336 	breakpoint();
337 
338 	/* NOTREACHED */
339 	while(1);
340 }
341 
342 #ifdef SMP
343 static void
344 cpu_reset_proxy(void)
345 {
346 
347 	cpu_reset_proxy_active = 1;
348 	while (cpu_reset_proxy_active == 1)
349 		ia32_pause(); /* Wait for other cpu to see that we've started */
350 
351 	printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
352 	DELAY(1000000);
353 	cpu_reset_real();
354 }
355 #endif
356 
357 void
358 cpu_reset(void)
359 {
360 #ifdef SMP
361 	cpuset_t map;
362 	u_int cnt;
363 
364 	if (smp_started) {
365 		map = all_cpus;
366 		CPU_CLR(PCPU_GET(cpuid), &map);
367 		CPU_NAND(&map, &stopped_cpus);
368 		if (!CPU_EMPTY(&map)) {
369 			printf("cpu_reset: Stopping other CPUs\n");
370 			stop_cpus(map);
371 		}
372 
373 		if (PCPU_GET(cpuid) != 0) {
374 			cpu_reset_proxyid = PCPU_GET(cpuid);
375 			cpustop_restartfunc = cpu_reset_proxy;
376 			cpu_reset_proxy_active = 0;
377 			printf("cpu_reset: Restarting BSP\n");
378 
379 			/* Restart CPU #0. */
380 			CPU_SETOF(0, &started_cpus);
381 			wmb();
382 
383 			cnt = 0;
384 			while (cpu_reset_proxy_active == 0 && cnt < 10000000) {
385 				ia32_pause();
386 				cnt++;	/* Wait for BSP to announce restart */
387 			}
388 			if (cpu_reset_proxy_active == 0) {
389 				printf("cpu_reset: Failed to restart BSP\n");
390 			} else {
391 				cpu_reset_proxy_active = 2;
392 				while (1)
393 					ia32_pause();
394 				/* NOTREACHED */
395 			}
396 		}
397 
398 		DELAY(1000000);
399 	}
400 #endif
401 	cpu_reset_real();
402 	/* NOTREACHED */
403 }
404 
405 bool
406 cpu_mwait_usable(void)
407 {
408 
409 	return ((cpu_feature2 & CPUID2_MON) != 0 && ((cpu_mon_mwait_flags &
410 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)) ==
411 	    (CPUID5_MON_MWAIT_EXT | CPUID5_MWAIT_INTRBREAK)));
412 }
413 
414 void (*cpu_idle_hook)(sbintime_t) = NULL;	/* ACPI idle hook. */
415 static int	cpu_ident_amdc1e = 0;	/* AMD C1E supported. */
416 static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
417 SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RWTUN, &idle_mwait,
418     0, "Use MONITOR/MWAIT for short idle");
419 
420 static void
421 cpu_idle_acpi(sbintime_t sbt)
422 {
423 	int *state;
424 
425 	state = (int *)PCPU_PTR(monitorbuf);
426 	atomic_store_int(state, STATE_SLEEPING);
427 
428 	/* See comments in cpu_idle_hlt(). */
429 	disable_intr();
430 	if (sched_runnable())
431 		enable_intr();
432 	else if (cpu_idle_hook)
433 		cpu_idle_hook(sbt);
434 	else
435 		acpi_cpu_c1();
436 	atomic_store_int(state, STATE_RUNNING);
437 }
438 
439 static void
440 cpu_idle_hlt(sbintime_t sbt)
441 {
442 	int *state;
443 
444 	state = (int *)PCPU_PTR(monitorbuf);
445 	atomic_store_int(state, STATE_SLEEPING);
446 
447 	/*
448 	 * Since we may be in a critical section from cpu_idle(), if
449 	 * an interrupt fires during that critical section we may have
450 	 * a pending preemption.  If the CPU halts, then that thread
451 	 * may not execute until a later interrupt awakens the CPU.
452 	 * To handle this race, check for a runnable thread after
453 	 * disabling interrupts and immediately return if one is
454 	 * found.  Also, we must absolutely guarentee that hlt is
455 	 * the next instruction after sti.  This ensures that any
456 	 * interrupt that fires after the call to disable_intr() will
457 	 * immediately awaken the CPU from hlt.  Finally, please note
458 	 * that on x86 this works fine because of interrupts enabled only
459 	 * after the instruction following sti takes place, while IF is set
460 	 * to 1 immediately, allowing hlt instruction to acknowledge the
461 	 * interrupt.
462 	 */
463 	disable_intr();
464 	if (sched_runnable())
465 		enable_intr();
466 	else
467 		acpi_cpu_c1();
468 	atomic_store_int(state, STATE_RUNNING);
469 }
470 
471 static void
472 cpu_idle_mwait(sbintime_t sbt)
473 {
474 	int *state;
475 
476 	state = (int *)PCPU_PTR(monitorbuf);
477 	atomic_store_int(state, STATE_MWAIT);
478 
479 	/* See comments in cpu_idle_hlt(). */
480 	disable_intr();
481 	if (sched_runnable()) {
482 		atomic_store_int(state, STATE_RUNNING);
483 		enable_intr();
484 		return;
485 	}
486 
487 	cpu_monitor(state, 0, 0);
488 	if (atomic_load_int(state) == STATE_MWAIT)
489 		__asm __volatile("sti; mwait" : : "a" (MWAIT_C1), "c" (0));
490 	else
491 		enable_intr();
492 	atomic_store_int(state, STATE_RUNNING);
493 }
494 
495 static void
496 cpu_idle_spin(sbintime_t sbt)
497 {
498 	int *state;
499 	int i;
500 
501 	state = (int *)PCPU_PTR(monitorbuf);
502 	atomic_store_int(state, STATE_RUNNING);
503 
504 	/*
505 	 * The sched_runnable() call is racy but as long as there is
506 	 * a loop missing it one time will have just a little impact if any
507 	 * (and it is much better than missing the check at all).
508 	 */
509 	for (i = 0; i < 1000; i++) {
510 		if (sched_runnable())
511 			return;
512 		cpu_spinwait();
513 	}
514 }
515 
516 /*
517  * C1E renders the local APIC timer dead, so we disable it by
518  * reading the Interrupt Pending Message register and clearing
519  * both C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
520  *
521  * Reference:
522  *   "BIOS and Kernel Developer's Guide for AMD NPT Family 0Fh Processors"
523  *   #32559 revision 3.00+
524  */
525 #define	MSR_AMDK8_IPM		0xc0010055
526 #define	AMDK8_SMIONCMPHALT	(1ULL << 27)
527 #define	AMDK8_C1EONCMPHALT	(1ULL << 28)
528 #define	AMDK8_CMPHALT		(AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
529 
530 void
531 cpu_probe_amdc1e(void)
532 {
533 
534 	/*
535 	 * Detect the presence of C1E capability mostly on latest
536 	 * dual-cores (or future) k8 family.
537 	 */
538 	if (cpu_vendor_id == CPU_VENDOR_AMD &&
539 	    (cpu_id & 0x00000f00) == 0x00000f00 &&
540 	    (cpu_id & 0x0fff0000) >=  0x00040000) {
541 		cpu_ident_amdc1e = 1;
542 	}
543 }
544 
545 void (*cpu_idle_fn)(sbintime_t) = cpu_idle_acpi;
546 
547 void
548 cpu_idle(int busy)
549 {
550 	uint64_t msr;
551 	sbintime_t sbt = -1;
552 
553 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
554 	    busy, curcpu);
555 #ifdef MP_WATCHDOG
556 	ap_watchdog(PCPU_GET(cpuid));
557 #endif
558 
559 	/* If we are busy - try to use fast methods. */
560 	if (busy) {
561 		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
562 			cpu_idle_mwait(busy);
563 			goto out;
564 		}
565 	}
566 
567 	/* If we have time - switch timers into idle mode. */
568 	if (!busy) {
569 		critical_enter();
570 		sbt = cpu_idleclock();
571 	}
572 
573 	/* Apply AMD APIC timer C1E workaround. */
574 	if (cpu_ident_amdc1e && cpu_disable_c3_sleep) {
575 		msr = rdmsr(MSR_AMDK8_IPM);
576 		if (msr & AMDK8_CMPHALT)
577 			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
578 	}
579 
580 	/* Call main idle method. */
581 	cpu_idle_fn(sbt);
582 
583 	/* Switch timers back into active mode. */
584 	if (!busy) {
585 		cpu_activeclock();
586 		critical_exit();
587 	}
588 out:
589 	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
590 	    busy, curcpu);
591 }
592 
593 static int cpu_idle_apl31_workaround;
594 SYSCTL_INT(_machdep, OID_AUTO, idle_apl31, CTLFLAG_RW,
595     &cpu_idle_apl31_workaround, 0,
596     "Apollo Lake APL31 MWAIT bug workaround");
597 
598 int
599 cpu_idle_wakeup(int cpu)
600 {
601 	int *state;
602 
603 	state = (int *)pcpu_find(cpu)->pc_monitorbuf;
604 	switch (atomic_load_int(state)) {
605 	case STATE_SLEEPING:
606 		return (0);
607 	case STATE_MWAIT:
608 		atomic_store_int(state, STATE_RUNNING);
609 		return (cpu_idle_apl31_workaround ? 0 : 1);
610 	case STATE_RUNNING:
611 		return (1);
612 	default:
613 		panic("bad monitor state");
614 		return (1);
615 	}
616 }
617 
618 /*
619  * Ordered by speed/power consumption.
620  */
621 static struct {
622 	void	*id_fn;
623 	char	*id_name;
624 	int	id_cpuid2_flag;
625 } idle_tbl[] = {
626 	{ .id_fn = cpu_idle_spin, .id_name = "spin" },
627 	{ .id_fn = cpu_idle_mwait, .id_name = "mwait",
628 	    .id_cpuid2_flag = CPUID2_MON },
629 	{ .id_fn = cpu_idle_hlt, .id_name = "hlt" },
630 	{ .id_fn = cpu_idle_acpi, .id_name = "acpi" },
631 };
632 
633 static int
634 idle_sysctl_available(SYSCTL_HANDLER_ARGS)
635 {
636 	char *avail, *p;
637 	int error;
638 	int i;
639 
640 	avail = malloc(256, M_TEMP, M_WAITOK);
641 	p = avail;
642 	for (i = 0; i < nitems(idle_tbl); i++) {
643 		if (idle_tbl[i].id_cpuid2_flag != 0 &&
644 		    (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
645 			continue;
646 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
647 		    cpu_idle_hook == NULL)
648 			continue;
649 		p += sprintf(p, "%s%s", p != avail ? ", " : "",
650 		    idle_tbl[i].id_name);
651 	}
652 	error = sysctl_handle_string(oidp, avail, 0, req);
653 	free(avail, M_TEMP);
654 	return (error);
655 }
656 
657 SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
658     0, 0, idle_sysctl_available, "A", "list of available idle functions");
659 
660 static bool
661 cpu_idle_selector(const char *new_idle_name)
662 {
663 	int i;
664 
665 	for (i = 0; i < nitems(idle_tbl); i++) {
666 		if (idle_tbl[i].id_cpuid2_flag != 0 &&
667 		    (cpu_feature2 & idle_tbl[i].id_cpuid2_flag) == 0)
668 			continue;
669 		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
670 		    cpu_idle_hook == NULL)
671 			continue;
672 		if (strcmp(idle_tbl[i].id_name, new_idle_name))
673 			continue;
674 		cpu_idle_fn = idle_tbl[i].id_fn;
675 		if (bootverbose)
676 			printf("CPU idle set to %s\n", idle_tbl[i].id_name);
677 		return (true);
678 	}
679 	return (false);
680 }
681 
682 static int
683 cpu_idle_sysctl(SYSCTL_HANDLER_ARGS)
684 {
685 	char buf[16], *p;
686 	int error, i;
687 
688 	p = "unknown";
689 	for (i = 0; i < nitems(idle_tbl); i++) {
690 		if (idle_tbl[i].id_fn == cpu_idle_fn) {
691 			p = idle_tbl[i].id_name;
692 			break;
693 		}
694 	}
695 	strncpy(buf, p, sizeof(buf));
696 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
697 	if (error != 0 || req->newptr == NULL)
698 		return (error);
699 	return (cpu_idle_selector(buf) ? 0 : EINVAL);
700 }
701 
702 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
703     cpu_idle_sysctl, "A", "currently selected idle function");
704 
705 static void
706 cpu_idle_tun(void *unused __unused)
707 {
708 	char tunvar[16];
709 
710 	if (TUNABLE_STR_FETCH("machdep.idle", tunvar, sizeof(tunvar)))
711 		cpu_idle_selector(tunvar);
712 	else if (cpu_vendor_id == CPU_VENDOR_AMD &&
713 	    CPUID_TO_FAMILY(cpu_id) == 0x17 && CPUID_TO_MODEL(cpu_id) == 0x1) {
714 		/* Ryzen erratas 1057, 1109. */
715 		cpu_idle_selector("hlt");
716 		idle_mwait = 0;
717 	}
718 
719 	if (cpu_vendor_id == CPU_VENDOR_INTEL && cpu_id == 0x506c9) {
720 		/*
721 		 * Apollo Lake errata APL31 (public errata APL30).
722 		 * Stores to the armed address range may not trigger
723 		 * MWAIT to resume execution.  OS needs to use
724 		 * interrupts to wake processors from MWAIT-induced
725 		 * sleep states.
726 		 */
727 		cpu_idle_apl31_workaround = 1;
728 	}
729 	TUNABLE_INT_FETCH("machdep.idle_apl31", &cpu_idle_apl31_workaround);
730 }
731 SYSINIT(cpu_idle_tun, SI_SUB_CPU, SI_ORDER_MIDDLE, cpu_idle_tun, NULL);
732 
733 static int panic_on_nmi = 1;
734 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RWTUN,
735     &panic_on_nmi, 0,
736     "Panic on NMI raised by hardware failure");
737 int nmi_is_broadcast = 1;
738 SYSCTL_INT(_machdep, OID_AUTO, nmi_is_broadcast, CTLFLAG_RWTUN,
739     &nmi_is_broadcast, 0,
740     "Chipset NMI is broadcast");
741 #ifdef KDB
742 int kdb_on_nmi = 1;
743 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RWTUN,
744     &kdb_on_nmi, 0,
745     "Go to KDB on NMI with unknown source");
746 #endif
747 
748 void
749 nmi_call_kdb(u_int cpu, u_int type, struct trapframe *frame)
750 {
751 	bool claimed = false;
752 
753 #ifdef DEV_ISA
754 	/* machine/parity/power fail/"kitchen sink" faults */
755 	if (isa_nmi(frame->tf_err)) {
756 		claimed = true;
757 		if (panic_on_nmi)
758 			panic("NMI indicates hardware failure");
759 	}
760 #endif /* DEV_ISA */
761 #ifdef KDB
762 	if (!claimed && kdb_on_nmi) {
763 		/*
764 		 * NMI can be hooked up to a pushbutton for debugging.
765 		 */
766 		printf("NMI/cpu%d ... going to debugger\n", cpu);
767 		kdb_trap(type, 0, frame);
768 	}
769 #endif /* KDB */
770 }
771 
772 void
773 nmi_handle_intr(u_int type, struct trapframe *frame)
774 {
775 
776 #ifdef SMP
777 	if (nmi_is_broadcast) {
778 		nmi_call_kdb_smp(type, frame);
779 		return;
780 	}
781 #endif
782 	nmi_call_kdb(PCPU_GET(cpuid), type, frame);
783 }
784 
785 int hw_ibrs_active;
786 int hw_ibrs_disable = 1;
787 
788 SYSCTL_INT(_hw, OID_AUTO, ibrs_active, CTLFLAG_RD, &hw_ibrs_active, 0,
789     "Indirect Branch Restricted Speculation active");
790 
791 void
792 hw_ibrs_recalculate(void)
793 {
794 	uint64_t v;
795 
796 	if ((cpu_ia32_arch_caps & IA32_ARCH_CAP_IBRS_ALL) != 0) {
797 		if (hw_ibrs_disable) {
798 			v = rdmsr(MSR_IA32_SPEC_CTRL);
799 			v &= ~(uint64_t)IA32_SPEC_CTRL_IBRS;
800 			wrmsr(MSR_IA32_SPEC_CTRL, v);
801 		} else {
802 			v = rdmsr(MSR_IA32_SPEC_CTRL);
803 			v |= IA32_SPEC_CTRL_IBRS;
804 			wrmsr(MSR_IA32_SPEC_CTRL, v);
805 		}
806 		return;
807 	}
808 	hw_ibrs_active = (cpu_stdext_feature3 & CPUID_STDEXT3_IBPB) != 0 &&
809 	    !hw_ibrs_disable;
810 }
811 
812 static int
813 hw_ibrs_disable_handler(SYSCTL_HANDLER_ARGS)
814 {
815 	int error, val;
816 
817 	val = hw_ibrs_disable;
818 	error = sysctl_handle_int(oidp, &val, 0, req);
819 	if (error != 0 || req->newptr == NULL)
820 		return (error);
821 	hw_ibrs_disable = val != 0;
822 	hw_ibrs_recalculate();
823 	return (0);
824 }
825 SYSCTL_PROC(_hw, OID_AUTO, ibrs_disable, CTLTYPE_INT | CTLFLAG_RWTUN |
826     CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0, hw_ibrs_disable_handler, "I",
827     "Disable Indirect Branch Restricted Speculation");
828 
829 int hw_ssb_active;
830 int hw_ssb_disable;
831 
832 SYSCTL_INT(_hw, OID_AUTO, spec_store_bypass_disable_active, CTLFLAG_RD,
833     &hw_ssb_active, 0,
834     "Speculative Store Bypass Disable active");
835 
836 static void
837 hw_ssb_set_one(bool enable)
838 {
839 	uint64_t v;
840 
841 	v = rdmsr(MSR_IA32_SPEC_CTRL);
842 	if (enable)
843 		v |= (uint64_t)IA32_SPEC_CTRL_SSBD;
844 	else
845 		v &= ~(uint64_t)IA32_SPEC_CTRL_SSBD;
846 	wrmsr(MSR_IA32_SPEC_CTRL, v);
847 }
848 
849 static void
850 hw_ssb_set(bool enable, bool for_all_cpus)
851 {
852 	struct thread *td;
853 	int bound_cpu, i, is_bound;
854 
855 	if ((cpu_stdext_feature3 & CPUID_STDEXT3_SSBD) == 0) {
856 		hw_ssb_active = 0;
857 		return;
858 	}
859 	hw_ssb_active = enable;
860 	if (for_all_cpus) {
861 		td = curthread;
862 		thread_lock(td);
863 		is_bound = sched_is_bound(td);
864 		bound_cpu = td->td_oncpu;
865 		CPU_FOREACH(i) {
866 			sched_bind(td, i);
867 			hw_ssb_set_one(enable);
868 		}
869 		if (is_bound)
870 			sched_bind(td, bound_cpu);
871 		else
872 			sched_unbind(td);
873 		thread_unlock(td);
874 	} else {
875 		hw_ssb_set_one(enable);
876 	}
877 }
878 
879 void
880 hw_ssb_recalculate(bool all_cpus)
881 {
882 
883 	switch (hw_ssb_disable) {
884 	default:
885 		hw_ssb_disable = 0;
886 		/* FALLTHROUGH */
887 	case 0: /* off */
888 		hw_ssb_set(false, all_cpus);
889 		break;
890 	case 1: /* on */
891 		hw_ssb_set(true, all_cpus);
892 		break;
893 	case 2: /* auto */
894 		hw_ssb_set((cpu_ia32_arch_caps & IA32_ARCH_CAP_SSB_NO) != 0 ?
895 		    false : true, all_cpus);
896 		break;
897 	}
898 }
899 
900 static int
901 hw_ssb_disable_handler(SYSCTL_HANDLER_ARGS)
902 {
903 	int error, val;
904 
905 	val = hw_ssb_disable;
906 	error = sysctl_handle_int(oidp, &val, 0, req);
907 	if (error != 0 || req->newptr == NULL)
908 		return (error);
909 	hw_ssb_disable = val;
910 	hw_ssb_recalculate(true);
911 	return (0);
912 }
913 SYSCTL_PROC(_hw, OID_AUTO, spec_store_bypass_disable, CTLTYPE_INT |
914     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
915     hw_ssb_disable_handler, "I",
916     "Speculative Store Bypass Disable (0 - off, 1 - on, 2 - auto");
917 
918 /*
919  * Enable and restore kernel text write permissions.
920  * Callers must ensure that disable_wp()/restore_wp() are executed
921  * without rescheduling on the same core.
922  */
923 bool
924 disable_wp(void)
925 {
926 	u_int cr0;
927 
928 	cr0 = rcr0();
929 	if ((cr0 & CR0_WP) == 0)
930 		return (false);
931 	load_cr0(cr0 & ~CR0_WP);
932 	return (true);
933 }
934 
935 void
936 restore_wp(bool old_wp)
937 {
938 
939 	if (old_wp)
940 		load_cr0(rcr0() | CR0_WP);
941 }
942 
943 bool
944 acpi_get_fadt_bootflags(uint16_t *flagsp)
945 {
946 #ifdef DEV_ACPI
947 	ACPI_TABLE_FADT *fadt;
948 	vm_paddr_t physaddr;
949 
950 	physaddr = acpi_find_table(ACPI_SIG_FADT);
951 	if (physaddr == 0)
952 		return (false);
953 	fadt = acpi_map_table(physaddr, ACPI_SIG_FADT);
954 	if (fadt == NULL)
955 		return (false);
956 	*flagsp = fadt->BootFlags;
957 	acpi_unmap_table(fadt);
958 	return (true);
959 #else
960 	return (false);
961 #endif
962 }
963