main.c 126 KB

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