scheduler.c 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941
  1. /* scheduler.c -*-C-*-
  2. *
  3. *************************************************************************
  4. *
  5. * @copyright
  6. * Copyright (C) 2007-2013, Intel Corporation
  7. * All rights reserved.
  8. *
  9. * @copyright
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions
  12. * are met:
  13. *
  14. * * Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. * * Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in
  18. * the documentation and/or other materials provided with the
  19. * distribution.
  20. * * Neither the name of Intel Corporation nor the names of its
  21. * contributors may be used to endorse or promote products derived
  22. * from this software without specific prior written permission.
  23. *
  24. * @copyright
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  28. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  29. * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  30. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  31. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  32. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  33. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  34. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
  35. * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  36. * POSSIBILITY OF SUCH DAMAGE.
  37. *
  38. **************************************************************************/
  39. /*
  40. * Cilk scheduler
  41. */
  42. #include "scheduler.h"
  43. #include "bug.h"
  44. #include "os.h"
  45. #include "os_mutex.h"
  46. #include "local_state.h"
  47. #include "signal_node.h"
  48. #include "full_frame.h"
  49. #include "sysdep.h"
  50. #include "except.h"
  51. #include "cilk_malloc.h"
  52. #include "pedigrees.h"
  53. #include "record-replay.h"
  54. #include <limits.h>
  55. #include <string.h> /* memcpy */
  56. #include <stdio.h> // sprintf
  57. #include <stdlib.h> // malloc, free, abort
  58. #ifdef _WIN32
  59. # pragma warning(disable:1786) // disable warning: sprintf is deprecated
  60. # include "sysdep-win.h"
  61. # include "except-win32.h"
  62. #endif // _WIN32
  63. // ICL: Don't complain about conversion from pointer to same-sized integral
  64. // type in __cilkrts_put_stack. That's why we're using ptrdiff_t
  65. #ifdef _WIN32
  66. # pragma warning(disable: 1684)
  67. #endif
  68. #include "cilk/cilk_api.h"
  69. #include "frame_malloc.h"
  70. #include "metacall_impl.h"
  71. #include "reducer_impl.h"
  72. #include "cilk-tbb-interop.h"
  73. #include "cilk-ittnotify.h"
  74. #include "stats.h"
  75. // ICL: Don't complain about loss of precision in myrand
  76. // I tried restoring the warning after the function, but it didn't
  77. // suppress it
  78. #ifdef _WIN32
  79. # pragma warning(disable: 2259)
  80. #endif
  81. #ifndef _WIN32
  82. # include <unistd.h>
  83. #endif
  84. #ifdef __VXWORKS__
  85. // redeclare longjmp() with noreturn to stop warnings
  86. extern __attribute__((noreturn))
  87. void longjmp(jmp_buf, int);
  88. #endif
  89. //#define DEBUG_LOCKS 1
  90. #ifdef DEBUG_LOCKS
  91. // The currently executing worker must own this worker's lock
  92. # define ASSERT_WORKER_LOCK_OWNED(w) \
  93. { \
  94. __cilkrts_worker *tls_worker = __cilkrts_get_tls_worker(); \
  95. CILK_ASSERT((w)->l->lock.owner == tls_worker); \
  96. }
  97. #else
  98. # define ASSERT_WORKER_LOCK_OWNED(w)
  99. #endif // DEBUG_LOCKS
  100. // Options for the scheduler.
  101. enum schedule_t { SCHEDULE_RUN,
  102. SCHEDULE_WAIT,
  103. SCHEDULE_EXIT };
  104. // Return values for provably_good_steal()
  105. enum provably_good_steal_t
  106. {
  107. ABANDON_EXECUTION, // Not the last child to the sync - attempt to steal work
  108. CONTINUE_EXECUTION, // Last child to the sync - continue executing on this worker
  109. WAIT_FOR_CONTINUE // The replay log indicates that this was the worker
  110. // which continued. Loop until we are the last worker
  111. // to the sync.
  112. };
  113. // Verify that "w" is the worker we are currently executing on.
  114. // Because this check is expensive, this method is usually a no-op.
  115. static inline void verify_current_wkr(__cilkrts_worker *w)
  116. {
  117. #if ((REDPAR_DEBUG >= 3) || (FIBER_DEBUG >= 1))
  118. // Lookup the worker from TLS and compare to w.
  119. __cilkrts_worker* tmp = __cilkrts_get_tls_worker();
  120. if (w != tmp) {
  121. fprintf(stderr, "Error. W=%d, actual worker =%d...\n",
  122. w->self,
  123. tmp->self);
  124. }
  125. CILK_ASSERT(w == tmp);
  126. #endif
  127. }
  128. static enum schedule_t worker_runnable(__cilkrts_worker *w);
  129. // Scheduling-fiber functions:
  130. static void do_return_from_spawn (__cilkrts_worker *w,
  131. full_frame *ff,
  132. __cilkrts_stack_frame *sf);
  133. static void do_sync (__cilkrts_worker *w,
  134. full_frame *ff,
  135. __cilkrts_stack_frame *sf);
  136. // max is defined on Windows and VxWorks
  137. #if (! defined(_WIN32)) && (! defined(__VXWORKS__))
  138. // TBD: definition of max() for Linux.
  139. # define max(a, b) ((a) < (b) ? (b) : (a))
  140. #endif
  141. void __cilkrts_dump_stats_to_stderr(global_state_t *g)
  142. {
  143. #ifdef CILK_PROFILE
  144. int i;
  145. for (i = 0; i < g->total_workers; ++i) {
  146. // Print out statistics for each worker. We collected them,
  147. // so why not print them out?
  148. fprintf(stderr, "Stats for worker %d\n", i);
  149. dump_stats_to_file(stderr, g->workers[i]->l->stats);
  150. __cilkrts_accum_stats(&g->stats, g->workers[i]->l->stats);
  151. }
  152. // Also print out aggregate statistics.
  153. dump_stats_to_file(stderr, &g->stats);
  154. #endif
  155. fprintf(stderr,
  156. "CILK PLUS Thread Info: P=%d, Q=%d\n",
  157. g->P,
  158. g->Q);
  159. fprintf(stderr,
  160. "CILK PLUS RUNTIME MEMORY USAGE: %lld bytes",
  161. (long long)g->frame_malloc.allocated_from_os);
  162. #ifdef CILK_PROFILE
  163. if (g->stats.stack_hwm)
  164. fprintf(stderr, ", %ld stacks", g->stats.stack_hwm);
  165. #endif
  166. fputc('\n', stderr);
  167. }
  168. static void validate_worker(__cilkrts_worker *w)
  169. {
  170. /* check the magic numbers, for debugging purposes */
  171. if (w->l->worker_magic_0 != WORKER_MAGIC_0 ||
  172. w->l->worker_magic_1 != WORKER_MAGIC_1)
  173. abort_because_rts_is_corrupted();
  174. }
  175. static void double_link(full_frame *left_ff, full_frame *right_ff)
  176. {
  177. if (left_ff)
  178. left_ff->right_sibling = right_ff;
  179. if (right_ff)
  180. right_ff->left_sibling = left_ff;
  181. }
  182. /* add CHILD to the right of all children of PARENT */
  183. static void push_child(full_frame *parent_ff, full_frame *child_ff)
  184. {
  185. double_link(parent_ff->rightmost_child, child_ff);
  186. double_link(child_ff, 0);
  187. parent_ff->rightmost_child = child_ff;
  188. }
  189. /* unlink CHILD from the list of all children of PARENT */
  190. static void unlink_child(full_frame *parent_ff, full_frame *child_ff)
  191. {
  192. double_link(child_ff->left_sibling, child_ff->right_sibling);
  193. if (!child_ff->right_sibling) {
  194. /* this is the rightmost child -- update parent link */
  195. CILK_ASSERT(parent_ff->rightmost_child == child_ff);
  196. parent_ff->rightmost_child = child_ff->left_sibling;
  197. }
  198. child_ff->left_sibling = child_ff->right_sibling = 0; /* paranoia */
  199. }
  200. static void incjoin(full_frame *ff)
  201. {
  202. ++ff->join_counter;
  203. }
  204. static int decjoin(full_frame *ff)
  205. {
  206. CILK_ASSERT(ff->join_counter > 0);
  207. return (--ff->join_counter);
  208. }
  209. static int simulate_decjoin(full_frame *ff)
  210. {
  211. CILK_ASSERT(ff->join_counter > 0);
  212. return (ff->join_counter - 1);
  213. }
  214. /*
  215. * Pseudo-random generator defined by the congruence S' = 69070 * S
  216. * mod (2^32 - 5). Marsaglia (CACM July 1993) says on page 107 that
  217. * this is a ``good one''. There you go.
  218. *
  219. * The literature makes a big fuss about avoiding the division, but
  220. * for us it is not worth the hassle.
  221. */
  222. static const unsigned RNGMOD = ((1ULL << 32) - 5);
  223. static const unsigned RNGMUL = 69070U;
  224. static unsigned myrand(__cilkrts_worker *w)
  225. {
  226. unsigned state = w->l->rand_seed;
  227. state = (unsigned)((RNGMUL * (unsigned long long)state) % RNGMOD);
  228. w->l->rand_seed = state;
  229. return state;
  230. }
  231. static void mysrand(__cilkrts_worker *w, unsigned seed)
  232. {
  233. seed %= RNGMOD;
  234. seed += (seed == 0); /* 0 does not belong to the multiplicative
  235. group. Use 1 instead */
  236. w->l->rand_seed = seed;
  237. }
  238. /* W grabs its own lock */
  239. void __cilkrts_worker_lock(__cilkrts_worker *w)
  240. {
  241. validate_worker(w);
  242. CILK_ASSERT(w->l->do_not_steal == 0);
  243. /* tell thieves to stay out of the way */
  244. w->l->do_not_steal = 1;
  245. __cilkrts_fence(); /* probably redundant */
  246. __cilkrts_mutex_lock(w, &w->l->lock);
  247. }
  248. void __cilkrts_worker_unlock(__cilkrts_worker *w)
  249. {
  250. __cilkrts_mutex_unlock(w, &w->l->lock);
  251. CILK_ASSERT(w->l->do_not_steal == 1);
  252. /* The fence is probably redundant. Use a release
  253. operation when supported (gcc and compatibile);
  254. that is faster on x86 which serializes normal stores. */
  255. #if defined __GNUC__ && (__GNUC__ * 10 + __GNUC_MINOR__ > 43 || __ICC >= 1110)
  256. __sync_lock_release(&w->l->do_not_steal);
  257. #else
  258. w->l->do_not_steal = 0;
  259. __cilkrts_fence(); /* store-store barrier, redundant on x86 */
  260. #endif
  261. }
  262. /* try to acquire the lock of some *other* worker */
  263. static int worker_trylock_other(__cilkrts_worker *w,
  264. __cilkrts_worker *other)
  265. {
  266. int status = 0;
  267. validate_worker(other);
  268. /* This protocol guarantees that, after setting the DO_NOT_STEAL
  269. flag, worker W can enter its critical section after waiting for
  270. the thief currently in the critical section (if any) and at
  271. most one other thief.
  272. This requirement is overly paranoid, but it should protect us
  273. against future nonsense from OS implementors.
  274. */
  275. /* compete for the right to disturb OTHER */
  276. if (__cilkrts_mutex_trylock(w, &other->l->steal_lock)) {
  277. if (other->l->do_not_steal) {
  278. /* leave it alone */
  279. } else {
  280. status = __cilkrts_mutex_trylock(w, &other->l->lock);
  281. }
  282. __cilkrts_mutex_unlock(w, &other->l->steal_lock);
  283. }
  284. return status;
  285. }
  286. static void worker_unlock_other(__cilkrts_worker *w,
  287. __cilkrts_worker *other)
  288. {
  289. __cilkrts_mutex_unlock(w, &other->l->lock);
  290. }
  291. /* Lock macro Usage:
  292. BEGIN_WITH_WORKER_LOCK(w) {
  293. statement;
  294. statement;
  295. BEGIN_WITH_FRAME_LOCK(w, ff) {
  296. statement;
  297. statement;
  298. } END_WITH_FRAME_LOCK(w, ff);
  299. } END_WITH_WORKER_LOCK(w);
  300. */
  301. #define BEGIN_WITH_WORKER_LOCK(w) __cilkrts_worker_lock(w); do
  302. #define END_WITH_WORKER_LOCK(w) while (__cilkrts_worker_unlock(w), 0)
  303. // TBD(jsukha): These are worker lock acquistions on
  304. // a worker whose deque is empty. My conjecture is that we
  305. // do not need to hold the worker lock at these points.
  306. // I have left them in for now, however.
  307. //
  308. // #define REMOVE_POSSIBLY_OPTIONAL_LOCKS
  309. #ifdef REMOVE_POSSIBLY_OPTIONAL_LOCKS
  310. #define BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) do
  311. #define END_WITH_WORKER_LOCK_OPTIONAL(w) while (0)
  312. #else
  313. #define BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) __cilkrts_worker_lock(w); do
  314. #define END_WITH_WORKER_LOCK_OPTIONAL(w) while (__cilkrts_worker_unlock(w), 0)
  315. #endif
  316. #define BEGIN_WITH_FRAME_LOCK(w, ff) \
  317. do { full_frame *_locked_ff = ff; __cilkrts_frame_lock(w, _locked_ff); do
  318. #define END_WITH_FRAME_LOCK(w, ff) \
  319. while (__cilkrts_frame_unlock(w, _locked_ff), 0); } while (0)
  320. /* W becomes the owner of F and F can be stolen from W */
  321. static void make_runnable(__cilkrts_worker *w, full_frame *ff)
  322. {
  323. w->l->frame_ff = ff;
  324. /* CALL_STACK is invalid (the information is stored implicitly in W) */
  325. ff->call_stack = 0;
  326. }
  327. /*
  328. * The worker parameter is unused, except for print-debugging purposes.
  329. */
  330. static void make_unrunnable(__cilkrts_worker *w,
  331. full_frame *ff,
  332. __cilkrts_stack_frame *sf,
  333. int is_loot,
  334. const char *why)
  335. {
  336. /* CALL_STACK becomes valid again */
  337. ff->call_stack = sf;
  338. if (sf) {
  339. #if CILK_LIB_DEBUG
  340. if (__builtin_expect(sf->flags & CILK_FRAME_EXITING, 0))
  341. __cilkrts_bug("W%d suspending exiting frame %p/%p\n", w->self, ff, sf);
  342. #endif
  343. sf->flags |= CILK_FRAME_STOLEN | CILK_FRAME_SUSPENDED;
  344. sf->worker = 0;
  345. if (is_loot)
  346. __cilkrts_put_stack(ff, sf);
  347. /* perform any system-dependent action, such as saving the
  348. state of the stack */
  349. __cilkrts_make_unrunnable_sysdep(w, ff, sf, is_loot, why);
  350. }
  351. }
  352. /* Push the next full frame to be made active in this worker and increment its
  353. * join counter. __cilkrts_push_next_frame and pop_next_frame work on a
  354. * one-element queue. This queue is used to communicate across the runtime
  355. * from the code that wants to activate a frame to the code that can actually
  356. * begin execution on that frame. They are asymetrical in that push
  357. * increments the join counter but pop does not decrement it. Rather, a
  358. * single push/pop combination makes a frame active and increments its join
  359. * counter once. */
  360. void __cilkrts_push_next_frame(__cilkrts_worker *w, full_frame *ff)
  361. {
  362. CILK_ASSERT(ff);
  363. CILK_ASSERT(!w->l->next_frame_ff);
  364. incjoin(ff);
  365. w->l->next_frame_ff = ff;
  366. }
  367. /* Get the next full-frame to be made active in this worker. The join count
  368. * of the full frame will have been incremented by the corresponding push
  369. * event. See __cilkrts_push_next_frame, above.
  370. */
  371. static full_frame *pop_next_frame(__cilkrts_worker *w)
  372. {
  373. full_frame *ff;
  374. ff = w->l->next_frame_ff;
  375. // Remove the frame from the next_frame field.
  376. //
  377. // If this is a user worker, then there is a chance that another worker
  378. // from our team could push work into our next_frame (if it is the last
  379. // worker doing work for this team). The other worker's setting of the
  380. // next_frame could race with our setting of next_frame to NULL. This is
  381. // the only possible race condition on next_frame. However, if next_frame
  382. // has a non-NULL value, then it means the team still has work to do, and
  383. // there is no chance of another team member populating next_frame. Thus,
  384. // it is safe to set next_frame to NULL, if it was populated. There is no
  385. // need for an atomic op.
  386. if (NULL != ff) {
  387. w->l->next_frame_ff = NULL;
  388. }
  389. return ff;
  390. }
  391. /*
  392. * Identify the single worker that is allowed to cross a sync in this frame. A
  393. * thief should call this function when it is the first to steal work from a
  394. * user worker. "First to steal work" may mean that there has been parallelism
  395. * in the user worker before, but the whole team sync'd, and this is the first
  396. * steal after that.
  397. *
  398. * This should happen while holding the worker and frame lock.
  399. */
  400. static void set_sync_master(__cilkrts_worker *w, full_frame *ff)
  401. {
  402. w->l->last_full_frame = ff;
  403. ff->sync_master = w;
  404. }
  405. /*
  406. * The sync that ends all parallelism for a particular user worker is about to
  407. * be crossed. Decouple the worker and frame.
  408. *
  409. * No locks need to be held since the user worker isn't doing anything, and none
  410. * of the system workers can steal from it. But unset_sync_master() should be
  411. * called before the user worker knows about this work (i.e., before it is
  412. * inserted into the w->l->next_frame_ff is set).
  413. */
  414. static void unset_sync_master(__cilkrts_worker *w, full_frame *ff)
  415. {
  416. CILK_ASSERT(WORKER_USER == w->l->type);
  417. CILK_ASSERT(ff->sync_master == w);
  418. ff->sync_master = NULL;
  419. w->l->last_full_frame = NULL;
  420. }
  421. /********************************************************************
  422. * THE protocol:
  423. ********************************************************************/
  424. /*
  425. * This is a protocol for work stealing that minimizes the overhead on
  426. * the victim.
  427. *
  428. * The protocol uses three shared pointers into the worker's deque:
  429. * - T - the "tail"
  430. * - H - the "head"
  431. * - E - the "exception" NB: In this case, "exception" has nothing to do
  432. * with C++ throw-catch exceptions -- it refers only to a non-normal return,
  433. * i.e., a steal or similar scheduling exception.
  434. *
  435. * with H <= E, H <= T.
  436. *
  437. * Stack frames SF, where H <= E < T, are available for stealing.
  438. *
  439. * The worker operates on the T end of the stack. The frame being
  440. * worked on is not on the stack. To make a continuation available for
  441. * stealing the worker pushes a from onto the stack: stores *T++ = SF.
  442. * To return, it pops the frame off the stack: obtains SF = *--T.
  443. *
  444. * After decrementing T, the condition E > T signals to the victim that
  445. * it should invoke the runtime system's "THE" exception handler. The
  446. * pointer E can become INFINITY, in which case the victim must invoke
  447. * the THE exception handler as soon as possible.
  448. *
  449. * See "The implementation of the Cilk-5 multithreaded language", PLDI 1998,
  450. * http://portal.acm.org/citation.cfm?doid=277652.277725, for more information
  451. * on the THE protocol.
  452. */
  453. /* the infinity value of E */
  454. #define EXC_INFINITY ((__cilkrts_stack_frame **) (-1))
  455. static void increment_E(__cilkrts_worker *victim)
  456. {
  457. __cilkrts_stack_frame *volatile *tmp;
  458. // The currently executing worker must own the worker lock to touch
  459. // victim->exc
  460. ASSERT_WORKER_LOCK_OWNED(victim);
  461. tmp = victim->exc;
  462. if (tmp != EXC_INFINITY) {
  463. /* On most x86 this pair of operations would be slightly faster
  464. as an atomic exchange due to the implicit memory barrier in
  465. an atomic instruction. */
  466. victim->exc = tmp + 1;
  467. __cilkrts_fence();
  468. }
  469. }
  470. static void decrement_E(__cilkrts_worker *victim)
  471. {
  472. __cilkrts_stack_frame *volatile *tmp;
  473. // The currently executing worker must own the worker lock to touch
  474. // victim->exc
  475. ASSERT_WORKER_LOCK_OWNED(victim);
  476. tmp = victim->exc;
  477. if (tmp != EXC_INFINITY) {
  478. /* On most x86 this pair of operations would be slightly faster
  479. as an atomic exchange due to the implicit memory barrier in
  480. an atomic instruction. */
  481. victim->exc = tmp - 1;
  482. __cilkrts_fence(); /* memory fence not really necessary */
  483. }
  484. }
  485. #if 0
  486. /* for now unused, will be necessary if we implement abort */
  487. static void signal_THE_exception(__cilkrts_worker *wparent)
  488. {
  489. wparent->exc = EXC_INFINITY;
  490. __cilkrts_fence();
  491. }
  492. #endif
  493. static void reset_THE_exception(__cilkrts_worker *w)
  494. {
  495. // The currently executing worker must own the worker lock to touch
  496. // w->exc
  497. ASSERT_WORKER_LOCK_OWNED(w);
  498. w->exc = w->head;
  499. __cilkrts_fence();
  500. }
  501. /* conditions under which victim->head can be stolen: */
  502. static int can_steal_from(__cilkrts_worker *victim)
  503. {
  504. return ((victim->head < victim->tail) &&
  505. (victim->head < victim->protected_tail));
  506. }
  507. /* Return TRUE if the frame can be stolen, false otherwise */
  508. static int dekker_protocol(__cilkrts_worker *victim)
  509. {
  510. // increment_E and decrement_E are going to touch victim->exc. The
  511. // currently executing worker must own victim's lock before they can
  512. // modify it
  513. ASSERT_WORKER_LOCK_OWNED(victim);
  514. /* ASSERT(E >= H); */
  515. increment_E(victim);
  516. /* ASSERT(E >= H + 1); */
  517. if (can_steal_from(victim)) {
  518. /* success, we can steal victim->head and set H <- H + 1
  519. in detach() */
  520. return 1;
  521. } else {
  522. /* failure, restore previous state */
  523. decrement_E(victim);
  524. return 0;
  525. }
  526. }
  527. /* Link PARENT and CHILD in the spawn tree */
  528. static full_frame *make_child(__cilkrts_worker *w,
  529. full_frame *parent_ff,
  530. __cilkrts_stack_frame *child_sf,
  531. cilk_fiber *fiber)
  532. {
  533. full_frame *child_ff = __cilkrts_make_full_frame(w, child_sf);
  534. child_ff->parent = parent_ff;
  535. push_child(parent_ff, child_ff);
  536. //DBGPRINTF("%d- make_child - child_frame: %p, parent_frame: %p, child_sf: %p\n"
  537. // " parent - parent: %p, left_sibling: %p, right_sibling: %p, rightmost_child: %p\n"
  538. // " child - parent: %p, left_sibling: %p, right_sibling: %p, rightmost_child: %p\n",
  539. // w->self, child, parent, child_sf,
  540. // parent->parent, parent->left_sibling, parent->right_sibling, parent->rightmost_child,
  541. // child->parent, child->left_sibling, child->right_sibling, child->rightmost_child);
  542. CILK_ASSERT(parent_ff->call_stack);
  543. child_ff->is_call_child = (fiber == NULL);
  544. /* PLACEHOLDER_FIBER is used as non-null marker indicating that
  545. child should be treated as a spawn child even though we have not
  546. yet assigned a real fiber to its parent. */
  547. if (fiber == PLACEHOLDER_FIBER)
  548. fiber = NULL; /* Parent actually gets a null fiber, for now */
  549. /* perform any system-dependent actions, such as capturing
  550. parameter passing information */
  551. /*__cilkrts_make_child_sysdep(child, parent);*/
  552. /* Child gets reducer map and stack of parent.
  553. Parent gets a new map and new stack. */
  554. child_ff->fiber_self = parent_ff->fiber_self;
  555. child_ff->sync_master = NULL;
  556. if (child_ff->is_call_child) {
  557. /* Cause segfault on any attempted access. The parent gets
  558. the child map and stack when the child completes. */
  559. parent_ff->fiber_self = 0;
  560. } else {
  561. parent_ff->fiber_self = fiber;
  562. }
  563. incjoin(parent_ff);
  564. return child_ff;
  565. }
  566. static inline __cilkrts_stack_frame *__cilkrts_advance_frame(__cilkrts_stack_frame *sf)
  567. {
  568. __cilkrts_stack_frame *p = sf->call_parent;
  569. sf->call_parent = 0;
  570. return p;
  571. }
  572. /* w should be the currently executing worker.
  573. * loot_sf is the youngest stack frame in the call stack being
  574. * unrolled (i.e., the most deeply nested stack frame.)
  575. *
  576. * When this method is called for a steal, loot_sf should be on a
  577. * victim worker which is different from w.
  578. * For CILK_FORCE_REDUCE, the victim worker will equal w.
  579. *
  580. * Before execution, the __cilkrts_stack_frame's have pointers from
  581. * older to younger, i.e., a __cilkrts_stack_frame points to parent.
  582. *
  583. * This method creates a full frame for each __cilkrts_stack_frame in
  584. * the call stack, with each full frame also pointing to its parent.
  585. *
  586. * The method returns the full frame created for loot_sf, i.e., the
  587. * youngest full frame.
  588. */
  589. static full_frame *unroll_call_stack(__cilkrts_worker *w,
  590. full_frame *ff,
  591. __cilkrts_stack_frame *const loot_sf)
  592. {
  593. __cilkrts_stack_frame *sf = loot_sf;
  594. __cilkrts_stack_frame *rev_sf = 0;
  595. __cilkrts_stack_frame *t_sf;
  596. CILK_ASSERT(sf);
  597. /*CILK_ASSERT(sf->call_parent != sf);*/
  598. /* The leafmost frame is unsynched. */
  599. if (sf->worker != w)
  600. sf->flags |= CILK_FRAME_UNSYNCHED;
  601. /* Reverse the call stack to make a linked list ordered from parent
  602. to child. sf->call_parent points to the child of SF instead of
  603. the parent. */
  604. do {
  605. t_sf = (sf->flags & (CILK_FRAME_DETACHED|CILK_FRAME_STOLEN|CILK_FRAME_LAST))? 0 : sf->call_parent;
  606. sf->call_parent = rev_sf;
  607. rev_sf = sf;
  608. sf = t_sf;
  609. } while (sf);
  610. sf = rev_sf;
  611. /* Promote each stack frame to a full frame in order from parent
  612. to child, following the reversed list we just built. */
  613. make_unrunnable(w, ff, sf, sf == loot_sf, "steal 1");
  614. /* T is the *child* of SF, because we have reversed the list */
  615. for (t_sf = __cilkrts_advance_frame(sf); t_sf;
  616. sf = t_sf, t_sf = __cilkrts_advance_frame(sf)) {
  617. ff = make_child(w, ff, t_sf, NULL);
  618. make_unrunnable(w, ff, t_sf, t_sf == loot_sf, "steal 2");
  619. }
  620. /* XXX What if the leafmost frame does not contain a sync
  621. and this steal is from promote own deque? */
  622. /*sf->flags |= CILK_FRAME_UNSYNCHED;*/
  623. CILK_ASSERT(!sf->call_parent);
  624. return ff;
  625. }
  626. /* detach the top of the deque frame from the VICTIM and install a new
  627. CHILD frame in its place */
  628. static void detach_for_steal(__cilkrts_worker *w,
  629. __cilkrts_worker *victim,
  630. cilk_fiber* fiber)
  631. {
  632. /* ASSERT: we own victim->lock */
  633. full_frame *parent_ff, *child_ff, *loot_ff;
  634. __cilkrts_stack_frame *volatile *h;
  635. __cilkrts_stack_frame *sf;
  636. w->l->team = victim->l->team;
  637. CILK_ASSERT(w->l->frame_ff == 0 || w == victim);
  638. h = victim->head;
  639. CILK_ASSERT(*h);
  640. victim->head = h + 1;
  641. parent_ff = victim->l->frame_ff;
  642. BEGIN_WITH_FRAME_LOCK(w, parent_ff) {
  643. /* parent no longer referenced by victim */
  644. decjoin(parent_ff);
  645. /* obtain the victim call stack */
  646. sf = *h;
  647. /* perform system-dependent normalizations */
  648. /*__cilkrts_normalize_call_stack_on_steal(sf);*/
  649. /* unroll PARENT_FF with call stack SF, adopt the youngest
  650. frame LOOT. If loot_ff == parent_ff, then we hold loot_ff->lock,
  651. otherwise, loot_ff is newly created and we can modify it without
  652. holding its lock. */
  653. loot_ff = unroll_call_stack(w, parent_ff, sf);
  654. #if REDPAR_DEBUG >= 3
  655. fprintf(stderr, "[W=%d, victim=%d, desc=detach, parent_ff=%p, loot=%p]\n",
  656. w->self, victim->self,
  657. parent_ff, loot_ff);
  658. #endif
  659. if (WORKER_USER == victim->l->type &&
  660. NULL == victim->l->last_full_frame) {
  661. // Mark this looted frame as special: only the original user worker
  662. // may cross the sync.
  663. //
  664. // This call is a shared access to
  665. // victim->l->last_full_frame.
  666. set_sync_master(victim, loot_ff);
  667. }
  668. /* LOOT is the next frame that the thief W is supposed to
  669. run, unless the thief is stealing from itself, in which
  670. case the thief W == VICTIM executes CHILD and nobody
  671. executes LOOT. */
  672. if (w == victim) {
  673. /* Pretend that frame has been stolen */
  674. loot_ff->call_stack->flags |= CILK_FRAME_UNSYNCHED;
  675. loot_ff->simulated_stolen = 1;
  676. }
  677. else
  678. __cilkrts_push_next_frame(w, loot_ff);
  679. // After this "push_next_frame" call, w now owns loot_ff.
  680. child_ff = make_child(w, loot_ff, 0, fiber);
  681. BEGIN_WITH_FRAME_LOCK(w, child_ff) {
  682. /* install child in the victim's work queue, taking
  683. the parent_ff's place */
  684. /* child is referenced by victim */
  685. incjoin(child_ff);
  686. // With this call, w is bestowing ownership of the newly
  687. // created frame child_ff to the victim, and victim is
  688. // giving up ownership of parent_ff.
  689. //
  690. // Worker w will either take ownership of parent_ff
  691. // if parent_ff == loot_ff, or parent_ff will be
  692. // suspended.
  693. //
  694. // Note that this call changes the victim->frame_ff
  695. // while the victim may be executing.
  696. make_runnable(victim, child_ff);
  697. } END_WITH_FRAME_LOCK(w, child_ff);
  698. } END_WITH_FRAME_LOCK(w, parent_ff);
  699. }
  700. /**
  701. * @brief cilk_fiber_proc that resumes user code after a successful
  702. * random steal.
  703. * This function longjmps back into the user code whose state is
  704. * stored in cilk_fiber_get_data(fiber)->resume_sf. The stack pointer
  705. * is adjusted so that the code resumes on the specified fiber stack
  706. * instead of its original stack.
  707. *
  708. * This method gets executed only on a fiber freshly allocated from a
  709. * pool.
  710. *
  711. * @param fiber The fiber being used to resume user code.
  712. * @param arg Unused.
  713. */
  714. static
  715. void fiber_proc_to_resume_user_code_for_random_steal(cilk_fiber *fiber)
  716. {
  717. cilk_fiber_data *data = cilk_fiber_get_data(fiber);
  718. __cilkrts_stack_frame* sf = data->resume_sf;
  719. full_frame *ff;
  720. CILK_ASSERT(sf);
  721. // When we pull the resume_sf out of the fiber to resume it, clear
  722. // the old value.
  723. data->resume_sf = NULL;
  724. CILK_ASSERT(sf->worker == data->owner);
  725. ff = sf->worker->l->frame_ff;
  726. // For Win32, we need to overwrite the default exception handler
  727. // in this function, so that when the OS exception handling code
  728. // walks off the top of the current Cilk stack, it reaches our stub
  729. // handler.
  730. // Also, this function needs to be wrapped into a try-catch block
  731. // so the compiler generates the appropriate exception information
  732. // in this frame.
  733. // TBD: IS THIS HANDLER IN THE WRONG PLACE? Can we longjmp out of
  734. // this function (and does it matter?)
  735. #if defined(_WIN32) && !defined(_WIN64)
  736. install_exception_stub_handler();
  737. __try
  738. #endif
  739. {
  740. char* new_sp = sysdep_reset_jump_buffers_for_resume(fiber, ff, sf);
  741. // Notify the Intel tools that we're stealing code
  742. ITT_SYNC_ACQUIRED(sf->worker);
  743. NOTIFY_ZC_INTRINSIC("cilk_continue", sf);
  744. // TBD: We'd like to move TBB-interop methods into the fiber
  745. // eventually.
  746. cilk_fiber_invoke_tbb_stack_op(fiber, CILK_TBB_STACK_ADOPT);
  747. sf->flags &= ~CILK_FRAME_SUSPENDED;
  748. // longjmp to user code. Don't process exceptions here,
  749. // because we are resuming a stolen frame.
  750. sysdep_longjmp_to_sf(new_sp, sf, NULL);
  751. /*NOTREACHED*/
  752. // Intel's C compiler respects the preceding lint pragma
  753. }
  754. #if defined(_WIN32) && !defined(_WIN64)
  755. __except (CILK_ASSERT(!"should not execute the the stub filter"),
  756. EXCEPTION_EXECUTE_HANDLER)
  757. {
  758. // If we are here, that means something very wrong
  759. // has happened in our exception processing...
  760. CILK_ASSERT(! "should not be here!");
  761. }
  762. #endif
  763. }
  764. static void random_steal(__cilkrts_worker *w)
  765. {
  766. __cilkrts_worker *victim = NULL;
  767. cilk_fiber *fiber = NULL;
  768. int n;
  769. int success = 0;
  770. int32_t victim_id;
  771. // Nothing's been stolen yet. When true, this will flag
  772. // setup_for_execution_pedigree to increment the pedigree
  773. w->l->work_stolen = 0;
  774. /* If the user has disabled stealing (using the debugger) we fail */
  775. if (__builtin_expect(w->g->stealing_disabled, 0))
  776. return;
  777. CILK_ASSERT(w->l->type == WORKER_SYSTEM || w->l->team == w);
  778. /* If there is only one processor work can still be stolen.
  779. There must be only one worker to prevent stealing. */
  780. CILK_ASSERT(w->g->total_workers > 1);
  781. /* pick random *other* victim */
  782. n = myrand(w) % (w->g->total_workers - 1);
  783. if (n >= w->self)
  784. ++n;
  785. // If we're replaying a log, override the victim. -1 indicates that
  786. // we've exhausted the list of things this worker stole when we recorded
  787. // the log so just return. If we're not replaying a log,
  788. // replay_get_next_recorded_victim() just returns the victim ID passed in.
  789. n = replay_get_next_recorded_victim(w, n);
  790. if (-1 == n)
  791. return;
  792. victim = w->g->workers[n];
  793. START_INTERVAL(w, INTERVAL_FIBER_ALLOCATE) {
  794. /* Verify that we can get a stack. If not, no need to continue. */
  795. fiber = cilk_fiber_allocate(&w->l->fiber_pool);
  796. } STOP_INTERVAL(w, INTERVAL_FIBER_ALLOCATE);
  797. if (NULL == fiber) {
  798. #if FIBER_DEBUG >= 2
  799. fprintf(stderr, "w=%d: failed steal because we could not get a fiber\n",
  800. w->self);
  801. #endif
  802. return;
  803. }
  804. /* do not steal from self */
  805. CILK_ASSERT (victim != w);
  806. /* Execute a quick check before engaging in the THE protocol.
  807. Avoid grabbing locks if there is nothing to steal. */
  808. if (!can_steal_from(victim)) {
  809. NOTE_INTERVAL(w, INTERVAL_STEAL_FAIL_EMPTYQ);
  810. START_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE) {
  811. int ref_count = cilk_fiber_remove_reference(fiber, &w->l->fiber_pool);
  812. // Fibers we use when trying to steal should not be active,
  813. // and thus should not have any other references.
  814. CILK_ASSERT(0 == ref_count);
  815. } STOP_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE);
  816. return;
  817. }
  818. /* Attempt to steal work from the victim */
  819. if (worker_trylock_other(w, victim)) {
  820. if (w->l->type == WORKER_USER && victim->l->team != w) {
  821. // Fail to steal if this is a user worker and the victim is not
  822. // on this team. If a user worker were allowed to steal work
  823. // descended from another user worker, the former might not be
  824. // done with its work by the time it was needed to resume and
  825. // unbind. Therefore, user workers are not permitted to change
  826. // teams.
  827. // There is no race on the victim's team because the victim cannot
  828. // change its team until it runs out of work to do, at which point
  829. // it will try to take out its own lock, and this worker already
  830. // holds it.
  831. NOTE_INTERVAL(w, INTERVAL_STEAL_FAIL_USER_WORKER);
  832. } else if (victim->l->frame_ff) {
  833. // A successful steal will change victim->frame_ff, even
  834. // though the victim may be executing. Thus, the lock on
  835. // the victim's deque is also protecting victim->frame_ff.
  836. if (dekker_protocol(victim)) {
  837. int proceed_with_steal = 1; // optimistic
  838. // If we're replaying a log, verify that this the correct frame
  839. // to steal from the victim
  840. if (! replay_match_victim_pedigree(w, victim))
  841. {
  842. // Abort the steal attempt. decrement_E(victim) to
  843. // counter the increment_E(victim) done by the
  844. // dekker protocol
  845. decrement_E(victim);
  846. proceed_with_steal = 0;
  847. }
  848. if (proceed_with_steal)
  849. {
  850. START_INTERVAL(w, INTERVAL_STEAL_SUCCESS) {
  851. success = 1;
  852. detach_for_steal(w, victim, fiber);
  853. victim_id = victim->self;
  854. #if REDPAR_DEBUG >= 1
  855. fprintf(stderr, "Wkr %d stole from victim %d, fiber = %p\n",
  856. w->self, victim->self, fiber);
  857. #endif
  858. // The use of victim->self contradicts our
  859. // classification of the "self" field as
  860. // local. But since this code is only for
  861. // debugging, it is ok.
  862. DBGPRINTF ("%d-%p: Stealing work from worker %d\n"
  863. " sf: %p, call parent: %p\n",
  864. w->self, GetCurrentFiber(), victim->self,
  865. w->l->next_frame_ff->call_stack,
  866. w->l->next_frame_ff->call_stack->call_parent);
  867. } STOP_INTERVAL(w, INTERVAL_STEAL_SUCCESS);
  868. } // end if(proceed_with_steal)
  869. } else {
  870. NOTE_INTERVAL(w, INTERVAL_STEAL_FAIL_DEKKER);
  871. }
  872. } else {
  873. NOTE_INTERVAL(w, INTERVAL_STEAL_FAIL_EMPTYQ);
  874. }
  875. worker_unlock_other(w, victim);
  876. } else {
  877. NOTE_INTERVAL(w, INTERVAL_STEAL_FAIL_LOCK);
  878. }
  879. // Record whether work was stolen. When true, this will flag
  880. // setup_for_execution_pedigree to increment the pedigree
  881. w->l->work_stolen = success;
  882. if (0 == success) {
  883. // failed to steal work. Return the fiber to the pool.
  884. START_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE) {
  885. int ref_count = cilk_fiber_remove_reference(fiber, &w->l->fiber_pool);
  886. // Fibers we use when trying to steal should not be active,
  887. // and thus should not have any other references.
  888. CILK_ASSERT(0 == ref_count);
  889. } STOP_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE);
  890. }
  891. else
  892. {
  893. // Since our steal was successful, finish initialization of
  894. // the fiber.
  895. cilk_fiber_reset_state(fiber,
  896. fiber_proc_to_resume_user_code_for_random_steal);
  897. // Record the pedigree of the frame that w has stolen.
  898. // record only if CILK_RECORD_LOG is set
  899. replay_record_steal(w, victim_id);
  900. }
  901. }
  902. /**
  903. * At a provably good steal, we need to transfer the child reducer map
  904. * from ff->children_reducer_map into v->reducer_map, where v is the
  905. * worker that resumes execution of ff.
  906. *
  907. * Normally, we have v == w, where w is the currently executing
  908. * worker. In the case where we are resuming a team leader on a user
  909. * worker, however, v might differ from w.
  910. * Thus, this, operation is a no-op, since we can't really move
  911. * ff->children_reducer_map into w here.
  912. *
  913. * Instead, this work is done in setup_for_execution_reducers().
  914. */
  915. static inline void provably_good_steal_reducers(__cilkrts_worker *w,
  916. full_frame *ff)
  917. {
  918. // No-op.
  919. }
  920. /* at a provably good steal, incorporate the accumulated exceptions of
  921. children into the parent's exception */
  922. static void provably_good_steal_exceptions(__cilkrts_worker *w,
  923. full_frame *ff)
  924. {
  925. // ASSERT: we own ff->lock
  926. ff->pending_exception =
  927. __cilkrts_merge_pending_exceptions(w,
  928. ff->child_pending_exception,
  929. ff->pending_exception);
  930. ff->child_pending_exception = NULL;
  931. }
  932. /* At sync discard the frame's old stack and take the leftmost child's. */
  933. static void provably_good_steal_stacks(__cilkrts_worker *w, full_frame *ff)
  934. {
  935. CILK_ASSERT(NULL == ff->fiber_self);
  936. ff->fiber_self = ff->fiber_child;
  937. ff->fiber_child = NULL;
  938. }
  939. static void __cilkrts_mark_synched(full_frame *ff)
  940. {
  941. ff->call_stack->flags &= ~CILK_FRAME_UNSYNCHED;
  942. ff->simulated_stolen = 0;
  943. }
  944. static
  945. enum provably_good_steal_t provably_good_steal(__cilkrts_worker *w,
  946. full_frame *ff)
  947. {
  948. // ASSERT: we hold w->lock and ff->lock
  949. enum provably_good_steal_t result = ABANDON_EXECUTION;
  950. // If the current replay entry is a sync record matching the worker's
  951. // pedigree, AND this isn't the last child to the sync, return
  952. // WAIT_FOR_CONTINUE to indicate that the caller should loop until
  953. // we find the right frame to steal and CONTINUE_EXECUTION is returned.
  954. int match_found = replay_match_sync_pedigree(w);
  955. if (match_found && (0 != simulate_decjoin(ff)))
  956. return WAIT_FOR_CONTINUE;
  957. START_INTERVAL(w, INTERVAL_PROVABLY_GOOD_STEAL) {
  958. if (decjoin(ff) == 0) {
  959. provably_good_steal_reducers(w, ff);
  960. provably_good_steal_exceptions(w, ff);
  961. provably_good_steal_stacks(w, ff);
  962. __cilkrts_mark_synched(ff);
  963. // If the original owner wants this frame back (to resume
  964. // it on its original thread) pass it back now.
  965. if (NULL != ff->sync_master) {
  966. // The frame wants to go back and be executed by the original
  967. // user thread. We can throw caution to the wind and push the
  968. // frame straight onto its queue because the only way we have
  969. // gotten to this point of being able to continue execution of
  970. // the frame is if the original user worker is spinning without
  971. // work.
  972. unset_sync_master(w->l->team, ff);
  973. __cilkrts_push_next_frame(w->l->team, ff);
  974. // If this is the team leader we're not abandoning the work
  975. if (w == w->l->team)
  976. result = CONTINUE_EXECUTION;
  977. } else {
  978. __cilkrts_push_next_frame(w, ff);
  979. result = CONTINUE_EXECUTION; // Continue working on this thread
  980. }
  981. // The __cilkrts_push_next_frame() call changes ownership
  982. // of ff to the specified worker.
  983. }
  984. } STOP_INTERVAL(w, INTERVAL_PROVABLY_GOOD_STEAL);
  985. // Only write a SYNC record if:
  986. // - We're recording a log *AND*
  987. // - We're the worker continuing from this sync
  988. replay_record_sync(w, result == CONTINUE_EXECUTION);
  989. // If we're replaying a log, and matched a sync from the log, mark the
  990. // sync record seen if the sync isn't going to be abandoned.
  991. replay_advance_from_sync (w, match_found, result == CONTINUE_EXECUTION);
  992. return result;
  993. }
  994. static void unconditional_steal(__cilkrts_worker *w,
  995. full_frame *ff)
  996. {
  997. // ASSERT: we hold ff->lock
  998. START_INTERVAL(w, INTERVAL_UNCONDITIONAL_STEAL) {
  999. decjoin(ff);
  1000. __cilkrts_push_next_frame(w, ff);
  1001. } STOP_INTERVAL(w, INTERVAL_UNCONDITIONAL_STEAL);
  1002. }
  1003. /* CHILD is about to die. Give its exceptions to a sibling or to the
  1004. parent. */
  1005. static inline void splice_exceptions_for_call(__cilkrts_worker *w,
  1006. full_frame *parent_ff,
  1007. full_frame *child_ff)
  1008. {
  1009. // ASSERT: We own parent_ff->lock
  1010. CILK_ASSERT(child_ff->is_call_child);
  1011. CILK_ASSERT(NULL == child_ff->right_pending_exception);
  1012. CILK_ASSERT(NULL == parent_ff->pending_exception);
  1013. parent_ff->pending_exception = child_ff->pending_exception;
  1014. child_ff->pending_exception = NULL;
  1015. }
  1016. /**
  1017. * Merge exceptions for a dying child.
  1018. *
  1019. * @param w The currently executing worker.
  1020. * @param ff The child frame that is dying.
  1021. * @param left_exception_ptr Pointer to the exception that is to our left.
  1022. */
  1023. static inline
  1024. void splice_exceptions_for_spawn(__cilkrts_worker *w,
  1025. full_frame *ff,
  1026. struct pending_exception_info **left_exception_ptr)
  1027. {
  1028. // ASSERT: parent_ff == child_ff->parent.
  1029. // ASSERT: We own parent_ff->lock
  1030. // Merge current exception into the slot where the left
  1031. // exception should go.
  1032. *left_exception_ptr =
  1033. __cilkrts_merge_pending_exceptions(w,
  1034. *left_exception_ptr,
  1035. ff->pending_exception);
  1036. ff->pending_exception = NULL;
  1037. // Merge right exception into the slot where the left exception
  1038. // should go.
  1039. *left_exception_ptr =
  1040. __cilkrts_merge_pending_exceptions(w,
  1041. *left_exception_ptr,
  1042. ff->right_pending_exception);
  1043. ff->right_pending_exception = NULL;
  1044. }
  1045. static inline void splice_stacks_for_call(__cilkrts_worker *w,
  1046. full_frame *parent_ff,
  1047. full_frame *child_ff)
  1048. {
  1049. #if CILK_LIB_DEBUG
  1050. if (parent_ff->call_stack)
  1051. CILK_ASSERT(!(parent_ff->call_stack->flags & CILK_FRAME_MBZ));
  1052. #endif
  1053. /* A synched frame does not have accumulated child reducers. */
  1054. CILK_ASSERT(!child_ff->fiber_child);
  1055. CILK_ASSERT(child_ff->is_call_child);
  1056. /* An attached parent has no self fiber. It may have
  1057. accumulated child fibers or child owners, which should be
  1058. ignored until sync. */
  1059. CILK_ASSERT(!parent_ff->fiber_self);
  1060. parent_ff->fiber_self = child_ff->fiber_self;
  1061. child_ff->fiber_self = NULL;
  1062. }
  1063. static void finalize_child_for_call(__cilkrts_worker *w,
  1064. full_frame *parent_ff,
  1065. full_frame *child_ff)
  1066. {
  1067. // ASSERT: we hold w->lock and parent_ff->lock
  1068. START_INTERVAL(w, INTERVAL_FINALIZE_CHILD) {
  1069. CILK_ASSERT(child_ff->is_call_child);
  1070. CILK_ASSERT(child_ff->join_counter == 0);
  1071. CILK_ASSERT(!child_ff->rightmost_child);
  1072. CILK_ASSERT(child_ff == parent_ff->rightmost_child);
  1073. // CHILD is about to die.
  1074. // Splicing out reducers is a no-op for a call since
  1075. // w->reducer_map should already store the correct
  1076. // reducer map.
  1077. // ASSERT there are no maps left to reduce.
  1078. CILK_ASSERT(NULL == child_ff->children_reducer_map);
  1079. CILK_ASSERT(NULL == child_ff->right_reducer_map);
  1080. splice_exceptions_for_call(w, parent_ff, child_ff);
  1081. splice_stacks_for_call(w, parent_ff, child_ff);
  1082. /* remove CHILD from list of children of PARENT */
  1083. unlink_child(parent_ff, child_ff);
  1084. /* continue with the parent. */
  1085. unconditional_steal(w, parent_ff);
  1086. __cilkrts_destroy_full_frame(w, child_ff);
  1087. } STOP_INTERVAL(w, INTERVAL_FINALIZE_CHILD);
  1088. }
  1089. /**
  1090. * The invariant on ff->children_reducer_map is that when ff is
  1091. * synched and when we are about to resume execution of ff, at least
  1092. * one of ff->children_reducer_map and w->reducer_map must be NULL.
  1093. *
  1094. * Consider the two possibilities before resuming execution of ff:
  1095. *
  1096. * 1. Suppose ff is synched and suspended. Then either
  1097. *
  1098. * (a) ff->children_reducer_map stores the reducer map that w
  1099. * should use, where w is the worker resuming execution of ff,
  1100. * OR
  1101. * (b) w already has a user map, and ff->children_reducer_map is NULL.
  1102. *
  1103. * Case (a) happens when we are resuming execution of ff as a
  1104. * provably good steal. In this case, w->reducer_map should be
  1105. * NULL and ff->children_reducer_map is valid. To resume
  1106. * execution of ff on w, set w->reducer_map to
  1107. * ff->children_reducer_map.
  1108. *
  1109. * Case (b) occurs when we resume execution of ff because ff is a
  1110. * called child. Then, ff->children_reducer_map should be NULL,
  1111. * and w should already have a valid reducer map when resuming
  1112. * execution of ff. We resume execution of ff without changing
  1113. * w->reducer_map.
  1114. *
  1115. * 2. Suppose frame ff is not synched (i.e., it is active and might have
  1116. * active children). Then ff->children_reducer_map is the slot for
  1117. * storing the reducer map from ff's leftmost child, as in the reducer
  1118. * protocol. The runtime may resume execution of ff while it is not
  1119. * synched only because of a steal.
  1120. * In this case, while we are resuming ff, ff->children_reducer_map
  1121. * may be non-NULL (because one of ff's children has completed).
  1122. * We resume execution of ff without changing w->reducer_map.
  1123. */
  1124. static void setup_for_execution_reducers(__cilkrts_worker *w,
  1125. full_frame *ff)
  1126. {
  1127. // We only need to move ff->children_reducer_map into
  1128. // w->reducer_map in case 1(a).
  1129. //
  1130. // First check whether ff is synched.
  1131. __cilkrts_stack_frame *sf = ff->call_stack;
  1132. if (!(sf->flags & CILK_FRAME_UNSYNCHED)) {
  1133. // In this case, ff is synched. (Case 1).
  1134. CILK_ASSERT(!ff->rightmost_child);
  1135. // Test whether we are in case 1(a) and have
  1136. // something to do. Note that if both
  1137. // ff->children_reducer_map and w->reducer_map are NULL, we
  1138. // can't distinguish between cases 1(a) and 1(b) here.
  1139. if (ff->children_reducer_map) {
  1140. // We are in Case 1(a).
  1141. CILK_ASSERT(!w->reducer_map);
  1142. w->reducer_map = ff->children_reducer_map;
  1143. ff->children_reducer_map = NULL;
  1144. }
  1145. }
  1146. }
  1147. static void setup_for_execution_exceptions(__cilkrts_worker *w,
  1148. full_frame *ff)
  1149. {
  1150. CILK_ASSERT(NULL == w->l->pending_exception);
  1151. w->l->pending_exception = ff->pending_exception;
  1152. ff->pending_exception = NULL;
  1153. }
  1154. #if 0 /* unused */
  1155. static void setup_for_execution_stack(__cilkrts_worker *w,
  1156. full_frame *ff)
  1157. {
  1158. }
  1159. #endif
  1160. /*
  1161. * setup_for_execution_pedigree
  1162. *
  1163. * Copies the pedigree information from the frame we're resuming to the
  1164. * worker. Increments the pedigree if this is work that has been stolen
  1165. * to match the increment on a return from a spawn helper.
  1166. */
  1167. static void setup_for_execution_pedigree(__cilkrts_worker *w)
  1168. {
  1169. int pedigree_unsynched;
  1170. __cilkrts_stack_frame *sf = w->current_stack_frame;
  1171. CILK_ASSERT(NULL != sf);
  1172. // If this isn't an ABI 1 or later frame, there's no pedigree information
  1173. if (0 == CILK_FRAME_VERSION_VALUE(sf->flags))
  1174. return;
  1175. // Note whether the pedigree is unsynched and clear the flag before
  1176. // we forget
  1177. pedigree_unsynched = sf->flags & CILK_FRAME_SF_PEDIGREE_UNSYNCHED;
  1178. sf->flags &= ~CILK_FRAME_SF_PEDIGREE_UNSYNCHED;
  1179. // If we're just marshalling onto this worker, do not increment
  1180. // the rank since that wouldn't happen in a sequential execution
  1181. if (w->l->work_stolen || pedigree_unsynched)
  1182. {
  1183. if (w->l->work_stolen)
  1184. w->pedigree.rank = sf->parent_pedigree.rank + 1;
  1185. else
  1186. w->pedigree.rank = sf->parent_pedigree.rank;
  1187. }
  1188. w->pedigree.parent = sf->parent_pedigree.parent;
  1189. w->l->work_stolen = 0;
  1190. }
  1191. static void setup_for_execution(__cilkrts_worker *w,
  1192. full_frame *ff,
  1193. int is_return_from_call)
  1194. {
  1195. // ASSERT: We own w->lock and ff->lock || P == 1
  1196. setup_for_execution_reducers(w, ff);
  1197. setup_for_execution_exceptions(w, ff);
  1198. /*setup_for_execution_stack(w, ff);*/
  1199. ff->call_stack->worker = w;
  1200. w->current_stack_frame = ff->call_stack;
  1201. // If this is a return from a call, leave the pedigree alone
  1202. if (! is_return_from_call)
  1203. setup_for_execution_pedigree(w);
  1204. __cilkrts_setup_for_execution_sysdep(w, ff);
  1205. w->head = w->tail = w->l->ltq;
  1206. reset_THE_exception(w);
  1207. make_runnable(w, ff);
  1208. }
  1209. /*
  1210. * Called by the scheduling fiber, right before
  1211. * resuming a sf/ff for user code.
  1212. *
  1213. * This method associates the specified sf with the worker.
  1214. *
  1215. * It also asserts that w, ff, and sf all have the expected properties
  1216. * for resuming user code.
  1217. */
  1218. void scheduling_fiber_prepare_to_resume_user_code(__cilkrts_worker *w,
  1219. full_frame *ff,
  1220. __cilkrts_stack_frame *sf)
  1221. {
  1222. w->current_stack_frame = sf;
  1223. sf->worker = w;
  1224. // Lots of debugging checks on the state of the fiber we might be
  1225. // resuming.
  1226. #if FIBER_DEBUG >= 1
  1227. # if FIBER_DEBUG >= 3
  1228. {
  1229. fprintf(stderr, "w=%d: ff=%p, sf=%p. about to resume user code\n",
  1230. w->self, ff, sf);
  1231. }
  1232. # endif
  1233. const int flags = sf->flags;
  1234. CILK_ASSERT(flags & CILK_FRAME_SUSPENDED);
  1235. CILK_ASSERT(!sf->call_parent);
  1236. CILK_ASSERT(w->head == w->tail);
  1237. /* A frame can not be resumed unless it was suspended. */
  1238. CILK_ASSERT(ff->sync_sp != NULL);
  1239. /* The leftmost frame has no allocated stack */
  1240. if (ff->simulated_stolen)
  1241. CILK_ASSERT(flags & CILK_FRAME_UNSYNCHED);
  1242. else if (flags & CILK_FRAME_UNSYNCHED)
  1243. /* XXX By coincidence sync_sp could be null. */
  1244. CILK_ASSERT(ff->fiber_self != NULL);
  1245. else
  1246. /* XXX This frame could be resumed unsynched on the leftmost stack */
  1247. CILK_ASSERT((ff->sync_master == 0 || ff->sync_master == w));
  1248. CILK_ASSERT(w->l->frame_ff == ff);
  1249. #endif
  1250. }
  1251. /**
  1252. * This method is the first method that should execute after we've
  1253. * switched to a scheduling fiber from user code.
  1254. *
  1255. * @param fiber The scheduling fiber for the current worker.
  1256. * @param wptr The current worker.
  1257. */
  1258. static void enter_runtime_transition_proc(cilk_fiber *fiber)
  1259. {
  1260. // We can execute this method for one of three reasons:
  1261. // 1. Undo-detach finds parent stolen.
  1262. // 2. Sync suspends frame.
  1263. // 3. Return from Cilk entry point.
  1264. //
  1265. //
  1266. // In cases 1 and 2, the frame may be truly suspended or
  1267. // may be immediately executed by this worker after provably_good_steal.
  1268. //
  1269. //
  1270. // There is a fourth case, which can, but does not need to execute
  1271. // this function:
  1272. // 4. Starting up the scheduling loop on a user or
  1273. // system worker. In this case, we won't have
  1274. // a scheduling stack function to run.
  1275. __cilkrts_worker* w = cilk_fiber_get_owner(fiber);
  1276. if (w->l->post_suspend) {
  1277. // Run the continuation function passed to longjmp_into_runtime
  1278. run_scheduling_stack_fcn(w);
  1279. // After we have jumped into the runtime and run the
  1280. // scheduling function, any reducer map the worker had before entering the runtime
  1281. // should have already been saved into the appropriate full
  1282. // frame.
  1283. CILK_ASSERT(NULL == w->reducer_map);
  1284. // There shouldn't be any uncaught exceptions.
  1285. //
  1286. // In Windows, the OS catches any exceptions not caught by the
  1287. // user code. Thus, we are omitting the check on Windows.
  1288. //
  1289. // On Android, calling std::uncaught_exception with the stlport
  1290. // library causes a seg fault. Since we're not supporting
  1291. // exceptions there at this point, just don't do the check
  1292. //
  1293. // TBD: Is this check also safe to do on Windows?
  1294. CILKBUG_ASSERT_NO_UNCAUGHT_EXCEPTION();
  1295. }
  1296. }
  1297. /**
  1298. * Method called to jump back to executing user code.
  1299. *
  1300. * A normal return from the runtime back to resuming user code calls
  1301. * this method. A computation executed using force_reduce also calls
  1302. * this method to return to user code.
  1303. *
  1304. * This function should not contain any code that depends on a fiber.
  1305. * In a force-reduce case, the user worker may not have a fiber. In
  1306. * the force-reduce case, we call this method directly instead of
  1307. * calling @c user_code_resume_after_switch_into_runtime.
  1308. */
  1309. static inline NORETURN
  1310. cilkrts_resume(__cilkrts_stack_frame *sf, full_frame *ff)
  1311. {
  1312. // Save the sync stack pointer, and do the bookkeeping
  1313. char* sync_sp = ff->sync_sp;
  1314. __cilkrts_take_stack(ff, sync_sp); // leaves ff->sync_sp null
  1315. sf->flags &= ~CILK_FRAME_SUSPENDED;
  1316. // Actually longjmp to the user code.
  1317. // We may have exceptions to deal with, since we are resuming
  1318. // a previous-suspended frame.
  1319. sysdep_longjmp_to_sf(sync_sp, sf, ff);
  1320. }
  1321. /**
  1322. * Called by the user-code fiber right before resuming a full frame
  1323. * (sf/ff).
  1324. *
  1325. * This method pulls sf/ff out of the worker, and then calls
  1326. * cilkrts_resume to jump to user code.
  1327. */
  1328. static NORETURN
  1329. user_code_resume_after_switch_into_runtime(cilk_fiber *fiber)
  1330. {
  1331. __cilkrts_worker *w = cilk_fiber_get_owner(fiber);
  1332. __cilkrts_stack_frame *sf;
  1333. full_frame *ff;
  1334. sf = w->current_stack_frame;
  1335. ff = sf->worker->l->frame_ff;
  1336. #if FIBER_DEBUG >= 1
  1337. CILK_ASSERT(ff->fiber_self == fiber);
  1338. cilk_fiber_data *fdata = cilk_fiber_get_data(fiber);
  1339. DBGPRINTF ("%d-%p: resume_after_switch_into_runtime, fiber=%p\n",
  1340. w->self, w, fiber);
  1341. CILK_ASSERT(sf == fdata->resume_sf);
  1342. #endif
  1343. // Notify the Intel tools that we're stealing code
  1344. ITT_SYNC_ACQUIRED(sf->worker);
  1345. NOTIFY_ZC_INTRINSIC("cilk_continue", sf);
  1346. cilk_fiber_invoke_tbb_stack_op(fiber, CILK_TBB_STACK_ADOPT);
  1347. // Actually jump to user code.
  1348. cilkrts_resume(sf, ff);
  1349. }
  1350. /* The current stack is about to either be suspended or destroyed. This
  1351. * function will switch to the stack on which the scheduler is suspended and
  1352. * resume running the scheduler within function do_work(). Upon waking up,
  1353. * the scheduler will run the 'cont' function, using the supplied worker and
  1354. * frame.
  1355. */
  1356. static NORETURN
  1357. longjmp_into_runtime(__cilkrts_worker *w,
  1358. scheduling_stack_fcn_t fcn,
  1359. __cilkrts_stack_frame *sf)
  1360. {
  1361. full_frame *ff, *ff2;
  1362. CILK_ASSERT(!w->l->post_suspend);
  1363. ff = w->l->frame_ff;
  1364. // If we've got only one worker, stealing shouldn't be possible.
  1365. // Assume that this is a steal or return from spawn in a force-reduce case.
  1366. // We don't have a scheduling stack to switch to, so call the continuation
  1367. // function directly.
  1368. if (1 == w->g->P) {
  1369. fcn(w, ff, sf);
  1370. /* The call to function c() will have pushed ff as the next frame. If
  1371. * this were a normal (non-forced-reduce) execution, there would have
  1372. * been a pop_next_frame call in a separate part of the runtime. We
  1373. * must call pop_next_frame here to complete the push/pop cycle. */
  1374. ff2 = pop_next_frame(w);
  1375. setup_for_execution(w, ff2, 0);
  1376. scheduling_fiber_prepare_to_resume_user_code(w, ff2, w->current_stack_frame);
  1377. cilkrts_resume(w->current_stack_frame, ff2);
  1378. // Suppress clang warning that the expression result is unused
  1379. #if defined(__clang__) && (! defined(__INTEL_COMPILER))
  1380. # pragma clang diagnostic push
  1381. # pragma clang diagnostic ignored "-Wunused-value"
  1382. #endif // __clang__
  1383. /* no return */
  1384. CILK_ASSERT(((void)"returned from __cilkrts_resume", 0));
  1385. #if defined(__clang__) && (! defined(__INTEL_COMPILER))
  1386. # pragma clang diagnostic pop
  1387. #endif // __clang__
  1388. }
  1389. w->l->post_suspend = fcn;
  1390. w->l->suspended_stack = sf;
  1391. ITT_SYNC_RELEASING(w);
  1392. ITT_SYNC_PREPARE(w);
  1393. #if FIBER_DEBUG >= 2
  1394. fprintf(stderr, "ThreadId=%p, W=%d: about to switch into runtime... w->l->frame_ff = %p, sf=%p\n",
  1395. cilkos_get_current_thread_id(),
  1396. w->self, w->l->frame_ff,
  1397. sf);
  1398. #endif
  1399. // Current fiber is either the (1) one we are about to free,
  1400. // or (2) it has been passed up to the parent.
  1401. cilk_fiber *current_fiber = ( w->l->fiber_to_free ?
  1402. w->l->fiber_to_free :
  1403. w->l->frame_ff->parent->fiber_child );
  1404. cilk_fiber_data* fdata = cilk_fiber_get_data(current_fiber);
  1405. CILK_ASSERT(NULL == w->l->frame_ff->fiber_self);
  1406. // Clear the sf in the current fiber for cleanliness, to prevent
  1407. // us from accidentally resuming a bad sf.
  1408. // Technically, resume_sf gets overwritten for a fiber when
  1409. // we are about to resume it anyway.
  1410. fdata->resume_sf = NULL;
  1411. CILK_ASSERT(fdata->owner == w);
  1412. // Set the function to execute immediately after switching to the
  1413. // scheduling fiber, but before freeing any fibers.
  1414. cilk_fiber_set_post_switch_proc(w->l->scheduling_fiber,
  1415. enter_runtime_transition_proc);
  1416. cilk_fiber_invoke_tbb_stack_op(current_fiber, CILK_TBB_STACK_ORPHAN);
  1417. if (w->l->fiber_to_free) {
  1418. // Case 1: we are freeing this fiber. We never
  1419. // resume this fiber again after jumping into the runtime.
  1420. w->l->fiber_to_free = NULL;
  1421. // Extra check. Normally, the fiber we are about to switch to
  1422. // should have a NULL owner.
  1423. CILK_ASSERT(NULL == cilk_fiber_get_data(w->l->scheduling_fiber)->owner);
  1424. #if FIBER_DEBUG >= 4
  1425. fprintf(stderr, "ThreadId=%p, W=%d: about to switch into runtime.. current_fiber = %p, deallcoate, switch to fiber %p\n",
  1426. cilkos_get_current_thread_id(),
  1427. w->self,
  1428. current_fiber, w->l->scheduling_fiber);
  1429. #endif
  1430. cilk_fiber_invoke_tbb_stack_op(current_fiber, CILK_TBB_STACK_RELEASE);
  1431. NOTE_INTERVAL(w, INTERVAL_DEALLOCATE_RESUME_OTHER);
  1432. cilk_fiber_remove_reference_from_self_and_resume_other(current_fiber,
  1433. &w->l->fiber_pool,
  1434. w->l->scheduling_fiber);
  1435. // We should never come back here!
  1436. CILK_ASSERT(0);
  1437. }
  1438. else {
  1439. // Case 2: We are passing the fiber to our parent because we
  1440. // are leftmost. We should come back later to
  1441. // resume execution of user code.
  1442. //
  1443. // If we are not freeing a fiber, there we must be
  1444. // returning from a spawn or processing an exception. The
  1445. // "sync" path always frees a fiber.
  1446. //
  1447. // We must be the leftmost child, and by left holder logic, we
  1448. // have already moved the current fiber into our parent full
  1449. // frame.
  1450. #if FIBER_DEBUG >= 2
  1451. fprintf(stderr, "ThreadId=%p, W=%d: about to suspend self into runtime.. current_fiber = %p, deallcoate, switch to fiber %p\n",
  1452. cilkos_get_current_thread_id(),
  1453. w->self,
  1454. current_fiber, w->l->scheduling_fiber);
  1455. #endif
  1456. NOTE_INTERVAL(w, INTERVAL_SUSPEND_RESUME_OTHER);
  1457. cilk_fiber_suspend_self_and_resume_other(current_fiber,
  1458. w->l->scheduling_fiber);
  1459. // Resuming this fiber returns control back to
  1460. // this function because our implementation uses OS fibers.
  1461. //
  1462. // On Unix, we could have the choice of passing the
  1463. // user_code_resume_after_switch_into_runtime as an extra "resume_proc"
  1464. // that resumes execution of user code instead of the
  1465. // jumping back here, and then jumping back to user code.
  1466. #if FIBER_DEBUG >= 2
  1467. CILK_ASSERT(fdata->owner == __cilkrts_get_tls_worker());
  1468. #endif
  1469. user_code_resume_after_switch_into_runtime(current_fiber);
  1470. }
  1471. }
  1472. /*
  1473. * Send a message to the children of the specified worker: run or wait.
  1474. */
  1475. static void notify_children(__cilkrts_worker *w, unsigned int msg)
  1476. {
  1477. int child_num;
  1478. __cilkrts_worker *child;
  1479. int num_sys_workers = w->g->P - 1;
  1480. // If worker is "n", then its children are 2n + 1, and 2n + 2.
  1481. child_num = (w->self << 1) + 1;
  1482. if (child_num < num_sys_workers) {
  1483. child = w->g->workers[child_num];
  1484. CILK_ASSERT(child->l->signal_node);
  1485. signal_node_msg(child->l->signal_node, msg);
  1486. child_num++;
  1487. if (child_num < num_sys_workers) {
  1488. child = w->g->workers[child_num];
  1489. CILK_ASSERT(child->l->signal_node);
  1490. signal_node_msg(child->l->signal_node, msg);
  1491. }
  1492. }
  1493. }
  1494. /*
  1495. * Notify this worker's children that they need to wait.
  1496. */
  1497. static void notify_children_wait(__cilkrts_worker *w)
  1498. {
  1499. notify_children(w, 0);
  1500. }
  1501. /*
  1502. * Notify this worker's children to run and start trying to steal.
  1503. */
  1504. static void notify_children_run(__cilkrts_worker *w)
  1505. {
  1506. notify_children(w, 1);
  1507. }
  1508. /**
  1509. * A single "check" to find work, either on our queue or through a
  1510. * steal attempt. This method checks our local queue once, and
  1511. * performs one steal attempt.
  1512. */
  1513. static full_frame* check_for_work(__cilkrts_worker *w)
  1514. {
  1515. full_frame *ff = NULL;
  1516. ff = pop_next_frame(w);
  1517. // If there is no work on the queue, try to steal some.
  1518. if (NULL == ff) {
  1519. START_INTERVAL(w, INTERVAL_STEALING) {
  1520. if (w->l->type != WORKER_USER && w->l->team != NULL) {
  1521. // At this point, the worker knows for certain that it has run
  1522. // out of work. Therefore, it loses its team affiliation. User
  1523. // workers never change teams, of course.
  1524. __cilkrts_worker_lock(w);
  1525. w->l->team = NULL;
  1526. __cilkrts_worker_unlock(w);
  1527. }
  1528. // If we are about to do a random steal, we should have no
  1529. // full frame...
  1530. CILK_ASSERT(NULL == w->l->frame_ff);
  1531. random_steal(w);
  1532. } STOP_INTERVAL(w, INTERVAL_STEALING);
  1533. // If the steal was successful, then the worker has populated its next
  1534. // frame with the work to resume.
  1535. ff = pop_next_frame(w);
  1536. if (NULL == ff) {
  1537. // Punish the worker for failing to steal.
  1538. // No quantum for you!
  1539. __cilkrts_yield();
  1540. w->l->steal_failure_count++;
  1541. } else {
  1542. // Reset steal_failure_count since there is obviously still work to
  1543. // be done.
  1544. w->l->steal_failure_count = 0;
  1545. }
  1546. }
  1547. return ff;
  1548. }
  1549. /**
  1550. * Keep stealing or looking on our queue.
  1551. *
  1552. * Returns either when a full frame is found, or NULL if the
  1553. * computation is done.
  1554. */
  1555. static full_frame* search_until_work_found_or_done(__cilkrts_worker *w)
  1556. {
  1557. full_frame *ff = NULL;
  1558. // Find a full frame to execute (either through random stealing,
  1559. // or because we pull it off w's 1-element queue).
  1560. while (!ff) {
  1561. // Check worker state to figure out our next action.
  1562. switch (worker_runnable(w))
  1563. {
  1564. case SCHEDULE_RUN: // One attempt at checking for work.
  1565. ff = check_for_work(w);
  1566. break;
  1567. case SCHEDULE_WAIT: // go into wait-mode.
  1568. CILK_ASSERT(WORKER_SYSTEM == w->l->type);
  1569. // If we are about to wait, then we better not have
  1570. // a frame that we should execute...
  1571. CILK_ASSERT(NULL == w->l->next_frame_ff);
  1572. notify_children_wait(w);
  1573. signal_node_wait(w->l->signal_node);
  1574. // ...
  1575. // Runtime is waking up.
  1576. notify_children_run(w);
  1577. w->l->steal_failure_count = 0;
  1578. break;
  1579. case SCHEDULE_EXIT: // exit the scheduler.
  1580. CILK_ASSERT(WORKER_USER != w->l->type);
  1581. return NULL;
  1582. default:
  1583. CILK_ASSERT(0);
  1584. abort();
  1585. }
  1586. }
  1587. return ff;
  1588. }
  1589. /**
  1590. * The proc method for a scheduling fiber on a user worker.
  1591. *
  1592. * When a user worker jumps into the runtime, it jumps into this
  1593. * method by either starting it if the scheduling fiber has never run
  1594. * before, or resuming the fiber if it was previously suspended.
  1595. */
  1596. COMMON_PORTABLE
  1597. void scheduler_fiber_proc_for_user_worker(cilk_fiber *fiber)
  1598. {
  1599. __cilkrts_worker* w = cilk_fiber_get_owner(fiber);
  1600. CILK_ASSERT(w);
  1601. // This must be a user worker
  1602. CILK_ASSERT(WORKER_USER == w->l->type);
  1603. // If we aren't the current worker, then something is very wrong
  1604. // here..
  1605. verify_current_wkr(w);
  1606. __cilkrts_run_scheduler_with_exceptions(w);
  1607. }
  1608. /**
  1609. * The body of the runtime scheduling loop. This function executes in
  1610. * 4 stages:
  1611. *
  1612. * 1. Transitions from the user code into the runtime by
  1613. * executing any scheduling-stack functions.
  1614. * 2. Looks for a full frame enqueued from a successful provably
  1615. * good steal.
  1616. * 3. If no full frame is found in step 2, steal until
  1617. * a frame is found or we are done. If we are done, finish
  1618. * the scheduling loop.
  1619. * 4. When a frame is found, setup to resume user code.
  1620. * In particular, suspend the current fiber and resume the
  1621. * user fiber to execute the frame.
  1622. *
  1623. * Returns a fiber object that we should switch to after completing
  1624. * the body of the loop, or NULL if we should continue executing on
  1625. * this fiber.
  1626. *
  1627. * @pre @c current_fiber should equal @c wptr->l->scheduling_fiber
  1628. *
  1629. * @param current_fiber The currently executing (scheduling_ fiber
  1630. * @param wptr The currently executing worker.
  1631. * @param return The next fiber we should switch to.
  1632. */
  1633. static cilk_fiber* worker_scheduling_loop_body(cilk_fiber* current_fiber,
  1634. void* wptr)
  1635. {
  1636. __cilkrts_worker *w = (__cilkrts_worker*) wptr;
  1637. CILK_ASSERT(current_fiber == w->l->scheduling_fiber);
  1638. // Stage 1: Transition from executing user code to the runtime code.
  1639. // We don't need to do this call here any more, because
  1640. // every switch to the scheduling fiber should make this call
  1641. // using a post_switch_proc on the fiber.
  1642. //
  1643. // enter_runtime_transition_proc(w->l->scheduling_fiber, wptr);
  1644. // After Stage 1 is complete, w should no longer have
  1645. // an associated full frame.
  1646. CILK_ASSERT(NULL == w->l->frame_ff);
  1647. // Stage 2. First do a quick check of our 1-element queue.
  1648. full_frame *ff = pop_next_frame(w);
  1649. if (!ff) {
  1650. // Stage 3. We didn't find anything from our 1-element
  1651. // queue. Now go through the steal loop to find work.
  1652. ff = search_until_work_found_or_done(w);
  1653. if (!ff) {
  1654. CILK_ASSERT(w->g->work_done);
  1655. return NULL;
  1656. }
  1657. }
  1658. // Stage 4. Now that we have found a full frame to work on,
  1659. // actually execute it.
  1660. __cilkrts_stack_frame *sf;
  1661. // There shouldn't be any uncaught exceptions.
  1662. //
  1663. // In Windows, the OS catches any exceptions not caught by the
  1664. // user code. Thus, we are omitting the check on Windows.
  1665. //
  1666. // On Android, calling std::uncaught_exception with the stlport
  1667. // library causes a seg fault. Since we're not supporting
  1668. // exceptions there at this point, just don't do the check
  1669. CILKBUG_ASSERT_NO_UNCAUGHT_EXCEPTION();
  1670. BEGIN_WITH_WORKER_LOCK(w) {
  1671. CILK_ASSERT(!w->l->frame_ff);
  1672. BEGIN_WITH_FRAME_LOCK(w, ff) {
  1673. sf = ff->call_stack;
  1674. CILK_ASSERT(sf && !sf->call_parent);
  1675. setup_for_execution(w, ff, 0);
  1676. } END_WITH_FRAME_LOCK(w, ff);
  1677. } END_WITH_WORKER_LOCK(w);
  1678. /* run it */
  1679. //
  1680. // Prepare to run the full frame. To do so, we need to:
  1681. // (a) Execute some code on this fiber (the scheduling
  1682. // fiber) to set up data structures, and
  1683. // (b) Suspend the scheduling fiber, and resume the
  1684. // user-code fiber.
  1685. // Part (a). Set up data structures.
  1686. scheduling_fiber_prepare_to_resume_user_code(w, ff, sf);
  1687. cilk_fiber *other = w->l->frame_ff->fiber_self;
  1688. cilk_fiber_data* other_data = cilk_fiber_get_data(other);
  1689. cilk_fiber_data* current_fiber_data = cilk_fiber_get_data(current_fiber);
  1690. // I believe two cases are possible here, both of which
  1691. // should have other_data->resume_sf as NULL.
  1692. //
  1693. // 1. Resuming a fiber that was previously executing
  1694. // user code (i.e., a provably-good-steal).
  1695. // In this case, resume_sf should have been
  1696. // set to NULL when it was suspended.
  1697. //
  1698. // 2. Resuming code on a steal. In this case, since we
  1699. // grabbed a new fiber, resume_sf should be NULL.
  1700. CILK_ASSERT(NULL == other_data->resume_sf);
  1701. #if FIBER_DEBUG >= 2
  1702. fprintf(stderr, "W=%d: other fiber=%p, setting resume_sf to %p\n",
  1703. w->self, other, other_data->resume_sf);
  1704. #endif
  1705. // Update our own fiber's data.
  1706. current_fiber_data->resume_sf = NULL;
  1707. // The scheduling fiber should have the right owner from before.
  1708. CILK_ASSERT(current_fiber_data->owner == w);
  1709. other_data->resume_sf = sf;
  1710. #if FIBER_DEBUG >= 3
  1711. fprintf(stderr, "ThreadId=%p (about to suspend self resume other), W=%d: current_fiber=%p, other=%p, current_fiber->resume_sf = %p, other->resume_sf = %p\n",
  1712. cilkos_get_current_thread_id(),
  1713. w->self,
  1714. current_fiber, other,
  1715. current_fiber_data->resume_sf,
  1716. other_data->resume_sf);
  1717. #endif
  1718. return other;
  1719. }
  1720. /**
  1721. * This function is executed once by each worker, to initialize its
  1722. * scheduling loop.
  1723. */
  1724. static void worker_scheduler_init_function(__cilkrts_worker *w)
  1725. {
  1726. // First, execute the startup tasks that must happen for all
  1727. // worker types.
  1728. ITT_SYNC_PREPARE(w);
  1729. /* Notify tools about the new worker. Inspector needs this, but we
  1730. don't want to confuse Cilkscreen with system threads. User threads
  1731. do this notification in bind_thread */
  1732. if (! w->g->under_ptool)
  1733. __cilkrts_cilkscreen_establish_worker(w);
  1734. // Seed the initial random number generator.
  1735. // If we forget to do this, then the worker always steals from 0.
  1736. // Programs will still execute correctly, but
  1737. // you may see a subtle performance bug...
  1738. mysrand(w, (w->self + 1));
  1739. // The startup work varies, depending on the worker type.
  1740. switch (w->l->type) {
  1741. case WORKER_USER:
  1742. // Stop working once we've entered the scheduler.
  1743. // For user workers, INTERVAL_IN_SCHEDULER counts the time
  1744. // since we called bind_thread.
  1745. break;
  1746. case WORKER_SYSTEM:
  1747. // If a system worker is starting, we must also be starting
  1748. // the runtime.
  1749. // Runtime begins in a wait-state and is woken up by the first user
  1750. // worker when the runtime is ready.
  1751. signal_node_wait(w->l->signal_node);
  1752. // ...
  1753. // Runtime is waking up.
  1754. notify_children_run(w);
  1755. w->l->steal_failure_count = 0;
  1756. // For system threads, count all the time this thread is
  1757. // alive in the scheduling loop.
  1758. START_INTERVAL(w, INTERVAL_IN_SCHEDULER);
  1759. START_INTERVAL(w, INTERVAL_WORKING);
  1760. break;
  1761. default:
  1762. __cilkrts_bug("Unknown worker %p of type %d entering scheduling loop\n",
  1763. w, w->l->type);
  1764. }
  1765. }
  1766. /**
  1767. * This function is executed once by each worker, to finish its
  1768. * scheduling loop.
  1769. *
  1770. * @note Currently, only system workers finish their loops. User
  1771. * workers will jump away to user code without exiting their
  1772. * scheduling loop.
  1773. */
  1774. static void worker_scheduler_terminate_function(__cilkrts_worker *w)
  1775. {
  1776. // A user worker should never finish by falling through the
  1777. // scheduling loop.
  1778. CILK_ASSERT(WORKER_USER != w->l->type);
  1779. STOP_INTERVAL(w, INTERVAL_IN_RUNTIME);
  1780. STOP_INTERVAL(w, INTERVAL_IN_SCHEDULER);
  1781. }
  1782. /**
  1783. * The main scheduler function executed by a worker's scheduling
  1784. * fiber.
  1785. *
  1786. * This method is started by either a new system worker, or a user
  1787. * worker that has stalled and just been imported into the runtime.
  1788. */
  1789. static void worker_scheduler_function(__cilkrts_worker *w)
  1790. {
  1791. worker_scheduler_init_function(w);
  1792. // The main scheduling loop body.
  1793. while (!w->g->work_done) {
  1794. // Set intervals. Now we are in the runtime instead of working.
  1795. START_INTERVAL(w, INTERVAL_IN_RUNTIME);
  1796. STOP_INTERVAL(w, INTERVAL_WORKING);
  1797. // Execute the "body" of the scheduling loop, and figure
  1798. // out the fiber to jump to next.
  1799. cilk_fiber* fiber_to_resume
  1800. = worker_scheduling_loop_body(w->l->scheduling_fiber, w);
  1801. if (fiber_to_resume) {
  1802. // Suspend the current fiber and resume next one.
  1803. NOTE_INTERVAL(w, INTERVAL_SUSPEND_RESUME_OTHER);
  1804. STOP_INTERVAL(w, INTERVAL_IN_RUNTIME);
  1805. START_INTERVAL(w, INTERVAL_WORKING);
  1806. cilk_fiber_suspend_self_and_resume_other(w->l->scheduling_fiber,
  1807. fiber_to_resume);
  1808. // Return here only when this (scheduling) fiber is
  1809. // resumed (i.e., this worker wants to reenter the runtime).
  1810. }
  1811. }
  1812. // Finish the scheduling loop.
  1813. worker_scheduler_terminate_function(w);
  1814. }
  1815. /*************************************************************
  1816. Forward declarations for reduction protocol.
  1817. *************************************************************/
  1818. static __cilkrts_worker*
  1819. execute_reductions_for_sync(__cilkrts_worker *w,
  1820. full_frame *ff,
  1821. __cilkrts_stack_frame *sf_at_sync);
  1822. static __cilkrts_worker*
  1823. execute_reductions_for_spawn_return(__cilkrts_worker *w,
  1824. full_frame *ff,
  1825. __cilkrts_stack_frame *returning_sf);
  1826. /*************************************************************
  1827. Scheduler functions that are callable by client code
  1828. *************************************************************/
  1829. static full_frame *disown(__cilkrts_worker *w,
  1830. full_frame *ff,
  1831. __cilkrts_stack_frame *sf,
  1832. const char *why)
  1833. {
  1834. CILK_ASSERT(ff);
  1835. make_unrunnable(w, ff, sf, sf != 0, why);
  1836. w->l->frame_ff = 0;
  1837. return ff->parent;
  1838. }
  1839. /**
  1840. * Called when ff is returning from a spawn, and we need to execute a
  1841. * reduction.
  1842. *
  1843. * @param w The currently executing worker.
  1844. * @param ff The full frame for w.
  1845. * @param returning_sf The stack frame for the spawn helper that is returning.
  1846. *
  1847. * Normally, by the time we gain control in the runtime, the worker
  1848. * has already popped off the __cilkrts_stack_frame "returning_sf"
  1849. * from its call chain.
  1850. *
  1851. * When we have only serial reductions, w->current_stack_frame is not
  1852. * needed any more, because w is about to enter the runtime scheduling
  1853. * loop anyway. Similarly, the frame "ff" is slated to be destroyed
  1854. * after the runtime finishes the return from spawn and splices ff out
  1855. * of the tree of full frames.
  1856. *
  1857. * To execute a parallel reduction, however, we still want
  1858. * w->current_stack_frame == returning_sf, and we are going to use the
  1859. * frame ff for a little bit longer.
  1860. *
  1861. * This method:
  1862. *
  1863. * 1. Puts returning_sf back as w's current stack frame.
  1864. * 2. Makes "ff" runnable again on w.
  1865. */
  1866. static inline
  1867. void restore_frame_for_spawn_return_reduction(__cilkrts_worker *w,
  1868. full_frame *ff,
  1869. __cilkrts_stack_frame *returning_sf) {
  1870. #if REDPAR_DEBUG >= 2
  1871. CILK_ASSERT(returning_sf);
  1872. CILK_ASSERT(returning_sf->worker == w);
  1873. #endif
  1874. // Change w's current stack frame back to "returning_sf".
  1875. //
  1876. // Intuitively, w->current_stack_frame should be
  1877. // returning_sf->call_parent at this point.
  1878. //
  1879. // We can not assert this, however, because the pop of
  1880. // returning_sf from the call chain has already cleared
  1881. // returning_sf->call_parent. We don't want to restore the call
  1882. // parent of returning_sf, because its parent has been stolen, and
  1883. // the runtime assumes that steals break this link.
  1884. // We cannot assert call_parent is NULL either, since that's not true for
  1885. // Win64 exception handling
  1886. // CILK_ASSERT(returning_sf->call_parent == NULL);
  1887. w->current_stack_frame = returning_sf;
  1888. // Make the full frame "ff" runnable again, in preparation for
  1889. // executing the reduction.
  1890. make_runnable(w, ff);
  1891. }
  1892. NORETURN __cilkrts_c_sync(__cilkrts_worker *w,
  1893. __cilkrts_stack_frame *sf_at_sync)
  1894. {
  1895. full_frame *ff;
  1896. // Claim: This read of w->l->frame_ff can occur without
  1897. // holding the worker lock because when w has reached a sync
  1898. // and entered the runtime (because it stalls), w's deque is empty
  1899. // and no one else can steal and change w->l->frame_ff.
  1900. ff = w->l->frame_ff;
  1901. #ifdef _WIN32
  1902. __cilkrts_save_exception_state(w, ff);
  1903. #else
  1904. // Move any pending exceptions into the full frame
  1905. CILK_ASSERT(NULL == ff->pending_exception);
  1906. ff->pending_exception = w->l->pending_exception;
  1907. w->l->pending_exception = NULL;
  1908. #endif
  1909. w = execute_reductions_for_sync(w, ff, sf_at_sync);
  1910. #if FIBER_DEBUG >= 3
  1911. fprintf(stderr, "ThreadId=%p, w->self = %d. about to longjmp_into_runtim[c_sync] with ff=%p\n",
  1912. cilkos_get_current_thread_id(), w->self, ff);
  1913. #endif
  1914. longjmp_into_runtime(w, do_sync, sf_at_sync);
  1915. }
  1916. static void do_sync(__cilkrts_worker *w, full_frame *ff,
  1917. __cilkrts_stack_frame *sf)
  1918. {
  1919. //int abandoned = 1;
  1920. enum provably_good_steal_t steal_result = ABANDON_EXECUTION;
  1921. START_INTERVAL(w, INTERVAL_SYNC_CHECK) {
  1922. BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) {
  1923. CILK_ASSERT(ff);
  1924. BEGIN_WITH_FRAME_LOCK(w, ff) {
  1925. CILK_ASSERT(sf->call_parent == 0);
  1926. CILK_ASSERT(sf->flags & CILK_FRAME_UNSYNCHED);
  1927. // Before switching into the scheduling fiber, we should have
  1928. // already taken care of deallocating the current
  1929. // fiber.
  1930. CILK_ASSERT(NULL == ff->fiber_self);
  1931. // Update the frame's pedigree information if this is an ABI 1
  1932. // or later frame
  1933. if (CILK_FRAME_VERSION_VALUE(sf->flags) >= 1)
  1934. {
  1935. sf->parent_pedigree.rank = w->pedigree.rank;
  1936. sf->parent_pedigree.parent = w->pedigree.parent;
  1937. // Note that the pedigree rank needs to be updated
  1938. // when setup_for_execution_pedigree runs
  1939. sf->flags |= CILK_FRAME_SF_PEDIGREE_UNSYNCHED;
  1940. }
  1941. /* the decjoin() occurs in provably_good_steal() */
  1942. steal_result = provably_good_steal(w, ff);
  1943. } END_WITH_FRAME_LOCK(w, ff);
  1944. // set w->l->frame_ff = NULL after checking abandoned
  1945. if (WAIT_FOR_CONTINUE != steal_result) {
  1946. w->l->frame_ff = NULL;
  1947. }
  1948. } END_WITH_WORKER_LOCK_OPTIONAL(w);
  1949. } STOP_INTERVAL(w, INTERVAL_SYNC_CHECK);
  1950. // Now, if we are in a replay situation and provably_good_steal() returned
  1951. // WAIT_FOR_CONTINUE, we should sleep, reacquire locks, call
  1952. // provably_good_steal(), and release locks until we get a value other
  1953. // than WAIT_FOR_CONTINUE from the function.
  1954. #ifdef CILK_RECORD_REPLAY
  1955. // We don't have to explicitly check for REPLAY_LOG below because
  1956. // steal_result can only be set to WAIT_FOR_CONTINUE during replay
  1957. while(WAIT_FOR_CONTINUE == steal_result)
  1958. {
  1959. __cilkrts_sleep();
  1960. BEGIN_WITH_WORKER_LOCK_OPTIONAL(w)
  1961. {
  1962. ff = w->l->frame_ff;
  1963. BEGIN_WITH_FRAME_LOCK(w, ff)
  1964. {
  1965. steal_result = provably_good_steal(w, ff);
  1966. } END_WITH_FRAME_LOCK(w, ff);
  1967. if (WAIT_FOR_CONTINUE != steal_result)
  1968. w->l->frame_ff = NULL;
  1969. } END_WITH_WORKER_LOCK_OPTIONAL(w);
  1970. }
  1971. #endif // CILK_RECORD_REPLAY
  1972. #ifdef ENABLE_NOTIFY_ZC_INTRINSIC
  1973. // If we can't make any further progress on this thread, tell Inspector
  1974. // that we're abandoning the work and will go find something else to do.
  1975. if (ABANDON_EXECUTION == steal_result)
  1976. {
  1977. NOTIFY_ZC_INTRINSIC("cilk_sync_abandon", 0);
  1978. }
  1979. #endif // defined ENABLE_NOTIFY_ZC_INTRINSIC
  1980. return; /* back to scheduler loop */
  1981. }
  1982. /* worker W completely promotes its own deque, simulating the case
  1983. where the whole deque is stolen. We use this mechanism to force
  1984. the allocation of new storage for reducers for race-detection
  1985. purposes. */
  1986. void __cilkrts_promote_own_deque(__cilkrts_worker *w)
  1987. {
  1988. // Remember the fiber we start this method on.
  1989. CILK_ASSERT(w->l->frame_ff);
  1990. cilk_fiber* starting_fiber = w->l->frame_ff->fiber_self;
  1991. BEGIN_WITH_WORKER_LOCK(w) {
  1992. while (dekker_protocol(w)) {
  1993. /* PLACEHOLDER_FIBER is used as non-null marker to tell detach()
  1994. and make_child() that this frame should be treated as a spawn
  1995. parent, even though we have not assigned it a stack. */
  1996. detach_for_steal(w, w, PLACEHOLDER_FIBER);
  1997. }
  1998. } END_WITH_WORKER_LOCK(w);
  1999. // TBD: The management of full frames and fibers is a bit
  2000. // sketchy here. We are promoting stack frames into full frames,
  2001. // and pretending they are stolen away, but no other worker is
  2002. // actually working on them. Some runtime invariants
  2003. // may be broken here.
  2004. //
  2005. // Technically, if we are simulating a steal from w
  2006. // w should get a new full frame, but
  2007. // keep the same fiber. A real thief would be taking the
  2008. // loot frame away, get a new fiber, and starting executing the
  2009. // loot frame.
  2010. //
  2011. // What should a fake thief do? Where does the frame go?
  2012. // In any case, we should be finishing the promotion process with
  2013. // the same fiber with.
  2014. CILK_ASSERT(w->l->frame_ff);
  2015. CILK_ASSERT(w->l->frame_ff->fiber_self == starting_fiber);
  2016. }
  2017. /* the client code calls this function after a spawn when the dekker
  2018. protocol fails. The function may either return or longjmp
  2019. into the rts
  2020. This function takes in a "returning_sf" argument which corresponds
  2021. to the __cilkrts_stack_frame that we are finishing (i.e., the
  2022. argument to __cilkrts_leave_frame).
  2023. */
  2024. void __cilkrts_c_THE_exception_check(__cilkrts_worker *w,
  2025. __cilkrts_stack_frame *returning_sf)
  2026. {
  2027. full_frame *ff;
  2028. int stolen_p;
  2029. __cilkrts_stack_frame *saved_sf = NULL;
  2030. START_INTERVAL(w, INTERVAL_THE_EXCEPTION_CHECK);
  2031. BEGIN_WITH_WORKER_LOCK(w) {
  2032. ff = w->l->frame_ff;
  2033. CILK_ASSERT(ff);
  2034. /* This code is called only upon a normal return and never
  2035. upon an exceptional return. Assert that this is the
  2036. case. */
  2037. CILK_ASSERT(!w->l->pending_exception);
  2038. reset_THE_exception(w);
  2039. stolen_p = !(w->head < (w->tail + 1)); /* +1 because tail was
  2040. speculatively
  2041. decremented by the
  2042. compiled code */
  2043. if (stolen_p) {
  2044. /* XXX This will be charged to THE for accounting purposes */
  2045. __cilkrts_save_exception_state(w, ff);
  2046. // Save the value of the current stack frame.
  2047. saved_sf = w->current_stack_frame;
  2048. // Reverse the decrement from undo_detach.
  2049. // This update effectively resets the deque to be
  2050. // empty (i.e., changes w->tail back to equal w->head).
  2051. // We need to reset the deque to execute parallel
  2052. // reductions. When we have only serial reductions, it
  2053. // does not matter, since serial reductions do not
  2054. // change the deque.
  2055. w->tail++;
  2056. #if REDPAR_DEBUG > 1
  2057. // ASSERT our deque is empty.
  2058. CILK_ASSERT(w->head == w->tail);
  2059. #endif
  2060. }
  2061. } END_WITH_WORKER_LOCK(w);
  2062. STOP_INTERVAL(w, INTERVAL_THE_EXCEPTION_CHECK);
  2063. if (stolen_p)
  2064. {
  2065. w = execute_reductions_for_spawn_return(w, ff, returning_sf);
  2066. // "Mr. Policeman? My parent always told me that if I was in trouble
  2067. // I should ask a nice policeman for help. I can't find my parent
  2068. // anywhere..."
  2069. //
  2070. // Write a record to the replay log for an attempt to return to a stolen parent
  2071. replay_record_orphaned(w);
  2072. // Update the pedigree only after we've finished the
  2073. // reductions.
  2074. update_pedigree_on_leave_frame(w, returning_sf);
  2075. // Notify Inspector that the parent has been stolen and we're
  2076. // going to abandon this work and go do something else. This
  2077. // will match the cilk_leave_begin in the compiled code
  2078. NOTIFY_ZC_INTRINSIC("cilk_leave_stolen", saved_sf);
  2079. DBGPRINTF ("%d: longjmp_into_runtime from __cilkrts_c_THE_exception_check\n", w->self);
  2080. longjmp_into_runtime(w, do_return_from_spawn, 0);
  2081. DBGPRINTF ("%d: returned from longjmp_into_runtime from __cilkrts_c_THE_exception_check?!\n", w->self);
  2082. }
  2083. else
  2084. {
  2085. NOTE_INTERVAL(w, INTERVAL_THE_EXCEPTION_CHECK_USELESS);
  2086. return;
  2087. }
  2088. }
  2089. /* Return an exception to a stolen parent. */
  2090. NORETURN __cilkrts_exception_from_spawn(__cilkrts_worker *w,
  2091. __cilkrts_stack_frame *returning_sf)
  2092. {
  2093. full_frame *ff = w->l->frame_ff;
  2094. // This is almost the same as THE_exception_check, except
  2095. // the detach didn't happen, we don't need to undo the tail
  2096. // update.
  2097. CILK_ASSERT(w->head == w->tail);
  2098. w = execute_reductions_for_spawn_return(w, ff, returning_sf);
  2099. longjmp_into_runtime(w, do_return_from_spawn, 0);
  2100. CILK_ASSERT(0);
  2101. }
  2102. static void do_return_from_spawn(__cilkrts_worker *w,
  2103. full_frame *ff,
  2104. __cilkrts_stack_frame *sf)
  2105. {
  2106. full_frame *parent_ff;
  2107. enum provably_good_steal_t steal_result = ABANDON_EXECUTION;
  2108. BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) {
  2109. CILK_ASSERT(ff);
  2110. CILK_ASSERT(!ff->is_call_child);
  2111. CILK_ASSERT(sf == NULL);
  2112. parent_ff = ff->parent;
  2113. BEGIN_WITH_FRAME_LOCK(w, ff) {
  2114. decjoin(ff);
  2115. } END_WITH_FRAME_LOCK(w, ff);
  2116. BEGIN_WITH_FRAME_LOCK(w, parent_ff) {
  2117. if (parent_ff->simulated_stolen)
  2118. unconditional_steal(w, parent_ff);
  2119. else
  2120. steal_result = provably_good_steal(w, parent_ff);
  2121. } END_WITH_FRAME_LOCK(w, parent_ff);
  2122. } END_WITH_WORKER_LOCK_OPTIONAL(w);
  2123. // Loop here in replay mode
  2124. #ifdef CILK_RECORD_REPLAY
  2125. // We don't have to explicitly check for REPLAY_LOG below because
  2126. // steal_result can only get set to WAIT_FOR_CONTINUE during replay.
  2127. // We also don't have to worry about the simulated_stolen flag
  2128. // because steal_result can only be set to WAIT_FOR_CONTINUE by
  2129. // provably_good_steal().
  2130. while(WAIT_FOR_CONTINUE == steal_result)
  2131. {
  2132. __cilkrts_sleep();
  2133. BEGIN_WITH_WORKER_LOCK_OPTIONAL(w)
  2134. {
  2135. BEGIN_WITH_FRAME_LOCK(w, parent_ff)
  2136. {
  2137. steal_result = provably_good_steal(w, parent_ff);
  2138. } END_WITH_FRAME_LOCK(w, parent_ff);
  2139. } END_WITH_WORKER_LOCK_OPTIONAL(w);
  2140. }
  2141. #endif // CILK_RECORD_REPLAY
  2142. // Cleanup the child frame.
  2143. __cilkrts_destroy_full_frame(w, ff);
  2144. return;
  2145. }
  2146. #ifdef _WIN32
  2147. /* migrate an exception across fibers. Call this function when an exception has
  2148. * been thrown and has to traverse across a steal. The exception has already
  2149. * been wrapped up, so all that remains is to longjmp() into the continuation,
  2150. * sync, and re-raise it.
  2151. */
  2152. void __cilkrts_migrate_exception(__cilkrts_stack_frame *sf) {
  2153. __cilkrts_worker *w = sf->worker;
  2154. full_frame *ff;
  2155. BEGIN_WITH_WORKER_LOCK(w) {
  2156. ff = w->l->frame_ff;
  2157. reset_THE_exception(w);
  2158. /* there is no need to check for a steal because we wouldn't be here if
  2159. there weren't a steal. */
  2160. __cilkrts_save_exception_state(w, ff);
  2161. CILK_ASSERT(w->head == w->tail);
  2162. } END_WITH_WORKER_LOCK(w);
  2163. {
  2164. // TBD(jsukha): This function emulates the
  2165. // the "do_return_from_spawn" path.
  2166. w = execute_reductions_for_spawn_return(w, ff, sf);
  2167. }
  2168. longjmp_into_runtime(w, do_return_from_spawn, 0); /* does not return. */
  2169. CILK_ASSERT(! "Shouldn't be here...");
  2170. }
  2171. #endif
  2172. /* Pop a call stack from TAIL. Return the call stack, or NULL if the
  2173. queue is empty */
  2174. __cilkrts_stack_frame *__cilkrts_pop_tail(__cilkrts_worker *w)
  2175. {
  2176. __cilkrts_stack_frame *sf;
  2177. BEGIN_WITH_WORKER_LOCK(w) {
  2178. __cilkrts_stack_frame *volatile *tail = w->tail;
  2179. if (w->head < tail) {
  2180. --tail;
  2181. sf = *tail;
  2182. w->tail = tail;
  2183. } else {
  2184. sf = 0;
  2185. }
  2186. } END_WITH_WORKER_LOCK(w);
  2187. return sf;
  2188. }
  2189. #ifdef CILK_RECORD_REPLAY
  2190. __cilkrts_stack_frame *simulate_pop_tail(__cilkrts_worker *w)
  2191. {
  2192. __cilkrts_stack_frame *sf;
  2193. BEGIN_WITH_WORKER_LOCK(w) {
  2194. if (w->head < w->tail) {
  2195. sf = *(w->tail-1);
  2196. } else {
  2197. sf = 0;
  2198. }
  2199. } END_WITH_WORKER_LOCK(w);
  2200. return sf;
  2201. }
  2202. #endif
  2203. /* Return from a call, not a spawn. */
  2204. void __cilkrts_return(__cilkrts_worker *w)
  2205. {
  2206. full_frame *ff, *parent_ff;
  2207. START_INTERVAL(w, INTERVAL_RETURNING);
  2208. BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) {
  2209. ff = w->l->frame_ff;
  2210. CILK_ASSERT(ff);
  2211. CILK_ASSERT(ff->join_counter == 1);
  2212. /* This path is not used to return from spawn. */
  2213. CILK_ASSERT(ff->is_call_child);
  2214. BEGIN_WITH_FRAME_LOCK(w, ff) {
  2215. // After this call, w->l->frame_ff != ff.
  2216. // Technically, w will "own" ff until ff is freed,
  2217. // however, because ff is a dying leaf full frame.
  2218. parent_ff = disown(w, ff, 0, "return");
  2219. decjoin(ff);
  2220. #ifdef _WIN32
  2221. __cilkrts_save_exception_state(w, ff);
  2222. #else
  2223. // Move the pending exceptions into the full frame
  2224. // This should always be NULL if this isn't a
  2225. // return with an exception
  2226. CILK_ASSERT(NULL == ff->pending_exception);
  2227. ff->pending_exception = w->l->pending_exception;
  2228. w->l->pending_exception = NULL;
  2229. #endif // _WIN32
  2230. } END_WITH_FRAME_LOCK(w, ff);
  2231. __cilkrts_fence(); /* redundant */
  2232. CILK_ASSERT(parent_ff);
  2233. BEGIN_WITH_FRAME_LOCK(w, parent_ff) {
  2234. finalize_child_for_call(w, parent_ff, ff);
  2235. } END_WITH_FRAME_LOCK(w, parent_ff);
  2236. ff = pop_next_frame(w);
  2237. /* ff will be non-null except when the parent frame is owned
  2238. by another worker.
  2239. CILK_ASSERT(ff)
  2240. */
  2241. CILK_ASSERT(!w->l->frame_ff);
  2242. if (ff) {
  2243. BEGIN_WITH_FRAME_LOCK(w, ff) {
  2244. __cilkrts_stack_frame *sf = ff->call_stack;
  2245. CILK_ASSERT(sf && !sf->call_parent);
  2246. setup_for_execution(w, ff, 1);
  2247. } END_WITH_FRAME_LOCK(w, ff);
  2248. }
  2249. } END_WITH_WORKER_LOCK_OPTIONAL(w);
  2250. STOP_INTERVAL(w, INTERVAL_RETURNING);
  2251. }
  2252. static void __cilkrts_unbind_thread()
  2253. {
  2254. int stop_cilkscreen = 0;
  2255. global_state_t *g;
  2256. // Take out the global OS mutex to protect accesses to the table of workers
  2257. global_os_mutex_lock();
  2258. if (cilkg_is_published()) {
  2259. __cilkrts_worker *w = __cilkrts_get_tls_worker();
  2260. if (w) {
  2261. g = w->g;
  2262. // If there's only 1 worker, the counts will be stopped in
  2263. // __cilkrts_scheduler
  2264. if (g->P > 1)
  2265. {
  2266. STOP_INTERVAL(w, INTERVAL_WORKING);
  2267. STOP_INTERVAL(w, INTERVAL_IN_SCHEDULER);
  2268. }
  2269. __cilkrts_set_tls_worker(0);
  2270. if (w->self == -1) {
  2271. // This worker is an overflow worker. I.e., it was created on-
  2272. // demand when the global pool ran out of workers.
  2273. destroy_worker(w);
  2274. __cilkrts_free(w);
  2275. } else {
  2276. // This is a normal user worker and needs to be counted by the
  2277. // global state for the purposes of throttling system workers.
  2278. w->l->type = WORKER_FREE;
  2279. __cilkrts_leave_cilk(g);
  2280. }
  2281. stop_cilkscreen = (0 == g->Q);
  2282. }
  2283. }
  2284. global_os_mutex_unlock();
  2285. /* Turn off Cilkscreen. This needs to be done when we are NOT holding the
  2286. * os mutex. */
  2287. if (stop_cilkscreen)
  2288. __cilkrts_cilkscreen_disable_instrumentation();
  2289. }
  2290. /* special return from the initial frame */
  2291. void __cilkrts_c_return_from_initial(__cilkrts_worker *w)
  2292. {
  2293. struct cilkred_map *rm;
  2294. /* This is only called on a user thread worker. */
  2295. CILK_ASSERT(w->l->type == WORKER_USER);
  2296. #if REDPAR_DEBUG >= 3
  2297. fprintf(stderr, "[W=%d, desc=cilkrts_c_return_from_initial, ff=%p]\n",
  2298. w->self, w->l->frame_ff);
  2299. #endif
  2300. BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) {
  2301. full_frame *ff = w->l->frame_ff;
  2302. CILK_ASSERT(ff);
  2303. CILK_ASSERT(ff->join_counter == 1);
  2304. w->l->frame_ff = 0;
  2305. CILK_ASSERT(ff->fiber_self);
  2306. // Save any TBB interop data for the next time this thread enters Cilk
  2307. cilk_fiber_tbb_interop_save_info_from_stack(ff->fiber_self);
  2308. // Deallocate cilk_fiber that mapped to the user stack. The stack
  2309. // itself does not get deallocated (of course) but our data
  2310. // structure becomes divorced from it.
  2311. #if FIBER_DEBUG >= 1
  2312. fprintf(stderr, "ThreadId=%p: w=%d: We are about to deallocate ff->fiber_self = %p here. w->l->scheduling_fiber = %p. w->l->type = %d\n",
  2313. cilkos_get_current_thread_id(),
  2314. w->self,
  2315. ff->fiber_self,
  2316. w->l->scheduling_fiber,
  2317. w->l->type);
  2318. #endif
  2319. // The fiber in ff is a user-code fiber. The fiber in
  2320. // w->l->scheduling_fiber is a scheduling fiber. These fibers should
  2321. // never be equal. When a user worker returns (and will unbind), we
  2322. // should destroy only the fiber in ff. The scheduling fiber will be
  2323. // re-used.
  2324. CILK_ASSERT(ff->fiber_self != w->l->scheduling_fiber);
  2325. START_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE) {
  2326. // This fiber might not be deallocated here if there
  2327. // is a pending exception on Windows that refers
  2328. // to this fiber.
  2329. //
  2330. // First "suspend" the fiber, and then try to delete it.
  2331. cilk_fiber_deallocate_from_thread(ff->fiber_self);
  2332. } STOP_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE);
  2333. ff->fiber_self = NULL;
  2334. /* Save reducer map into global_state object */
  2335. rm = w->reducer_map;
  2336. w->reducer_map = NULL;
  2337. #if REDPAR_DEBUG >= 3
  2338. fprintf(stderr, "W=%d, reducer_map_to_delete=%p, was in ff=%p\n",
  2339. w->self,
  2340. rm,
  2341. ff);
  2342. #endif
  2343. __cilkrts_destroy_full_frame(w, ff);
  2344. /* Work is never done. w->g->work_done = 1; __cilkrts_fence(); */
  2345. } END_WITH_WORKER_LOCK_OPTIONAL(w);
  2346. save_pedigree_leaf_from_user_worker(w);
  2347. // Workers can have NULL reducer maps now.
  2348. if (rm) {
  2349. __cilkrts_destroy_reducer_map(w, rm);
  2350. }
  2351. #if FIBER_DEBUG >= 1
  2352. __cilkrts_worker* tmp = w;
  2353. int tmp_id = w->self;
  2354. fprintf(stderr, "w=%d: We are about unbind thread (w= %p)\n",
  2355. w->self,
  2356. w);
  2357. #endif
  2358. w = NULL;
  2359. __cilkrts_unbind_thread();
  2360. #if FIBER_DEBUG >= 1
  2361. fprintf(stderr, "w=%p, %d: Finished unbind\n",
  2362. tmp, tmp_id);
  2363. #endif
  2364. /* Other workers will stop trying to steal if this was the last worker. */
  2365. return;
  2366. }
  2367. /*
  2368. * __cilkrts_restore_stealing
  2369. *
  2370. * Restore the protected_tail to a previous state, possibly allowing frames
  2371. * to be stolen. The dekker_protocol has been extended to steal only if
  2372. * head+1 is < protected_tail.
  2373. */
  2374. void __cilkrts_restore_stealing(
  2375. __cilkrts_worker *w,
  2376. __cilkrts_stack_frame *volatile *saved_protected_tail)
  2377. {
  2378. /* On most x86 this pair of operations would be slightly faster
  2379. as an atomic exchange due to the implicit memory barrier in
  2380. an atomic instruction. */
  2381. w->protected_tail = saved_protected_tail;
  2382. __cilkrts_fence();
  2383. }
  2384. /*
  2385. * __cilkrts_disallow_stealing
  2386. *
  2387. * Move the protected_tail to NEW_PROTECTED_TAIL, preventing any
  2388. * frames from being stolen. If NEW_PROTECTED_TAIL is NULL, prevent
  2389. * stealing from the whole queue. The dekker_protocol has been
  2390. * extended to only steal if head+1 is also < protected_tail.
  2391. */
  2392. __cilkrts_stack_frame *volatile *__cilkrts_disallow_stealing(
  2393. __cilkrts_worker *w,
  2394. __cilkrts_stack_frame *volatile *new_protected_tail)
  2395. {
  2396. __cilkrts_stack_frame *volatile *saved_protected_tail = w->protected_tail;
  2397. if (!new_protected_tail)
  2398. new_protected_tail = w->l->ltq;
  2399. if (w->protected_tail > new_protected_tail) {
  2400. w->protected_tail = new_protected_tail;
  2401. /* Issue a store-store barrier. The update to protected_tail
  2402. here must precede the update to tail in the next spawn.
  2403. On x86 this is probably not needed. */
  2404. #if defined __GNUC__ && __ICC >= 1200 && !(__MIC__ ||__MIC2__)
  2405. _mm_sfence();
  2406. #else
  2407. __cilkrts_fence();
  2408. #endif
  2409. }
  2410. return saved_protected_tail;
  2411. }
  2412. /*************************************************************
  2413. Initialization and startup
  2414. *************************************************************/
  2415. __cilkrts_worker *make_worker(global_state_t *g,
  2416. int self, __cilkrts_worker *w)
  2417. {
  2418. w->self = self;
  2419. w->g = g;
  2420. w->pedigree.rank = 0; // Initial rank is 0
  2421. w->pedigree.parent = NULL;
  2422. w->l = (local_state *)__cilkrts_malloc(sizeof(*w->l));
  2423. __cilkrts_frame_malloc_per_worker_init(w);
  2424. w->reducer_map = NULL;
  2425. w->current_stack_frame = NULL;
  2426. w->reserved = NULL;
  2427. w->l->worker_magic_0 = WORKER_MAGIC_0;
  2428. w->l->team = NULL;
  2429. w->l->type = WORKER_FREE;
  2430. __cilkrts_mutex_init(&w->l->lock);
  2431. __cilkrts_mutex_init(&w->l->steal_lock);
  2432. w->l->do_not_steal = 0;
  2433. w->l->frame_ff = 0;
  2434. w->l->next_frame_ff = 0;
  2435. w->l->last_full_frame = NULL;
  2436. w->l->ltq = (__cilkrts_stack_frame **)
  2437. __cilkrts_malloc(g->ltqsize * sizeof(*w->l->ltq));
  2438. w->ltq_limit = w->l->ltq + g->ltqsize;
  2439. w->head = w->tail = w->l->ltq;
  2440. cilk_fiber_pool_init(&w->l->fiber_pool,
  2441. &g->fiber_pool,
  2442. g->stack_size,
  2443. g->fiber_pool_size,
  2444. 0, // alloc_max is 0. We don't allocate from the heap directly without checking the parent pool.
  2445. 0);
  2446. #if FIBER_DEBUG >= 2
  2447. fprintf(stderr, "ThreadId=%p: Making w=%d (%p), pool = %p\n",
  2448. cilkos_get_current_thread_id(),
  2449. w->self, w,
  2450. &w->l->fiber_pool);
  2451. #endif
  2452. w->l->scheduling_fiber = NULL;
  2453. w->l->original_pedigree_leaf = NULL;
  2454. w->l->rand_seed = 0; /* the scheduler will overwrite this field */
  2455. w->l->post_suspend = 0;
  2456. w->l->suspended_stack = 0;
  2457. w->l->fiber_to_free = NULL;
  2458. w->l->pending_exception = NULL;
  2459. #if CILK_PROFILE
  2460. w->l->stats = __cilkrts_malloc(sizeof(statistics));
  2461. __cilkrts_init_stats(w->l->stats);
  2462. #else
  2463. w->l->stats = NULL;
  2464. #endif
  2465. w->l->steal_failure_count = 0;
  2466. w->l->work_stolen = 0;
  2467. // Initialize record/replay assuming we're doing neither
  2468. w->l->record_replay_fptr = NULL;
  2469. w->l->replay_list_root = NULL;
  2470. w->l->replay_list_entry = NULL;
  2471. w->l->signal_node = NULL;
  2472. // Nothing's been stolen yet
  2473. w->l->worker_magic_1 = WORKER_MAGIC_1;
  2474. /*w->parallelism_disabled = 0;*/
  2475. // Allow stealing all frames. Sets w->saved_protected_tail
  2476. __cilkrts_restore_stealing(w, w->ltq_limit);
  2477. __cilkrts_init_worker_sysdep(w);
  2478. reset_THE_exception(w);
  2479. return w;
  2480. }
  2481. void destroy_worker(__cilkrts_worker *w)
  2482. {
  2483. CILK_ASSERT (NULL == w->l->pending_exception);
  2484. // Deallocate the scheduling fiber
  2485. if (NULL != w->l->scheduling_fiber)
  2486. {
  2487. // The scheduling fiber is the main fiber for system workers and must
  2488. // be deallocated by the thread that created it. Thus, we can
  2489. // deallocate only free workers' (formerly user workers) scheduling
  2490. // fibers here.
  2491. CILK_ASSERT(WORKER_FREE == w->l->type);
  2492. #if FIBER_DEBUG >=1
  2493. fprintf(stderr, "ThreadId=%p, w=%p, %d, deallocating scheduling fiber = %p, \n",
  2494. cilkos_get_current_thread_id(),
  2495. w,
  2496. w->self,
  2497. w->l->scheduling_fiber);
  2498. #endif
  2499. int ref_count = cilk_fiber_remove_reference(w->l->scheduling_fiber, NULL);
  2500. // Scheduling fiber should never have extra references because of exceptions.
  2501. CILK_ASSERT(0 == ref_count);
  2502. w->l->scheduling_fiber = NULL;
  2503. }
  2504. #if CILK_PROFILE
  2505. if (w->l->stats) {
  2506. __cilkrts_free(w->l->stats);
  2507. }
  2508. #else
  2509. CILK_ASSERT(NULL == w->l->stats);
  2510. #endif
  2511. /* Free any cached fibers. */
  2512. cilk_fiber_pool_destroy(&w->l->fiber_pool);
  2513. __cilkrts_destroy_worker_sysdep(w);
  2514. if (w->l->signal_node) {
  2515. CILK_ASSERT(WORKER_SYSTEM == w->l->type);
  2516. signal_node_destroy(w->l->signal_node);
  2517. }
  2518. __cilkrts_free(w->l->ltq);
  2519. __cilkrts_mutex_destroy(0, &w->l->lock);
  2520. __cilkrts_mutex_destroy(0, &w->l->steal_lock);
  2521. __cilkrts_frame_malloc_per_worker_cleanup(w);
  2522. __cilkrts_free(w->l);
  2523. // The caller is responsible for freeing the worker memory
  2524. }
  2525. /*
  2526. * Make a worker into a system worker.
  2527. */
  2528. static void make_worker_system(__cilkrts_worker *w) {
  2529. CILK_ASSERT(WORKER_FREE == w->l->type);
  2530. w->l->type = WORKER_SYSTEM;
  2531. w->l->signal_node = signal_node_create();
  2532. }
  2533. void __cilkrts_deinit_internal(global_state_t *g)
  2534. {
  2535. int i;
  2536. __cilkrts_worker *w;
  2537. // If there's no global state then we're done
  2538. if (NULL == g)
  2539. return;
  2540. #ifdef CILK_PROFILE
  2541. __cilkrts_dump_stats_to_stderr(g);
  2542. #endif
  2543. w = g->workers[0];
  2544. if (w->l->frame_ff) {
  2545. __cilkrts_destroy_full_frame(w, w->l->frame_ff);
  2546. w->l->frame_ff = 0;
  2547. }
  2548. // Release any resources used for record/replay
  2549. replay_term(g);
  2550. // Destroy any system dependent global state
  2551. __cilkrts_destroy_global_sysdep(g);
  2552. for (i = 0; i < g->total_workers; ++i)
  2553. destroy_worker(g->workers[i]);
  2554. // Free memory for all worker blocks which were allocated contiguously
  2555. __cilkrts_free(g->workers[0]);
  2556. __cilkrts_free(g->workers);
  2557. cilk_fiber_pool_destroy(&g->fiber_pool);
  2558. __cilkrts_frame_malloc_global_cleanup(g);
  2559. cilkg_deinit_global_state();
  2560. }
  2561. /*
  2562. * Wake the runtime by notifying the system workers that they can steal. The
  2563. * first user worker into the runtime should call this.
  2564. */
  2565. static void wake_runtime(global_state_t *g)
  2566. {
  2567. __cilkrts_worker *root;
  2568. if (g->P > 1) {
  2569. // Send a message to the root node. The message will propagate.
  2570. root = g->workers[0];
  2571. CILK_ASSERT(root->l->signal_node);
  2572. signal_node_msg(root->l->signal_node, 1);
  2573. }
  2574. }
  2575. /*
  2576. * Put the runtime to sleep. The last user worker out of the runtime should
  2577. * call this. Like Dad always said, turn out the lights when nobody's in the
  2578. * room.
  2579. */
  2580. static void sleep_runtime(global_state_t *g)
  2581. {
  2582. __cilkrts_worker *root;
  2583. if (g->P > 1) {
  2584. // Send a message to the root node. The message will propagate.
  2585. root = g->workers[0];
  2586. CILK_ASSERT(root->l->signal_node);
  2587. signal_node_msg(root->l->signal_node, 0);
  2588. }
  2589. }
  2590. /* Called when a user thread joins Cilk.
  2591. Global lock must be held. */
  2592. void __cilkrts_enter_cilk(global_state_t *g)
  2593. {
  2594. if (g->Q++ == 0) {
  2595. // If this is the first user thread to enter Cilk wake
  2596. // up all the workers.
  2597. wake_runtime(g);
  2598. }
  2599. }
  2600. /* Called when a user thread leaves Cilk.
  2601. Global lock must be held. */
  2602. void __cilkrts_leave_cilk(global_state_t *g)
  2603. {
  2604. if (--g->Q == 0) {
  2605. // Put the runtime to sleep.
  2606. sleep_runtime(g);
  2607. }
  2608. }
  2609. /*
  2610. * worker_runnable
  2611. *
  2612. * Return true if the worker should continue to try to steal. False, otherwise.
  2613. */
  2614. NOINLINE
  2615. static enum schedule_t worker_runnable(__cilkrts_worker *w)
  2616. {
  2617. global_state_t *g = w->g;
  2618. /* If this worker has something to do, do it.
  2619. Otherwise the work would be lost. */
  2620. if (w->l->next_frame_ff)
  2621. return SCHEDULE_RUN;
  2622. // If Cilk has explicitly (by the user) been told to exit (i.e., by
  2623. // __cilkrts_end_cilk() -> __cilkrts_stop_workers(g)), then return 0.
  2624. if (g->work_done)
  2625. return SCHEDULE_EXIT;
  2626. if (0 == w->self) {
  2627. // This worker is the root node and is the only one that may query the
  2628. // global state to see if there are still any user workers in Cilk.
  2629. if (w->l->steal_failure_count > g->max_steal_failures) {
  2630. if (signal_node_should_wait(w->l->signal_node)) {
  2631. return SCHEDULE_WAIT;
  2632. } else {
  2633. // Reset the steal_failure_count since we have verified that
  2634. // user workers are still in Cilk.
  2635. w->l->steal_failure_count = 0;
  2636. }
  2637. }
  2638. } else if (WORKER_SYSTEM == w->l->type &&
  2639. signal_node_should_wait(w->l->signal_node)) {
  2640. // This worker has been notified by its parent that it should stop
  2641. // trying to steal.
  2642. return SCHEDULE_WAIT;
  2643. }
  2644. return SCHEDULE_RUN;
  2645. }
  2646. // Initialize the worker structs, but don't start the workers themselves.
  2647. static void init_workers(global_state_t *g)
  2648. {
  2649. int total_workers = g->total_workers;
  2650. int i;
  2651. struct CILK_ALIGNAS(256) buffered_worker {
  2652. __cilkrts_worker w;
  2653. char buf[64];
  2654. } *workers_memory;
  2655. /* not needed if only one worker */
  2656. cilk_fiber_pool_init(&g->fiber_pool,
  2657. NULL,
  2658. g->stack_size,
  2659. g->global_fiber_pool_size, // buffer_size
  2660. g->max_stacks, // maximum # to allocate
  2661. 1);
  2662. cilk_fiber_pool_set_fiber_limit(&g->fiber_pool,
  2663. (g->max_stacks ? g->max_stacks : INT_MAX));
  2664. g->workers = (__cilkrts_worker **)
  2665. __cilkrts_malloc(total_workers * sizeof(*g->workers));
  2666. // Allocate 1 block of memory for workers to make life easier for tools
  2667. // like Inspector which run multithreaded and need to know the memory
  2668. // range for all the workers that will be accessed in a user's program
  2669. workers_memory = (struct buffered_worker*)
  2670. __cilkrts_malloc(sizeof(*workers_memory) * total_workers);
  2671. // Notify any tools that care (Cilkscreen and Inspector) that they should
  2672. // ignore memory allocated for the workers
  2673. __cilkrts_cilkscreen_ignore_block(&workers_memory[0],
  2674. &workers_memory[total_workers]);
  2675. // Initialize worker structs, including unused worker slots.
  2676. for (i = 0; i < total_workers; ++i) {
  2677. g->workers[i] = make_worker(g, i, &workers_memory[i].w);
  2678. }
  2679. // Set the workers in the first P - 1 slots to be system workers.
  2680. // Remaining worker structs already have type == 0.
  2681. for (i = 0; i < g->system_workers; ++i) {
  2682. make_worker_system(g->workers[i]);
  2683. }
  2684. }
  2685. void __cilkrts_init_internal(int start)
  2686. {
  2687. global_state_t *g = NULL;
  2688. if (cilkg_is_published()) {
  2689. g = cilkg_init_global_state();
  2690. }
  2691. else {
  2692. // We think the state has not been published yet.
  2693. // Grab the lock and try to initialize/publish.
  2694. global_os_mutex_lock();
  2695. if (cilkg_is_published()) {
  2696. // Some other thread must have snuck in and published.
  2697. g = cilkg_init_global_state();
  2698. }
  2699. else {
  2700. // Initialize and retrieve global state
  2701. g = cilkg_init_global_state();
  2702. // Set the scheduler pointer
  2703. g->scheduler = worker_scheduler_function;
  2704. // If we're running under a sequential P-Tool (Cilkscreen or
  2705. // Cilkview) then there's only one worker and we need to tell
  2706. // the tool about the extent of the stack
  2707. if (g->under_ptool)
  2708. __cilkrts_establish_c_stack();
  2709. init_workers(g);
  2710. // Initialize per-work record/replay logging
  2711. replay_init_workers(g);
  2712. // Initialize any system dependent global state
  2713. __cilkrts_init_global_sysdep(g);
  2714. cilkg_publish_global_state(g);
  2715. }
  2716. global_os_mutex_unlock();
  2717. }
  2718. CILK_ASSERT(g);
  2719. if (start && !g->workers_running)
  2720. {
  2721. // Acquire the global OS mutex while we're starting the workers
  2722. global_os_mutex_lock();
  2723. if (!g->workers_running)
  2724. // Start P - 1 system workers since P includes the first user
  2725. // worker.
  2726. __cilkrts_start_workers(g, g->P - 1);
  2727. global_os_mutex_unlock();
  2728. }
  2729. }
  2730. /************************************************************************
  2731. Methods for reducer protocol.
  2732. Reductions occur in two places:
  2733. A. A full frame "ff" is returning from a spawn with a stolen parent.
  2734. B. A full frame "ff" is stalling at a sync.
  2735. To support parallel reductions, reduction functions need to be
  2736. executed while control is on a user stack, before jumping into the
  2737. runtime. These reductions can not occur while holding a worker or
  2738. frame lock.
  2739. Before a worker w executes a reduction in either Case A or B, w's
  2740. deque is empty.
  2741. Since parallel reductions push work onto the deque, we must do extra
  2742. work to set up runtime data structures properly before reductions
  2743. begin to allow stealing. ( Normally, when we have only serial
  2744. reductions, once a worker w starts a reduction, its deque remains
  2745. empty until w either steals another frame or resumes a suspended
  2746. frame. Thus, we don't care about the state of the deque, since w
  2747. will reset its deque when setting up execution of a frame. )
  2748. To allow for parallel reductions, we coerce the runtime data
  2749. structures so that, from their perspective, it looks as though we
  2750. have spliced in an "execute_reductions()" function. Consider the
  2751. two cases for reductions:
  2752. Case A: Return from a spawn with a stolen parent.
  2753. Consider a spawned function g is returning on a worker w.
  2754. Assume:
  2755. - g was spawned from a parent function f.
  2756. - ff is the full frame for g's spawn helper
  2757. - sf be the __cilkrts_stack_frame for g's spawn helper.
  2758. We are conceptually splicing "execute_reductions()" so that it
  2759. occurs immediately before the spawn helper of g returns to f.
  2760. We do so by creating two different world views --- one for the
  2761. runtime data structures, and one for the actual control flow.
  2762. - Before reductions begin, the runtime data structures should
  2763. look as though the spawn helper of g is calling
  2764. "execute_reductions()", in terms of both the user stack and
  2765. worker deque. More precisely, w should satisfy the
  2766. following properties:
  2767. (a) w has ff as its full frame,
  2768. (b) w has sf as its __cilkrts_stack_frame, and
  2769. (c) w has an empty deque.
  2770. If the runtime satisfies these properties, then if w
  2771. encounters a spawn in a parallel reduction, it can push onto
  2772. a valid deque. Also, when a steal from w occurs, it will
  2773. build the correct tree of full frames when w is stolen from.
  2774. - In actual control flow, however, once the
  2775. "execute_reductions()" function returns, it is actually
  2776. returning to runtime code instead of g's spawn helper.
  2777. At the point a worker w began executing reductions, the
  2778. control flow / compiled code had already finished g's spawn
  2779. helper, and w was about to enter the runtime. With parallel
  2780. reductions, some worker v (which might be different from w)
  2781. is the one returning to the runtime.
  2782. The reduction logic consists of 4 steps:
  2783. A1. Restore runtime data structures to make it look as though
  2784. the spawn helper of g() is still the currently executing
  2785. frame for w.
  2786. A2. Execute reductions on the user stack. Reductions also
  2787. includes the logic for exceptions and stacks. Note that
  2788. reductions start on w, but may finish on a different
  2789. worker if there is parallelism in the reduce.
  2790. A3. Splice out ff from the tree of full frames.
  2791. A4. Jump into the runtime/scheduling stack and execute
  2792. "do_return_from_spawn". This method
  2793. (a) Frees the user stack we were just on if it is no longer needed.
  2794. (b) Decrement the join counter on ff->parent, and tries to do a
  2795. provably good steal.
  2796. (c) Clean up the full frame ff.
  2797. Case B: Stalling at a sync.
  2798. Consider a function g(), with full frame ff and
  2799. __cilkrts_stack_frame sf. Suppose g() stalls at a sync, and we
  2800. are executing reductions.
  2801. Conceptually, we are splicing in an "execute_reductions()"
  2802. function into g() as the last action that g() takes immediately
  2803. before it executes the cilk_sync.
  2804. The reduction logic for this case is similar to Case A.
  2805. B1. Restore the runtime data structures.
  2806. The main difference from Case A is that ff/sf is still a
  2807. frame that needs to be executed later (since it is stalling
  2808. at a cilk_sync). Thus, we also need to save the current
  2809. stack information into "ff" so that we can correctly resume
  2810. execution of "ff" after the sync.
  2811. B2. Execute reductions on the user stack.
  2812. B3. No frame to splice out of the tree.
  2813. B4. Jump into the runtime/scheduling stack and execute "do_sync".
  2814. This method:
  2815. (a) Frees the user stack we were just on if it is no longer needed.
  2816. (b) Tries to execute a provably good steal.
  2817. Finally, for the reducer protocol, we consider two reduction paths,
  2818. namely a "fast" and "slow" path. On a fast path, only trivial
  2819. merges of reducer maps happen (i.e., one or both of the maps are
  2820. NULL). Otherwise, on the slow path, a reduction actually needs to
  2821. happen.
  2822. *****************************************************************/
  2823. /**
  2824. * @brief Locations to store the result of a reduction.
  2825. *
  2826. * Struct storing pointers to the fields in our "left" sibling that we
  2827. * should update when splicing out a full frame or stalling at a sync.
  2828. */
  2829. typedef struct {
  2830. /** A pointer to the location of our left reducer map. */
  2831. struct cilkred_map **map_ptr;
  2832. /** A pointer to the location of our left exception. */
  2833. struct pending_exception_info **exception_ptr;
  2834. } splice_left_ptrs;
  2835. /**
  2836. * For a full frame returning from a spawn, calculate the pointers to
  2837. * the maps and exceptions to my left.
  2838. *
  2839. * @param w The currently executing worker.
  2840. * @param ff Full frame that is dying
  2841. * @return Pointers to our "left" for reducers and exceptions.
  2842. */
  2843. static inline
  2844. splice_left_ptrs compute_left_ptrs_for_spawn_return(__cilkrts_worker *w,
  2845. full_frame *ff)
  2846. {
  2847. // ASSERT: we hold the lock on ff->parent
  2848. splice_left_ptrs left_ptrs;
  2849. if (ff->left_sibling) {
  2850. left_ptrs.map_ptr = &ff->left_sibling->right_reducer_map;
  2851. left_ptrs.exception_ptr = &ff->left_sibling->right_pending_exception;
  2852. }
  2853. else {
  2854. full_frame *parent_ff = ff->parent;
  2855. left_ptrs.map_ptr = &parent_ff->children_reducer_map;
  2856. left_ptrs.exception_ptr = &parent_ff->child_pending_exception;
  2857. }
  2858. return left_ptrs;
  2859. }
  2860. /**
  2861. * For a full frame at a sync, calculate the pointers to the maps and
  2862. * exceptions to my left.
  2863. *
  2864. * @param w The currently executing worker.
  2865. * @param ff Full frame that is stalling at a sync.
  2866. * @return Pointers to our "left" for reducers and exceptions.
  2867. */
  2868. static inline
  2869. splice_left_ptrs compute_left_ptrs_for_sync(__cilkrts_worker *w,
  2870. full_frame *ff)
  2871. {
  2872. // ASSERT: we hold the lock on ff
  2873. splice_left_ptrs left_ptrs;
  2874. // Figure out which map to the left we should merge into.
  2875. if (ff->rightmost_child) {
  2876. CILK_ASSERT(ff->rightmost_child->parent == ff);
  2877. left_ptrs.map_ptr = &(ff->rightmost_child->right_reducer_map);
  2878. left_ptrs.exception_ptr = &(ff->rightmost_child->right_pending_exception);
  2879. }
  2880. else {
  2881. // We have no children. Then, we should be the last
  2882. // worker at the sync... "left" is our child map.
  2883. left_ptrs.map_ptr = &(ff->children_reducer_map);
  2884. left_ptrs.exception_ptr = &(ff->child_pending_exception);
  2885. }
  2886. return left_ptrs;
  2887. }
  2888. /**
  2889. * After we have completed all reductions on a spawn return, call this
  2890. * method to finish up before jumping into the runtime.
  2891. *
  2892. * 1. Perform the "reduction" on stacks, i.e., execute the left
  2893. * holder logic to pass the leftmost stack up.
  2894. *
  2895. * w->l->fiber_to_free holds any stack that needs to be freed
  2896. * when control switches into the runtime fiber.
  2897. *
  2898. * 2. Unlink and remove child_ff from the tree of full frames.
  2899. *
  2900. * @param w The currently executing worker.
  2901. * @param parent_ff The parent of child_ff.
  2902. * @param child_ff The full frame returning from a spawn.
  2903. */
  2904. static inline
  2905. void finish_spawn_return_on_user_stack(__cilkrts_worker *w,
  2906. full_frame *parent_ff,
  2907. full_frame *child_ff)
  2908. {
  2909. CILK_ASSERT(w->l->fiber_to_free == NULL);
  2910. // Execute left-holder logic for stacks.
  2911. if (child_ff->left_sibling || parent_ff->fiber_child) {
  2912. // Case where we are not the leftmost stack.
  2913. CILK_ASSERT(parent_ff->fiber_child != child_ff->fiber_self);
  2914. // Remember any fiber we need to free in the worker.
  2915. // After we jump into the runtime, we will actually do the
  2916. // free.
  2917. w->l->fiber_to_free = child_ff->fiber_self;
  2918. }
  2919. else {
  2920. // We are leftmost, pass stack/fiber up to parent.
  2921. // Thus, no stack/fiber to free.
  2922. parent_ff->fiber_child = child_ff->fiber_self;
  2923. w->l->fiber_to_free = NULL;
  2924. }
  2925. child_ff->fiber_self = NULL;
  2926. unlink_child(parent_ff, child_ff);
  2927. }
  2928. /**
  2929. * Executes any fast reductions necessary to splice ff out of the tree
  2930. * of full frames.
  2931. *
  2932. * This "fast" path performs only trivial merges of reducer maps,
  2933. * i.e,. when one of them is NULL.
  2934. * (See slow_path_reductions_for_spawn_return() for slow path.)
  2935. *
  2936. * Returns: 1 if we finished all reductions.
  2937. * Returns: 0 if there are still reductions to execute, and
  2938. * we should execute the slow path.
  2939. *
  2940. * This method assumes w holds the frame lock on parent_ff.
  2941. * After this method completes:
  2942. * 1. We have spliced ff out of the tree of full frames.
  2943. * 2. The reducer maps of child_ff have been deposited
  2944. * "left" according to the reducer protocol.
  2945. * 3. w->l->stack_to_free stores the stack
  2946. * that needs to be freed once we jump into the runtime.
  2947. *
  2948. * We have not, however, decremented the join counter on ff->parent.
  2949. * This prevents any other workers from resuming execution of the parent.
  2950. *
  2951. * @param w The currently executing worker.
  2952. * @param ff The full frame returning from a spawn.
  2953. * @return NULL if we finished all reductions.
  2954. * @return The address where the left map is stored (which should be passed to
  2955. * slow_path_reductions_for_spawn_return()) if there are
  2956. * still reductions to execute.
  2957. */
  2958. struct cilkred_map**
  2959. fast_path_reductions_for_spawn_return(__cilkrts_worker *w,
  2960. full_frame *ff)
  2961. {
  2962. // ASSERT: we hold ff->parent->lock.
  2963. splice_left_ptrs left_ptrs;
  2964. CILK_ASSERT(NULL == w->l->pending_exception);
  2965. // Figure out the pointers to the left where I want
  2966. // to put reducers and exceptions.
  2967. left_ptrs = compute_left_ptrs_for_spawn_return(w, ff);
  2968. // Go ahead and merge exceptions while holding the lock.
  2969. splice_exceptions_for_spawn(w, ff, left_ptrs.exception_ptr);
  2970. // Now check if we have any reductions to perform.
  2971. //
  2972. // Consider all the cases of left, middle and right maps.
  2973. // 0. (-, -, -) : finish and return 1
  2974. // 1. (L, -, -) : finish and return 1
  2975. // 2. (-, M, -) : slide over to left, finish, and return 1.
  2976. // 3. (L, M, -) : return 0
  2977. // 4. (-, -, R) : slide over to left, finish, and return 1.
  2978. // 5. (L, -, R) : return 0
  2979. // 6. (-, M, R) : return 0
  2980. // 7. (L, M, R) : return 0
  2981. //
  2982. // In terms of code:
  2983. // L == *left_ptrs.map_ptr
  2984. // M == w->reducer_map
  2985. // R == f->right_reducer_map.
  2986. //
  2987. // The goal of the code below is to execute the fast path with
  2988. // as few branches and writes as possible.
  2989. int case_value = (*(left_ptrs.map_ptr) != NULL);
  2990. case_value += ((w->reducer_map != NULL) << 1);
  2991. case_value += ((ff->right_reducer_map != NULL) << 2);
  2992. // Fastest path is case_value == 0 or 1.
  2993. if (case_value >=2) {
  2994. switch (case_value) {
  2995. case 2:
  2996. *(left_ptrs.map_ptr) = w->reducer_map;
  2997. w->reducer_map = NULL;
  2998. return NULL;
  2999. break;
  3000. case 4:
  3001. *(left_ptrs.map_ptr) = ff->right_reducer_map;
  3002. ff->right_reducer_map = NULL;
  3003. return NULL;
  3004. default:
  3005. // If we have to execute the slow path, then
  3006. // return the pointer to the place to deposit the left
  3007. // map.
  3008. return left_ptrs.map_ptr;
  3009. }
  3010. }
  3011. // Do nothing
  3012. return NULL;
  3013. }
  3014. /**
  3015. * Executes any reductions necessary to splice "ff" frame out of
  3016. * the steal tree.
  3017. *
  3018. * This method executes the "slow" path for reductions on a spawn
  3019. * return, i.e., there are non-NULL maps that need to be merged
  3020. * together.
  3021. *
  3022. * This method should execute only if
  3023. * fast_path_reductions_for_spawn_return() returns a non-NULL
  3024. * left_map_ptr.
  3025. *
  3026. * Upon entry, left_map_ptr should be the location of the left map
  3027. * at the start of the reduction, as calculated by
  3028. * fast_path_reductions_for_spawn_return().
  3029. *
  3030. * After this method completes:
  3031. * 1. We have spliced ff out of the tree of full frames.
  3032. * 2. The reducer maps of child_ff have been deposited
  3033. * "left" according to the reducer protocol.
  3034. * 3. w->l->stack_to_free stores the stack
  3035. * that needs to be freed once we jump into the runtime.
  3036. * We have not, however, decremented the join counter on ff->parent,
  3037. * so no one can resume execution of the parent yet.
  3038. *
  3039. * WARNING:
  3040. * This method assumes the lock on ff->parent is held upon entry, and
  3041. * Upon exit, the worker that returns still holds a lock on ff->parent
  3042. * This method can, however, release and reacquire the lock on ff->parent.
  3043. *
  3044. * @param w The currently executing worker.
  3045. * @param ff The full frame returning from a spawn.
  3046. * @param left_map_ptr Pointer to our initial left map.
  3047. * @return The worker that this method returns on.
  3048. */
  3049. static __cilkrts_worker*
  3050. slow_path_reductions_for_spawn_return(__cilkrts_worker *w,
  3051. full_frame *ff,
  3052. struct cilkred_map **left_map_ptr)
  3053. {
  3054. // CILK_ASSERT: w is holding frame lock on parent_ff.
  3055. #if REDPAR_DEBUG > 0
  3056. CILK_ASSERT(!ff->rightmost_child);
  3057. CILK_ASSERT(!ff->is_call_child);
  3058. #endif
  3059. // Loop invariant:
  3060. // When beginning this loop, we should
  3061. // 1. Be holding the lock on ff->parent.
  3062. // 2. left_map_ptr should be the address of the pointer to the left map.
  3063. // 3. All maps should be slid over left by one, if possible.
  3064. // 4. All exceptions should be merged so far.
  3065. while (1) {
  3066. // Slide middle map left if possible.
  3067. if (!(*left_map_ptr)) {
  3068. *left_map_ptr = w->reducer_map;
  3069. w->reducer_map = NULL;
  3070. }
  3071. // Slide right map to middle if possible.
  3072. if (!w->reducer_map) {
  3073. w->reducer_map = ff->right_reducer_map;
  3074. ff->right_reducer_map = NULL;
  3075. }
  3076. // Since we slid everything left by one,
  3077. // we are finished if there is no middle map.
  3078. if (!w->reducer_map) {
  3079. verify_current_wkr(w);
  3080. return w;
  3081. }
  3082. else {
  3083. struct cilkred_map* left_map;
  3084. struct cilkred_map* middle_map;
  3085. struct cilkred_map* right_map;
  3086. // Take all the maps from their respective locations.
  3087. // We can't leave them in place and execute a reduction because these fields
  3088. // might change once we release the lock.
  3089. left_map = *left_map_ptr;
  3090. *left_map_ptr = NULL;
  3091. middle_map = w->reducer_map;
  3092. w->reducer_map = NULL;
  3093. right_map = ff->right_reducer_map;
  3094. ff->right_reducer_map = NULL;
  3095. // WARNING!!! Lock release here.
  3096. // We have reductions to execute (and we can't hold locks).
  3097. __cilkrts_frame_unlock(w, ff->parent);
  3098. // Merge all reducers into the left map.
  3099. left_map = repeated_merge_reducer_maps(&w,
  3100. left_map,
  3101. middle_map);
  3102. verify_current_wkr(w);
  3103. left_map = repeated_merge_reducer_maps(&w,
  3104. left_map,
  3105. right_map);
  3106. verify_current_wkr(w);
  3107. CILK_ASSERT(NULL == w->reducer_map);
  3108. // Put the final answer back into w->reducer_map.
  3109. w->reducer_map = left_map;
  3110. // Save any exceptions generated because of the reduction
  3111. // process from the returning worker. These get merged
  3112. // the next time around the loop.
  3113. CILK_ASSERT(NULL == ff->pending_exception);
  3114. ff->pending_exception = w->l->pending_exception;
  3115. w->l->pending_exception = NULL;
  3116. // Lock ff->parent for the next loop around.
  3117. __cilkrts_frame_lock(w, ff->parent);
  3118. // Once we have the lock again, recompute who is to our
  3119. // left.
  3120. splice_left_ptrs left_ptrs;
  3121. left_ptrs = compute_left_ptrs_for_spawn_return(w, ff);
  3122. // Update the pointer for the left map.
  3123. left_map_ptr = left_ptrs.map_ptr;
  3124. // Splice the exceptions for spawn.
  3125. splice_exceptions_for_spawn(w, ff, left_ptrs.exception_ptr);
  3126. }
  3127. }
  3128. // We should never break out of this loop.
  3129. CILK_ASSERT(0);
  3130. return NULL;
  3131. }
  3132. /**
  3133. * Execute reductions when returning from a spawn whose parent has
  3134. * been stolen.
  3135. *
  3136. * Execution may start on w, but may finish on a different worker.
  3137. * This method acquires/releases the lock on ff->parent.
  3138. *
  3139. * @param w The currently executing worker.
  3140. * @param ff The full frame of the spawned function that is returning.
  3141. * @param returning_sf The __cilkrts_stack_frame for this returning function.
  3142. * @return The worker returning from this method.
  3143. */
  3144. static __cilkrts_worker*
  3145. execute_reductions_for_spawn_return(__cilkrts_worker *w,
  3146. full_frame *ff,
  3147. __cilkrts_stack_frame *returning_sf)
  3148. {
  3149. // Step A1 from reducer protocol described above.
  3150. //
  3151. // Coerce the runtime into thinking that
  3152. // ff/returning_sf are still on the bottom of
  3153. // w's deque.
  3154. restore_frame_for_spawn_return_reduction(w, ff, returning_sf);
  3155. // Step A2 and A3: Execute reductions on user stack.
  3156. BEGIN_WITH_FRAME_LOCK(w, ff->parent) {
  3157. struct cilkred_map **left_map_ptr;
  3158. left_map_ptr = fast_path_reductions_for_spawn_return(w, ff);
  3159. // Pointer will be non-NULL if there are
  3160. // still reductions to execute.
  3161. if (left_map_ptr) {
  3162. // WARNING: This method call may release the lock
  3163. // on ff->parent and re-acquire it (possibly on a
  3164. // different worker).
  3165. // We can't hold locks while actually executing
  3166. // reduce functions.
  3167. w = slow_path_reductions_for_spawn_return(w,
  3168. ff,
  3169. left_map_ptr);
  3170. verify_current_wkr(w);
  3171. }
  3172. finish_spawn_return_on_user_stack(w, ff->parent, ff);
  3173. // WARNING: the use of this lock macro is deceptive.
  3174. // The worker may have changed here.
  3175. } END_WITH_FRAME_LOCK(w, ff->parent);
  3176. return w;
  3177. }
  3178. /**
  3179. * Execute fast "reductions" when ff stalls at a sync.
  3180. *
  3181. * @param w The currently executing worker.
  3182. * @param ff The full frame stalling at a sync.
  3183. * @return 1 if we are finished with all reductions after calling this method.
  3184. * @return 0 if we still need to execute the slow path reductions.
  3185. */
  3186. static inline
  3187. int fast_path_reductions_for_sync(__cilkrts_worker *w,
  3188. full_frame *ff) {
  3189. // Return 0 if there is some reduction that needs to happen.
  3190. return !(w->reducer_map || ff->pending_exception);
  3191. }
  3192. /**
  3193. * Executes slow reductions when ff stalls at a sync.
  3194. * This method should execute only if
  3195. * fast_path_reductions_for_sync(w, ff) returned 0.
  3196. *
  3197. * After this method completes:
  3198. * 1. ff's current reducer map has been deposited into
  3199. * right_reducer_map of ff's rightmost child, or
  3200. * ff->children_reducer_map if ff has no children.
  3201. * 2. Similarly for ff's current exception.
  3202. * 3. Nothing to calculate for stacks --- if we are stalling
  3203. * we will always free a stack.
  3204. *
  3205. * This method may repeatedly acquire/release the lock on ff.
  3206. *
  3207. * @param w The currently executing worker.
  3208. * @param ff The full frame stalling at a sync.
  3209. * @return The worker returning from this method.
  3210. */
  3211. static __cilkrts_worker*
  3212. slow_path_reductions_for_sync(__cilkrts_worker *w,
  3213. full_frame *ff)
  3214. {
  3215. struct cilkred_map *left_map;
  3216. struct cilkred_map *middle_map;
  3217. #if (REDPAR_DEBUG > 0)
  3218. CILK_ASSERT(ff);
  3219. CILK_ASSERT(w->head == w->tail);
  3220. #endif
  3221. middle_map = w->reducer_map;
  3222. w->reducer_map = NULL;
  3223. // Loop invariant: middle_map should be valid (the current map to reduce).
  3224. // left_map is junk.
  3225. // w->reducer_map == NULL.
  3226. while (1) {
  3227. BEGIN_WITH_FRAME_LOCK(w, ff) {
  3228. splice_left_ptrs left_ptrs = compute_left_ptrs_for_sync(w, ff);
  3229. // Grab the "left" map and store pointers to those locations.
  3230. left_map = *(left_ptrs.map_ptr);
  3231. *(left_ptrs.map_ptr) = NULL;
  3232. // Slide the maps in our struct left as far as possible.
  3233. if (!left_map) {
  3234. left_map = middle_map;
  3235. middle_map = NULL;
  3236. }
  3237. *(left_ptrs.exception_ptr) =
  3238. __cilkrts_merge_pending_exceptions(w,
  3239. *left_ptrs.exception_ptr,
  3240. ff->pending_exception);
  3241. ff->pending_exception = NULL;
  3242. // If there is no middle map, then we are done.
  3243. // Deposit left and return.
  3244. if (!middle_map) {
  3245. *(left_ptrs).map_ptr = left_map;
  3246. #if (REDPAR_DEBUG > 0)
  3247. CILK_ASSERT(NULL == w->reducer_map);
  3248. #endif
  3249. // Sanity check upon leaving the loop.
  3250. verify_current_wkr(w);
  3251. // Make sure to unlock before we return!
  3252. __cilkrts_frame_unlock(w, ff);
  3253. return w;
  3254. }
  3255. } END_WITH_FRAME_LOCK(w, ff);
  3256. // If we get here, we have a nontrivial reduction to execute.
  3257. middle_map = repeated_merge_reducer_maps(&w,
  3258. left_map,
  3259. middle_map);
  3260. verify_current_wkr(w);
  3261. // Save any exceptions generated because of the reduction
  3262. // process. These get merged the next time around the
  3263. // loop.
  3264. CILK_ASSERT(NULL == ff->pending_exception);
  3265. ff->pending_exception = w->l->pending_exception;
  3266. w->l->pending_exception = NULL;
  3267. }
  3268. // We should never break out of the loop above.
  3269. CILK_ASSERT(0);
  3270. return NULL;
  3271. }
  3272. /**
  3273. * Execute reductions when ff stalls at a sync.
  3274. *
  3275. * Execution starts on w, but may finish on a different worker.
  3276. * This method may acquire/release the lock on ff.
  3277. *
  3278. * @param w The currently executing worker.
  3279. * @param ff The full frame of the spawned function at the sync
  3280. * @param sf_at_sync The __cilkrts_stack_frame stalling at a sync
  3281. * @return The worker returning from this method.
  3282. */
  3283. static __cilkrts_worker*
  3284. execute_reductions_for_sync(__cilkrts_worker *w,
  3285. full_frame *ff,
  3286. __cilkrts_stack_frame *sf_at_sync)
  3287. {
  3288. int finished_reductions;
  3289. // Step B1 from reducer protocol above:
  3290. // Restore runtime invariants.
  3291. //
  3292. // The following code for this step is almost equivalent to
  3293. // the following sequence:
  3294. // 1. disown(w, ff, sf_at_sync, "sync") (which itself
  3295. // calls make_unrunnable(w, ff, sf_at_sync))
  3296. // 2. make_runnable(w, ff, sf_at_sync).
  3297. //
  3298. // The "disown" will mark the frame "sf_at_sync"
  3299. // as stolen and suspended, and save its place on the stack,
  3300. // so it can be resumed after the sync.
  3301. //
  3302. // The difference is, that we don't want the disown to
  3303. // break the following connections yet, since we are
  3304. // about to immediately make sf/ff runnable again anyway.
  3305. // sf_at_sync->worker == w
  3306. // w->l->frame_ff == ff.
  3307. //
  3308. // These connections are needed for parallel reductions, since
  3309. // we will use sf / ff as the stack frame / full frame for
  3310. // executing any potential reductions.
  3311. //
  3312. // TBD: Can we refactor the disown / make_unrunnable code
  3313. // to avoid the code duplication here?
  3314. ff->call_stack = NULL;
  3315. // Normally, "make_unrunnable" would add CILK_FRAME_STOLEN and
  3316. // CILK_FRAME_SUSPENDED to sf_at_sync->flags and save the state of
  3317. // the stack so that a worker can resume the frame in the correct
  3318. // place.
  3319. //
  3320. // But on this path, CILK_FRAME_STOLEN should already be set.
  3321. // Also, we technically don't want to suspend the frame until
  3322. // the reduction finishes.
  3323. // We do, however, need to save the stack before
  3324. // we start any reductions, since the reductions might push more
  3325. // data onto the stack.
  3326. CILK_ASSERT(sf_at_sync->flags | CILK_FRAME_STOLEN);
  3327. __cilkrts_put_stack(ff, sf_at_sync);
  3328. __cilkrts_make_unrunnable_sysdep(w, ff, sf_at_sync, 1,
  3329. "execute_reductions_for_sync");
  3330. CILK_ASSERT(w->l->frame_ff == ff);
  3331. // Step B2: Execute reductions on user stack.
  3332. // Check if we have any "real" reductions to do.
  3333. finished_reductions = fast_path_reductions_for_sync(w, ff);
  3334. if (!finished_reductions) {
  3335. // Still have some real reductions to execute.
  3336. // Run them here.
  3337. // This method may acquire/release the lock on ff.
  3338. w = slow_path_reductions_for_sync(w, ff);
  3339. // The previous call may return on a different worker.
  3340. // than what we started on.
  3341. verify_current_wkr(w);
  3342. }
  3343. #if REDPAR_DEBUG >= 0
  3344. CILK_ASSERT(w->l->frame_ff == ff);
  3345. CILK_ASSERT(ff->call_stack == NULL);
  3346. #endif
  3347. // Now we suspend the frame ff (since we've
  3348. // finished the reductions). Roughly, we've split apart the
  3349. // "make_unrunnable" call here --- we've already saved the
  3350. // stack info earlier before the reductions execute.
  3351. // All that remains is to restore the call stack back into the
  3352. // full frame, and mark the frame as suspended.
  3353. ff->call_stack = sf_at_sync;
  3354. sf_at_sync->flags |= CILK_FRAME_SUSPENDED;
  3355. // At a nontrivial sync, we should always free the current fiber,
  3356. // because it can not be leftmost.
  3357. w->l->fiber_to_free = ff->fiber_self;
  3358. ff->fiber_self = NULL;
  3359. return w;
  3360. }
  3361. /*
  3362. Local Variables: **
  3363. c-file-style:"bsd" **
  3364. c-basic-offset:4 **
  3365. indent-tabs-mode:nil **
  3366. End: **
  3367. */