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