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 falsecfg!(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 >= 0x8000_0001 {
84        let CpuidResult { ecx, .. } = __cpuid(0x8000_0001_u32);
85        ecx
86    } else {
87        0
88    };
89
90    // As Hygon Dhyana originates from AMD technology and shares most of the architecture with
91    // AMD's family 17h, but with different CPU Vendor ID("HygonGenuine")/Family series
92    // number(Family 18h).
93    //
94    // For CPUID feature bits, Hygon Dhyana(family 18h) share the same definition with AMD
95    // family 17h.
96    //
97    // Related AMD CPUID specification is https://www.amd.com/system/files/TechDocs/25481.pdf.
98    // Related Hygon kernel patch can be found on
99    // http://lkml.kernel.org/r/5ce86123a7b9dad925ac583d88d2f921040e859b.1538583282.git.puwen@hygon.cn
100    let is_amd_or_hygon = vendor_id == *b"AuthenticAMD" || vendor_id == *b"HygonGenuine";
101
102    {
103        // borrows value till the end of this scope:
104        let mut enable = |r, rb, f| {
105            let present = bit::test(r as usize, rb);
106            if present {
107                value.set(f as u32);
108            }
109            present
110        };
111
112        enable(proc_info_ecx, 0, Feature::sse3);
113        enable(proc_info_ecx, 1, Feature::pclmulqdq);
114        enable(proc_info_ecx, 9, Feature::ssse3);
115        enable(proc_info_ecx, 13, Feature::cmpxchg16b);
116        enable(proc_info_ecx, 19, Feature::sse4_1);
117        enable(proc_info_ecx, 20, Feature::sse4_2);
118        enable(proc_info_ecx, 22, Feature::movbe);
119        enable(proc_info_ecx, 23, Feature::popcnt);
120        enable(proc_info_ecx, 25, Feature::aes);
121        enable(proc_info_ecx, 30, Feature::rdrand);
122        enable(extended_features_ebx, 18, Feature::rdseed);
123        enable(extended_features_ebx, 19, Feature::adx);
124        enable(extended_features_ebx, 11, Feature::rtm);
125        enable(proc_info_edx, 4, Feature::tsc);
126        enable(proc_info_edx, 23, Feature::mmx);
127        enable(proc_info_edx, 24, Feature::fxsr);
128        enable(proc_info_edx, 25, Feature::sse);
129        enable(proc_info_edx, 26, Feature::sse2);
130        enable(extended_features_ebx, 29, Feature::sha);
131
132        enable(extended_features_ecx, 8, Feature::gfni);
133        enable(extended_features_ecx, 27, Feature::movdiri);
134        enable(extended_features_ecx, 28, Feature::movdir64b);
135
136        enable(extended_features_ebx, 3, Feature::bmi1);
137        enable(extended_features_ebx, 8, Feature::bmi2);
138
139        enable(extended_features_ebx, 9, Feature::ermsb);
140
141        enable(extended_features_ebx, 23, Feature::clflushopt);
142
143        enable(extended_features_eax_leaf_1, 31, Feature::movrs);
144
145        // Detect if CPUID.19h available
146        if bit::test(extended_features_ecx as usize, 23) {
147            let CpuidResult { ebx, .. } = __cpuid(0x19);
148            if enable(ebx, 0, Feature::kl) {
149                enable(ebx, 2, Feature::widekl);
150            }
151        }
152
153        // This detects ABM on AMD CPUs and LZCNT on Intel CPUs.
154        // On intel CPUs with popcnt, lzcnt implements the
155        // "missing part" of ABM, so we map both to the same
156        // internal feature.
157        //
158        // The `is_x86_feature_detected!("lzcnt")` macro then
159        // internally maps to Feature::abm.
160        enable(extended_proc_info_ecx, 5, Feature::lzcnt);
161
162        if is_amd_or_hygon {
163            // These features are available on AMD arch CPUs:
164            enable(extended_proc_info_ecx, 6, Feature::sse4a);
165            enable(extended_proc_info_ecx, 21, Feature::tbm);
166        }
167
168        // `XSAVE` and `AVX` support:
169        let cpu_xsave = bit::test(proc_info_ecx as usize, 26);
170        if cpu_xsave {
171            // 0. Here the CPU supports `XSAVE`.
172
173            // 1. Detect `OSXSAVE`, that is, whether the OS is AVX enabled and
174            // supports saving the state of the AVX/AVX2 vector registers on
175            // context-switches, see:
176            //
177            // - [intel: is avx enabled?][is_avx_enabled],
178            // - [mozilla: sse.cpp][mozilla_sse_cpp].
179            //
180            // [is_avx_enabled]: https://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled
181            // [mozilla_sse_cpp]: https://hg.mozilla.org/mozilla-central/file/64bab5cbb9b6/mozglue/build/SSE.cpp#l190
182            let cpu_osxsave = bit::test(proc_info_ecx as usize, 27);
183
184            if cpu_osxsave {
185                // See "13.3 ENABLING THE XSAVE FEATURE SET AND XSAVE-ENABLED
186                // FEATURES" in the "Intel® 64 and IA-32 Architectures Software
187                // Developer's Manual, Volume 1: Basic Architecture":
188                //
189                // "Software enables the XSAVE feature set by setting
190                // CR4.OSXSAVE[bit 18] to 1 (e.g., with the MOV to CR4
191                // instruction). If this bit is 0, execution of any of XGETBV,
192                // XRSTOR, XRSTORS, XSAVE, XSAVEC, XSAVEOPT, XSAVES, and XSETBV
193                // causes an invalid-opcode exception (#UD)"
194                enable(proc_info_ecx, 26, Feature::xsave);
195
196                // For `xsaveopt`, `xsavec`, and `xsaves` we need to query:
197                // Processor Extended State Enumeration Sub-leaf (EAX = 0DH,
198                // ECX = 1):
199                if max_basic_leaf >= 0x0d {
200                    let CpuidResult { eax: proc_extended_state1_eax, .. } = __cpuid_count(0x0d, 1);
201                    enable(proc_extended_state1_eax, 0, Feature::xsaveopt);
202                    enable(proc_extended_state1_eax, 1, Feature::xsavec);
203                    enable(proc_extended_state1_eax, 3, Feature::xsaves);
204                }
205
206                // 2. The OS must have signaled the CPU that it supports saving and
207                // restoring the:
208                //
209                // * SSE -> `XCR0.SSE[1]`
210                // * AVX -> `XCR0.AVX[2]`
211                // * AVX-512 -> `XCR0.AVX-512[7:5]`.
212                // * AMX -> `XCR0.AMX[18:17]`
213                // * APX -> `XCR0.APX[19]`
214                //
215                // by setting the corresponding bits of `XCR0` to `1`.
216                //
217                // This is safe because the CPU supports `xsave`
218                // and the OS has set `osxsave`.
219                let xcr0 = unsafe { _xgetbv(0) };
220                // Test `XCR0.SSE[1]` and `XCR0.AVX[2]` with the mask `0b110 == 6`:
221                let os_avx_support = xcr0 & 6 == 6;
222                // Test `XCR0.AVX-512[7:5]` with the mask `0b1110_0000 == 0xe0`:
223                let os_avx512_support = xcr0 & 0xe0 == 0xe0;
224                // Test `XCR0.AMX[18:17]` with the mask `0b110_0000_0000_0000_0000 == 0x60000`
225                let os_amx_support = xcr0 & 0x60000 == 0x60000;
226                // Test `XCR0.APX[19]` with the mask `0b1000_0000_0000_0000_0000 == 0x80000`
227                let os_apx_support = xcr0 & 0x80000 == 0x80000;
228
229                if os_amx_support {
230                    enable(extended_features_edx, 24, Feature::amx_tile);
231                    enable(extended_features_edx, 25, Feature::amx_int8);
232                    enable(extended_features_edx, 22, Feature::amx_bf16);
233                    enable(extended_features_eax_leaf_1, 21, Feature::amx_fp16);
234                    enable(extended_features_edx_leaf_1, 8, Feature::amx_complex);
235
236                    if max_basic_leaf >= 0x1e {
237                        let CpuidResult { eax: amx_feature_flags_eax, .. } =
238                            __cpuid_count(0x1e_u32, 1);
239
240                        enable(amx_feature_flags_eax, 4, Feature::amx_fp8);
241                        enable(amx_feature_flags_eax, 7, Feature::amx_avx512);
242                        enable(amx_feature_flags_eax, 8, Feature::amx_movrs);
243                    }
244                }
245
246                if os_apx_support {
247                    enable(extended_features_edx_leaf_1, 21, Feature::apxf);
248                }
249
250                if os_avx_support {
251                    // FMA and F16C (use VEX encodings / AVX state):
252                    let fma = enable(proc_info_ecx, 12, Feature::fma);
253                    let f16c = enable(proc_info_ecx, 29, Feature::f16c);
254
255                    // AVX/AVX2 and VEX/EVEX crypto extensions:
256                    enable(proc_info_ecx, 28, Feature::avx);
257                    enable(extended_features_ebx, 5, Feature::avx2);
258                    enable(extended_features_ecx, 9, Feature::vaes);
259                    enable(extended_features_ecx, 10, Feature::vpclmulqdq);
260
261                    if is_amd_or_hygon {
262                        enable(extended_proc_info_ecx, 11, Feature::xop);
263                    }
264
265                    // "Short" versions of AVX512 instructions
266                    let avxvnni = enable(extended_features_eax_leaf_1, 4, Feature::avxvnni);
267                    enable(extended_features_eax_leaf_1, 23, Feature::avxifma);
268                    let avxvnniint8 = enable(extended_features_edx_leaf_1, 4, Feature::avxvnniint8);
269                    enable(extended_features_edx_leaf_1, 5, Feature::avxneconvert);
270                    let avxvnniint16 =
271                        enable(extended_features_edx_leaf_1, 10, Feature::avxvnniint16);
272
273                    enable(extended_features_eax_leaf_1, 0, Feature::sha512);
274                    enable(extended_features_eax_leaf_1, 1, Feature::sm3);
275                    enable(extended_features_eax_leaf_1, 2, Feature::sm4);
276
277                    // For AVX-512 the OS also needs to support saving/restoring
278                    // the extended state, only then we enable AVX-512 support:
279                    // Also, Rust makes `avx512f` imply `fma` and `f16c`, because
280                    // otherwise the assembler is broken. But Intel doesn't guarantee
281                    // that `fma` and `f16c` are available with `avx512f`, so we
282                    // need to check for them separately.
283                    if os_avx512_support && f16c && fma {
284                        enable(extended_features_ebx, 16, Feature::avx512f);
285                        enable(extended_features_ebx, 17, Feature::avx512dq);
286                        enable(extended_features_ebx, 21, Feature::avx512ifma);
287                        enable(extended_features_ebx, 26, Feature::avx512pf);
288                        enable(extended_features_ebx, 27, Feature::avx512er);
289                        enable(extended_features_ebx, 28, Feature::avx512cd);
290                        enable(extended_features_ebx, 30, Feature::avx512bw);
291                        enable(extended_features_ebx, 31, Feature::avx512vl);
292                        enable(extended_features_ecx, 1, Feature::avx512vbmi);
293                        enable(extended_features_ecx, 6, Feature::avx512vbmi2);
294                        enable(extended_features_ecx, 11, Feature::avx512vnni);
295                        enable(extended_features_ecx, 12, Feature::avx512bitalg);
296                        enable(extended_features_ecx, 14, Feature::avx512vpopcntdq);
297                        enable(extended_features_edx, 8, Feature::avx512vp2intersect);
298                        enable(extended_features_edx, 23, Feature::avx512fp16);
299                        enable(extended_features_eax_leaf_1, 5, Feature::avx512bf16);
300
301                        let avx10_1 = enable(extended_features_edx_leaf_1, 19, Feature::avx10_1);
302                        if avx10_1 {
303                            let CpuidResult { ebx, .. } = __cpuid(0x24);
304                            let avx10_version = ebx & 0xff;
305
306                            // AVX10.2 supports masked versions of dot-product instructions available in avxvnni etc,
307                            // so it doesn't make sense to have it without the unmasked versions
308                            if avx10_version >= 2 && avxvnni && avxvnniint8 && avxvnniint16 {
309                                value.set(Feature::avx10_2 as u32);
310                            }
311                        }
312                    }
313                }
314            }
315        }
316    }
317
318    // Unfortunately, some Skylake chips erroneously report support for BMI1 and
319    // BMI2 without actual support. These chips don't support AVX, and it seems
320    // that all Intel chips with non-erroneous support BMI do (I didn't check
321    // other vendors), so we can disable these flags for chips that don't also
322    // report support for AVX.
323    //
324    // It's possible this will pessimize future chips that do support BMI and
325    // not AVX, but this seems minor compared to a hard crash you get when
326    // executing an unsupported instruction (to put it another way, it's safe
327    // for us to under-report CPU features, but not to over-report them). Still,
328    // to limit any impact this may have in the future, we only do this for
329    // Intel chips, as it's a bug only present in their chips.
330    //
331    // This bug is documented as `SKL052` in the errata section of this document:
332    // http://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/desktop-6th-gen-core-family-spec-update.pdf
333    if vendor_id == *b"GenuineIntel" && !value.test(Feature::avx as u32) {
334        value.unset(Feature::bmi1 as u32);
335        value.unset(Feature::bmi2 as u32);
336    }
337
338    value
339}