Skip to main content

std_detect/detect/os/
x86.rs

1//! x86 run-time feature detection is OS independent.
2
3#[cfg(target_arch = "x86")]
4use core::arch::x86::*;
5#[cfg(target_arch = "x86_64")]
6use core::arch::x86_64::*;
7use core::mem;
8
9use crate::detect::{Feature, bit, cache};
10
11/// Run-time feature detection on x86 works by using the CPUID instruction.
12///
13/// The [CPUID Wikipedia page][wiki_cpuid] contains
14/// all the information about which flags to set to query which values, and in
15/// which registers these are reported.
16///
17/// The definitive references are:
18/// - [Intel 64 and IA-32 Architectures Software Developer's Manual Volume 2:
19///   Instruction Set Reference, A-Z][intel64_ref].
20/// - [AMD64 Architecture Programmer's Manual, Volume 3: General-Purpose and
21///   System Instructions][amd64_ref].
22///
23/// [wiki_cpuid]: https://en.wikipedia.org/wiki/CPUID
24/// [intel64_ref]: http://www.intel.de/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf
25/// [amd64_ref]: http://support.amd.com/TechDocs/24594.pdf
26#[allow(clippy::similar_names)]
27pub(crate) fn detect_features() -> cache::Initializer {
28    let mut value = cache::Initializer::default();
29
30    if cfg!(target_env = "sgx") {
31        // doesn't support this because it is untrusted data
32        return value;
33    }
34
35    // Calling `__cpuid`/`__cpuid_count` from here on is safe because the CPU
36    // has `cpuid` support.
37
38    // 0. EAX = 0: Basic Information:
39    // - EAX returns the "Highest Function Parameter", that is, the maximum
40    // leaf value for subsequent calls of `cpuinfo` in range [0,
41    // 0x8000_0000]. - The vendor ID is stored in 12 u8 ascii chars,
42    // returned in EBX, EDX, and   ECX (in that order):
43    let (max_basic_leaf, vendor_id) = {
44        let CpuidResult { eax: max_basic_leaf, ebx, ecx, edx } = __cpuid(0);
45        let vendor_id: [[u8; 4]; 3] = [ebx.to_ne_bytes(), edx.to_ne_bytes(), ecx.to_ne_bytes()];
46        let vendor_id: [u8; 12] = unsafe { mem::transmute(vendor_id) };
47        (max_basic_leaf, vendor_id)
48    };
49
50    if max_basic_leaf < 1 {
51        // Earlier Intel 486, CPUID not implemented
52        return value;
53    }
54
55    // EAX = 1, ECX = 0: Queries "Processor Info and Feature Bits";
56    // Contains information about most x86 features.
57    let CpuidResult { ecx: proc_info_ecx, edx: proc_info_edx, .. } = __cpuid(0x0000_0001_u32);
58
59    // EAX = 7: Queries "Extended Features";
60    // Contains information about bmi,bmi2, and avx2 support.
61    let (
62        extended_features_ebx,
63        extended_features_ecx,
64        extended_features_edx,
65        extended_features_eax_leaf_1,
66        extended_features_edx_leaf_1,
67    ) = if max_basic_leaf >= 7 {
68        let CpuidResult { ebx, ecx, edx, .. } = __cpuid(0x0000_0007_u32);
69        let CpuidResult { eax: eax_1, edx: edx_1, .. } =
70            __cpuid_count(0x0000_0007_u32, 0x0000_0001_u32);
71        (ebx, ecx, edx, eax_1, edx_1)
72    } else {
73        (0, 0, 0, 0, 0) // CPUID does not support "Extended Features"
74    };
75
76    // EAX = 0x8000_0000, ECX = 0: Get Highest Extended Function Supported
77    // - EAX returns the max leaf value for extended information, that is,
78    // `cpuid` calls in range [0x8000_0000; u32::MAX]:
79    let CpuidResult { eax: extended_max_basic_leaf, .. } = __cpuid(0x8000_0000_u32);
80
81    // EAX = 0x8000_0001, ECX=0: Queries "Extended Processor Info and Feature
82    // Bits"
83    let extended_proc_info_ecx = if extended_max_basic_leaf >= 1 {
84        let CpuidResult { ecx, .. } = __cpuid(0x8000_0001_u32);
85        ecx
86    } else {
87        0
88    };
89
90    {
91        // borrows value till the end of this scope:
92        let mut enable = |r, rb, f| {
93            let present = bit::test(r as usize, rb);
94            if present {
95                value.set(f as u32);
96            }
97            present
98        };
99
100        enable(proc_info_ecx, 0, Feature::sse3);
101        enable(proc_info_ecx, 1, Feature::pclmulqdq);
102        enable(proc_info_ecx, 9, Feature::ssse3);
103        enable(proc_info_ecx, 13, Feature::cmpxchg16b);
104        enable(proc_info_ecx, 19, Feature::sse4_1);
105        enable(proc_info_ecx, 20, Feature::sse4_2);
106        enable(proc_info_ecx, 22, Feature::movbe);
107        enable(proc_info_ecx, 23, Feature::popcnt);
108        enable(proc_info_ecx, 25, Feature::aes);
109        let f16c = enable(proc_info_ecx, 29, Feature::f16c);
110        enable(proc_info_ecx, 30, Feature::rdrand);
111        enable(extended_features_ebx, 18, Feature::rdseed);
112        enable(extended_features_ebx, 19, Feature::adx);
113        enable(extended_features_ebx, 11, Feature::rtm);
114        enable(proc_info_edx, 4, Feature::tsc);
115        enable(proc_info_edx, 23, Feature::mmx);
116        enable(proc_info_edx, 24, Feature::fxsr);
117        enable(proc_info_edx, 25, Feature::sse);
118        enable(proc_info_edx, 26, Feature::sse2);
119        enable(extended_features_ebx, 29, Feature::sha);
120
121        enable(extended_features_ecx, 8, Feature::gfni);
122        enable(extended_features_ecx, 9, Feature::vaes);
123        enable(extended_features_ecx, 10, Feature::vpclmulqdq);
124
125        enable(extended_features_ebx, 3, Feature::bmi1);
126        enable(extended_features_ebx, 8, Feature::bmi2);
127
128        enable(extended_features_ebx, 9, Feature::ermsb);
129
130        enable(extended_features_eax_leaf_1, 31, Feature::movrs);
131
132        // Detect if CPUID.19h available
133        if bit::test(extended_features_ecx as usize, 23) {
134            let CpuidResult { ebx, .. } = __cpuid(0x19);
135            enable(ebx, 0, Feature::kl);
136            enable(ebx, 2, Feature::widekl);
137        }
138
139        // This detects ABM on AMD CPUs and LZCNT on Intel CPUs.
140        // On intel CPUs with popcnt, lzcnt implements the
141        // "missing part" of ABM, so we map both to the same
142        // internal feature.
143        //
144        // The `is_x86_feature_detected!("lzcnt")` macro then
145        // internally maps to Feature::abm.
146        enable(extended_proc_info_ecx, 5, Feature::lzcnt);
147
148        // As Hygon Dhyana originates from AMD technology and shares most of the architecture with
149        // AMD's family 17h, but with different CPU Vendor ID("HygonGenuine")/Family series
150        // number(Family 18h).
151        //
152        // For CPUID feature bits, Hygon Dhyana(family 18h) share the same definition with AMD
153        // family 17h.
154        //
155        // Related AMD CPUID specification is https://www.amd.com/system/files/TechDocs/25481.pdf.
156        // Related Hygon kernel patch can be found on
157        // http://lkml.kernel.org/r/5ce86123a7b9dad925ac583d88d2f921040e859b.1538583282.git.puwen@hygon.cn
158        if vendor_id == *b"AuthenticAMD" || vendor_id == *b"HygonGenuine" {
159            // These features are available on AMD arch CPUs:
160            enable(extended_proc_info_ecx, 6, Feature::sse4a);
161            enable(extended_proc_info_ecx, 21, Feature::tbm);
162            enable(extended_proc_info_ecx, 11, Feature::xop);
163        }
164
165        // `XSAVE` and `AVX` support:
166        let cpu_xsave = bit::test(proc_info_ecx as usize, 26);
167        if cpu_xsave {
168            // 0. Here the CPU supports `XSAVE`.
169
170            // 1. Detect `OSXSAVE`, that is, whether the OS is AVX enabled and
171            // supports saving the state of the AVX/AVX2 vector registers on
172            // context-switches, see:
173            //
174            // - [intel: is avx enabled?][is_avx_enabled],
175            // - [mozilla: sse.cpp][mozilla_sse_cpp].
176            //
177            // [is_avx_enabled]: https://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled
178            // [mozilla_sse_cpp]: https://hg.mozilla.org/mozilla-central/file/64bab5cbb9b6/mozglue/build/SSE.cpp#l190
179            let cpu_osxsave = bit::test(proc_info_ecx as usize, 27);
180
181            if cpu_osxsave {
182                // 2. The OS must have signaled the CPU that it supports saving and
183                // restoring the:
184                //
185                // * SSE -> `XCR0.SSE[1]`
186                // * AVX -> `XCR0.AVX[2]`
187                // * AVX-512 -> `XCR0.AVX-512[7:5]`.
188                // * AMX -> `XCR0.AMX[18:17]`
189                // * APX -> `XCR0.APX[19]`
190                //
191                // by setting the corresponding bits of `XCR0` to `1`.
192                //
193                // This is safe because the CPU supports `xsave`
194                // and the OS has set `osxsave`.
195                let xcr0 = unsafe { _xgetbv(0) };
196                // Test `XCR0.SSE[1]` and `XCR0.AVX[2]` with the mask `0b110 == 6`:
197                let os_avx_support = xcr0 & 6 == 6;
198                // Test `XCR0.AVX-512[7:5]` with the mask `0b1110_0000 == 0xe0`:
199                let os_avx512_support = xcr0 & 0xe0 == 0xe0;
200                // Test `XCR0.AMX[18:17]` with the mask `0b110_0000_0000_0000_0000 == 0x60000`
201                let os_amx_support = xcr0 & 0x60000 == 0x60000;
202                // Test `XCR0.APX[19]` with the mask `0b1000_0000_0000_0000_0000 == 0x80000`
203                let os_apx_support = xcr0 & 0x80000 == 0x80000;
204
205                // Only if the OS and the CPU support saving/restoring the AVX
206                // registers we enable `xsave` support:
207                if os_avx_support {
208                    // See "13.3 ENABLING THE XSAVE FEATURE SET AND XSAVE-ENABLED
209                    // FEATURES" in the "Intel® 64 and IA-32 Architectures Software
210                    // Developer’s Manual, Volume 1: Basic Architecture":
211                    //
212                    // "Software enables the XSAVE feature set by setting
213                    // CR4.OSXSAVE[bit 18] to 1 (e.g., with the MOV to CR4
214                    // instruction). If this bit is 0, execution of any of XGETBV,
215                    // XRSTOR, XRSTORS, XSAVE, XSAVEC, XSAVEOPT, XSAVES, and XSETBV
216                    // causes an invalid-opcode exception (#UD)"
217                    //
218                    enable(proc_info_ecx, 26, Feature::xsave);
219
220                    // For `xsaveopt`, `xsavec`, and `xsaves` we need to query:
221                    // Processor Extended State Enumeration Sub-leaf (EAX = 0DH,
222                    // ECX = 1):
223                    if max_basic_leaf >= 0xd {
224                        let CpuidResult { eax: proc_extended_state1_eax, .. } =
225                            __cpuid_count(0xd_u32, 1);
226                        enable(proc_extended_state1_eax, 0, Feature::xsaveopt);
227                        enable(proc_extended_state1_eax, 1, Feature::xsavec);
228                        enable(proc_extended_state1_eax, 3, Feature::xsaves);
229                    }
230
231                    // FMA (uses 256-bit wide registers):
232                    let fma = enable(proc_info_ecx, 12, Feature::fma);
233
234                    // And AVX/AVX2:
235                    enable(proc_info_ecx, 28, Feature::avx);
236                    enable(extended_features_ebx, 5, Feature::avx2);
237
238                    // "Short" versions of AVX512 instructions
239                    enable(extended_features_eax_leaf_1, 4, Feature::avxvnni);
240                    enable(extended_features_eax_leaf_1, 23, Feature::avxifma);
241                    enable(extended_features_edx_leaf_1, 4, Feature::avxvnniint8);
242                    enable(extended_features_edx_leaf_1, 5, Feature::avxneconvert);
243                    enable(extended_features_edx_leaf_1, 10, Feature::avxvnniint16);
244
245                    enable(extended_features_eax_leaf_1, 0, Feature::sha512);
246                    enable(extended_features_eax_leaf_1, 1, Feature::sm3);
247                    enable(extended_features_eax_leaf_1, 2, Feature::sm4);
248
249                    // For AVX-512 the OS also needs to support saving/restoring
250                    // the extended state, only then we enable AVX-512 support:
251                    // Also, Rust makes `avx512f` imply `fma` and `f16c`, because
252                    // otherwise the assembler is broken. But Intel doesn't guarantee
253                    // that `fma` and `f16c` are available with `avx512f`, so we
254                    // need to check for them separately.
255                    if os_avx512_support && f16c && fma {
256                        enable(extended_features_ebx, 16, Feature::avx512f);
257                        enable(extended_features_ebx, 17, Feature::avx512dq);
258                        enable(extended_features_ebx, 21, Feature::avx512ifma);
259                        enable(extended_features_ebx, 26, Feature::avx512pf);
260                        enable(extended_features_ebx, 27, Feature::avx512er);
261                        enable(extended_features_ebx, 28, Feature::avx512cd);
262                        enable(extended_features_ebx, 30, Feature::avx512bw);
263                        enable(extended_features_ebx, 31, Feature::avx512vl);
264                        enable(extended_features_ecx, 1, Feature::avx512vbmi);
265                        enable(extended_features_ecx, 6, Feature::avx512vbmi2);
266                        enable(extended_features_ecx, 11, Feature::avx512vnni);
267                        enable(extended_features_ecx, 12, Feature::avx512bitalg);
268                        enable(extended_features_ecx, 14, Feature::avx512vpopcntdq);
269                        enable(extended_features_edx, 8, Feature::avx512vp2intersect);
270                        enable(extended_features_edx, 23, Feature::avx512fp16);
271                        enable(extended_features_eax_leaf_1, 5, Feature::avx512bf16);
272                    }
273                }
274
275                if os_amx_support {
276                    enable(extended_features_edx, 24, Feature::amx_tile);
277                    enable(extended_features_edx, 25, Feature::amx_int8);
278                    enable(extended_features_edx, 22, Feature::amx_bf16);
279                    enable(extended_features_eax_leaf_1, 21, Feature::amx_fp16);
280                    enable(extended_features_edx_leaf_1, 8, Feature::amx_complex);
281
282                    if max_basic_leaf >= 0x1e {
283                        let CpuidResult { eax: amx_feature_flags_eax, .. } =
284                            __cpuid_count(0x1e_u32, 1);
285
286                        enable(amx_feature_flags_eax, 4, Feature::amx_fp8);
287                        enable(amx_feature_flags_eax, 6, Feature::amx_tf32);
288                        enable(amx_feature_flags_eax, 7, Feature::amx_avx512);
289                        enable(amx_feature_flags_eax, 8, Feature::amx_movrs);
290                    }
291                }
292
293                if os_apx_support {
294                    enable(extended_features_edx_leaf_1, 21, Feature::apxf);
295                }
296
297                let avx10_1 = enable(extended_features_edx_leaf_1, 19, Feature::avx10_1);
298                if avx10_1 {
299                    let CpuidResult { ebx, .. } = __cpuid(0x24);
300                    let avx10_version = ebx & 0xff;
301                    if avx10_version >= 2 {
302                        value.set(Feature::avx10_2 as u32);
303                    }
304                }
305            }
306        }
307    }
308
309    // Unfortunately, some Skylake chips erroneously report support for BMI1 and
310    // BMI2 without actual support. These chips don't support AVX, and it seems
311    // that all Intel chips with non-erroneous support BMI do (I didn't check
312    // other vendors), so we can disable these flags for chips that don't also
313    // report support for AVX.
314    //
315    // It's possible this will pessimize future chips that do support BMI and
316    // not AVX, but this seems minor compared to a hard crash you get when
317    // executing an unsupported instruction (to put it another way, it's safe
318    // for us to under-report CPU features, but not to over-report them). Still,
319    // to limit any impact this may have in the future, we only do this for
320    // Intel chips, as it's a bug only present in their chips.
321    //
322    // This bug is documented as `SKL052` in the errata section of this document:
323    // http://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/desktop-6th-gen-core-family-spec-update.pdf
324    if vendor_id == *b"GenuineIntel" && !value.test(Feature::avx as u32) {
325        value.unset(Feature::bmi1 as u32);
326        value.unset(Feature::bmi2 as u32);
327    }
328
329    value
330}