main.c 126 KB

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