/* CPU feature detection (see cpu.h). */ #include "cpu.h" static int sse2 = -1; /* -1 = not probed yet, 0 = no, 1 = yes */ /* CPUID exists only if the ID bit in EFLAGS can be toggled (i586+). */ int cpu_has_cpuid(void) { unsigned int a, b; __asm__ volatile ("pushfl; popl %0" : "=r"(a)); b = a ^ (1u << 21); __asm__ volatile ("pushl %0; popfl" :: "r"(b)); __asm__ volatile ("pushfl; popl %0" : "=r"(b)); return ((a ^ b) & (1u << 21)) != 0; } unsigned int cpu_family_model(void) { unsigned int a, b, c, d, family, model; if (!cpu_has_cpuid()) return 0; a = 0; __asm__ volatile ("cpuid" : "+a"(a), "=b"(b), "=c"(c), "=d"(d)); if (a < 1) return 0; a = 1; __asm__ volatile ("cpuid" : "+a"(a), "=b"(b), "=c"(c), "=d"(d)); family = (a >> 8) & 0xFu; model = (a >> 4) & 0xFu; if (family == 0xFu) family += (a >> 20) & 0xFFu; if (family == 0x6u || family == 0xFu) model |= ((a >> 16) & 0xFu) << 4; return (family << 8) | model; } /* An AP leaves INIT with CR0.NE clear and an x87 control word of 0x0040: * every exception unmasked and 24-bit precision. With NE clear an * unmasked exception (an inexact result, i.e. most floating-point * operations) freezes the CPU at the next FPU instruction until an external * interrupt -- the next 1 ms timer tick. QuickJS computes with doubles, so * the browser's scripts ran several hundred times slower whenever it was * scheduled on an AP, at 100% CPU, with single-precision results. QEMU * models neither the freeze nor the precision. Native #MF reporting (NE), * MP for WAIT, no emulation or task-switch trap, and FNINIT's 0x037F. */ void cpu_init_fpu(void) { unsigned int cr0; __asm__ volatile ("mov %%cr0, %0" : "=r"(cr0)); cr0 |= (1u << 5) | (1u << 1); /* NE | MP */ cr0 &= ~((1u << 2) | (1u << 3)); /* EM | TS */ __asm__ volatile ("mov %0, %%cr0" :: "r"(cr0) : "memory"); __asm__ volatile ("fninit"); } void cpu_enable_sse(void) { unsigned int eax, ebx, ecx, edx, cr4; if (!cpu_has_cpuid()) return; eax = 1; __asm__ volatile ("cpuid" : "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)); if (!(edx & (1u << 24))) /* FXSR */ return; __asm__ volatile ("mov %%cr4, %0" : "=r"(cr4)); cr4 |= (1u << 9) | (1u << 10); /* OSFXSR | OSXMMEXCPT */ __asm__ volatile ("mov %0, %%cr4" :: "r"(cr4) : "memory"); } int cpu_has_sse2(void) { unsigned int eax, ebx, ecx, edx; if (sse2 >= 0) return sse2; sse2 = 0; if (cpu_has_cpuid()) { eax = 1; __asm__ volatile ("cpuid" : "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)); if (edx & (1u << 26)) { /* SSE instructions #UD unless CR4 enables the state * (OSFXSR). The kernel is built -mno-sse, so the * registers are only used inside a single helper and * need no per-process save. */ if (edx & (1u << 24)) { /* FXSR */ unsigned int cr4; __asm__ volatile ("mov %%cr4, %0" : "=r"(cr4)); cr4 |= (1u << 9) | (1u << 10); /* OSFXSR | OSXMMEXCPT */ __asm__ volatile ("mov %0, %%cr4" :: "r"(cr4) : "memory"); } sse2 = 1; } } return sse2; }