main.c 127 KB

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