main.c 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <curses.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <unistd.h>
  18. #include <sys/time.h>
  19. #include <time.h>
  20. #include <math.h>
  21. #include <stdarg.h>
  22. #include <assert.h>
  23. #include <signal.h>
  24. #ifndef WIN32
  25. #include <sys/resource.h>
  26. #endif
  27. #include <ccan/opt/opt.h>
  28. #include <jansson.h>
  29. #include <curl/curl.h>
  30. #include "compat.h"
  31. #include "miner.h"
  32. #include "findnonce.h"
  33. #include "bench_block.h"
  34. #include "ocl.h"
  35. #if defined(unix)
  36. #include <errno.h>
  37. #include <fcntl.h>
  38. #include <unistd.h>
  39. #include <sys/wait.h>
  40. #include <sys/types.h>
  41. #endif
  42. #define PROGRAM_NAME "cgminer"
  43. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  44. #define DEF_RPC_USERNAME "rpcuser"
  45. #define DEF_RPC_PASSWORD "rpcpass"
  46. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  47. #ifdef __linux /* Linux specific policy and affinity management */
  48. #include <sched.h>
  49. static inline void drop_policy(void)
  50. {
  51. struct sched_param param;
  52. #ifdef SCHED_BATCH
  53. #ifdef SCHED_IDLE
  54. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  55. #endif
  56. sched_setscheduler(0, SCHED_BATCH, &param);
  57. #endif
  58. }
  59. static inline void affine_to_cpu(int id, int cpu)
  60. {
  61. cpu_set_t set;
  62. CPU_ZERO(&set);
  63. CPU_SET(cpu, &set);
  64. sched_setaffinity(0, sizeof(&set), &set);
  65. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  66. }
  67. #else
  68. static inline void drop_policy(void)
  69. {
  70. }
  71. static inline void affine_to_cpu(int id, int cpu)
  72. {
  73. }
  74. #endif
  75. enum workio_commands {
  76. WC_GET_WORK,
  77. WC_SUBMIT_WORK,
  78. WC_DIE,
  79. };
  80. struct workio_cmd {
  81. enum workio_commands cmd;
  82. struct thr_info *thr;
  83. union {
  84. struct work *work;
  85. } u;
  86. bool lagging;
  87. };
  88. enum sha256_algos {
  89. ALGO_C, /* plain C */
  90. ALGO_4WAY, /* parallel SSE2 */
  91. ALGO_VIA, /* VIA padlock */
  92. ALGO_CRYPTOPP, /* Crypto++ (C) */
  93. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  94. ALGO_SSE2_64, /* SSE2 for x86_64 */
  95. ALGO_SSE4_64, /* SSE4 for x86_64 */
  96. };
  97. enum pool_strategy {
  98. POOL_FAILOVER,
  99. POOL_ROUNDROBIN,
  100. POOL_ROTATE,
  101. POOL_LOADBALANCE,
  102. };
  103. #define TOP_STRATEGY (POOL_LOADBALANCE)
  104. struct strategies {
  105. const char *s;
  106. } strategies[] = {
  107. { "Failover" },
  108. { "Round Robin" },
  109. { "Rotate" },
  110. { "Load Balance" },
  111. };
  112. static size_t max_name_len = 0;
  113. static char *name_spaces_pad = NULL;
  114. static const char *algo_names[] = {
  115. [ALGO_C] = "c",
  116. #ifdef WANT_SSE2_4WAY
  117. [ALGO_4WAY] = "4way",
  118. #endif
  119. #ifdef WANT_VIA_PADLOCK
  120. [ALGO_VIA] = "via",
  121. #endif
  122. [ALGO_CRYPTOPP] = "cryptopp",
  123. #ifdef WANT_CRYPTOPP_ASM32
  124. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  125. #endif
  126. #ifdef WANT_X8664_SSE2
  127. [ALGO_SSE2_64] = "sse2_64",
  128. #endif
  129. #ifdef WANT_X8664_SSE4
  130. [ALGO_SSE4_64] = "sse4_64",
  131. #endif
  132. };
  133. typedef void (*sha256_func)();
  134. static const sha256_func sha256_funcs[] = {
  135. [ALGO_C] = (sha256_func)scanhash_c,
  136. #ifdef WANT_SSE2_4WAY
  137. [ALGO_4WAY] = (sha256_func)ScanHash_4WaySSE2,
  138. #endif
  139. #ifdef WANT_VIA_PADLOCK
  140. [ALGO_VIA] = (sha256_func)scanhash_via,
  141. #endif
  142. [ALGO_CRYPTOPP] = (sha256_func)scanhash_cryptopp,
  143. #ifdef WANT_CRYPTOPP_ASM32
  144. [ALGO_CRYPTOPP_ASM32] = (sha256_func)scanhash_asm32,
  145. #endif
  146. #ifdef WANT_X8664_SSE2
  147. [ALGO_SSE2_64] = (sha256_func)scanhash_sse2_64,
  148. #endif
  149. #ifdef WANT_X8664_SSE4
  150. [ALGO_SSE4_64] = (sha256_func)scanhash_sse4_64
  151. #endif
  152. };
  153. bool opt_debug = false;
  154. bool opt_protocol = false;
  155. static bool want_longpoll = true;
  156. static bool have_longpoll = false;
  157. static bool want_per_device_stats = false;
  158. bool use_syslog = false;
  159. static bool opt_quiet = false;
  160. static bool opt_realquiet = false;
  161. static bool opt_loginput = false;
  162. static int opt_retries = -1;
  163. static int opt_fail_pause = 5;
  164. static int opt_log_interval = 5;
  165. bool opt_log_output = false;
  166. static bool opt_dynamic = true;
  167. static int opt_queue;
  168. int opt_vectors;
  169. int opt_worksize;
  170. int opt_scantime = 60;
  171. int opt_bench_algo = -1;
  172. static const bool opt_time = true;
  173. #if defined(WANT_X8664_SSE4) && defined(__SSE4_1__)
  174. static enum sha256_algos opt_algo = ALGO_SSE4_64;
  175. #elif defined(WANT_X8664_SSE2) && defined(__SSE2__)
  176. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  177. #else
  178. static enum sha256_algos opt_algo = ALGO_C;
  179. #endif
  180. static int nDevs;
  181. static int opt_g_threads = 2;
  182. static int opt_device;
  183. static int total_devices;
  184. static bool gpu_devices[16];
  185. static int gpu_threads;
  186. static bool forced_n_threads;
  187. static int opt_n_threads;
  188. static int mining_threads;
  189. static int num_processors;
  190. static int scan_intensity;
  191. static bool use_curses = true;
  192. static bool opt_submit_stale;
  193. #define QUIET (opt_quiet || opt_realquiet)
  194. struct thr_info *thr_info;
  195. static int work_thr_id;
  196. int longpoll_thr_id;
  197. static int stage_thr_id;
  198. static int watchdog_thr_id;
  199. static int input_thr_id;
  200. static int gpur_thr_id;
  201. static int cpur_thr_id;
  202. static int total_threads;
  203. struct work_restart *work_restart = NULL;
  204. static pthread_mutex_t hash_lock;
  205. static pthread_mutex_t qd_lock;
  206. static pthread_mutex_t stgd_lock;
  207. static pthread_mutex_t curses_lock;
  208. static double total_mhashes_done;
  209. static struct timeval total_tv_start, total_tv_end;
  210. pthread_mutex_t control_lock;
  211. int hw_errors;
  212. static int total_accepted, total_rejected;
  213. static int total_getworks, total_stale, total_discarded;
  214. static int total_queued, total_staged, lp_staged;
  215. static unsigned int new_blocks;
  216. enum block_change {
  217. BLOCK_NONE,
  218. BLOCK_LP,
  219. BLOCK_DETECT,
  220. BLOCK_FIRST,
  221. };
  222. static enum block_change block_changed = BLOCK_FIRST;
  223. static unsigned int local_work;
  224. static unsigned int total_lo, total_ro;
  225. #define MAX_POOLS (32)
  226. static struct pool *pools[MAX_POOLS];
  227. static struct pool *currentpool = NULL;
  228. static int total_pools;
  229. static enum pool_strategy pool_strategy = POOL_FAILOVER;
  230. static int opt_rotate_period;
  231. static int total_urls, total_users, total_passes, total_userpasses;
  232. static bool curses_active = false;
  233. static char current_block[37];
  234. static char *current_hash;
  235. static char datestamp[40];
  236. static char blocktime[30];
  237. static char *opt_kernel = NULL;
  238. #if defined(unix)
  239. static char *opt_stderr_cmd = NULL;
  240. #endif // defined(unix)
  241. enum cl_kernel chosen_kernel;
  242. static bool ping = true;
  243. struct sigaction termhandler, inthandler;
  244. struct thread_q *getq;
  245. void get_datestamp(char *f, struct timeval *tv)
  246. {
  247. struct tm tm;
  248. localtime_r(&tv->tv_sec, &tm);
  249. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  250. tm.tm_year + 1900,
  251. tm.tm_mon + 1,
  252. tm.tm_mday,
  253. tm.tm_hour,
  254. tm.tm_min,
  255. tm.tm_sec);
  256. }
  257. void get_timestamp(char *f, struct timeval *tv)
  258. {
  259. struct tm tm;
  260. localtime_r(&tv->tv_sec, &tm);
  261. sprintf(f, "[%02d:%02d:%02d]",
  262. tm.tm_hour,
  263. tm.tm_min,
  264. tm.tm_sec);
  265. }
  266. static void applog_and_exit(const char *fmt, ...)
  267. {
  268. va_list ap;
  269. va_start(ap, fmt);
  270. vapplog(LOG_ERR, fmt, ap);
  271. va_end(ap);
  272. exit(1);
  273. }
  274. static void add_pool(void)
  275. {
  276. struct pool *pool;
  277. pool = calloc(sizeof(struct pool), 1);
  278. if (!pool) {
  279. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  280. exit (1);
  281. }
  282. pool->pool_no = pool->prio = total_pools;
  283. pools[total_pools++] = pool;
  284. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  285. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  286. exit (1);
  287. }
  288. /* Make sure the pool doesn't think we've been idle since time 0 */
  289. pool->tv_idle.tv_sec = ~0UL;
  290. }
  291. /* Pool variant of test and set */
  292. static bool pool_tset(struct pool *pool, bool *var)
  293. {
  294. bool ret;
  295. mutex_lock(&pool->pool_lock);
  296. ret = *var;
  297. *var = true;
  298. mutex_unlock(&pool->pool_lock);
  299. return ret;
  300. }
  301. static bool pool_tclear(struct pool *pool, bool *var)
  302. {
  303. bool ret;
  304. mutex_lock(&pool->pool_lock);
  305. ret = *var;
  306. *var = false;
  307. mutex_unlock(&pool->pool_lock);
  308. return ret;
  309. }
  310. static struct pool *current_pool(void)
  311. {
  312. struct pool *pool;
  313. mutex_lock(&control_lock);
  314. pool = currentpool;
  315. mutex_unlock(&control_lock);
  316. return pool;
  317. }
  318. // Algo benchmark, crash-prone, system independent stage
  319. static double bench_algo_stage3(
  320. enum sha256_algos algo
  321. )
  322. {
  323. // Use a random work block pulled from a pool
  324. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  325. struct work work __attribute__((aligned(128)));
  326. size_t bench_size = sizeof(work);
  327. size_t work_size = sizeof(bench_block);
  328. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  329. memset(&work, 0, sizeof(work));
  330. memcpy(&work, &bench_block, min_size);
  331. struct work_restart dummy;
  332. work_restart = &dummy;
  333. struct timeval end;
  334. struct timeval start;
  335. uint32_t max_nonce = (1<<22);
  336. unsigned long hashes_done = 0;
  337. gettimeofday(&start, 0);
  338. #if defined(WANT_VIA_PADLOCK)
  339. // For some reason, the VIA padlock hasher has a different API ...
  340. if (ALGO_VIA==algo) {
  341. (void)scanhash_via(
  342. 0,
  343. work.data,
  344. work.target,
  345. max_nonce,
  346. &hashes_done,
  347. work.blk.nonce
  348. );
  349. } else
  350. #endif
  351. {
  352. sha256_func func = sha256_funcs[algo];
  353. (*func)(
  354. 0,
  355. work.midstate,
  356. work.data + 64,
  357. work.hash1,
  358. work.hash,
  359. work.target,
  360. max_nonce,
  361. &hashes_done,
  362. work.blk.nonce
  363. );
  364. }
  365. gettimeofday(&end, 0);
  366. work_restart = NULL;
  367. uint64_t usec_end = ((uint64_t)end.tv_sec)*1000*1000 + end.tv_usec;
  368. uint64_t usec_start = ((uint64_t)start.tv_sec)*1000*1000 + start.tv_usec;
  369. uint64_t usec_elapsed = usec_end - usec_start;
  370. double rate = -1.0;
  371. if (0<usec_elapsed) {
  372. rate = (1.0*hashes_done)/usec_elapsed;
  373. }
  374. return rate;
  375. }
  376. #if defined(unix)
  377. // Change non-blocking status on a file descriptor
  378. static void set_non_blocking(
  379. int fd,
  380. int yes
  381. )
  382. {
  383. int flags = fcntl(fd, F_GETFL, 0);
  384. if (flags<0) {
  385. perror("fcntl(GET) failed");
  386. exit(1);
  387. }
  388. flags = yes ? (flags|O_NONBLOCK) : (flags&~O_NONBLOCK);
  389. int r = fcntl(fd, F_SETFL, flags);
  390. if (r<0) {
  391. perror("fcntl(SET) failed");
  392. exit(1);
  393. }
  394. }
  395. #endif // defined(unix)
  396. // Algo benchmark, crash-safe, system-dependent stage
  397. static double bench_algo_stage2(
  398. enum sha256_algos algo
  399. )
  400. {
  401. // Here, the gig is to safely run a piece of code that potentially
  402. // crashes. Unfortunately, the Right Way (tm) to do this is rather
  403. // heavily platform dependent :(
  404. double rate = -1.23457;
  405. #if defined(unix)
  406. // Make a pipe: [readFD, writeFD]
  407. int pfd[2];
  408. int r = pipe(pfd);
  409. if (r<0) {
  410. perror("pipe - failed to create pipe for --algo auto");
  411. exit(1);
  412. }
  413. // Make pipe non blocking
  414. set_non_blocking(pfd[0], 1);
  415. set_non_blocking(pfd[1], 1);
  416. // Don't allow a crashing child to kill the main process
  417. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  418. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  419. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  420. perror("signal - failed to edit signal mask for --algo auto");
  421. exit(1);
  422. }
  423. // Fork a child to do the actual benchmarking
  424. pid_t child_pid = fork();
  425. if (child_pid<0) {
  426. perror("fork - failed to create a child process for --algo auto");
  427. exit(1);
  428. }
  429. // Do the dangerous work in the child, knowing we might crash
  430. if (0==child_pid) {
  431. // TODO: some umask trickery to prevent coredumps
  432. // Benchmark this algorithm
  433. double r = bench_algo_stage3(algo);
  434. // We survived, send result to parent and bail
  435. int loop_count = 0;
  436. while (1) {
  437. ssize_t bytes_written = write(pfd[1], &r, sizeof(r));
  438. int try_again = (0==bytes_written || (bytes_written<0 && EAGAIN==errno));
  439. int success = (sizeof(r)==(size_t)bytes_written);
  440. if (success)
  441. break;
  442. if (!try_again) {
  443. perror("write - child failed to write benchmark result to pipe");
  444. exit(1);
  445. }
  446. if (5<loop_count) {
  447. applog(LOG_ERR, "child tried %d times to communicate with parent, giving up", loop_count);
  448. exit(1);
  449. }
  450. ++loop_count;
  451. sleep(1);
  452. }
  453. exit(0);
  454. }
  455. // Parent waits for a result from child
  456. int loop_count = 0;
  457. while (1) {
  458. // Wait for child to die
  459. int status;
  460. int r = waitpid(child_pid, &status, WNOHANG);
  461. if ((child_pid==r) || (r<0 && ECHILD==errno)) {
  462. // Child died somehow. Grab result and bail
  463. double tmp;
  464. ssize_t bytes_read = read(pfd[0], &tmp, sizeof(tmp));
  465. if (sizeof(tmp)==(size_t)bytes_read)
  466. rate = tmp;
  467. break;
  468. } else if (r<0) {
  469. perror("bench_algo: waitpid failed. giving up.");
  470. exit(1);
  471. }
  472. // Give up on child after a ~60s
  473. if (60<loop_count) {
  474. kill(child_pid, SIGKILL);
  475. waitpid(child_pid, &status, 0);
  476. break;
  477. }
  478. // Wait a bit longer
  479. ++loop_count;
  480. sleep(1);
  481. }
  482. // Close pipe
  483. r = close(pfd[0]);
  484. if (r<0) {
  485. perror("close - failed to close read end of pipe for --algo auto");
  486. exit(1);
  487. }
  488. r = close(pfd[1]);
  489. if (r<0) {
  490. perror("close - failed to close read end of pipe for --algo auto");
  491. exit(1);
  492. }
  493. #elif defined(WIN32)
  494. // Get handle to current exe
  495. HINSTANCE module = GetModuleHandle(0);
  496. if (!module) {
  497. applog(LOG_ERR, "failed to retrieve module handle");
  498. exit(1);
  499. }
  500. // Create a unique name
  501. char unique_name[32];
  502. snprintf(
  503. unique_name,
  504. sizeof(unique_name)-1,
  505. "cgminer-%p",
  506. (void*)module
  507. );
  508. // Create and init a chunked of shared memory
  509. HANDLE map_handle = CreateFileMapping(
  510. INVALID_HANDLE_VALUE, // use paging file
  511. NULL, // default security attributes
  512. PAGE_READWRITE, // read/write access
  513. 0, // size: high 32-bits
  514. 4096, // size: low 32-bits
  515. unique_name // name of map object
  516. );
  517. if (NULL==map_handle) {
  518. applog(LOG_ERR, "could not create shared memory");
  519. exit(1);
  520. }
  521. void *shared_mem = MapViewOfFile(
  522. map_handle, // object to map view of
  523. FILE_MAP_WRITE, // read/write access
  524. 0, // high offset: map from
  525. 0, // low offset: beginning
  526. 0 // default: map entire file
  527. );
  528. if (NULL==shared_mem) {
  529. applog(LOG_ERR, "could not map shared memory");
  530. exit(1);
  531. }
  532. SetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name);
  533. CopyMemory(shared_mem, &rate, sizeof(rate));
  534. // Get path to current exe
  535. char cmd_line[256 + MAX_PATH];
  536. const size_t n = sizeof(cmd_line)-200;
  537. DWORD size = GetModuleFileName(module, cmd_line, n);
  538. if (0==size) {
  539. applog(LOG_ERR, "failed to retrieve module path");
  540. exit(1);
  541. }
  542. // Construct new command line based on that
  543. char *p = strlen(cmd_line) + cmd_line;
  544. sprintf(p, " --bench-algo %d", algo);
  545. SetEnvironmentVariable("CGMINER_BENCH_ALGO", "1");
  546. // Launch a debug copy of cgminer
  547. STARTUPINFO startup_info;
  548. PROCESS_INFORMATION process_info;
  549. ZeroMemory(&startup_info, sizeof(startup_info));
  550. ZeroMemory(&process_info, sizeof(process_info));
  551. startup_info.cb = sizeof(startup_info);
  552. BOOL ok = CreateProcess(
  553. NULL, // No module name (use command line)
  554. cmd_line, // Command line
  555. NULL, // Process handle not inheritable
  556. NULL, // Thread handle not inheritable
  557. FALSE, // Set handle inheritance to FALSE
  558. DEBUG_ONLY_THIS_PROCESS,// We're going to debug the child
  559. NULL, // Use parent's environment block
  560. NULL, // Use parent's starting directory
  561. &startup_info, // Pointer to STARTUPINFO structure
  562. &process_info // Pointer to PROCESS_INFORMATION structure
  563. );
  564. if (!ok) {
  565. applog(LOG_ERR, "CreateProcess failed with error %d\n", GetLastError() );
  566. exit(1);
  567. }
  568. // Debug the child (only clean way to catch exceptions)
  569. while (1) {
  570. // Wait for child to do something
  571. DEBUG_EVENT debug_event;
  572. ZeroMemory(&debug_event, sizeof(debug_event));
  573. BOOL ok = WaitForDebugEvent(&debug_event, 60 * 1000);
  574. if (!ok)
  575. break;
  576. // Decide if event is "normal"
  577. int go_on =
  578. CREATE_PROCESS_DEBUG_EVENT== debug_event.dwDebugEventCode ||
  579. CREATE_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  580. EXIT_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  581. EXCEPTION_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  582. LOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  583. OUTPUT_DEBUG_STRING_EVENT == debug_event.dwDebugEventCode ||
  584. UNLOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode;
  585. if (!go_on)
  586. break;
  587. // Some exceptions are also "normal", apparently.
  588. if (EXCEPTION_DEBUG_EVENT== debug_event.dwDebugEventCode) {
  589. int go_on =
  590. EXCEPTION_BREAKPOINT== debug_event.u.Exception.ExceptionRecord.ExceptionCode;
  591. if (!go_on)
  592. break;
  593. }
  594. // If nothing unexpected happened, let child proceed
  595. ContinueDebugEvent(
  596. debug_event.dwProcessId,
  597. debug_event.dwThreadId,
  598. DBG_CONTINUE
  599. );
  600. }
  601. // Clean up child process
  602. TerminateProcess(process_info.hProcess, 1);
  603. CloseHandle(process_info.hProcess);
  604. CloseHandle(process_info.hThread);
  605. // Reap return value and cleanup
  606. CopyMemory(&rate, shared_mem, sizeof(rate));
  607. (void)UnmapViewOfFile(shared_mem);
  608. (void)CloseHandle(map_handle);
  609. #else
  610. // Not linux, not unix, not WIN32 ... do our best
  611. rate = bench_algo_stage3(algo);
  612. #endif // defined(unix)
  613. // Done
  614. return rate;
  615. }
  616. static void bench_algo(
  617. double *best_rate,
  618. enum sha256_algos *best_algo,
  619. enum sha256_algos algo
  620. )
  621. {
  622. size_t n = max_name_len - strlen(algo_names[algo]);
  623. memset(name_spaces_pad, ' ', n);
  624. name_spaces_pad[n] = 0;
  625. applog(
  626. LOG_ERR,
  627. "\"%s\"%s : benchmarking algorithm ...",
  628. algo_names[algo],
  629. name_spaces_pad
  630. );
  631. double rate = bench_algo_stage2(algo);
  632. if (rate<0.0) {
  633. applog(
  634. LOG_ERR,
  635. "\"%s\"%s : algorithm fails on this platform",
  636. algo_names[algo],
  637. name_spaces_pad
  638. );
  639. } else {
  640. applog(
  641. LOG_ERR,
  642. "\"%s\"%s : algorithm runs at %.5f MH/s",
  643. algo_names[algo],
  644. name_spaces_pad,
  645. rate
  646. );
  647. if (*best_rate<rate) {
  648. *best_rate = rate;
  649. *best_algo = algo;
  650. }
  651. }
  652. }
  653. // Figure out the longest algorithm name
  654. static void init_max_name_len()
  655. {
  656. size_t i;
  657. size_t nb_names = sizeof(algo_names)/sizeof(algo_names[0]);
  658. for (i=0; i<nb_names; ++i) {
  659. const char *p = algo_names[i];
  660. size_t name_len = p ? strlen(p) : 0;
  661. if (max_name_len<name_len)
  662. max_name_len = name_len;
  663. }
  664. name_spaces_pad = (char*) malloc(max_name_len+16);
  665. if (0==name_spaces_pad) {
  666. perror("malloc failed");
  667. exit(1);
  668. }
  669. }
  670. // Pick the fastest CPU hasher
  671. static enum sha256_algos pick_fastest_algo()
  672. {
  673. double best_rate = -1.0;
  674. enum sha256_algos best_algo = 0;
  675. applog(LOG_ERR, "benchmarking all sha256 algorithms ...");
  676. bench_algo(&best_rate, &best_algo, ALGO_C);
  677. #if defined(WANT_SSE2_4WAY)
  678. bench_algo(&best_rate, &best_algo, ALGO_4WAY);
  679. #endif
  680. #if defined(WANT_VIA_PADLOCK)
  681. bench_algo(&best_rate, &best_algo, ALGO_VIA);
  682. #endif
  683. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP);
  684. #if defined(WANT_CRYPTOPP_ASM32)
  685. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP_ASM32);
  686. #endif
  687. #if defined(WANT_X8664_SSE2)
  688. bench_algo(&best_rate, &best_algo, ALGO_SSE2_64);
  689. #endif
  690. #if defined(WANT_X8664_SSE4)
  691. bench_algo(&best_rate, &best_algo, ALGO_SSE4_64);
  692. #endif
  693. size_t n = max_name_len - strlen(algo_names[best_algo]);
  694. memset(name_spaces_pad, ' ', n);
  695. name_spaces_pad[n] = 0;
  696. applog(
  697. LOG_ERR,
  698. "\"%s\"%s : is fastest algorithm at %.5f MH/s",
  699. algo_names[best_algo],
  700. name_spaces_pad,
  701. best_rate
  702. );
  703. return best_algo;
  704. }
  705. /* FIXME: Use asprintf for better errors. */
  706. static char *set_algo(const char *arg, enum sha256_algos *algo)
  707. {
  708. enum sha256_algos i;
  709. if (!strcmp(arg, "auto")) {
  710. *algo = pick_fastest_algo();
  711. return NULL;
  712. }
  713. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  714. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  715. *algo = i;
  716. return NULL;
  717. }
  718. }
  719. return "Unknown algorithm";
  720. }
  721. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  722. {
  723. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  724. }
  725. static char *set_int_range(const char *arg, int *i, int min, int max)
  726. {
  727. char *err = opt_set_intval(arg, i);
  728. if (err)
  729. return err;
  730. if (*i < min || *i > max)
  731. return "Value out of range";
  732. return NULL;
  733. }
  734. static char *set_int_0_to_9999(const char *arg, int *i)
  735. {
  736. return set_int_range(arg, i, 0, 9999);
  737. }
  738. static char *forced_int_1010(const char *arg, int *i)
  739. {
  740. opt_dynamic = false;
  741. return set_int_range(arg, i, -10, 10);
  742. }
  743. static char *force_nthreads_int(const char *arg, int *i)
  744. {
  745. forced_n_threads = true;
  746. return set_int_range(arg, i, 0, 9999);
  747. }
  748. static char *set_int_0_to_10(const char *arg, int *i)
  749. {
  750. return set_int_range(arg, i, 0, 10);
  751. }
  752. static char *set_devices(const char *arg, int *i)
  753. {
  754. char *err = opt_set_intval(arg, i);
  755. if (err)
  756. return err;
  757. if (*i < 0 || *i > 15)
  758. return "Invalid GPU device number";
  759. total_devices++;
  760. gpu_devices[*i] = true;
  761. return NULL;
  762. }
  763. static char *set_loadbalance(enum pool_strategy *strategy)
  764. {
  765. *strategy = POOL_LOADBALANCE;
  766. return NULL;
  767. }
  768. static char *set_rotate(const char *arg, int *i)
  769. {
  770. pool_strategy = POOL_ROTATE;
  771. return set_int_range(arg, i, 0, 9999);
  772. }
  773. static char *set_rr(enum pool_strategy *strategy)
  774. {
  775. *strategy = POOL_ROUNDROBIN;
  776. return NULL;
  777. }
  778. static char *set_url(char *arg, char **p)
  779. {
  780. struct pool *pool;
  781. total_urls++;
  782. if (total_urls > total_pools)
  783. add_pool();
  784. pool = pools[total_urls - 1];
  785. opt_set_charp(arg, &pool->rpc_url);
  786. if (strncmp(arg, "http://", 7) &&
  787. strncmp(arg, "https://", 8)) {
  788. char *httpinput;
  789. httpinput = malloc(255);
  790. if (!httpinput)
  791. quit(1, "Failed to malloc httpinput");
  792. strcpy(httpinput, "http://");
  793. strncat(httpinput, arg, 248);
  794. pool->rpc_url = httpinput;
  795. }
  796. return NULL;
  797. }
  798. static char *set_user(const char *arg, char **p)
  799. {
  800. struct pool *pool;
  801. if (total_userpasses)
  802. return "Use only user + pass or userpass, but not both";
  803. total_users++;
  804. if (total_users > total_pools)
  805. add_pool();
  806. pool = pools[total_users - 1];
  807. opt_set_charp(arg, &pool->rpc_user);
  808. return NULL;
  809. }
  810. static char *set_pass(const char *arg, char **p)
  811. {
  812. struct pool *pool;
  813. if (total_userpasses)
  814. return "Use only user + pass or userpass, but not both";
  815. total_passes++;
  816. if (total_passes > total_pools)
  817. add_pool();
  818. pool = pools[total_passes - 1];
  819. opt_set_charp(arg, &pool->rpc_pass);
  820. return NULL;
  821. }
  822. static char *set_userpass(const char *arg, char **p)
  823. {
  824. struct pool *pool;
  825. if (total_users || total_passes)
  826. return "Use only user + pass or userpass, but not both";
  827. total_userpasses++;
  828. if (total_userpasses > total_pools)
  829. add_pool();
  830. pool = pools[total_userpasses - 1];
  831. opt_set_charp(arg, &pool->rpc_userpass);
  832. return NULL;
  833. }
  834. static char *set_vector(const char *arg, int *i)
  835. {
  836. char *err = opt_set_intval(arg, i);
  837. if (err)
  838. return err;
  839. if (*i != 1 && *i != 2 && *i != 4)
  840. return "Valid vectors are 1, 2 or 4";
  841. return NULL;
  842. }
  843. static char *enable_debug(bool *flag)
  844. {
  845. *flag = true;
  846. /* Turn out verbose output, too. */
  847. opt_log_output = true;
  848. return NULL;
  849. }
  850. static char *trpc_url;
  851. static char *trpc_userpass;
  852. static char *trpc_user, *trpc_pass;
  853. /* These options are available from config file or commandline */
  854. static struct opt_table opt_config_table[] = {
  855. OPT_WITH_ARG("--algo|-a",
  856. set_algo, show_algo, &opt_algo,
  857. "Specify sha256 implementation for CPU mining:\n"
  858. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  859. "\n\tc\t\tLinux kernel sha256, implemented in C"
  860. #ifdef WANT_SSE2_4WAY
  861. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  862. #endif
  863. #ifdef WANT_VIA_PADLOCK
  864. "\n\tvia\t\tVIA padlock implementation"
  865. #endif
  866. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  867. #ifdef WANT_CRYPTOPP_ASM32
  868. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  869. #endif
  870. #ifdef WANT_X8664_SSE2
  871. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  872. #endif
  873. #ifdef WANT_X8664_SSE4
  874. "\n\tsse4_64\t\tSSE4 implementation for x86_64 machines"
  875. #endif
  876. ),
  877. OPT_WITH_ARG("--bench-algo|-b",
  878. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  879. opt_hidden),
  880. OPT_WITH_ARG("--cpu-threads|-t",
  881. force_nthreads_int, opt_show_intval, &opt_n_threads,
  882. "Number of miner CPU threads"),
  883. OPT_WITHOUT_ARG("--debug|-D",
  884. enable_debug, &opt_debug,
  885. "Enable debug output"),
  886. #ifdef HAVE_OPENCL
  887. OPT_WITH_ARG("--device|-d",
  888. set_devices, NULL, &opt_device,
  889. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  890. OPT_WITH_ARG("--gpu-threads|-g",
  891. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  892. "Number of threads per GPU (0 - 10)"),
  893. OPT_WITH_ARG("--intensity|-I",
  894. forced_int_1010, opt_show_intval, &scan_intensity,
  895. "Intensity of GPU scanning (-10 -> 10, default: dynamic to maintain desktop interactivity)"),
  896. OPT_WITH_ARG("--kernel|-k",
  897. opt_set_charp, NULL, &opt_kernel,
  898. "Select kernel to use (poclbm or phatk - default: auto)"),
  899. #endif
  900. OPT_WITHOUT_ARG("--load-balance",
  901. set_loadbalance, &pool_strategy,
  902. "Change multipool strategy from failover to even load balance"),
  903. OPT_WITH_ARG("--log|-l",
  904. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  905. "Interval in seconds between log output"),
  906. #if defined(unix)
  907. OPT_WITH_ARG("--monitor|-m",
  908. opt_set_charp, NULL, &opt_stderr_cmd,
  909. "Use custom pipe cmd for output messages"),
  910. #endif // defined(unix)
  911. OPT_WITHOUT_ARG("--no-longpoll",
  912. opt_set_invbool, &want_longpoll,
  913. "Disable X-Long-Polling support"),
  914. OPT_WITH_ARG("--pass|-p",
  915. set_pass, NULL, &trpc_pass,
  916. "Password for bitcoin JSON-RPC server"),
  917. OPT_WITHOUT_ARG("--per-device-stats",
  918. opt_set_bool, &want_per_device_stats,
  919. "Force verbose mode and output per-device statistics"),
  920. OPT_WITHOUT_ARG("--protocol-dump|-P",
  921. opt_set_bool, &opt_protocol,
  922. "Verbose dump of protocol-level activities"),
  923. OPT_WITH_ARG("--queue|-Q",
  924. set_int_0_to_10, opt_show_intval, &opt_queue,
  925. "Number of extra work items to queue (0 - 10)"),
  926. OPT_WITHOUT_ARG("--quiet|-q",
  927. opt_set_bool, &opt_quiet,
  928. "Disable logging output, display status and errors"),
  929. OPT_WITHOUT_ARG("--real-quiet",
  930. opt_set_bool, &opt_realquiet,
  931. "Disable all output"),
  932. OPT_WITH_ARG("--retries|-r",
  933. opt_set_intval, opt_show_intval, &opt_retries,
  934. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  935. OPT_WITH_ARG("--retry-pause|-R",
  936. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  937. "Number of seconds to pause, between retries"),
  938. OPT_WITH_ARG("--rotate",
  939. set_rotate, opt_show_intval, &opt_rotate_period,
  940. "Change multipool strategy from failover to regularly rotate at N minutes"),
  941. OPT_WITHOUT_ARG("--round-robin",
  942. set_rr, &pool_strategy,
  943. "Change multipool strategy from failover to round robin on failure"),
  944. OPT_WITH_ARG("--scan-time|-s",
  945. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  946. "Upper bound on time spent scanning current work, in seconds"),
  947. OPT_WITHOUT_ARG("--submit-stale",
  948. opt_set_bool, &opt_submit_stale,
  949. "Submit shares even if they would normally be considered stale"),
  950. #ifdef HAVE_SYSLOG_H
  951. OPT_WITHOUT_ARG("--syslog",
  952. opt_set_bool, &use_syslog,
  953. "Use system log for output messages (default: standard error)"),
  954. #endif
  955. OPT_WITHOUT_ARG("--text-only|-T",
  956. opt_set_invbool, &use_curses,
  957. "Disable ncurses formatted screen output"),
  958. OPT_WITH_ARG("--url|-o",
  959. set_url, opt_show_charp, &trpc_url,
  960. "URL for bitcoin JSON-RPC server"),
  961. OPT_WITH_ARG("--user|-u",
  962. set_user, NULL, &trpc_user,
  963. "Username for bitcoin JSON-RPC server"),
  964. #ifdef HAVE_OPENCL
  965. OPT_WITH_ARG("--vectors|-v",
  966. set_vector, NULL, &opt_vectors,
  967. "Override detected optimal vector width (1, 2 or 4)"),
  968. #endif
  969. OPT_WITHOUT_ARG("--verbose",
  970. opt_set_bool, &opt_log_output,
  971. "Log verbose output to stderr as well as status output"),
  972. #ifdef HAVE_OPENCL
  973. OPT_WITH_ARG("--worksize|-w",
  974. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  975. "Override detected optimal worksize"),
  976. #endif
  977. OPT_WITH_ARG("--userpass|-O",
  978. set_userpass, NULL, &trpc_userpass,
  979. "Username:Password pair for bitcoin JSON-RPC server"),
  980. OPT_ENDTABLE
  981. };
  982. static char *parse_config(json_t *config)
  983. {
  984. static char err_buf[200];
  985. json_t *val;
  986. struct opt_table *opt;
  987. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  988. char *p, *name;
  989. /* We don't handle subtables. */
  990. assert(!(opt->type & OPT_SUBTABLE));
  991. /* Pull apart the option name(s). */
  992. name = strdup(opt->names);
  993. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  994. char *err;
  995. /* Ignore short options. */
  996. if (p[1] != '-')
  997. continue;
  998. val = json_object_get(config, p+2);
  999. if (!val)
  1000. continue;
  1001. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  1002. err = opt->cb_arg(json_string_value(val),
  1003. opt->u.arg);
  1004. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  1005. err = opt->cb(opt->u.arg);
  1006. } else {
  1007. err = "Invalid value";
  1008. }
  1009. if (err) {
  1010. sprintf(err_buf, "Parsing JSON option %s: %s",
  1011. p, err);
  1012. return err_buf;
  1013. }
  1014. }
  1015. free(name);
  1016. }
  1017. return NULL;
  1018. }
  1019. static char *load_config(const char *arg, void *unused)
  1020. {
  1021. json_error_t err;
  1022. json_t *config;
  1023. config = json_load_file(arg, 0, &err);
  1024. if (!json_is_object(config))
  1025. return "JSON decode of file failed";
  1026. /* Parse the config now, so we can override it. That can keep pointers
  1027. * so don't free config object. */
  1028. return parse_config(config);
  1029. }
  1030. #ifdef HAVE_OPENCL
  1031. static char *print_ndevs_and_exit(int *ndevs)
  1032. {
  1033. printf("%i GPU devices detected\n", *ndevs);
  1034. fflush(stdout);
  1035. exit(*ndevs);
  1036. }
  1037. #endif
  1038. /* These options are available from commandline only */
  1039. static struct opt_table opt_cmdline_table[] = {
  1040. OPT_WITH_ARG("--config|-c",
  1041. load_config, NULL, NULL,
  1042. "Load a JSON-format configuration file\n"
  1043. "See example-cfg.json for an example configuration."),
  1044. OPT_WITHOUT_ARG("--help|-h",
  1045. opt_usage_and_exit,
  1046. #ifdef HAVE_OPENCL
  1047. "\nBuilt with CPU and GPU mining support.\n",
  1048. #else
  1049. "\nBuilt with CPU mining support only.\n",
  1050. #endif
  1051. "Print this message"),
  1052. #ifdef HAVE_OPENCL
  1053. OPT_WITHOUT_ARG("--ndevs|-n",
  1054. print_ndevs_and_exit, &nDevs,
  1055. "Enumerate number of detected GPUs and exit"),
  1056. #endif
  1057. OPT_ENDTABLE
  1058. };
  1059. static bool jobj_binary(const json_t *obj, const char *key,
  1060. void *buf, size_t buflen)
  1061. {
  1062. const char *hexstr;
  1063. json_t *tmp;
  1064. tmp = json_object_get(obj, key);
  1065. if (unlikely(!tmp)) {
  1066. applog(LOG_ERR, "JSON key '%s' not found", key);
  1067. return false;
  1068. }
  1069. hexstr = json_string_value(tmp);
  1070. if (unlikely(!hexstr)) {
  1071. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1072. return false;
  1073. }
  1074. if (!hex2bin(buf, hexstr, buflen))
  1075. return false;
  1076. return true;
  1077. }
  1078. static bool work_decode(const json_t *val, struct work *work)
  1079. {
  1080. if (unlikely(!jobj_binary(val, "midstate",
  1081. work->midstate, sizeof(work->midstate)))) {
  1082. applog(LOG_ERR, "JSON inval midstate");
  1083. goto err_out;
  1084. }
  1085. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  1086. applog(LOG_ERR, "JSON inval data");
  1087. goto err_out;
  1088. }
  1089. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  1090. applog(LOG_ERR, "JSON inval hash1");
  1091. goto err_out;
  1092. }
  1093. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  1094. applog(LOG_ERR, "JSON inval target");
  1095. goto err_out;
  1096. }
  1097. memset(work->hash, 0, sizeof(work->hash));
  1098. gettimeofday(&work->tv_staged, NULL);
  1099. return true;
  1100. err_out:
  1101. return false;
  1102. }
  1103. static inline int dev_from_id(int thr_id)
  1104. {
  1105. return thr_info[thr_id].cgpu->cpu_gpu;
  1106. }
  1107. /* Simulate a rolling average by faking an exponential decay over 5 * log */
  1108. static inline void decay_time(double *f, double fadd)
  1109. {
  1110. *f = (fadd + *f * 0.9) / 1.9;
  1111. }
  1112. static WINDOW *mainwin, *statuswin, *logwin;
  1113. static double total_secs = 0.1;
  1114. static char statusline[256];
  1115. static int cpucursor, gpucursor, logstart, logcursor;
  1116. static struct cgpu_info *gpus, *cpus;
  1117. static void text_print_status(int thr_id)
  1118. {
  1119. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1120. printf(" %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  1121. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  1122. cgpu->total_mhashes / total_secs, cgpu->getworks,
  1123. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1124. cgpu->efficiency, cgpu->utility);
  1125. }
  1126. /* Must be called with curses mutex lock held and curses_active */
  1127. static void curses_print_status(int thr_id)
  1128. {
  1129. struct pool *pool = current_pool();
  1130. wmove(statuswin, 0, 0);
  1131. wattron(statuswin, A_BOLD);
  1132. wprintw(statuswin, " " PROGRAM_NAME " version " VERSION " - Started: %s", datestamp);
  1133. if (opt_n_threads)
  1134. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1135. wattroff(statuswin, A_BOLD);
  1136. wmove(statuswin, 1, 0);
  1137. whline(statuswin, '-', 80);
  1138. wmove(statuswin, 2,0);
  1139. wprintw(statuswin, " %s", statusline);
  1140. wclrtoeol(statuswin);
  1141. wmove(statuswin, 3,0);
  1142. wprintw(statuswin, " TQ: %d ST: %d LS: %d SS: %d DW: %d NB: %d LW: %d LO: %d RF: %d I: %d",
  1143. total_queued, total_staged, lp_staged, total_stale, total_discarded, new_blocks,
  1144. local_work, total_lo, total_ro, scan_intensity);
  1145. wclrtoeol(statuswin);
  1146. wmove(statuswin, 4, 0);
  1147. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1148. wprintw(statuswin, " Connected to multiple pools with%s LP",
  1149. have_longpoll ? "": "out");
  1150. else
  1151. wprintw(statuswin, " Connected to %s with%s LP as user %s",
  1152. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1153. wclrtoeol(statuswin);
  1154. wmove(statuswin, 5, 0);
  1155. wprintw(statuswin, " Block: %s... Started: %s", current_hash, blocktime);
  1156. wmove(statuswin, 6, 0);
  1157. whline(statuswin, '-', 80);
  1158. wmove(statuswin, logstart - 1, 0);
  1159. whline(statuswin, '-', 80);
  1160. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1161. opt_g_threads ? "[G]PU management " : "");
  1162. if (thr_id >= 0 && thr_id < gpu_threads) {
  1163. int gpu = dev_from_id(thr_id);
  1164. struct cgpu_info *cgpu = &gpus[gpu];
  1165. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1166. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1167. wmove(statuswin, gpucursor + gpu, 0);
  1168. wprintw(statuswin, " GPU %d: ", gpu);
  1169. if (cgpu->status == LIFE_DEAD)
  1170. wprintw(statuswin, "[DEAD ");
  1171. else if (cgpu->status == LIFE_SICK)
  1172. wprintw(statuswin, "[SICK ");
  1173. else if (!gpu_devices[gpu])
  1174. wprintw(statuswin, "[DISABLED ");
  1175. else
  1176. wprintw(statuswin, "[%.1f ", cgpu->rolling);
  1177. wprintw(statuswin, "/ %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1178. cgpu->total_mhashes / total_secs,
  1179. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1180. cgpu->efficiency, cgpu->utility);
  1181. wclrtoeol(statuswin);
  1182. } else if (thr_id >= gpu_threads) {
  1183. int cpu = dev_from_id(thr_id);
  1184. struct cgpu_info *cgpu = &cpus[cpu];
  1185. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1186. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1187. wmove(statuswin, cpucursor + cpu, 0);
  1188. wprintw(statuswin, " CPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d E:%.0f%% U:%.2f/m]",
  1189. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1190. cgpu->getworks, cgpu->accepted, cgpu->rejected,
  1191. cgpu->efficiency, cgpu->utility);
  1192. wclrtoeol(statuswin);
  1193. }
  1194. wrefresh(statuswin);
  1195. }
  1196. static void print_status(int thr_id)
  1197. {
  1198. if (!curses_active)
  1199. text_print_status(thr_id);
  1200. else {
  1201. mutex_lock(&curses_lock);
  1202. curses_print_status(thr_id);
  1203. mutex_unlock(&curses_lock);
  1204. }
  1205. }
  1206. /* Check for window resize. Called with curses mutex locked */
  1207. static inline void check_logwinsize(void)
  1208. {
  1209. int x, y, logx, logy;
  1210. getmaxyx(mainwin, y, x);
  1211. getmaxyx(logwin, logy, logx);
  1212. y -= logcursor;
  1213. /* Detect screen size change */
  1214. if ((x != logx || y != logy) && x >= 80 && y >= 25)
  1215. wresize(logwin, y, x);
  1216. }
  1217. /* For mandatory printing when mutex is already locked */
  1218. static void wlog(const char *f, ...)
  1219. {
  1220. va_list ap;
  1221. va_start(ap, f);
  1222. vw_printw(logwin, f, ap);
  1223. va_end(ap);
  1224. }
  1225. /* Mandatory printing */
  1226. static void wlogprint(const char *f, ...)
  1227. {
  1228. va_list ap;
  1229. mutex_lock(&curses_lock);
  1230. va_start(ap, f);
  1231. vw_printw(logwin, f, ap);
  1232. va_end(ap);
  1233. wrefresh(logwin);
  1234. mutex_unlock(&curses_lock);
  1235. }
  1236. void log_curses(int prio, const char *f, va_list ap)
  1237. {
  1238. if (opt_quiet && prio != LOG_ERR)
  1239. return;
  1240. if (curses_active) {
  1241. if (!opt_loginput) {
  1242. mutex_lock(&curses_lock);
  1243. vw_printw(logwin, f, ap);
  1244. wrefresh(logwin);
  1245. mutex_unlock(&curses_lock);
  1246. }
  1247. } else
  1248. vprintf(f, ap);
  1249. }
  1250. static void clear_logwin(void)
  1251. {
  1252. mutex_lock(&curses_lock);
  1253. wclear(logwin);
  1254. wrefresh(logwin);
  1255. mutex_unlock(&curses_lock);
  1256. }
  1257. static bool submit_upstream_work(const struct work *work)
  1258. {
  1259. char *hexstr = NULL;
  1260. json_t *val, *res;
  1261. char s[345], sd[345];
  1262. bool rc = false;
  1263. int thr_id = work->thr_id;
  1264. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1265. CURL *curl = curl_easy_init();
  1266. struct pool *pool = work->pool;
  1267. bool rolltime;
  1268. if (unlikely(!curl)) {
  1269. applog(LOG_ERR, "CURL initialisation failed");
  1270. return rc;
  1271. }
  1272. /* build hex string */
  1273. hexstr = bin2hex(work->data, sizeof(work->data));
  1274. if (unlikely(!hexstr)) {
  1275. applog(LOG_ERR, "submit_upstream_work OOM");
  1276. goto out_nofree;
  1277. }
  1278. /* build JSON-RPC request */
  1279. sprintf(s,
  1280. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1281. hexstr);
  1282. sprintf(sd,
  1283. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1284. hexstr);
  1285. if (opt_debug)
  1286. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1287. /* issue JSON-RPC request */
  1288. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool);
  1289. if (unlikely(!val)) {
  1290. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1291. if (!pool_tset(pool, &pool->submit_fail)) {
  1292. total_ro++;
  1293. pool->remotefail_occasions++;
  1294. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1295. }
  1296. goto out;
  1297. } else if (pool_tclear(pool, &pool->submit_fail))
  1298. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1299. res = json_object_get(val, "result");
  1300. /* Theoretically threads could race when modifying accepted and
  1301. * rejected values but the chance of two submits completing at the
  1302. * same time is zero so there is no point adding extra locking */
  1303. if (json_is_true(res)) {
  1304. cgpu->accepted++;
  1305. total_accepted++;
  1306. pool->accepted++;
  1307. if (opt_debug)
  1308. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1309. if (!QUIET) {
  1310. if (total_pools > 1)
  1311. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  1312. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1313. else
  1314. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  1315. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1316. }
  1317. } else {
  1318. cgpu->rejected++;
  1319. total_rejected++;
  1320. pool->rejected++;
  1321. if (opt_debug)
  1322. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1323. if (!QUIET) {
  1324. if (total_pools > 1)
  1325. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  1326. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1327. else
  1328. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  1329. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1330. }
  1331. }
  1332. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1333. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1334. if (!opt_realquiet)
  1335. print_status(thr_id);
  1336. if (!want_per_device_stats)
  1337. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  1338. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  1339. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  1340. json_decref(val);
  1341. rc = true;
  1342. out:
  1343. free(hexstr);
  1344. out_nofree:
  1345. curl_easy_cleanup(curl);
  1346. return rc;
  1347. }
  1348. static const char *rpc_req =
  1349. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1350. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1351. static inline struct pool *select_pool(bool lagging)
  1352. {
  1353. static int rotating_pool = 0;
  1354. struct pool *pool, *cp;
  1355. cp = current_pool();
  1356. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1357. pool = cp;
  1358. else
  1359. pool = NULL;
  1360. while (!pool) {
  1361. if (++rotating_pool >= total_pools)
  1362. rotating_pool = 0;
  1363. pool = pools[rotating_pool];
  1364. if ((!pool->idle && pool->enabled) || pool == cp)
  1365. break;
  1366. pool = NULL;
  1367. }
  1368. return pool;
  1369. }
  1370. static bool get_upstream_work(struct work *work, bool lagging)
  1371. {
  1372. struct pool *pool;
  1373. json_t *val;
  1374. bool rc = false;
  1375. CURL *curl;
  1376. curl = curl_easy_init();
  1377. if (unlikely(!curl)) {
  1378. applog(LOG_ERR, "CURL initialisation failed");
  1379. return rc;
  1380. }
  1381. pool = select_pool(lagging);
  1382. if (opt_debug)
  1383. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1384. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1385. false, false, &work->rolltime, pool);
  1386. if (unlikely(!val)) {
  1387. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1388. goto out;
  1389. }
  1390. rc = work_decode(json_object_get(val, "result"), work);
  1391. work->pool = pool;
  1392. total_getworks++;
  1393. pool->getwork_requested++;
  1394. if (work->thr)
  1395. work->thr->cgpu->getworks++;
  1396. json_decref(val);
  1397. out:
  1398. curl_easy_cleanup(curl);
  1399. return rc;
  1400. }
  1401. static struct work *make_work(void)
  1402. {
  1403. struct work *work = calloc(1, sizeof(struct work));
  1404. if (unlikely(!work))
  1405. quit(1, "Failed to calloc work in make_work");
  1406. return work;
  1407. }
  1408. static void free_work(struct work *work)
  1409. {
  1410. free(work);
  1411. }
  1412. static void workio_cmd_free(struct workio_cmd *wc)
  1413. {
  1414. if (!wc)
  1415. return;
  1416. switch (wc->cmd) {
  1417. case WC_SUBMIT_WORK:
  1418. free_work(wc->u.work);
  1419. break;
  1420. default: /* do nothing */
  1421. break;
  1422. }
  1423. memset(wc, 0, sizeof(*wc)); /* poison */
  1424. free(wc);
  1425. }
  1426. static void disable_curses(void)
  1427. {
  1428. if (test_and_clear(&curses_active)) {
  1429. leaveok(logwin, false);
  1430. leaveok(statuswin, false);
  1431. leaveok(mainwin, false);
  1432. nocbreak();
  1433. echo();
  1434. delwin(logwin);
  1435. delwin(statuswin);
  1436. delwin(mainwin);
  1437. endwin();
  1438. refresh();
  1439. #ifdef WIN32
  1440. // Move the cursor to after curses output.
  1441. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1442. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1443. COORD coord;
  1444. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1445. coord.X = 0;
  1446. coord.Y = csbi.dwSize.Y - 1;
  1447. SetConsoleCursorPosition(hout, coord);
  1448. }
  1449. #endif
  1450. }
  1451. }
  1452. void kill_work(void)
  1453. {
  1454. struct workio_cmd *wc;
  1455. struct thr_info *thr;
  1456. unsigned int i;
  1457. disable_curses();
  1458. applog(LOG_INFO, "Received kill message");
  1459. /* Kill the watchdog thread */
  1460. thr = &thr_info[watchdog_thr_id];
  1461. pthread_cancel(*thr->pth);
  1462. /* Stop the mining threads*/
  1463. for (i = 0; i < mining_threads; i++) {
  1464. thr = &thr_info[i];
  1465. if (!thr->pth)
  1466. continue;
  1467. tq_freeze(thr->q);
  1468. /* No need to check if this succeeds or not */
  1469. pthread_cancel(*thr->pth);
  1470. }
  1471. /* Stop the others */
  1472. thr = &thr_info[stage_thr_id];
  1473. pthread_cancel(*thr->pth);
  1474. thr = &thr_info[longpoll_thr_id];
  1475. pthread_cancel(*thr->pth);
  1476. wc = calloc(1, sizeof(*wc));
  1477. if (unlikely(!wc)) {
  1478. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  1479. /* We're just trying to die anyway, so forget graceful */
  1480. exit (1);
  1481. }
  1482. wc->cmd = WC_DIE;
  1483. wc->thr = 0;
  1484. if (opt_debug)
  1485. applog(LOG_DEBUG, "Pushing die request to work thread");
  1486. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1487. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  1488. exit (1);
  1489. }
  1490. }
  1491. static void sighandler(int sig)
  1492. {
  1493. /* Restore signal handlers so we can still quit if kill_work fails */
  1494. sigaction(SIGTERM, &termhandler, NULL);
  1495. sigaction(SIGINT, &inthandler, NULL);
  1496. kill_work();
  1497. }
  1498. static void *get_work_thread(void *userdata)
  1499. {
  1500. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1501. struct work *ret_work;
  1502. int failures = 0;
  1503. pthread_detach(pthread_self());
  1504. ret_work = make_work();
  1505. if (wc->thr)
  1506. ret_work->thr = wc->thr;
  1507. else
  1508. ret_work->thr = NULL;
  1509. /* obtain new work from bitcoin via JSON-RPC */
  1510. while (!get_upstream_work(ret_work, wc->lagging)) {
  1511. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1512. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1513. free_work(ret_work);
  1514. kill_work();
  1515. goto out;
  1516. }
  1517. /* pause, then restart work-request loop */
  1518. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1519. opt_fail_pause);
  1520. sleep(opt_fail_pause);
  1521. }
  1522. if (opt_debug)
  1523. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1524. /* send work to requesting thread */
  1525. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1526. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1527. kill_work();
  1528. free_work(ret_work);
  1529. }
  1530. out:
  1531. workio_cmd_free(wc);
  1532. return NULL;
  1533. }
  1534. static bool workio_get_work(struct workio_cmd *wc)
  1535. {
  1536. pthread_t get_thread;
  1537. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1538. applog(LOG_ERR, "Failed to create get_work_thread");
  1539. return false;
  1540. }
  1541. return true;
  1542. }
  1543. static bool stale_work(struct work *work)
  1544. {
  1545. struct timeval now;
  1546. bool ret = false;
  1547. char *hexstr;
  1548. gettimeofday(&now, NULL);
  1549. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1550. return true;
  1551. /* Only use the primary pool for determination as the work may
  1552. * interleave at times of new blocks */
  1553. if (work->pool != current_pool())
  1554. return ret;
  1555. hexstr = bin2hex(work->data, 36);
  1556. if (unlikely(!hexstr)) {
  1557. applog(LOG_ERR, "submit_work_thread OOM");
  1558. return ret;
  1559. }
  1560. if (strncmp(hexstr, current_block, 36))
  1561. ret = true;
  1562. free(hexstr);
  1563. return ret;
  1564. }
  1565. static void *submit_work_thread(void *userdata)
  1566. {
  1567. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1568. struct work *work = wc->u.work;
  1569. struct pool *pool = work->pool;
  1570. int failures = 0;
  1571. pthread_detach(pthread_self());
  1572. if (!opt_submit_stale && stale_work(work)) {
  1573. applog(LOG_WARNING, "Stale share detected, discarding");
  1574. total_stale++;
  1575. pool->stale_shares++;
  1576. goto out;
  1577. }
  1578. /* submit solution to bitcoin via JSON-RPC */
  1579. while (!submit_upstream_work(work)) {
  1580. if (!opt_submit_stale && stale_work(work)) {
  1581. applog(LOG_WARNING, "Stale share detected, discarding");
  1582. total_stale++;
  1583. pool->stale_shares++;
  1584. break;
  1585. }
  1586. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1587. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1588. kill_work();
  1589. break;
  1590. }
  1591. /* pause, then restart work-request loop */
  1592. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1593. opt_fail_pause);
  1594. sleep(opt_fail_pause);
  1595. }
  1596. out:
  1597. workio_cmd_free(wc);
  1598. return NULL;
  1599. }
  1600. static bool workio_submit_work(struct workio_cmd *wc)
  1601. {
  1602. pthread_t submit_thread;
  1603. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1604. applog(LOG_ERR, "Failed to create submit_work_thread");
  1605. return false;
  1606. }
  1607. return true;
  1608. }
  1609. static void inc_staged(struct pool *pool, int inc, bool lp)
  1610. {
  1611. mutex_lock(&stgd_lock);
  1612. if (lp) {
  1613. lp_staged += inc;
  1614. total_staged += inc;
  1615. } else if (lp_staged)
  1616. --lp_staged;
  1617. else
  1618. total_staged += inc;
  1619. mutex_unlock(&stgd_lock);
  1620. }
  1621. static void dec_staged(int inc)
  1622. {
  1623. mutex_lock(&stgd_lock);
  1624. total_staged -= inc;
  1625. mutex_unlock(&stgd_lock);
  1626. }
  1627. static int requests_staged(void)
  1628. {
  1629. int ret;
  1630. mutex_lock(&stgd_lock);
  1631. ret = total_staged;
  1632. mutex_unlock(&stgd_lock);
  1633. return ret;
  1634. }
  1635. static int real_staged(void)
  1636. {
  1637. int ret;
  1638. mutex_lock(&stgd_lock);
  1639. ret = total_staged - lp_staged;
  1640. mutex_unlock(&stgd_lock);
  1641. return ret;
  1642. }
  1643. /* Find the pool that currently has the highest priority */
  1644. static struct pool *priority_pool(int choice)
  1645. {
  1646. struct pool *ret = NULL;
  1647. int i;
  1648. for (i = 0; i < total_pools; i++) {
  1649. struct pool *pool = pools[i];
  1650. if (pool->prio == choice) {
  1651. ret = pool;
  1652. break;
  1653. }
  1654. }
  1655. if (unlikely(!ret)) {
  1656. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1657. return pools[choice];
  1658. }
  1659. return ret;
  1660. }
  1661. static void restart_longpoll(void);
  1662. static void switch_pools(struct pool *selected)
  1663. {
  1664. struct pool *pool, *last_pool;
  1665. int i, pool_no;
  1666. mutex_lock(&control_lock);
  1667. last_pool = currentpool;
  1668. pool_no = currentpool->pool_no;
  1669. /* Switch selected to pool number 0 and move the rest down */
  1670. if (selected) {
  1671. if (selected->prio != 0) {
  1672. for (i = 0; i < total_pools; i++) {
  1673. pool = pools[i];
  1674. if (pool->prio < selected->prio)
  1675. pool->prio++;
  1676. }
  1677. selected->prio = 0;
  1678. }
  1679. }
  1680. switch (pool_strategy) {
  1681. /* Both of these set to the master pool */
  1682. case POOL_FAILOVER:
  1683. case POOL_LOADBALANCE:
  1684. for (i = 0; i < total_pools; i++) {
  1685. pool = priority_pool(i);
  1686. if (!pool->idle && pool->enabled) {
  1687. pool_no = pool->pool_no;
  1688. break;
  1689. }
  1690. }
  1691. break;
  1692. /* Both of these simply increment and cycle */
  1693. case POOL_ROUNDROBIN:
  1694. case POOL_ROTATE:
  1695. if (selected) {
  1696. pool_no = selected->pool_no;
  1697. break;
  1698. }
  1699. pool_no++;
  1700. if (pool_no >= total_pools)
  1701. pool_no = 0;
  1702. break;
  1703. default:
  1704. break;
  1705. }
  1706. currentpool = pools[pool_no];
  1707. pool = currentpool;
  1708. mutex_unlock(&control_lock);
  1709. if (pool != last_pool) {
  1710. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1711. restart_longpoll();
  1712. }
  1713. /* Reset the queued amount to allow more to be queued for the new pool */
  1714. mutex_lock(&qd_lock);
  1715. total_queued = 0;
  1716. mutex_unlock(&qd_lock);
  1717. inc_staged(pool, 1, true);
  1718. }
  1719. static void set_curblock(char *hexstr, unsigned char *hash)
  1720. {
  1721. unsigned char hash_swap[32];
  1722. char *old_hash = NULL;
  1723. struct timeval tv_now;
  1724. /* Don't free current_hash directly to avoid dereferencing it when
  1725. * we might be accessing its data elsewhere */
  1726. if (current_hash)
  1727. old_hash = current_hash;
  1728. memcpy(current_block, hexstr, 36);
  1729. gettimeofday(&tv_now, NULL);
  1730. get_timestamp(blocktime, &tv_now);
  1731. swap256(hash_swap, hash);
  1732. current_hash = bin2hex(hash_swap, 16);
  1733. if (unlikely(!current_hash))
  1734. quit (1, "set_curblock OOM");
  1735. if (old_hash)
  1736. free(old_hash);
  1737. }
  1738. static void test_work_current(struct work *work)
  1739. {
  1740. char *hexstr;
  1741. /* Only use the primary pool for determination */
  1742. if (work->pool != current_pool() || work->cloned || work->rolls || work->clone)
  1743. return;
  1744. hexstr = bin2hex(work->data, 36);
  1745. if (unlikely(!hexstr)) {
  1746. applog(LOG_ERR, "stage_thread OOM");
  1747. return;
  1748. }
  1749. /* current_block is blanked out on successful longpoll */
  1750. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1751. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1752. block_changed = BLOCK_DETECT;
  1753. new_blocks++;
  1754. if (have_longpoll)
  1755. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1756. else
  1757. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1758. /* As we can't flush the work from here, signal the
  1759. * wakeup thread to restart all the threads */
  1760. work_restart[watchdog_thr_id].restart = 1;
  1761. } else
  1762. block_changed = BLOCK_NONE;
  1763. set_curblock(hexstr, work->data);
  1764. }
  1765. free(hexstr);
  1766. }
  1767. static void *stage_thread(void *userdata)
  1768. {
  1769. struct thr_info *mythr = userdata;
  1770. bool ok = true;
  1771. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1772. while (ok) {
  1773. struct work *work = NULL;
  1774. if (opt_debug)
  1775. applog(LOG_DEBUG, "Popping work to stage thread");
  1776. work = tq_pop(mythr->q, NULL);
  1777. if (unlikely(!work)) {
  1778. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1779. ok = false;
  1780. break;
  1781. }
  1782. test_work_current(work);
  1783. if (opt_debug)
  1784. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1785. if (unlikely(!tq_push(getq, work))) {
  1786. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1787. ok = false;
  1788. break;
  1789. }
  1790. inc_staged(work->pool, 1, false);
  1791. }
  1792. tq_freeze(mythr->q);
  1793. return NULL;
  1794. }
  1795. static char *curses_input(const char *query);
  1796. static int curses_int(const char *query)
  1797. {
  1798. int ret;
  1799. char *cvar;
  1800. cvar = curses_input(query);
  1801. ret = atoi(cvar);
  1802. free(cvar);
  1803. return ret;
  1804. }
  1805. static bool input_pool(bool live);
  1806. static int active_pools(void)
  1807. {
  1808. int ret = 0;
  1809. int i;
  1810. for (i = 0; i < total_pools; i++) {
  1811. if ((pools[i])->enabled)
  1812. ret++;
  1813. }
  1814. return ret;
  1815. }
  1816. static void display_pool_summary(struct pool *pool)
  1817. {
  1818. double efficiency = 0.0;
  1819. mutex_lock(&curses_lock);
  1820. wlog("Pool: %s\n", pool->rpc_url);
  1821. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  1822. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1823. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1824. wlog(" Accepted shares: %d\n", pool->accepted);
  1825. wlog(" Rejected shares: %d\n", pool->rejected);
  1826. if (pool->accepted || pool->rejected)
  1827. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1828. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1829. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1830. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1831. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1832. wlog(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1833. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1834. wrefresh(logwin);
  1835. mutex_unlock(&curses_lock);
  1836. }
  1837. /* We can't remove the memory used for this struct pool because there may
  1838. * still be work referencing it. We just remove it from the pools list */
  1839. static void remove_pool(struct pool *pool)
  1840. {
  1841. int i, last_pool = total_pools - 1;
  1842. struct pool *other;
  1843. /* Boost priority of any lower prio than this one */
  1844. for (i = 0; i < total_pools; i++) {
  1845. other = pools[i];
  1846. if (other->prio > pool->prio)
  1847. other->prio--;
  1848. }
  1849. if (pool->pool_no < last_pool) {
  1850. /* Swap the last pool for this one */
  1851. (pools[last_pool])->pool_no = pool->pool_no;
  1852. pools[pool->pool_no] = pools[last_pool];
  1853. }
  1854. /* Give it an invalid number */
  1855. pool->pool_no = total_pools;
  1856. total_pools--;
  1857. }
  1858. static void display_pools(void)
  1859. {
  1860. struct pool *pool;
  1861. int selected, i;
  1862. char input;
  1863. opt_loginput = true;
  1864. immedok(logwin, true);
  1865. updated:
  1866. clear_logwin();
  1867. for (i = 0; i < total_pools; i++) {
  1868. pool = pools[i];
  1869. if (pool == current_pool())
  1870. wattron(logwin, A_BOLD);
  1871. if (!pool->enabled)
  1872. wattron(logwin, A_DIM);
  1873. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  1874. pool->pool_no,
  1875. pool->enabled? "Enabled" : "Disabled",
  1876. pool->idle? "Dead" : "Alive",
  1877. pool->prio,
  1878. pool->rpc_url, pool->rpc_user);
  1879. wattroff(logwin, A_BOLD | A_DIM);
  1880. }
  1881. retry:
  1882. wlogprint("\nCurrent pool management strategy: %s\n",
  1883. strategies[pool_strategy]);
  1884. if (pool_strategy == POOL_ROTATE)
  1885. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  1886. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  1887. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  1888. wlogprint("Or press any other key to continue\n");
  1889. input = getch();
  1890. if (!strncasecmp(&input, "a", 1)) {
  1891. input_pool(true);
  1892. goto updated;
  1893. } else if (!strncasecmp(&input, "r", 1)) {
  1894. if (total_pools <= 1) {
  1895. wlogprint("Cannot remove last pool");
  1896. goto retry;
  1897. }
  1898. selected = curses_int("Select pool number");
  1899. if (selected < 0 || selected >= total_pools) {
  1900. wlogprint("Invalid selection\n");
  1901. goto retry;
  1902. }
  1903. pool = pools[selected];
  1904. if (pool == current_pool())
  1905. switch_pools(NULL);
  1906. if (pool == current_pool()) {
  1907. wlogprint("Unable to remove pool due to activity\n");
  1908. goto retry;
  1909. }
  1910. pool->enabled = false;
  1911. remove_pool(pool);
  1912. goto updated;
  1913. } else if (!strncasecmp(&input, "s", 1)) {
  1914. selected = curses_int("Select pool number");
  1915. if (selected < 0 || selected >= total_pools) {
  1916. wlogprint("Invalid selection\n");
  1917. goto retry;
  1918. }
  1919. pool = pools[selected];
  1920. pool->enabled = true;
  1921. switch_pools(pool);
  1922. goto updated;
  1923. } else if (!strncasecmp(&input, "d", 1)) {
  1924. if (active_pools() <= 1) {
  1925. wlogprint("Cannot disable last pool");
  1926. goto retry;
  1927. }
  1928. selected = curses_int("Select pool number");
  1929. if (selected < 0 || selected >= total_pools) {
  1930. wlogprint("Invalid selection\n");
  1931. goto retry;
  1932. }
  1933. pool = pools[selected];
  1934. pool->enabled = false;
  1935. if (pool == current_pool())
  1936. switch_pools(NULL);
  1937. goto updated;
  1938. } else if (!strncasecmp(&input, "e", 1)) {
  1939. selected = curses_int("Select pool number");
  1940. if (selected < 0 || selected >= total_pools) {
  1941. wlogprint("Invalid selection\n");
  1942. goto retry;
  1943. }
  1944. pool = pools[selected];
  1945. pool->enabled = true;
  1946. if (pool->prio < current_pool()->prio)
  1947. switch_pools(pool);
  1948. goto updated;
  1949. } else if (!strncasecmp(&input, "c", 1)) {
  1950. for (i = 0; i <= TOP_STRATEGY; i++)
  1951. wlogprint("%d: %s\n", i, strategies[i]);
  1952. selected = curses_int("Select strategy number type");
  1953. if (selected < 0 || selected > TOP_STRATEGY) {
  1954. wlogprint("Invalid selection\n");
  1955. goto retry;
  1956. }
  1957. if (selected == POOL_ROTATE) {
  1958. opt_rotate_period = curses_int("Select interval in minutes");
  1959. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  1960. opt_rotate_period = 0;
  1961. wlogprint("Invalid selection\n");
  1962. goto retry;
  1963. }
  1964. }
  1965. pool_strategy = selected;
  1966. switch_pools(NULL);
  1967. goto updated;
  1968. } else if (!strncasecmp(&input, "i", 1)) {
  1969. selected = curses_int("Select pool number");
  1970. if (selected < 0 || selected >= total_pools) {
  1971. wlogprint("Invalid selection\n");
  1972. goto retry;
  1973. }
  1974. pool = pools[selected];
  1975. display_pool_summary(pool);
  1976. goto retry;
  1977. }
  1978. clear_logwin();
  1979. immedok(logwin, false);
  1980. opt_loginput = false;
  1981. }
  1982. static void display_options(void)
  1983. {
  1984. int selected;
  1985. char input;
  1986. opt_loginput = true;
  1987. immedok(logwin, true);
  1988. retry:
  1989. clear_logwin();
  1990. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  1991. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n[R]PC debug:%s\n[L]og interval:%d\n",
  1992. opt_debug ? "on" : "off",
  1993. want_per_device_stats? "on" : "off",
  1994. opt_quiet ? "on" : "off",
  1995. opt_log_output ? "on" : "off",
  1996. opt_protocol ? "on" : "off",
  1997. opt_log_interval);
  1998. wlogprint("Select an option or any other key to return\n");
  1999. input = getch();
  2000. if (!strncasecmp(&input, "q", 1)) {
  2001. opt_quiet ^= true;
  2002. clear_logwin();
  2003. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2004. } else if (!strncasecmp(&input, "v", 1)) {
  2005. opt_log_output ^= true;
  2006. if (opt_log_output)
  2007. opt_quiet = false;
  2008. clear_logwin();
  2009. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2010. } else if (!strncasecmp(&input, "n", 1)) {
  2011. opt_log_output = false;
  2012. opt_debug = false;
  2013. opt_quiet = false;
  2014. opt_protocol = false;
  2015. want_per_device_stats = false;
  2016. clear_logwin();
  2017. wlogprint("Output mode reset to normal\n");
  2018. } else if (!strncasecmp(&input, "d", 1)) {
  2019. opt_debug ^= true;
  2020. opt_log_output = opt_debug;
  2021. if (opt_debug)
  2022. opt_quiet = false;
  2023. clear_logwin();
  2024. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2025. } else if (!strncasecmp(&input, "p", 1)) {
  2026. want_per_device_stats ^= true;
  2027. opt_log_output = want_per_device_stats;
  2028. clear_logwin();
  2029. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2030. } else if (!strncasecmp(&input, "r", 1)) {
  2031. opt_protocol ^= true;
  2032. if (opt_protocol)
  2033. opt_quiet = false;
  2034. clear_logwin();
  2035. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2036. } else if (!strncasecmp(&input, "c", 1))
  2037. clear_logwin();
  2038. else if (!strncasecmp(&input, "l", 1)) {
  2039. selected = curses_int("Interval in seconds");
  2040. if (selected < 0 || selected > 9999) {
  2041. wlogprint("Invalid selection\n");
  2042. goto retry;
  2043. }
  2044. opt_log_interval = selected;
  2045. clear_logwin();
  2046. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2047. } else if (!strncasecmp(&input, "s", 1)) {
  2048. opt_realquiet = true;
  2049. clear_logwin();
  2050. } else clear_logwin();
  2051. immedok(logwin, false);
  2052. opt_loginput = false;
  2053. }
  2054. static void set_options(void)
  2055. {
  2056. int selected;
  2057. char input;
  2058. opt_loginput = true;
  2059. immedok(logwin, true);
  2060. retry:
  2061. clear_logwin();
  2062. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  2063. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  2064. if (opt_dynamic)
  2065. wlogprint("[I]ntensity: Dynamic\n");
  2066. else
  2067. wlogprint("[I]ntensity: %d\n", scan_intensity);
  2068. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  2069. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  2070. wlogprint("Select an option or any other key to return\n");
  2071. input = getch();
  2072. if (!strncasecmp(&input, "q", 1)) {
  2073. selected = curses_int("Extra work items to queue");
  2074. if (selected < 0 || selected > 9999) {
  2075. wlogprint("Invalid selection\n");
  2076. goto retry;
  2077. }
  2078. opt_queue = selected;
  2079. goto retry;
  2080. } else if (!strncasecmp(&input, "d", 1)) {
  2081. opt_dynamic ^= true;
  2082. goto retry;
  2083. } else if (!strncasecmp(&input, "l", 1)) {
  2084. want_longpoll ^= true;
  2085. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2086. restart_longpoll();
  2087. goto retry;
  2088. } else if (!strncasecmp(&input, "i", 1)) {
  2089. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  2090. if (selected < -10 || selected > 10) {
  2091. wlogprint("Invalid selection\n");
  2092. goto retry;
  2093. }
  2094. opt_dynamic = false;
  2095. scan_intensity = selected;
  2096. goto retry;
  2097. } else if (!strncasecmp(&input, "s", 1)) {
  2098. selected = curses_int("Set scantime in seconds");
  2099. if (selected < 0 || selected > 9999) {
  2100. wlogprint("Invalid selection\n");
  2101. goto retry;
  2102. }
  2103. opt_scantime = selected;
  2104. goto retry;
  2105. } else if (!strncasecmp(&input, "r", 1)) {
  2106. selected = curses_int("Retries before failing (-1 infinite)");
  2107. if (selected < -1 || selected > 9999) {
  2108. wlogprint("Invalid selection\n");
  2109. goto retry;
  2110. }
  2111. opt_retries = selected;
  2112. goto retry;
  2113. } else if (!strncasecmp(&input, "p", 1)) {
  2114. selected = curses_int("Seconds to pause before network retries");
  2115. if (selected < 1 || selected > 9999) {
  2116. wlogprint("Invalid selection\n");
  2117. goto retry;
  2118. }
  2119. opt_fail_pause = selected;
  2120. goto retry;
  2121. }
  2122. clear_logwin();
  2123. immedok(logwin, false);
  2124. opt_loginput = false;
  2125. }
  2126. #ifdef HAVE_OPENCL
  2127. static void reinit_device(struct cgpu_info *cgpu);
  2128. static void manage_gpu(void)
  2129. {
  2130. struct thr_info *thr;
  2131. int selected, gpu, i;
  2132. char checkin[40];
  2133. char input;
  2134. if (!opt_g_threads)
  2135. return;
  2136. opt_loginput = true;
  2137. immedok(logwin, true);
  2138. clear_logwin();
  2139. retry:
  2140. for (gpu = 0; gpu < nDevs; gpu++) {
  2141. struct cgpu_info *cgpu = &gpus[gpu];
  2142. wlog("GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  2143. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  2144. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  2145. cgpu->efficiency, cgpu->utility);
  2146. wlog("Last initialised: %s\n", cgpu->init);
  2147. for (i = 0; i < mining_threads; i++) {
  2148. thr = &thr_info[i];
  2149. if (thr->cgpu != cgpu)
  2150. continue;
  2151. get_datestamp(checkin, &thr->last);
  2152. wlog("Thread %d: %.1f Mh/s %s ", i, thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  2153. switch (cgpu->status) {
  2154. default:
  2155. case LIFE_WELL:
  2156. wlog("ALIVE");
  2157. break;
  2158. case LIFE_SICK:
  2159. wlog("SICK reported in %s", checkin);
  2160. break;
  2161. case LIFE_DEAD:
  2162. wlog("DEAD reported in %s", checkin);
  2163. break;
  2164. }
  2165. wlog("\n");
  2166. }
  2167. wlog("\n");
  2168. }
  2169. wlogprint("[E]nable [D]isable [R]estart GPU\n");
  2170. wlogprint("Or press any other key to continue\n");
  2171. input = getch();
  2172. if (!strncasecmp(&input, "e", 1)) {
  2173. selected = curses_int("Select GPU to enable");
  2174. if (selected < 0 || selected >= nDevs) {
  2175. wlogprint("Invalid selection\n");
  2176. goto retry;
  2177. }
  2178. if (gpu_devices[selected]) {
  2179. wlogprint("Device already enabled\n");
  2180. goto retry;
  2181. }
  2182. gpu_devices[selected] = true;
  2183. for (i = 0; i < gpu_threads; i++) {
  2184. if (dev_from_id(i) != selected)
  2185. continue;
  2186. thr = &thr_info[i];
  2187. if (opt_debug)
  2188. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  2189. tq_push(thr->q, &ping);
  2190. }
  2191. } if (!strncasecmp(&input, "d", 1)) {
  2192. selected = curses_int("Select GPU to disable");
  2193. if (selected < 0 || selected >= nDevs) {
  2194. wlogprint("Invalid selection\n");
  2195. goto retry;
  2196. }
  2197. if (!gpu_devices[selected]) {
  2198. wlogprint("Device already disabled\n");
  2199. goto retry;
  2200. }
  2201. gpu_devices[selected] = false;
  2202. } else if (!strncasecmp(&input, "r", 1)) {
  2203. selected = curses_int("Select GPU to attempt to restart");
  2204. if (selected < 0 || selected >= nDevs) {
  2205. wlogprint("Invalid selection\n");
  2206. goto retry;
  2207. }
  2208. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  2209. reinit_device(&gpus[selected]);
  2210. }
  2211. clear_logwin();
  2212. immedok(logwin, false);
  2213. opt_loginput = false;
  2214. }
  2215. #else
  2216. static void manage_gpu(void)
  2217. {
  2218. }
  2219. #endif
  2220. static void *input_thread(void *userdata)
  2221. {
  2222. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2223. if (!curses_active)
  2224. return NULL;
  2225. while (1) {
  2226. char input;
  2227. input = getch();
  2228. if (!strncasecmp(&input, "q", 1)) {
  2229. kill_work();
  2230. return NULL;
  2231. } else if (!strncasecmp(&input, "d", 1))
  2232. display_options();
  2233. else if (!strncasecmp(&input, "p", 1))
  2234. display_pools();
  2235. else if (!strncasecmp(&input, "s", 1))
  2236. set_options();
  2237. else if (!strncasecmp(&input, "g", 1))
  2238. manage_gpu();
  2239. if (opt_realquiet) {
  2240. disable_curses();
  2241. break;
  2242. }
  2243. }
  2244. return NULL;
  2245. }
  2246. static void *workio_thread(void *userdata)
  2247. {
  2248. struct thr_info *mythr = userdata;
  2249. bool ok = true;
  2250. while (ok) {
  2251. struct workio_cmd *wc;
  2252. if (opt_debug)
  2253. applog(LOG_DEBUG, "Popping work to work thread");
  2254. /* wait for workio_cmd sent to us, on our queue */
  2255. wc = tq_pop(mythr->q, NULL);
  2256. if (unlikely(!wc)) {
  2257. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2258. ok = false;
  2259. break;
  2260. }
  2261. /* process workio_cmd */
  2262. switch (wc->cmd) {
  2263. case WC_GET_WORK:
  2264. ok = workio_get_work(wc);
  2265. break;
  2266. case WC_SUBMIT_WORK:
  2267. ok = workio_submit_work(wc);
  2268. break;
  2269. case WC_DIE:
  2270. default:
  2271. ok = false;
  2272. break;
  2273. }
  2274. }
  2275. tq_freeze(mythr->q);
  2276. return NULL;
  2277. }
  2278. static void thread_reportin(struct thr_info *thr)
  2279. {
  2280. gettimeofday(&thr->last, NULL);
  2281. thr->cgpu->status = LIFE_WELL;
  2282. thr->getwork = false;
  2283. }
  2284. static inline void thread_reportout(struct thr_info *thr)
  2285. {
  2286. thr->getwork = true;
  2287. }
  2288. static void hashmeter(int thr_id, struct timeval *diff,
  2289. unsigned long hashes_done)
  2290. {
  2291. struct timeval temp_tv_end, total_diff;
  2292. double secs;
  2293. double local_secs;
  2294. double utility, efficiency = 0.0;
  2295. static double local_mhashes_done = 0;
  2296. static double rolling = 0;
  2297. double local_mhashes = (double)hashes_done / 1000000.0;
  2298. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2299. bool showlog = false;
  2300. /* Update the last time this thread reported in */
  2301. if (thr_id >= 0)
  2302. gettimeofday(&thr_info[thr_id].last, NULL);
  2303. /* Don't bother calculating anything if we're not displaying it */
  2304. if (opt_realquiet || !opt_log_interval)
  2305. return;
  2306. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2307. /* So we can call hashmeter from a non worker thread */
  2308. if (thr_id >= 0) {
  2309. struct thr_info *thr = &thr_info[thr_id];
  2310. double thread_rolling = 0.0;
  2311. int i;
  2312. if (opt_debug)
  2313. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2314. thr_id, hashes_done, hashes_done / secs);
  2315. /* Rolling average for each thread and each device */
  2316. decay_time(&thr->rolling, local_mhashes / secs);
  2317. for (i = 0; i < mining_threads; i++) {
  2318. struct thr_info *th = &thr_info[i];
  2319. if (th->cgpu == cgpu)
  2320. thread_rolling += th->rolling;
  2321. }
  2322. decay_time(&cgpu->rolling, thread_rolling);
  2323. cgpu->total_mhashes += local_mhashes;
  2324. // If needed, output detailed, per-device stats
  2325. if (want_per_device_stats) {
  2326. struct timeval now;
  2327. struct timeval elapsed;
  2328. gettimeofday(&now, NULL);
  2329. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2330. if (opt_log_interval <= elapsed.tv_sec) {
  2331. thr->cgpu->last_message_tv = now;
  2332. sprintf(
  2333. statusline,
  2334. "[%sPU%d (%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2335. thr->cgpu->is_gpu ? "G" : "C",
  2336. thr->cgpu->cpu_gpu,
  2337. opt_log_interval,
  2338. thr->cgpu->rolling,
  2339. thr->cgpu->total_mhashes / total_secs,
  2340. thr->cgpu->getworks,
  2341. thr->cgpu->accepted,
  2342. thr->cgpu->rejected,
  2343. thr->cgpu->hw_errors,
  2344. thr->cgpu->efficiency,
  2345. thr->cgpu->utility
  2346. );
  2347. if (!curses_active) {
  2348. printf("%s \r", statusline);
  2349. fflush(stdout);
  2350. } else
  2351. applog(LOG_INFO, "%s", statusline);
  2352. }
  2353. }
  2354. }
  2355. /* Totals are updated by all threads so can race without locking */
  2356. mutex_lock(&hash_lock);
  2357. gettimeofday(&temp_tv_end, NULL);
  2358. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2359. total_mhashes_done += local_mhashes;
  2360. local_mhashes_done += local_mhashes;
  2361. if (total_diff.tv_sec < opt_log_interval)
  2362. /* Only update the total every opt_log_interval seconds */
  2363. goto out_unlock;
  2364. showlog = true;
  2365. gettimeofday(&total_tv_end, NULL);
  2366. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2367. decay_time(&rolling, local_mhashes_done / local_secs);
  2368. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2369. total_secs = (double)total_diff.tv_sec +
  2370. ((double)total_diff.tv_usec / 1000000.0);
  2371. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2372. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2373. sprintf(statusline, "[%s(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2374. want_per_device_stats ? "ALL " : "",
  2375. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2376. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2377. local_mhashes_done = 0;
  2378. out_unlock:
  2379. mutex_unlock(&hash_lock);
  2380. if (showlog) {
  2381. if (!curses_active) {
  2382. printf("%s \r", statusline);
  2383. fflush(stdout);
  2384. } else
  2385. applog(LOG_INFO, "%s", statusline);
  2386. }
  2387. }
  2388. /* This is overkill, but at least we'll know accurately how much work is
  2389. * queued to prevent ever being left without work */
  2390. static void inc_queued(void)
  2391. {
  2392. mutex_lock(&qd_lock);
  2393. total_queued++;
  2394. mutex_unlock(&qd_lock);
  2395. }
  2396. static void dec_queued(void)
  2397. {
  2398. mutex_lock(&qd_lock);
  2399. if (total_queued > 0)
  2400. total_queued--;
  2401. mutex_unlock(&qd_lock);
  2402. dec_staged(1);
  2403. }
  2404. static int requests_queued(void)
  2405. {
  2406. int ret;
  2407. mutex_lock(&qd_lock);
  2408. ret = total_queued;
  2409. mutex_unlock(&qd_lock);
  2410. return ret;
  2411. }
  2412. static bool pool_active(struct pool *pool, bool pinging)
  2413. {
  2414. bool ret = false;
  2415. json_t *val;
  2416. CURL *curl;
  2417. bool rolltime;
  2418. curl = curl_easy_init();
  2419. if (unlikely(!curl)) {
  2420. applog(LOG_ERR, "CURL initialisation failed");
  2421. return false;
  2422. }
  2423. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2424. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2425. true, false, &rolltime, pool);
  2426. if (val) {
  2427. struct work *work = make_work();
  2428. bool rc;
  2429. rc = work_decode(json_object_get(val, "result"), work);
  2430. if (rc) {
  2431. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2432. pool->pool_no, pool->rpc_url);
  2433. work->pool = pool;
  2434. work->rolltime = rolltime;
  2435. if (opt_debug)
  2436. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2437. tq_push(thr_info[stage_thr_id].q, work);
  2438. total_getworks++;
  2439. pool->getwork_requested++;
  2440. inc_queued();
  2441. ret = true;
  2442. gettimeofday(&pool->tv_idle, NULL);
  2443. } else {
  2444. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2445. pool->pool_no, pool->rpc_url);
  2446. free_work(work);
  2447. }
  2448. json_decref(val);
  2449. } else {
  2450. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2451. pool->pool_no, pool->rpc_url);
  2452. if (!pinging)
  2453. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  2454. }
  2455. curl_easy_cleanup(curl);
  2456. return ret;
  2457. }
  2458. static void pool_died(struct pool *pool)
  2459. {
  2460. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2461. gettimeofday(&pool->tv_idle, NULL);
  2462. switch_pools(NULL);
  2463. }
  2464. static void pool_resus(struct pool *pool)
  2465. {
  2466. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  2467. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  2468. switch_pools(NULL);
  2469. }
  2470. static bool queue_request(struct thr_info *thr, bool needed)
  2471. {
  2472. int maxq = opt_queue + mining_threads;
  2473. struct workio_cmd *wc;
  2474. int rq, rs;
  2475. rq = requests_queued();
  2476. rs = real_staged();
  2477. /* If we've been generating lots of local work we may already have
  2478. * enough in the queue */
  2479. if (rq >= maxq || rs >= maxq)
  2480. return true;
  2481. /* fill out work request message */
  2482. wc = calloc(1, sizeof(*wc));
  2483. if (unlikely(!wc)) {
  2484. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2485. return false;
  2486. }
  2487. wc->cmd = WC_GET_WORK;
  2488. if (thr)
  2489. wc->thr = thr;
  2490. else
  2491. wc->thr = NULL;
  2492. /* If we're queueing work faster than we can stage it, consider the
  2493. * system lagging and allow work to be gathered from another pool if
  2494. * possible */
  2495. if (!rs && rq && needed)
  2496. wc->lagging = true;
  2497. if (opt_debug)
  2498. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2499. /* send work request to workio thread */
  2500. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2501. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2502. workio_cmd_free(wc);
  2503. return false;
  2504. }
  2505. inc_queued();
  2506. return true;
  2507. }
  2508. static void discard_work(struct work *work)
  2509. {
  2510. if (!work->clone && !work->rolls && !work->mined) {
  2511. if (work->pool)
  2512. work->pool->discarded_work++;
  2513. total_discarded++;
  2514. if (opt_debug)
  2515. applog(LOG_DEBUG, "Discarded work");
  2516. } else if (opt_debug)
  2517. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2518. free_work(work);
  2519. }
  2520. static void discard_staged(void)
  2521. {
  2522. struct timespec abstime = {};
  2523. struct timeval now;
  2524. struct work *work_heap;
  2525. /* Just in case we fell in a hole and missed a queue filling */
  2526. if (unlikely(!requests_staged()))
  2527. return;
  2528. gettimeofday(&now, NULL);
  2529. abstime.tv_sec = now.tv_sec + 60;
  2530. if (opt_debug)
  2531. applog(LOG_DEBUG, "Popping work to discard staged");
  2532. work_heap = tq_pop(getq, &abstime);
  2533. if (unlikely(!work_heap))
  2534. return;
  2535. discard_work(work_heap);
  2536. dec_queued();
  2537. }
  2538. static void flush_requests(void)
  2539. {
  2540. struct pool *pool = current_pool();
  2541. int i, stale;
  2542. /* We should have one fresh work item staged from the block change. */
  2543. stale = requests_staged() - 1;
  2544. /* Temporarily increase the staged count so that get_work thinks there
  2545. * is work available instead of making threads reuse existing work */
  2546. inc_staged(pool, mining_threads, true);
  2547. for (i = 0; i < stale; i++) {
  2548. /* Queue a whole batch of new requests */
  2549. if (unlikely(!queue_request(NULL, true))) {
  2550. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  2551. kill_work();
  2552. break;
  2553. }
  2554. /* Pop off the old requests. Cancelling the requests would be better
  2555. * but is tricky */
  2556. discard_staged();
  2557. }
  2558. }
  2559. static inline bool should_roll(struct work *work)
  2560. {
  2561. int rs;
  2562. rs = real_staged();
  2563. if (rs >= opt_queue + mining_threads)
  2564. return false;
  2565. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  2566. return true;
  2567. return false;
  2568. }
  2569. static inline bool can_roll(struct work *work)
  2570. {
  2571. return (work->pool && !stale_work(work) && work->rolltime &&
  2572. work->rolls < 11 && !work->clone);
  2573. }
  2574. static void roll_work(struct work *work)
  2575. {
  2576. uint32_t *work_ntime;
  2577. uint32_t ntime;
  2578. work_ntime = (uint32_t *)(work->data + 68);
  2579. ntime = be32toh(*work_ntime);
  2580. ntime++;
  2581. *work_ntime = htobe32(ntime);
  2582. local_work++;
  2583. work->rolls++;
  2584. work->blk.nonce = 0;
  2585. if (opt_debug)
  2586. applog(LOG_DEBUG, "Successfully rolled work");
  2587. }
  2588. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  2589. * giving it to will not finish scanning it. We keep the master copy to be
  2590. * recycled more rapidly and discard the clone to avoid repeating work */
  2591. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  2592. {
  2593. uint64_t hash_inc;
  2594. if (work->clone)
  2595. return false;
  2596. hash_inc = MAXTHREADS / hash_div * 2;
  2597. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  2598. /* Okay we can divide it up */
  2599. work->blk.nonce += hash_inc;
  2600. work->cloned = true;
  2601. local_work++;
  2602. if (opt_debug)
  2603. applog(LOG_DEBUG, "Successfully divided work");
  2604. return true;
  2605. } else if (can_roll(work) && should_roll(work)) {
  2606. roll_work(work);
  2607. return true;
  2608. }
  2609. return false;
  2610. }
  2611. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2612. const int thr_id, uint32_t hash_div)
  2613. {
  2614. struct timespec abstime = {};
  2615. struct timeval now;
  2616. struct work *work_heap;
  2617. struct pool *pool;
  2618. bool ret = false;
  2619. int failures = 0;
  2620. /* Tell the watchdog thread this thread is waiting on getwork and
  2621. * should not be restarted */
  2622. thread_reportout(thr);
  2623. retry:
  2624. pool = current_pool();
  2625. if (unlikely(!requested && !queue_request(thr, true))) {
  2626. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2627. goto out;
  2628. }
  2629. requested = false;
  2630. if (!requests_staged() && can_roll(work)) {
  2631. /* Only print this message once each time we shift to localgen */
  2632. if (!pool_tset(pool, &pool->idle)) {
  2633. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  2634. pool->pool_no);
  2635. pool->localgen_occasions++;
  2636. total_lo++;
  2637. gettimeofday(&pool->tv_idle, NULL);
  2638. } else {
  2639. struct timeval tv_now, diff;
  2640. gettimeofday(&tv_now, NULL);
  2641. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  2642. /* Attempt to switch pools if this one has been unresponsive for >half
  2643. * a block's duration */
  2644. if (diff.tv_sec > 300) {
  2645. pool_died(pool);
  2646. goto retry;
  2647. }
  2648. }
  2649. roll_work(work);
  2650. ret = true;
  2651. goto out;
  2652. }
  2653. gettimeofday(&now, NULL);
  2654. abstime.tv_sec = now.tv_sec + 60;
  2655. if (opt_debug)
  2656. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2657. /* wait for 1st response, or get cached response */
  2658. work_heap = tq_pop(getq, &abstime);
  2659. if (unlikely(!work_heap)) {
  2660. /* Attempt to switch pools if this one has mandatory work that
  2661. * has timed out or does not support rolltime */
  2662. pool->localgen_occasions++;
  2663. total_lo++;
  2664. pool_died(pool);
  2665. goto retry;
  2666. }
  2667. if (stale_work(work_heap)) {
  2668. dec_queued();
  2669. discard_work(work_heap);
  2670. goto retry;
  2671. }
  2672. pool = work_heap->pool;
  2673. /* If we make it here we have succeeded in getting fresh work */
  2674. if (pool_tclear(pool, &pool->idle))
  2675. pool_resus(pool);
  2676. memcpy(work, work_heap, sizeof(*work));
  2677. /* Copy the res nonce back so we know to start at a higher baseline
  2678. * should we divide the same work up again. Make the work we're
  2679. * handing out be clone */
  2680. if (divide_work(&now, work_heap, hash_div)) {
  2681. if (opt_debug)
  2682. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2683. tq_push_head(getq, work_heap);
  2684. work->clone = true;
  2685. } else {
  2686. dec_queued();
  2687. free_work(work_heap);
  2688. }
  2689. ret = true;
  2690. out:
  2691. if (unlikely(ret == false)) {
  2692. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2693. applog(LOG_ERR, "Failed %d times to get_work");
  2694. return ret;
  2695. }
  2696. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  2697. sleep(opt_fail_pause);
  2698. goto retry;
  2699. }
  2700. work->thr_id = thr_id;
  2701. thread_reportin(thr);
  2702. if (ret)
  2703. work->mined = true;
  2704. return ret;
  2705. }
  2706. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2707. {
  2708. struct workio_cmd *wc;
  2709. /* fill out work request message */
  2710. wc = calloc(1, sizeof(*wc));
  2711. if (unlikely(!wc)) {
  2712. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2713. return false;
  2714. }
  2715. wc->u.work = make_work();
  2716. wc->cmd = WC_SUBMIT_WORK;
  2717. wc->thr = thr;
  2718. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2719. if (opt_debug)
  2720. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2721. /* send solution to workio thread */
  2722. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2723. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2724. goto err_out;
  2725. }
  2726. return true;
  2727. err_out:
  2728. workio_cmd_free(wc);
  2729. return false;
  2730. }
  2731. struct swa {
  2732. struct thr_info *thr;
  2733. const struct work *work_in;
  2734. };
  2735. static void *swasync_thread(void *userdata)
  2736. {
  2737. struct swa *swa = (struct swa *)userdata;
  2738. /* Return value ignored */
  2739. submit_work_sync(swa->thr, swa->work_in);
  2740. free(swa);
  2741. return NULL;
  2742. }
  2743. static bool submit_work_async(struct thr_info *thr, const struct work *work_in)
  2744. {
  2745. pthread_t sw_thread;
  2746. struct swa *swa;
  2747. swa = malloc(sizeof(struct swa));
  2748. if (unlikely(!swa)) {
  2749. applog(LOG_ERR, "Failed to malloc swa in submit_work_async");
  2750. return false;
  2751. }
  2752. swa->thr = thr;
  2753. swa->work_in = work_in;
  2754. if (unlikely(pthread_create(&sw_thread, NULL, swasync_thread, (void *)swa))) {
  2755. applog(LOG_ERR, "Failed to create swasync_thread");
  2756. return false;
  2757. }
  2758. return true;
  2759. }
  2760. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2761. {
  2762. work->data[64+12+0] = (nonce>>0) & 0xff;
  2763. work->data[64+12+1] = (nonce>>8) & 0xff;
  2764. work->data[64+12+2] = (nonce>>16) & 0xff;
  2765. work->data[64+12+3] = (nonce>>24) & 0xff;
  2766. /* Do one last check before attempting to submit the work */
  2767. if (!fulltest(work->data + 64, work->target))
  2768. return true;
  2769. return submit_work_sync(thr, work);
  2770. }
  2771. static void *miner_thread(void *userdata)
  2772. {
  2773. struct work *work = make_work();
  2774. struct thr_info *mythr = userdata;
  2775. const int thr_id = mythr->id;
  2776. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  2777. unsigned long hashes_done = max_nonce;
  2778. bool needs_work = true;
  2779. /* Try to cycle approximately 5 times before each log update */
  2780. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2781. int request_interval;
  2782. bool requested = false;
  2783. uint32_t hash_div = 1;
  2784. double hash_divfloat = 1.0;
  2785. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2786. /* Request the next work item just before the end of the scantime. We
  2787. * don't want the work lying around too long since the CPU will always
  2788. * spend the full scantime */
  2789. request_interval = opt_scantime - 5;
  2790. if (request_interval < 1)
  2791. request_interval = 1;
  2792. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  2793. * and if that fails, then SCHED_BATCH. No need for this to be an
  2794. * error if it fails */
  2795. setpriority(PRIO_PROCESS, 0, 19);
  2796. drop_policy();
  2797. /* Cpu affinity only makes sense if the number of threads is a multiple
  2798. * of the number of CPUs */
  2799. if (!(opt_n_threads % num_processors))
  2800. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  2801. /* Invalidate pool so it fails can_roll() test */
  2802. work->pool = NULL;
  2803. while (1) {
  2804. struct timeval tv_workstart, tv_start, tv_end, diff;
  2805. uint64_t max64;
  2806. bool rc;
  2807. if (needs_work) {
  2808. gettimeofday(&tv_workstart, NULL);
  2809. /* obtain new work from internal workio thread */
  2810. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2811. applog(LOG_ERR, "work retrieval failed, exiting "
  2812. "mining thread %d", thr_id);
  2813. goto out;
  2814. }
  2815. needs_work = requested = false;
  2816. total_hashes = 0;
  2817. max_nonce = work->blk.nonce + hashes_done;
  2818. }
  2819. hashes_done = 0;
  2820. gettimeofday(&tv_start, NULL);
  2821. /* scan nonces for a proof-of-work hash */
  2822. switch (opt_algo) {
  2823. case ALGO_C:
  2824. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  2825. work->hash1, work->hash, work->target,
  2826. max_nonce, &hashes_done,
  2827. work->blk.nonce);
  2828. break;
  2829. #ifdef WANT_X8664_SSE2
  2830. case ALGO_SSE2_64: {
  2831. unsigned int rc5 =
  2832. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  2833. work->hash1, work->hash,
  2834. work->target,
  2835. max_nonce, &hashes_done,
  2836. work->blk.nonce);
  2837. rc = (rc5 == -1) ? false : true;
  2838. }
  2839. break;
  2840. #endif
  2841. #ifdef WANT_X8664_SSE4
  2842. case ALGO_SSE4_64: {
  2843. unsigned int rc5 =
  2844. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  2845. work->hash1, work->hash,
  2846. work->target,
  2847. max_nonce, &hashes_done,
  2848. work->blk.nonce);
  2849. rc = (rc5 == -1) ? false : true;
  2850. }
  2851. break;
  2852. #endif
  2853. #ifdef WANT_SSE2_4WAY
  2854. case ALGO_4WAY: {
  2855. unsigned int rc4 =
  2856. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  2857. work->hash1, work->hash,
  2858. work->target,
  2859. max_nonce, &hashes_done,
  2860. work->blk.nonce);
  2861. rc = (rc4 == -1) ? false : true;
  2862. }
  2863. break;
  2864. #endif
  2865. #ifdef WANT_VIA_PADLOCK
  2866. case ALGO_VIA:
  2867. rc = scanhash_via(thr_id, work->data, work->target,
  2868. max_nonce, &hashes_done,
  2869. work->blk.nonce);
  2870. break;
  2871. #endif
  2872. case ALGO_CRYPTOPP:
  2873. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  2874. work->hash1, work->hash, work->target,
  2875. max_nonce, &hashes_done,
  2876. work->blk.nonce);
  2877. break;
  2878. #ifdef WANT_CRYPTOPP_ASM32
  2879. case ALGO_CRYPTOPP_ASM32:
  2880. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  2881. work->hash1, work->hash, work->target,
  2882. max_nonce, &hashes_done,
  2883. work->blk.nonce);
  2884. break;
  2885. #endif
  2886. default:
  2887. /* should never happen */
  2888. goto out;
  2889. }
  2890. /* record scanhash elapsed time */
  2891. gettimeofday(&tv_end, NULL);
  2892. timeval_subtract(&diff, &tv_end, &tv_start);
  2893. hashes_done -= work->blk.nonce;
  2894. hashmeter(thr_id, &diff, hashes_done);
  2895. total_hashes += hashes_done;
  2896. work->blk.nonce += hashes_done;
  2897. /* adjust max_nonce to meet target cycle time */
  2898. if (diff.tv_usec > 500000)
  2899. diff.tv_sec++;
  2900. if (diff.tv_sec && diff.tv_sec != cycle) {
  2901. max64 = work->blk.nonce +
  2902. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  2903. } else if (!diff.tv_sec)
  2904. max64 = work->blk.nonce + (hashes_done * 2);
  2905. else
  2906. max64 = work->blk.nonce + hashes_done;
  2907. if (max64 > 0xfffffffaULL)
  2908. max64 = 0xfffffffaULL;
  2909. max_nonce = max64;
  2910. /* if nonce found, submit work */
  2911. if (unlikely(rc)) {
  2912. if (opt_debug)
  2913. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  2914. if (unlikely(!submit_work_async(mythr, work))) {
  2915. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  2916. break;
  2917. }
  2918. work->blk.nonce += 4;
  2919. }
  2920. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2921. if (!requested && (diff.tv_sec >= request_interval)) {
  2922. thread_reportout(mythr);
  2923. if (unlikely(!queue_request(mythr, false))) {
  2924. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2925. goto out;
  2926. }
  2927. thread_reportin(mythr);
  2928. requested = true;
  2929. }
  2930. if (diff.tv_sec > opt_scantime) {
  2931. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  2932. hash_div = hash_divfloat;
  2933. needs_work = true;
  2934. } else if (work_restart[thr_id].restart || stale_work(work) ||
  2935. work->blk.nonce >= MAXTHREADS - hashes_done)
  2936. needs_work = true;
  2937. }
  2938. out:
  2939. thread_reportin(mythr);
  2940. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2941. tq_freeze(mythr->q);
  2942. return NULL;
  2943. }
  2944. enum {
  2945. STAT_SLEEP_INTERVAL = 1,
  2946. STAT_CTR_INTERVAL = 10000000,
  2947. FAILURE_INTERVAL = 30,
  2948. };
  2949. #ifdef HAVE_OPENCL
  2950. static _clState *clStates[16];
  2951. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  2952. {
  2953. cl_kernel *kernel = &clState->kernel;
  2954. cl_int status = 0;
  2955. int num = 0;
  2956. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2957. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2958. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2959. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2960. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2961. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2962. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2963. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2964. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2965. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2966. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  2967. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2968. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2969. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2970. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2971. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  2972. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  2973. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  2974. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  2975. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  2976. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  2977. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  2978. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  2979. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2980. (void *)&clState->outputBuffer);
  2981. return status;
  2982. }
  2983. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  2984. {
  2985. cl_uint vwidth = clState->preferred_vwidth;
  2986. cl_kernel *kernel = &clState->kernel;
  2987. cl_int status = 0;
  2988. int i, num = 0;
  2989. uint *nonces;
  2990. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2991. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2992. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2993. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2994. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2995. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2996. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2997. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2998. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2999. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3000. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3001. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3002. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3003. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3004. nonces = alloca(sizeof(uint) * vwidth);
  3005. for (i = 0; i < vwidth; i++)
  3006. nonces[i] = blk->nonce + i;
  3007. status |= clSetKernelArg(*kernel, num++, vwidth * sizeof(uint), (void *)nonces);
  3008. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  3009. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  3010. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4_2);
  3011. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal0);
  3012. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW18);
  3013. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW19);
  3014. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW31);
  3015. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW32);
  3016. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3017. (void *)&clState->outputBuffer);
  3018. return status;
  3019. }
  3020. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  3021. unsigned int *hashes, size_t *globalThreads,
  3022. unsigned int minthreads)
  3023. {
  3024. *threads = 1 << (15 + scan_intensity);
  3025. if (*threads < minthreads)
  3026. *threads = minthreads;
  3027. *globalThreads = *threads;
  3028. *hashes = *threads * vectors;
  3029. }
  3030. static void *gpuminer_thread(void *userdata)
  3031. {
  3032. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  3033. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3034. struct timeval tv_start, tv_end, diff, tv_workstart;
  3035. struct thr_info *mythr = userdata;
  3036. const int thr_id = mythr->id;
  3037. uint32_t *res, *blank_res;
  3038. double gpu_ms_average = 7;
  3039. int gpu = dev_from_id(thr_id);
  3040. size_t globalThreads[1];
  3041. size_t localThreads[1];
  3042. cl_int status;
  3043. _clState *clState = clStates[thr_id];
  3044. const cl_kernel *kernel = &clState->kernel;
  3045. struct work *work = make_work();
  3046. unsigned int threads;
  3047. unsigned const int vectors = clState->preferred_vwidth;
  3048. unsigned int hashes;
  3049. unsigned int hashes_done = 0;
  3050. /* Request the next work item at 2/3 of the scantime */
  3051. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3052. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3053. bool requested = false;
  3054. uint32_t total_hashes = 0, hash_div = 1;
  3055. switch (chosen_kernel) {
  3056. case KL_POCLBM:
  3057. queue_kernel_parameters = &queue_poclbm_kernel;
  3058. break;
  3059. case KL_PHATK:
  3060. default:
  3061. queue_kernel_parameters = &queue_phatk_kernel;
  3062. break;
  3063. }
  3064. if (opt_dynamic) {
  3065. /* Minimise impact on desktop if we want dynamic mode */
  3066. setpriority(PRIO_PROCESS, 0, 19);
  3067. drop_policy();
  3068. }
  3069. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3070. res = calloc(BUFFERSIZE, 1);
  3071. blank_res = calloc(BUFFERSIZE, 1);
  3072. if (!res || !blank_res) {
  3073. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  3074. goto out;
  3075. }
  3076. gettimeofday(&tv_start, NULL);
  3077. localThreads[0] = clState->work_size;
  3078. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  3079. localThreads[0]);
  3080. diff.tv_sec = 0;
  3081. gettimeofday(&tv_end, NULL);
  3082. work->pool = NULL;
  3083. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  3084. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3085. if (unlikely(status != CL_SUCCESS))
  3086. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3087. mythr->cgpu->status = LIFE_WELL;
  3088. if (opt_debug)
  3089. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  3090. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3091. gettimeofday(&tv_workstart, NULL);
  3092. /* obtain new work from internal workio thread */
  3093. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3094. applog(LOG_ERR, "work retrieval failed, exiting "
  3095. "gpu mining thread %d", thr_id);
  3096. goto out;
  3097. }
  3098. requested = false;
  3099. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3100. work->blk.nonce = 0;
  3101. while (1) {
  3102. struct timeval tv_gpustart, tv_gpuend;
  3103. suseconds_t gpu_us;
  3104. gettimeofday(&tv_gpustart, NULL);
  3105. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  3106. /* This finish flushes the readbuffer set with CL_FALSE later */
  3107. clFinish(clState->commandQueue);
  3108. gettimeofday(&tv_gpuend, NULL);
  3109. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  3110. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  3111. decay_time(&gpu_ms_average, gpu_us / 1000);
  3112. if (opt_dynamic) {
  3113. /* Try to not let the GPU be out for longer than 6ms, but
  3114. * increase intensity when the system is idle, unless
  3115. * dynamic is disabled. */
  3116. if (gpu_ms_average > 7) {
  3117. if (scan_intensity > -10)
  3118. scan_intensity--;
  3119. } else if (gpu_ms_average < 3) {
  3120. if (scan_intensity < 10)
  3121. scan_intensity++;
  3122. }
  3123. }
  3124. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  3125. if (diff.tv_sec > opt_scantime ||
  3126. work->blk.nonce >= MAXTHREADS - hashes ||
  3127. work_restart[thr_id].restart ||
  3128. stale_work(work)) {
  3129. /* Ignore any reads since we're getting new work and queue a clean buffer */
  3130. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3131. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3132. if (unlikely(status != CL_SUCCESS))
  3133. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3134. memset(res, 0, BUFFERSIZE);
  3135. gettimeofday(&tv_workstart, NULL);
  3136. if (opt_debug)
  3137. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  3138. /* obtain new work from internal workio thread */
  3139. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3140. applog(LOG_ERR, "work retrieval failed, exiting "
  3141. "gpu mining thread %d", thr_id);
  3142. goto out;
  3143. }
  3144. requested = false;
  3145. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3146. work_restart[thr_id].restart = 0;
  3147. /* Flushes the writebuffer set with CL_FALSE above */
  3148. clFinish(clState->commandQueue);
  3149. }
  3150. status = queue_kernel_parameters(clState, &work->blk);
  3151. if (unlikely(status != CL_SUCCESS))
  3152. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  3153. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  3154. if (res[FOUND]) {
  3155. /* Clear the buffer again */
  3156. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3157. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3158. if (unlikely(status != CL_SUCCESS))
  3159. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3160. if (opt_debug)
  3161. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  3162. postcalc_hash_async(mythr, work, res);
  3163. memset(res, 0, BUFFERSIZE);
  3164. clFinish(clState->commandQueue);
  3165. }
  3166. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  3167. globalThreads, localThreads, 0, NULL, NULL);
  3168. if (unlikely(status != CL_SUCCESS))
  3169. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  3170. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3171. BUFFERSIZE, res, 0, NULL, NULL);
  3172. if (unlikely(status != CL_SUCCESS))
  3173. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  3174. gettimeofday(&tv_end, NULL);
  3175. timeval_subtract(&diff, &tv_end, &tv_start);
  3176. hashes_done += hashes;
  3177. total_hashes += hashes;
  3178. work->blk.nonce += hashes;
  3179. if (diff.tv_sec >= cycle) {
  3180. hashmeter(thr_id, &diff, hashes_done);
  3181. gettimeofday(&tv_start, NULL);
  3182. hashes_done = 0;
  3183. }
  3184. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3185. if (!requested) {
  3186. #if 0
  3187. if (diff.tv_sec > request_interval)
  3188. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  3189. #endif
  3190. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3191. thread_reportout(mythr);
  3192. if (unlikely(!queue_request(mythr, false))) {
  3193. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  3194. goto out;
  3195. }
  3196. thread_reportin(mythr);
  3197. requested = true;
  3198. }
  3199. }
  3200. if (unlikely(!gpu_devices[gpu])) {
  3201. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3202. mythr->rolling = mythr->cgpu->rolling = 0;
  3203. if (opt_debug)
  3204. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  3205. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3206. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3207. }
  3208. }
  3209. out:
  3210. thread_reportin(mythr);
  3211. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3212. tq_freeze(mythr->q);
  3213. return NULL;
  3214. }
  3215. #endif /* HAVE_OPENCL */
  3216. static void restart_threads(void)
  3217. {
  3218. int i;
  3219. if (block_changed == BLOCK_DETECT)
  3220. block_changed = BLOCK_NONE;
  3221. /* Discard old queued requests and get new ones */
  3222. flush_requests();
  3223. for (i = 0; i < mining_threads; i++)
  3224. work_restart[i].restart = 1;
  3225. }
  3226. /* Stage another work item from the work returned in a longpoll */
  3227. static void convert_to_work(json_t *val, bool rolltime)
  3228. {
  3229. struct work *work;
  3230. bool rc;
  3231. work = make_work();
  3232. rc= work_decode(json_object_get(val, "result"), work);
  3233. if (unlikely(!rc)) {
  3234. applog(LOG_ERR, "Could not convert longpoll data to work");
  3235. return;
  3236. }
  3237. work->pool = current_pool();
  3238. work->rolltime = rolltime;
  3239. if (opt_debug)
  3240. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3241. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  3242. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  3243. else if (opt_debug)
  3244. applog(LOG_DEBUG, "Converted longpoll data to work");
  3245. }
  3246. static void *longpoll_thread(void *userdata)
  3247. {
  3248. struct thr_info *mythr = userdata;
  3249. CURL *curl = NULL;
  3250. char *copy_start, *hdr_path, *lp_url = NULL;
  3251. bool need_slash = false;
  3252. int failures = 0;
  3253. struct pool *pool = current_pool();
  3254. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3255. curl = curl_easy_init();
  3256. if (unlikely(!curl)) {
  3257. applog(LOG_ERR, "CURL initialisation failed");
  3258. goto out;
  3259. }
  3260. tq_pop(mythr->q, NULL);
  3261. if (!pool->hdr_path) {
  3262. applog(LOG_WARNING, "No long-poll found on this server");
  3263. goto out;
  3264. }
  3265. hdr_path = pool->hdr_path;
  3266. /* full URL */
  3267. if (strstr(hdr_path, "://")) {
  3268. lp_url = hdr_path;
  3269. hdr_path = NULL;
  3270. }
  3271. /* absolute path, on current server */
  3272. else {
  3273. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3274. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3275. need_slash = true;
  3276. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3277. if (!lp_url)
  3278. goto out;
  3279. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3280. }
  3281. have_longpoll = true;
  3282. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  3283. while (1) {
  3284. struct timeval start, end;
  3285. bool rolltime;
  3286. json_t *val;
  3287. gettimeofday(&start, NULL);
  3288. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3289. false, true, &rolltime, pool);
  3290. if (likely(val)) {
  3291. /* Keep track of who ordered a restart_threads to make
  3292. * sure it's only done once per new block */
  3293. if (block_changed != BLOCK_DETECT) {
  3294. block_changed = BLOCK_LP;
  3295. new_blocks++;
  3296. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  3297. restart_threads();
  3298. } else {
  3299. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  3300. block_changed = BLOCK_NONE;
  3301. }
  3302. convert_to_work(val, rolltime);
  3303. failures = 0;
  3304. json_decref(val);
  3305. } else {
  3306. /* Some pools regularly drop the longpoll request so
  3307. * only see this as longpoll failure if it happens
  3308. * immediately and just restart it the rest of the
  3309. * time. */
  3310. gettimeofday(&end, NULL);
  3311. if (end.tv_sec - start.tv_sec > 30)
  3312. continue;
  3313. if (failures++ < 10) {
  3314. sleep(30);
  3315. applog(LOG_WARNING,
  3316. "longpoll failed, sleeping for 30s");
  3317. } else {
  3318. applog(LOG_ERR,
  3319. "longpoll failed, ending thread");
  3320. goto out;
  3321. }
  3322. }
  3323. }
  3324. out:
  3325. have_longpoll = false;
  3326. free(lp_url);
  3327. tq_freeze(mythr->q);
  3328. if (curl)
  3329. curl_easy_cleanup(curl);
  3330. return NULL;
  3331. }
  3332. static void stop_longpoll(void)
  3333. {
  3334. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3335. tq_freeze(thr->q);
  3336. pthread_cancel(*thr->pth);
  3337. have_longpoll = false;
  3338. }
  3339. static void start_longpoll(void)
  3340. {
  3341. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3342. tq_thaw(thr->q);
  3343. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3344. quit(1, "longpoll thread create failed");
  3345. pthread_detach(*thr->pth);
  3346. if (opt_debug)
  3347. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3348. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3349. }
  3350. static void restart_longpoll(void)
  3351. {
  3352. stop_longpoll();
  3353. if (want_longpoll)
  3354. start_longpoll();
  3355. }
  3356. static void *reinit_cpu(void *userdata)
  3357. {
  3358. pthread_detach(pthread_self());
  3359. #if 0
  3360. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  3361. int cpu = cgpu->cpu_gpu;
  3362. long thr_id = ....(long)userdata;
  3363. struct thr_info *thr = &thr_info[thr_id];
  3364. int cpu = dev_from_id(thr_id);
  3365. cpus[cpu].alive = false;
  3366. thr->rolling = thr->cgpu->rolling = 0;
  3367. tq_freeze(thr->q);
  3368. if (!pthread_cancel(*thr->pth))
  3369. pthread_join(*thr->pth, NULL);
  3370. free(thr->q);
  3371. thr->q = tq_new();
  3372. if (!thr->q)
  3373. quit(1, "Failed to tq_new in reinit_cputhread");
  3374. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  3375. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  3376. applog(LOG_ERR, "thread %d create failed", thr_id);
  3377. return NULL;
  3378. }
  3379. tq_push(thr->q, &ping);
  3380. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3381. #endif
  3382. return NULL;
  3383. }
  3384. #ifdef HAVE_OPENCL
  3385. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  3386. * init command fails due to a completely wedged GPU, the thread will never
  3387. * return, unable to harm other GPUs. If it does return, it means we only had
  3388. * a soft failure and then the reinit_gpu thread is ready to tackle another
  3389. * GPU */
  3390. static void *reinit_gpu(void *userdata)
  3391. {
  3392. struct thr_info *mythr = userdata;
  3393. struct cgpu_info *cgpu;
  3394. struct thr_info *thr;
  3395. struct timeval now;
  3396. char name[256];
  3397. int thr_id;
  3398. int gpu;
  3399. pthread_detach(pthread_self());
  3400. select_cgpu:
  3401. cgpu = tq_pop(mythr->q, NULL);
  3402. if (!cgpu)
  3403. goto out;
  3404. if (clDevicesNum() != nDevs) {
  3405. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  3406. goto out;
  3407. }
  3408. gpu = cgpu->cpu_gpu;
  3409. gpu_devices[gpu] = false;
  3410. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3411. if (dev_from_id(thr_id) != gpu)
  3412. continue;
  3413. thr = &thr_info[thr_id];
  3414. thr->rolling = thr->cgpu->rolling = 0;
  3415. if (!pthread_cancel(*thr->pth)) {
  3416. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  3417. } else
  3418. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  3419. }
  3420. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3421. if (dev_from_id(thr_id) != gpu)
  3422. continue;
  3423. thr = &thr_info[thr_id];
  3424. /* Lose this ram cause we may get stuck here! */
  3425. //tq_freeze(thr->q);
  3426. thr->q = tq_new();
  3427. if (!thr->q)
  3428. quit(1, "Failed to tq_new in reinit_gpu");
  3429. /* Lose this ram cause we may dereference in the dying thread! */
  3430. //free(clState);
  3431. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  3432. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  3433. if (!clStates[thr_id]) {
  3434. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  3435. goto out;
  3436. }
  3437. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3438. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  3439. applog(LOG_ERR, "thread %d create failed", thr_id);
  3440. return NULL;
  3441. }
  3442. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3443. }
  3444. gettimeofday(&now, NULL);
  3445. get_datestamp(cgpu->init, &now);
  3446. gpu_devices[gpu] = true;
  3447. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3448. if (dev_from_id(thr_id) != gpu)
  3449. continue;
  3450. thr = &thr_info[thr_id];
  3451. tq_push(thr->q, &ping);
  3452. }
  3453. goto select_cgpu;
  3454. out:
  3455. return NULL;
  3456. }
  3457. #else
  3458. static void *reinit_gpu(void *userdata)
  3459. {
  3460. }
  3461. #endif
  3462. static void reinit_device(struct cgpu_info *cgpu)
  3463. {
  3464. if (cgpu->is_gpu)
  3465. tq_push(thr_info[gpur_thr_id].q, cgpu);
  3466. else
  3467. tq_push(thr_info[cpur_thr_id].q, cgpu);
  3468. }
  3469. /* Determine which are the first threads belonging to a device and if they're
  3470. * active */
  3471. static bool active_device(int thr_id)
  3472. {
  3473. if (thr_id < gpu_threads) {
  3474. if (thr_id >= total_devices)
  3475. return false;
  3476. if (!gpu_devices[dev_from_id(thr_id)])
  3477. return false;
  3478. } else if (thr_id > gpu_threads + num_processors)
  3479. return false;
  3480. return true;
  3481. }
  3482. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3483. * the screen at regular intervals, and restarts threads if they appear to have
  3484. * died. */
  3485. static void *watchdog_thread(void *userdata)
  3486. {
  3487. const unsigned int interval = opt_log_interval / 2 ? : 1;
  3488. static struct timeval rotate_tv;
  3489. struct timeval zero_tv;
  3490. bool statwin = false;
  3491. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3492. memset(&zero_tv, 0, sizeof(struct timeval));
  3493. gettimeofday(&rotate_tv, NULL);
  3494. while (1) {
  3495. int i;
  3496. struct timeval now;
  3497. sleep(interval);
  3498. if (requests_queued() < opt_queue)
  3499. queue_request(NULL, false);
  3500. hashmeter(-1, &zero_tv, 0);
  3501. if (curses_active) {
  3502. statwin ^= true;
  3503. mutex_lock(&curses_lock);
  3504. for (i = 0; i < mining_threads; i++)
  3505. curses_print_status(i);
  3506. if (statwin)
  3507. redrawwin(statuswin);
  3508. else {
  3509. check_logwinsize();
  3510. redrawwin(logwin);
  3511. }
  3512. mutex_unlock(&curses_lock);
  3513. }
  3514. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  3515. restart_threads();
  3516. work_restart[watchdog_thr_id].restart = 0;
  3517. }
  3518. gettimeofday(&now, NULL);
  3519. for (i = 0; i < total_pools; i++) {
  3520. struct pool *pool = pools[i];
  3521. if (!pool->enabled)
  3522. continue;
  3523. /* Test pool is idle once every minute */
  3524. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3525. gettimeofday(&pool->tv_idle, NULL);
  3526. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3527. pool_resus(pool);
  3528. }
  3529. }
  3530. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3531. gettimeofday(&rotate_tv, NULL);
  3532. switch_pools(NULL);
  3533. }
  3534. //for (i = 0; i < mining_threads; i++) {
  3535. for (i = 0; i < gpu_threads; i++) {
  3536. struct thr_info *thr = &thr_info[i];
  3537. int gpu = thr->cgpu->cpu_gpu;
  3538. /* Thread is waiting on getwork or disabled */
  3539. if (thr->getwork || !gpu_devices[gpu])
  3540. continue;
  3541. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3542. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  3543. gpus[gpu].status = LIFE_WELL;
  3544. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3545. thr->rolling = thr->cgpu->rolling = 0;
  3546. gpus[gpu].status = LIFE_SICK;
  3547. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3548. /* Sent it a ping, it might respond */
  3549. tq_push(thr->q, &ping);
  3550. } else if (now.tv_sec - thr->last.tv_sec > 300 && gpus[i].status == LIFE_SICK) {
  3551. gpus[gpu].status = LIFE_DEAD;
  3552. applog(LOG_ERR, "Thread %d idle for more than 5 minutes, GPU %d declared DEAD!", i, gpu);
  3553. applog(LOG_ERR, "Attempting to restart GPU");
  3554. reinit_device(thr->cgpu);
  3555. break;
  3556. }
  3557. }
  3558. }
  3559. return NULL;
  3560. }
  3561. static void log_print_status(int thr_id)
  3562. {
  3563. struct cgpu_info *cgpu;
  3564. cgpu = thr_info[thr_id].cgpu;
  3565. applog(LOG_WARNING, " %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  3566. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  3567. cgpu->total_mhashes / total_secs, cgpu->getworks,
  3568. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  3569. cgpu->efficiency, cgpu->utility);
  3570. }
  3571. static void print_summary(void)
  3572. {
  3573. struct timeval diff;
  3574. int hours, mins, secs, i;
  3575. double utility, efficiency = 0.0;
  3576. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3577. hours = diff.tv_sec / 3600;
  3578. mins = (diff.tv_sec % 3600) / 60;
  3579. secs = diff.tv_sec % 60;
  3580. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3581. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3582. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  3583. applog(LOG_WARNING, "Started at %s", datestamp);
  3584. if (opt_n_threads)
  3585. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  3586. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  3587. if (total_secs)
  3588. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  3589. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  3590. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  3591. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  3592. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  3593. if (total_accepted || total_rejected)
  3594. applog(LOG_WARNING, "Reject ratio: %.1f", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3595. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  3596. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  3597. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  3598. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  3599. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  3600. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_lo);
  3601. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  3602. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  3603. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  3604. if (total_pools > 1) {
  3605. for (i = 0; i < total_pools; i++) {
  3606. struct pool *pool = pools[i];
  3607. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  3608. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  3609. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  3610. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  3611. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  3612. if (pool->accepted || pool->rejected)
  3613. applog(LOG_WARNING, " Reject ratio: %.1f", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3614. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3615. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  3616. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  3617. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  3618. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->localgen_occasions);
  3619. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  3620. }
  3621. }
  3622. applog(LOG_WARNING, "Summary of per device statistics:\n");
  3623. for (i = 0; i < mining_threads; i++) {
  3624. if (active_device(i))
  3625. log_print_status(i);
  3626. }
  3627. fflush(stdout);
  3628. fflush(stderr);
  3629. }
  3630. void quit(int status, const char *format, ...)
  3631. {
  3632. va_list ap;
  3633. disable_curses();
  3634. if (format) {
  3635. va_start(ap, format);
  3636. vfprintf(stderr, format, ap);
  3637. va_end(ap);
  3638. }
  3639. fprintf(stderr, "\n");
  3640. fflush(stderr);
  3641. exit(status);
  3642. }
  3643. static char *curses_input(const char *query)
  3644. {
  3645. char *input;
  3646. echo();
  3647. input = malloc(255);
  3648. if (!input)
  3649. quit(1, "Failed to malloc input");
  3650. leaveok(logwin, false);
  3651. wlogprint("%s: ", query);
  3652. wgetnstr(logwin, input, 255);
  3653. leaveok(logwin, true);
  3654. noecho();
  3655. return input;
  3656. }
  3657. static bool input_pool(bool live)
  3658. {
  3659. char *url = NULL, *user = NULL, *pass = NULL;
  3660. struct pool *pool = NULL;
  3661. bool ret = false;
  3662. immedok(logwin, true);
  3663. if (total_pools == MAX_POOLS) {
  3664. wlogprint("Reached maximum number of pools.\n");
  3665. goto out;
  3666. }
  3667. wlogprint("Input server details.\n");
  3668. url = curses_input("URL");
  3669. if (!url)
  3670. goto out;
  3671. if (strncmp(url, "http://", 7) &&
  3672. strncmp(url, "https://", 8)) {
  3673. char *httpinput;
  3674. httpinput = malloc(255);
  3675. if (!httpinput)
  3676. quit(1, "Failed to malloc httpinput");
  3677. strcpy(httpinput, "http://");
  3678. strncat(httpinput, url, 248);
  3679. free(url);
  3680. url = httpinput;
  3681. }
  3682. user = curses_input("Username");
  3683. if (!user)
  3684. goto out;
  3685. pass = curses_input("Password");
  3686. if (!pass)
  3687. goto out;
  3688. pool = calloc(sizeof(struct pool), 1);
  3689. if (!pool)
  3690. quit(1, "Failed to realloc pools in input_pool");
  3691. pool->pool_no = total_pools;
  3692. pool->prio = total_pools;
  3693. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3694. quit (1, "Failed to pthread_mutex_init in input_pool");
  3695. pool->rpc_url = url;
  3696. pool->rpc_user = user;
  3697. pool->rpc_pass = pass;
  3698. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3699. if (!pool->rpc_userpass)
  3700. quit(1, "Failed to malloc userpass");
  3701. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3702. pool->tv_idle.tv_sec = ~0UL;
  3703. /* Test the pool before we enable it if we're live running, otherwise
  3704. * it will be tested separately */
  3705. ret = true;
  3706. if (live && pool_active(pool, false))
  3707. pool->enabled = true;
  3708. pools[total_pools++] = pool;
  3709. out:
  3710. immedok(logwin, false);
  3711. if (!ret) {
  3712. if (url)
  3713. free(url);
  3714. if (user)
  3715. free(user);
  3716. if (pass)
  3717. free(pass);
  3718. if (pool)
  3719. free(pool);
  3720. }
  3721. return ret;
  3722. }
  3723. #if defined(unix)
  3724. static void fork_monitor()
  3725. {
  3726. // Make a pipe: [readFD, writeFD]
  3727. int pfd[2];
  3728. int r = pipe(pfd);
  3729. if (r<0) {
  3730. perror("pipe - failed to create pipe for --monitor");
  3731. exit(1);
  3732. }
  3733. // Make stderr write end of pipe
  3734. fflush(stderr);
  3735. r = dup2(pfd[1], 2);
  3736. if (r<0) {
  3737. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3738. exit(1);
  3739. }
  3740. r = close(pfd[1]);
  3741. if (r<0) {
  3742. perror("close - failed to close write end of pipe for --monitor");
  3743. exit(1);
  3744. }
  3745. // Don't allow a dying monitor to kill the main process
  3746. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3747. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3748. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3749. perror("signal - failed to edit signal mask for --monitor");
  3750. exit(1);
  3751. }
  3752. // Fork a child process
  3753. r = fork();
  3754. if (r<0) {
  3755. perror("fork - failed to fork child process for --monitor");
  3756. exit(1);
  3757. }
  3758. // Child: launch monitor command
  3759. if (0==r) {
  3760. // Make stdin read end of pipe
  3761. r = dup2(pfd[0], 0);
  3762. if (r<0) {
  3763. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3764. exit(1);
  3765. }
  3766. close(pfd[0]);
  3767. if (r<0) {
  3768. perror("close - in child, failed to close read end of pipe for --monitor");
  3769. exit(1);
  3770. }
  3771. // Launch user specified command
  3772. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3773. perror("execl - in child failed to exec user specified command for --monitor");
  3774. exit(1);
  3775. }
  3776. // Parent: clean up unused fds and bail
  3777. r = close(pfd[0]);
  3778. if (r<0) {
  3779. perror("close - failed to close read end of pipe for --monitor");
  3780. exit(1);
  3781. }
  3782. }
  3783. #endif // defined(unix)
  3784. int main (int argc, char *argv[])
  3785. {
  3786. unsigned int i, x, y, pools_active = 0;
  3787. struct sigaction handler;
  3788. struct thr_info *thr;
  3789. char name[256];
  3790. /* This dangerous functions tramples random dynamically allocated
  3791. * variables so do it before anything at all */
  3792. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3793. quit(1, "Failed to curl_global_init");
  3794. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  3795. quit(1, "Failed to pthread_mutex_init");
  3796. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  3797. quit(1, "Failed to pthread_mutex_init");
  3798. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  3799. quit(1, "Failed to pthread_mutex_init");
  3800. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  3801. quit(1, "Failed to pthread_mutex_init");
  3802. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  3803. quit(1, "Failed to pthread_mutex_init");
  3804. init_max_name_len();
  3805. handler.sa_handler = &sighandler;
  3806. sigaction(SIGTERM, &handler, &termhandler);
  3807. sigaction(SIGINT, &handler, &inthandler);
  3808. gettimeofday(&total_tv_start, NULL);
  3809. gettimeofday(&total_tv_end, NULL);
  3810. get_datestamp(datestamp, &total_tv_start);
  3811. // Hack to make cgminer silent when called recursively on WIN32
  3812. int skip_to_bench = 0;
  3813. #if defined(WIN32)
  3814. char buf[32];
  3815. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  3816. skip_to_bench = 1;
  3817. #endif // defined(WIN32)
  3818. for (i = 0; i < 36; i++)
  3819. strcat(current_block, "0");
  3820. current_hash = calloc(sizeof(current_hash), 1);
  3821. if (unlikely(!current_hash))
  3822. quit (1, "main OOM");
  3823. // Reckon number of cores in the box
  3824. #if defined(WIN32)
  3825. DWORD system_am;
  3826. DWORD process_am;
  3827. BOOL ok = GetProcessAffinityMask(
  3828. GetCurrentProcess(),
  3829. &system_am,
  3830. &process_am
  3831. );
  3832. if (!ok) {
  3833. applog(LOG_ERR, "couldn't figure out number of processors :(");
  3834. num_processors = 1;
  3835. } else {
  3836. size_t n = 32;
  3837. num_processors = 0;
  3838. while (n--)
  3839. if (process_am & (1<<n))
  3840. ++num_processors;
  3841. }
  3842. #else
  3843. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  3844. #endif /* !WIN32 */
  3845. opt_n_threads = num_processors;
  3846. #ifdef HAVE_OPENCL
  3847. if (!skip_to_bench) {
  3848. for (i = 0; i < 16; i++)
  3849. gpu_devices[i] = false;
  3850. nDevs = clDevicesNum();
  3851. if (nDevs < 0) {
  3852. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  3853. nDevs = 0;
  3854. }
  3855. }
  3856. #endif
  3857. if (nDevs)
  3858. opt_n_threads = 0;
  3859. trpc_url = strdup(DEF_RPC_URL);
  3860. /* parse command line */
  3861. opt_register_table(opt_config_table,
  3862. "Options for both config file and command line");
  3863. opt_register_table(opt_cmdline_table,
  3864. "Options for command line only");
  3865. opt_parse(&argc, argv, applog_and_exit);
  3866. if (argc != 1)
  3867. quit(1, "Unexpected extra commandline arguments");
  3868. if (want_per_device_stats)
  3869. opt_log_output = true;
  3870. if (0<=opt_bench_algo) {
  3871. double rate = bench_algo_stage3(opt_bench_algo);
  3872. if (!skip_to_bench) {
  3873. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  3874. } else {
  3875. // Write result to shared memory for parent
  3876. #if defined(WIN32)
  3877. char unique_name[64];
  3878. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  3879. HANDLE map_handle = CreateFileMapping(
  3880. INVALID_HANDLE_VALUE, // use paging file
  3881. NULL, // default security attributes
  3882. PAGE_READWRITE, // read/write access
  3883. 0, // size: high 32-bits
  3884. 4096, // size: low 32-bits
  3885. unique_name // name of map object
  3886. );
  3887. if (NULL!=map_handle) {
  3888. void *shared_mem = MapViewOfFile(
  3889. map_handle, // object to map view of
  3890. FILE_MAP_WRITE, // read/write access
  3891. 0, // high offset: map from
  3892. 0, // low offset: beginning
  3893. 0 // default: map entire file
  3894. );
  3895. if (NULL!=shared_mem)
  3896. CopyMemory(shared_mem, &rate, sizeof(rate));
  3897. (void)UnmapViewOfFile(shared_mem);
  3898. }
  3899. (void)CloseHandle(map_handle);
  3900. }
  3901. #endif
  3902. }
  3903. exit(0);
  3904. }
  3905. if (opt_kernel) {
  3906. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  3907. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  3908. if (!strcmp(opt_kernel, "poclbm"))
  3909. chosen_kernel = KL_POCLBM;
  3910. else
  3911. chosen_kernel = KL_PHATK;
  3912. } else
  3913. chosen_kernel = KL_NONE;
  3914. gpu_threads = nDevs * opt_g_threads;
  3915. if (total_devices) {
  3916. if (total_devices > nDevs)
  3917. quit(1, "More devices specified than exist");
  3918. for (i = 0; i < 16; i++)
  3919. if (gpu_devices[i] && i + 1 > nDevs)
  3920. quit (1, "Command line options set a device that doesn't exist");
  3921. } else {
  3922. for (i = 0; i < nDevs; i++)
  3923. gpu_devices[i] = true;
  3924. total_devices = nDevs;
  3925. }
  3926. if (!gpu_threads && !forced_n_threads) {
  3927. /* Maybe they turned GPU off; restore default CPU threads. */
  3928. opt_n_threads = num_processors;
  3929. }
  3930. logcursor = 8;
  3931. gpucursor = logcursor;
  3932. cpucursor = gpucursor + nDevs;
  3933. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  3934. logcursor = logstart + 1;
  3935. /* Set up the ncurses interface */
  3936. if (!opt_realquiet && use_curses) {
  3937. mainwin = initscr();
  3938. getmaxyx(mainwin, y, x);
  3939. statuswin = newwin(logstart, x, 0, 0);
  3940. leaveok(statuswin, true);
  3941. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3942. idlok(logwin, true);
  3943. scrollok(logwin, true);
  3944. leaveok(logwin, true);
  3945. cbreak();
  3946. noecho();
  3947. test_and_set(&curses_active);
  3948. }
  3949. if (!total_pools) {
  3950. if (curses_active) {
  3951. if (!input_pool(false))
  3952. quit(1, "Pool setup failed");
  3953. } else
  3954. quit(1, "No server specified");
  3955. }
  3956. for (i = 0; i < total_pools; i++) {
  3957. struct pool *pool = pools[i];
  3958. if (!pool->rpc_userpass) {
  3959. if (!pool->rpc_user || !pool->rpc_pass)
  3960. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3961. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3962. if (!pool->rpc_userpass)
  3963. quit(1, "Failed to malloc userpass");
  3964. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3965. } else {
  3966. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  3967. if (!pool->rpc_user)
  3968. quit(1, "Failed to malloc user");
  3969. strcpy(pool->rpc_user, pool->rpc_userpass);
  3970. pool->rpc_user = strtok(pool->rpc_user, ":");
  3971. if (!pool->rpc_user)
  3972. quit(1, "Failed to find colon delimiter in userpass");
  3973. }
  3974. }
  3975. /* Set the currentpool to pool 0 */
  3976. currentpool = pools[0];
  3977. #ifdef HAVE_SYSLOG_H
  3978. if (use_syslog)
  3979. openlog(PROGRAM_NAME, LOG_PID, LOG_USER);
  3980. #endif
  3981. #if defined(unix)
  3982. if (opt_stderr_cmd)
  3983. fork_monitor();
  3984. #endif // defined(unix)
  3985. mining_threads = opt_n_threads + gpu_threads;
  3986. total_threads = mining_threads + 7;
  3987. work_restart = calloc(total_threads, sizeof(*work_restart));
  3988. if (!work_restart)
  3989. quit(1, "Failed to calloc work_restart");
  3990. thr_info = calloc(total_threads, sizeof(*thr));
  3991. if (!thr_info)
  3992. quit(1, "Failed to calloc thr_info");
  3993. /* init workio thread info */
  3994. work_thr_id = mining_threads;
  3995. thr = &thr_info[work_thr_id];
  3996. thr->id = work_thr_id;
  3997. thr->q = tq_new();
  3998. if (!thr->q)
  3999. quit(1, "Failed to tq_new");
  4000. /* start work I/O thread */
  4001. if (thr_info_create(thr, NULL, workio_thread, thr))
  4002. quit(1, "workio thread create failed");
  4003. /* init longpoll thread info */
  4004. longpoll_thr_id = mining_threads + 1;
  4005. thr = &thr_info[longpoll_thr_id];
  4006. thr->id = longpoll_thr_id;
  4007. thr->q = tq_new();
  4008. if (!thr->q)
  4009. quit(1, "Failed to tq_new");
  4010. if (opt_n_threads ) {
  4011. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  4012. if (unlikely(!cpus))
  4013. quit(1, "Failed to calloc cpus");
  4014. }
  4015. if (gpu_threads) {
  4016. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  4017. if (unlikely(!gpus))
  4018. quit(1, "Failed to calloc gpus");
  4019. }
  4020. stage_thr_id = mining_threads + 3;
  4021. thr = &thr_info[stage_thr_id];
  4022. thr->q = tq_new();
  4023. if (!thr->q)
  4024. quit(1, "Failed to tq_new");
  4025. /* start stage thread */
  4026. if (thr_info_create(thr, NULL, stage_thread, thr))
  4027. quit(1, "stage thread create failed");
  4028. pthread_detach(*thr->pth);
  4029. /* Create a unique get work queue */
  4030. getq = tq_new();
  4031. if (!getq)
  4032. quit(1, "Failed to create getq");
  4033. /* Test each pool to see if we can retrieve and use work and for what
  4034. * it supports */
  4035. for (i = 0; i < total_pools; i++) {
  4036. struct pool *pool;
  4037. pool = pools[i];
  4038. if (pool_active(pool, false)) {
  4039. if (!currentpool)
  4040. currentpool = pool;
  4041. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4042. pools_active++;
  4043. pool->enabled = true;
  4044. } else {
  4045. if (pool == currentpool)
  4046. currentpool = NULL;
  4047. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4048. }
  4049. }
  4050. if (!pools_active)
  4051. quit(0, "No pools active! Exiting.");
  4052. if (want_longpoll)
  4053. start_longpoll();
  4054. #ifdef HAVE_OPENCL
  4055. /* start GPU mining threads */
  4056. for (i = 0; i < nDevs * opt_g_threads; i++) {
  4057. int gpu = i % nDevs;
  4058. struct cgpu_info *cgpu;
  4059. struct timeval now;
  4060. gpus[gpu].is_gpu = 1;
  4061. gpus[gpu].cpu_gpu = gpu;
  4062. thr = &thr_info[i];
  4063. thr->id = i;
  4064. cgpu = thr->cgpu = &gpus[gpu];
  4065. thr->q = tq_new();
  4066. if (!thr->q)
  4067. quit(1, "tq_new failed in starting gpu mining threads");
  4068. /* Enable threads for devices set not to mine but disable
  4069. * their queue in case we wish to enable them later*/
  4070. if (gpu_devices[gpu]) {
  4071. if (opt_debug)
  4072. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4073. tq_push(thr->q, &ping);
  4074. }
  4075. applog(LOG_INFO, "Init GPU thread %i", i);
  4076. clStates[i] = initCl(gpu, name, sizeof(name));
  4077. if (!clStates[i]) {
  4078. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  4079. gpu_devices[i] = false;
  4080. continue;
  4081. }
  4082. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4083. gettimeofday(&now, NULL);
  4084. get_datestamp(cgpu->init, &now);
  4085. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  4086. quit(1, "thread %d create failed", i);
  4087. }
  4088. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4089. #else
  4090. opt_g_threads = 0;
  4091. #endif
  4092. /* start CPU mining threads */
  4093. for (i = gpu_threads; i < mining_threads; i++) {
  4094. int cpu = (i - gpu_threads) % num_processors;
  4095. thr = &thr_info[i];
  4096. thr->id = i;
  4097. cpus[cpu].cpu_gpu = cpu;
  4098. thr->cgpu = &cpus[cpu];
  4099. thr->q = tq_new();
  4100. if (!thr->q)
  4101. quit(1, "tq_new failed in starting cpu mining threads");
  4102. thread_reportin(thr);
  4103. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4104. quit(1, "thread %d create failed", i);
  4105. }
  4106. applog(LOG_INFO, "%d cpu miner threads started, "
  4107. "using SHA256 '%s' algorithm.",
  4108. opt_n_threads,
  4109. algo_names[opt_algo]);
  4110. watchdog_thr_id = mining_threads + 2;
  4111. thr = &thr_info[watchdog_thr_id];
  4112. /* start wakeup thread */
  4113. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4114. quit(1, "wakeup thread create failed");
  4115. /* Create curses input thread for keyboard input */
  4116. input_thr_id = mining_threads + 4;
  4117. thr = &thr_info[input_thr_id];
  4118. if (thr_info_create(thr, NULL, input_thread, thr))
  4119. quit(1, "input thread create failed");
  4120. pthread_detach(*thr->pth);
  4121. /* Create reinit cpu thread */
  4122. cpur_thr_id = mining_threads + 5;
  4123. thr = &thr_info[cpur_thr_id];
  4124. thr->q = tq_new();
  4125. if (!thr->q)
  4126. quit(1, "tq_new failed for cpur_thr_id");
  4127. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  4128. quit(1, "reinit_cpu thread create failed");
  4129. /* Create reinit gpu thread */
  4130. gpur_thr_id = mining_threads + 6;
  4131. thr = &thr_info[gpur_thr_id];
  4132. thr->q = tq_new();
  4133. if (!thr->q)
  4134. quit(1, "tq_new failed for gpur_thr_id");
  4135. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4136. quit(1, "reinit_gpu thread create failed");
  4137. /* main loop - simply wait for workio thread to exit */
  4138. pthread_join(*thr_info[work_thr_id].pth, NULL);
  4139. applog(LOG_INFO, "workio thread dead, exiting.");
  4140. gettimeofday(&total_tv_end, NULL);
  4141. disable_curses();
  4142. if (!opt_realquiet && successful_connect)
  4143. print_summary();
  4144. if (gpu_threads)
  4145. free(gpus);
  4146. if (opt_n_threads)
  4147. free(cpus);
  4148. curl_global_cleanup();
  4149. return 0;
  4150. }