main.c 126 KB

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