main.c 127 KB

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