platformCPUCount.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. // Original code is:
  2. // Copyright (c) 2005 Intel Corporation
  3. // All Rights Reserved
  4. //
  5. // CPUCount.cpp : Detects three forms of hardware multi-threading support across IA-32 platform
  6. // The three forms of HW multithreading are: Multi-processor, Multi-core, and
  7. // HyperThreading Technology.
  8. // This application enumerates all the logical processors enabled by OS and BIOS,
  9. // determine the HW topology of these enabled logical processors in the system
  10. // using information provided by CPUID instruction.
  11. // A multi-processing system can support any combination of the three forms of HW
  12. // multi-threading support. The relevant topology can be identified using a
  13. // three level decomposition of the "initial APIC ID" into
  14. // Package_id, core_id, and SMT_id. Such decomposition provides a three-level map of
  15. // the topology of hardware resources and
  16. // allow multi-threaded software to manage shared hardware resources in
  17. // the platform to reduce resource contention
  18. // Multicore detection algorithm for processor and cache topology requires
  19. // all leaf functions of CPUID instructions be available. System administrator
  20. // must ensure BIOS settings is not configured to restrict CPUID functionalities.
  21. //-------------------------------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "platform/platformCPUCount.h"
  24. // Consoles don't need this
  25. #if defined(TORQUE_OS_XENON) || defined(TORQUE_OS_PS3)
  26. namespace CPUInfo
  27. {
  28. EConfig CPUCount(U32& TotAvailLogical, U32& TotAvailCore, U32& PhysicalNum)
  29. {
  30. TotAvailLogical = 6;
  31. TotAvailCore = 6;
  32. PhysicalNum = 3;
  33. return CONFIG_MultiCoreAndHTEnabled;
  34. }
  35. }; // namespace
  36. #else
  37. #ifdef TORQUE_OS_LINUX
  38. // The Linux source code listing can be compiled using Linux kernel verison 2.6
  39. // or higher (e.g. RH 4AS-2.8 using GCC 3.4.4).
  40. // Due to syntax variances of Linux affinity APIs with earlier kernel versions
  41. // and dependence on glibc library versions, compilation on Linux environment
  42. // with older kernels and compilers may require kernel patches or compiler upgrades.
  43. #include <stdlib.h>
  44. #include <unistd.h>
  45. #include <string.h>
  46. #include <sched.h>
  47. #define DWORD unsigned long
  48. #elif defined( TORQUE_OS_WIN )
  49. #include <windows.h>
  50. #elif defined( TORQUE_OS_MAC )
  51. # include <sys/types.h>
  52. # include <sys/sysctl.h>
  53. #else
  54. #error Not implemented on platform.
  55. #endif
  56. #include <stdio.h>
  57. #include <assert.h>
  58. namespace CPUInfo {
  59. #define HWD_MT_BIT 0x10000000 // EDX[28] Bit 28 is set if HT or multi-core is supported
  60. #define NUM_LOGICAL_BITS 0x00FF0000 // EBX[23:16] Bit 16-23 in ebx contains the number of logical
  61. // processors per physical processor when execute cpuid with
  62. // eax set to 1
  63. #define NUM_CORE_BITS 0xFC000000 // EAX[31:26] Bit 26-31 in eax contains the number of cores minus one
  64. // per physical processor when execute cpuid with
  65. // eax set to 4.
  66. #define INITIAL_APIC_ID_BITS 0xFF000000 // EBX[31:24] Bits 24-31 (8 bits) return the 8-bit unique
  67. // initial APIC ID for the processor this code is running on.
  68. #ifndef TORQUE_OS_MAC
  69. static unsigned int CpuIDSupported(void);
  70. static unsigned int find_maskwidth(unsigned int);
  71. static unsigned int HWD_MTSupported(void);
  72. static unsigned int MaxLogicalProcPerPhysicalProc(void);
  73. static unsigned int MaxCorePerPhysicalProc(void);
  74. static unsigned char GetAPIC_ID(void);
  75. static unsigned char GetNzbSubID(unsigned char, unsigned char, unsigned char);
  76. #endif
  77. static char g_s3Levels[2048];
  78. #ifndef TORQUE_OS_MAC
  79. //
  80. // CpuIDSupported will return 0 if CPUID instruction is unavailable. Otherwise, it will return
  81. // the maximum supported standard function.
  82. //
  83. static unsigned int CpuIDSupported(void)
  84. {
  85. unsigned int maxInputValue = 0;
  86. // If CPUID instruction is supported
  87. #ifdef TORQUE_COMPILER_GCC
  88. try
  89. {
  90. // call cpuid with eax = 0
  91. asm
  92. (
  93. "pushl %%ebx\n\t"
  94. "xorl %%eax,%%eax\n\t"
  95. "cpuid\n\t"
  96. "popl %%ebx\n\t"
  97. : "=a" (maxInputValue)
  98. :
  99. : "%ecx", "%edx"
  100. );
  101. }
  102. catch (...)
  103. {
  104. return(0); // cpuid instruction is unavailable
  105. }
  106. #elif defined( TORQUE_COMPILER_VISUALC )
  107. try
  108. {
  109. // call cpuid with eax = 0
  110. __asm
  111. {
  112. xor eax, eax
  113. cpuid
  114. mov maxInputValue, eax
  115. }
  116. }
  117. catch (...)
  118. {
  119. // cpuid instruction is unavailable
  120. }
  121. #else
  122. # error Not implemented.
  123. #endif
  124. return maxInputValue;
  125. }
  126. //
  127. // Function returns the maximum cores per physical package. Note that the number of
  128. // AVAILABLE cores per physical to be used by an application might be less than this
  129. // maximum value.
  130. //
  131. static unsigned int MaxCorePerPhysicalProc(void)
  132. {
  133. unsigned int Regeax = 0;
  134. if (!HWD_MTSupported()) return (unsigned int) 1; // Single core
  135. #ifdef TORQUE_COMPILER_GCC
  136. {
  137. asm
  138. (
  139. "pushl %ebx\n\t"
  140. "xorl %eax, %eax\n\t"
  141. "cpuid\n\t"
  142. "cmpl $4, %eax\n\t" // check if cpuid supports leaf 4
  143. "jl .single_core\n\t" // Single core
  144. "movl $4, %eax\n\t"
  145. "movl $0, %ecx\n\t" // start with index = 0; Leaf 4 reports
  146. "popl %ebx\n\t"
  147. ); // at least one valid cache level
  148. asm
  149. (
  150. "cpuid"
  151. : "=a" (Regeax)
  152. :
  153. : "%ecx", "%edx"
  154. );
  155. asm
  156. (
  157. "jmp .multi_core\n"
  158. ".single_core:\n\t"
  159. "xor %eax, %eax\n"
  160. ".multi_core:"
  161. );
  162. }
  163. #elif defined( TORQUE_COMPILER_VISUALC )
  164. __asm
  165. {
  166. xor eax, eax
  167. cpuid
  168. cmp eax, 4 // check if cpuid supports leaf 4
  169. jl single_core // Single core
  170. mov eax, 4
  171. mov ecx, 0 // start with index = 0; Leaf 4 reports
  172. cpuid // at least one valid cache level
  173. mov Regeax, eax
  174. jmp multi_core
  175. single_core:
  176. xor eax, eax
  177. multi_core:
  178. }
  179. #else
  180. # error Not implemented.
  181. #endif
  182. return (unsigned int)((Regeax & NUM_CORE_BITS) >> 26)+1;
  183. }
  184. //
  185. // The function returns 0 when the hardware multi-threaded bit is not set.
  186. //
  187. static unsigned int HWD_MTSupported(void)
  188. {
  189. unsigned int Regedx = 0;
  190. if ((CpuIDSupported() >= 1))
  191. {
  192. #ifdef TORQUE_COMPILER_GCC
  193. asm
  194. (
  195. "pushl %%ebx\n\t"
  196. "movl $1,%%eax\n\t"
  197. "cpuid\n\t"
  198. "popl %%ebx\n\t"
  199. : "=d" (Regedx)
  200. :
  201. : "%eax","%ecx"
  202. );
  203. #elif defined( TORQUE_COMPILER_VISUALC )
  204. __asm
  205. {
  206. mov eax, 1
  207. cpuid
  208. mov Regedx, edx
  209. }
  210. #else
  211. # error Not implemented.
  212. #endif
  213. }
  214. return (Regedx & HWD_MT_BIT);
  215. }
  216. //
  217. // Function returns the maximum logical processors per physical package. Note that the number of
  218. // AVAILABLE logical processors per physical to be used by an application might be less than this
  219. // maximum value.
  220. //
  221. static unsigned int MaxLogicalProcPerPhysicalProc(void)
  222. {
  223. unsigned int Regebx = 0;
  224. if (!HWD_MTSupported()) return (unsigned int) 1;
  225. #ifdef TORQUE_COMPILER_GCC
  226. asm
  227. (
  228. "movl $1,%%eax\n\t"
  229. "cpuid"
  230. : "=b" (Regebx)
  231. :
  232. : "%eax","%ecx","%edx"
  233. );
  234. #elif defined( TORQUE_COMPILER_VISUALC )
  235. __asm
  236. {
  237. mov eax, 1
  238. cpuid
  239. mov Regebx, ebx
  240. }
  241. #else
  242. # error Not implemented.
  243. #endif
  244. return (unsigned int) ((Regebx & NUM_LOGICAL_BITS) >> 16);
  245. }
  246. static unsigned char GetAPIC_ID(void)
  247. {
  248. unsigned int Regebx = 0;
  249. #ifdef TORQUE_COMPILER_GCC
  250. asm
  251. (
  252. "movl $1, %%eax\n\t"
  253. "cpuid"
  254. : "=b" (Regebx)
  255. :
  256. : "%eax","%ecx","%edx"
  257. );
  258. #elif defined( TORQUE_COMPILER_VISUALC )
  259. __asm
  260. {
  261. mov eax, 1
  262. cpuid
  263. mov Regebx, ebx
  264. }
  265. #else
  266. # error Not implemented.
  267. #endif
  268. return (unsigned char) ((Regebx & INITIAL_APIC_ID_BITS) >> 24);
  269. }
  270. //
  271. // Determine the width of the bit field that can represent the value count_item.
  272. //
  273. unsigned int find_maskwidth(unsigned int CountItem)
  274. {
  275. unsigned int MaskWidth,
  276. count = CountItem;
  277. #ifdef TORQUE_COMPILER_GCC
  278. asm
  279. (
  280. #ifdef __x86_64__ // define constant to compile
  281. "push %%rcx\n\t" // under 64-bit Linux
  282. "push %%rax\n\t"
  283. #else
  284. "pushl %%ecx\n\t"
  285. "pushl %%eax\n\t"
  286. #endif
  287. // "movl $count, %%eax\n\t" //done by Assembler below
  288. "xorl %%ecx, %%ecx"
  289. // "movl %%ecx, MaskWidth\n\t" //done by Assembler below
  290. : "=c" (MaskWidth)
  291. : "a" (count)
  292. // : "%ecx", "%eax" We don't list these as clobbered because we don't want the assembler
  293. //to put them back when we are done
  294. );
  295. asm
  296. (
  297. "decl %%eax\n\t"
  298. "bsrw %%ax,%%cx\n\t"
  299. "jz next\n\t"
  300. "incw %%cx\n\t"
  301. // "movl %%ecx, MaskWidth\n" //done by Assembler below
  302. : "=c" (MaskWidth)
  303. :
  304. );
  305. asm
  306. (
  307. "next:\n\t"
  308. #ifdef __x86_64__
  309. "pop %rax\n\t"
  310. "pop %rcx"
  311. #else
  312. "popl %eax\n\t"
  313. "popl %ecx"
  314. #endif
  315. );
  316. #elif defined( TORQUE_COMPILER_VISUALC )
  317. __asm
  318. {
  319. mov eax, count
  320. mov ecx, 0
  321. mov MaskWidth, ecx
  322. dec eax
  323. bsr cx, ax
  324. jz next
  325. inc cx
  326. mov MaskWidth, ecx
  327. next:
  328. }
  329. #else
  330. # error Not implemented.
  331. #endif
  332. return MaskWidth;
  333. }
  334. //
  335. // Extract the subset of bit field from the 8-bit value FullID. It returns the 8-bit sub ID value
  336. //
  337. static unsigned char GetNzbSubID(unsigned char FullID,
  338. unsigned char MaxSubIDValue,
  339. unsigned char ShiftCount)
  340. {
  341. unsigned int MaskWidth;
  342. unsigned char MaskBits;
  343. MaskWidth = find_maskwidth((unsigned int) MaxSubIDValue);
  344. MaskBits = (0xff << ShiftCount) ^
  345. ((unsigned char) (0xff << (ShiftCount + MaskWidth)));
  346. return (FullID & MaskBits);
  347. }
  348. #endif
  349. //
  350. //
  351. //
  352. EConfig CPUCount(U32& TotAvailLogical, U32& TotAvailCore, U32& PhysicalNum)
  353. {
  354. EConfig StatusFlag = CONFIG_UserConfigIssue;
  355. g_s3Levels[0] = 0;
  356. TotAvailCore = 1;
  357. PhysicalNum = 1;
  358. unsigned int numLPEnabled = 0;
  359. int MaxLPPerCore = 1;
  360. #ifdef TORQUE_OS_MAC
  361. //FIXME: This isn't a proper port but more or less just some sneaky cheating
  362. // to get around having to mess with yet another crap UNIX-style API. Seems
  363. // like there isn't a way to do this that's working across all OSX incarnations
  364. // and machine configurations anyway.
  365. int numCPUs;
  366. int numPackages;
  367. // Get the number of CPUs.
  368. size_t len = sizeof( numCPUs );
  369. if( sysctlbyname( "hw.ncpu", &numCPUs, &len, 0, 0 ) == -1 )
  370. return CONFIG_UserConfigIssue;
  371. // Get the number of packages.
  372. len = sizeof( numPackages );
  373. if( sysctlbyname( "hw.packages", &numPackages, &len, 0, 0 ) == -1 )
  374. return CONFIG_UserConfigIssue;
  375. TotAvailCore = numCPUs;
  376. TotAvailLogical = numCPUs;
  377. PhysicalNum = numPackages;
  378. #else
  379. U32 dwAffinityMask;
  380. int j = 0;
  381. unsigned char apicID, PackageIDMask;
  382. unsigned char tblPkgID[256], tblCoreID[256], tblSMTID[256];
  383. char tmp[256];
  384. #ifdef TORQUE_OS_LINUX
  385. //we need to make sure that this process is allowed to run on
  386. //all of the logical processors that the OS itself can run on.
  387. //A process could acquire/inherit affinity settings that restricts the
  388. // current process to run on a subset of all logical processor visible to OS.
  389. // Linux doesn't easily allow us to look at the Affinity Bitmask directly,
  390. // but it does provide an API to test affinity maskbits of the current process
  391. // against each logical processor visible under OS.
  392. int sysNumProcs = sysconf(_SC_NPROCESSORS_CONF); //This will tell us how many
  393. //CPUs are currently enabled.
  394. //this will tell us which processors this process can run on.
  395. cpu_set_t allowedCPUs;
  396. sched_getaffinity(0, sizeof(allowedCPUs), &allowedCPUs);
  397. for (int i = 0; i < sysNumProcs; i++ )
  398. {
  399. if ( CPU_ISSET(i, &allowedCPUs) == 0 )
  400. return CONFIG_UserConfigIssue;
  401. }
  402. #elif defined( TORQUE_OS_WIN )
  403. DWORD dwProcessAffinity, dwSystemAffinity;
  404. GetProcessAffinityMask(GetCurrentProcess(),
  405. &dwProcessAffinity,
  406. &dwSystemAffinity);
  407. if (dwProcessAffinity != dwSystemAffinity) // not all CPUs are enabled
  408. return CONFIG_UserConfigIssue;
  409. #else
  410. # error Not implemented.
  411. #endif
  412. // Assume that cores within a package have the SAME number of
  413. // logical processors. Also, values returned by
  414. // MaxLogicalProcPerPhysicalProc and MaxCorePerPhysicalProc do not have
  415. // to be power of 2.
  416. MaxLPPerCore = MaxLogicalProcPerPhysicalProc() / MaxCorePerPhysicalProc();
  417. dwAffinityMask = 1;
  418. #ifdef TORQUE_OS_LINUX
  419. cpu_set_t currentCPU;
  420. while ( j < sysNumProcs )
  421. {
  422. CPU_ZERO(&currentCPU);
  423. CPU_SET(j, &currentCPU);
  424. if ( sched_setaffinity (0, sizeof(currentCPU), &currentCPU) == 0 )
  425. {
  426. sleep(0); // Ensure system to switch to the right CPU
  427. #elif defined( TORQUE_OS_WIN )
  428. while (dwAffinityMask && dwAffinityMask <= dwSystemAffinity)
  429. {
  430. if (SetThreadAffinityMask(GetCurrentThread(), dwAffinityMask))
  431. {
  432. Sleep(0); // Ensure system to switch to the right CPU
  433. #else
  434. # error Not implemented.
  435. #endif
  436. apicID = GetAPIC_ID();
  437. // Store SMT ID and core ID of each logical processor
  438. // Shift vlaue for SMT ID is 0
  439. // Shift value for core ID is the mask width for maximum logical
  440. // processors per core
  441. tblSMTID[j] = GetNzbSubID(apicID, MaxLPPerCore, 0);
  442. unsigned char maxCorePPP = MaxCorePerPhysicalProc();
  443. unsigned char maskWidth = find_maskwidth(MaxLPPerCore);
  444. tblCoreID[j] = GetNzbSubID(apicID, maxCorePPP, maskWidth);
  445. // Extract package ID, assume single cluster.
  446. // Shift value is the mask width for max Logical per package
  447. PackageIDMask = (unsigned char) (0xff <<
  448. find_maskwidth(MaxLogicalProcPerPhysicalProc()));
  449. tblPkgID[j] = apicID & PackageIDMask;
  450. sprintf(tmp," AffinityMask = %d; Initial APIC = %d; Physical ID = %d, Core ID = %d, SMT ID = %d\n",
  451. dwAffinityMask, apicID, tblPkgID[j], tblCoreID[j], tblSMTID[j]);
  452. strcat(g_s3Levels, tmp);
  453. numLPEnabled ++; // Number of available logical processors in the system.
  454. } // if
  455. j++;
  456. dwAffinityMask = 1 << j;
  457. } // while
  458. // restore the affinity setting to its original state
  459. #ifdef TORQUE_OS_LINUX
  460. sched_setaffinity (0, sizeof(allowedCPUs), &allowedCPUs);
  461. sleep(0);
  462. #elif defined( TORQUE_OS_WIN )
  463. SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinity);
  464. Sleep(0);
  465. #else
  466. # error Not implemented.
  467. #endif
  468. TotAvailLogical = numLPEnabled;
  469. //
  470. // Count available cores (TotAvailCore) in the system
  471. //
  472. unsigned char CoreIDBucket[256];
  473. DWORD ProcessorMask, pCoreMask[256];
  474. unsigned int i, ProcessorNum;
  475. CoreIDBucket[0] = tblPkgID[0] | tblCoreID[0];
  476. ProcessorMask = 1;
  477. pCoreMask[0] = ProcessorMask;
  478. for (ProcessorNum = 1; ProcessorNum < numLPEnabled; ProcessorNum++)
  479. {
  480. ProcessorMask <<= 1;
  481. for (i = 0; i < TotAvailCore; i++)
  482. {
  483. // Comparing bit-fields of logical processors residing in different packages
  484. // Assuming the bit-masks are the same on all processors in the system.
  485. if ((tblPkgID[ProcessorNum] | tblCoreID[ProcessorNum]) == CoreIDBucket[i])
  486. {
  487. pCoreMask[i] |= ProcessorMask;
  488. break;
  489. }
  490. } // for i
  491. if (i == TotAvailCore) // did not match any bucket. Start a new one.
  492. {
  493. CoreIDBucket[i] = tblPkgID[ProcessorNum] | tblCoreID[ProcessorNum];
  494. pCoreMask[i] = ProcessorMask;
  495. TotAvailCore++; // Number of available cores in the system
  496. }
  497. } // for ProcessorNum
  498. //
  499. // Count physical processor (PhysicalNum) in the system
  500. //
  501. unsigned char PackageIDBucket[256];
  502. DWORD pPackageMask[256];
  503. PackageIDBucket[0] = tblPkgID[0];
  504. ProcessorMask = 1;
  505. pPackageMask[0] = ProcessorMask;
  506. for (ProcessorNum = 1; ProcessorNum < numLPEnabled; ProcessorNum++)
  507. {
  508. ProcessorMask <<= 1;
  509. for (i = 0; i < PhysicalNum; i++)
  510. {
  511. // Comparing bit-fields of logical processors residing in different packages
  512. // Assuming the bit-masks are the same on all processors in the system.
  513. if (tblPkgID[ProcessorNum]== PackageIDBucket[i])
  514. {
  515. pPackageMask[i] |= ProcessorMask;
  516. break;
  517. }
  518. } // for i
  519. if (i == PhysicalNum) // did not match any bucket. Start a new one.
  520. {
  521. PackageIDBucket[i] = tblPkgID[ProcessorNum];
  522. pPackageMask[i] = ProcessorMask;
  523. PhysicalNum++; // Total number of physical processors in the system
  524. }
  525. } // for ProcessorNum
  526. #endif
  527. //
  528. // Check to see if the system is multi-core
  529. // Check if the system is hyper-threading
  530. //
  531. if (TotAvailCore > PhysicalNum)
  532. {
  533. // Multi-core
  534. if (MaxLPPerCore == 1)
  535. StatusFlag = CONFIG_MultiCoreAndHTNotCapable;
  536. else if (numLPEnabled > TotAvailCore)
  537. StatusFlag = CONFIG_MultiCoreAndHTEnabled;
  538. else StatusFlag = CONFIG_MultiCoreAndHTDisabled;
  539. }
  540. else
  541. {
  542. // Single-core
  543. if (MaxLPPerCore == 1)
  544. StatusFlag = CONFIG_SingleCoreAndHTNotCapable;
  545. else if (numLPEnabled > TotAvailCore)
  546. StatusFlag = CONFIG_SingleCoreHTEnabled;
  547. else StatusFlag = CONFIG_SingleCoreHTDisabled;
  548. }
  549. return StatusFlag;
  550. }
  551. } // namespace CPUInfo
  552. #endif