main.c 118 KB

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