main.c 125 KB

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