Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : /*
24 : * CPU-specific routines common to 32 and 64-bit x86
25 : */
26 :
27 : #include "precompiled.h"
28 :
29 : #include "x86_x64.h"
30 :
31 : #include "lib/bits.h"
32 : #include "lib/code_annotation.h"
33 : #include "lib/debug.h"
34 : #include "lib/lib.h"
35 : #include "lib/module_init.h"
36 : #include "lib/posix/posix_pthread.h"
37 : #include "lib/secure_crt.h"
38 : #include "lib/status.h"
39 : #include "lib/sysdep/cpu.h"
40 : #include "lib/timer.h"
41 :
42 : #include <algorithm>
43 : #include <cstring>
44 : #include <vector>
45 :
46 : #if MSC_VERSION
47 : # include <intrin.h> // __cpuidex
48 : #endif
49 :
50 : namespace x86_x64 {
51 :
52 : #if defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 150030729
53 : // VC10+ and VC9 SP1: __cpuidex is already available
54 : #elif GCC_VERSION
55 : # define __cpuidex(regsArray, level, index)\
56 : __asm__ __volatile__ ("cpuid"\
57 : : "=a" ((regsArray)[0]), "=b" ((regsArray)[1]), "=c" ((regsArray)[2]), "=d" ((regsArray)[3])\
58 : : "0" (level), "2" (index));
59 : #else
60 : # error "compiler not supported"
61 : #endif
62 :
63 :
64 : // some of this module's functions are frequently called but require
65 : // non-trivial initialization, so caching is helpful. isInitialized
66 : // flags aren't thread-safe, so we use ModuleInit. calling it from
67 : // every function is a bit wasteful, but it is convenient to avoid
68 : // requiring users to pass around a global state object.
69 : // one big Init() would be prone to deadlock if its subroutines also
70 : // call a public function (that re-enters ModuleInit), so each
71 : // function gets its own initState.
72 :
73 : //-----------------------------------------------------------------------------
74 : // CPUID
75 :
76 0 : static void Invoke_cpuid(CpuidRegs* regs)
77 : {
78 0 : cassert(sizeof(regs->eax) == sizeof(int));
79 0 : cassert(sizeof(*regs) == 4*sizeof(int));
80 0 : __cpuidex((int*)regs, regs->eax, regs->ecx);
81 : }
82 :
83 : static std::uint32_t cpuid_maxFunction;
84 : static std::uint32_t cpuid_maxExtendedFunction;
85 :
86 0 : static Status InitCpuid()
87 : {
88 0 : CpuidRegs regs = { 0 };
89 :
90 0 : regs.eax = 0;
91 0 : Invoke_cpuid(®s);
92 0 : cpuid_maxFunction = regs.eax;
93 :
94 0 : regs.eax = 0x80000000;
95 0 : Invoke_cpuid(®s);
96 0 : cpuid_maxExtendedFunction = regs.eax;
97 :
98 0 : return INFO::OK;
99 : }
100 :
101 0 : bool cpuid(CpuidRegs* regs)
102 : {
103 0 : static ModuleInitState initState{ 0 };
104 0 : ModuleInit(&initState, InitCpuid);
105 :
106 0 : const std::uint32_t function = regs->eax;
107 0 : if(function > cpuid_maxExtendedFunction)
108 : return false;
109 0 : if(function < 0x80000000 && function > cpuid_maxFunction)
110 : return false;
111 :
112 0 : Invoke_cpuid(regs);
113 0 : return true;
114 : }
115 :
116 :
117 : //-----------------------------------------------------------------------------
118 : // capability bits
119 :
120 : // treated as 128 bit field; order: std ecx, std edx, ext ecx, ext edx
121 : // keep in sync with enum Cap!
122 : static std::uint32_t caps[4];
123 :
124 : static ModuleInitState capsInitState{ 0 };
125 :
126 0 : static Status InitCaps()
127 : {
128 0 : CpuidRegs regs = { 0 };
129 0 : regs.eax = 1;
130 0 : if(cpuid(®s))
131 : {
132 0 : caps[0] = regs.ecx;
133 0 : caps[1] = regs.edx;
134 : }
135 0 : regs.eax = 0x80000001;
136 0 : if(cpuid(®s))
137 : {
138 0 : caps[2] = regs.ecx;
139 0 : caps[3] = regs.edx;
140 : }
141 :
142 0 : return INFO::OK;
143 : }
144 :
145 0 : bool Cap(Caps cap)
146 : {
147 0 : ModuleInit(&capsInitState, InitCaps);
148 :
149 0 : const size_t index = cap >> 5;
150 0 : const size_t bit = cap & 0x1F;
151 0 : if(index >= ARRAY_SIZE(caps))
152 : {
153 0 : DEBUG_WARN_ERR(ERR::INVALID_PARAM);
154 0 : return false;
155 : }
156 0 : return IsBitSet(caps[index], bit);
157 : }
158 :
159 :
160 : //-----------------------------------------------------------------------------
161 : // vendor
162 :
163 : static Vendors vendor;
164 :
165 0 : static Status InitVendor()
166 : {
167 0 : CpuidRegs regs = { 0 };
168 0 : regs.eax = 0;
169 0 : if(!cpuid(®s))
170 0 : DEBUG_WARN_ERR(ERR::CPU_FEATURE_MISSING);
171 :
172 : // copy regs to string
173 : // note: 'strange' ebx,edx,ecx reg order is due to ModR/M encoding order.
174 0 : char vendorString[13];
175 0 : memcpy(&vendorString[0], ®s.ebx, 4);
176 0 : memcpy(&vendorString[4], ®s.edx, 4);
177 0 : memcpy(&vendorString[8], ®s.ecx, 4);
178 0 : vendorString[12] = '\0'; // 0-terminate
179 :
180 0 : if(!strcmp(vendorString, "AuthenticAMD"))
181 0 : vendor = x86_x64::VENDOR_AMD;
182 0 : else if(!strcmp(vendorString, "GenuineIntel"))
183 0 : vendor = x86_x64::VENDOR_INTEL;
184 : else
185 : {
186 0 : DEBUG_WARN_ERR(ERR::CPU_UNKNOWN_VENDOR);
187 0 : vendor = x86_x64::VENDOR_UNKNOWN;
188 : }
189 :
190 0 : return INFO::OK;
191 : }
192 :
193 0 : Vendors Vendor()
194 : {
195 0 : static ModuleInitState initState{ 0 };
196 0 : ModuleInit(&initState, InitVendor);
197 0 : return vendor;
198 : }
199 :
200 :
201 : //-----------------------------------------------------------------------------
202 : // signature
203 :
204 : static size_t m_Model;
205 : static size_t m_Family;
206 : static ModuleInitState signatureInitState{ 0 };
207 :
208 0 : static Status InitSignature()
209 : {
210 0 : CpuidRegs regs = { 0 };
211 0 : regs.eax = 1;
212 0 : if(!cpuid(®s))
213 0 : DEBUG_WARN_ERR(ERR::CPU_FEATURE_MISSING);
214 0 : m_Model = bits(regs.eax, 4, 7);
215 0 : m_Family = bits(regs.eax, 8, 11);
216 0 : const size_t extendedModel = bits(regs.eax, 16, 19);
217 0 : const size_t extendedFamily = bits(regs.eax, 20, 27);
218 0 : if(m_Family == 0xF)
219 0 : m_Family += extendedFamily;
220 0 : if(m_Family == 0xF || (Vendor() == x86_x64::VENDOR_INTEL && m_Family == 6))
221 0 : m_Model += extendedModel << 4;
222 0 : return INFO::OK;
223 : }
224 :
225 0 : size_t Model()
226 : {
227 0 : ModuleInit(&signatureInitState, InitSignature);
228 0 : return m_Model;
229 : }
230 :
231 0 : size_t Family()
232 : {
233 0 : ModuleInit(&signatureInitState, InitSignature);
234 0 : return m_Family;
235 : }
236 :
237 :
238 :
239 :
240 : //-----------------------------------------------------------------------------
241 : // identifier string
242 :
243 : /// functor to remove substrings from the CPU identifier string
244 : class StringStripper
245 : {
246 : public:
247 0 : StringStripper(char* string, size_t max_chars)
248 : : m_string(string), m_max_chars(max_chars)
249 : {
250 : }
251 :
252 : // remove all instances of substring from m_string
253 0 : void operator()(const char* substring)
254 : {
255 0 : const size_t substring_length = strlen(substring);
256 0 : for(;;)
257 : {
258 0 : char* substring_pos = strstr(m_string, substring);
259 0 : if(!substring_pos)
260 : break;
261 0 : const size_t substring_ofs = substring_pos - m_string;
262 0 : const size_t num_chars = m_max_chars - substring_ofs - substring_length;
263 0 : memmove(substring_pos, substring_pos+substring_length, num_chars);
264 : }
265 0 : }
266 :
267 : private:
268 : char* m_string;
269 : size_t m_max_chars;
270 : };
271 :
272 : // 3 calls x 4 registers x 4 bytes = 48 + 0-terminator
273 : static char identifierString[48+1];
274 :
275 0 : static Status InitIdentifierString()
276 : {
277 : // get brand string (if available)
278 0 : char* pos = identifierString;
279 0 : bool gotBrandString = true;
280 0 : for(std::uint32_t function = 0x80000002; function <= 0x80000004; function++)
281 : {
282 0 : CpuidRegs regs = { 0 };
283 0 : regs.eax = function;
284 0 : gotBrandString &= cpuid(®s);
285 0 : memcpy(pos, ®s, 16);
286 0 : pos += 16;
287 : }
288 :
289 : // fall back to manual detect of CPU type because either:
290 : // - CPU doesn't support brand string (we use a flag to indicate this
291 : // rather than comparing against a default value because it is safer);
292 : // - the brand string is useless, e.g. "Unknown". this happens on
293 : // some older boards whose BIOS reprograms the string for CPUs it
294 : // doesn't recognize.
295 0 : if(!gotBrandString || strncmp(identifierString, "Unknow", 6) == 0)
296 : {
297 0 : const size_t family = Family();
298 0 : const size_t model = Model();
299 0 : switch(Vendor())
300 : {
301 0 : case x86_x64::VENDOR_AMD:
302 : // everything else is either too old, or should have a brand string.
303 0 : if(family == 6)
304 : {
305 0 : if(model == 3 || model == 7)
306 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "AMD Duron");
307 0 : else if(model <= 5)
308 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "AMD Athlon");
309 : else
310 : {
311 0 : if(Cap(x86_x64::CAP_AMD_MP))
312 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "AMD Athlon MP");
313 : else
314 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "AMD Athlon XP");
315 : }
316 : }
317 : break;
318 :
319 0 : case x86_x64::VENDOR_INTEL:
320 : // everything else is either too old, or should have a brand string.
321 0 : if(family == 6)
322 : {
323 0 : if(model == 1)
324 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "Intel Pentium Pro");
325 0 : else if(model == 3 || model == 5)
326 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "Intel Pentium II");
327 0 : else if(model == 6)
328 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "Intel Celeron");
329 : else
330 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "Intel Pentium III");
331 : }
332 : break;
333 :
334 0 : default:
335 0 : strcpy_s(identifierString, ARRAY_SIZE(identifierString), "Unknown, non-Intel/AMD");
336 0 : break;
337 : }
338 : }
339 : // identifierString already holds a valid brand string; pretty it up.
340 : else
341 : {
342 0 : const char* const undesiredStrings[] = { "(tm)", "(TM)", "(R)", "CPU ", " " };
343 0 : std::for_each(undesiredStrings, undesiredStrings+ARRAY_SIZE(undesiredStrings),
344 0 : StringStripper(identifierString, strlen(identifierString)+1));
345 :
346 : // note: Intel brand strings include a frequency, but we can't rely
347 : // on it because the CPU may be overclocked. we'll leave it in the
348 : // string to show measurement accuracy and if SpeedStep is active.
349 : }
350 :
351 0 : return INFO::OK;
352 : }
353 :
354 0 : static const char* IdentifierString()
355 : {
356 0 : static ModuleInitState initState{ 0 };
357 0 : ModuleInit(&initState, InitIdentifierString);
358 0 : return identifierString;
359 : }
360 :
361 :
362 : //-----------------------------------------------------------------------------
363 : // miscellaneous stateless functions
364 :
365 0 : void DebugBreak()
366 : {
367 : #if MSC_VERSION
368 : __debugbreak();
369 : #elif GCC_VERSION
370 : // note: this probably isn't necessary, since unix_debug_break
371 : // (SIGTRAP) is most probably available if GCC_VERSION.
372 : // we include it for completeness, though.
373 0 : __asm__ __volatile__ ("int $3");
374 : #endif
375 0 : }
376 :
377 : } // namespace x86_x64
378 :
379 :
380 0 : const char* cpu_IdentifierString()
381 : {
382 0 : return x86_x64::IdentifierString();
383 : }
|