kmp_affinity.h 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. /*
  2. * kmp_affinity.h -- header for affinity management
  3. */
  4. //===----------------------------------------------------------------------===//
  5. //
  6. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  7. // See https://llvm.org/LICENSE.txt for license information.
  8. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  9. //
  10. //===----------------------------------------------------------------------===//
  11. #ifndef KMP_AFFINITY_H
  12. #define KMP_AFFINITY_H
  13. #include "kmp.h"
  14. #include "kmp_os.h"
  15. #include <limits>
  16. #if KMP_AFFINITY_SUPPORTED
  17. #if KMP_USE_HWLOC
  18. class KMPHwlocAffinity : public KMPAffinity {
  19. public:
  20. class Mask : public KMPAffinity::Mask {
  21. hwloc_cpuset_t mask;
  22. public:
  23. Mask() {
  24. mask = hwloc_bitmap_alloc();
  25. this->zero();
  26. }
  27. ~Mask() { hwloc_bitmap_free(mask); }
  28. void set(int i) override { hwloc_bitmap_set(mask, i); }
  29. bool is_set(int i) const override { return hwloc_bitmap_isset(mask, i); }
  30. void clear(int i) override { hwloc_bitmap_clr(mask, i); }
  31. void zero() override { hwloc_bitmap_zero(mask); }
  32. void copy(const KMPAffinity::Mask *src) override {
  33. const Mask *convert = static_cast<const Mask *>(src);
  34. hwloc_bitmap_copy(mask, convert->mask);
  35. }
  36. void bitwise_and(const KMPAffinity::Mask *rhs) override {
  37. const Mask *convert = static_cast<const Mask *>(rhs);
  38. hwloc_bitmap_and(mask, mask, convert->mask);
  39. }
  40. void bitwise_or(const KMPAffinity::Mask *rhs) override {
  41. const Mask *convert = static_cast<const Mask *>(rhs);
  42. hwloc_bitmap_or(mask, mask, convert->mask);
  43. }
  44. void bitwise_not() override { hwloc_bitmap_not(mask, mask); }
  45. int begin() const override { return hwloc_bitmap_first(mask); }
  46. int end() const override { return -1; }
  47. int next(int previous) const override {
  48. return hwloc_bitmap_next(mask, previous);
  49. }
  50. int get_system_affinity(bool abort_on_error) override {
  51. KMP_ASSERT2(KMP_AFFINITY_CAPABLE(),
  52. "Illegal get affinity operation when not capable");
  53. long retval =
  54. hwloc_get_cpubind(__kmp_hwloc_topology, mask, HWLOC_CPUBIND_THREAD);
  55. if (retval >= 0) {
  56. return 0;
  57. }
  58. int error = errno;
  59. if (abort_on_error) {
  60. __kmp_fatal(KMP_MSG(FatalSysError), KMP_ERR(error), __kmp_msg_null);
  61. }
  62. return error;
  63. }
  64. int set_system_affinity(bool abort_on_error) const override {
  65. KMP_ASSERT2(KMP_AFFINITY_CAPABLE(),
  66. "Illegal set affinity operation when not capable");
  67. long retval =
  68. hwloc_set_cpubind(__kmp_hwloc_topology, mask, HWLOC_CPUBIND_THREAD);
  69. if (retval >= 0) {
  70. return 0;
  71. }
  72. int error = errno;
  73. if (abort_on_error) {
  74. __kmp_fatal(KMP_MSG(FatalSysError), KMP_ERR(error), __kmp_msg_null);
  75. }
  76. return error;
  77. }
  78. #if KMP_OS_WINDOWS
  79. int set_process_affinity(bool abort_on_error) const override {
  80. KMP_ASSERT2(KMP_AFFINITY_CAPABLE(),
  81. "Illegal set process affinity operation when not capable");
  82. int error = 0;
  83. const hwloc_topology_support *support =
  84. hwloc_topology_get_support(__kmp_hwloc_topology);
  85. if (support->cpubind->set_proc_cpubind) {
  86. int retval;
  87. retval = hwloc_set_cpubind(__kmp_hwloc_topology, mask,
  88. HWLOC_CPUBIND_PROCESS);
  89. if (retval >= 0)
  90. return 0;
  91. error = errno;
  92. if (abort_on_error)
  93. __kmp_fatal(KMP_MSG(FatalSysError), KMP_ERR(error), __kmp_msg_null);
  94. }
  95. return error;
  96. }
  97. #endif
  98. int get_proc_group() const override {
  99. int group = -1;
  100. #if KMP_OS_WINDOWS
  101. if (__kmp_num_proc_groups == 1) {
  102. return 1;
  103. }
  104. for (int i = 0; i < __kmp_num_proc_groups; i++) {
  105. // On windows, the long type is always 32 bits
  106. unsigned long first_32_bits = hwloc_bitmap_to_ith_ulong(mask, i * 2);
  107. unsigned long second_32_bits =
  108. hwloc_bitmap_to_ith_ulong(mask, i * 2 + 1);
  109. if (first_32_bits == 0 && second_32_bits == 0) {
  110. continue;
  111. }
  112. if (group >= 0) {
  113. return -1;
  114. }
  115. group = i;
  116. }
  117. #endif /* KMP_OS_WINDOWS */
  118. return group;
  119. }
  120. };
  121. void determine_capable(const char *var) override {
  122. const hwloc_topology_support *topology_support;
  123. if (__kmp_hwloc_topology == NULL) {
  124. if (hwloc_topology_init(&__kmp_hwloc_topology) < 0) {
  125. __kmp_hwloc_error = TRUE;
  126. if (__kmp_affinity_verbose)
  127. KMP_WARNING(AffHwlocErrorOccurred, var, "hwloc_topology_init()");
  128. }
  129. if (hwloc_topology_load(__kmp_hwloc_topology) < 0) {
  130. __kmp_hwloc_error = TRUE;
  131. if (__kmp_affinity_verbose)
  132. KMP_WARNING(AffHwlocErrorOccurred, var, "hwloc_topology_load()");
  133. }
  134. }
  135. topology_support = hwloc_topology_get_support(__kmp_hwloc_topology);
  136. // Is the system capable of setting/getting this thread's affinity?
  137. // Also, is topology discovery possible? (pu indicates ability to discover
  138. // processing units). And finally, were there no errors when calling any
  139. // hwloc_* API functions?
  140. if (topology_support && topology_support->cpubind->set_thisthread_cpubind &&
  141. topology_support->cpubind->get_thisthread_cpubind &&
  142. topology_support->discovery->pu && !__kmp_hwloc_error) {
  143. // enables affinity according to KMP_AFFINITY_CAPABLE() macro
  144. KMP_AFFINITY_ENABLE(TRUE);
  145. } else {
  146. // indicate that hwloc didn't work and disable affinity
  147. __kmp_hwloc_error = TRUE;
  148. KMP_AFFINITY_DISABLE();
  149. }
  150. }
  151. void bind_thread(int which) override {
  152. KMP_ASSERT2(KMP_AFFINITY_CAPABLE(),
  153. "Illegal set affinity operation when not capable");
  154. KMPAffinity::Mask *mask;
  155. KMP_CPU_ALLOC_ON_STACK(mask);
  156. KMP_CPU_ZERO(mask);
  157. KMP_CPU_SET(which, mask);
  158. __kmp_set_system_affinity(mask, TRUE);
  159. KMP_CPU_FREE_FROM_STACK(mask);
  160. }
  161. KMPAffinity::Mask *allocate_mask() override { return new Mask(); }
  162. void deallocate_mask(KMPAffinity::Mask *m) override { delete m; }
  163. KMPAffinity::Mask *allocate_mask_array(int num) override {
  164. return new Mask[num];
  165. }
  166. void deallocate_mask_array(KMPAffinity::Mask *array) override {
  167. Mask *hwloc_array = static_cast<Mask *>(array);
  168. delete[] hwloc_array;
  169. }
  170. KMPAffinity::Mask *index_mask_array(KMPAffinity::Mask *array,
  171. int index) override {
  172. Mask *hwloc_array = static_cast<Mask *>(array);
  173. return &(hwloc_array[index]);
  174. }
  175. api_type get_api_type() const override { return HWLOC; }
  176. };
  177. #endif /* KMP_USE_HWLOC */
  178. #if KMP_OS_LINUX || KMP_OS_FREEBSD
  179. #if KMP_OS_LINUX
  180. /* On some of the older OS's that we build on, these constants aren't present
  181. in <asm/unistd.h> #included from <sys.syscall.h>. They must be the same on
  182. all systems of the same arch where they are defined, and they cannot change.
  183. stone forever. */
  184. #include <sys/syscall.h>
  185. #if KMP_ARCH_X86 || KMP_ARCH_ARM
  186. #ifndef __NR_sched_setaffinity
  187. #define __NR_sched_setaffinity 241
  188. #elif __NR_sched_setaffinity != 241
  189. #error Wrong code for setaffinity system call.
  190. #endif /* __NR_sched_setaffinity */
  191. #ifndef __NR_sched_getaffinity
  192. #define __NR_sched_getaffinity 242
  193. #elif __NR_sched_getaffinity != 242
  194. #error Wrong code for getaffinity system call.
  195. #endif /* __NR_sched_getaffinity */
  196. #elif KMP_ARCH_AARCH64
  197. #ifndef __NR_sched_setaffinity
  198. #define __NR_sched_setaffinity 122
  199. #elif __NR_sched_setaffinity != 122
  200. #error Wrong code for setaffinity system call.
  201. #endif /* __NR_sched_setaffinity */
  202. #ifndef __NR_sched_getaffinity
  203. #define __NR_sched_getaffinity 123
  204. #elif __NR_sched_getaffinity != 123
  205. #error Wrong code for getaffinity system call.
  206. #endif /* __NR_sched_getaffinity */
  207. #elif KMP_ARCH_X86_64
  208. #ifndef __NR_sched_setaffinity
  209. #define __NR_sched_setaffinity 203
  210. #elif __NR_sched_setaffinity != 203
  211. #error Wrong code for setaffinity system call.
  212. #endif /* __NR_sched_setaffinity */
  213. #ifndef __NR_sched_getaffinity
  214. #define __NR_sched_getaffinity 204
  215. #elif __NR_sched_getaffinity != 204
  216. #error Wrong code for getaffinity system call.
  217. #endif /* __NR_sched_getaffinity */
  218. #elif KMP_ARCH_PPC64
  219. #ifndef __NR_sched_setaffinity
  220. #define __NR_sched_setaffinity 222
  221. #elif __NR_sched_setaffinity != 222
  222. #error Wrong code for setaffinity system call.
  223. #endif /* __NR_sched_setaffinity */
  224. #ifndef __NR_sched_getaffinity
  225. #define __NR_sched_getaffinity 223
  226. #elif __NR_sched_getaffinity != 223
  227. #error Wrong code for getaffinity system call.
  228. #endif /* __NR_sched_getaffinity */
  229. #elif KMP_ARCH_MIPS
  230. #ifndef __NR_sched_setaffinity
  231. #define __NR_sched_setaffinity 4239
  232. #elif __NR_sched_setaffinity != 4239
  233. #error Wrong code for setaffinity system call.
  234. #endif /* __NR_sched_setaffinity */
  235. #ifndef __NR_sched_getaffinity
  236. #define __NR_sched_getaffinity 4240
  237. #elif __NR_sched_getaffinity != 4240
  238. #error Wrong code for getaffinity system call.
  239. #endif /* __NR_sched_getaffinity */
  240. #elif KMP_ARCH_MIPS64
  241. #ifndef __NR_sched_setaffinity
  242. #define __NR_sched_setaffinity 5195
  243. #elif __NR_sched_setaffinity != 5195
  244. #error Wrong code for setaffinity system call.
  245. #endif /* __NR_sched_setaffinity */
  246. #ifndef __NR_sched_getaffinity
  247. #define __NR_sched_getaffinity 5196
  248. #elif __NR_sched_getaffinity != 5196
  249. #error Wrong code for getaffinity system call.
  250. #endif /* __NR_sched_getaffinity */
  251. #error Unknown or unsupported architecture
  252. #endif /* KMP_ARCH_* */
  253. #elif KMP_OS_FREEBSD
  254. #include <pthread.h>
  255. #include <pthread_np.h>
  256. #endif
  257. class KMPNativeAffinity : public KMPAffinity {
  258. class Mask : public KMPAffinity::Mask {
  259. typedef unsigned long mask_t;
  260. typedef decltype(__kmp_affin_mask_size) mask_size_type;
  261. static const unsigned int BITS_PER_MASK_T = sizeof(mask_t) * CHAR_BIT;
  262. static const mask_t ONE = 1;
  263. mask_size_type get_num_mask_types() const {
  264. return __kmp_affin_mask_size / sizeof(mask_t);
  265. }
  266. public:
  267. mask_t *mask;
  268. Mask() { mask = (mask_t *)__kmp_allocate(__kmp_affin_mask_size); }
  269. ~Mask() {
  270. if (mask)
  271. __kmp_free(mask);
  272. }
  273. void set(int i) override {
  274. mask[i / BITS_PER_MASK_T] |= (ONE << (i % BITS_PER_MASK_T));
  275. }
  276. bool is_set(int i) const override {
  277. return (mask[i / BITS_PER_MASK_T] & (ONE << (i % BITS_PER_MASK_T)));
  278. }
  279. void clear(int i) override {
  280. mask[i / BITS_PER_MASK_T] &= ~(ONE << (i % BITS_PER_MASK_T));
  281. }
  282. void zero() override {
  283. mask_size_type e = get_num_mask_types();
  284. for (mask_size_type i = 0; i < e; ++i)
  285. mask[i] = (mask_t)0;
  286. }
  287. void copy(const KMPAffinity::Mask *src) override {
  288. const Mask *convert = static_cast<const Mask *>(src);
  289. mask_size_type e = get_num_mask_types();
  290. for (mask_size_type i = 0; i < e; ++i)
  291. mask[i] = convert->mask[i];
  292. }
  293. void bitwise_and(const KMPAffinity::Mask *rhs) override {
  294. const Mask *convert = static_cast<const Mask *>(rhs);
  295. mask_size_type e = get_num_mask_types();
  296. for (mask_size_type i = 0; i < e; ++i)
  297. mask[i] &= convert->mask[i];
  298. }
  299. void bitwise_or(const KMPAffinity::Mask *rhs) override {
  300. const Mask *convert = static_cast<const Mask *>(rhs);
  301. mask_size_type e = get_num_mask_types();
  302. for (mask_size_type i = 0; i < e; ++i)
  303. mask[i] |= convert->mask[i];
  304. }
  305. void bitwise_not() override {
  306. mask_size_type e = get_num_mask_types();
  307. for (mask_size_type i = 0; i < e; ++i)
  308. mask[i] = ~(mask[i]);
  309. }
  310. int begin() const override {
  311. int retval = 0;
  312. while (retval < end() && !is_set(retval))
  313. ++retval;
  314. return retval;
  315. }
  316. int end() const override {
  317. int e;
  318. __kmp_type_convert(get_num_mask_types() * BITS_PER_MASK_T, &e);
  319. return e;
  320. }
  321. int next(int previous) const override {
  322. int retval = previous + 1;
  323. while (retval < end() && !is_set(retval))
  324. ++retval;
  325. return retval;
  326. }
  327. int get_system_affinity(bool abort_on_error) override {
  328. KMP_ASSERT2(KMP_AFFINITY_CAPABLE(),
  329. "Illegal get affinity operation when not capable");
  330. #if KMP_OS_LINUX
  331. long retval =
  332. syscall(__NR_sched_getaffinity, 0, __kmp_affin_mask_size, mask);
  333. #elif KMP_OS_FREEBSD
  334. int r = pthread_getaffinity_np(pthread_self(), __kmp_affin_mask_size,
  335. reinterpret_cast<cpuset_t *>(mask));
  336. int retval = (r == 0 ? 0 : -1);
  337. #endif
  338. if (retval >= 0) {
  339. return 0;
  340. }
  341. int error = errno;
  342. if (abort_on_error) {
  343. __kmp_fatal(KMP_MSG(FatalSysError), KMP_ERR(error), __kmp_msg_null);
  344. }
  345. return error;
  346. }
  347. int set_system_affinity(bool abort_on_error) const override {
  348. KMP_ASSERT2(KMP_AFFINITY_CAPABLE(),
  349. "Illegal set affinity operation when not capable");
  350. #if KMP_OS_LINUX
  351. long retval =
  352. syscall(__NR_sched_setaffinity, 0, __kmp_affin_mask_size, mask);
  353. #elif KMP_OS_FREEBSD
  354. int r = pthread_setaffinity_np(pthread_self(), __kmp_affin_mask_size,
  355. reinterpret_cast<cpuset_t *>(mask));
  356. int retval = (r == 0 ? 0 : -1);
  357. #endif
  358. if (retval >= 0) {
  359. return 0;
  360. }
  361. int error = errno;
  362. if (abort_on_error) {
  363. __kmp_fatal(KMP_MSG(FatalSysError), KMP_ERR(error), __kmp_msg_null);
  364. }
  365. return error;
  366. }
  367. };
  368. void determine_capable(const char *env_var) override {
  369. __kmp_affinity_determine_capable(env_var);
  370. }
  371. void bind_thread(int which) override { __kmp_affinity_bind_thread(which); }
  372. KMPAffinity::Mask *allocate_mask() override {
  373. KMPNativeAffinity::Mask *retval = new Mask();
  374. return retval;
  375. }
  376. void deallocate_mask(KMPAffinity::Mask *m) override {
  377. KMPNativeAffinity::Mask *native_mask =
  378. static_cast<KMPNativeAffinity::Mask *>(m);
  379. delete native_mask;
  380. }
  381. KMPAffinity::Mask *allocate_mask_array(int num) override {
  382. return new Mask[num];
  383. }
  384. void deallocate_mask_array(KMPAffinity::Mask *array) override {
  385. Mask *linux_array = static_cast<Mask *>(array);
  386. delete[] linux_array;
  387. }
  388. KMPAffinity::Mask *index_mask_array(KMPAffinity::Mask *array,
  389. int index) override {
  390. Mask *linux_array = static_cast<Mask *>(array);
  391. return &(linux_array[index]);
  392. }
  393. api_type get_api_type() const override { return NATIVE_OS; }
  394. };
  395. #endif /* KMP_OS_LINUX || KMP_OS_FREEBSD */
  396. #if KMP_OS_WINDOWS
  397. class KMPNativeAffinity : public KMPAffinity {
  398. class Mask : public KMPAffinity::Mask {
  399. typedef ULONG_PTR mask_t;
  400. static const int BITS_PER_MASK_T = sizeof(mask_t) * CHAR_BIT;
  401. mask_t *mask;
  402. public:
  403. Mask() {
  404. mask = (mask_t *)__kmp_allocate(sizeof(mask_t) * __kmp_num_proc_groups);
  405. }
  406. ~Mask() {
  407. if (mask)
  408. __kmp_free(mask);
  409. }
  410. void set(int i) override {
  411. mask[i / BITS_PER_MASK_T] |= ((mask_t)1 << (i % BITS_PER_MASK_T));
  412. }
  413. bool is_set(int i) const override {
  414. return (mask[i / BITS_PER_MASK_T] & ((mask_t)1 << (i % BITS_PER_MASK_T)));
  415. }
  416. void clear(int i) override {
  417. mask[i / BITS_PER_MASK_T] &= ~((mask_t)1 << (i % BITS_PER_MASK_T));
  418. }
  419. void zero() override {
  420. for (int i = 0; i < __kmp_num_proc_groups; ++i)
  421. mask[i] = 0;
  422. }
  423. void copy(const KMPAffinity::Mask *src) override {
  424. const Mask *convert = static_cast<const Mask *>(src);
  425. for (int i = 0; i < __kmp_num_proc_groups; ++i)
  426. mask[i] = convert->mask[i];
  427. }
  428. void bitwise_and(const KMPAffinity::Mask *rhs) override {
  429. const Mask *convert = static_cast<const Mask *>(rhs);
  430. for (int i = 0; i < __kmp_num_proc_groups; ++i)
  431. mask[i] &= convert->mask[i];
  432. }
  433. void bitwise_or(const KMPAffinity::Mask *rhs) override {
  434. const Mask *convert = static_cast<const Mask *>(rhs);
  435. for (int i = 0; i < __kmp_num_proc_groups; ++i)
  436. mask[i] |= convert->mask[i];
  437. }
  438. void bitwise_not() override {
  439. for (int i = 0; i < __kmp_num_proc_groups; ++i)
  440. mask[i] = ~(mask[i]);
  441. }
  442. int begin() const override {
  443. int retval = 0;
  444. while (retval < end() && !is_set(retval))
  445. ++retval;
  446. return retval;
  447. }
  448. int end() const override { return __kmp_num_proc_groups * BITS_PER_MASK_T; }
  449. int next(int previous) const override {
  450. int retval = previous + 1;
  451. while (retval < end() && !is_set(retval))
  452. ++retval;
  453. return retval;
  454. }
  455. int set_process_affinity(bool abort_on_error) const override {
  456. if (__kmp_num_proc_groups <= 1) {
  457. if (!SetProcessAffinityMask(GetCurrentProcess(), *mask)) {
  458. DWORD error = GetLastError();
  459. if (abort_on_error) {
  460. __kmp_fatal(KMP_MSG(CantSetThreadAffMask), KMP_ERR(error),
  461. __kmp_msg_null);
  462. }
  463. return error;
  464. }
  465. }
  466. return 0;
  467. }
  468. int set_system_affinity(bool abort_on_error) const override {
  469. if (__kmp_num_proc_groups > 1) {
  470. // Check for a valid mask.
  471. GROUP_AFFINITY ga;
  472. int group = get_proc_group();
  473. if (group < 0) {
  474. if (abort_on_error) {
  475. KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
  476. }
  477. return -1;
  478. }
  479. // Transform the bit vector into a GROUP_AFFINITY struct
  480. // and make the system call to set affinity.
  481. ga.Group = group;
  482. ga.Mask = mask[group];
  483. ga.Reserved[0] = ga.Reserved[1] = ga.Reserved[2] = 0;
  484. KMP_DEBUG_ASSERT(__kmp_SetThreadGroupAffinity != NULL);
  485. if (__kmp_SetThreadGroupAffinity(GetCurrentThread(), &ga, NULL) == 0) {
  486. DWORD error = GetLastError();
  487. if (abort_on_error) {
  488. __kmp_fatal(KMP_MSG(CantSetThreadAffMask), KMP_ERR(error),
  489. __kmp_msg_null);
  490. }
  491. return error;
  492. }
  493. } else {
  494. if (!SetThreadAffinityMask(GetCurrentThread(), *mask)) {
  495. DWORD error = GetLastError();
  496. if (abort_on_error) {
  497. __kmp_fatal(KMP_MSG(CantSetThreadAffMask), KMP_ERR(error),
  498. __kmp_msg_null);
  499. }
  500. return error;
  501. }
  502. }
  503. return 0;
  504. }
  505. int get_system_affinity(bool abort_on_error) override {
  506. if (__kmp_num_proc_groups > 1) {
  507. this->zero();
  508. GROUP_AFFINITY ga;
  509. KMP_DEBUG_ASSERT(__kmp_GetThreadGroupAffinity != NULL);
  510. if (__kmp_GetThreadGroupAffinity(GetCurrentThread(), &ga) == 0) {
  511. DWORD error = GetLastError();
  512. if (abort_on_error) {
  513. __kmp_fatal(KMP_MSG(FunctionError, "GetThreadGroupAffinity()"),
  514. KMP_ERR(error), __kmp_msg_null);
  515. }
  516. return error;
  517. }
  518. if ((ga.Group < 0) || (ga.Group > __kmp_num_proc_groups) ||
  519. (ga.Mask == 0)) {
  520. return -1;
  521. }
  522. mask[ga.Group] = ga.Mask;
  523. } else {
  524. mask_t newMask, sysMask, retval;
  525. if (!GetProcessAffinityMask(GetCurrentProcess(), &newMask, &sysMask)) {
  526. DWORD error = GetLastError();
  527. if (abort_on_error) {
  528. __kmp_fatal(KMP_MSG(FunctionError, "GetProcessAffinityMask()"),
  529. KMP_ERR(error), __kmp_msg_null);
  530. }
  531. return error;
  532. }
  533. retval = SetThreadAffinityMask(GetCurrentThread(), newMask);
  534. if (!retval) {
  535. DWORD error = GetLastError();
  536. if (abort_on_error) {
  537. __kmp_fatal(KMP_MSG(FunctionError, "SetThreadAffinityMask()"),
  538. KMP_ERR(error), __kmp_msg_null);
  539. }
  540. return error;
  541. }
  542. newMask = SetThreadAffinityMask(GetCurrentThread(), retval);
  543. if (!newMask) {
  544. DWORD error = GetLastError();
  545. if (abort_on_error) {
  546. __kmp_fatal(KMP_MSG(FunctionError, "SetThreadAffinityMask()"),
  547. KMP_ERR(error), __kmp_msg_null);
  548. }
  549. }
  550. *mask = retval;
  551. }
  552. return 0;
  553. }
  554. int get_proc_group() const override {
  555. int group = -1;
  556. if (__kmp_num_proc_groups == 1) {
  557. return 1;
  558. }
  559. for (int i = 0; i < __kmp_num_proc_groups; i++) {
  560. if (mask[i] == 0)
  561. continue;
  562. if (group >= 0)
  563. return -1;
  564. group = i;
  565. }
  566. return group;
  567. }
  568. };
  569. void determine_capable(const char *env_var) override {
  570. __kmp_affinity_determine_capable(env_var);
  571. }
  572. void bind_thread(int which) override { __kmp_affinity_bind_thread(which); }
  573. KMPAffinity::Mask *allocate_mask() override { return new Mask(); }
  574. void deallocate_mask(KMPAffinity::Mask *m) override { delete m; }
  575. KMPAffinity::Mask *allocate_mask_array(int num) override {
  576. return new Mask[num];
  577. }
  578. void deallocate_mask_array(KMPAffinity::Mask *array) override {
  579. Mask *windows_array = static_cast<Mask *>(array);
  580. delete[] windows_array;
  581. }
  582. KMPAffinity::Mask *index_mask_array(KMPAffinity::Mask *array,
  583. int index) override {
  584. Mask *windows_array = static_cast<Mask *>(array);
  585. return &(windows_array[index]);
  586. }
  587. api_type get_api_type() const override { return NATIVE_OS; }
  588. };
  589. #endif /* KMP_OS_WINDOWS */
  590. #endif /* KMP_AFFINITY_SUPPORTED */
  591. // Describe an attribute for a level in the machine topology
  592. struct kmp_hw_attr_t {
  593. int core_type : 8;
  594. int core_eff : 8;
  595. unsigned valid : 1;
  596. unsigned reserved : 15;
  597. static const int UNKNOWN_CORE_EFF = -1;
  598. kmp_hw_attr_t()
  599. : core_type(KMP_HW_CORE_TYPE_UNKNOWN), core_eff(UNKNOWN_CORE_EFF),
  600. valid(0), reserved(0) {}
  601. void set_core_type(kmp_hw_core_type_t type) {
  602. valid = 1;
  603. core_type = type;
  604. }
  605. void set_core_eff(int eff) {
  606. valid = 1;
  607. core_eff = eff;
  608. }
  609. kmp_hw_core_type_t get_core_type() const {
  610. return (kmp_hw_core_type_t)core_type;
  611. }
  612. int get_core_eff() const { return core_eff; }
  613. bool is_core_type_valid() const {
  614. return core_type != KMP_HW_CORE_TYPE_UNKNOWN;
  615. }
  616. bool is_core_eff_valid() const { return core_eff != UNKNOWN_CORE_EFF; }
  617. operator bool() const { return valid; }
  618. void clear() {
  619. core_type = KMP_HW_CORE_TYPE_UNKNOWN;
  620. core_eff = UNKNOWN_CORE_EFF;
  621. valid = 0;
  622. }
  623. bool contains(const kmp_hw_attr_t &other) const {
  624. if (!valid && !other.valid)
  625. return true;
  626. if (valid && other.valid) {
  627. if (other.is_core_type_valid()) {
  628. if (!is_core_type_valid() || (get_core_type() != other.get_core_type()))
  629. return false;
  630. }
  631. if (other.is_core_eff_valid()) {
  632. if (!is_core_eff_valid() || (get_core_eff() != other.get_core_eff()))
  633. return false;
  634. }
  635. return true;
  636. }
  637. return false;
  638. }
  639. bool operator==(const kmp_hw_attr_t &rhs) const {
  640. return (rhs.valid == valid && rhs.core_eff == core_eff &&
  641. rhs.core_type == core_type);
  642. }
  643. bool operator!=(const kmp_hw_attr_t &rhs) const { return !operator==(rhs); }
  644. };
  645. class kmp_hw_thread_t {
  646. public:
  647. static const int UNKNOWN_ID = -1;
  648. static int compare_ids(const void *a, const void *b);
  649. static int compare_compact(const void *a, const void *b);
  650. int ids[KMP_HW_LAST];
  651. int sub_ids[KMP_HW_LAST];
  652. bool leader;
  653. int os_id;
  654. kmp_hw_attr_t attrs;
  655. void print() const;
  656. void clear() {
  657. for (int i = 0; i < (int)KMP_HW_LAST; ++i)
  658. ids[i] = UNKNOWN_ID;
  659. leader = false;
  660. attrs.clear();
  661. }
  662. };
  663. class kmp_topology_t {
  664. struct flags_t {
  665. int uniform : 1;
  666. int reserved : 31;
  667. };
  668. int depth;
  669. // The following arrays are all 'depth' long and have been
  670. // allocated to hold up to KMP_HW_LAST number of objects if
  671. // needed so layers can be added without reallocation of any array
  672. // Orderd array of the types in the topology
  673. kmp_hw_t *types;
  674. // Keep quick topology ratios, for non-uniform topologies,
  675. // this ratio holds the max number of itemAs per itemB
  676. // e.g., [ 4 packages | 6 cores / package | 2 threads / core ]
  677. int *ratio;
  678. // Storage containing the absolute number of each topology layer
  679. int *count;
  680. // The number of core efficiencies. This is only useful for hybrid
  681. // topologies. Core efficiencies will range from 0 to num efficiencies - 1
  682. int num_core_efficiencies;
  683. int num_core_types;
  684. kmp_hw_core_type_t core_types[KMP_HW_MAX_NUM_CORE_TYPES];
  685. // The hardware threads array
  686. // hw_threads is num_hw_threads long
  687. // Each hw_thread's ids and sub_ids are depth deep
  688. int num_hw_threads;
  689. kmp_hw_thread_t *hw_threads;
  690. // Equivalence hash where the key is the hardware topology item
  691. // and the value is the equivalent hardware topology type in the
  692. // types[] array, if the value is KMP_HW_UNKNOWN, then there is no
  693. // known equivalence for the topology type
  694. kmp_hw_t equivalent[KMP_HW_LAST];
  695. // Flags describing the topology
  696. flags_t flags;
  697. // Insert a new topology layer after allocation
  698. void _insert_layer(kmp_hw_t type, const int *ids);
  699. #if KMP_GROUP_AFFINITY
  700. // Insert topology information about Windows Processor groups
  701. void _insert_windows_proc_groups();
  702. #endif
  703. // Count each item & get the num x's per y
  704. // e.g., get the number of cores and the number of threads per core
  705. // for each (x, y) in (KMP_HW_* , KMP_HW_*)
  706. void _gather_enumeration_information();
  707. // Remove layers that don't add information to the topology.
  708. // This is done by having the layer take on the id = UNKNOWN_ID (-1)
  709. void _remove_radix1_layers();
  710. // Find out if the topology is uniform
  711. void _discover_uniformity();
  712. // Set all the sub_ids for each hardware thread
  713. void _set_sub_ids();
  714. // Set global affinity variables describing the number of threads per
  715. // core, the number of packages, the number of cores per package, and
  716. // the number of cores.
  717. void _set_globals();
  718. // Set the last level cache equivalent type
  719. void _set_last_level_cache();
  720. // Return the number of cores with a particular attribute, 'attr'.
  721. // If 'find_all' is true, then find all cores on the machine, otherwise find
  722. // all cores per the layer 'above'
  723. int _get_ncores_with_attr(const kmp_hw_attr_t &attr, int above,
  724. bool find_all = false) const;
  725. public:
  726. // Force use of allocate()/deallocate()
  727. kmp_topology_t() = delete;
  728. kmp_topology_t(const kmp_topology_t &t) = delete;
  729. kmp_topology_t(kmp_topology_t &&t) = delete;
  730. kmp_topology_t &operator=(const kmp_topology_t &t) = delete;
  731. kmp_topology_t &operator=(kmp_topology_t &&t) = delete;
  732. static kmp_topology_t *allocate(int nproc, int ndepth, const kmp_hw_t *types);
  733. static void deallocate(kmp_topology_t *);
  734. // Functions used in create_map() routines
  735. kmp_hw_thread_t &at(int index) {
  736. KMP_DEBUG_ASSERT(index >= 0 && index < num_hw_threads);
  737. return hw_threads[index];
  738. }
  739. const kmp_hw_thread_t &at(int index) const {
  740. KMP_DEBUG_ASSERT(index >= 0 && index < num_hw_threads);
  741. return hw_threads[index];
  742. }
  743. int get_num_hw_threads() const { return num_hw_threads; }
  744. void sort_ids() {
  745. qsort(hw_threads, num_hw_threads, sizeof(kmp_hw_thread_t),
  746. kmp_hw_thread_t::compare_ids);
  747. }
  748. // Check if the hardware ids are unique, if they are
  749. // return true, otherwise return false
  750. bool check_ids() const;
  751. // Function to call after the create_map() routine
  752. void canonicalize();
  753. void canonicalize(int pkgs, int cores_per_pkg, int thr_per_core, int cores);
  754. // Functions used after canonicalize() called
  755. bool filter_hw_subset();
  756. bool is_close(int hwt1, int hwt2, int level) const;
  757. bool is_uniform() const { return flags.uniform; }
  758. // Tell whether a type is a valid type in the topology
  759. // returns KMP_HW_UNKNOWN when there is no equivalent type
  760. kmp_hw_t get_equivalent_type(kmp_hw_t type) const { return equivalent[type]; }
  761. // Set type1 = type2
  762. void set_equivalent_type(kmp_hw_t type1, kmp_hw_t type2) {
  763. KMP_DEBUG_ASSERT_VALID_HW_TYPE(type1);
  764. KMP_DEBUG_ASSERT_VALID_HW_TYPE(type2);
  765. kmp_hw_t real_type2 = equivalent[type2];
  766. if (real_type2 == KMP_HW_UNKNOWN)
  767. real_type2 = type2;
  768. equivalent[type1] = real_type2;
  769. // This loop is required since any of the types may have been set to
  770. // be equivalent to type1. They all must be checked and reset to type2.
  771. KMP_FOREACH_HW_TYPE(type) {
  772. if (equivalent[type] == type1) {
  773. equivalent[type] = real_type2;
  774. }
  775. }
  776. }
  777. // Calculate number of types corresponding to level1
  778. // per types corresponding to level2 (e.g., number of threads per core)
  779. int calculate_ratio(int level1, int level2) const {
  780. KMP_DEBUG_ASSERT(level1 >= 0 && level1 < depth);
  781. KMP_DEBUG_ASSERT(level2 >= 0 && level2 < depth);
  782. int r = 1;
  783. for (int level = level1; level > level2; --level)
  784. r *= ratio[level];
  785. return r;
  786. }
  787. int get_ratio(int level) const {
  788. KMP_DEBUG_ASSERT(level >= 0 && level < depth);
  789. return ratio[level];
  790. }
  791. int get_depth() const { return depth; };
  792. kmp_hw_t get_type(int level) const {
  793. KMP_DEBUG_ASSERT(level >= 0 && level < depth);
  794. return types[level];
  795. }
  796. int get_level(kmp_hw_t type) const {
  797. KMP_DEBUG_ASSERT_VALID_HW_TYPE(type);
  798. int eq_type = equivalent[type];
  799. if (eq_type == KMP_HW_UNKNOWN)
  800. return -1;
  801. for (int i = 0; i < depth; ++i)
  802. if (types[i] == eq_type)
  803. return i;
  804. return -1;
  805. }
  806. int get_count(int level) const {
  807. KMP_DEBUG_ASSERT(level >= 0 && level < depth);
  808. return count[level];
  809. }
  810. // Return the total number of cores with attribute 'attr'
  811. int get_ncores_with_attr(const kmp_hw_attr_t &attr) const {
  812. return _get_ncores_with_attr(attr, -1, true);
  813. }
  814. // Return the number of cores with attribute
  815. // 'attr' per topology level 'above'
  816. int get_ncores_with_attr_per(const kmp_hw_attr_t &attr, int above) const {
  817. return _get_ncores_with_attr(attr, above, false);
  818. }
  819. #if KMP_AFFINITY_SUPPORTED
  820. void sort_compact() {
  821. qsort(hw_threads, num_hw_threads, sizeof(kmp_hw_thread_t),
  822. kmp_hw_thread_t::compare_compact);
  823. }
  824. #endif
  825. void print(const char *env_var = "KMP_AFFINITY") const;
  826. void dump() const;
  827. };
  828. extern kmp_topology_t *__kmp_topology;
  829. class kmp_hw_subset_t {
  830. const static size_t MAX_ATTRS = KMP_HW_MAX_NUM_CORE_EFFS;
  831. public:
  832. // Describe a machine topology item in KMP_HW_SUBSET
  833. struct item_t {
  834. kmp_hw_t type;
  835. int num_attrs;
  836. int num[MAX_ATTRS];
  837. int offset[MAX_ATTRS];
  838. kmp_hw_attr_t attr[MAX_ATTRS];
  839. };
  840. // Put parenthesis around max to avoid accidental use of Windows max macro.
  841. const static int USE_ALL = (std::numeric_limits<int>::max)();
  842. private:
  843. int depth;
  844. int capacity;
  845. item_t *items;
  846. kmp_uint64 set;
  847. bool absolute;
  848. // The set must be able to handle up to KMP_HW_LAST number of layers
  849. KMP_BUILD_ASSERT(sizeof(set) * 8 >= KMP_HW_LAST);
  850. // Sorting the KMP_HW_SUBSET items to follow topology order
  851. // All unknown topology types will be at the beginning of the subset
  852. static int hw_subset_compare(const void *i1, const void *i2) {
  853. kmp_hw_t type1 = ((const item_t *)i1)->type;
  854. kmp_hw_t type2 = ((const item_t *)i2)->type;
  855. int level1 = __kmp_topology->get_level(type1);
  856. int level2 = __kmp_topology->get_level(type2);
  857. return level1 - level2;
  858. }
  859. public:
  860. // Force use of allocate()/deallocate()
  861. kmp_hw_subset_t() = delete;
  862. kmp_hw_subset_t(const kmp_hw_subset_t &t) = delete;
  863. kmp_hw_subset_t(kmp_hw_subset_t &&t) = delete;
  864. kmp_hw_subset_t &operator=(const kmp_hw_subset_t &t) = delete;
  865. kmp_hw_subset_t &operator=(kmp_hw_subset_t &&t) = delete;
  866. static kmp_hw_subset_t *allocate() {
  867. int initial_capacity = 5;
  868. kmp_hw_subset_t *retval =
  869. (kmp_hw_subset_t *)__kmp_allocate(sizeof(kmp_hw_subset_t));
  870. retval->depth = 0;
  871. retval->capacity = initial_capacity;
  872. retval->set = 0ull;
  873. retval->absolute = false;
  874. retval->items = (item_t *)__kmp_allocate(sizeof(item_t) * initial_capacity);
  875. return retval;
  876. }
  877. static void deallocate(kmp_hw_subset_t *subset) {
  878. __kmp_free(subset->items);
  879. __kmp_free(subset);
  880. }
  881. void set_absolute() { absolute = true; }
  882. bool is_absolute() const { return absolute; }
  883. void push_back(int num, kmp_hw_t type, int offset, kmp_hw_attr_t attr) {
  884. for (int i = 0; i < depth; ++i) {
  885. // Found an existing item for this layer type
  886. // Add the num, offset, and attr to this item
  887. if (items[i].type == type) {
  888. int idx = items[i].num_attrs++;
  889. if ((size_t)idx >= MAX_ATTRS)
  890. return;
  891. items[i].num[idx] = num;
  892. items[i].offset[idx] = offset;
  893. items[i].attr[idx] = attr;
  894. return;
  895. }
  896. }
  897. if (depth == capacity - 1) {
  898. capacity *= 2;
  899. item_t *new_items = (item_t *)__kmp_allocate(sizeof(item_t) * capacity);
  900. for (int i = 0; i < depth; ++i)
  901. new_items[i] = items[i];
  902. __kmp_free(items);
  903. items = new_items;
  904. }
  905. items[depth].num_attrs = 1;
  906. items[depth].type = type;
  907. items[depth].num[0] = num;
  908. items[depth].offset[0] = offset;
  909. items[depth].attr[0] = attr;
  910. depth++;
  911. set |= (1ull << type);
  912. }
  913. int get_depth() const { return depth; }
  914. const item_t &at(int index) const {
  915. KMP_DEBUG_ASSERT(index >= 0 && index < depth);
  916. return items[index];
  917. }
  918. item_t &at(int index) {
  919. KMP_DEBUG_ASSERT(index >= 0 && index < depth);
  920. return items[index];
  921. }
  922. void remove(int index) {
  923. KMP_DEBUG_ASSERT(index >= 0 && index < depth);
  924. set &= ~(1ull << items[index].type);
  925. for (int j = index + 1; j < depth; ++j) {
  926. items[j - 1] = items[j];
  927. }
  928. depth--;
  929. }
  930. void sort() {
  931. KMP_DEBUG_ASSERT(__kmp_topology);
  932. qsort(items, depth, sizeof(item_t), hw_subset_compare);
  933. }
  934. bool specified(kmp_hw_t type) const { return ((set & (1ull << type)) > 0); }
  935. void dump() const {
  936. printf("**********************\n");
  937. printf("*** kmp_hw_subset: ***\n");
  938. printf("* depth: %d\n", depth);
  939. printf("* items:\n");
  940. for (int i = 0; i < depth; ++i) {
  941. printf(" type: %s\n", __kmp_hw_get_keyword(items[i].type));
  942. for (int j = 0; j < items[i].num_attrs; ++j) {
  943. printf(" num: %d, offset: %d, attr: ", items[i].num[j],
  944. items[i].offset[j]);
  945. if (!items[i].attr[j]) {
  946. printf(" (none)\n");
  947. } else {
  948. printf(
  949. " core_type = %s, core_eff = %d\n",
  950. __kmp_hw_get_core_type_string(items[i].attr[j].get_core_type()),
  951. items[i].attr[j].get_core_eff());
  952. }
  953. }
  954. }
  955. printf("* set: 0x%llx\n", set);
  956. printf("* absolute: %d\n", absolute);
  957. printf("**********************\n");
  958. }
  959. };
  960. extern kmp_hw_subset_t *__kmp_hw_subset;
  961. /* A structure for holding machine-specific hierarchy info to be computed once
  962. at init. This structure represents a mapping of threads to the actual machine
  963. hierarchy, or to our best guess at what the hierarchy might be, for the
  964. purpose of performing an efficient barrier. In the worst case, when there is
  965. no machine hierarchy information, it produces a tree suitable for a barrier,
  966. similar to the tree used in the hyper barrier. */
  967. class hierarchy_info {
  968. public:
  969. /* Good default values for number of leaves and branching factor, given no
  970. affinity information. Behaves a bit like hyper barrier. */
  971. static const kmp_uint32 maxLeaves = 4;
  972. static const kmp_uint32 minBranch = 4;
  973. /** Number of levels in the hierarchy. Typical levels are threads/core,
  974. cores/package or socket, packages/node, nodes/machine, etc. We don't want
  975. to get specific with nomenclature. When the machine is oversubscribed we
  976. add levels to duplicate the hierarchy, doubling the thread capacity of the
  977. hierarchy each time we add a level. */
  978. kmp_uint32 maxLevels;
  979. /** This is specifically the depth of the machine configuration hierarchy, in
  980. terms of the number of levels along the longest path from root to any
  981. leaf. It corresponds to the number of entries in numPerLevel if we exclude
  982. all but one trailing 1. */
  983. kmp_uint32 depth;
  984. kmp_uint32 base_num_threads;
  985. enum init_status { initialized = 0, not_initialized = 1, initializing = 2 };
  986. volatile kmp_int8 uninitialized; // 0=initialized, 1=not initialized,
  987. // 2=initialization in progress
  988. volatile kmp_int8 resizing; // 0=not resizing, 1=resizing
  989. /** Level 0 corresponds to leaves. numPerLevel[i] is the number of children
  990. the parent of a node at level i has. For example, if we have a machine
  991. with 4 packages, 4 cores/package and 2 HT per core, then numPerLevel =
  992. {2, 4, 4, 1, 1}. All empty levels are set to 1. */
  993. kmp_uint32 *numPerLevel;
  994. kmp_uint32 *skipPerLevel;
  995. void deriveLevels() {
  996. int hier_depth = __kmp_topology->get_depth();
  997. for (int i = hier_depth - 1, level = 0; i >= 0; --i, ++level) {
  998. numPerLevel[level] = __kmp_topology->get_ratio(i);
  999. }
  1000. }
  1001. hierarchy_info()
  1002. : maxLevels(7), depth(1), uninitialized(not_initialized), resizing(0) {}
  1003. void fini() {
  1004. if (!uninitialized && numPerLevel) {
  1005. __kmp_free(numPerLevel);
  1006. numPerLevel = NULL;
  1007. uninitialized = not_initialized;
  1008. }
  1009. }
  1010. void init(int num_addrs) {
  1011. kmp_int8 bool_result = KMP_COMPARE_AND_STORE_ACQ8(
  1012. &uninitialized, not_initialized, initializing);
  1013. if (bool_result == 0) { // Wait for initialization
  1014. while (TCR_1(uninitialized) != initialized)
  1015. KMP_CPU_PAUSE();
  1016. return;
  1017. }
  1018. KMP_DEBUG_ASSERT(bool_result == 1);
  1019. /* Added explicit initialization of the data fields here to prevent usage of
  1020. dirty value observed when static library is re-initialized multiple times
  1021. (e.g. when non-OpenMP thread repeatedly launches/joins thread that uses
  1022. OpenMP). */
  1023. depth = 1;
  1024. resizing = 0;
  1025. maxLevels = 7;
  1026. numPerLevel =
  1027. (kmp_uint32 *)__kmp_allocate(maxLevels * 2 * sizeof(kmp_uint32));
  1028. skipPerLevel = &(numPerLevel[maxLevels]);
  1029. for (kmp_uint32 i = 0; i < maxLevels;
  1030. ++i) { // init numPerLevel[*] to 1 item per level
  1031. numPerLevel[i] = 1;
  1032. skipPerLevel[i] = 1;
  1033. }
  1034. // Sort table by physical ID
  1035. if (__kmp_topology && __kmp_topology->get_depth() > 0) {
  1036. deriveLevels();
  1037. } else {
  1038. numPerLevel[0] = maxLeaves;
  1039. numPerLevel[1] = num_addrs / maxLeaves;
  1040. if (num_addrs % maxLeaves)
  1041. numPerLevel[1]++;
  1042. }
  1043. base_num_threads = num_addrs;
  1044. for (int i = maxLevels - 1; i >= 0;
  1045. --i) // count non-empty levels to get depth
  1046. if (numPerLevel[i] != 1 || depth > 1) // only count one top-level '1'
  1047. depth++;
  1048. kmp_uint32 branch = minBranch;
  1049. if (numPerLevel[0] == 1)
  1050. branch = num_addrs / maxLeaves;
  1051. if (branch < minBranch)
  1052. branch = minBranch;
  1053. for (kmp_uint32 d = 0; d < depth - 1; ++d) { // optimize hierarchy width
  1054. while (numPerLevel[d] > branch ||
  1055. (d == 0 && numPerLevel[d] > maxLeaves)) { // max 4 on level 0!
  1056. if (numPerLevel[d] & 1)
  1057. numPerLevel[d]++;
  1058. numPerLevel[d] = numPerLevel[d] >> 1;
  1059. if (numPerLevel[d + 1] == 1)
  1060. depth++;
  1061. numPerLevel[d + 1] = numPerLevel[d + 1] << 1;
  1062. }
  1063. if (numPerLevel[0] == 1) {
  1064. branch = branch >> 1;
  1065. if (branch < 4)
  1066. branch = minBranch;
  1067. }
  1068. }
  1069. for (kmp_uint32 i = 1; i < depth; ++i)
  1070. skipPerLevel[i] = numPerLevel[i - 1] * skipPerLevel[i - 1];
  1071. // Fill in hierarchy in the case of oversubscription
  1072. for (kmp_uint32 i = depth; i < maxLevels; ++i)
  1073. skipPerLevel[i] = 2 * skipPerLevel[i - 1];
  1074. uninitialized = initialized; // One writer
  1075. }
  1076. // Resize the hierarchy if nproc changes to something larger than before
  1077. void resize(kmp_uint32 nproc) {
  1078. kmp_int8 bool_result = KMP_COMPARE_AND_STORE_ACQ8(&resizing, 0, 1);
  1079. while (bool_result == 0) { // someone else is trying to resize
  1080. KMP_CPU_PAUSE();
  1081. if (nproc <= base_num_threads) // happy with other thread's resize
  1082. return;
  1083. else // try to resize
  1084. bool_result = KMP_COMPARE_AND_STORE_ACQ8(&resizing, 0, 1);
  1085. }
  1086. KMP_DEBUG_ASSERT(bool_result != 0);
  1087. if (nproc <= base_num_threads)
  1088. return; // happy with other thread's resize
  1089. // Calculate new maxLevels
  1090. kmp_uint32 old_sz = skipPerLevel[depth - 1];
  1091. kmp_uint32 incs = 0, old_maxLevels = maxLevels;
  1092. // First see if old maxLevels is enough to contain new size
  1093. for (kmp_uint32 i = depth; i < maxLevels && nproc > old_sz; ++i) {
  1094. skipPerLevel[i] = 2 * skipPerLevel[i - 1];
  1095. numPerLevel[i - 1] *= 2;
  1096. old_sz *= 2;
  1097. depth++;
  1098. }
  1099. if (nproc > old_sz) { // Not enough space, need to expand hierarchy
  1100. while (nproc > old_sz) {
  1101. old_sz *= 2;
  1102. incs++;
  1103. depth++;
  1104. }
  1105. maxLevels += incs;
  1106. // Resize arrays
  1107. kmp_uint32 *old_numPerLevel = numPerLevel;
  1108. kmp_uint32 *old_skipPerLevel = skipPerLevel;
  1109. numPerLevel = skipPerLevel = NULL;
  1110. numPerLevel =
  1111. (kmp_uint32 *)__kmp_allocate(maxLevels * 2 * sizeof(kmp_uint32));
  1112. skipPerLevel = &(numPerLevel[maxLevels]);
  1113. // Copy old elements from old arrays
  1114. for (kmp_uint32 i = 0; i < old_maxLevels; ++i) {
  1115. // init numPerLevel[*] to 1 item per level
  1116. numPerLevel[i] = old_numPerLevel[i];
  1117. skipPerLevel[i] = old_skipPerLevel[i];
  1118. }
  1119. // Init new elements in arrays to 1
  1120. for (kmp_uint32 i = old_maxLevels; i < maxLevels; ++i) {
  1121. // init numPerLevel[*] to 1 item per level
  1122. numPerLevel[i] = 1;
  1123. skipPerLevel[i] = 1;
  1124. }
  1125. // Free old arrays
  1126. __kmp_free(old_numPerLevel);
  1127. }
  1128. // Fill in oversubscription levels of hierarchy
  1129. for (kmp_uint32 i = old_maxLevels; i < maxLevels; ++i)
  1130. skipPerLevel[i] = 2 * skipPerLevel[i - 1];
  1131. base_num_threads = nproc;
  1132. resizing = 0; // One writer
  1133. }
  1134. };
  1135. #endif // KMP_AFFINITY_H