main.c 124 KB

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