main.c 124 KB

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