main.c 122 KB

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