kmp_affinity.cpp 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194
  1. /*
  2. * kmp_affinity.cpp -- 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. #include "kmp.h"
  12. #include "kmp_affinity.h"
  13. #include "kmp_i18n.h"
  14. #include "kmp_io.h"
  15. #include "kmp_str.h"
  16. #include "kmp_wrapper_getpid.h"
  17. #if KMP_USE_HIER_SCHED
  18. #error #include "kmp_dispatch_hier.h"
  19. #endif
  20. #if KMP_USE_HWLOC
  21. // Copied from hwloc
  22. #define HWLOC_GROUP_KIND_INTEL_MODULE 102
  23. #define HWLOC_GROUP_KIND_INTEL_TILE 103
  24. #define HWLOC_GROUP_KIND_INTEL_DIE 104
  25. #define HWLOC_GROUP_KIND_WINDOWS_PROCESSOR_GROUP 220
  26. #endif
  27. #include <ctype.h>
  28. // The machine topology
  29. kmp_topology_t *__kmp_topology = nullptr;
  30. // KMP_HW_SUBSET environment variable
  31. kmp_hw_subset_t *__kmp_hw_subset = nullptr;
  32. // Store the real or imagined machine hierarchy here
  33. static hierarchy_info machine_hierarchy;
  34. void __kmp_cleanup_hierarchy() { machine_hierarchy.fini(); }
  35. void __kmp_get_hierarchy(kmp_uint32 nproc, kmp_bstate_t *thr_bar) {
  36. kmp_uint32 depth;
  37. // The test below is true if affinity is available, but set to "none". Need to
  38. // init on first use of hierarchical barrier.
  39. if (TCR_1(machine_hierarchy.uninitialized))
  40. machine_hierarchy.init(nproc);
  41. // Adjust the hierarchy in case num threads exceeds original
  42. if (nproc > machine_hierarchy.base_num_threads)
  43. machine_hierarchy.resize(nproc);
  44. depth = machine_hierarchy.depth;
  45. KMP_DEBUG_ASSERT(depth > 0);
  46. thr_bar->depth = depth;
  47. __kmp_type_convert(machine_hierarchy.numPerLevel[0] - 1,
  48. &(thr_bar->base_leaf_kids));
  49. thr_bar->skip_per_level = machine_hierarchy.skipPerLevel;
  50. }
  51. static int nCoresPerPkg, nPackages;
  52. static int __kmp_nThreadsPerCore;
  53. #ifndef KMP_DFLT_NTH_CORES
  54. static int __kmp_ncores;
  55. #endif
  56. const char *__kmp_hw_get_catalog_string(kmp_hw_t type, bool plural) {
  57. switch (type) {
  58. case KMP_HW_SOCKET:
  59. return ((plural) ? KMP_I18N_STR(Sockets) : KMP_I18N_STR(Socket));
  60. case KMP_HW_DIE:
  61. return ((plural) ? KMP_I18N_STR(Dice) : KMP_I18N_STR(Die));
  62. case KMP_HW_MODULE:
  63. return ((plural) ? KMP_I18N_STR(Modules) : KMP_I18N_STR(Module));
  64. case KMP_HW_TILE:
  65. return ((plural) ? KMP_I18N_STR(Tiles) : KMP_I18N_STR(Tile));
  66. case KMP_HW_NUMA:
  67. return ((plural) ? KMP_I18N_STR(NumaDomains) : KMP_I18N_STR(NumaDomain));
  68. case KMP_HW_L3:
  69. return ((plural) ? KMP_I18N_STR(L3Caches) : KMP_I18N_STR(L3Cache));
  70. case KMP_HW_L2:
  71. return ((plural) ? KMP_I18N_STR(L2Caches) : KMP_I18N_STR(L2Cache));
  72. case KMP_HW_L1:
  73. return ((plural) ? KMP_I18N_STR(L1Caches) : KMP_I18N_STR(L1Cache));
  74. case KMP_HW_LLC:
  75. return ((plural) ? KMP_I18N_STR(LLCaches) : KMP_I18N_STR(LLCache));
  76. case KMP_HW_CORE:
  77. return ((plural) ? KMP_I18N_STR(Cores) : KMP_I18N_STR(Core));
  78. case KMP_HW_THREAD:
  79. return ((plural) ? KMP_I18N_STR(Threads) : KMP_I18N_STR(Thread));
  80. case KMP_HW_PROC_GROUP:
  81. return ((plural) ? KMP_I18N_STR(ProcGroups) : KMP_I18N_STR(ProcGroup));
  82. }
  83. return KMP_I18N_STR(Unknown);
  84. }
  85. const char *__kmp_hw_get_keyword(kmp_hw_t type, bool plural) {
  86. switch (type) {
  87. case KMP_HW_SOCKET:
  88. return ((plural) ? "sockets" : "socket");
  89. case KMP_HW_DIE:
  90. return ((plural) ? "dice" : "die");
  91. case KMP_HW_MODULE:
  92. return ((plural) ? "modules" : "module");
  93. case KMP_HW_TILE:
  94. return ((plural) ? "tiles" : "tile");
  95. case KMP_HW_NUMA:
  96. return ((plural) ? "numa_domains" : "numa_domain");
  97. case KMP_HW_L3:
  98. return ((plural) ? "l3_caches" : "l3_cache");
  99. case KMP_HW_L2:
  100. return ((plural) ? "l2_caches" : "l2_cache");
  101. case KMP_HW_L1:
  102. return ((plural) ? "l1_caches" : "l1_cache");
  103. case KMP_HW_LLC:
  104. return ((plural) ? "ll_caches" : "ll_cache");
  105. case KMP_HW_CORE:
  106. return ((plural) ? "cores" : "core");
  107. case KMP_HW_THREAD:
  108. return ((plural) ? "threads" : "thread");
  109. case KMP_HW_PROC_GROUP:
  110. return ((plural) ? "proc_groups" : "proc_group");
  111. }
  112. return ((plural) ? "unknowns" : "unknown");
  113. }
  114. const char *__kmp_hw_get_core_type_string(kmp_hw_core_type_t type) {
  115. switch (type) {
  116. case KMP_HW_CORE_TYPE_UNKNOWN:
  117. return "unknown";
  118. #if KMP_ARCH_X86 || KMP_ARCH_X86_64
  119. case KMP_HW_CORE_TYPE_ATOM:
  120. return "Intel Atom(R) processor";
  121. case KMP_HW_CORE_TYPE_CORE:
  122. return "Intel(R) Core(TM) processor";
  123. #endif
  124. }
  125. return "unknown";
  126. }
  127. #if KMP_AFFINITY_SUPPORTED
  128. // If affinity is supported, check the affinity
  129. // verbose and warning flags before printing warning
  130. #define KMP_AFF_WARNING(...) \
  131. if (__kmp_affinity_verbose || \
  132. (__kmp_affinity_warnings && (__kmp_affinity_type != affinity_none))) { \
  133. KMP_WARNING(__VA_ARGS__); \
  134. }
  135. #else
  136. #define KMP_AFF_WARNING KMP_WARNING
  137. #endif
  138. ////////////////////////////////////////////////////////////////////////////////
  139. // kmp_hw_thread_t methods
  140. int kmp_hw_thread_t::compare_ids(const void *a, const void *b) {
  141. const kmp_hw_thread_t *ahwthread = (const kmp_hw_thread_t *)a;
  142. const kmp_hw_thread_t *bhwthread = (const kmp_hw_thread_t *)b;
  143. int depth = __kmp_topology->get_depth();
  144. for (int level = 0; level < depth; ++level) {
  145. if (ahwthread->ids[level] < bhwthread->ids[level])
  146. return -1;
  147. else if (ahwthread->ids[level] > bhwthread->ids[level])
  148. return 1;
  149. }
  150. if (ahwthread->os_id < bhwthread->os_id)
  151. return -1;
  152. else if (ahwthread->os_id > bhwthread->os_id)
  153. return 1;
  154. return 0;
  155. }
  156. #if KMP_AFFINITY_SUPPORTED
  157. int kmp_hw_thread_t::compare_compact(const void *a, const void *b) {
  158. int i;
  159. const kmp_hw_thread_t *aa = (const kmp_hw_thread_t *)a;
  160. const kmp_hw_thread_t *bb = (const kmp_hw_thread_t *)b;
  161. int depth = __kmp_topology->get_depth();
  162. KMP_DEBUG_ASSERT(__kmp_affinity_compact >= 0);
  163. KMP_DEBUG_ASSERT(__kmp_affinity_compact <= depth);
  164. for (i = 0; i < __kmp_affinity_compact; i++) {
  165. int j = depth - i - 1;
  166. if (aa->sub_ids[j] < bb->sub_ids[j])
  167. return -1;
  168. if (aa->sub_ids[j] > bb->sub_ids[j])
  169. return 1;
  170. }
  171. for (; i < depth; i++) {
  172. int j = i - __kmp_affinity_compact;
  173. if (aa->sub_ids[j] < bb->sub_ids[j])
  174. return -1;
  175. if (aa->sub_ids[j] > bb->sub_ids[j])
  176. return 1;
  177. }
  178. return 0;
  179. }
  180. #endif
  181. void kmp_hw_thread_t::print() const {
  182. int depth = __kmp_topology->get_depth();
  183. printf("%4d ", os_id);
  184. for (int i = 0; i < depth; ++i) {
  185. printf("%4d ", ids[i]);
  186. }
  187. if (attrs) {
  188. if (attrs.is_core_type_valid())
  189. printf(" (%s)", __kmp_hw_get_core_type_string(attrs.get_core_type()));
  190. if (attrs.is_core_eff_valid())
  191. printf(" (eff=%d)", attrs.get_core_eff());
  192. }
  193. printf("\n");
  194. }
  195. ////////////////////////////////////////////////////////////////////////////////
  196. // kmp_topology_t methods
  197. // Add a layer to the topology based on the ids. Assume the topology
  198. // is perfectly nested (i.e., so no object has more than one parent)
  199. void kmp_topology_t::_insert_layer(kmp_hw_t type, const int *ids) {
  200. // Figure out where the layer should go by comparing the ids of the current
  201. // layers with the new ids
  202. int target_layer;
  203. int previous_id = kmp_hw_thread_t::UNKNOWN_ID;
  204. int previous_new_id = kmp_hw_thread_t::UNKNOWN_ID;
  205. // Start from the highest layer and work down to find target layer
  206. // If new layer is equal to another layer then put the new layer above
  207. for (target_layer = 0; target_layer < depth; ++target_layer) {
  208. bool layers_equal = true;
  209. bool strictly_above_target_layer = false;
  210. for (int i = 0; i < num_hw_threads; ++i) {
  211. int id = hw_threads[i].ids[target_layer];
  212. int new_id = ids[i];
  213. if (id != previous_id && new_id == previous_new_id) {
  214. // Found the layer we are strictly above
  215. strictly_above_target_layer = true;
  216. layers_equal = false;
  217. break;
  218. } else if (id == previous_id && new_id != previous_new_id) {
  219. // Found a layer we are below. Move to next layer and check.
  220. layers_equal = false;
  221. break;
  222. }
  223. previous_id = id;
  224. previous_new_id = new_id;
  225. }
  226. if (strictly_above_target_layer || layers_equal)
  227. break;
  228. }
  229. // Found the layer we are above. Now move everything to accommodate the new
  230. // layer. And put the new ids and type into the topology.
  231. for (int i = depth - 1, j = depth; i >= target_layer; --i, --j)
  232. types[j] = types[i];
  233. types[target_layer] = type;
  234. for (int k = 0; k < num_hw_threads; ++k) {
  235. for (int i = depth - 1, j = depth; i >= target_layer; --i, --j)
  236. hw_threads[k].ids[j] = hw_threads[k].ids[i];
  237. hw_threads[k].ids[target_layer] = ids[k];
  238. }
  239. equivalent[type] = type;
  240. depth++;
  241. }
  242. #if KMP_GROUP_AFFINITY
  243. // Insert the Windows Processor Group structure into the topology
  244. void kmp_topology_t::_insert_windows_proc_groups() {
  245. // Do not insert the processor group structure for a single group
  246. if (__kmp_num_proc_groups == 1)
  247. return;
  248. kmp_affin_mask_t *mask;
  249. int *ids = (int *)__kmp_allocate(sizeof(int) * num_hw_threads);
  250. KMP_CPU_ALLOC(mask);
  251. for (int i = 0; i < num_hw_threads; ++i) {
  252. KMP_CPU_ZERO(mask);
  253. KMP_CPU_SET(hw_threads[i].os_id, mask);
  254. ids[i] = __kmp_get_proc_group(mask);
  255. }
  256. KMP_CPU_FREE(mask);
  257. _insert_layer(KMP_HW_PROC_GROUP, ids);
  258. __kmp_free(ids);
  259. }
  260. #endif
  261. // Remove layers that don't add information to the topology.
  262. // This is done by having the layer take on the id = UNKNOWN_ID (-1)
  263. void kmp_topology_t::_remove_radix1_layers() {
  264. int preference[KMP_HW_LAST];
  265. int top_index1, top_index2;
  266. // Set up preference associative array
  267. preference[KMP_HW_SOCKET] = 110;
  268. preference[KMP_HW_PROC_GROUP] = 100;
  269. preference[KMP_HW_CORE] = 95;
  270. preference[KMP_HW_THREAD] = 90;
  271. preference[KMP_HW_NUMA] = 85;
  272. preference[KMP_HW_DIE] = 80;
  273. preference[KMP_HW_TILE] = 75;
  274. preference[KMP_HW_MODULE] = 73;
  275. preference[KMP_HW_L3] = 70;
  276. preference[KMP_HW_L2] = 65;
  277. preference[KMP_HW_L1] = 60;
  278. preference[KMP_HW_LLC] = 5;
  279. top_index1 = 0;
  280. top_index2 = 1;
  281. while (top_index1 < depth - 1 && top_index2 < depth) {
  282. kmp_hw_t type1 = types[top_index1];
  283. kmp_hw_t type2 = types[top_index2];
  284. KMP_ASSERT_VALID_HW_TYPE(type1);
  285. KMP_ASSERT_VALID_HW_TYPE(type2);
  286. // Do not allow the three main topology levels (sockets, cores, threads) to
  287. // be compacted down
  288. if ((type1 == KMP_HW_THREAD || type1 == KMP_HW_CORE ||
  289. type1 == KMP_HW_SOCKET) &&
  290. (type2 == KMP_HW_THREAD || type2 == KMP_HW_CORE ||
  291. type2 == KMP_HW_SOCKET)) {
  292. top_index1 = top_index2++;
  293. continue;
  294. }
  295. bool radix1 = true;
  296. bool all_same = true;
  297. int id1 = hw_threads[0].ids[top_index1];
  298. int id2 = hw_threads[0].ids[top_index2];
  299. int pref1 = preference[type1];
  300. int pref2 = preference[type2];
  301. for (int hwidx = 1; hwidx < num_hw_threads; ++hwidx) {
  302. if (hw_threads[hwidx].ids[top_index1] == id1 &&
  303. hw_threads[hwidx].ids[top_index2] != id2) {
  304. radix1 = false;
  305. break;
  306. }
  307. if (hw_threads[hwidx].ids[top_index2] != id2)
  308. all_same = false;
  309. id1 = hw_threads[hwidx].ids[top_index1];
  310. id2 = hw_threads[hwidx].ids[top_index2];
  311. }
  312. if (radix1) {
  313. // Select the layer to remove based on preference
  314. kmp_hw_t remove_type, keep_type;
  315. int remove_layer, remove_layer_ids;
  316. if (pref1 > pref2) {
  317. remove_type = type2;
  318. remove_layer = remove_layer_ids = top_index2;
  319. keep_type = type1;
  320. } else {
  321. remove_type = type1;
  322. remove_layer = remove_layer_ids = top_index1;
  323. keep_type = type2;
  324. }
  325. // If all the indexes for the second (deeper) layer are the same.
  326. // e.g., all are zero, then make sure to keep the first layer's ids
  327. if (all_same)
  328. remove_layer_ids = top_index2;
  329. // Remove radix one type by setting the equivalence, removing the id from
  330. // the hw threads and removing the layer from types and depth
  331. set_equivalent_type(remove_type, keep_type);
  332. for (int idx = 0; idx < num_hw_threads; ++idx) {
  333. kmp_hw_thread_t &hw_thread = hw_threads[idx];
  334. for (int d = remove_layer_ids; d < depth - 1; ++d)
  335. hw_thread.ids[d] = hw_thread.ids[d + 1];
  336. }
  337. for (int idx = remove_layer; idx < depth - 1; ++idx)
  338. types[idx] = types[idx + 1];
  339. depth--;
  340. } else {
  341. top_index1 = top_index2++;
  342. }
  343. }
  344. KMP_ASSERT(depth > 0);
  345. }
  346. void kmp_topology_t::_set_last_level_cache() {
  347. if (get_equivalent_type(KMP_HW_L3) != KMP_HW_UNKNOWN)
  348. set_equivalent_type(KMP_HW_LLC, KMP_HW_L3);
  349. else if (get_equivalent_type(KMP_HW_L2) != KMP_HW_UNKNOWN)
  350. set_equivalent_type(KMP_HW_LLC, KMP_HW_L2);
  351. #if KMP_MIC_SUPPORTED
  352. else if (__kmp_mic_type == mic3) {
  353. if (get_equivalent_type(KMP_HW_L2) != KMP_HW_UNKNOWN)
  354. set_equivalent_type(KMP_HW_LLC, KMP_HW_L2);
  355. else if (get_equivalent_type(KMP_HW_TILE) != KMP_HW_UNKNOWN)
  356. set_equivalent_type(KMP_HW_LLC, KMP_HW_TILE);
  357. // L2/Tile wasn't detected so just say L1
  358. else
  359. set_equivalent_type(KMP_HW_LLC, KMP_HW_L1);
  360. }
  361. #endif
  362. else if (get_equivalent_type(KMP_HW_L1) != KMP_HW_UNKNOWN)
  363. set_equivalent_type(KMP_HW_LLC, KMP_HW_L1);
  364. // Fallback is to set last level cache to socket or core
  365. if (get_equivalent_type(KMP_HW_LLC) == KMP_HW_UNKNOWN) {
  366. if (get_equivalent_type(KMP_HW_SOCKET) != KMP_HW_UNKNOWN)
  367. set_equivalent_type(KMP_HW_LLC, KMP_HW_SOCKET);
  368. else if (get_equivalent_type(KMP_HW_CORE) != KMP_HW_UNKNOWN)
  369. set_equivalent_type(KMP_HW_LLC, KMP_HW_CORE);
  370. }
  371. KMP_ASSERT(get_equivalent_type(KMP_HW_LLC) != KMP_HW_UNKNOWN);
  372. }
  373. // Gather the count of each topology layer and the ratio
  374. void kmp_topology_t::_gather_enumeration_information() {
  375. int previous_id[KMP_HW_LAST];
  376. int max[KMP_HW_LAST];
  377. for (int i = 0; i < depth; ++i) {
  378. previous_id[i] = kmp_hw_thread_t::UNKNOWN_ID;
  379. max[i] = 0;
  380. count[i] = 0;
  381. ratio[i] = 0;
  382. }
  383. int core_level = get_level(KMP_HW_CORE);
  384. for (int i = 0; i < num_hw_threads; ++i) {
  385. kmp_hw_thread_t &hw_thread = hw_threads[i];
  386. for (int layer = 0; layer < depth; ++layer) {
  387. int id = hw_thread.ids[layer];
  388. if (id != previous_id[layer]) {
  389. // Add an additional increment to each count
  390. for (int l = layer; l < depth; ++l)
  391. count[l]++;
  392. // Keep track of topology layer ratio statistics
  393. max[layer]++;
  394. for (int l = layer + 1; l < depth; ++l) {
  395. if (max[l] > ratio[l])
  396. ratio[l] = max[l];
  397. max[l] = 1;
  398. }
  399. // Figure out the number of different core types
  400. // and efficiencies for hybrid CPUs
  401. if (__kmp_is_hybrid_cpu() && core_level >= 0 && layer <= core_level) {
  402. if (hw_thread.attrs.is_core_eff_valid() &&
  403. hw_thread.attrs.core_eff >= num_core_efficiencies) {
  404. // Because efficiencies can range from 0 to max efficiency - 1,
  405. // the number of efficiencies is max efficiency + 1
  406. num_core_efficiencies = hw_thread.attrs.core_eff + 1;
  407. }
  408. if (hw_thread.attrs.is_core_type_valid()) {
  409. bool found = false;
  410. for (int j = 0; j < num_core_types; ++j) {
  411. if (hw_thread.attrs.get_core_type() == core_types[j]) {
  412. found = true;
  413. break;
  414. }
  415. }
  416. if (!found) {
  417. KMP_ASSERT(num_core_types < KMP_HW_MAX_NUM_CORE_TYPES);
  418. core_types[num_core_types++] = hw_thread.attrs.get_core_type();
  419. }
  420. }
  421. }
  422. break;
  423. }
  424. }
  425. for (int layer = 0; layer < depth; ++layer) {
  426. previous_id[layer] = hw_thread.ids[layer];
  427. }
  428. }
  429. for (int layer = 0; layer < depth; ++layer) {
  430. if (max[layer] > ratio[layer])
  431. ratio[layer] = max[layer];
  432. }
  433. }
  434. int kmp_topology_t::_get_ncores_with_attr(const kmp_hw_attr_t &attr,
  435. int above_level,
  436. bool find_all) const {
  437. int current, current_max;
  438. int previous_id[KMP_HW_LAST];
  439. for (int i = 0; i < depth; ++i)
  440. previous_id[i] = kmp_hw_thread_t::UNKNOWN_ID;
  441. int core_level = get_level(KMP_HW_CORE);
  442. if (find_all)
  443. above_level = -1;
  444. KMP_ASSERT(above_level < core_level);
  445. current_max = 0;
  446. current = 0;
  447. for (int i = 0; i < num_hw_threads; ++i) {
  448. kmp_hw_thread_t &hw_thread = hw_threads[i];
  449. if (!find_all && hw_thread.ids[above_level] != previous_id[above_level]) {
  450. if (current > current_max)
  451. current_max = current;
  452. current = hw_thread.attrs.contains(attr);
  453. } else {
  454. for (int level = above_level + 1; level <= core_level; ++level) {
  455. if (hw_thread.ids[level] != previous_id[level]) {
  456. if (hw_thread.attrs.contains(attr))
  457. current++;
  458. break;
  459. }
  460. }
  461. }
  462. for (int level = 0; level < depth; ++level)
  463. previous_id[level] = hw_thread.ids[level];
  464. }
  465. if (current > current_max)
  466. current_max = current;
  467. return current_max;
  468. }
  469. // Find out if the topology is uniform
  470. void kmp_topology_t::_discover_uniformity() {
  471. int num = 1;
  472. for (int level = 0; level < depth; ++level)
  473. num *= ratio[level];
  474. flags.uniform = (num == count[depth - 1]);
  475. }
  476. // Set all the sub_ids for each hardware thread
  477. void kmp_topology_t::_set_sub_ids() {
  478. int previous_id[KMP_HW_LAST];
  479. int sub_id[KMP_HW_LAST];
  480. for (int i = 0; i < depth; ++i) {
  481. previous_id[i] = -1;
  482. sub_id[i] = -1;
  483. }
  484. for (int i = 0; i < num_hw_threads; ++i) {
  485. kmp_hw_thread_t &hw_thread = hw_threads[i];
  486. // Setup the sub_id
  487. for (int j = 0; j < depth; ++j) {
  488. if (hw_thread.ids[j] != previous_id[j]) {
  489. sub_id[j]++;
  490. for (int k = j + 1; k < depth; ++k) {
  491. sub_id[k] = 0;
  492. }
  493. break;
  494. }
  495. }
  496. // Set previous_id
  497. for (int j = 0; j < depth; ++j) {
  498. previous_id[j] = hw_thread.ids[j];
  499. }
  500. // Set the sub_ids field
  501. for (int j = 0; j < depth; ++j) {
  502. hw_thread.sub_ids[j] = sub_id[j];
  503. }
  504. }
  505. }
  506. void kmp_topology_t::_set_globals() {
  507. // Set nCoresPerPkg, nPackages, __kmp_nThreadsPerCore, __kmp_ncores
  508. int core_level, thread_level, package_level;
  509. package_level = get_level(KMP_HW_SOCKET);
  510. #if KMP_GROUP_AFFINITY
  511. if (package_level == -1)
  512. package_level = get_level(KMP_HW_PROC_GROUP);
  513. #endif
  514. core_level = get_level(KMP_HW_CORE);
  515. thread_level = get_level(KMP_HW_THREAD);
  516. KMP_ASSERT(core_level != -1);
  517. KMP_ASSERT(thread_level != -1);
  518. __kmp_nThreadsPerCore = calculate_ratio(thread_level, core_level);
  519. if (package_level != -1) {
  520. nCoresPerPkg = calculate_ratio(core_level, package_level);
  521. nPackages = get_count(package_level);
  522. } else {
  523. // assume one socket
  524. nCoresPerPkg = get_count(core_level);
  525. nPackages = 1;
  526. }
  527. #ifndef KMP_DFLT_NTH_CORES
  528. __kmp_ncores = get_count(core_level);
  529. #endif
  530. }
  531. kmp_topology_t *kmp_topology_t::allocate(int nproc, int ndepth,
  532. const kmp_hw_t *types) {
  533. kmp_topology_t *retval;
  534. // Allocate all data in one large allocation
  535. size_t size = sizeof(kmp_topology_t) + sizeof(kmp_hw_thread_t) * nproc +
  536. sizeof(int) * (size_t)KMP_HW_LAST * 3;
  537. char *bytes = (char *)__kmp_allocate(size);
  538. retval = (kmp_topology_t *)bytes;
  539. if (nproc > 0) {
  540. retval->hw_threads = (kmp_hw_thread_t *)(bytes + sizeof(kmp_topology_t));
  541. } else {
  542. retval->hw_threads = nullptr;
  543. }
  544. retval->num_hw_threads = nproc;
  545. retval->depth = ndepth;
  546. int *arr =
  547. (int *)(bytes + sizeof(kmp_topology_t) + sizeof(kmp_hw_thread_t) * nproc);
  548. retval->types = (kmp_hw_t *)arr;
  549. retval->ratio = arr + (size_t)KMP_HW_LAST;
  550. retval->count = arr + 2 * (size_t)KMP_HW_LAST;
  551. retval->num_core_efficiencies = 0;
  552. retval->num_core_types = 0;
  553. for (int i = 0; i < KMP_HW_MAX_NUM_CORE_TYPES; ++i)
  554. retval->core_types[i] = KMP_HW_CORE_TYPE_UNKNOWN;
  555. KMP_FOREACH_HW_TYPE(type) { retval->equivalent[type] = KMP_HW_UNKNOWN; }
  556. for (int i = 0; i < ndepth; ++i) {
  557. retval->types[i] = types[i];
  558. retval->equivalent[types[i]] = types[i];
  559. }
  560. return retval;
  561. }
  562. void kmp_topology_t::deallocate(kmp_topology_t *topology) {
  563. if (topology)
  564. __kmp_free(topology);
  565. }
  566. bool kmp_topology_t::check_ids() const {
  567. // Assume ids have been sorted
  568. if (num_hw_threads == 0)
  569. return true;
  570. for (int i = 1; i < num_hw_threads; ++i) {
  571. kmp_hw_thread_t &current_thread = hw_threads[i];
  572. kmp_hw_thread_t &previous_thread = hw_threads[i - 1];
  573. bool unique = false;
  574. for (int j = 0; j < depth; ++j) {
  575. if (previous_thread.ids[j] != current_thread.ids[j]) {
  576. unique = true;
  577. break;
  578. }
  579. }
  580. if (unique)
  581. continue;
  582. return false;
  583. }
  584. return true;
  585. }
  586. void kmp_topology_t::dump() const {
  587. printf("***********************\n");
  588. printf("*** __kmp_topology: ***\n");
  589. printf("***********************\n");
  590. printf("* depth: %d\n", depth);
  591. printf("* types: ");
  592. for (int i = 0; i < depth; ++i)
  593. printf("%15s ", __kmp_hw_get_keyword(types[i]));
  594. printf("\n");
  595. printf("* ratio: ");
  596. for (int i = 0; i < depth; ++i) {
  597. printf("%15d ", ratio[i]);
  598. }
  599. printf("\n");
  600. printf("* count: ");
  601. for (int i = 0; i < depth; ++i) {
  602. printf("%15d ", count[i]);
  603. }
  604. printf("\n");
  605. printf("* num_core_eff: %d\n", num_core_efficiencies);
  606. printf("* num_core_types: %d\n", num_core_types);
  607. printf("* core_types: ");
  608. for (int i = 0; i < num_core_types; ++i)
  609. printf("%3d ", core_types[i]);
  610. printf("\n");
  611. printf("* equivalent map:\n");
  612. KMP_FOREACH_HW_TYPE(i) {
  613. const char *key = __kmp_hw_get_keyword(i);
  614. const char *value = __kmp_hw_get_keyword(equivalent[i]);
  615. printf("%-15s -> %-15s\n", key, value);
  616. }
  617. printf("* uniform: %s\n", (is_uniform() ? "Yes" : "No"));
  618. printf("* num_hw_threads: %d\n", num_hw_threads);
  619. printf("* hw_threads:\n");
  620. for (int i = 0; i < num_hw_threads; ++i) {
  621. hw_threads[i].print();
  622. }
  623. printf("***********************\n");
  624. }
  625. void kmp_topology_t::print(const char *env_var) const {
  626. kmp_str_buf_t buf;
  627. int print_types_depth;
  628. __kmp_str_buf_init(&buf);
  629. kmp_hw_t print_types[KMP_HW_LAST + 2];
  630. // Num Available Threads
  631. KMP_INFORM(AvailableOSProc, env_var, num_hw_threads);
  632. // Uniform or not
  633. if (is_uniform()) {
  634. KMP_INFORM(Uniform, env_var);
  635. } else {
  636. KMP_INFORM(NonUniform, env_var);
  637. }
  638. // Equivalent types
  639. KMP_FOREACH_HW_TYPE(type) {
  640. kmp_hw_t eq_type = equivalent[type];
  641. if (eq_type != KMP_HW_UNKNOWN && eq_type != type) {
  642. KMP_INFORM(AffEqualTopologyTypes, env_var,
  643. __kmp_hw_get_catalog_string(type),
  644. __kmp_hw_get_catalog_string(eq_type));
  645. }
  646. }
  647. // Quick topology
  648. KMP_ASSERT(depth > 0 && depth <= (int)KMP_HW_LAST);
  649. // Create a print types array that always guarantees printing
  650. // the core and thread level
  651. print_types_depth = 0;
  652. for (int level = 0; level < depth; ++level)
  653. print_types[print_types_depth++] = types[level];
  654. if (equivalent[KMP_HW_CORE] != KMP_HW_CORE) {
  655. // Force in the core level for quick topology
  656. if (print_types[print_types_depth - 1] == KMP_HW_THREAD) {
  657. // Force core before thread e.g., 1 socket X 2 threads/socket
  658. // becomes 1 socket X 1 core/socket X 2 threads/socket
  659. print_types[print_types_depth - 1] = KMP_HW_CORE;
  660. print_types[print_types_depth++] = KMP_HW_THREAD;
  661. } else {
  662. print_types[print_types_depth++] = KMP_HW_CORE;
  663. }
  664. }
  665. // Always put threads at very end of quick topology
  666. if (equivalent[KMP_HW_THREAD] != KMP_HW_THREAD)
  667. print_types[print_types_depth++] = KMP_HW_THREAD;
  668. __kmp_str_buf_clear(&buf);
  669. kmp_hw_t numerator_type;
  670. kmp_hw_t denominator_type = KMP_HW_UNKNOWN;
  671. int core_level = get_level(KMP_HW_CORE);
  672. int ncores = get_count(core_level);
  673. for (int plevel = 0, level = 0; plevel < print_types_depth; ++plevel) {
  674. int c;
  675. bool plural;
  676. numerator_type = print_types[plevel];
  677. KMP_ASSERT_VALID_HW_TYPE(numerator_type);
  678. if (equivalent[numerator_type] != numerator_type)
  679. c = 1;
  680. else
  681. c = get_ratio(level++);
  682. plural = (c > 1);
  683. if (plevel == 0) {
  684. __kmp_str_buf_print(&buf, "%d %s", c,
  685. __kmp_hw_get_catalog_string(numerator_type, plural));
  686. } else {
  687. __kmp_str_buf_print(&buf, " x %d %s/%s", c,
  688. __kmp_hw_get_catalog_string(numerator_type, plural),
  689. __kmp_hw_get_catalog_string(denominator_type));
  690. }
  691. denominator_type = numerator_type;
  692. }
  693. KMP_INFORM(TopologyGeneric, env_var, buf.str, ncores);
  694. // Hybrid topology information
  695. if (__kmp_is_hybrid_cpu()) {
  696. for (int i = 0; i < num_core_types; ++i) {
  697. kmp_hw_core_type_t core_type = core_types[i];
  698. kmp_hw_attr_t attr;
  699. attr.clear();
  700. attr.set_core_type(core_type);
  701. int ncores = get_ncores_with_attr(attr);
  702. if (ncores > 0) {
  703. KMP_INFORM(TopologyHybrid, env_var, ncores,
  704. __kmp_hw_get_core_type_string(core_type));
  705. KMP_ASSERT(num_core_efficiencies <= KMP_HW_MAX_NUM_CORE_EFFS)
  706. for (int eff = 0; eff < num_core_efficiencies; ++eff) {
  707. attr.set_core_eff(eff);
  708. int ncores_with_eff = get_ncores_with_attr(attr);
  709. if (ncores_with_eff > 0) {
  710. KMP_INFORM(TopologyHybridCoreEff, env_var, ncores_with_eff, eff);
  711. }
  712. }
  713. }
  714. }
  715. }
  716. if (num_hw_threads <= 0) {
  717. __kmp_str_buf_free(&buf);
  718. return;
  719. }
  720. // Full OS proc to hardware thread map
  721. KMP_INFORM(OSProcToPhysicalThreadMap, env_var);
  722. for (int i = 0; i < num_hw_threads; i++) {
  723. __kmp_str_buf_clear(&buf);
  724. for (int level = 0; level < depth; ++level) {
  725. kmp_hw_t type = types[level];
  726. __kmp_str_buf_print(&buf, "%s ", __kmp_hw_get_catalog_string(type));
  727. __kmp_str_buf_print(&buf, "%d ", hw_threads[i].ids[level]);
  728. }
  729. if (__kmp_is_hybrid_cpu())
  730. __kmp_str_buf_print(
  731. &buf, "(%s)",
  732. __kmp_hw_get_core_type_string(hw_threads[i].attrs.get_core_type()));
  733. KMP_INFORM(OSProcMapToPack, env_var, hw_threads[i].os_id, buf.str);
  734. }
  735. __kmp_str_buf_free(&buf);
  736. }
  737. void kmp_topology_t::canonicalize() {
  738. #if KMP_GROUP_AFFINITY
  739. _insert_windows_proc_groups();
  740. #endif
  741. _remove_radix1_layers();
  742. _gather_enumeration_information();
  743. _discover_uniformity();
  744. _set_sub_ids();
  745. _set_globals();
  746. _set_last_level_cache();
  747. #if KMP_MIC_SUPPORTED
  748. // Manually Add L2 = Tile equivalence
  749. if (__kmp_mic_type == mic3) {
  750. if (get_level(KMP_HW_L2) != -1)
  751. set_equivalent_type(KMP_HW_TILE, KMP_HW_L2);
  752. else if (get_level(KMP_HW_TILE) != -1)
  753. set_equivalent_type(KMP_HW_L2, KMP_HW_TILE);
  754. }
  755. #endif
  756. // Perform post canonicalization checking
  757. KMP_ASSERT(depth > 0);
  758. for (int level = 0; level < depth; ++level) {
  759. // All counts, ratios, and types must be valid
  760. KMP_ASSERT(count[level] > 0 && ratio[level] > 0);
  761. KMP_ASSERT_VALID_HW_TYPE(types[level]);
  762. // Detected types must point to themselves
  763. KMP_ASSERT(equivalent[types[level]] == types[level]);
  764. }
  765. #if KMP_AFFINITY_SUPPORTED
  766. // Set the number of affinity granularity levels
  767. if (__kmp_affinity_gran_levels < 0) {
  768. kmp_hw_t gran_type = get_equivalent_type(__kmp_affinity_gran);
  769. // Check if user's granularity request is valid
  770. if (gran_type == KMP_HW_UNKNOWN) {
  771. // First try core, then thread, then package
  772. kmp_hw_t gran_types[3] = {KMP_HW_CORE, KMP_HW_THREAD, KMP_HW_SOCKET};
  773. for (auto g : gran_types) {
  774. if (get_equivalent_type(g) != KMP_HW_UNKNOWN) {
  775. gran_type = g;
  776. break;
  777. }
  778. }
  779. KMP_ASSERT(gran_type != KMP_HW_UNKNOWN);
  780. // Warn user what granularity setting will be used instead
  781. KMP_AFF_WARNING(AffGranularityBad, "KMP_AFFINITY",
  782. __kmp_hw_get_catalog_string(__kmp_affinity_gran),
  783. __kmp_hw_get_catalog_string(gran_type));
  784. __kmp_affinity_gran = gran_type;
  785. }
  786. #if KMP_GROUP_AFFINITY
  787. // If more than one processor group exists, and the level of
  788. // granularity specified by the user is too coarse, then the
  789. // granularity must be adjusted "down" to processor group affinity
  790. // because threads can only exist within one processor group.
  791. // For example, if a user sets granularity=socket and there are two
  792. // processor groups that cover a socket, then the runtime must
  793. // restrict the granularity down to the processor group level.
  794. if (__kmp_num_proc_groups > 1) {
  795. int gran_depth = get_level(gran_type);
  796. int proc_group_depth = get_level(KMP_HW_PROC_GROUP);
  797. if (gran_depth >= 0 && proc_group_depth >= 0 &&
  798. gran_depth < proc_group_depth) {
  799. KMP_AFF_WARNING(AffGranTooCoarseProcGroup, "KMP_AFFINITY",
  800. __kmp_hw_get_catalog_string(__kmp_affinity_gran));
  801. __kmp_affinity_gran = gran_type = KMP_HW_PROC_GROUP;
  802. }
  803. }
  804. #endif
  805. __kmp_affinity_gran_levels = 0;
  806. for (int i = depth - 1; i >= 0 && get_type(i) != gran_type; --i)
  807. __kmp_affinity_gran_levels++;
  808. }
  809. #endif // KMP_AFFINITY_SUPPORTED
  810. }
  811. // Canonicalize an explicit packages X cores/pkg X threads/core topology
  812. void kmp_topology_t::canonicalize(int npackages, int ncores_per_pkg,
  813. int nthreads_per_core, int ncores) {
  814. int ndepth = 3;
  815. depth = ndepth;
  816. KMP_FOREACH_HW_TYPE(i) { equivalent[i] = KMP_HW_UNKNOWN; }
  817. for (int level = 0; level < depth; ++level) {
  818. count[level] = 0;
  819. ratio[level] = 0;
  820. }
  821. count[0] = npackages;
  822. count[1] = ncores;
  823. count[2] = __kmp_xproc;
  824. ratio[0] = npackages;
  825. ratio[1] = ncores_per_pkg;
  826. ratio[2] = nthreads_per_core;
  827. equivalent[KMP_HW_SOCKET] = KMP_HW_SOCKET;
  828. equivalent[KMP_HW_CORE] = KMP_HW_CORE;
  829. equivalent[KMP_HW_THREAD] = KMP_HW_THREAD;
  830. types[0] = KMP_HW_SOCKET;
  831. types[1] = KMP_HW_CORE;
  832. types[2] = KMP_HW_THREAD;
  833. //__kmp_avail_proc = __kmp_xproc;
  834. _discover_uniformity();
  835. }
  836. // Represents running sub IDs for a single core attribute where
  837. // attribute values have SIZE possibilities.
  838. template <size_t SIZE, typename IndexFunc> struct kmp_sub_ids_t {
  839. int last_level; // last level in topology to consider for sub_ids
  840. int sub_id[SIZE]; // The sub ID for a given attribute value
  841. int prev_sub_id[KMP_HW_LAST];
  842. IndexFunc indexer;
  843. public:
  844. kmp_sub_ids_t(int last_level) : last_level(last_level) {
  845. KMP_ASSERT(last_level < KMP_HW_LAST);
  846. for (size_t i = 0; i < SIZE; ++i)
  847. sub_id[i] = -1;
  848. for (size_t i = 0; i < KMP_HW_LAST; ++i)
  849. prev_sub_id[i] = -1;
  850. }
  851. void update(const kmp_hw_thread_t &hw_thread) {
  852. int idx = indexer(hw_thread);
  853. KMP_ASSERT(idx < (int)SIZE);
  854. for (int level = 0; level <= last_level; ++level) {
  855. if (hw_thread.sub_ids[level] != prev_sub_id[level]) {
  856. if (level < last_level)
  857. sub_id[idx] = -1;
  858. sub_id[idx]++;
  859. break;
  860. }
  861. }
  862. for (int level = 0; level <= last_level; ++level)
  863. prev_sub_id[level] = hw_thread.sub_ids[level];
  864. }
  865. int get_sub_id(const kmp_hw_thread_t &hw_thread) const {
  866. return sub_id[indexer(hw_thread)];
  867. }
  868. };
  869. static kmp_str_buf_t *
  870. __kmp_hw_get_catalog_core_string(const kmp_hw_attr_t &attr, kmp_str_buf_t *buf,
  871. bool plural) {
  872. __kmp_str_buf_init(buf);
  873. if (attr.is_core_type_valid())
  874. __kmp_str_buf_print(buf, "%s %s",
  875. __kmp_hw_get_core_type_string(attr.get_core_type()),
  876. __kmp_hw_get_catalog_string(KMP_HW_CORE, plural));
  877. else
  878. __kmp_str_buf_print(buf, "%s eff=%d",
  879. __kmp_hw_get_catalog_string(KMP_HW_CORE, plural),
  880. attr.get_core_eff());
  881. return buf;
  882. }
  883. // Apply the KMP_HW_SUBSET envirable to the topology
  884. // Returns true if KMP_HW_SUBSET filtered any processors
  885. // otherwise, returns false
  886. bool kmp_topology_t::filter_hw_subset() {
  887. // If KMP_HW_SUBSET wasn't requested, then do nothing.
  888. if (!__kmp_hw_subset)
  889. return false;
  890. // First, sort the KMP_HW_SUBSET items by the machine topology
  891. __kmp_hw_subset->sort();
  892. // Check to see if KMP_HW_SUBSET is a valid subset of the detected topology
  893. bool using_core_types = false;
  894. bool using_core_effs = false;
  895. int hw_subset_depth = __kmp_hw_subset->get_depth();
  896. kmp_hw_t specified[KMP_HW_LAST];
  897. int *topology_levels = (int *)KMP_ALLOCA(sizeof(int) * hw_subset_depth);
  898. KMP_ASSERT(hw_subset_depth > 0);
  899. KMP_FOREACH_HW_TYPE(i) { specified[i] = KMP_HW_UNKNOWN; }
  900. int core_level = get_level(KMP_HW_CORE);
  901. for (int i = 0; i < hw_subset_depth; ++i) {
  902. int max_count;
  903. const kmp_hw_subset_t::item_t &item = __kmp_hw_subset->at(i);
  904. int num = item.num[0];
  905. int offset = item.offset[0];
  906. kmp_hw_t type = item.type;
  907. kmp_hw_t equivalent_type = equivalent[type];
  908. int level = get_level(type);
  909. topology_levels[i] = level;
  910. // Check to see if current layer is in detected machine topology
  911. if (equivalent_type != KMP_HW_UNKNOWN) {
  912. __kmp_hw_subset->at(i).type = equivalent_type;
  913. } else {
  914. KMP_AFF_WARNING(AffHWSubsetNotExistGeneric,
  915. __kmp_hw_get_catalog_string(type));
  916. return false;
  917. }
  918. // Check to see if current layer has already been
  919. // specified either directly or through an equivalent type
  920. if (specified[equivalent_type] != KMP_HW_UNKNOWN) {
  921. KMP_AFF_WARNING(AffHWSubsetEqvLayers, __kmp_hw_get_catalog_string(type),
  922. __kmp_hw_get_catalog_string(specified[equivalent_type]));
  923. return false;
  924. }
  925. specified[equivalent_type] = type;
  926. // Check to see if each layer's num & offset parameters are valid
  927. max_count = get_ratio(level);
  928. if (max_count < 0 ||
  929. (num != kmp_hw_subset_t::USE_ALL && num + offset > max_count)) {
  930. bool plural = (num > 1);
  931. KMP_AFF_WARNING(AffHWSubsetManyGeneric,
  932. __kmp_hw_get_catalog_string(type, plural));
  933. return false;
  934. }
  935. // Check to see if core attributes are consistent
  936. if (core_level == level) {
  937. // Determine which core attributes are specified
  938. for (int j = 0; j < item.num_attrs; ++j) {
  939. if (item.attr[j].is_core_type_valid())
  940. using_core_types = true;
  941. if (item.attr[j].is_core_eff_valid())
  942. using_core_effs = true;
  943. }
  944. // Check if using a single core attribute on non-hybrid arch.
  945. // Do not ignore all of KMP_HW_SUBSET, just ignore the attribute.
  946. //
  947. // Check if using multiple core attributes on non-hyrbid arch.
  948. // Ignore all of KMP_HW_SUBSET if this is the case.
  949. if ((using_core_effs || using_core_types) && !__kmp_is_hybrid_cpu()) {
  950. if (item.num_attrs == 1) {
  951. if (using_core_effs) {
  952. KMP_AFF_WARNING(AffHWSubsetIgnoringAttr, "efficiency");
  953. } else {
  954. KMP_AFF_WARNING(AffHWSubsetIgnoringAttr, "core_type");
  955. }
  956. using_core_effs = false;
  957. using_core_types = false;
  958. } else {
  959. KMP_AFF_WARNING(AffHWSubsetAttrsNonHybrid);
  960. return false;
  961. }
  962. }
  963. // Check if using both core types and core efficiencies together
  964. if (using_core_types && using_core_effs) {
  965. KMP_AFF_WARNING(AffHWSubsetIncompat, "core_type", "efficiency");
  966. return false;
  967. }
  968. // Check that core efficiency values are valid
  969. if (using_core_effs) {
  970. for (int j = 0; j < item.num_attrs; ++j) {
  971. if (item.attr[j].is_core_eff_valid()) {
  972. int core_eff = item.attr[j].get_core_eff();
  973. if (core_eff < 0 || core_eff >= num_core_efficiencies) {
  974. kmp_str_buf_t buf;
  975. __kmp_str_buf_init(&buf);
  976. __kmp_str_buf_print(&buf, "%d", item.attr[j].get_core_eff());
  977. __kmp_msg(kmp_ms_warning,
  978. KMP_MSG(AffHWSubsetAttrInvalid, "efficiency", buf.str),
  979. KMP_HNT(ValidValuesRange, 0, num_core_efficiencies - 1),
  980. __kmp_msg_null);
  981. __kmp_str_buf_free(&buf);
  982. return false;
  983. }
  984. }
  985. }
  986. }
  987. // Check that the number of requested cores with attributes is valid
  988. if (using_core_types || using_core_effs) {
  989. for (int j = 0; j < item.num_attrs; ++j) {
  990. int num = item.num[j];
  991. int offset = item.offset[j];
  992. int level_above = core_level - 1;
  993. if (level_above >= 0) {
  994. max_count = get_ncores_with_attr_per(item.attr[j], level_above);
  995. if (max_count <= 0 ||
  996. (num != kmp_hw_subset_t::USE_ALL && num + offset > max_count)) {
  997. kmp_str_buf_t buf;
  998. __kmp_hw_get_catalog_core_string(item.attr[j], &buf, num > 0);
  999. KMP_AFF_WARNING(AffHWSubsetManyGeneric, buf.str);
  1000. __kmp_str_buf_free(&buf);
  1001. return false;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. if ((using_core_types || using_core_effs) && item.num_attrs > 1) {
  1007. for (int j = 0; j < item.num_attrs; ++j) {
  1008. // Ambiguous use of specific core attribute + generic core
  1009. // e.g., 4c & 3c:intel_core or 4c & 3c:eff1
  1010. if (!item.attr[j]) {
  1011. kmp_hw_attr_t other_attr;
  1012. for (int k = 0; k < item.num_attrs; ++k) {
  1013. if (item.attr[k] != item.attr[j]) {
  1014. other_attr = item.attr[k];
  1015. break;
  1016. }
  1017. }
  1018. kmp_str_buf_t buf;
  1019. __kmp_hw_get_catalog_core_string(other_attr, &buf, item.num[j] > 0);
  1020. KMP_AFF_WARNING(AffHWSubsetIncompat,
  1021. __kmp_hw_get_catalog_string(KMP_HW_CORE), buf.str);
  1022. __kmp_str_buf_free(&buf);
  1023. return false;
  1024. }
  1025. // Allow specifying a specific core type or core eff exactly once
  1026. for (int k = 0; k < j; ++k) {
  1027. if (!item.attr[j] || !item.attr[k])
  1028. continue;
  1029. if (item.attr[k] == item.attr[j]) {
  1030. kmp_str_buf_t buf;
  1031. __kmp_hw_get_catalog_core_string(item.attr[j], &buf,
  1032. item.num[j] > 0);
  1033. KMP_AFF_WARNING(AffHWSubsetAttrRepeat, buf.str);
  1034. __kmp_str_buf_free(&buf);
  1035. return false;
  1036. }
  1037. }
  1038. }
  1039. }
  1040. }
  1041. }
  1042. struct core_type_indexer {
  1043. int operator()(const kmp_hw_thread_t &t) const {
  1044. switch (t.attrs.get_core_type()) {
  1045. #if KMP_ARCH_X86 || KMP_ARCH_X86_64
  1046. case KMP_HW_CORE_TYPE_ATOM:
  1047. return 1;
  1048. case KMP_HW_CORE_TYPE_CORE:
  1049. return 2;
  1050. #endif
  1051. case KMP_HW_CORE_TYPE_UNKNOWN:
  1052. return 0;
  1053. }
  1054. KMP_ASSERT(0);
  1055. return 0;
  1056. }
  1057. };
  1058. struct core_eff_indexer {
  1059. int operator()(const kmp_hw_thread_t &t) const {
  1060. return t.attrs.get_core_eff();
  1061. }
  1062. };
  1063. kmp_sub_ids_t<KMP_HW_MAX_NUM_CORE_TYPES, core_type_indexer> core_type_sub_ids(
  1064. core_level);
  1065. kmp_sub_ids_t<KMP_HW_MAX_NUM_CORE_EFFS, core_eff_indexer> core_eff_sub_ids(
  1066. core_level);
  1067. // Determine which hardware threads should be filtered.
  1068. int num_filtered = 0;
  1069. bool *filtered = (bool *)__kmp_allocate(sizeof(bool) * num_hw_threads);
  1070. for (int i = 0; i < num_hw_threads; ++i) {
  1071. kmp_hw_thread_t &hw_thread = hw_threads[i];
  1072. // Update type_sub_id
  1073. if (using_core_types)
  1074. core_type_sub_ids.update(hw_thread);
  1075. if (using_core_effs)
  1076. core_eff_sub_ids.update(hw_thread);
  1077. // Check to see if this hardware thread should be filtered
  1078. bool should_be_filtered = false;
  1079. for (int hw_subset_index = 0; hw_subset_index < hw_subset_depth;
  1080. ++hw_subset_index) {
  1081. const auto &hw_subset_item = __kmp_hw_subset->at(hw_subset_index);
  1082. int level = topology_levels[hw_subset_index];
  1083. if (level == -1)
  1084. continue;
  1085. if ((using_core_effs || using_core_types) && level == core_level) {
  1086. // Look for the core attribute in KMP_HW_SUBSET which corresponds
  1087. // to this hardware thread's core attribute. Use this num,offset plus
  1088. // the running sub_id for the particular core attribute of this hardware
  1089. // thread to determine if the hardware thread should be filtered or not.
  1090. int attr_idx;
  1091. kmp_hw_core_type_t core_type = hw_thread.attrs.get_core_type();
  1092. int core_eff = hw_thread.attrs.get_core_eff();
  1093. for (attr_idx = 0; attr_idx < hw_subset_item.num_attrs; ++attr_idx) {
  1094. if (using_core_types &&
  1095. hw_subset_item.attr[attr_idx].get_core_type() == core_type)
  1096. break;
  1097. if (using_core_effs &&
  1098. hw_subset_item.attr[attr_idx].get_core_eff() == core_eff)
  1099. break;
  1100. }
  1101. // This core attribute isn't in the KMP_HW_SUBSET so always filter it.
  1102. if (attr_idx == hw_subset_item.num_attrs) {
  1103. should_be_filtered = true;
  1104. break;
  1105. }
  1106. int sub_id;
  1107. int num = hw_subset_item.num[attr_idx];
  1108. int offset = hw_subset_item.offset[attr_idx];
  1109. if (using_core_types)
  1110. sub_id = core_type_sub_ids.get_sub_id(hw_thread);
  1111. else
  1112. sub_id = core_eff_sub_ids.get_sub_id(hw_thread);
  1113. if (sub_id < offset ||
  1114. (num != kmp_hw_subset_t::USE_ALL && sub_id >= offset + num)) {
  1115. should_be_filtered = true;
  1116. break;
  1117. }
  1118. } else {
  1119. int num = hw_subset_item.num[0];
  1120. int offset = hw_subset_item.offset[0];
  1121. if (hw_thread.sub_ids[level] < offset ||
  1122. (num != kmp_hw_subset_t::USE_ALL &&
  1123. hw_thread.sub_ids[level] >= offset + num)) {
  1124. should_be_filtered = true;
  1125. break;
  1126. }
  1127. }
  1128. }
  1129. // Collect filtering information
  1130. filtered[i] = should_be_filtered;
  1131. if (should_be_filtered)
  1132. num_filtered++;
  1133. }
  1134. // One last check that we shouldn't allow filtering entire machine
  1135. if (num_filtered == num_hw_threads) {
  1136. KMP_AFF_WARNING(AffHWSubsetAllFiltered);
  1137. __kmp_free(filtered);
  1138. return false;
  1139. }
  1140. // Apply the filter
  1141. int new_index = 0;
  1142. for (int i = 0; i < num_hw_threads; ++i) {
  1143. if (!filtered[i]) {
  1144. if (i != new_index)
  1145. hw_threads[new_index] = hw_threads[i];
  1146. new_index++;
  1147. } else {
  1148. #if KMP_AFFINITY_SUPPORTED
  1149. KMP_CPU_CLR(hw_threads[i].os_id, __kmp_affin_fullMask);
  1150. #endif
  1151. __kmp_avail_proc--;
  1152. }
  1153. }
  1154. KMP_DEBUG_ASSERT(new_index <= num_hw_threads);
  1155. num_hw_threads = new_index;
  1156. // Post hardware subset canonicalization
  1157. _gather_enumeration_information();
  1158. _discover_uniformity();
  1159. _set_globals();
  1160. _set_last_level_cache();
  1161. __kmp_free(filtered);
  1162. return true;
  1163. }
  1164. bool kmp_topology_t::is_close(int hwt1, int hwt2, int hw_level) const {
  1165. if (hw_level >= depth)
  1166. return true;
  1167. bool retval = true;
  1168. const kmp_hw_thread_t &t1 = hw_threads[hwt1];
  1169. const kmp_hw_thread_t &t2 = hw_threads[hwt2];
  1170. for (int i = 0; i < (depth - hw_level); ++i) {
  1171. if (t1.ids[i] != t2.ids[i])
  1172. return false;
  1173. }
  1174. return retval;
  1175. }
  1176. ////////////////////////////////////////////////////////////////////////////////
  1177. #if KMP_AFFINITY_SUPPORTED
  1178. class kmp_affinity_raii_t {
  1179. kmp_affin_mask_t *mask;
  1180. bool restored;
  1181. public:
  1182. kmp_affinity_raii_t() : restored(false) {
  1183. KMP_CPU_ALLOC(mask);
  1184. KMP_ASSERT(mask != NULL);
  1185. __kmp_get_system_affinity(mask, TRUE);
  1186. }
  1187. void restore() {
  1188. __kmp_set_system_affinity(mask, TRUE);
  1189. KMP_CPU_FREE(mask);
  1190. restored = true;
  1191. }
  1192. ~kmp_affinity_raii_t() {
  1193. if (!restored) {
  1194. __kmp_set_system_affinity(mask, TRUE);
  1195. KMP_CPU_FREE(mask);
  1196. }
  1197. }
  1198. };
  1199. bool KMPAffinity::picked_api = false;
  1200. void *KMPAffinity::Mask::operator new(size_t n) { return __kmp_allocate(n); }
  1201. void *KMPAffinity::Mask::operator new[](size_t n) { return __kmp_allocate(n); }
  1202. void KMPAffinity::Mask::operator delete(void *p) { __kmp_free(p); }
  1203. void KMPAffinity::Mask::operator delete[](void *p) { __kmp_free(p); }
  1204. void *KMPAffinity::operator new(size_t n) { return __kmp_allocate(n); }
  1205. void KMPAffinity::operator delete(void *p) { __kmp_free(p); }
  1206. void KMPAffinity::pick_api() {
  1207. KMPAffinity *affinity_dispatch;
  1208. if (picked_api)
  1209. return;
  1210. #if KMP_USE_HWLOC
  1211. // Only use Hwloc if affinity isn't explicitly disabled and
  1212. // user requests Hwloc topology method
  1213. if (__kmp_affinity_top_method == affinity_top_method_hwloc &&
  1214. __kmp_affinity_type != affinity_disabled) {
  1215. affinity_dispatch = new KMPHwlocAffinity();
  1216. } else
  1217. #endif
  1218. {
  1219. affinity_dispatch = new KMPNativeAffinity();
  1220. }
  1221. __kmp_affinity_dispatch = affinity_dispatch;
  1222. picked_api = true;
  1223. }
  1224. void KMPAffinity::destroy_api() {
  1225. if (__kmp_affinity_dispatch != NULL) {
  1226. delete __kmp_affinity_dispatch;
  1227. __kmp_affinity_dispatch = NULL;
  1228. picked_api = false;
  1229. }
  1230. }
  1231. #define KMP_ADVANCE_SCAN(scan) \
  1232. while (*scan != '\0') { \
  1233. scan++; \
  1234. }
  1235. // Print the affinity mask to the character array in a pretty format.
  1236. // The format is a comma separated list of non-negative integers or integer
  1237. // ranges: e.g., 1,2,3-5,7,9-15
  1238. // The format can also be the string "{<empty>}" if no bits are set in mask
  1239. char *__kmp_affinity_print_mask(char *buf, int buf_len,
  1240. kmp_affin_mask_t *mask) {
  1241. int start = 0, finish = 0, previous = 0;
  1242. bool first_range;
  1243. KMP_ASSERT(buf);
  1244. KMP_ASSERT(buf_len >= 40);
  1245. KMP_ASSERT(mask);
  1246. char *scan = buf;
  1247. char *end = buf + buf_len - 1;
  1248. // Check for empty set.
  1249. if (mask->begin() == mask->end()) {
  1250. KMP_SNPRINTF(scan, end - scan + 1, "{<empty>}");
  1251. KMP_ADVANCE_SCAN(scan);
  1252. KMP_ASSERT(scan <= end);
  1253. return buf;
  1254. }
  1255. first_range = true;
  1256. start = mask->begin();
  1257. while (1) {
  1258. // Find next range
  1259. // [start, previous] is inclusive range of contiguous bits in mask
  1260. for (finish = mask->next(start), previous = start;
  1261. finish == previous + 1 && finish != mask->end();
  1262. finish = mask->next(finish)) {
  1263. previous = finish;
  1264. }
  1265. // The first range does not need a comma printed before it, but the rest
  1266. // of the ranges do need a comma beforehand
  1267. if (!first_range) {
  1268. KMP_SNPRINTF(scan, end - scan + 1, "%s", ",");
  1269. KMP_ADVANCE_SCAN(scan);
  1270. } else {
  1271. first_range = false;
  1272. }
  1273. // Range with three or more contiguous bits in the affinity mask
  1274. if (previous - start > 1) {
  1275. KMP_SNPRINTF(scan, end - scan + 1, "%u-%u", start, previous);
  1276. } else {
  1277. // Range with one or two contiguous bits in the affinity mask
  1278. KMP_SNPRINTF(scan, end - scan + 1, "%u", start);
  1279. KMP_ADVANCE_SCAN(scan);
  1280. if (previous - start > 0) {
  1281. KMP_SNPRINTF(scan, end - scan + 1, ",%u", previous);
  1282. }
  1283. }
  1284. KMP_ADVANCE_SCAN(scan);
  1285. // Start over with new start point
  1286. start = finish;
  1287. if (start == mask->end())
  1288. break;
  1289. // Check for overflow
  1290. if (end - scan < 2)
  1291. break;
  1292. }
  1293. // Check for overflow
  1294. KMP_ASSERT(scan <= end);
  1295. return buf;
  1296. }
  1297. #undef KMP_ADVANCE_SCAN
  1298. // Print the affinity mask to the string buffer object in a pretty format
  1299. // The format is a comma separated list of non-negative integers or integer
  1300. // ranges: e.g., 1,2,3-5,7,9-15
  1301. // The format can also be the string "{<empty>}" if no bits are set in mask
  1302. kmp_str_buf_t *__kmp_affinity_str_buf_mask(kmp_str_buf_t *buf,
  1303. kmp_affin_mask_t *mask) {
  1304. int start = 0, finish = 0, previous = 0;
  1305. bool first_range;
  1306. KMP_ASSERT(buf);
  1307. KMP_ASSERT(mask);
  1308. __kmp_str_buf_clear(buf);
  1309. // Check for empty set.
  1310. if (mask->begin() == mask->end()) {
  1311. __kmp_str_buf_print(buf, "%s", "{<empty>}");
  1312. return buf;
  1313. }
  1314. first_range = true;
  1315. start = mask->begin();
  1316. while (1) {
  1317. // Find next range
  1318. // [start, previous] is inclusive range of contiguous bits in mask
  1319. for (finish = mask->next(start), previous = start;
  1320. finish == previous + 1 && finish != mask->end();
  1321. finish = mask->next(finish)) {
  1322. previous = finish;
  1323. }
  1324. // The first range does not need a comma printed before it, but the rest
  1325. // of the ranges do need a comma beforehand
  1326. if (!first_range) {
  1327. __kmp_str_buf_print(buf, "%s", ",");
  1328. } else {
  1329. first_range = false;
  1330. }
  1331. // Range with three or more contiguous bits in the affinity mask
  1332. if (previous - start > 1) {
  1333. __kmp_str_buf_print(buf, "%u-%u", start, previous);
  1334. } else {
  1335. // Range with one or two contiguous bits in the affinity mask
  1336. __kmp_str_buf_print(buf, "%u", start);
  1337. if (previous - start > 0) {
  1338. __kmp_str_buf_print(buf, ",%u", previous);
  1339. }
  1340. }
  1341. // Start over with new start point
  1342. start = finish;
  1343. if (start == mask->end())
  1344. break;
  1345. }
  1346. return buf;
  1347. }
  1348. // Return (possibly empty) affinity mask representing the offline CPUs
  1349. // Caller must free the mask
  1350. kmp_affin_mask_t *__kmp_affinity_get_offline_cpus() {
  1351. kmp_affin_mask_t *offline;
  1352. KMP_CPU_ALLOC(offline);
  1353. KMP_CPU_ZERO(offline);
  1354. #if KMP_OS_LINUX
  1355. int n, begin_cpu, end_cpu;
  1356. kmp_safe_raii_file_t offline_file;
  1357. auto skip_ws = [](FILE *f) {
  1358. int c;
  1359. do {
  1360. c = fgetc(f);
  1361. } while (isspace(c));
  1362. if (c != EOF)
  1363. ungetc(c, f);
  1364. };
  1365. // File contains CSV of integer ranges representing the offline CPUs
  1366. // e.g., 1,2,4-7,9,11-15
  1367. int status = offline_file.try_open("/sys/devices/system/cpu/offline", "r");
  1368. if (status != 0)
  1369. return offline;
  1370. while (!feof(offline_file)) {
  1371. skip_ws(offline_file);
  1372. n = fscanf(offline_file, "%d", &begin_cpu);
  1373. if (n != 1)
  1374. break;
  1375. skip_ws(offline_file);
  1376. int c = fgetc(offline_file);
  1377. if (c == EOF || c == ',') {
  1378. // Just single CPU
  1379. end_cpu = begin_cpu;
  1380. } else if (c == '-') {
  1381. // Range of CPUs
  1382. skip_ws(offline_file);
  1383. n = fscanf(offline_file, "%d", &end_cpu);
  1384. if (n != 1)
  1385. break;
  1386. skip_ws(offline_file);
  1387. c = fgetc(offline_file); // skip ','
  1388. } else {
  1389. // Syntax problem
  1390. break;
  1391. }
  1392. // Ensure a valid range of CPUs
  1393. if (begin_cpu < 0 || begin_cpu >= __kmp_xproc || end_cpu < 0 ||
  1394. end_cpu >= __kmp_xproc || begin_cpu > end_cpu) {
  1395. continue;
  1396. }
  1397. // Insert [begin_cpu, end_cpu] into offline mask
  1398. for (int cpu = begin_cpu; cpu <= end_cpu; ++cpu) {
  1399. KMP_CPU_SET(cpu, offline);
  1400. }
  1401. }
  1402. #endif
  1403. return offline;
  1404. }
  1405. // Return the number of available procs
  1406. int __kmp_affinity_entire_machine_mask(kmp_affin_mask_t *mask) {
  1407. int avail_proc = 0;
  1408. KMP_CPU_ZERO(mask);
  1409. #if KMP_GROUP_AFFINITY
  1410. if (__kmp_num_proc_groups > 1) {
  1411. int group;
  1412. KMP_DEBUG_ASSERT(__kmp_GetActiveProcessorCount != NULL);
  1413. for (group = 0; group < __kmp_num_proc_groups; group++) {
  1414. int i;
  1415. int num = __kmp_GetActiveProcessorCount(group);
  1416. for (i = 0; i < num; i++) {
  1417. KMP_CPU_SET(i + group * (CHAR_BIT * sizeof(DWORD_PTR)), mask);
  1418. avail_proc++;
  1419. }
  1420. }
  1421. } else
  1422. #endif /* KMP_GROUP_AFFINITY */
  1423. {
  1424. int proc;
  1425. kmp_affin_mask_t *offline_cpus = __kmp_affinity_get_offline_cpus();
  1426. for (proc = 0; proc < __kmp_xproc; proc++) {
  1427. // Skip offline CPUs
  1428. if (KMP_CPU_ISSET(proc, offline_cpus))
  1429. continue;
  1430. KMP_CPU_SET(proc, mask);
  1431. avail_proc++;
  1432. }
  1433. KMP_CPU_FREE(offline_cpus);
  1434. }
  1435. return avail_proc;
  1436. }
  1437. // All of the __kmp_affinity_create_*_map() routines should allocate the
  1438. // internal topology object and set the layer ids for it. Each routine
  1439. // returns a boolean on whether it was successful at doing so.
  1440. kmp_affin_mask_t *__kmp_affin_fullMask = NULL;
  1441. // Original mask is a subset of full mask in multiple processor groups topology
  1442. kmp_affin_mask_t *__kmp_affin_origMask = NULL;
  1443. #if KMP_USE_HWLOC
  1444. static inline bool __kmp_hwloc_is_cache_type(hwloc_obj_t obj) {
  1445. #if HWLOC_API_VERSION >= 0x00020000
  1446. return hwloc_obj_type_is_cache(obj->type);
  1447. #else
  1448. return obj->type == HWLOC_OBJ_CACHE;
  1449. #endif
  1450. }
  1451. // Returns KMP_HW_* type derived from HWLOC_* type
  1452. static inline kmp_hw_t __kmp_hwloc_type_2_topology_type(hwloc_obj_t obj) {
  1453. if (__kmp_hwloc_is_cache_type(obj)) {
  1454. if (obj->attr->cache.type == HWLOC_OBJ_CACHE_INSTRUCTION)
  1455. return KMP_HW_UNKNOWN;
  1456. switch (obj->attr->cache.depth) {
  1457. case 1:
  1458. return KMP_HW_L1;
  1459. case 2:
  1460. #if KMP_MIC_SUPPORTED
  1461. if (__kmp_mic_type == mic3) {
  1462. return KMP_HW_TILE;
  1463. }
  1464. #endif
  1465. return KMP_HW_L2;
  1466. case 3:
  1467. return KMP_HW_L3;
  1468. }
  1469. return KMP_HW_UNKNOWN;
  1470. }
  1471. switch (obj->type) {
  1472. case HWLOC_OBJ_PACKAGE:
  1473. return KMP_HW_SOCKET;
  1474. case HWLOC_OBJ_NUMANODE:
  1475. return KMP_HW_NUMA;
  1476. case HWLOC_OBJ_CORE:
  1477. return KMP_HW_CORE;
  1478. case HWLOC_OBJ_PU:
  1479. return KMP_HW_THREAD;
  1480. case HWLOC_OBJ_GROUP:
  1481. if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_DIE)
  1482. return KMP_HW_DIE;
  1483. else if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_TILE)
  1484. return KMP_HW_TILE;
  1485. else if (obj->attr->group.kind == HWLOC_GROUP_KIND_INTEL_MODULE)
  1486. return KMP_HW_MODULE;
  1487. else if (obj->attr->group.kind == HWLOC_GROUP_KIND_WINDOWS_PROCESSOR_GROUP)
  1488. return KMP_HW_PROC_GROUP;
  1489. return KMP_HW_UNKNOWN;
  1490. #if HWLOC_API_VERSION >= 0x00020100
  1491. case HWLOC_OBJ_DIE:
  1492. return KMP_HW_DIE;
  1493. #endif
  1494. }
  1495. return KMP_HW_UNKNOWN;
  1496. }
  1497. // Returns the number of objects of type 'type' below 'obj' within the topology
  1498. // tree structure. e.g., if obj is a HWLOC_OBJ_PACKAGE object, and type is
  1499. // HWLOC_OBJ_PU, then this will return the number of PU's under the SOCKET
  1500. // object.
  1501. static int __kmp_hwloc_get_nobjs_under_obj(hwloc_obj_t obj,
  1502. hwloc_obj_type_t type) {
  1503. int retval = 0;
  1504. hwloc_obj_t first;
  1505. for (first = hwloc_get_obj_below_by_type(__kmp_hwloc_topology, obj->type,
  1506. obj->logical_index, type, 0);
  1507. first != NULL && hwloc_get_ancestor_obj_by_type(__kmp_hwloc_topology,
  1508. obj->type, first) == obj;
  1509. first = hwloc_get_next_obj_by_type(__kmp_hwloc_topology, first->type,
  1510. first)) {
  1511. ++retval;
  1512. }
  1513. return retval;
  1514. }
  1515. // This gets the sub_id for a lower object under a higher object in the
  1516. // topology tree
  1517. static int __kmp_hwloc_get_sub_id(hwloc_topology_t t, hwloc_obj_t higher,
  1518. hwloc_obj_t lower) {
  1519. hwloc_obj_t obj;
  1520. hwloc_obj_type_t ltype = lower->type;
  1521. int lindex = lower->logical_index - 1;
  1522. int sub_id = 0;
  1523. // Get the previous lower object
  1524. obj = hwloc_get_obj_by_type(t, ltype, lindex);
  1525. while (obj && lindex >= 0 &&
  1526. hwloc_bitmap_isincluded(obj->cpuset, higher->cpuset)) {
  1527. if (obj->userdata) {
  1528. sub_id = (int)(RCAST(kmp_intptr_t, obj->userdata));
  1529. break;
  1530. }
  1531. sub_id++;
  1532. lindex--;
  1533. obj = hwloc_get_obj_by_type(t, ltype, lindex);
  1534. }
  1535. // store sub_id + 1 so that 0 is differed from NULL
  1536. lower->userdata = RCAST(void *, sub_id + 1);
  1537. return sub_id;
  1538. }
  1539. static bool __kmp_affinity_create_hwloc_map(kmp_i18n_id_t *const msg_id) {
  1540. kmp_hw_t type;
  1541. int hw_thread_index, sub_id;
  1542. int depth;
  1543. hwloc_obj_t pu, obj, root, prev;
  1544. kmp_hw_t types[KMP_HW_LAST];
  1545. hwloc_obj_type_t hwloc_types[KMP_HW_LAST];
  1546. hwloc_topology_t tp = __kmp_hwloc_topology;
  1547. *msg_id = kmp_i18n_null;
  1548. if (__kmp_affinity_verbose) {
  1549. KMP_INFORM(AffUsingHwloc, "KMP_AFFINITY");
  1550. }
  1551. if (!KMP_AFFINITY_CAPABLE()) {
  1552. // Hack to try and infer the machine topology using only the data
  1553. // available from hwloc on the current thread, and __kmp_xproc.
  1554. KMP_ASSERT(__kmp_affinity_type == affinity_none);
  1555. // hwloc only guarantees existance of PU object, so check PACKAGE and CORE
  1556. hwloc_obj_t o = hwloc_get_obj_by_type(tp, HWLOC_OBJ_PACKAGE, 0);
  1557. if (o != NULL)
  1558. nCoresPerPkg = __kmp_hwloc_get_nobjs_under_obj(o, HWLOC_OBJ_CORE);
  1559. else
  1560. nCoresPerPkg = 1; // no PACKAGE found
  1561. o = hwloc_get_obj_by_type(tp, HWLOC_OBJ_CORE, 0);
  1562. if (o != NULL)
  1563. __kmp_nThreadsPerCore = __kmp_hwloc_get_nobjs_under_obj(o, HWLOC_OBJ_PU);
  1564. else
  1565. __kmp_nThreadsPerCore = 1; // no CORE found
  1566. __kmp_ncores = __kmp_xproc / __kmp_nThreadsPerCore;
  1567. if (nCoresPerPkg == 0)
  1568. nCoresPerPkg = 1; // to prevent possible division by 0
  1569. nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;
  1570. return true;
  1571. }
  1572. // Handle multiple types of cores if they exist on the system
  1573. int nr_cpu_kinds = hwloc_cpukinds_get_nr(tp, 0);
  1574. typedef struct kmp_hwloc_cpukinds_info_t {
  1575. int efficiency;
  1576. kmp_hw_core_type_t core_type;
  1577. hwloc_bitmap_t mask;
  1578. } kmp_hwloc_cpukinds_info_t;
  1579. kmp_hwloc_cpukinds_info_t *cpukinds = nullptr;
  1580. if (nr_cpu_kinds > 0) {
  1581. unsigned nr_infos;
  1582. struct hwloc_info_s *infos;
  1583. cpukinds = (kmp_hwloc_cpukinds_info_t *)__kmp_allocate(
  1584. sizeof(kmp_hwloc_cpukinds_info_t) * nr_cpu_kinds);
  1585. for (unsigned idx = 0; idx < (unsigned)nr_cpu_kinds; ++idx) {
  1586. cpukinds[idx].efficiency = -1;
  1587. cpukinds[idx].core_type = KMP_HW_CORE_TYPE_UNKNOWN;
  1588. cpukinds[idx].mask = hwloc_bitmap_alloc();
  1589. if (hwloc_cpukinds_get_info(tp, idx, cpukinds[idx].mask,
  1590. &cpukinds[idx].efficiency, &nr_infos, &infos,
  1591. 0) == 0) {
  1592. for (unsigned i = 0; i < nr_infos; ++i) {
  1593. if (__kmp_str_match("CoreType", 8, infos[i].name)) {
  1594. #if KMP_ARCH_X86 || KMP_ARCH_X86_64
  1595. if (__kmp_str_match("IntelAtom", 9, infos[i].value)) {
  1596. cpukinds[idx].core_type = KMP_HW_CORE_TYPE_ATOM;
  1597. break;
  1598. } else if (__kmp_str_match("IntelCore", 9, infos[i].value)) {
  1599. cpukinds[idx].core_type = KMP_HW_CORE_TYPE_CORE;
  1600. break;
  1601. }
  1602. #endif
  1603. }
  1604. }
  1605. }
  1606. }
  1607. }
  1608. root = hwloc_get_root_obj(tp);
  1609. // Figure out the depth and types in the topology
  1610. depth = 0;
  1611. pu = hwloc_get_pu_obj_by_os_index(tp, __kmp_affin_fullMask->begin());
  1612. KMP_ASSERT(pu);
  1613. obj = pu;
  1614. types[depth] = KMP_HW_THREAD;
  1615. hwloc_types[depth] = obj->type;
  1616. depth++;
  1617. while (obj != root && obj != NULL) {
  1618. obj = obj->parent;
  1619. #if HWLOC_API_VERSION >= 0x00020000
  1620. if (obj->memory_arity) {
  1621. hwloc_obj_t memory;
  1622. for (memory = obj->memory_first_child; memory;
  1623. memory = hwloc_get_next_child(tp, obj, memory)) {
  1624. if (memory->type == HWLOC_OBJ_NUMANODE)
  1625. break;
  1626. }
  1627. if (memory && memory->type == HWLOC_OBJ_NUMANODE) {
  1628. types[depth] = KMP_HW_NUMA;
  1629. hwloc_types[depth] = memory->type;
  1630. depth++;
  1631. }
  1632. }
  1633. #endif
  1634. type = __kmp_hwloc_type_2_topology_type(obj);
  1635. if (type != KMP_HW_UNKNOWN) {
  1636. types[depth] = type;
  1637. hwloc_types[depth] = obj->type;
  1638. depth++;
  1639. }
  1640. }
  1641. KMP_ASSERT(depth > 0);
  1642. // Get the order for the types correct
  1643. for (int i = 0, j = depth - 1; i < j; ++i, --j) {
  1644. hwloc_obj_type_t hwloc_temp = hwloc_types[i];
  1645. kmp_hw_t temp = types[i];
  1646. types[i] = types[j];
  1647. types[j] = temp;
  1648. hwloc_types[i] = hwloc_types[j];
  1649. hwloc_types[j] = hwloc_temp;
  1650. }
  1651. // Allocate the data structure to be returned.
  1652. __kmp_topology = kmp_topology_t::allocate(__kmp_avail_proc, depth, types);
  1653. hw_thread_index = 0;
  1654. pu = NULL;
  1655. while ((pu = hwloc_get_next_obj_by_type(tp, HWLOC_OBJ_PU, pu))) {
  1656. int index = depth - 1;
  1657. bool included = KMP_CPU_ISSET(pu->os_index, __kmp_affin_fullMask);
  1658. kmp_hw_thread_t &hw_thread = __kmp_topology->at(hw_thread_index);
  1659. if (included) {
  1660. hw_thread.clear();
  1661. hw_thread.ids[index] = pu->logical_index;
  1662. hw_thread.os_id = pu->os_index;
  1663. // If multiple core types, then set that attribute for the hardware thread
  1664. if (cpukinds) {
  1665. int cpukind_index = -1;
  1666. for (int i = 0; i < nr_cpu_kinds; ++i) {
  1667. if (hwloc_bitmap_isset(cpukinds[i].mask, hw_thread.os_id)) {
  1668. cpukind_index = i;
  1669. break;
  1670. }
  1671. }
  1672. if (cpukind_index >= 0) {
  1673. hw_thread.attrs.set_core_type(cpukinds[cpukind_index].core_type);
  1674. hw_thread.attrs.set_core_eff(cpukinds[cpukind_index].efficiency);
  1675. }
  1676. }
  1677. index--;
  1678. }
  1679. obj = pu;
  1680. prev = obj;
  1681. while (obj != root && obj != NULL) {
  1682. obj = obj->parent;
  1683. #if HWLOC_API_VERSION >= 0x00020000
  1684. // NUMA Nodes are handled differently since they are not within the
  1685. // parent/child structure anymore. They are separate children
  1686. // of obj (memory_first_child points to first memory child)
  1687. if (obj->memory_arity) {
  1688. hwloc_obj_t memory;
  1689. for (memory = obj->memory_first_child; memory;
  1690. memory = hwloc_get_next_child(tp, obj, memory)) {
  1691. if (memory->type == HWLOC_OBJ_NUMANODE)
  1692. break;
  1693. }
  1694. if (memory && memory->type == HWLOC_OBJ_NUMANODE) {
  1695. sub_id = __kmp_hwloc_get_sub_id(tp, memory, prev);
  1696. if (included) {
  1697. hw_thread.ids[index] = memory->logical_index;
  1698. hw_thread.ids[index + 1] = sub_id;
  1699. index--;
  1700. }
  1701. prev = memory;
  1702. }
  1703. prev = obj;
  1704. }
  1705. #endif
  1706. type = __kmp_hwloc_type_2_topology_type(obj);
  1707. if (type != KMP_HW_UNKNOWN) {
  1708. sub_id = __kmp_hwloc_get_sub_id(tp, obj, prev);
  1709. if (included) {
  1710. hw_thread.ids[index] = obj->logical_index;
  1711. hw_thread.ids[index + 1] = sub_id;
  1712. index--;
  1713. }
  1714. prev = obj;
  1715. }
  1716. }
  1717. if (included)
  1718. hw_thread_index++;
  1719. }
  1720. // Free the core types information
  1721. if (cpukinds) {
  1722. for (int idx = 0; idx < nr_cpu_kinds; ++idx)
  1723. hwloc_bitmap_free(cpukinds[idx].mask);
  1724. __kmp_free(cpukinds);
  1725. }
  1726. __kmp_topology->sort_ids();
  1727. return true;
  1728. }
  1729. #endif // KMP_USE_HWLOC
  1730. // If we don't know how to retrieve the machine's processor topology, or
  1731. // encounter an error in doing so, this routine is called to form a "flat"
  1732. // mapping of os thread id's <-> processor id's.
  1733. static bool __kmp_affinity_create_flat_map(kmp_i18n_id_t *const msg_id) {
  1734. *msg_id = kmp_i18n_null;
  1735. int depth = 3;
  1736. kmp_hw_t types[] = {KMP_HW_SOCKET, KMP_HW_CORE, KMP_HW_THREAD};
  1737. if (__kmp_affinity_verbose) {
  1738. KMP_INFORM(UsingFlatOS, "KMP_AFFINITY");
  1739. }
  1740. // Even if __kmp_affinity_type == affinity_none, this routine might still
  1741. // called to set __kmp_ncores, as well as
  1742. // __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
  1743. if (!KMP_AFFINITY_CAPABLE()) {
  1744. KMP_ASSERT(__kmp_affinity_type == affinity_none);
  1745. __kmp_ncores = nPackages = __kmp_xproc;
  1746. __kmp_nThreadsPerCore = nCoresPerPkg = 1;
  1747. return true;
  1748. }
  1749. // When affinity is off, this routine will still be called to set
  1750. // __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
  1751. // Make sure all these vars are set correctly, and return now if affinity is
  1752. // not enabled.
  1753. __kmp_ncores = nPackages = __kmp_avail_proc;
  1754. __kmp_nThreadsPerCore = nCoresPerPkg = 1;
  1755. // Construct the data structure to be returned.
  1756. __kmp_topology = kmp_topology_t::allocate(__kmp_avail_proc, depth, types);
  1757. int avail_ct = 0;
  1758. int i;
  1759. KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
  1760. // Skip this proc if it is not included in the machine model.
  1761. if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
  1762. continue;
  1763. }
  1764. kmp_hw_thread_t &hw_thread = __kmp_topology->at(avail_ct);
  1765. hw_thread.clear();
  1766. hw_thread.os_id = i;
  1767. hw_thread.ids[0] = i;
  1768. hw_thread.ids[1] = 0;
  1769. hw_thread.ids[2] = 0;
  1770. avail_ct++;
  1771. }
  1772. if (__kmp_affinity_verbose) {
  1773. KMP_INFORM(OSProcToPackage, "KMP_AFFINITY");
  1774. }
  1775. return true;
  1776. }
  1777. #if KMP_GROUP_AFFINITY
  1778. // If multiple Windows* OS processor groups exist, we can create a 2-level
  1779. // topology map with the groups at level 0 and the individual procs at level 1.
  1780. // This facilitates letting the threads float among all procs in a group,
  1781. // if granularity=group (the default when there are multiple groups).
  1782. static bool __kmp_affinity_create_proc_group_map(kmp_i18n_id_t *const msg_id) {
  1783. *msg_id = kmp_i18n_null;
  1784. int depth = 3;
  1785. kmp_hw_t types[] = {KMP_HW_PROC_GROUP, KMP_HW_CORE, KMP_HW_THREAD};
  1786. const static size_t BITS_PER_GROUP = CHAR_BIT * sizeof(DWORD_PTR);
  1787. if (__kmp_affinity_verbose) {
  1788. KMP_INFORM(AffWindowsProcGroupMap, "KMP_AFFINITY");
  1789. }
  1790. // If we aren't affinity capable, then use flat topology
  1791. if (!KMP_AFFINITY_CAPABLE()) {
  1792. KMP_ASSERT(__kmp_affinity_type == affinity_none);
  1793. nPackages = __kmp_num_proc_groups;
  1794. __kmp_nThreadsPerCore = 1;
  1795. __kmp_ncores = __kmp_xproc;
  1796. nCoresPerPkg = nPackages / __kmp_ncores;
  1797. return true;
  1798. }
  1799. // Construct the data structure to be returned.
  1800. __kmp_topology = kmp_topology_t::allocate(__kmp_avail_proc, depth, types);
  1801. int avail_ct = 0;
  1802. int i;
  1803. KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
  1804. // Skip this proc if it is not included in the machine model.
  1805. if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
  1806. continue;
  1807. }
  1808. kmp_hw_thread_t &hw_thread = __kmp_topology->at(avail_ct++);
  1809. hw_thread.clear();
  1810. hw_thread.os_id = i;
  1811. hw_thread.ids[0] = i / BITS_PER_GROUP;
  1812. hw_thread.ids[1] = hw_thread.ids[2] = i % BITS_PER_GROUP;
  1813. }
  1814. return true;
  1815. }
  1816. #endif /* KMP_GROUP_AFFINITY */
  1817. #if KMP_ARCH_X86 || KMP_ARCH_X86_64
  1818. template <kmp_uint32 LSB, kmp_uint32 MSB>
  1819. static inline unsigned __kmp_extract_bits(kmp_uint32 v) {
  1820. const kmp_uint32 SHIFT_LEFT = sizeof(kmp_uint32) * 8 - 1 - MSB;
  1821. const kmp_uint32 SHIFT_RIGHT = LSB;
  1822. kmp_uint32 retval = v;
  1823. retval <<= SHIFT_LEFT;
  1824. retval >>= (SHIFT_LEFT + SHIFT_RIGHT);
  1825. return retval;
  1826. }
  1827. static int __kmp_cpuid_mask_width(int count) {
  1828. int r = 0;
  1829. while ((1 << r) < count)
  1830. ++r;
  1831. return r;
  1832. }
  1833. class apicThreadInfo {
  1834. public:
  1835. unsigned osId; // param to __kmp_affinity_bind_thread
  1836. unsigned apicId; // from cpuid after binding
  1837. unsigned maxCoresPerPkg; // ""
  1838. unsigned maxThreadsPerPkg; // ""
  1839. unsigned pkgId; // inferred from above values
  1840. unsigned coreId; // ""
  1841. unsigned threadId; // ""
  1842. };
  1843. static int __kmp_affinity_cmp_apicThreadInfo_phys_id(const void *a,
  1844. const void *b) {
  1845. const apicThreadInfo *aa = (const apicThreadInfo *)a;
  1846. const apicThreadInfo *bb = (const apicThreadInfo *)b;
  1847. if (aa->pkgId < bb->pkgId)
  1848. return -1;
  1849. if (aa->pkgId > bb->pkgId)
  1850. return 1;
  1851. if (aa->coreId < bb->coreId)
  1852. return -1;
  1853. if (aa->coreId > bb->coreId)
  1854. return 1;
  1855. if (aa->threadId < bb->threadId)
  1856. return -1;
  1857. if (aa->threadId > bb->threadId)
  1858. return 1;
  1859. return 0;
  1860. }
  1861. class kmp_cache_info_t {
  1862. public:
  1863. struct info_t {
  1864. unsigned level, mask;
  1865. };
  1866. kmp_cache_info_t() : depth(0) { get_leaf4_levels(); }
  1867. size_t get_depth() const { return depth; }
  1868. info_t &operator[](size_t index) { return table[index]; }
  1869. const info_t &operator[](size_t index) const { return table[index]; }
  1870. static kmp_hw_t get_topology_type(unsigned level) {
  1871. KMP_DEBUG_ASSERT(level >= 1 && level <= MAX_CACHE_LEVEL);
  1872. switch (level) {
  1873. case 1:
  1874. return KMP_HW_L1;
  1875. case 2:
  1876. return KMP_HW_L2;
  1877. case 3:
  1878. return KMP_HW_L3;
  1879. }
  1880. return KMP_HW_UNKNOWN;
  1881. }
  1882. private:
  1883. static const int MAX_CACHE_LEVEL = 3;
  1884. size_t depth;
  1885. info_t table[MAX_CACHE_LEVEL];
  1886. void get_leaf4_levels() {
  1887. unsigned level = 0;
  1888. while (depth < MAX_CACHE_LEVEL) {
  1889. unsigned cache_type, max_threads_sharing;
  1890. unsigned cache_level, cache_mask_width;
  1891. kmp_cpuid buf2;
  1892. __kmp_x86_cpuid(4, level, &buf2);
  1893. cache_type = __kmp_extract_bits<0, 4>(buf2.eax);
  1894. if (!cache_type)
  1895. break;
  1896. // Skip instruction caches
  1897. if (cache_type == 2) {
  1898. level++;
  1899. continue;
  1900. }
  1901. max_threads_sharing = __kmp_extract_bits<14, 25>(buf2.eax) + 1;
  1902. cache_mask_width = __kmp_cpuid_mask_width(max_threads_sharing);
  1903. cache_level = __kmp_extract_bits<5, 7>(buf2.eax);
  1904. table[depth].level = cache_level;
  1905. table[depth].mask = ((-1) << cache_mask_width);
  1906. depth++;
  1907. level++;
  1908. }
  1909. }
  1910. };
  1911. // On IA-32 architecture and Intel(R) 64 architecture, we attempt to use
  1912. // an algorithm which cycles through the available os threads, setting
  1913. // the current thread's affinity mask to that thread, and then retrieves
  1914. // the Apic Id for each thread context using the cpuid instruction.
  1915. static bool __kmp_affinity_create_apicid_map(kmp_i18n_id_t *const msg_id) {
  1916. kmp_cpuid buf;
  1917. *msg_id = kmp_i18n_null;
  1918. if (__kmp_affinity_verbose) {
  1919. KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(DecodingLegacyAPIC));
  1920. }
  1921. // Check if cpuid leaf 4 is supported.
  1922. __kmp_x86_cpuid(0, 0, &buf);
  1923. if (buf.eax < 4) {
  1924. *msg_id = kmp_i18n_str_NoLeaf4Support;
  1925. return false;
  1926. }
  1927. // The algorithm used starts by setting the affinity to each available thread
  1928. // and retrieving info from the cpuid instruction, so if we are not capable of
  1929. // calling __kmp_get_system_affinity() and _kmp_get_system_affinity(), then we
  1930. // need to do something else - use the defaults that we calculated from
  1931. // issuing cpuid without binding to each proc.
  1932. if (!KMP_AFFINITY_CAPABLE()) {
  1933. // Hack to try and infer the machine topology using only the data
  1934. // available from cpuid on the current thread, and __kmp_xproc.
  1935. KMP_ASSERT(__kmp_affinity_type == affinity_none);
  1936. // Get an upper bound on the number of threads per package using cpuid(1).
  1937. // On some OS/chps combinations where HT is supported by the chip but is
  1938. // disabled, this value will be 2 on a single core chip. Usually, it will be
  1939. // 2 if HT is enabled and 1 if HT is disabled.
  1940. __kmp_x86_cpuid(1, 0, &buf);
  1941. int maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;
  1942. if (maxThreadsPerPkg == 0) {
  1943. maxThreadsPerPkg = 1;
  1944. }
  1945. // The num cores per pkg comes from cpuid(4). 1 must be added to the encoded
  1946. // value.
  1947. //
  1948. // The author of cpu_count.cpp treated this only an upper bound on the
  1949. // number of cores, but I haven't seen any cases where it was greater than
  1950. // the actual number of cores, so we will treat it as exact in this block of
  1951. // code.
  1952. //
  1953. // First, we need to check if cpuid(4) is supported on this chip. To see if
  1954. // cpuid(n) is supported, issue cpuid(0) and check if eax has the value n or
  1955. // greater.
  1956. __kmp_x86_cpuid(0, 0, &buf);
  1957. if (buf.eax >= 4) {
  1958. __kmp_x86_cpuid(4, 0, &buf);
  1959. nCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;
  1960. } else {
  1961. nCoresPerPkg = 1;
  1962. }
  1963. // There is no way to reliably tell if HT is enabled without issuing the
  1964. // cpuid instruction from every thread, can correlating the cpuid info, so
  1965. // if the machine is not affinity capable, we assume that HT is off. We have
  1966. // seen quite a few machines where maxThreadsPerPkg is 2, yet the machine
  1967. // does not support HT.
  1968. //
  1969. // - Older OSes are usually found on machines with older chips, which do not
  1970. // support HT.
  1971. // - The performance penalty for mistakenly identifying a machine as HT when
  1972. // it isn't (which results in blocktime being incorrectly set to 0) is
  1973. // greater than the penalty when for mistakenly identifying a machine as
  1974. // being 1 thread/core when it is really HT enabled (which results in
  1975. // blocktime being incorrectly set to a positive value).
  1976. __kmp_ncores = __kmp_xproc;
  1977. nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;
  1978. __kmp_nThreadsPerCore = 1;
  1979. return true;
  1980. }
  1981. // From here on, we can assume that it is safe to call
  1982. // __kmp_get_system_affinity() and __kmp_set_system_affinity(), even if
  1983. // __kmp_affinity_type = affinity_none.
  1984. // Save the affinity mask for the current thread.
  1985. kmp_affinity_raii_t previous_affinity;
  1986. // Run through each of the available contexts, binding the current thread
  1987. // to it, and obtaining the pertinent information using the cpuid instr.
  1988. //
  1989. // The relevant information is:
  1990. // - Apic Id: Bits 24:31 of ebx after issuing cpuid(1) - each thread context
  1991. // has a uniqie Apic Id, which is of the form pkg# : core# : thread#.
  1992. // - Max Threads Per Pkg: Bits 16:23 of ebx after issuing cpuid(1). The value
  1993. // of this field determines the width of the core# + thread# fields in the
  1994. // Apic Id. It is also an upper bound on the number of threads per
  1995. // package, but it has been verified that situations happen were it is not
  1996. // exact. In particular, on certain OS/chip combinations where Intel(R)
  1997. // Hyper-Threading Technology is supported by the chip but has been
  1998. // disabled, the value of this field will be 2 (for a single core chip).
  1999. // On other OS/chip combinations supporting Intel(R) Hyper-Threading
  2000. // Technology, the value of this field will be 1 when Intel(R)
  2001. // Hyper-Threading Technology is disabled and 2 when it is enabled.
  2002. // - Max Cores Per Pkg: Bits 26:31 of eax after issuing cpuid(4). The value
  2003. // of this field (+1) determines the width of the core# field in the Apic
  2004. // Id. The comments in "cpucount.cpp" say that this value is an upper
  2005. // bound, but the IA-32 architecture manual says that it is exactly the
  2006. // number of cores per package, and I haven't seen any case where it
  2007. // wasn't.
  2008. //
  2009. // From this information, deduce the package Id, core Id, and thread Id,
  2010. // and set the corresponding fields in the apicThreadInfo struct.
  2011. unsigned i;
  2012. apicThreadInfo *threadInfo = (apicThreadInfo *)__kmp_allocate(
  2013. __kmp_avail_proc * sizeof(apicThreadInfo));
  2014. unsigned nApics = 0;
  2015. KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
  2016. // Skip this proc if it is not included in the machine model.
  2017. if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
  2018. continue;
  2019. }
  2020. KMP_DEBUG_ASSERT((int)nApics < __kmp_avail_proc);
  2021. __kmp_affinity_dispatch->bind_thread(i);
  2022. threadInfo[nApics].osId = i;
  2023. // The apic id and max threads per pkg come from cpuid(1).
  2024. __kmp_x86_cpuid(1, 0, &buf);
  2025. if (((buf.edx >> 9) & 1) == 0) {
  2026. __kmp_free(threadInfo);
  2027. *msg_id = kmp_i18n_str_ApicNotPresent;
  2028. return false;
  2029. }
  2030. threadInfo[nApics].apicId = (buf.ebx >> 24) & 0xff;
  2031. threadInfo[nApics].maxThreadsPerPkg = (buf.ebx >> 16) & 0xff;
  2032. if (threadInfo[nApics].maxThreadsPerPkg == 0) {
  2033. threadInfo[nApics].maxThreadsPerPkg = 1;
  2034. }
  2035. // Max cores per pkg comes from cpuid(4). 1 must be added to the encoded
  2036. // value.
  2037. //
  2038. // First, we need to check if cpuid(4) is supported on this chip. To see if
  2039. // cpuid(n) is supported, issue cpuid(0) and check if eax has the value n
  2040. // or greater.
  2041. __kmp_x86_cpuid(0, 0, &buf);
  2042. if (buf.eax >= 4) {
  2043. __kmp_x86_cpuid(4, 0, &buf);
  2044. threadInfo[nApics].maxCoresPerPkg = ((buf.eax >> 26) & 0x3f) + 1;
  2045. } else {
  2046. threadInfo[nApics].maxCoresPerPkg = 1;
  2047. }
  2048. // Infer the pkgId / coreId / threadId using only the info obtained locally.
  2049. int widthCT = __kmp_cpuid_mask_width(threadInfo[nApics].maxThreadsPerPkg);
  2050. threadInfo[nApics].pkgId = threadInfo[nApics].apicId >> widthCT;
  2051. int widthC = __kmp_cpuid_mask_width(threadInfo[nApics].maxCoresPerPkg);
  2052. int widthT = widthCT - widthC;
  2053. if (widthT < 0) {
  2054. // I've never seen this one happen, but I suppose it could, if the cpuid
  2055. // instruction on a chip was really screwed up. Make sure to restore the
  2056. // affinity mask before the tail call.
  2057. __kmp_free(threadInfo);
  2058. *msg_id = kmp_i18n_str_InvalidCpuidInfo;
  2059. return false;
  2060. }
  2061. int maskC = (1 << widthC) - 1;
  2062. threadInfo[nApics].coreId = (threadInfo[nApics].apicId >> widthT) & maskC;
  2063. int maskT = (1 << widthT) - 1;
  2064. threadInfo[nApics].threadId = threadInfo[nApics].apicId & maskT;
  2065. nApics++;
  2066. }
  2067. // We've collected all the info we need.
  2068. // Restore the old affinity mask for this thread.
  2069. previous_affinity.restore();
  2070. // Sort the threadInfo table by physical Id.
  2071. qsort(threadInfo, nApics, sizeof(*threadInfo),
  2072. __kmp_affinity_cmp_apicThreadInfo_phys_id);
  2073. // The table is now sorted by pkgId / coreId / threadId, but we really don't
  2074. // know the radix of any of the fields. pkgId's may be sparsely assigned among
  2075. // the chips on a system. Although coreId's are usually assigned
  2076. // [0 .. coresPerPkg-1] and threadId's are usually assigned
  2077. // [0..threadsPerCore-1], we don't want to make any such assumptions.
  2078. //
  2079. // For that matter, we don't know what coresPerPkg and threadsPerCore (or the
  2080. // total # packages) are at this point - we want to determine that now. We
  2081. // only have an upper bound on the first two figures.
  2082. //
  2083. // We also perform a consistency check at this point: the values returned by
  2084. // the cpuid instruction for any thread bound to a given package had better
  2085. // return the same info for maxThreadsPerPkg and maxCoresPerPkg.
  2086. nPackages = 1;
  2087. nCoresPerPkg = 1;
  2088. __kmp_nThreadsPerCore = 1;
  2089. unsigned nCores = 1;
  2090. unsigned pkgCt = 1; // to determine radii
  2091. unsigned lastPkgId = threadInfo[0].pkgId;
  2092. unsigned coreCt = 1;
  2093. unsigned lastCoreId = threadInfo[0].coreId;
  2094. unsigned threadCt = 1;
  2095. unsigned lastThreadId = threadInfo[0].threadId;
  2096. // intra-pkg consist checks
  2097. unsigned prevMaxCoresPerPkg = threadInfo[0].maxCoresPerPkg;
  2098. unsigned prevMaxThreadsPerPkg = threadInfo[0].maxThreadsPerPkg;
  2099. for (i = 1; i < nApics; i++) {
  2100. if (threadInfo[i].pkgId != lastPkgId) {
  2101. nCores++;
  2102. pkgCt++;
  2103. lastPkgId = threadInfo[i].pkgId;
  2104. if ((int)coreCt > nCoresPerPkg)
  2105. nCoresPerPkg = coreCt;
  2106. coreCt = 1;
  2107. lastCoreId = threadInfo[i].coreId;
  2108. if ((int)threadCt > __kmp_nThreadsPerCore)
  2109. __kmp_nThreadsPerCore = threadCt;
  2110. threadCt = 1;
  2111. lastThreadId = threadInfo[i].threadId;
  2112. // This is a different package, so go on to the next iteration without
  2113. // doing any consistency checks. Reset the consistency check vars, though.
  2114. prevMaxCoresPerPkg = threadInfo[i].maxCoresPerPkg;
  2115. prevMaxThreadsPerPkg = threadInfo[i].maxThreadsPerPkg;
  2116. continue;
  2117. }
  2118. if (threadInfo[i].coreId != lastCoreId) {
  2119. nCores++;
  2120. coreCt++;
  2121. lastCoreId = threadInfo[i].coreId;
  2122. if ((int)threadCt > __kmp_nThreadsPerCore)
  2123. __kmp_nThreadsPerCore = threadCt;
  2124. threadCt = 1;
  2125. lastThreadId = threadInfo[i].threadId;
  2126. } else if (threadInfo[i].threadId != lastThreadId) {
  2127. threadCt++;
  2128. lastThreadId = threadInfo[i].threadId;
  2129. } else {
  2130. __kmp_free(threadInfo);
  2131. *msg_id = kmp_i18n_str_LegacyApicIDsNotUnique;
  2132. return false;
  2133. }
  2134. // Check to make certain that the maxCoresPerPkg and maxThreadsPerPkg
  2135. // fields agree between all the threads bounds to a given package.
  2136. if ((prevMaxCoresPerPkg != threadInfo[i].maxCoresPerPkg) ||
  2137. (prevMaxThreadsPerPkg != threadInfo[i].maxThreadsPerPkg)) {
  2138. __kmp_free(threadInfo);
  2139. *msg_id = kmp_i18n_str_InconsistentCpuidInfo;
  2140. return false;
  2141. }
  2142. }
  2143. // When affinity is off, this routine will still be called to set
  2144. // __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
  2145. // Make sure all these vars are set correctly
  2146. nPackages = pkgCt;
  2147. if ((int)coreCt > nCoresPerPkg)
  2148. nCoresPerPkg = coreCt;
  2149. if ((int)threadCt > __kmp_nThreadsPerCore)
  2150. __kmp_nThreadsPerCore = threadCt;
  2151. __kmp_ncores = nCores;
  2152. KMP_DEBUG_ASSERT(nApics == (unsigned)__kmp_avail_proc);
  2153. // Now that we've determined the number of packages, the number of cores per
  2154. // package, and the number of threads per core, we can construct the data
  2155. // structure that is to be returned.
  2156. int idx = 0;
  2157. int pkgLevel = 0;
  2158. int coreLevel = 1;
  2159. int threadLevel = 2;
  2160. //(__kmp_nThreadsPerCore <= 1) ? -1 : ((coreLevel >= 0) ? 2 : 1);
  2161. int depth = (pkgLevel >= 0) + (coreLevel >= 0) + (threadLevel >= 0);
  2162. kmp_hw_t types[3];
  2163. if (pkgLevel >= 0)
  2164. types[idx++] = KMP_HW_SOCKET;
  2165. if (coreLevel >= 0)
  2166. types[idx++] = KMP_HW_CORE;
  2167. if (threadLevel >= 0)
  2168. types[idx++] = KMP_HW_THREAD;
  2169. KMP_ASSERT(depth > 0);
  2170. __kmp_topology = kmp_topology_t::allocate(nApics, depth, types);
  2171. for (i = 0; i < nApics; ++i) {
  2172. idx = 0;
  2173. unsigned os = threadInfo[i].osId;
  2174. kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
  2175. hw_thread.clear();
  2176. if (pkgLevel >= 0) {
  2177. hw_thread.ids[idx++] = threadInfo[i].pkgId;
  2178. }
  2179. if (coreLevel >= 0) {
  2180. hw_thread.ids[idx++] = threadInfo[i].coreId;
  2181. }
  2182. if (threadLevel >= 0) {
  2183. hw_thread.ids[idx++] = threadInfo[i].threadId;
  2184. }
  2185. hw_thread.os_id = os;
  2186. }
  2187. __kmp_free(threadInfo);
  2188. __kmp_topology->sort_ids();
  2189. if (!__kmp_topology->check_ids()) {
  2190. kmp_topology_t::deallocate(__kmp_topology);
  2191. __kmp_topology = nullptr;
  2192. *msg_id = kmp_i18n_str_LegacyApicIDsNotUnique;
  2193. return false;
  2194. }
  2195. return true;
  2196. }
  2197. // Hybrid cpu detection using CPUID.1A
  2198. // Thread should be pinned to processor already
  2199. static void __kmp_get_hybrid_info(kmp_hw_core_type_t *type, int *efficiency,
  2200. unsigned *native_model_id) {
  2201. kmp_cpuid buf;
  2202. __kmp_x86_cpuid(0x1a, 0, &buf);
  2203. *type = (kmp_hw_core_type_t)__kmp_extract_bits<24, 31>(buf.eax);
  2204. switch (*type) {
  2205. case KMP_HW_CORE_TYPE_ATOM:
  2206. *efficiency = 0;
  2207. break;
  2208. case KMP_HW_CORE_TYPE_CORE:
  2209. *efficiency = 1;
  2210. break;
  2211. default:
  2212. *efficiency = 0;
  2213. }
  2214. *native_model_id = __kmp_extract_bits<0, 23>(buf.eax);
  2215. }
  2216. // Intel(R) microarchitecture code name Nehalem, Dunnington and later
  2217. // architectures support a newer interface for specifying the x2APIC Ids,
  2218. // based on CPUID.B or CPUID.1F
  2219. /*
  2220. * CPUID.B or 1F, Input ECX (sub leaf # aka level number)
  2221. Bits Bits Bits Bits
  2222. 31-16 15-8 7-4 4-0
  2223. ---+-----------+--------------+-------------+-----------------+
  2224. EAX| reserved | reserved | reserved | Bits to Shift |
  2225. ---+-----------|--------------+-------------+-----------------|
  2226. EBX| reserved | Num logical processors at level (16 bits) |
  2227. ---+-----------|--------------+-------------------------------|
  2228. ECX| reserved | Level Type | Level Number (8 bits) |
  2229. ---+-----------+--------------+-------------------------------|
  2230. EDX| X2APIC ID (32 bits) |
  2231. ---+----------------------------------------------------------+
  2232. */
  2233. enum {
  2234. INTEL_LEVEL_TYPE_INVALID = 0, // Package level
  2235. INTEL_LEVEL_TYPE_SMT = 1,
  2236. INTEL_LEVEL_TYPE_CORE = 2,
  2237. INTEL_LEVEL_TYPE_TILE = 3,
  2238. INTEL_LEVEL_TYPE_MODULE = 4,
  2239. INTEL_LEVEL_TYPE_DIE = 5,
  2240. INTEL_LEVEL_TYPE_LAST = 6,
  2241. };
  2242. struct cpuid_level_info_t {
  2243. unsigned level_type, mask, mask_width, nitems, cache_mask;
  2244. };
  2245. static kmp_hw_t __kmp_intel_type_2_topology_type(int intel_type) {
  2246. switch (intel_type) {
  2247. case INTEL_LEVEL_TYPE_INVALID:
  2248. return KMP_HW_SOCKET;
  2249. case INTEL_LEVEL_TYPE_SMT:
  2250. return KMP_HW_THREAD;
  2251. case INTEL_LEVEL_TYPE_CORE:
  2252. return KMP_HW_CORE;
  2253. case INTEL_LEVEL_TYPE_TILE:
  2254. return KMP_HW_TILE;
  2255. case INTEL_LEVEL_TYPE_MODULE:
  2256. return KMP_HW_MODULE;
  2257. case INTEL_LEVEL_TYPE_DIE:
  2258. return KMP_HW_DIE;
  2259. }
  2260. return KMP_HW_UNKNOWN;
  2261. }
  2262. // This function takes the topology leaf, a levels array to store the levels
  2263. // detected and a bitmap of the known levels.
  2264. // Returns the number of levels in the topology
  2265. static unsigned
  2266. __kmp_x2apicid_get_levels(int leaf,
  2267. cpuid_level_info_t levels[INTEL_LEVEL_TYPE_LAST],
  2268. kmp_uint64 known_levels) {
  2269. unsigned level, levels_index;
  2270. unsigned level_type, mask_width, nitems;
  2271. kmp_cpuid buf;
  2272. // New algorithm has known topology layers act as highest unknown topology
  2273. // layers when unknown topology layers exist.
  2274. // e.g., Suppose layers were SMT <X> CORE <Y> <Z> PACKAGE, where <X> <Y> <Z>
  2275. // are unknown topology layers, Then SMT will take the characteristics of
  2276. // (SMT x <X>) and CORE will take the characteristics of (CORE x <Y> x <Z>).
  2277. // This eliminates unknown portions of the topology while still keeping the
  2278. // correct structure.
  2279. level = levels_index = 0;
  2280. do {
  2281. __kmp_x86_cpuid(leaf, level, &buf);
  2282. level_type = __kmp_extract_bits<8, 15>(buf.ecx);
  2283. mask_width = __kmp_extract_bits<0, 4>(buf.eax);
  2284. nitems = __kmp_extract_bits<0, 15>(buf.ebx);
  2285. if (level_type != INTEL_LEVEL_TYPE_INVALID && nitems == 0)
  2286. return 0;
  2287. if (known_levels & (1ull << level_type)) {
  2288. // Add a new level to the topology
  2289. KMP_ASSERT(levels_index < INTEL_LEVEL_TYPE_LAST);
  2290. levels[levels_index].level_type = level_type;
  2291. levels[levels_index].mask_width = mask_width;
  2292. levels[levels_index].nitems = nitems;
  2293. levels_index++;
  2294. } else {
  2295. // If it is an unknown level, then logically move the previous layer up
  2296. if (levels_index > 0) {
  2297. levels[levels_index - 1].mask_width = mask_width;
  2298. levels[levels_index - 1].nitems = nitems;
  2299. }
  2300. }
  2301. level++;
  2302. } while (level_type != INTEL_LEVEL_TYPE_INVALID);
  2303. // Set the masks to & with apicid
  2304. for (unsigned i = 0; i < levels_index; ++i) {
  2305. if (levels[i].level_type != INTEL_LEVEL_TYPE_INVALID) {
  2306. levels[i].mask = ~((-1) << levels[i].mask_width);
  2307. levels[i].cache_mask = (-1) << levels[i].mask_width;
  2308. for (unsigned j = 0; j < i; ++j)
  2309. levels[i].mask ^= levels[j].mask;
  2310. } else {
  2311. KMP_DEBUG_ASSERT(levels_index > 0);
  2312. levels[i].mask = (-1) << levels[i - 1].mask_width;
  2313. levels[i].cache_mask = 0;
  2314. }
  2315. }
  2316. return levels_index;
  2317. }
  2318. static bool __kmp_affinity_create_x2apicid_map(kmp_i18n_id_t *const msg_id) {
  2319. cpuid_level_info_t levels[INTEL_LEVEL_TYPE_LAST];
  2320. kmp_hw_t types[INTEL_LEVEL_TYPE_LAST];
  2321. unsigned levels_index;
  2322. kmp_cpuid buf;
  2323. kmp_uint64 known_levels;
  2324. int topology_leaf, highest_leaf, apic_id;
  2325. int num_leaves;
  2326. static int leaves[] = {0, 0};
  2327. kmp_i18n_id_t leaf_message_id;
  2328. KMP_BUILD_ASSERT(sizeof(known_levels) * CHAR_BIT > KMP_HW_LAST);
  2329. *msg_id = kmp_i18n_null;
  2330. if (__kmp_affinity_verbose) {
  2331. KMP_INFORM(AffInfoStr, "KMP_AFFINITY", KMP_I18N_STR(Decodingx2APIC));
  2332. }
  2333. // Figure out the known topology levels
  2334. known_levels = 0ull;
  2335. for (int i = 0; i < INTEL_LEVEL_TYPE_LAST; ++i) {
  2336. if (__kmp_intel_type_2_topology_type(i) != KMP_HW_UNKNOWN) {
  2337. known_levels |= (1ull << i);
  2338. }
  2339. }
  2340. // Get the highest cpuid leaf supported
  2341. __kmp_x86_cpuid(0, 0, &buf);
  2342. highest_leaf = buf.eax;
  2343. // If a specific topology method was requested, only allow that specific leaf
  2344. // otherwise, try both leaves 31 and 11 in that order
  2345. num_leaves = 0;
  2346. if (__kmp_affinity_top_method == affinity_top_method_x2apicid) {
  2347. num_leaves = 1;
  2348. leaves[0] = 11;
  2349. leaf_message_id = kmp_i18n_str_NoLeaf11Support;
  2350. } else if (__kmp_affinity_top_method == affinity_top_method_x2apicid_1f) {
  2351. num_leaves = 1;
  2352. leaves[0] = 31;
  2353. leaf_message_id = kmp_i18n_str_NoLeaf31Support;
  2354. } else {
  2355. num_leaves = 2;
  2356. leaves[0] = 31;
  2357. leaves[1] = 11;
  2358. leaf_message_id = kmp_i18n_str_NoLeaf11Support;
  2359. }
  2360. // Check to see if cpuid leaf 31 or 11 is supported.
  2361. __kmp_nThreadsPerCore = nCoresPerPkg = nPackages = 1;
  2362. topology_leaf = -1;
  2363. for (int i = 0; i < num_leaves; ++i) {
  2364. int leaf = leaves[i];
  2365. if (highest_leaf < leaf)
  2366. continue;
  2367. __kmp_x86_cpuid(leaf, 0, &buf);
  2368. if (buf.ebx == 0)
  2369. continue;
  2370. topology_leaf = leaf;
  2371. levels_index = __kmp_x2apicid_get_levels(leaf, levels, known_levels);
  2372. if (levels_index == 0)
  2373. continue;
  2374. break;
  2375. }
  2376. if (topology_leaf == -1 || levels_index == 0) {
  2377. *msg_id = leaf_message_id;
  2378. return false;
  2379. }
  2380. KMP_ASSERT(levels_index <= INTEL_LEVEL_TYPE_LAST);
  2381. // The algorithm used starts by setting the affinity to each available thread
  2382. // and retrieving info from the cpuid instruction, so if we are not capable of
  2383. // calling __kmp_get_system_affinity() and __kmp_get_system_affinity(), then
  2384. // we need to do something else - use the defaults that we calculated from
  2385. // issuing cpuid without binding to each proc.
  2386. if (!KMP_AFFINITY_CAPABLE()) {
  2387. // Hack to try and infer the machine topology using only the data
  2388. // available from cpuid on the current thread, and __kmp_xproc.
  2389. KMP_ASSERT(__kmp_affinity_type == affinity_none);
  2390. for (unsigned i = 0; i < levels_index; ++i) {
  2391. if (levels[i].level_type == INTEL_LEVEL_TYPE_SMT) {
  2392. __kmp_nThreadsPerCore = levels[i].nitems;
  2393. } else if (levels[i].level_type == INTEL_LEVEL_TYPE_CORE) {
  2394. nCoresPerPkg = levels[i].nitems;
  2395. }
  2396. }
  2397. __kmp_ncores = __kmp_xproc / __kmp_nThreadsPerCore;
  2398. nPackages = (__kmp_xproc + nCoresPerPkg - 1) / nCoresPerPkg;
  2399. return true;
  2400. }
  2401. // Allocate the data structure to be returned.
  2402. int depth = levels_index;
  2403. for (int i = depth - 1, j = 0; i >= 0; --i, ++j)
  2404. types[j] = __kmp_intel_type_2_topology_type(levels[i].level_type);
  2405. __kmp_topology =
  2406. kmp_topology_t::allocate(__kmp_avail_proc, levels_index, types);
  2407. // Insert equivalent cache types if they exist
  2408. kmp_cache_info_t cache_info;
  2409. for (size_t i = 0; i < cache_info.get_depth(); ++i) {
  2410. const kmp_cache_info_t::info_t &info = cache_info[i];
  2411. unsigned cache_mask = info.mask;
  2412. unsigned cache_level = info.level;
  2413. for (unsigned j = 0; j < levels_index; ++j) {
  2414. unsigned hw_cache_mask = levels[j].cache_mask;
  2415. kmp_hw_t cache_type = kmp_cache_info_t::get_topology_type(cache_level);
  2416. if (hw_cache_mask == cache_mask && j < levels_index - 1) {
  2417. kmp_hw_t type =
  2418. __kmp_intel_type_2_topology_type(levels[j + 1].level_type);
  2419. __kmp_topology->set_equivalent_type(cache_type, type);
  2420. }
  2421. }
  2422. }
  2423. // From here on, we can assume that it is safe to call
  2424. // __kmp_get_system_affinity() and __kmp_set_system_affinity(), even if
  2425. // __kmp_affinity_type = affinity_none.
  2426. // Save the affinity mask for the current thread.
  2427. kmp_affinity_raii_t previous_affinity;
  2428. // Run through each of the available contexts, binding the current thread
  2429. // to it, and obtaining the pertinent information using the cpuid instr.
  2430. unsigned int proc;
  2431. int hw_thread_index = 0;
  2432. KMP_CPU_SET_ITERATE(proc, __kmp_affin_fullMask) {
  2433. cpuid_level_info_t my_levels[INTEL_LEVEL_TYPE_LAST];
  2434. unsigned my_levels_index;
  2435. // Skip this proc if it is not included in the machine model.
  2436. if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
  2437. continue;
  2438. }
  2439. KMP_DEBUG_ASSERT(hw_thread_index < __kmp_avail_proc);
  2440. __kmp_affinity_dispatch->bind_thread(proc);
  2441. // New algorithm
  2442. __kmp_x86_cpuid(topology_leaf, 0, &buf);
  2443. apic_id = buf.edx;
  2444. kmp_hw_thread_t &hw_thread = __kmp_topology->at(hw_thread_index);
  2445. my_levels_index =
  2446. __kmp_x2apicid_get_levels(topology_leaf, my_levels, known_levels);
  2447. if (my_levels_index == 0 || my_levels_index != levels_index) {
  2448. *msg_id = kmp_i18n_str_InvalidCpuidInfo;
  2449. return false;
  2450. }
  2451. hw_thread.clear();
  2452. hw_thread.os_id = proc;
  2453. // Put in topology information
  2454. for (unsigned j = 0, idx = depth - 1; j < my_levels_index; ++j, --idx) {
  2455. hw_thread.ids[idx] = apic_id & my_levels[j].mask;
  2456. if (j > 0) {
  2457. hw_thread.ids[idx] >>= my_levels[j - 1].mask_width;
  2458. }
  2459. }
  2460. // Hybrid information
  2461. if (__kmp_is_hybrid_cpu() && highest_leaf >= 0x1a) {
  2462. kmp_hw_core_type_t type;
  2463. unsigned native_model_id;
  2464. int efficiency;
  2465. __kmp_get_hybrid_info(&type, &efficiency, &native_model_id);
  2466. hw_thread.attrs.set_core_type(type);
  2467. hw_thread.attrs.set_core_eff(efficiency);
  2468. }
  2469. hw_thread_index++;
  2470. }
  2471. KMP_ASSERT(hw_thread_index > 0);
  2472. __kmp_topology->sort_ids();
  2473. if (!__kmp_topology->check_ids()) {
  2474. kmp_topology_t::deallocate(__kmp_topology);
  2475. __kmp_topology = nullptr;
  2476. *msg_id = kmp_i18n_str_x2ApicIDsNotUnique;
  2477. return false;
  2478. }
  2479. return true;
  2480. }
  2481. #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
  2482. #define osIdIndex 0
  2483. #define threadIdIndex 1
  2484. #define coreIdIndex 2
  2485. #define pkgIdIndex 3
  2486. #define nodeIdIndex 4
  2487. typedef unsigned *ProcCpuInfo;
  2488. static unsigned maxIndex = pkgIdIndex;
  2489. static int __kmp_affinity_cmp_ProcCpuInfo_phys_id(const void *a,
  2490. const void *b) {
  2491. unsigned i;
  2492. const unsigned *aa = *(unsigned *const *)a;
  2493. const unsigned *bb = *(unsigned *const *)b;
  2494. for (i = maxIndex;; i--) {
  2495. if (aa[i] < bb[i])
  2496. return -1;
  2497. if (aa[i] > bb[i])
  2498. return 1;
  2499. if (i == osIdIndex)
  2500. break;
  2501. }
  2502. return 0;
  2503. }
  2504. #if KMP_USE_HIER_SCHED
  2505. // Set the array sizes for the hierarchy layers
  2506. static void __kmp_dispatch_set_hierarchy_values() {
  2507. // Set the maximum number of L1's to number of cores
  2508. // Set the maximum number of L2's to to either number of cores / 2 for
  2509. // Intel(R) Xeon Phi(TM) coprocessor formally codenamed Knights Landing
  2510. // Or the number of cores for Intel(R) Xeon(R) processors
  2511. // Set the maximum number of NUMA nodes and L3's to number of packages
  2512. __kmp_hier_max_units[kmp_hier_layer_e::LAYER_THREAD + 1] =
  2513. nPackages * nCoresPerPkg * __kmp_nThreadsPerCore;
  2514. __kmp_hier_max_units[kmp_hier_layer_e::LAYER_L1 + 1] = __kmp_ncores;
  2515. #if KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_WINDOWS) && \
  2516. KMP_MIC_SUPPORTED
  2517. if (__kmp_mic_type >= mic3)
  2518. __kmp_hier_max_units[kmp_hier_layer_e::LAYER_L2 + 1] = __kmp_ncores / 2;
  2519. else
  2520. #endif // KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_WINDOWS)
  2521. __kmp_hier_max_units[kmp_hier_layer_e::LAYER_L2 + 1] = __kmp_ncores;
  2522. __kmp_hier_max_units[kmp_hier_layer_e::LAYER_L3 + 1] = nPackages;
  2523. __kmp_hier_max_units[kmp_hier_layer_e::LAYER_NUMA + 1] = nPackages;
  2524. __kmp_hier_max_units[kmp_hier_layer_e::LAYER_LOOP + 1] = 1;
  2525. // Set the number of threads per unit
  2526. // Number of hardware threads per L1/L2/L3/NUMA/LOOP
  2527. __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_THREAD + 1] = 1;
  2528. __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L1 + 1] =
  2529. __kmp_nThreadsPerCore;
  2530. #if KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_WINDOWS) && \
  2531. KMP_MIC_SUPPORTED
  2532. if (__kmp_mic_type >= mic3)
  2533. __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L2 + 1] =
  2534. 2 * __kmp_nThreadsPerCore;
  2535. else
  2536. #endif // KMP_ARCH_X86_64 && (KMP_OS_LINUX || KMP_OS_WINDOWS)
  2537. __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L2 + 1] =
  2538. __kmp_nThreadsPerCore;
  2539. __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_L3 + 1] =
  2540. nCoresPerPkg * __kmp_nThreadsPerCore;
  2541. __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_NUMA + 1] =
  2542. nCoresPerPkg * __kmp_nThreadsPerCore;
  2543. __kmp_hier_threads_per[kmp_hier_layer_e::LAYER_LOOP + 1] =
  2544. nPackages * nCoresPerPkg * __kmp_nThreadsPerCore;
  2545. }
  2546. // Return the index into the hierarchy for this tid and layer type (L1, L2, etc)
  2547. // i.e., this thread's L1 or this thread's L2, etc.
  2548. int __kmp_dispatch_get_index(int tid, kmp_hier_layer_e type) {
  2549. int index = type + 1;
  2550. int num_hw_threads = __kmp_hier_max_units[kmp_hier_layer_e::LAYER_THREAD + 1];
  2551. KMP_DEBUG_ASSERT(type != kmp_hier_layer_e::LAYER_LAST);
  2552. if (type == kmp_hier_layer_e::LAYER_THREAD)
  2553. return tid;
  2554. else if (type == kmp_hier_layer_e::LAYER_LOOP)
  2555. return 0;
  2556. KMP_DEBUG_ASSERT(__kmp_hier_max_units[index] != 0);
  2557. if (tid >= num_hw_threads)
  2558. tid = tid % num_hw_threads;
  2559. return (tid / __kmp_hier_threads_per[index]) % __kmp_hier_max_units[index];
  2560. }
  2561. // Return the number of t1's per t2
  2562. int __kmp_dispatch_get_t1_per_t2(kmp_hier_layer_e t1, kmp_hier_layer_e t2) {
  2563. int i1 = t1 + 1;
  2564. int i2 = t2 + 1;
  2565. KMP_DEBUG_ASSERT(i1 <= i2);
  2566. KMP_DEBUG_ASSERT(t1 != kmp_hier_layer_e::LAYER_LAST);
  2567. KMP_DEBUG_ASSERT(t2 != kmp_hier_layer_e::LAYER_LAST);
  2568. KMP_DEBUG_ASSERT(__kmp_hier_threads_per[i1] != 0);
  2569. // (nthreads/t2) / (nthreads/t1) = t1 / t2
  2570. return __kmp_hier_threads_per[i2] / __kmp_hier_threads_per[i1];
  2571. }
  2572. #endif // KMP_USE_HIER_SCHED
  2573. static inline const char *__kmp_cpuinfo_get_filename() {
  2574. const char *filename;
  2575. if (__kmp_cpuinfo_file != nullptr)
  2576. filename = __kmp_cpuinfo_file;
  2577. else
  2578. filename = "/proc/cpuinfo";
  2579. return filename;
  2580. }
  2581. static inline const char *__kmp_cpuinfo_get_envvar() {
  2582. const char *envvar = nullptr;
  2583. if (__kmp_cpuinfo_file != nullptr)
  2584. envvar = "KMP_CPUINFO_FILE";
  2585. return envvar;
  2586. }
  2587. // Parse /proc/cpuinfo (or an alternate file in the same format) to obtain the
  2588. // affinity map.
  2589. static bool __kmp_affinity_create_cpuinfo_map(int *line,
  2590. kmp_i18n_id_t *const msg_id) {
  2591. const char *filename = __kmp_cpuinfo_get_filename();
  2592. const char *envvar = __kmp_cpuinfo_get_envvar();
  2593. *msg_id = kmp_i18n_null;
  2594. if (__kmp_affinity_verbose) {
  2595. KMP_INFORM(AffParseFilename, "KMP_AFFINITY", filename);
  2596. }
  2597. kmp_safe_raii_file_t f(filename, "r", envvar);
  2598. // Scan of the file, and count the number of "processor" (osId) fields,
  2599. // and find the highest value of <n> for a node_<n> field.
  2600. char buf[256];
  2601. unsigned num_records = 0;
  2602. while (!feof(f)) {
  2603. buf[sizeof(buf) - 1] = 1;
  2604. if (!fgets(buf, sizeof(buf), f)) {
  2605. // Read errors presumably because of EOF
  2606. break;
  2607. }
  2608. char s1[] = "processor";
  2609. if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {
  2610. num_records++;
  2611. continue;
  2612. }
  2613. // FIXME - this will match "node_<n> <garbage>"
  2614. unsigned level;
  2615. if (KMP_SSCANF(buf, "node_%u id", &level) == 1) {
  2616. // validate the input fisrt:
  2617. if (level > (unsigned)__kmp_xproc) { // level is too big
  2618. level = __kmp_xproc;
  2619. }
  2620. if (nodeIdIndex + level >= maxIndex) {
  2621. maxIndex = nodeIdIndex + level;
  2622. }
  2623. continue;
  2624. }
  2625. }
  2626. // Check for empty file / no valid processor records, or too many. The number
  2627. // of records can't exceed the number of valid bits in the affinity mask.
  2628. if (num_records == 0) {
  2629. *msg_id = kmp_i18n_str_NoProcRecords;
  2630. return false;
  2631. }
  2632. if (num_records > (unsigned)__kmp_xproc) {
  2633. *msg_id = kmp_i18n_str_TooManyProcRecords;
  2634. return false;
  2635. }
  2636. // Set the file pointer back to the beginning, so that we can scan the file
  2637. // again, this time performing a full parse of the data. Allocate a vector of
  2638. // ProcCpuInfo object, where we will place the data. Adding an extra element
  2639. // at the end allows us to remove a lot of extra checks for termination
  2640. // conditions.
  2641. if (fseek(f, 0, SEEK_SET) != 0) {
  2642. *msg_id = kmp_i18n_str_CantRewindCpuinfo;
  2643. return false;
  2644. }
  2645. // Allocate the array of records to store the proc info in. The dummy
  2646. // element at the end makes the logic in filling them out easier to code.
  2647. unsigned **threadInfo =
  2648. (unsigned **)__kmp_allocate((num_records + 1) * sizeof(unsigned *));
  2649. unsigned i;
  2650. for (i = 0; i <= num_records; i++) {
  2651. threadInfo[i] =
  2652. (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
  2653. }
  2654. #define CLEANUP_THREAD_INFO \
  2655. for (i = 0; i <= num_records; i++) { \
  2656. __kmp_free(threadInfo[i]); \
  2657. } \
  2658. __kmp_free(threadInfo);
  2659. // A value of UINT_MAX means that we didn't find the field
  2660. unsigned __index;
  2661. #define INIT_PROC_INFO(p) \
  2662. for (__index = 0; __index <= maxIndex; __index++) { \
  2663. (p)[__index] = UINT_MAX; \
  2664. }
  2665. for (i = 0; i <= num_records; i++) {
  2666. INIT_PROC_INFO(threadInfo[i]);
  2667. }
  2668. unsigned num_avail = 0;
  2669. *line = 0;
  2670. while (!feof(f)) {
  2671. // Create an inner scoping level, so that all the goto targets at the end of
  2672. // the loop appear in an outer scoping level. This avoids warnings about
  2673. // jumping past an initialization to a target in the same block.
  2674. {
  2675. buf[sizeof(buf) - 1] = 1;
  2676. bool long_line = false;
  2677. if (!fgets(buf, sizeof(buf), f)) {
  2678. // Read errors presumably because of EOF
  2679. // If there is valid data in threadInfo[num_avail], then fake
  2680. // a blank line in ensure that the last address gets parsed.
  2681. bool valid = false;
  2682. for (i = 0; i <= maxIndex; i++) {
  2683. if (threadInfo[num_avail][i] != UINT_MAX) {
  2684. valid = true;
  2685. }
  2686. }
  2687. if (!valid) {
  2688. break;
  2689. }
  2690. buf[0] = 0;
  2691. } else if (!buf[sizeof(buf) - 1]) {
  2692. // The line is longer than the buffer. Set a flag and don't
  2693. // emit an error if we were going to ignore the line, anyway.
  2694. long_line = true;
  2695. #define CHECK_LINE \
  2696. if (long_line) { \
  2697. CLEANUP_THREAD_INFO; \
  2698. *msg_id = kmp_i18n_str_LongLineCpuinfo; \
  2699. return false; \
  2700. }
  2701. }
  2702. (*line)++;
  2703. char s1[] = "processor";
  2704. if (strncmp(buf, s1, sizeof(s1) - 1) == 0) {
  2705. CHECK_LINE;
  2706. char *p = strchr(buf + sizeof(s1) - 1, ':');
  2707. unsigned val;
  2708. if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
  2709. goto no_val;
  2710. if (threadInfo[num_avail][osIdIndex] != UINT_MAX)
  2711. #if KMP_ARCH_AARCH64
  2712. // Handle the old AArch64 /proc/cpuinfo layout differently,
  2713. // it contains all of the 'processor' entries listed in a
  2714. // single 'Processor' section, therefore the normal looking
  2715. // for duplicates in that section will always fail.
  2716. num_avail++;
  2717. #else
  2718. goto dup_field;
  2719. #endif
  2720. threadInfo[num_avail][osIdIndex] = val;
  2721. #if KMP_OS_LINUX && !(KMP_ARCH_X86 || KMP_ARCH_X86_64)
  2722. char path[256];
  2723. KMP_SNPRINTF(
  2724. path, sizeof(path),
  2725. "/sys/devices/system/cpu/cpu%u/topology/physical_package_id",
  2726. threadInfo[num_avail][osIdIndex]);
  2727. __kmp_read_from_file(path, "%u", &threadInfo[num_avail][pkgIdIndex]);
  2728. KMP_SNPRINTF(path, sizeof(path),
  2729. "/sys/devices/system/cpu/cpu%u/topology/core_id",
  2730. threadInfo[num_avail][osIdIndex]);
  2731. __kmp_read_from_file(path, "%u", &threadInfo[num_avail][coreIdIndex]);
  2732. continue;
  2733. #else
  2734. }
  2735. char s2[] = "physical id";
  2736. if (strncmp(buf, s2, sizeof(s2) - 1) == 0) {
  2737. CHECK_LINE;
  2738. char *p = strchr(buf + sizeof(s2) - 1, ':');
  2739. unsigned val;
  2740. if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
  2741. goto no_val;
  2742. if (threadInfo[num_avail][pkgIdIndex] != UINT_MAX)
  2743. goto dup_field;
  2744. threadInfo[num_avail][pkgIdIndex] = val;
  2745. continue;
  2746. }
  2747. char s3[] = "core id";
  2748. if (strncmp(buf, s3, sizeof(s3) - 1) == 0) {
  2749. CHECK_LINE;
  2750. char *p = strchr(buf + sizeof(s3) - 1, ':');
  2751. unsigned val;
  2752. if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
  2753. goto no_val;
  2754. if (threadInfo[num_avail][coreIdIndex] != UINT_MAX)
  2755. goto dup_field;
  2756. threadInfo[num_avail][coreIdIndex] = val;
  2757. continue;
  2758. #endif // KMP_OS_LINUX && USE_SYSFS_INFO
  2759. }
  2760. char s4[] = "thread id";
  2761. if (strncmp(buf, s4, sizeof(s4) - 1) == 0) {
  2762. CHECK_LINE;
  2763. char *p = strchr(buf + sizeof(s4) - 1, ':');
  2764. unsigned val;
  2765. if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
  2766. goto no_val;
  2767. if (threadInfo[num_avail][threadIdIndex] != UINT_MAX)
  2768. goto dup_field;
  2769. threadInfo[num_avail][threadIdIndex] = val;
  2770. continue;
  2771. }
  2772. unsigned level;
  2773. if (KMP_SSCANF(buf, "node_%u id", &level) == 1) {
  2774. CHECK_LINE;
  2775. char *p = strchr(buf + sizeof(s4) - 1, ':');
  2776. unsigned val;
  2777. if ((p == NULL) || (KMP_SSCANF(p + 1, "%u\n", &val) != 1))
  2778. goto no_val;
  2779. // validate the input before using level:
  2780. if (level > (unsigned)__kmp_xproc) { // level is too big
  2781. level = __kmp_xproc;
  2782. }
  2783. if (threadInfo[num_avail][nodeIdIndex + level] != UINT_MAX)
  2784. goto dup_field;
  2785. threadInfo[num_avail][nodeIdIndex + level] = val;
  2786. continue;
  2787. }
  2788. // We didn't recognize the leading token on the line. There are lots of
  2789. // leading tokens that we don't recognize - if the line isn't empty, go on
  2790. // to the next line.
  2791. if ((*buf != 0) && (*buf != '\n')) {
  2792. // If the line is longer than the buffer, read characters
  2793. // until we find a newline.
  2794. if (long_line) {
  2795. int ch;
  2796. while (((ch = fgetc(f)) != EOF) && (ch != '\n'))
  2797. ;
  2798. }
  2799. continue;
  2800. }
  2801. // A newline has signalled the end of the processor record.
  2802. // Check that there aren't too many procs specified.
  2803. if ((int)num_avail == __kmp_xproc) {
  2804. CLEANUP_THREAD_INFO;
  2805. *msg_id = kmp_i18n_str_TooManyEntries;
  2806. return false;
  2807. }
  2808. // Check for missing fields. The osId field must be there, and we
  2809. // currently require that the physical id field is specified, also.
  2810. if (threadInfo[num_avail][osIdIndex] == UINT_MAX) {
  2811. CLEANUP_THREAD_INFO;
  2812. *msg_id = kmp_i18n_str_MissingProcField;
  2813. return false;
  2814. }
  2815. if (threadInfo[0][pkgIdIndex] == UINT_MAX) {
  2816. CLEANUP_THREAD_INFO;
  2817. *msg_id = kmp_i18n_str_MissingPhysicalIDField;
  2818. return false;
  2819. }
  2820. // Skip this proc if it is not included in the machine model.
  2821. if (!KMP_CPU_ISSET(threadInfo[num_avail][osIdIndex],
  2822. __kmp_affin_fullMask)) {
  2823. INIT_PROC_INFO(threadInfo[num_avail]);
  2824. continue;
  2825. }
  2826. // We have a successful parse of this proc's info.
  2827. // Increment the counter, and prepare for the next proc.
  2828. num_avail++;
  2829. KMP_ASSERT(num_avail <= num_records);
  2830. INIT_PROC_INFO(threadInfo[num_avail]);
  2831. }
  2832. continue;
  2833. no_val:
  2834. CLEANUP_THREAD_INFO;
  2835. *msg_id = kmp_i18n_str_MissingValCpuinfo;
  2836. return false;
  2837. dup_field:
  2838. CLEANUP_THREAD_INFO;
  2839. *msg_id = kmp_i18n_str_DuplicateFieldCpuinfo;
  2840. return false;
  2841. }
  2842. *line = 0;
  2843. #if KMP_MIC && REDUCE_TEAM_SIZE
  2844. unsigned teamSize = 0;
  2845. #endif // KMP_MIC && REDUCE_TEAM_SIZE
  2846. // check for num_records == __kmp_xproc ???
  2847. // If it is configured to omit the package level when there is only a single
  2848. // package, the logic at the end of this routine won't work if there is only a
  2849. // single thread
  2850. KMP_ASSERT(num_avail > 0);
  2851. KMP_ASSERT(num_avail <= num_records);
  2852. // Sort the threadInfo table by physical Id.
  2853. qsort(threadInfo, num_avail, sizeof(*threadInfo),
  2854. __kmp_affinity_cmp_ProcCpuInfo_phys_id);
  2855. // The table is now sorted by pkgId / coreId / threadId, but we really don't
  2856. // know the radix of any of the fields. pkgId's may be sparsely assigned among
  2857. // the chips on a system. Although coreId's are usually assigned
  2858. // [0 .. coresPerPkg-1] and threadId's are usually assigned
  2859. // [0..threadsPerCore-1], we don't want to make any such assumptions.
  2860. //
  2861. // For that matter, we don't know what coresPerPkg and threadsPerCore (or the
  2862. // total # packages) are at this point - we want to determine that now. We
  2863. // only have an upper bound on the first two figures.
  2864. unsigned *counts =
  2865. (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
  2866. unsigned *maxCt =
  2867. (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
  2868. unsigned *totals =
  2869. (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
  2870. unsigned *lastId =
  2871. (unsigned *)__kmp_allocate((maxIndex + 1) * sizeof(unsigned));
  2872. bool assign_thread_ids = false;
  2873. unsigned threadIdCt;
  2874. unsigned index;
  2875. restart_radix_check:
  2876. threadIdCt = 0;
  2877. // Initialize the counter arrays with data from threadInfo[0].
  2878. if (assign_thread_ids) {
  2879. if (threadInfo[0][threadIdIndex] == UINT_MAX) {
  2880. threadInfo[0][threadIdIndex] = threadIdCt++;
  2881. } else if (threadIdCt <= threadInfo[0][threadIdIndex]) {
  2882. threadIdCt = threadInfo[0][threadIdIndex] + 1;
  2883. }
  2884. }
  2885. for (index = 0; index <= maxIndex; index++) {
  2886. counts[index] = 1;
  2887. maxCt[index] = 1;
  2888. totals[index] = 1;
  2889. lastId[index] = threadInfo[0][index];
  2890. ;
  2891. }
  2892. // Run through the rest of the OS procs.
  2893. for (i = 1; i < num_avail; i++) {
  2894. // Find the most significant index whose id differs from the id for the
  2895. // previous OS proc.
  2896. for (index = maxIndex; index >= threadIdIndex; index--) {
  2897. if (assign_thread_ids && (index == threadIdIndex)) {
  2898. // Auto-assign the thread id field if it wasn't specified.
  2899. if (threadInfo[i][threadIdIndex] == UINT_MAX) {
  2900. threadInfo[i][threadIdIndex] = threadIdCt++;
  2901. }
  2902. // Apparently the thread id field was specified for some entries and not
  2903. // others. Start the thread id counter off at the next higher thread id.
  2904. else if (threadIdCt <= threadInfo[i][threadIdIndex]) {
  2905. threadIdCt = threadInfo[i][threadIdIndex] + 1;
  2906. }
  2907. }
  2908. if (threadInfo[i][index] != lastId[index]) {
  2909. // Run through all indices which are less significant, and reset the
  2910. // counts to 1. At all levels up to and including index, we need to
  2911. // increment the totals and record the last id.
  2912. unsigned index2;
  2913. for (index2 = threadIdIndex; index2 < index; index2++) {
  2914. totals[index2]++;
  2915. if (counts[index2] > maxCt[index2]) {
  2916. maxCt[index2] = counts[index2];
  2917. }
  2918. counts[index2] = 1;
  2919. lastId[index2] = threadInfo[i][index2];
  2920. }
  2921. counts[index]++;
  2922. totals[index]++;
  2923. lastId[index] = threadInfo[i][index];
  2924. if (assign_thread_ids && (index > threadIdIndex)) {
  2925. #if KMP_MIC && REDUCE_TEAM_SIZE
  2926. // The default team size is the total #threads in the machine
  2927. // minus 1 thread for every core that has 3 or more threads.
  2928. teamSize += (threadIdCt <= 2) ? (threadIdCt) : (threadIdCt - 1);
  2929. #endif // KMP_MIC && REDUCE_TEAM_SIZE
  2930. // Restart the thread counter, as we are on a new core.
  2931. threadIdCt = 0;
  2932. // Auto-assign the thread id field if it wasn't specified.
  2933. if (threadInfo[i][threadIdIndex] == UINT_MAX) {
  2934. threadInfo[i][threadIdIndex] = threadIdCt++;
  2935. }
  2936. // Apparently the thread id field was specified for some entries and
  2937. // not others. Start the thread id counter off at the next higher
  2938. // thread id.
  2939. else if (threadIdCt <= threadInfo[i][threadIdIndex]) {
  2940. threadIdCt = threadInfo[i][threadIdIndex] + 1;
  2941. }
  2942. }
  2943. break;
  2944. }
  2945. }
  2946. if (index < threadIdIndex) {
  2947. // If thread ids were specified, it is an error if they are not unique.
  2948. // Also, check that we waven't already restarted the loop (to be safe -
  2949. // shouldn't need to).
  2950. if ((threadInfo[i][threadIdIndex] != UINT_MAX) || assign_thread_ids) {
  2951. __kmp_free(lastId);
  2952. __kmp_free(totals);
  2953. __kmp_free(maxCt);
  2954. __kmp_free(counts);
  2955. CLEANUP_THREAD_INFO;
  2956. *msg_id = kmp_i18n_str_PhysicalIDsNotUnique;
  2957. return false;
  2958. }
  2959. // If the thread ids were not specified and we see entries entries that
  2960. // are duplicates, start the loop over and assign the thread ids manually.
  2961. assign_thread_ids = true;
  2962. goto restart_radix_check;
  2963. }
  2964. }
  2965. #if KMP_MIC && REDUCE_TEAM_SIZE
  2966. // The default team size is the total #threads in the machine
  2967. // minus 1 thread for every core that has 3 or more threads.
  2968. teamSize += (threadIdCt <= 2) ? (threadIdCt) : (threadIdCt - 1);
  2969. #endif // KMP_MIC && REDUCE_TEAM_SIZE
  2970. for (index = threadIdIndex; index <= maxIndex; index++) {
  2971. if (counts[index] > maxCt[index]) {
  2972. maxCt[index] = counts[index];
  2973. }
  2974. }
  2975. __kmp_nThreadsPerCore = maxCt[threadIdIndex];
  2976. nCoresPerPkg = maxCt[coreIdIndex];
  2977. nPackages = totals[pkgIdIndex];
  2978. // When affinity is off, this routine will still be called to set
  2979. // __kmp_ncores, as well as __kmp_nThreadsPerCore, nCoresPerPkg, & nPackages.
  2980. // Make sure all these vars are set correctly, and return now if affinity is
  2981. // not enabled.
  2982. __kmp_ncores = totals[coreIdIndex];
  2983. if (!KMP_AFFINITY_CAPABLE()) {
  2984. KMP_ASSERT(__kmp_affinity_type == affinity_none);
  2985. return true;
  2986. }
  2987. #if KMP_MIC && REDUCE_TEAM_SIZE
  2988. // Set the default team size.
  2989. if ((__kmp_dflt_team_nth == 0) && (teamSize > 0)) {
  2990. __kmp_dflt_team_nth = teamSize;
  2991. KA_TRACE(20, ("__kmp_affinity_create_cpuinfo_map: setting "
  2992. "__kmp_dflt_team_nth = %d\n",
  2993. __kmp_dflt_team_nth));
  2994. }
  2995. #endif // KMP_MIC && REDUCE_TEAM_SIZE
  2996. KMP_DEBUG_ASSERT(num_avail == (unsigned)__kmp_avail_proc);
  2997. // Count the number of levels which have more nodes at that level than at the
  2998. // parent's level (with there being an implicit root node of the top level).
  2999. // This is equivalent to saying that there is at least one node at this level
  3000. // which has a sibling. These levels are in the map, and the package level is
  3001. // always in the map.
  3002. bool *inMap = (bool *)__kmp_allocate((maxIndex + 1) * sizeof(bool));
  3003. for (index = threadIdIndex; index < maxIndex; index++) {
  3004. KMP_ASSERT(totals[index] >= totals[index + 1]);
  3005. inMap[index] = (totals[index] > totals[index + 1]);
  3006. }
  3007. inMap[maxIndex] = (totals[maxIndex] > 1);
  3008. inMap[pkgIdIndex] = true;
  3009. inMap[coreIdIndex] = true;
  3010. inMap[threadIdIndex] = true;
  3011. int depth = 0;
  3012. int idx = 0;
  3013. kmp_hw_t types[KMP_HW_LAST];
  3014. int pkgLevel = -1;
  3015. int coreLevel = -1;
  3016. int threadLevel = -1;
  3017. for (index = threadIdIndex; index <= maxIndex; index++) {
  3018. if (inMap[index]) {
  3019. depth++;
  3020. }
  3021. }
  3022. if (inMap[pkgIdIndex]) {
  3023. pkgLevel = idx;
  3024. types[idx++] = KMP_HW_SOCKET;
  3025. }
  3026. if (inMap[coreIdIndex]) {
  3027. coreLevel = idx;
  3028. types[idx++] = KMP_HW_CORE;
  3029. }
  3030. if (inMap[threadIdIndex]) {
  3031. threadLevel = idx;
  3032. types[idx++] = KMP_HW_THREAD;
  3033. }
  3034. KMP_ASSERT(depth > 0);
  3035. // Construct the data structure that is to be returned.
  3036. __kmp_topology = kmp_topology_t::allocate(num_avail, depth, types);
  3037. for (i = 0; i < num_avail; ++i) {
  3038. unsigned os = threadInfo[i][osIdIndex];
  3039. int src_index;
  3040. int dst_index = 0;
  3041. kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
  3042. hw_thread.clear();
  3043. hw_thread.os_id = os;
  3044. idx = 0;
  3045. for (src_index = maxIndex; src_index >= threadIdIndex; src_index--) {
  3046. if (!inMap[src_index]) {
  3047. continue;
  3048. }
  3049. if (src_index == pkgIdIndex) {
  3050. hw_thread.ids[pkgLevel] = threadInfo[i][src_index];
  3051. } else if (src_index == coreIdIndex) {
  3052. hw_thread.ids[coreLevel] = threadInfo[i][src_index];
  3053. } else if (src_index == threadIdIndex) {
  3054. hw_thread.ids[threadLevel] = threadInfo[i][src_index];
  3055. }
  3056. dst_index++;
  3057. }
  3058. }
  3059. __kmp_free(inMap);
  3060. __kmp_free(lastId);
  3061. __kmp_free(totals);
  3062. __kmp_free(maxCt);
  3063. __kmp_free(counts);
  3064. CLEANUP_THREAD_INFO;
  3065. __kmp_topology->sort_ids();
  3066. if (!__kmp_topology->check_ids()) {
  3067. kmp_topology_t::deallocate(__kmp_topology);
  3068. __kmp_topology = nullptr;
  3069. *msg_id = kmp_i18n_str_PhysicalIDsNotUnique;
  3070. return false;
  3071. }
  3072. return true;
  3073. }
  3074. // Create and return a table of affinity masks, indexed by OS thread ID.
  3075. // This routine handles OR'ing together all the affinity masks of threads
  3076. // that are sufficiently close, if granularity > fine.
  3077. static kmp_affin_mask_t *__kmp_create_masks(unsigned *maxIndex,
  3078. unsigned *numUnique) {
  3079. // First form a table of affinity masks in order of OS thread id.
  3080. int maxOsId;
  3081. int i;
  3082. int numAddrs = __kmp_topology->get_num_hw_threads();
  3083. int depth = __kmp_topology->get_depth();
  3084. KMP_ASSERT(numAddrs);
  3085. KMP_ASSERT(depth);
  3086. maxOsId = 0;
  3087. for (i = numAddrs - 1;; --i) {
  3088. int osId = __kmp_topology->at(i).os_id;
  3089. if (osId > maxOsId) {
  3090. maxOsId = osId;
  3091. }
  3092. if (i == 0)
  3093. break;
  3094. }
  3095. kmp_affin_mask_t *osId2Mask;
  3096. KMP_CPU_ALLOC_ARRAY(osId2Mask, (maxOsId + 1));
  3097. KMP_ASSERT(__kmp_affinity_gran_levels >= 0);
  3098. if (__kmp_affinity_verbose && (__kmp_affinity_gran_levels > 0)) {
  3099. KMP_INFORM(ThreadsMigrate, "KMP_AFFINITY", __kmp_affinity_gran_levels);
  3100. }
  3101. if (__kmp_affinity_gran_levels >= (int)depth) {
  3102. KMP_AFF_WARNING(AffThreadsMayMigrate);
  3103. }
  3104. // Run through the table, forming the masks for all threads on each core.
  3105. // Threads on the same core will have identical kmp_hw_thread_t objects, not
  3106. // considering the last level, which must be the thread id. All threads on a
  3107. // core will appear consecutively.
  3108. int unique = 0;
  3109. int j = 0; // index of 1st thread on core
  3110. int leader = 0;
  3111. kmp_affin_mask_t *sum;
  3112. KMP_CPU_ALLOC_ON_STACK(sum);
  3113. KMP_CPU_ZERO(sum);
  3114. KMP_CPU_SET(__kmp_topology->at(0).os_id, sum);
  3115. for (i = 1; i < numAddrs; i++) {
  3116. // If this thread is sufficiently close to the leader (within the
  3117. // granularity setting), then set the bit for this os thread in the
  3118. // affinity mask for this group, and go on to the next thread.
  3119. if (__kmp_topology->is_close(leader, i, __kmp_affinity_gran_levels)) {
  3120. KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);
  3121. continue;
  3122. }
  3123. // For every thread in this group, copy the mask to the thread's entry in
  3124. // the osId2Mask table. Mark the first address as a leader.
  3125. for (; j < i; j++) {
  3126. int osId = __kmp_topology->at(j).os_id;
  3127. KMP_DEBUG_ASSERT(osId <= maxOsId);
  3128. kmp_affin_mask_t *mask = KMP_CPU_INDEX(osId2Mask, osId);
  3129. KMP_CPU_COPY(mask, sum);
  3130. __kmp_topology->at(j).leader = (j == leader);
  3131. }
  3132. unique++;
  3133. // Start a new mask.
  3134. leader = i;
  3135. KMP_CPU_ZERO(sum);
  3136. KMP_CPU_SET(__kmp_topology->at(i).os_id, sum);
  3137. }
  3138. // For every thread in last group, copy the mask to the thread's
  3139. // entry in the osId2Mask table.
  3140. for (; j < i; j++) {
  3141. int osId = __kmp_topology->at(j).os_id;
  3142. KMP_DEBUG_ASSERT(osId <= maxOsId);
  3143. kmp_affin_mask_t *mask = KMP_CPU_INDEX(osId2Mask, osId);
  3144. KMP_CPU_COPY(mask, sum);
  3145. __kmp_topology->at(j).leader = (j == leader);
  3146. }
  3147. unique++;
  3148. KMP_CPU_FREE_FROM_STACK(sum);
  3149. *maxIndex = maxOsId;
  3150. *numUnique = unique;
  3151. return osId2Mask;
  3152. }
  3153. // Stuff for the affinity proclist parsers. It's easier to declare these vars
  3154. // as file-static than to try and pass them through the calling sequence of
  3155. // the recursive-descent OMP_PLACES parser.
  3156. static kmp_affin_mask_t *newMasks;
  3157. static int numNewMasks;
  3158. static int nextNewMask;
  3159. #define ADD_MASK(_mask) \
  3160. { \
  3161. if (nextNewMask >= numNewMasks) { \
  3162. int i; \
  3163. numNewMasks *= 2; \
  3164. kmp_affin_mask_t *temp; \
  3165. KMP_CPU_INTERNAL_ALLOC_ARRAY(temp, numNewMasks); \
  3166. for (i = 0; i < numNewMasks / 2; i++) { \
  3167. kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i); \
  3168. kmp_affin_mask_t *dest = KMP_CPU_INDEX(temp, i); \
  3169. KMP_CPU_COPY(dest, src); \
  3170. } \
  3171. KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks / 2); \
  3172. newMasks = temp; \
  3173. } \
  3174. KMP_CPU_COPY(KMP_CPU_INDEX(newMasks, nextNewMask), (_mask)); \
  3175. nextNewMask++; \
  3176. }
  3177. #define ADD_MASK_OSID(_osId, _osId2Mask, _maxOsId) \
  3178. { \
  3179. if (((_osId) > _maxOsId) || \
  3180. (!KMP_CPU_ISSET((_osId), KMP_CPU_INDEX((_osId2Mask), (_osId))))) { \
  3181. KMP_AFF_WARNING(AffIgnoreInvalidProcID, _osId); \
  3182. } else { \
  3183. ADD_MASK(KMP_CPU_INDEX(_osId2Mask, (_osId))); \
  3184. } \
  3185. }
  3186. // Re-parse the proclist (for the explicit affinity type), and form the list
  3187. // of affinity newMasks indexed by gtid.
  3188. static void __kmp_affinity_process_proclist(kmp_affin_mask_t **out_masks,
  3189. unsigned int *out_numMasks,
  3190. const char *proclist,
  3191. kmp_affin_mask_t *osId2Mask,
  3192. int maxOsId) {
  3193. int i;
  3194. const char *scan = proclist;
  3195. const char *next = proclist;
  3196. // We use malloc() for the temporary mask vector, so that we can use
  3197. // realloc() to extend it.
  3198. numNewMasks = 2;
  3199. KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);
  3200. nextNewMask = 0;
  3201. kmp_affin_mask_t *sumMask;
  3202. KMP_CPU_ALLOC(sumMask);
  3203. int setSize = 0;
  3204. for (;;) {
  3205. int start, end, stride;
  3206. SKIP_WS(scan);
  3207. next = scan;
  3208. if (*next == '\0') {
  3209. break;
  3210. }
  3211. if (*next == '{') {
  3212. int num;
  3213. setSize = 0;
  3214. next++; // skip '{'
  3215. SKIP_WS(next);
  3216. scan = next;
  3217. // Read the first integer in the set.
  3218. KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad proclist");
  3219. SKIP_DIGITS(next);
  3220. num = __kmp_str_to_int(scan, *next);
  3221. KMP_ASSERT2(num >= 0, "bad explicit proc list");
  3222. // Copy the mask for that osId to the sum (union) mask.
  3223. if ((num > maxOsId) ||
  3224. (!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
  3225. KMP_AFF_WARNING(AffIgnoreInvalidProcID, num);
  3226. KMP_CPU_ZERO(sumMask);
  3227. } else {
  3228. KMP_CPU_COPY(sumMask, KMP_CPU_INDEX(osId2Mask, num));
  3229. setSize = 1;
  3230. }
  3231. for (;;) {
  3232. // Check for end of set.
  3233. SKIP_WS(next);
  3234. if (*next == '}') {
  3235. next++; // skip '}'
  3236. break;
  3237. }
  3238. // Skip optional comma.
  3239. if (*next == ',') {
  3240. next++;
  3241. }
  3242. SKIP_WS(next);
  3243. // Read the next integer in the set.
  3244. scan = next;
  3245. KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
  3246. SKIP_DIGITS(next);
  3247. num = __kmp_str_to_int(scan, *next);
  3248. KMP_ASSERT2(num >= 0, "bad explicit proc list");
  3249. // Add the mask for that osId to the sum mask.
  3250. if ((num > maxOsId) ||
  3251. (!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
  3252. KMP_AFF_WARNING(AffIgnoreInvalidProcID, num);
  3253. } else {
  3254. KMP_CPU_UNION(sumMask, KMP_CPU_INDEX(osId2Mask, num));
  3255. setSize++;
  3256. }
  3257. }
  3258. if (setSize > 0) {
  3259. ADD_MASK(sumMask);
  3260. }
  3261. SKIP_WS(next);
  3262. if (*next == ',') {
  3263. next++;
  3264. }
  3265. scan = next;
  3266. continue;
  3267. }
  3268. // Read the first integer.
  3269. KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
  3270. SKIP_DIGITS(next);
  3271. start = __kmp_str_to_int(scan, *next);
  3272. KMP_ASSERT2(start >= 0, "bad explicit proc list");
  3273. SKIP_WS(next);
  3274. // If this isn't a range, then add a mask to the list and go on.
  3275. if (*next != '-') {
  3276. ADD_MASK_OSID(start, osId2Mask, maxOsId);
  3277. // Skip optional comma.
  3278. if (*next == ',') {
  3279. next++;
  3280. }
  3281. scan = next;
  3282. continue;
  3283. }
  3284. // This is a range. Skip over the '-' and read in the 2nd int.
  3285. next++; // skip '-'
  3286. SKIP_WS(next);
  3287. scan = next;
  3288. KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
  3289. SKIP_DIGITS(next);
  3290. end = __kmp_str_to_int(scan, *next);
  3291. KMP_ASSERT2(end >= 0, "bad explicit proc list");
  3292. // Check for a stride parameter
  3293. stride = 1;
  3294. SKIP_WS(next);
  3295. if (*next == ':') {
  3296. // A stride is specified. Skip over the ':" and read the 3rd int.
  3297. int sign = +1;
  3298. next++; // skip ':'
  3299. SKIP_WS(next);
  3300. scan = next;
  3301. if (*next == '-') {
  3302. sign = -1;
  3303. next++;
  3304. SKIP_WS(next);
  3305. scan = next;
  3306. }
  3307. KMP_ASSERT2((*next >= '0') && (*next <= '9'), "bad explicit proc list");
  3308. SKIP_DIGITS(next);
  3309. stride = __kmp_str_to_int(scan, *next);
  3310. KMP_ASSERT2(stride >= 0, "bad explicit proc list");
  3311. stride *= sign;
  3312. }
  3313. // Do some range checks.
  3314. KMP_ASSERT2(stride != 0, "bad explicit proc list");
  3315. if (stride > 0) {
  3316. KMP_ASSERT2(start <= end, "bad explicit proc list");
  3317. } else {
  3318. KMP_ASSERT2(start >= end, "bad explicit proc list");
  3319. }
  3320. KMP_ASSERT2((end - start) / stride <= 65536, "bad explicit proc list");
  3321. // Add the mask for each OS proc # to the list.
  3322. if (stride > 0) {
  3323. do {
  3324. ADD_MASK_OSID(start, osId2Mask, maxOsId);
  3325. start += stride;
  3326. } while (start <= end);
  3327. } else {
  3328. do {
  3329. ADD_MASK_OSID(start, osId2Mask, maxOsId);
  3330. start += stride;
  3331. } while (start >= end);
  3332. }
  3333. // Skip optional comma.
  3334. SKIP_WS(next);
  3335. if (*next == ',') {
  3336. next++;
  3337. }
  3338. scan = next;
  3339. }
  3340. *out_numMasks = nextNewMask;
  3341. if (nextNewMask == 0) {
  3342. *out_masks = NULL;
  3343. KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
  3344. return;
  3345. }
  3346. KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);
  3347. for (i = 0; i < nextNewMask; i++) {
  3348. kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i);
  3349. kmp_affin_mask_t *dest = KMP_CPU_INDEX((*out_masks), i);
  3350. KMP_CPU_COPY(dest, src);
  3351. }
  3352. KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
  3353. KMP_CPU_FREE(sumMask);
  3354. }
  3355. /*-----------------------------------------------------------------------------
  3356. Re-parse the OMP_PLACES proc id list, forming the newMasks for the different
  3357. places. Again, Here is the grammar:
  3358. place_list := place
  3359. place_list := place , place_list
  3360. place := num
  3361. place := place : num
  3362. place := place : num : signed
  3363. place := { subplacelist }
  3364. place := ! place // (lowest priority)
  3365. subplace_list := subplace
  3366. subplace_list := subplace , subplace_list
  3367. subplace := num
  3368. subplace := num : num
  3369. subplace := num : num : signed
  3370. signed := num
  3371. signed := + signed
  3372. signed := - signed
  3373. -----------------------------------------------------------------------------*/
  3374. static void __kmp_process_subplace_list(const char **scan,
  3375. kmp_affin_mask_t *osId2Mask,
  3376. int maxOsId, kmp_affin_mask_t *tempMask,
  3377. int *setSize) {
  3378. const char *next;
  3379. for (;;) {
  3380. int start, count, stride, i;
  3381. // Read in the starting proc id
  3382. SKIP_WS(*scan);
  3383. KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");
  3384. next = *scan;
  3385. SKIP_DIGITS(next);
  3386. start = __kmp_str_to_int(*scan, *next);
  3387. KMP_ASSERT(start >= 0);
  3388. *scan = next;
  3389. // valid follow sets are ',' ':' and '}'
  3390. SKIP_WS(*scan);
  3391. if (**scan == '}' || **scan == ',') {
  3392. if ((start > maxOsId) ||
  3393. (!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
  3394. KMP_AFF_WARNING(AffIgnoreInvalidProcID, start);
  3395. } else {
  3396. KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
  3397. (*setSize)++;
  3398. }
  3399. if (**scan == '}') {
  3400. break;
  3401. }
  3402. (*scan)++; // skip ','
  3403. continue;
  3404. }
  3405. KMP_ASSERT2(**scan == ':', "bad explicit places list");
  3406. (*scan)++; // skip ':'
  3407. // Read count parameter
  3408. SKIP_WS(*scan);
  3409. KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");
  3410. next = *scan;
  3411. SKIP_DIGITS(next);
  3412. count = __kmp_str_to_int(*scan, *next);
  3413. KMP_ASSERT(count >= 0);
  3414. *scan = next;
  3415. // valid follow sets are ',' ':' and '}'
  3416. SKIP_WS(*scan);
  3417. if (**scan == '}' || **scan == ',') {
  3418. for (i = 0; i < count; i++) {
  3419. if ((start > maxOsId) ||
  3420. (!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
  3421. KMP_AFF_WARNING(AffIgnoreInvalidProcID, start);
  3422. break; // don't proliferate warnings for large count
  3423. } else {
  3424. KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
  3425. start++;
  3426. (*setSize)++;
  3427. }
  3428. }
  3429. if (**scan == '}') {
  3430. break;
  3431. }
  3432. (*scan)++; // skip ','
  3433. continue;
  3434. }
  3435. KMP_ASSERT2(**scan == ':', "bad explicit places list");
  3436. (*scan)++; // skip ':'
  3437. // Read stride parameter
  3438. int sign = +1;
  3439. for (;;) {
  3440. SKIP_WS(*scan);
  3441. if (**scan == '+') {
  3442. (*scan)++; // skip '+'
  3443. continue;
  3444. }
  3445. if (**scan == '-') {
  3446. sign *= -1;
  3447. (*scan)++; // skip '-'
  3448. continue;
  3449. }
  3450. break;
  3451. }
  3452. SKIP_WS(*scan);
  3453. KMP_ASSERT2((**scan >= '0') && (**scan <= '9'), "bad explicit places list");
  3454. next = *scan;
  3455. SKIP_DIGITS(next);
  3456. stride = __kmp_str_to_int(*scan, *next);
  3457. KMP_ASSERT(stride >= 0);
  3458. *scan = next;
  3459. stride *= sign;
  3460. // valid follow sets are ',' and '}'
  3461. SKIP_WS(*scan);
  3462. if (**scan == '}' || **scan == ',') {
  3463. for (i = 0; i < count; i++) {
  3464. if ((start > maxOsId) ||
  3465. (!KMP_CPU_ISSET(start, KMP_CPU_INDEX(osId2Mask, start)))) {
  3466. KMP_AFF_WARNING(AffIgnoreInvalidProcID, start);
  3467. break; // don't proliferate warnings for large count
  3468. } else {
  3469. KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, start));
  3470. start += stride;
  3471. (*setSize)++;
  3472. }
  3473. }
  3474. if (**scan == '}') {
  3475. break;
  3476. }
  3477. (*scan)++; // skip ','
  3478. continue;
  3479. }
  3480. KMP_ASSERT2(0, "bad explicit places list");
  3481. }
  3482. }
  3483. static void __kmp_process_place(const char **scan, kmp_affin_mask_t *osId2Mask,
  3484. int maxOsId, kmp_affin_mask_t *tempMask,
  3485. int *setSize) {
  3486. const char *next;
  3487. // valid follow sets are '{' '!' and num
  3488. SKIP_WS(*scan);
  3489. if (**scan == '{') {
  3490. (*scan)++; // skip '{'
  3491. __kmp_process_subplace_list(scan, osId2Mask, maxOsId, tempMask, setSize);
  3492. KMP_ASSERT2(**scan == '}', "bad explicit places list");
  3493. (*scan)++; // skip '}'
  3494. } else if (**scan == '!') {
  3495. (*scan)++; // skip '!'
  3496. __kmp_process_place(scan, osId2Mask, maxOsId, tempMask, setSize);
  3497. KMP_CPU_COMPLEMENT(maxOsId, tempMask);
  3498. } else if ((**scan >= '0') && (**scan <= '9')) {
  3499. next = *scan;
  3500. SKIP_DIGITS(next);
  3501. int num = __kmp_str_to_int(*scan, *next);
  3502. KMP_ASSERT(num >= 0);
  3503. if ((num > maxOsId) ||
  3504. (!KMP_CPU_ISSET(num, KMP_CPU_INDEX(osId2Mask, num)))) {
  3505. KMP_AFF_WARNING(AffIgnoreInvalidProcID, num);
  3506. } else {
  3507. KMP_CPU_UNION(tempMask, KMP_CPU_INDEX(osId2Mask, num));
  3508. (*setSize)++;
  3509. }
  3510. *scan = next; // skip num
  3511. } else {
  3512. KMP_ASSERT2(0, "bad explicit places list");
  3513. }
  3514. }
  3515. // static void
  3516. void __kmp_affinity_process_placelist(kmp_affin_mask_t **out_masks,
  3517. unsigned int *out_numMasks,
  3518. const char *placelist,
  3519. kmp_affin_mask_t *osId2Mask,
  3520. int maxOsId) {
  3521. int i, j, count, stride, sign;
  3522. const char *scan = placelist;
  3523. const char *next = placelist;
  3524. numNewMasks = 2;
  3525. KMP_CPU_INTERNAL_ALLOC_ARRAY(newMasks, numNewMasks);
  3526. nextNewMask = 0;
  3527. // tempMask is modified based on the previous or initial
  3528. // place to form the current place
  3529. // previousMask contains the previous place
  3530. kmp_affin_mask_t *tempMask;
  3531. kmp_affin_mask_t *previousMask;
  3532. KMP_CPU_ALLOC(tempMask);
  3533. KMP_CPU_ZERO(tempMask);
  3534. KMP_CPU_ALLOC(previousMask);
  3535. KMP_CPU_ZERO(previousMask);
  3536. int setSize = 0;
  3537. for (;;) {
  3538. __kmp_process_place(&scan, osId2Mask, maxOsId, tempMask, &setSize);
  3539. // valid follow sets are ',' ':' and EOL
  3540. SKIP_WS(scan);
  3541. if (*scan == '\0' || *scan == ',') {
  3542. if (setSize > 0) {
  3543. ADD_MASK(tempMask);
  3544. }
  3545. KMP_CPU_ZERO(tempMask);
  3546. setSize = 0;
  3547. if (*scan == '\0') {
  3548. break;
  3549. }
  3550. scan++; // skip ','
  3551. continue;
  3552. }
  3553. KMP_ASSERT2(*scan == ':', "bad explicit places list");
  3554. scan++; // skip ':'
  3555. // Read count parameter
  3556. SKIP_WS(scan);
  3557. KMP_ASSERT2((*scan >= '0') && (*scan <= '9'), "bad explicit places list");
  3558. next = scan;
  3559. SKIP_DIGITS(next);
  3560. count = __kmp_str_to_int(scan, *next);
  3561. KMP_ASSERT(count >= 0);
  3562. scan = next;
  3563. // valid follow sets are ',' ':' and EOL
  3564. SKIP_WS(scan);
  3565. if (*scan == '\0' || *scan == ',') {
  3566. stride = +1;
  3567. } else {
  3568. KMP_ASSERT2(*scan == ':', "bad explicit places list");
  3569. scan++; // skip ':'
  3570. // Read stride parameter
  3571. sign = +1;
  3572. for (;;) {
  3573. SKIP_WS(scan);
  3574. if (*scan == '+') {
  3575. scan++; // skip '+'
  3576. continue;
  3577. }
  3578. if (*scan == '-') {
  3579. sign *= -1;
  3580. scan++; // skip '-'
  3581. continue;
  3582. }
  3583. break;
  3584. }
  3585. SKIP_WS(scan);
  3586. KMP_ASSERT2((*scan >= '0') && (*scan <= '9'), "bad explicit places list");
  3587. next = scan;
  3588. SKIP_DIGITS(next);
  3589. stride = __kmp_str_to_int(scan, *next);
  3590. KMP_DEBUG_ASSERT(stride >= 0);
  3591. scan = next;
  3592. stride *= sign;
  3593. }
  3594. // Add places determined by initial_place : count : stride
  3595. for (i = 0; i < count; i++) {
  3596. if (setSize == 0) {
  3597. break;
  3598. }
  3599. // Add the current place, then build the next place (tempMask) from that
  3600. KMP_CPU_COPY(previousMask, tempMask);
  3601. ADD_MASK(previousMask);
  3602. KMP_CPU_ZERO(tempMask);
  3603. setSize = 0;
  3604. KMP_CPU_SET_ITERATE(j, previousMask) {
  3605. if (!KMP_CPU_ISSET(j, previousMask)) {
  3606. continue;
  3607. }
  3608. if ((j + stride > maxOsId) || (j + stride < 0) ||
  3609. (!KMP_CPU_ISSET(j, __kmp_affin_fullMask)) ||
  3610. (!KMP_CPU_ISSET(j + stride,
  3611. KMP_CPU_INDEX(osId2Mask, j + stride)))) {
  3612. if (i < count - 1) {
  3613. KMP_AFF_WARNING(AffIgnoreInvalidProcID, j + stride);
  3614. }
  3615. continue;
  3616. }
  3617. KMP_CPU_SET(j + stride, tempMask);
  3618. setSize++;
  3619. }
  3620. }
  3621. KMP_CPU_ZERO(tempMask);
  3622. setSize = 0;
  3623. // valid follow sets are ',' and EOL
  3624. SKIP_WS(scan);
  3625. if (*scan == '\0') {
  3626. break;
  3627. }
  3628. if (*scan == ',') {
  3629. scan++; // skip ','
  3630. continue;
  3631. }
  3632. KMP_ASSERT2(0, "bad explicit places list");
  3633. }
  3634. *out_numMasks = nextNewMask;
  3635. if (nextNewMask == 0) {
  3636. *out_masks = NULL;
  3637. KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
  3638. return;
  3639. }
  3640. KMP_CPU_ALLOC_ARRAY((*out_masks), nextNewMask);
  3641. KMP_CPU_FREE(tempMask);
  3642. KMP_CPU_FREE(previousMask);
  3643. for (i = 0; i < nextNewMask; i++) {
  3644. kmp_affin_mask_t *src = KMP_CPU_INDEX(newMasks, i);
  3645. kmp_affin_mask_t *dest = KMP_CPU_INDEX((*out_masks), i);
  3646. KMP_CPU_COPY(dest, src);
  3647. }
  3648. KMP_CPU_INTERNAL_FREE_ARRAY(newMasks, numNewMasks);
  3649. }
  3650. #undef ADD_MASK
  3651. #undef ADD_MASK_OSID
  3652. // This function figures out the deepest level at which there is at least one
  3653. // cluster/core with more than one processing unit bound to it.
  3654. static int __kmp_affinity_find_core_level(int nprocs, int bottom_level) {
  3655. int core_level = 0;
  3656. for (int i = 0; i < nprocs; i++) {
  3657. const kmp_hw_thread_t &hw_thread = __kmp_topology->at(i);
  3658. for (int j = bottom_level; j > 0; j--) {
  3659. if (hw_thread.ids[j] > 0) {
  3660. if (core_level < (j - 1)) {
  3661. core_level = j - 1;
  3662. }
  3663. }
  3664. }
  3665. }
  3666. return core_level;
  3667. }
  3668. // This function counts number of clusters/cores at given level.
  3669. static int __kmp_affinity_compute_ncores(int nprocs, int bottom_level,
  3670. int core_level) {
  3671. return __kmp_topology->get_count(core_level);
  3672. }
  3673. // This function finds to which cluster/core given processing unit is bound.
  3674. static int __kmp_affinity_find_core(int proc, int bottom_level,
  3675. int core_level) {
  3676. int core = 0;
  3677. KMP_DEBUG_ASSERT(proc >= 0 && proc < __kmp_topology->get_num_hw_threads());
  3678. for (int i = 0; i <= proc; ++i) {
  3679. if (i + 1 <= proc) {
  3680. for (int j = 0; j <= core_level; ++j) {
  3681. if (__kmp_topology->at(i + 1).sub_ids[j] !=
  3682. __kmp_topology->at(i).sub_ids[j]) {
  3683. core++;
  3684. break;
  3685. }
  3686. }
  3687. }
  3688. }
  3689. return core;
  3690. }
  3691. // This function finds maximal number of processing units bound to a
  3692. // cluster/core at given level.
  3693. static int __kmp_affinity_max_proc_per_core(int nprocs, int bottom_level,
  3694. int core_level) {
  3695. if (core_level >= bottom_level)
  3696. return 1;
  3697. int thread_level = __kmp_topology->get_level(KMP_HW_THREAD);
  3698. return __kmp_topology->calculate_ratio(thread_level, core_level);
  3699. }
  3700. static int *procarr = NULL;
  3701. static int __kmp_aff_depth = 0;
  3702. // Create a one element mask array (set of places) which only contains the
  3703. // initial process's affinity mask
  3704. static void __kmp_create_affinity_none_places() {
  3705. KMP_ASSERT(__kmp_affin_fullMask != NULL);
  3706. KMP_ASSERT(__kmp_affinity_type == affinity_none);
  3707. __kmp_affinity_num_masks = 1;
  3708. KMP_CPU_ALLOC_ARRAY(__kmp_affinity_masks, __kmp_affinity_num_masks);
  3709. kmp_affin_mask_t *dest = KMP_CPU_INDEX(__kmp_affinity_masks, 0);
  3710. KMP_CPU_COPY(dest, __kmp_affin_fullMask);
  3711. }
  3712. static void __kmp_aux_affinity_initialize(void) {
  3713. if (__kmp_affinity_masks != NULL) {
  3714. KMP_ASSERT(__kmp_affin_fullMask != NULL);
  3715. return;
  3716. }
  3717. // Create the "full" mask - this defines all of the processors that we
  3718. // consider to be in the machine model. If respect is set, then it is the
  3719. // initialization thread's affinity mask. Otherwise, it is all processors that
  3720. // we know about on the machine.
  3721. if (__kmp_affin_fullMask == NULL) {
  3722. KMP_CPU_ALLOC(__kmp_affin_fullMask);
  3723. }
  3724. if (__kmp_affin_origMask == NULL) {
  3725. KMP_CPU_ALLOC(__kmp_affin_origMask);
  3726. }
  3727. if (KMP_AFFINITY_CAPABLE()) {
  3728. __kmp_get_system_affinity(__kmp_affin_fullMask, TRUE);
  3729. // Make a copy before possible expanding to the entire machine mask
  3730. __kmp_affin_origMask->copy(__kmp_affin_fullMask);
  3731. if (__kmp_affinity_respect_mask) {
  3732. // Count the number of available processors.
  3733. unsigned i;
  3734. __kmp_avail_proc = 0;
  3735. KMP_CPU_SET_ITERATE(i, __kmp_affin_fullMask) {
  3736. if (!KMP_CPU_ISSET(i, __kmp_affin_fullMask)) {
  3737. continue;
  3738. }
  3739. __kmp_avail_proc++;
  3740. }
  3741. if (__kmp_avail_proc > __kmp_xproc) {
  3742. KMP_AFF_WARNING(ErrorInitializeAffinity);
  3743. __kmp_affinity_type = affinity_none;
  3744. KMP_AFFINITY_DISABLE();
  3745. return;
  3746. }
  3747. if (__kmp_affinity_verbose) {
  3748. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  3749. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  3750. __kmp_affin_fullMask);
  3751. KMP_INFORM(InitOSProcSetRespect, "KMP_AFFINITY", buf);
  3752. }
  3753. } else {
  3754. if (__kmp_affinity_verbose) {
  3755. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  3756. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  3757. __kmp_affin_fullMask);
  3758. KMP_INFORM(InitOSProcSetNotRespect, "KMP_AFFINITY", buf);
  3759. }
  3760. __kmp_avail_proc =
  3761. __kmp_affinity_entire_machine_mask(__kmp_affin_fullMask);
  3762. #if KMP_OS_WINDOWS
  3763. if (__kmp_num_proc_groups <= 1) {
  3764. // Copy expanded full mask if topology has single processor group
  3765. __kmp_affin_origMask->copy(__kmp_affin_fullMask);
  3766. }
  3767. // Set the process affinity mask since threads' affinity
  3768. // masks must be subset of process mask in Windows* OS
  3769. __kmp_affin_fullMask->set_process_affinity(true);
  3770. #endif
  3771. }
  3772. }
  3773. kmp_i18n_id_t msg_id = kmp_i18n_null;
  3774. // For backward compatibility, setting KMP_CPUINFO_FILE =>
  3775. // KMP_TOPOLOGY_METHOD=cpuinfo
  3776. if ((__kmp_cpuinfo_file != NULL) &&
  3777. (__kmp_affinity_top_method == affinity_top_method_all)) {
  3778. __kmp_affinity_top_method = affinity_top_method_cpuinfo;
  3779. }
  3780. bool success = false;
  3781. if (__kmp_affinity_top_method == affinity_top_method_all) {
  3782. // In the default code path, errors are not fatal - we just try using
  3783. // another method. We only emit a warning message if affinity is on, or the
  3784. // verbose flag is set, an the nowarnings flag was not set.
  3785. #if KMP_USE_HWLOC
  3786. if (!success &&
  3787. __kmp_affinity_dispatch->get_api_type() == KMPAffinity::HWLOC) {
  3788. if (!__kmp_hwloc_error) {
  3789. success = __kmp_affinity_create_hwloc_map(&msg_id);
  3790. if (!success && __kmp_affinity_verbose) {
  3791. KMP_INFORM(AffIgnoringHwloc, "KMP_AFFINITY");
  3792. }
  3793. } else if (__kmp_affinity_verbose) {
  3794. KMP_INFORM(AffIgnoringHwloc, "KMP_AFFINITY");
  3795. }
  3796. }
  3797. #endif
  3798. #if KMP_ARCH_X86 || KMP_ARCH_X86_64
  3799. if (!success) {
  3800. success = __kmp_affinity_create_x2apicid_map(&msg_id);
  3801. if (!success && __kmp_affinity_verbose && msg_id != kmp_i18n_null) {
  3802. KMP_INFORM(AffInfoStr, "KMP_AFFINITY", __kmp_i18n_catgets(msg_id));
  3803. }
  3804. }
  3805. if (!success) {
  3806. success = __kmp_affinity_create_apicid_map(&msg_id);
  3807. if (!success && __kmp_affinity_verbose && msg_id != kmp_i18n_null) {
  3808. KMP_INFORM(AffInfoStr, "KMP_AFFINITY", __kmp_i18n_catgets(msg_id));
  3809. }
  3810. }
  3811. #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
  3812. #if KMP_OS_LINUX
  3813. if (!success) {
  3814. int line = 0;
  3815. success = __kmp_affinity_create_cpuinfo_map(&line, &msg_id);
  3816. if (!success && __kmp_affinity_verbose && msg_id != kmp_i18n_null) {
  3817. KMP_INFORM(AffInfoStr, "KMP_AFFINITY", __kmp_i18n_catgets(msg_id));
  3818. }
  3819. }
  3820. #endif /* KMP_OS_LINUX */
  3821. #if KMP_GROUP_AFFINITY
  3822. if (!success && (__kmp_num_proc_groups > 1)) {
  3823. success = __kmp_affinity_create_proc_group_map(&msg_id);
  3824. if (!success && __kmp_affinity_verbose && msg_id != kmp_i18n_null) {
  3825. KMP_INFORM(AffInfoStr, "KMP_AFFINITY", __kmp_i18n_catgets(msg_id));
  3826. }
  3827. }
  3828. #endif /* KMP_GROUP_AFFINITY */
  3829. if (!success) {
  3830. success = __kmp_affinity_create_flat_map(&msg_id);
  3831. if (!success && __kmp_affinity_verbose && msg_id != kmp_i18n_null) {
  3832. KMP_INFORM(AffInfoStr, "KMP_AFFINITY", __kmp_i18n_catgets(msg_id));
  3833. }
  3834. KMP_ASSERT(success);
  3835. }
  3836. }
  3837. // If the user has specified that a paricular topology discovery method is to be
  3838. // used, then we abort if that method fails. The exception is group affinity,
  3839. // which might have been implicitly set.
  3840. #if KMP_USE_HWLOC
  3841. else if (__kmp_affinity_top_method == affinity_top_method_hwloc) {
  3842. KMP_ASSERT(__kmp_affinity_dispatch->get_api_type() == KMPAffinity::HWLOC);
  3843. success = __kmp_affinity_create_hwloc_map(&msg_id);
  3844. if (!success) {
  3845. KMP_ASSERT(msg_id != kmp_i18n_null);
  3846. KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
  3847. }
  3848. }
  3849. #endif // KMP_USE_HWLOC
  3850. #if KMP_ARCH_X86 || KMP_ARCH_X86_64
  3851. else if (__kmp_affinity_top_method == affinity_top_method_x2apicid ||
  3852. __kmp_affinity_top_method == affinity_top_method_x2apicid_1f) {
  3853. success = __kmp_affinity_create_x2apicid_map(&msg_id);
  3854. if (!success) {
  3855. KMP_ASSERT(msg_id != kmp_i18n_null);
  3856. KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
  3857. }
  3858. } else if (__kmp_affinity_top_method == affinity_top_method_apicid) {
  3859. success = __kmp_affinity_create_apicid_map(&msg_id);
  3860. if (!success) {
  3861. KMP_ASSERT(msg_id != kmp_i18n_null);
  3862. KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
  3863. }
  3864. }
  3865. #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
  3866. else if (__kmp_affinity_top_method == affinity_top_method_cpuinfo) {
  3867. int line = 0;
  3868. success = __kmp_affinity_create_cpuinfo_map(&line, &msg_id);
  3869. if (!success) {
  3870. KMP_ASSERT(msg_id != kmp_i18n_null);
  3871. const char *filename = __kmp_cpuinfo_get_filename();
  3872. if (line > 0) {
  3873. KMP_FATAL(FileLineMsgExiting, filename, line,
  3874. __kmp_i18n_catgets(msg_id));
  3875. } else {
  3876. KMP_FATAL(FileMsgExiting, filename, __kmp_i18n_catgets(msg_id));
  3877. }
  3878. }
  3879. }
  3880. #if KMP_GROUP_AFFINITY
  3881. else if (__kmp_affinity_top_method == affinity_top_method_group) {
  3882. success = __kmp_affinity_create_proc_group_map(&msg_id);
  3883. KMP_ASSERT(success);
  3884. if (!success) {
  3885. KMP_ASSERT(msg_id != kmp_i18n_null);
  3886. KMP_FATAL(MsgExiting, __kmp_i18n_catgets(msg_id));
  3887. }
  3888. }
  3889. #endif /* KMP_GROUP_AFFINITY */
  3890. else if (__kmp_affinity_top_method == affinity_top_method_flat) {
  3891. success = __kmp_affinity_create_flat_map(&msg_id);
  3892. // should not fail
  3893. KMP_ASSERT(success);
  3894. }
  3895. // Early exit if topology could not be created
  3896. if (!__kmp_topology) {
  3897. if (KMP_AFFINITY_CAPABLE()) {
  3898. KMP_AFF_WARNING(ErrorInitializeAffinity);
  3899. }
  3900. if (nPackages > 0 && nCoresPerPkg > 0 && __kmp_nThreadsPerCore > 0 &&
  3901. __kmp_ncores > 0) {
  3902. __kmp_topology = kmp_topology_t::allocate(0, 0, NULL);
  3903. __kmp_topology->canonicalize(nPackages, nCoresPerPkg,
  3904. __kmp_nThreadsPerCore, __kmp_ncores);
  3905. if (__kmp_affinity_verbose) {
  3906. __kmp_topology->print("KMP_AFFINITY");
  3907. }
  3908. }
  3909. __kmp_affinity_type = affinity_none;
  3910. __kmp_create_affinity_none_places();
  3911. #if KMP_USE_HIER_SCHED
  3912. __kmp_dispatch_set_hierarchy_values();
  3913. #endif
  3914. KMP_AFFINITY_DISABLE();
  3915. return;
  3916. }
  3917. // Canonicalize, print (if requested), apply KMP_HW_SUBSET, and
  3918. // initialize other data structures which depend on the topology
  3919. __kmp_topology->canonicalize();
  3920. if (__kmp_affinity_verbose)
  3921. __kmp_topology->print("KMP_AFFINITY");
  3922. bool filtered = __kmp_topology->filter_hw_subset();
  3923. if (filtered) {
  3924. #if KMP_OS_WINDOWS
  3925. // Copy filtered full mask if topology has single processor group
  3926. if (__kmp_num_proc_groups <= 1)
  3927. #endif
  3928. __kmp_affin_origMask->copy(__kmp_affin_fullMask);
  3929. }
  3930. if (filtered && __kmp_affinity_verbose)
  3931. __kmp_topology->print("KMP_HW_SUBSET");
  3932. machine_hierarchy.init(__kmp_topology->get_num_hw_threads());
  3933. KMP_ASSERT(__kmp_avail_proc == __kmp_topology->get_num_hw_threads());
  3934. // If KMP_AFFINITY=none, then only create the single "none" place
  3935. // which is the process's initial affinity mask or the number of
  3936. // hardware threads depending on respect,norespect
  3937. if (__kmp_affinity_type == affinity_none) {
  3938. __kmp_create_affinity_none_places();
  3939. #if KMP_USE_HIER_SCHED
  3940. __kmp_dispatch_set_hierarchy_values();
  3941. #endif
  3942. return;
  3943. }
  3944. int depth = __kmp_topology->get_depth();
  3945. // Create the table of masks, indexed by thread Id.
  3946. unsigned maxIndex;
  3947. unsigned numUnique;
  3948. kmp_affin_mask_t *osId2Mask = __kmp_create_masks(&maxIndex, &numUnique);
  3949. if (__kmp_affinity_gran_levels == 0) {
  3950. KMP_DEBUG_ASSERT((int)numUnique == __kmp_avail_proc);
  3951. }
  3952. switch (__kmp_affinity_type) {
  3953. case affinity_explicit:
  3954. KMP_DEBUG_ASSERT(__kmp_affinity_proclist != NULL);
  3955. if (__kmp_nested_proc_bind.bind_types[0] == proc_bind_intel) {
  3956. __kmp_affinity_process_proclist(
  3957. &__kmp_affinity_masks, &__kmp_affinity_num_masks,
  3958. __kmp_affinity_proclist, osId2Mask, maxIndex);
  3959. } else {
  3960. __kmp_affinity_process_placelist(
  3961. &__kmp_affinity_masks, &__kmp_affinity_num_masks,
  3962. __kmp_affinity_proclist, osId2Mask, maxIndex);
  3963. }
  3964. if (__kmp_affinity_num_masks == 0) {
  3965. KMP_AFF_WARNING(AffNoValidProcID);
  3966. __kmp_affinity_type = affinity_none;
  3967. __kmp_create_affinity_none_places();
  3968. return;
  3969. }
  3970. break;
  3971. // The other affinity types rely on sorting the hardware threads according to
  3972. // some permutation of the machine topology tree. Set __kmp_affinity_compact
  3973. // and __kmp_affinity_offset appropriately, then jump to a common code
  3974. // fragment to do the sort and create the array of affinity masks.
  3975. case affinity_logical:
  3976. __kmp_affinity_compact = 0;
  3977. if (__kmp_affinity_offset) {
  3978. __kmp_affinity_offset =
  3979. __kmp_nThreadsPerCore * __kmp_affinity_offset % __kmp_avail_proc;
  3980. }
  3981. goto sortTopology;
  3982. case affinity_physical:
  3983. if (__kmp_nThreadsPerCore > 1) {
  3984. __kmp_affinity_compact = 1;
  3985. if (__kmp_affinity_compact >= depth) {
  3986. __kmp_affinity_compact = 0;
  3987. }
  3988. } else {
  3989. __kmp_affinity_compact = 0;
  3990. }
  3991. if (__kmp_affinity_offset) {
  3992. __kmp_affinity_offset =
  3993. __kmp_nThreadsPerCore * __kmp_affinity_offset % __kmp_avail_proc;
  3994. }
  3995. goto sortTopology;
  3996. case affinity_scatter:
  3997. if (__kmp_affinity_compact >= depth) {
  3998. __kmp_affinity_compact = 0;
  3999. } else {
  4000. __kmp_affinity_compact = depth - 1 - __kmp_affinity_compact;
  4001. }
  4002. goto sortTopology;
  4003. case affinity_compact:
  4004. if (__kmp_affinity_compact >= depth) {
  4005. __kmp_affinity_compact = depth - 1;
  4006. }
  4007. goto sortTopology;
  4008. case affinity_balanced:
  4009. if (depth <= 1) {
  4010. KMP_AFF_WARNING(AffBalancedNotAvail, "KMP_AFFINITY");
  4011. __kmp_affinity_type = affinity_none;
  4012. __kmp_create_affinity_none_places();
  4013. return;
  4014. } else if (!__kmp_topology->is_uniform()) {
  4015. // Save the depth for further usage
  4016. __kmp_aff_depth = depth;
  4017. int core_level =
  4018. __kmp_affinity_find_core_level(__kmp_avail_proc, depth - 1);
  4019. int ncores = __kmp_affinity_compute_ncores(__kmp_avail_proc, depth - 1,
  4020. core_level);
  4021. int maxprocpercore = __kmp_affinity_max_proc_per_core(
  4022. __kmp_avail_proc, depth - 1, core_level);
  4023. int nproc = ncores * maxprocpercore;
  4024. if ((nproc < 2) || (nproc < __kmp_avail_proc)) {
  4025. KMP_AFF_WARNING(AffBalancedNotAvail, "KMP_AFFINITY");
  4026. __kmp_affinity_type = affinity_none;
  4027. return;
  4028. }
  4029. procarr = (int *)__kmp_allocate(sizeof(int) * nproc);
  4030. for (int i = 0; i < nproc; i++) {
  4031. procarr[i] = -1;
  4032. }
  4033. int lastcore = -1;
  4034. int inlastcore = 0;
  4035. for (int i = 0; i < __kmp_avail_proc; i++) {
  4036. int proc = __kmp_topology->at(i).os_id;
  4037. int core = __kmp_affinity_find_core(i, depth - 1, core_level);
  4038. if (core == lastcore) {
  4039. inlastcore++;
  4040. } else {
  4041. inlastcore = 0;
  4042. }
  4043. lastcore = core;
  4044. procarr[core * maxprocpercore + inlastcore] = proc;
  4045. }
  4046. }
  4047. if (__kmp_affinity_compact >= depth) {
  4048. __kmp_affinity_compact = depth - 1;
  4049. }
  4050. sortTopology:
  4051. // Allocate the gtid->affinity mask table.
  4052. if (__kmp_affinity_dups) {
  4053. __kmp_affinity_num_masks = __kmp_avail_proc;
  4054. } else {
  4055. __kmp_affinity_num_masks = numUnique;
  4056. }
  4057. if ((__kmp_nested_proc_bind.bind_types[0] != proc_bind_intel) &&
  4058. (__kmp_affinity_num_places > 0) &&
  4059. ((unsigned)__kmp_affinity_num_places < __kmp_affinity_num_masks)) {
  4060. __kmp_affinity_num_masks = __kmp_affinity_num_places;
  4061. }
  4062. KMP_CPU_ALLOC_ARRAY(__kmp_affinity_masks, __kmp_affinity_num_masks);
  4063. // Sort the topology table according to the current setting of
  4064. // __kmp_affinity_compact, then fill out __kmp_affinity_masks.
  4065. __kmp_topology->sort_compact();
  4066. {
  4067. int i;
  4068. unsigned j;
  4069. int num_hw_threads = __kmp_topology->get_num_hw_threads();
  4070. for (i = 0, j = 0; i < num_hw_threads; i++) {
  4071. if ((!__kmp_affinity_dups) && (!__kmp_topology->at(i).leader)) {
  4072. continue;
  4073. }
  4074. int osId = __kmp_topology->at(i).os_id;
  4075. kmp_affin_mask_t *src = KMP_CPU_INDEX(osId2Mask, osId);
  4076. kmp_affin_mask_t *dest = KMP_CPU_INDEX(__kmp_affinity_masks, j);
  4077. KMP_ASSERT(KMP_CPU_ISSET(osId, src));
  4078. KMP_CPU_COPY(dest, src);
  4079. if (++j >= __kmp_affinity_num_masks) {
  4080. break;
  4081. }
  4082. }
  4083. KMP_DEBUG_ASSERT(j == __kmp_affinity_num_masks);
  4084. }
  4085. // Sort the topology back using ids
  4086. __kmp_topology->sort_ids();
  4087. break;
  4088. default:
  4089. KMP_ASSERT2(0, "Unexpected affinity setting");
  4090. }
  4091. KMP_CPU_FREE_ARRAY(osId2Mask, maxIndex + 1);
  4092. }
  4093. void __kmp_affinity_initialize(void) {
  4094. // Much of the code above was written assuming that if a machine was not
  4095. // affinity capable, then __kmp_affinity_type == affinity_none. We now
  4096. // explicitly represent this as __kmp_affinity_type == affinity_disabled.
  4097. // There are too many checks for __kmp_affinity_type == affinity_none
  4098. // in this code. Instead of trying to change them all, check if
  4099. // __kmp_affinity_type == affinity_disabled, and if so, slam it with
  4100. // affinity_none, call the real initialization routine, then restore
  4101. // __kmp_affinity_type to affinity_disabled.
  4102. int disabled = (__kmp_affinity_type == affinity_disabled);
  4103. if (!KMP_AFFINITY_CAPABLE()) {
  4104. KMP_ASSERT(disabled);
  4105. }
  4106. if (disabled) {
  4107. __kmp_affinity_type = affinity_none;
  4108. }
  4109. __kmp_aux_affinity_initialize();
  4110. if (disabled) {
  4111. __kmp_affinity_type = affinity_disabled;
  4112. }
  4113. }
  4114. void __kmp_affinity_uninitialize(void) {
  4115. if (__kmp_affinity_masks != NULL) {
  4116. KMP_CPU_FREE_ARRAY(__kmp_affinity_masks, __kmp_affinity_num_masks);
  4117. __kmp_affinity_masks = NULL;
  4118. }
  4119. if (__kmp_affin_fullMask != NULL) {
  4120. KMP_CPU_FREE(__kmp_affin_fullMask);
  4121. __kmp_affin_fullMask = NULL;
  4122. }
  4123. if (__kmp_affin_origMask != NULL) {
  4124. KMP_CPU_FREE(__kmp_affin_origMask);
  4125. __kmp_affin_origMask = NULL;
  4126. }
  4127. __kmp_affinity_num_masks = 0;
  4128. __kmp_affinity_type = affinity_default;
  4129. __kmp_affinity_num_places = 0;
  4130. if (__kmp_affinity_proclist != NULL) {
  4131. __kmp_free(__kmp_affinity_proclist);
  4132. __kmp_affinity_proclist = NULL;
  4133. }
  4134. if (procarr != NULL) {
  4135. __kmp_free(procarr);
  4136. procarr = NULL;
  4137. }
  4138. #if KMP_USE_HWLOC
  4139. if (__kmp_hwloc_topology != NULL) {
  4140. hwloc_topology_destroy(__kmp_hwloc_topology);
  4141. __kmp_hwloc_topology = NULL;
  4142. }
  4143. #endif
  4144. if (__kmp_hw_subset) {
  4145. kmp_hw_subset_t::deallocate(__kmp_hw_subset);
  4146. __kmp_hw_subset = nullptr;
  4147. }
  4148. if (__kmp_topology) {
  4149. kmp_topology_t::deallocate(__kmp_topology);
  4150. __kmp_topology = nullptr;
  4151. }
  4152. KMPAffinity::destroy_api();
  4153. }
  4154. void __kmp_affinity_set_init_mask(int gtid, int isa_root) {
  4155. if (!KMP_AFFINITY_CAPABLE()) {
  4156. return;
  4157. }
  4158. kmp_info_t *th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[gtid]);
  4159. if (th->th.th_affin_mask == NULL) {
  4160. KMP_CPU_ALLOC(th->th.th_affin_mask);
  4161. } else {
  4162. KMP_CPU_ZERO(th->th.th_affin_mask);
  4163. }
  4164. // Copy the thread mask to the kmp_info_t structure. If
  4165. // __kmp_affinity_type == affinity_none, copy the "full" mask, i.e. one that
  4166. // has all of the OS proc ids set, or if __kmp_affinity_respect_mask is set,
  4167. // then the full mask is the same as the mask of the initialization thread.
  4168. kmp_affin_mask_t *mask;
  4169. int i;
  4170. if (KMP_AFFINITY_NON_PROC_BIND) {
  4171. if ((__kmp_affinity_type == affinity_none) ||
  4172. (__kmp_affinity_type == affinity_balanced) ||
  4173. KMP_HIDDEN_HELPER_THREAD(gtid)) {
  4174. #if KMP_GROUP_AFFINITY
  4175. if (__kmp_num_proc_groups > 1) {
  4176. return;
  4177. }
  4178. #endif
  4179. KMP_ASSERT(__kmp_affin_fullMask != NULL);
  4180. i = 0;
  4181. mask = __kmp_affin_fullMask;
  4182. } else {
  4183. int mask_idx = __kmp_adjust_gtid_for_hidden_helpers(gtid);
  4184. KMP_DEBUG_ASSERT(__kmp_affinity_num_masks > 0);
  4185. i = (mask_idx + __kmp_affinity_offset) % __kmp_affinity_num_masks;
  4186. mask = KMP_CPU_INDEX(__kmp_affinity_masks, i);
  4187. }
  4188. } else {
  4189. if ((!isa_root) || KMP_HIDDEN_HELPER_THREAD(gtid) ||
  4190. (__kmp_nested_proc_bind.bind_types[0] == proc_bind_false)) {
  4191. #if KMP_GROUP_AFFINITY
  4192. if (__kmp_num_proc_groups > 1) {
  4193. return;
  4194. }
  4195. #endif
  4196. KMP_ASSERT(__kmp_affin_fullMask != NULL);
  4197. i = KMP_PLACE_ALL;
  4198. mask = __kmp_affin_fullMask;
  4199. } else {
  4200. // int i = some hash function or just a counter that doesn't
  4201. // always start at 0. Use adjusted gtid for now.
  4202. int mask_idx = __kmp_adjust_gtid_for_hidden_helpers(gtid);
  4203. KMP_DEBUG_ASSERT(__kmp_affinity_num_masks > 0);
  4204. i = (mask_idx + __kmp_affinity_offset) % __kmp_affinity_num_masks;
  4205. mask = KMP_CPU_INDEX(__kmp_affinity_masks, i);
  4206. }
  4207. }
  4208. th->th.th_current_place = i;
  4209. if (isa_root || KMP_HIDDEN_HELPER_THREAD(gtid)) {
  4210. th->th.th_new_place = i;
  4211. th->th.th_first_place = 0;
  4212. th->th.th_last_place = __kmp_affinity_num_masks - 1;
  4213. } else if (KMP_AFFINITY_NON_PROC_BIND) {
  4214. // When using a Non-OMP_PROC_BIND affinity method,
  4215. // set all threads' place-partition-var to the entire place list
  4216. th->th.th_first_place = 0;
  4217. th->th.th_last_place = __kmp_affinity_num_masks - 1;
  4218. }
  4219. if (i == KMP_PLACE_ALL) {
  4220. KA_TRACE(100, ("__kmp_affinity_set_init_mask: binding T#%d to all places\n",
  4221. gtid));
  4222. } else {
  4223. KA_TRACE(100, ("__kmp_affinity_set_init_mask: binding T#%d to place %d\n",
  4224. gtid, i));
  4225. }
  4226. KMP_CPU_COPY(th->th.th_affin_mask, mask);
  4227. if (__kmp_affinity_verbose && !KMP_HIDDEN_HELPER_THREAD(gtid)
  4228. /* to avoid duplicate printing (will be correctly printed on barrier) */
  4229. && (__kmp_affinity_type == affinity_none ||
  4230. (i != KMP_PLACE_ALL && __kmp_affinity_type != affinity_balanced))) {
  4231. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4232. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4233. th->th.th_affin_mask);
  4234. KMP_INFORM(BoundToOSProcSet, "KMP_AFFINITY", (kmp_int32)getpid(),
  4235. __kmp_gettid(), gtid, buf);
  4236. }
  4237. #if KMP_DEBUG
  4238. // Hidden helper thread affinity only printed for debug builds
  4239. if (__kmp_affinity_verbose && KMP_HIDDEN_HELPER_THREAD(gtid)) {
  4240. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4241. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4242. th->th.th_affin_mask);
  4243. KMP_INFORM(BoundToOSProcSet, "KMP_AFFINITY (hidden helper thread)",
  4244. (kmp_int32)getpid(), __kmp_gettid(), gtid, buf);
  4245. }
  4246. #endif
  4247. #if KMP_OS_WINDOWS
  4248. // On Windows* OS, the process affinity mask might have changed. If the user
  4249. // didn't request affinity and this call fails, just continue silently.
  4250. // See CQ171393.
  4251. if (__kmp_affinity_type == affinity_none) {
  4252. __kmp_set_system_affinity(th->th.th_affin_mask, FALSE);
  4253. } else
  4254. #endif
  4255. __kmp_set_system_affinity(th->th.th_affin_mask, TRUE);
  4256. }
  4257. void __kmp_affinity_set_place(int gtid) {
  4258. if (!KMP_AFFINITY_CAPABLE()) {
  4259. return;
  4260. }
  4261. kmp_info_t *th = (kmp_info_t *)TCR_SYNC_PTR(__kmp_threads[gtid]);
  4262. KA_TRACE(100, ("__kmp_affinity_set_place: binding T#%d to place %d (current "
  4263. "place = %d)\n",
  4264. gtid, th->th.th_new_place, th->th.th_current_place));
  4265. // Check that the new place is within this thread's partition.
  4266. KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
  4267. KMP_ASSERT(th->th.th_new_place >= 0);
  4268. KMP_ASSERT((unsigned)th->th.th_new_place <= __kmp_affinity_num_masks);
  4269. if (th->th.th_first_place <= th->th.th_last_place) {
  4270. KMP_ASSERT((th->th.th_new_place >= th->th.th_first_place) &&
  4271. (th->th.th_new_place <= th->th.th_last_place));
  4272. } else {
  4273. KMP_ASSERT((th->th.th_new_place <= th->th.th_first_place) ||
  4274. (th->th.th_new_place >= th->th.th_last_place));
  4275. }
  4276. // Copy the thread mask to the kmp_info_t structure,
  4277. // and set this thread's affinity.
  4278. kmp_affin_mask_t *mask =
  4279. KMP_CPU_INDEX(__kmp_affinity_masks, th->th.th_new_place);
  4280. KMP_CPU_COPY(th->th.th_affin_mask, mask);
  4281. th->th.th_current_place = th->th.th_new_place;
  4282. if (__kmp_affinity_verbose) {
  4283. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4284. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4285. th->th.th_affin_mask);
  4286. KMP_INFORM(BoundToOSProcSet, "OMP_PROC_BIND", (kmp_int32)getpid(),
  4287. __kmp_gettid(), gtid, buf);
  4288. }
  4289. __kmp_set_system_affinity(th->th.th_affin_mask, TRUE);
  4290. }
  4291. int __kmp_aux_set_affinity(void **mask) {
  4292. int gtid;
  4293. kmp_info_t *th;
  4294. int retval;
  4295. if (!KMP_AFFINITY_CAPABLE()) {
  4296. return -1;
  4297. }
  4298. gtid = __kmp_entry_gtid();
  4299. KA_TRACE(
  4300. 1000, (""); {
  4301. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4302. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4303. (kmp_affin_mask_t *)(*mask));
  4304. __kmp_debug_printf(
  4305. "kmp_set_affinity: setting affinity mask for thread %d = %s\n",
  4306. gtid, buf);
  4307. });
  4308. if (__kmp_env_consistency_check) {
  4309. if ((mask == NULL) || (*mask == NULL)) {
  4310. KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
  4311. } else {
  4312. unsigned proc;
  4313. int num_procs = 0;
  4314. KMP_CPU_SET_ITERATE(proc, ((kmp_affin_mask_t *)(*mask))) {
  4315. if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
  4316. KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
  4317. }
  4318. if (!KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask))) {
  4319. continue;
  4320. }
  4321. num_procs++;
  4322. }
  4323. if (num_procs == 0) {
  4324. KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
  4325. }
  4326. #if KMP_GROUP_AFFINITY
  4327. if (__kmp_get_proc_group((kmp_affin_mask_t *)(*mask)) < 0) {
  4328. KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity");
  4329. }
  4330. #endif /* KMP_GROUP_AFFINITY */
  4331. }
  4332. }
  4333. th = __kmp_threads[gtid];
  4334. KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
  4335. retval = __kmp_set_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);
  4336. if (retval == 0) {
  4337. KMP_CPU_COPY(th->th.th_affin_mask, (kmp_affin_mask_t *)(*mask));
  4338. }
  4339. th->th.th_current_place = KMP_PLACE_UNDEFINED;
  4340. th->th.th_new_place = KMP_PLACE_UNDEFINED;
  4341. th->th.th_first_place = 0;
  4342. th->th.th_last_place = __kmp_affinity_num_masks - 1;
  4343. // Turn off 4.0 affinity for the current tread at this parallel level.
  4344. th->th.th_current_task->td_icvs.proc_bind = proc_bind_false;
  4345. return retval;
  4346. }
  4347. int __kmp_aux_get_affinity(void **mask) {
  4348. int gtid;
  4349. int retval;
  4350. #if KMP_OS_WINDOWS || KMP_DEBUG
  4351. kmp_info_t *th;
  4352. #endif
  4353. if (!KMP_AFFINITY_CAPABLE()) {
  4354. return -1;
  4355. }
  4356. gtid = __kmp_entry_gtid();
  4357. #if KMP_OS_WINDOWS || KMP_DEBUG
  4358. th = __kmp_threads[gtid];
  4359. #else
  4360. (void)gtid; // unused variable
  4361. #endif
  4362. KMP_DEBUG_ASSERT(th->th.th_affin_mask != NULL);
  4363. KA_TRACE(
  4364. 1000, (""); {
  4365. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4366. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4367. th->th.th_affin_mask);
  4368. __kmp_printf(
  4369. "kmp_get_affinity: stored affinity mask for thread %d = %s\n", gtid,
  4370. buf);
  4371. });
  4372. if (__kmp_env_consistency_check) {
  4373. if ((mask == NULL) || (*mask == NULL)) {
  4374. KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity");
  4375. }
  4376. }
  4377. #if !KMP_OS_WINDOWS
  4378. retval = __kmp_get_system_affinity((kmp_affin_mask_t *)(*mask), FALSE);
  4379. KA_TRACE(
  4380. 1000, (""); {
  4381. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4382. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4383. (kmp_affin_mask_t *)(*mask));
  4384. __kmp_printf(
  4385. "kmp_get_affinity: system affinity mask for thread %d = %s\n", gtid,
  4386. buf);
  4387. });
  4388. return retval;
  4389. #else
  4390. (void)retval;
  4391. KMP_CPU_COPY((kmp_affin_mask_t *)(*mask), th->th.th_affin_mask);
  4392. return 0;
  4393. #endif /* KMP_OS_WINDOWS */
  4394. }
  4395. int __kmp_aux_get_affinity_max_proc() {
  4396. if (!KMP_AFFINITY_CAPABLE()) {
  4397. return 0;
  4398. }
  4399. #if KMP_GROUP_AFFINITY
  4400. if (__kmp_num_proc_groups > 1) {
  4401. return (int)(__kmp_num_proc_groups * sizeof(DWORD_PTR) * CHAR_BIT);
  4402. }
  4403. #endif
  4404. return __kmp_xproc;
  4405. }
  4406. int __kmp_aux_set_affinity_mask_proc(int proc, void **mask) {
  4407. if (!KMP_AFFINITY_CAPABLE()) {
  4408. return -1;
  4409. }
  4410. KA_TRACE(
  4411. 1000, (""); {
  4412. int gtid = __kmp_entry_gtid();
  4413. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4414. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4415. (kmp_affin_mask_t *)(*mask));
  4416. __kmp_debug_printf("kmp_set_affinity_mask_proc: setting proc %d in "
  4417. "affinity mask for thread %d = %s\n",
  4418. proc, gtid, buf);
  4419. });
  4420. if (__kmp_env_consistency_check) {
  4421. if ((mask == NULL) || (*mask == NULL)) {
  4422. KMP_FATAL(AffinityInvalidMask, "kmp_set_affinity_mask_proc");
  4423. }
  4424. }
  4425. if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {
  4426. return -1;
  4427. }
  4428. if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
  4429. return -2;
  4430. }
  4431. KMP_CPU_SET(proc, (kmp_affin_mask_t *)(*mask));
  4432. return 0;
  4433. }
  4434. int __kmp_aux_unset_affinity_mask_proc(int proc, void **mask) {
  4435. if (!KMP_AFFINITY_CAPABLE()) {
  4436. return -1;
  4437. }
  4438. KA_TRACE(
  4439. 1000, (""); {
  4440. int gtid = __kmp_entry_gtid();
  4441. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4442. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4443. (kmp_affin_mask_t *)(*mask));
  4444. __kmp_debug_printf("kmp_unset_affinity_mask_proc: unsetting proc %d in "
  4445. "affinity mask for thread %d = %s\n",
  4446. proc, gtid, buf);
  4447. });
  4448. if (__kmp_env_consistency_check) {
  4449. if ((mask == NULL) || (*mask == NULL)) {
  4450. KMP_FATAL(AffinityInvalidMask, "kmp_unset_affinity_mask_proc");
  4451. }
  4452. }
  4453. if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {
  4454. return -1;
  4455. }
  4456. if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
  4457. return -2;
  4458. }
  4459. KMP_CPU_CLR(proc, (kmp_affin_mask_t *)(*mask));
  4460. return 0;
  4461. }
  4462. int __kmp_aux_get_affinity_mask_proc(int proc, void **mask) {
  4463. if (!KMP_AFFINITY_CAPABLE()) {
  4464. return -1;
  4465. }
  4466. KA_TRACE(
  4467. 1000, (""); {
  4468. int gtid = __kmp_entry_gtid();
  4469. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4470. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN,
  4471. (kmp_affin_mask_t *)(*mask));
  4472. __kmp_debug_printf("kmp_get_affinity_mask_proc: getting proc %d in "
  4473. "affinity mask for thread %d = %s\n",
  4474. proc, gtid, buf);
  4475. });
  4476. if (__kmp_env_consistency_check) {
  4477. if ((mask == NULL) || (*mask == NULL)) {
  4478. KMP_FATAL(AffinityInvalidMask, "kmp_get_affinity_mask_proc");
  4479. }
  4480. }
  4481. if ((proc < 0) || (proc >= __kmp_aux_get_affinity_max_proc())) {
  4482. return -1;
  4483. }
  4484. if (!KMP_CPU_ISSET(proc, __kmp_affin_fullMask)) {
  4485. return 0;
  4486. }
  4487. return KMP_CPU_ISSET(proc, (kmp_affin_mask_t *)(*mask));
  4488. }
  4489. // Dynamic affinity settings - Affinity balanced
  4490. void __kmp_balanced_affinity(kmp_info_t *th, int nthreads) {
  4491. KMP_DEBUG_ASSERT(th);
  4492. bool fine_gran = true;
  4493. int tid = th->th.th_info.ds.ds_tid;
  4494. // Do not perform balanced affinity for the hidden helper threads
  4495. if (KMP_HIDDEN_HELPER_THREAD(__kmp_gtid_from_thread(th)))
  4496. return;
  4497. switch (__kmp_affinity_gran) {
  4498. case KMP_HW_THREAD:
  4499. break;
  4500. case KMP_HW_CORE:
  4501. if (__kmp_nThreadsPerCore > 1) {
  4502. fine_gran = false;
  4503. }
  4504. break;
  4505. case KMP_HW_SOCKET:
  4506. if (nCoresPerPkg > 1) {
  4507. fine_gran = false;
  4508. }
  4509. break;
  4510. default:
  4511. fine_gran = false;
  4512. }
  4513. if (__kmp_topology->is_uniform()) {
  4514. int coreID;
  4515. int threadID;
  4516. // Number of hyper threads per core in HT machine
  4517. int __kmp_nth_per_core = __kmp_avail_proc / __kmp_ncores;
  4518. // Number of cores
  4519. int ncores = __kmp_ncores;
  4520. if ((nPackages > 1) && (__kmp_nth_per_core <= 1)) {
  4521. __kmp_nth_per_core = __kmp_avail_proc / nPackages;
  4522. ncores = nPackages;
  4523. }
  4524. // How many threads will be bound to each core
  4525. int chunk = nthreads / ncores;
  4526. // How many cores will have an additional thread bound to it - "big cores"
  4527. int big_cores = nthreads % ncores;
  4528. // Number of threads on the big cores
  4529. int big_nth = (chunk + 1) * big_cores;
  4530. if (tid < big_nth) {
  4531. coreID = tid / (chunk + 1);
  4532. threadID = (tid % (chunk + 1)) % __kmp_nth_per_core;
  4533. } else { // tid >= big_nth
  4534. coreID = (tid - big_cores) / chunk;
  4535. threadID = ((tid - big_cores) % chunk) % __kmp_nth_per_core;
  4536. }
  4537. KMP_DEBUG_ASSERT2(KMP_AFFINITY_CAPABLE(),
  4538. "Illegal set affinity operation when not capable");
  4539. kmp_affin_mask_t *mask = th->th.th_affin_mask;
  4540. KMP_CPU_ZERO(mask);
  4541. if (fine_gran) {
  4542. int osID =
  4543. __kmp_topology->at(coreID * __kmp_nth_per_core + threadID).os_id;
  4544. KMP_CPU_SET(osID, mask);
  4545. } else {
  4546. for (int i = 0; i < __kmp_nth_per_core; i++) {
  4547. int osID;
  4548. osID = __kmp_topology->at(coreID * __kmp_nth_per_core + i).os_id;
  4549. KMP_CPU_SET(osID, mask);
  4550. }
  4551. }
  4552. if (__kmp_affinity_verbose) {
  4553. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4554. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);
  4555. KMP_INFORM(BoundToOSProcSet, "KMP_AFFINITY", (kmp_int32)getpid(),
  4556. __kmp_gettid(), tid, buf);
  4557. }
  4558. __kmp_set_system_affinity(mask, TRUE);
  4559. } else { // Non-uniform topology
  4560. kmp_affin_mask_t *mask = th->th.th_affin_mask;
  4561. KMP_CPU_ZERO(mask);
  4562. int core_level =
  4563. __kmp_affinity_find_core_level(__kmp_avail_proc, __kmp_aff_depth - 1);
  4564. int ncores = __kmp_affinity_compute_ncores(__kmp_avail_proc,
  4565. __kmp_aff_depth - 1, core_level);
  4566. int nth_per_core = __kmp_affinity_max_proc_per_core(
  4567. __kmp_avail_proc, __kmp_aff_depth - 1, core_level);
  4568. // For performance gain consider the special case nthreads ==
  4569. // __kmp_avail_proc
  4570. if (nthreads == __kmp_avail_proc) {
  4571. if (fine_gran) {
  4572. int osID = __kmp_topology->at(tid).os_id;
  4573. KMP_CPU_SET(osID, mask);
  4574. } else {
  4575. int core =
  4576. __kmp_affinity_find_core(tid, __kmp_aff_depth - 1, core_level);
  4577. for (int i = 0; i < __kmp_avail_proc; i++) {
  4578. int osID = __kmp_topology->at(i).os_id;
  4579. if (__kmp_affinity_find_core(i, __kmp_aff_depth - 1, core_level) ==
  4580. core) {
  4581. KMP_CPU_SET(osID, mask);
  4582. }
  4583. }
  4584. }
  4585. } else if (nthreads <= ncores) {
  4586. int core = 0;
  4587. for (int i = 0; i < ncores; i++) {
  4588. // Check if this core from procarr[] is in the mask
  4589. int in_mask = 0;
  4590. for (int j = 0; j < nth_per_core; j++) {
  4591. if (procarr[i * nth_per_core + j] != -1) {
  4592. in_mask = 1;
  4593. break;
  4594. }
  4595. }
  4596. if (in_mask) {
  4597. if (tid == core) {
  4598. for (int j = 0; j < nth_per_core; j++) {
  4599. int osID = procarr[i * nth_per_core + j];
  4600. if (osID != -1) {
  4601. KMP_CPU_SET(osID, mask);
  4602. // For fine granularity it is enough to set the first available
  4603. // osID for this core
  4604. if (fine_gran) {
  4605. break;
  4606. }
  4607. }
  4608. }
  4609. break;
  4610. } else {
  4611. core++;
  4612. }
  4613. }
  4614. }
  4615. } else { // nthreads > ncores
  4616. // Array to save the number of processors at each core
  4617. int *nproc_at_core = (int *)KMP_ALLOCA(sizeof(int) * ncores);
  4618. // Array to save the number of cores with "x" available processors;
  4619. int *ncores_with_x_procs =
  4620. (int *)KMP_ALLOCA(sizeof(int) * (nth_per_core + 1));
  4621. // Array to save the number of cores with # procs from x to nth_per_core
  4622. int *ncores_with_x_to_max_procs =
  4623. (int *)KMP_ALLOCA(sizeof(int) * (nth_per_core + 1));
  4624. for (int i = 0; i <= nth_per_core; i++) {
  4625. ncores_with_x_procs[i] = 0;
  4626. ncores_with_x_to_max_procs[i] = 0;
  4627. }
  4628. for (int i = 0; i < ncores; i++) {
  4629. int cnt = 0;
  4630. for (int j = 0; j < nth_per_core; j++) {
  4631. if (procarr[i * nth_per_core + j] != -1) {
  4632. cnt++;
  4633. }
  4634. }
  4635. nproc_at_core[i] = cnt;
  4636. ncores_with_x_procs[cnt]++;
  4637. }
  4638. for (int i = 0; i <= nth_per_core; i++) {
  4639. for (int j = i; j <= nth_per_core; j++) {
  4640. ncores_with_x_to_max_procs[i] += ncores_with_x_procs[j];
  4641. }
  4642. }
  4643. // Max number of processors
  4644. int nproc = nth_per_core * ncores;
  4645. // An array to keep number of threads per each context
  4646. int *newarr = (int *)__kmp_allocate(sizeof(int) * nproc);
  4647. for (int i = 0; i < nproc; i++) {
  4648. newarr[i] = 0;
  4649. }
  4650. int nth = nthreads;
  4651. int flag = 0;
  4652. while (nth > 0) {
  4653. for (int j = 1; j <= nth_per_core; j++) {
  4654. int cnt = ncores_with_x_to_max_procs[j];
  4655. for (int i = 0; i < ncores; i++) {
  4656. // Skip the core with 0 processors
  4657. if (nproc_at_core[i] == 0) {
  4658. continue;
  4659. }
  4660. for (int k = 0; k < nth_per_core; k++) {
  4661. if (procarr[i * nth_per_core + k] != -1) {
  4662. if (newarr[i * nth_per_core + k] == 0) {
  4663. newarr[i * nth_per_core + k] = 1;
  4664. cnt--;
  4665. nth--;
  4666. break;
  4667. } else {
  4668. if (flag != 0) {
  4669. newarr[i * nth_per_core + k]++;
  4670. cnt--;
  4671. nth--;
  4672. break;
  4673. }
  4674. }
  4675. }
  4676. }
  4677. if (cnt == 0 || nth == 0) {
  4678. break;
  4679. }
  4680. }
  4681. if (nth == 0) {
  4682. break;
  4683. }
  4684. }
  4685. flag = 1;
  4686. }
  4687. int sum = 0;
  4688. for (int i = 0; i < nproc; i++) {
  4689. sum += newarr[i];
  4690. if (sum > tid) {
  4691. if (fine_gran) {
  4692. int osID = procarr[i];
  4693. KMP_CPU_SET(osID, mask);
  4694. } else {
  4695. int coreID = i / nth_per_core;
  4696. for (int ii = 0; ii < nth_per_core; ii++) {
  4697. int osID = procarr[coreID * nth_per_core + ii];
  4698. if (osID != -1) {
  4699. KMP_CPU_SET(osID, mask);
  4700. }
  4701. }
  4702. }
  4703. break;
  4704. }
  4705. }
  4706. __kmp_free(newarr);
  4707. }
  4708. if (__kmp_affinity_verbose) {
  4709. char buf[KMP_AFFIN_MASK_PRINT_LEN];
  4710. __kmp_affinity_print_mask(buf, KMP_AFFIN_MASK_PRINT_LEN, mask);
  4711. KMP_INFORM(BoundToOSProcSet, "KMP_AFFINITY", (kmp_int32)getpid(),
  4712. __kmp_gettid(), tid, buf);
  4713. }
  4714. __kmp_set_system_affinity(mask, TRUE);
  4715. }
  4716. }
  4717. #if KMP_OS_LINUX || KMP_OS_FREEBSD
  4718. // We don't need this entry for Windows because
  4719. // there is GetProcessAffinityMask() api
  4720. //
  4721. // The intended usage is indicated by these steps:
  4722. // 1) The user gets the current affinity mask
  4723. // 2) Then sets the affinity by calling this function
  4724. // 3) Error check the return value
  4725. // 4) Use non-OpenMP parallelization
  4726. // 5) Reset the affinity to what was stored in step 1)
  4727. #ifdef __cplusplus
  4728. extern "C"
  4729. #endif
  4730. int
  4731. kmp_set_thread_affinity_mask_initial()
  4732. // the function returns 0 on success,
  4733. // -1 if we cannot bind thread
  4734. // >0 (errno) if an error happened during binding
  4735. {
  4736. int gtid = __kmp_get_gtid();
  4737. if (gtid < 0) {
  4738. // Do not touch non-omp threads
  4739. KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "
  4740. "non-omp thread, returning\n"));
  4741. return -1;
  4742. }
  4743. if (!KMP_AFFINITY_CAPABLE() || !__kmp_init_middle) {
  4744. KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "
  4745. "affinity not initialized, returning\n"));
  4746. return -1;
  4747. }
  4748. KA_TRACE(30, ("kmp_set_thread_affinity_mask_initial: "
  4749. "set full mask for thread %d\n",
  4750. gtid));
  4751. KMP_DEBUG_ASSERT(__kmp_affin_fullMask != NULL);
  4752. return __kmp_set_system_affinity(__kmp_affin_fullMask, FALSE);
  4753. }
  4754. #endif
  4755. #endif // KMP_AFFINITY_SUPPORTED