main.c 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853
  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. if (!want_per_device_stats)
  1337. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  1338. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  1339. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  1340. json_decref(val);
  1341. rc = true;
  1342. out:
  1343. free(hexstr);
  1344. out_nofree:
  1345. curl_easy_cleanup(curl);
  1346. return rc;
  1347. }
  1348. static const char *rpc_req =
  1349. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1350. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1351. static inline struct pool *select_pool(bool lagging)
  1352. {
  1353. static int rotating_pool = 0;
  1354. struct pool *pool, *cp;
  1355. cp = current_pool();
  1356. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1357. pool = cp;
  1358. else
  1359. pool = NULL;
  1360. while (!pool) {
  1361. if (++rotating_pool >= total_pools)
  1362. rotating_pool = 0;
  1363. pool = pools[rotating_pool];
  1364. if ((!pool->idle && pool->enabled) || pool == cp)
  1365. break;
  1366. pool = NULL;
  1367. }
  1368. return pool;
  1369. }
  1370. static bool get_upstream_work(struct work *work, bool lagging)
  1371. {
  1372. struct pool *pool;
  1373. json_t *val;
  1374. bool rc = false;
  1375. CURL *curl;
  1376. curl = curl_easy_init();
  1377. if (unlikely(!curl)) {
  1378. applog(LOG_ERR, "CURL initialisation failed");
  1379. return rc;
  1380. }
  1381. pool = select_pool(lagging);
  1382. if (opt_debug)
  1383. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1384. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1385. false, false, &work->rolltime, pool);
  1386. if (unlikely(!val)) {
  1387. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1388. goto out;
  1389. }
  1390. rc = work_decode(json_object_get(val, "result"), work);
  1391. work->pool = pool;
  1392. total_getworks++;
  1393. pool->getwork_requested++;
  1394. if (work->thr)
  1395. work->thr->cgpu->getworks++;
  1396. json_decref(val);
  1397. out:
  1398. curl_easy_cleanup(curl);
  1399. return rc;
  1400. }
  1401. static struct work *make_work(void)
  1402. {
  1403. struct work *work = calloc(1, sizeof(struct work));
  1404. if (unlikely(!work))
  1405. quit(1, "Failed to calloc work in make_work");
  1406. return work;
  1407. }
  1408. static void free_work(struct work *work)
  1409. {
  1410. free(work);
  1411. }
  1412. static void workio_cmd_free(struct workio_cmd *wc)
  1413. {
  1414. if (!wc)
  1415. return;
  1416. switch (wc->cmd) {
  1417. case WC_SUBMIT_WORK:
  1418. free_work(wc->u.work);
  1419. break;
  1420. default: /* do nothing */
  1421. break;
  1422. }
  1423. memset(wc, 0, sizeof(*wc)); /* poison */
  1424. free(wc);
  1425. }
  1426. static void disable_curses(void)
  1427. {
  1428. if (test_and_clear(&curses_active)) {
  1429. leaveok(logwin, false);
  1430. leaveok(statuswin, false);
  1431. leaveok(mainwin, false);
  1432. nocbreak();
  1433. echo();
  1434. delwin(logwin);
  1435. delwin(statuswin);
  1436. delwin(mainwin);
  1437. endwin();
  1438. refresh();
  1439. #ifdef WIN32
  1440. // Move the cursor to after curses output.
  1441. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1442. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1443. COORD coord;
  1444. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1445. coord.X = 0;
  1446. coord.Y = csbi.dwSize.Y - 1;
  1447. SetConsoleCursorPosition(hout, coord);
  1448. }
  1449. #endif
  1450. }
  1451. }
  1452. void kill_work(void)
  1453. {
  1454. struct workio_cmd *wc;
  1455. struct thr_info *thr;
  1456. unsigned int i;
  1457. disable_curses();
  1458. applog(LOG_INFO, "Received kill message");
  1459. /* Kill the watchdog thread */
  1460. thr = &thr_info[watchdog_thr_id];
  1461. pthread_cancel(*thr->pth);
  1462. /* Stop the mining threads*/
  1463. for (i = 0; i < mining_threads; i++) {
  1464. thr = &thr_info[i];
  1465. if (!thr->pth)
  1466. continue;
  1467. tq_freeze(thr->q);
  1468. /* No need to check if this succeeds or not */
  1469. pthread_cancel(*thr->pth);
  1470. }
  1471. /* Stop the others */
  1472. thr = &thr_info[stage_thr_id];
  1473. pthread_cancel(*thr->pth);
  1474. thr = &thr_info[longpoll_thr_id];
  1475. pthread_cancel(*thr->pth);
  1476. wc = calloc(1, sizeof(*wc));
  1477. if (unlikely(!wc)) {
  1478. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  1479. /* We're just trying to die anyway, so forget graceful */
  1480. exit (1);
  1481. }
  1482. wc->cmd = WC_DIE;
  1483. wc->thr = 0;
  1484. if (opt_debug)
  1485. applog(LOG_DEBUG, "Pushing die request to work thread");
  1486. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1487. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  1488. exit (1);
  1489. }
  1490. }
  1491. static void sighandler(int sig)
  1492. {
  1493. /* Restore signal handlers so we can still quit if kill_work fails */
  1494. sigaction(SIGTERM, &termhandler, NULL);
  1495. sigaction(SIGINT, &inthandler, NULL);
  1496. kill_work();
  1497. }
  1498. static void *get_work_thread(void *userdata)
  1499. {
  1500. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1501. struct work *ret_work;
  1502. int failures = 0;
  1503. pthread_detach(pthread_self());
  1504. ret_work = make_work();
  1505. if (wc->thr)
  1506. ret_work->thr = wc->thr;
  1507. else
  1508. ret_work->thr = NULL;
  1509. /* obtain new work from bitcoin via JSON-RPC */
  1510. while (!get_upstream_work(ret_work, wc->lagging)) {
  1511. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1512. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1513. free_work(ret_work);
  1514. kill_work();
  1515. goto out;
  1516. }
  1517. /* pause, then restart work-request loop */
  1518. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1519. opt_fail_pause);
  1520. sleep(opt_fail_pause);
  1521. }
  1522. if (opt_debug)
  1523. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1524. /* send work to requesting thread */
  1525. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1526. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1527. kill_work();
  1528. free_work(ret_work);
  1529. }
  1530. out:
  1531. workio_cmd_free(wc);
  1532. return NULL;
  1533. }
  1534. static bool workio_get_work(struct workio_cmd *wc)
  1535. {
  1536. pthread_t get_thread;
  1537. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1538. applog(LOG_ERR, "Failed to create get_work_thread");
  1539. return false;
  1540. }
  1541. return true;
  1542. }
  1543. static bool stale_work(struct work *work)
  1544. {
  1545. struct timeval now;
  1546. bool ret = false;
  1547. char *hexstr;
  1548. gettimeofday(&now, NULL);
  1549. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1550. return true;
  1551. /* Only use the primary pool for determination as the work may
  1552. * interleave at times of new blocks */
  1553. if (work->pool != current_pool())
  1554. return ret;
  1555. hexstr = bin2hex(work->data, 36);
  1556. if (unlikely(!hexstr)) {
  1557. applog(LOG_ERR, "submit_work_thread OOM");
  1558. return ret;
  1559. }
  1560. if (strncmp(hexstr, current_block, 36))
  1561. ret = true;
  1562. free(hexstr);
  1563. return ret;
  1564. }
  1565. static void *submit_work_thread(void *userdata)
  1566. {
  1567. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1568. struct work *work = wc->u.work;
  1569. struct pool *pool = work->pool;
  1570. int failures = 0;
  1571. pthread_detach(pthread_self());
  1572. if (!opt_submit_stale && stale_work(work)) {
  1573. applog(LOG_WARNING, "Stale share detected, discarding");
  1574. total_stale++;
  1575. pool->stale_shares++;
  1576. goto out;
  1577. }
  1578. /* submit solution to bitcoin via JSON-RPC */
  1579. while (!submit_upstream_work(work)) {
  1580. if (!opt_submit_stale && stale_work(work)) {
  1581. applog(LOG_WARNING, "Stale share detected, discarding");
  1582. total_stale++;
  1583. pool->stale_shares++;
  1584. break;
  1585. }
  1586. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1587. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1588. kill_work();
  1589. break;
  1590. }
  1591. /* pause, then restart work-request loop */
  1592. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1593. opt_fail_pause);
  1594. sleep(opt_fail_pause);
  1595. }
  1596. out:
  1597. workio_cmd_free(wc);
  1598. return NULL;
  1599. }
  1600. static bool workio_submit_work(struct workio_cmd *wc)
  1601. {
  1602. pthread_t submit_thread;
  1603. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1604. applog(LOG_ERR, "Failed to create submit_work_thread");
  1605. return false;
  1606. }
  1607. return true;
  1608. }
  1609. static void inc_staged(struct pool *pool, int inc, bool lp)
  1610. {
  1611. mutex_lock(&stgd_lock);
  1612. if (lp) {
  1613. lp_staged += inc;
  1614. total_staged += inc;
  1615. } else if (lp_staged)
  1616. --lp_staged;
  1617. else
  1618. total_staged += inc;
  1619. mutex_unlock(&stgd_lock);
  1620. }
  1621. static void dec_staged(int inc)
  1622. {
  1623. mutex_lock(&stgd_lock);
  1624. total_staged -= inc;
  1625. mutex_unlock(&stgd_lock);
  1626. }
  1627. static int requests_staged(void)
  1628. {
  1629. int ret;
  1630. mutex_lock(&stgd_lock);
  1631. ret = total_staged;
  1632. mutex_unlock(&stgd_lock);
  1633. return ret;
  1634. }
  1635. static int real_staged(void)
  1636. {
  1637. int ret;
  1638. mutex_lock(&stgd_lock);
  1639. ret = total_staged - lp_staged;
  1640. mutex_unlock(&stgd_lock);
  1641. return ret;
  1642. }
  1643. /* Find the pool that currently has the highest priority */
  1644. static struct pool *priority_pool(int choice)
  1645. {
  1646. struct pool *ret = NULL;
  1647. int i;
  1648. for (i = 0; i < total_pools; i++) {
  1649. struct pool *pool = pools[i];
  1650. if (pool->prio == choice) {
  1651. ret = pool;
  1652. break;
  1653. }
  1654. }
  1655. if (unlikely(!ret)) {
  1656. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1657. return pools[choice];
  1658. }
  1659. return ret;
  1660. }
  1661. static void restart_longpoll(void);
  1662. static void switch_pools(struct pool *selected)
  1663. {
  1664. struct pool *pool, *last_pool;
  1665. int i, pool_no;
  1666. mutex_lock(&control_lock);
  1667. last_pool = currentpool;
  1668. pool_no = currentpool->pool_no;
  1669. /* Switch selected to pool number 0 and move the rest down */
  1670. if (selected) {
  1671. if (selected->prio != 0) {
  1672. for (i = 0; i < total_pools; i++) {
  1673. pool = pools[i];
  1674. if (pool->prio < selected->prio)
  1675. pool->prio++;
  1676. }
  1677. selected->prio = 0;
  1678. }
  1679. }
  1680. switch (pool_strategy) {
  1681. /* Both of these set to the master pool */
  1682. case POOL_FAILOVER:
  1683. case POOL_LOADBALANCE:
  1684. for (i = 0; i < total_pools; i++) {
  1685. pool = priority_pool(i);
  1686. if (!pool->idle && pool->enabled) {
  1687. pool_no = pool->pool_no;
  1688. break;
  1689. }
  1690. }
  1691. break;
  1692. /* Both of these simply increment and cycle */
  1693. case POOL_ROUNDROBIN:
  1694. case POOL_ROTATE:
  1695. if (selected) {
  1696. pool_no = selected->pool_no;
  1697. break;
  1698. }
  1699. pool_no++;
  1700. if (pool_no >= total_pools)
  1701. pool_no = 0;
  1702. break;
  1703. default:
  1704. break;
  1705. }
  1706. currentpool = pools[pool_no];
  1707. pool = currentpool;
  1708. mutex_unlock(&control_lock);
  1709. if (pool != last_pool) {
  1710. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1711. restart_longpoll();
  1712. }
  1713. /* Reset the queued amount to allow more to be queued for the new pool */
  1714. mutex_lock(&qd_lock);
  1715. total_queued = 0;
  1716. mutex_unlock(&qd_lock);
  1717. inc_staged(pool, 1, true);
  1718. }
  1719. static void set_curblock(char *hexstr, unsigned char *hash)
  1720. {
  1721. unsigned char hash_swap[32];
  1722. char *old_hash = NULL;
  1723. struct timeval tv_now;
  1724. /* Don't free current_hash directly to avoid dereferencing it when
  1725. * we might be accessing its data elsewhere */
  1726. if (current_hash)
  1727. old_hash = current_hash;
  1728. memcpy(current_block, hexstr, 36);
  1729. gettimeofday(&tv_now, NULL);
  1730. get_timestamp(blocktime, &tv_now);
  1731. swap256(hash_swap, hash);
  1732. current_hash = bin2hex(hash_swap, 16);
  1733. if (unlikely(!current_hash))
  1734. quit (1, "set_curblock OOM");
  1735. if (old_hash)
  1736. free(old_hash);
  1737. }
  1738. static void test_work_current(struct work *work)
  1739. {
  1740. char *hexstr;
  1741. /* Only use the primary pool for determination */
  1742. if (work->pool != current_pool() || work->cloned || work->rolls || work->clone)
  1743. return;
  1744. hexstr = bin2hex(work->data, 36);
  1745. if (unlikely(!hexstr)) {
  1746. applog(LOG_ERR, "stage_thread OOM");
  1747. return;
  1748. }
  1749. /* current_block is blanked out on successful longpoll */
  1750. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1751. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1752. block_changed = BLOCK_DETECT;
  1753. new_blocks++;
  1754. if (have_longpoll)
  1755. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1756. else
  1757. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1758. /* As we can't flush the work from here, signal the
  1759. * wakeup thread to restart all the threads */
  1760. work_restart[watchdog_thr_id].restart = 1;
  1761. } else
  1762. block_changed = BLOCK_NONE;
  1763. set_curblock(hexstr, work->data);
  1764. }
  1765. free(hexstr);
  1766. }
  1767. static void *stage_thread(void *userdata)
  1768. {
  1769. struct thr_info *mythr = userdata;
  1770. bool ok = true;
  1771. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1772. while (ok) {
  1773. struct work *work = NULL;
  1774. if (opt_debug)
  1775. applog(LOG_DEBUG, "Popping work to stage thread");
  1776. work = tq_pop(mythr->q, NULL);
  1777. if (unlikely(!work)) {
  1778. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1779. ok = false;
  1780. break;
  1781. }
  1782. test_work_current(work);
  1783. if (opt_debug)
  1784. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1785. if (unlikely(!tq_push(getq, work))) {
  1786. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1787. ok = false;
  1788. break;
  1789. }
  1790. inc_staged(work->pool, 1, false);
  1791. }
  1792. tq_freeze(mythr->q);
  1793. return NULL;
  1794. }
  1795. static char *curses_input(const char *query);
  1796. static int curses_int(const char *query)
  1797. {
  1798. int ret;
  1799. char *cvar;
  1800. cvar = curses_input(query);
  1801. ret = atoi(cvar);
  1802. free(cvar);
  1803. return ret;
  1804. }
  1805. static bool input_pool(bool live);
  1806. static int active_pools(void)
  1807. {
  1808. int ret = 0;
  1809. int i;
  1810. for (i = 0; i < total_pools; i++) {
  1811. if ((pools[i])->enabled)
  1812. ret++;
  1813. }
  1814. return ret;
  1815. }
  1816. static void display_pool_summary(struct pool *pool)
  1817. {
  1818. double efficiency = 0.0;
  1819. mutex_lock(&curses_lock);
  1820. wlog("Pool: %s\n", pool->rpc_url);
  1821. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  1822. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1823. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1824. wlog(" Accepted shares: %d\n", pool->accepted);
  1825. wlog(" Rejected shares: %d\n", pool->rejected);
  1826. if (pool->accepted || pool->rejected)
  1827. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1828. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1829. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1830. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1831. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1832. wlog(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1833. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1834. wrefresh(logwin);
  1835. mutex_unlock(&curses_lock);
  1836. }
  1837. /* We can't remove the memory used for this struct pool because there may
  1838. * still be work referencing it. We just remove it from the pools list */
  1839. static void remove_pool(struct pool *pool)
  1840. {
  1841. int i, last_pool = total_pools - 1;
  1842. struct pool *other;
  1843. /* Boost priority of any lower prio than this one */
  1844. for (i = 0; i < total_pools; i++) {
  1845. other = pools[i];
  1846. if (other->prio > pool->prio)
  1847. other->prio--;
  1848. }
  1849. if (pool->pool_no < last_pool) {
  1850. /* Swap the last pool for this one */
  1851. (pools[last_pool])->pool_no = pool->pool_no;
  1852. pools[pool->pool_no] = pools[last_pool];
  1853. }
  1854. /* Give it an invalid number */
  1855. pool->pool_no = total_pools;
  1856. total_pools--;
  1857. }
  1858. static void display_pools(void)
  1859. {
  1860. struct pool *pool;
  1861. int selected, i;
  1862. char input;
  1863. opt_loginput = true;
  1864. immedok(logwin, true);
  1865. updated:
  1866. clear_logwin();
  1867. for (i = 0; i < total_pools; i++) {
  1868. pool = pools[i];
  1869. if (pool == current_pool())
  1870. wattron(logwin, A_BOLD);
  1871. if (!pool->enabled)
  1872. wattron(logwin, A_DIM);
  1873. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  1874. pool->pool_no,
  1875. pool->enabled? "Enabled" : "Disabled",
  1876. pool->idle? "Dead" : "Alive",
  1877. pool->prio,
  1878. pool->rpc_url, pool->rpc_user);
  1879. wattroff(logwin, A_BOLD | A_DIM);
  1880. }
  1881. retry:
  1882. wlogprint("\nCurrent pool management strategy: %s\n",
  1883. strategies[pool_strategy]);
  1884. if (pool_strategy == POOL_ROTATE)
  1885. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  1886. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  1887. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  1888. wlogprint("Or press any other key to continue\n");
  1889. input = getch();
  1890. if (!strncasecmp(&input, "a", 1)) {
  1891. input_pool(true);
  1892. goto updated;
  1893. } else if (!strncasecmp(&input, "r", 1)) {
  1894. if (total_pools <= 1) {
  1895. wlogprint("Cannot remove last pool");
  1896. goto retry;
  1897. }
  1898. selected = curses_int("Select pool number");
  1899. if (selected < 0 || selected >= total_pools) {
  1900. wlogprint("Invalid selection\n");
  1901. goto retry;
  1902. }
  1903. pool = pools[selected];
  1904. if (pool == current_pool())
  1905. switch_pools(NULL);
  1906. if (pool == current_pool()) {
  1907. wlogprint("Unable to remove pool due to activity\n");
  1908. goto retry;
  1909. }
  1910. pool->enabled = false;
  1911. remove_pool(pool);
  1912. goto updated;
  1913. } else if (!strncasecmp(&input, "s", 1)) {
  1914. selected = curses_int("Select pool number");
  1915. if (selected < 0 || selected >= total_pools) {
  1916. wlogprint("Invalid selection\n");
  1917. goto retry;
  1918. }
  1919. pool = pools[selected];
  1920. pool->enabled = true;
  1921. switch_pools(pool);
  1922. goto updated;
  1923. } else if (!strncasecmp(&input, "d", 1)) {
  1924. if (active_pools() <= 1) {
  1925. wlogprint("Cannot disable last pool");
  1926. goto retry;
  1927. }
  1928. selected = curses_int("Select pool number");
  1929. if (selected < 0 || selected >= total_pools) {
  1930. wlogprint("Invalid selection\n");
  1931. goto retry;
  1932. }
  1933. pool = pools[selected];
  1934. pool->enabled = false;
  1935. if (pool == current_pool())
  1936. switch_pools(NULL);
  1937. goto updated;
  1938. } else if (!strncasecmp(&input, "e", 1)) {
  1939. selected = curses_int("Select pool number");
  1940. if (selected < 0 || selected >= total_pools) {
  1941. wlogprint("Invalid selection\n");
  1942. goto retry;
  1943. }
  1944. pool = pools[selected];
  1945. pool->enabled = true;
  1946. if (pool->prio < current_pool()->prio)
  1947. switch_pools(pool);
  1948. goto updated;
  1949. } else if (!strncasecmp(&input, "c", 1)) {
  1950. for (i = 0; i <= TOP_STRATEGY; i++)
  1951. wlogprint("%d: %s\n", i, strategies[i]);
  1952. selected = curses_int("Select strategy number type");
  1953. if (selected < 0 || selected > TOP_STRATEGY) {
  1954. wlogprint("Invalid selection\n");
  1955. goto retry;
  1956. }
  1957. if (selected == POOL_ROTATE) {
  1958. opt_rotate_period = curses_int("Select interval in minutes");
  1959. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  1960. opt_rotate_period = 0;
  1961. wlogprint("Invalid selection\n");
  1962. goto retry;
  1963. }
  1964. }
  1965. pool_strategy = selected;
  1966. switch_pools(NULL);
  1967. goto updated;
  1968. } else if (!strncasecmp(&input, "i", 1)) {
  1969. selected = curses_int("Select pool number");
  1970. if (selected < 0 || selected >= total_pools) {
  1971. wlogprint("Invalid selection\n");
  1972. goto retry;
  1973. }
  1974. pool = pools[selected];
  1975. display_pool_summary(pool);
  1976. goto retry;
  1977. }
  1978. clear_logwin();
  1979. immedok(logwin, false);
  1980. opt_loginput = false;
  1981. }
  1982. static void display_options(void)
  1983. {
  1984. int selected;
  1985. char input;
  1986. opt_loginput = true;
  1987. immedok(logwin, true);
  1988. retry:
  1989. clear_logwin();
  1990. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  1991. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n[R]PC debug:%s\n[L]og interval:%d\n",
  1992. opt_debug ? "on" : "off",
  1993. want_per_device_stats? "on" : "off",
  1994. opt_quiet ? "on" : "off",
  1995. opt_log_output ? "on" : "off",
  1996. opt_protocol ? "on" : "off",
  1997. opt_log_interval);
  1998. wlogprint("Select an option or any other key to return\n");
  1999. input = getch();
  2000. if (!strncasecmp(&input, "q", 1)) {
  2001. opt_quiet ^= true;
  2002. clear_logwin();
  2003. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2004. } else if (!strncasecmp(&input, "v", 1)) {
  2005. opt_log_output ^= true;
  2006. if (opt_log_output)
  2007. opt_quiet = false;
  2008. clear_logwin();
  2009. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2010. } else if (!strncasecmp(&input, "n", 1)) {
  2011. opt_log_output = false;
  2012. opt_debug = false;
  2013. opt_quiet = false;
  2014. opt_protocol = false;
  2015. want_per_device_stats = false;
  2016. clear_logwin();
  2017. wlogprint("Output mode reset to normal\n");
  2018. } else if (!strncasecmp(&input, "d", 1)) {
  2019. opt_debug ^= true;
  2020. opt_log_output = opt_debug;
  2021. if (opt_debug)
  2022. opt_quiet = false;
  2023. clear_logwin();
  2024. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2025. } else if (!strncasecmp(&input, "p", 1)) {
  2026. want_per_device_stats ^= true;
  2027. opt_log_output = want_per_device_stats;
  2028. clear_logwin();
  2029. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2030. } else if (!strncasecmp(&input, "r", 1)) {
  2031. opt_protocol ^= true;
  2032. if (opt_protocol)
  2033. opt_quiet = false;
  2034. clear_logwin();
  2035. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2036. } else if (!strncasecmp(&input, "c", 1))
  2037. clear_logwin();
  2038. else if (!strncasecmp(&input, "l", 1)) {
  2039. selected = curses_int("Interval in seconds");
  2040. if (selected < 0 || selected > 9999) {
  2041. wlogprint("Invalid selection\n");
  2042. goto retry;
  2043. }
  2044. opt_log_interval = selected;
  2045. clear_logwin();
  2046. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2047. } else if (!strncasecmp(&input, "s", 1)) {
  2048. opt_realquiet = true;
  2049. clear_logwin();
  2050. } else clear_logwin();
  2051. immedok(logwin, false);
  2052. opt_loginput = false;
  2053. }
  2054. static void set_options(void)
  2055. {
  2056. int selected;
  2057. char input;
  2058. opt_loginput = true;
  2059. immedok(logwin, true);
  2060. retry:
  2061. clear_logwin();
  2062. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  2063. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  2064. if (opt_dynamic)
  2065. wlogprint("[I]ntensity: Dynamic\n");
  2066. else
  2067. wlogprint("[I]ntensity: %d\n", scan_intensity);
  2068. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  2069. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  2070. wlogprint("Select an option or any other key to return\n");
  2071. input = getch();
  2072. if (!strncasecmp(&input, "q", 1)) {
  2073. selected = curses_int("Extra work items to queue");
  2074. if (selected < 0 || selected > 9999) {
  2075. wlogprint("Invalid selection\n");
  2076. goto retry;
  2077. }
  2078. opt_queue = selected;
  2079. goto retry;
  2080. } else if (!strncasecmp(&input, "d", 1)) {
  2081. opt_dynamic ^= true;
  2082. goto retry;
  2083. } else if (!strncasecmp(&input, "l", 1)) {
  2084. want_longpoll ^= true;
  2085. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2086. restart_longpoll();
  2087. goto retry;
  2088. } else if (!strncasecmp(&input, "i", 1)) {
  2089. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  2090. if (selected < -10 || selected > 10) {
  2091. wlogprint("Invalid selection\n");
  2092. goto retry;
  2093. }
  2094. opt_dynamic = false;
  2095. scan_intensity = selected;
  2096. goto retry;
  2097. } else if (!strncasecmp(&input, "s", 1)) {
  2098. selected = curses_int("Set scantime in seconds");
  2099. if (selected < 0 || selected > 9999) {
  2100. wlogprint("Invalid selection\n");
  2101. goto retry;
  2102. }
  2103. opt_scantime = selected;
  2104. goto retry;
  2105. } else if (!strncasecmp(&input, "r", 1)) {
  2106. selected = curses_int("Retries before failing (-1 infinite)");
  2107. if (selected < -1 || selected > 9999) {
  2108. wlogprint("Invalid selection\n");
  2109. goto retry;
  2110. }
  2111. opt_retries = selected;
  2112. goto retry;
  2113. } else if (!strncasecmp(&input, "p", 1)) {
  2114. selected = curses_int("Seconds to pause before network retries");
  2115. if (selected < 1 || selected > 9999) {
  2116. wlogprint("Invalid selection\n");
  2117. goto retry;
  2118. }
  2119. opt_fail_pause = selected;
  2120. goto retry;
  2121. }
  2122. clear_logwin();
  2123. immedok(logwin, false);
  2124. opt_loginput = false;
  2125. }
  2126. #ifdef HAVE_OPENCL
  2127. static void reinit_device(struct cgpu_info *cgpu);
  2128. static void manage_gpu(void)
  2129. {
  2130. struct thr_info *thr;
  2131. int selected, gpu, i;
  2132. char checkin[40];
  2133. char input;
  2134. if (!opt_g_threads)
  2135. return;
  2136. opt_loginput = true;
  2137. immedok(logwin, true);
  2138. clear_logwin();
  2139. retry:
  2140. for (gpu = 0; gpu < nDevs; gpu++) {
  2141. struct cgpu_info *cgpu = &gpus[gpu];
  2142. wlog("GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  2143. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  2144. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  2145. cgpu->efficiency, cgpu->utility);
  2146. wlog("Last initialised: %s\n", cgpu->init);
  2147. for (i = 0; i < mining_threads; i++) {
  2148. thr = &thr_info[i];
  2149. if (thr->cgpu != cgpu)
  2150. continue;
  2151. get_datestamp(checkin, &thr->last);
  2152. wlog("Thread %d: %.1f Mh/s %s ", i, thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  2153. switch (cgpu->status) {
  2154. default:
  2155. case LIFE_WELL:
  2156. wlog("ALIVE");
  2157. break;
  2158. case LIFE_SICK:
  2159. wlog("SICK reported in %s", checkin);
  2160. break;
  2161. case LIFE_DEAD:
  2162. wlog("DEAD reported in %s", checkin);
  2163. break;
  2164. }
  2165. wlog("\n");
  2166. }
  2167. wlog("\n");
  2168. }
  2169. wlogprint("[E]nable [D]isable [R]estart GPU\n");
  2170. wlogprint("Or press any other key to continue\n");
  2171. input = getch();
  2172. if (!strncasecmp(&input, "e", 1)) {
  2173. selected = curses_int("Select GPU to enable");
  2174. if (selected < 0 || selected >= nDevs) {
  2175. wlogprint("Invalid selection\n");
  2176. goto retry;
  2177. }
  2178. if (gpu_devices[selected]) {
  2179. wlogprint("Device already enabled\n");
  2180. goto retry;
  2181. }
  2182. gpu_devices[selected] = true;
  2183. for (i = 0; i < gpu_threads; i++) {
  2184. if (dev_from_id(i) != selected)
  2185. continue;
  2186. thr = &thr_info[i];
  2187. if (opt_debug)
  2188. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  2189. tq_push(thr->q, &ping);
  2190. }
  2191. } if (!strncasecmp(&input, "d", 1)) {
  2192. selected = curses_int("Select GPU to disable");
  2193. if (selected < 0 || selected >= nDevs) {
  2194. wlogprint("Invalid selection\n");
  2195. goto retry;
  2196. }
  2197. if (!gpu_devices[selected]) {
  2198. wlogprint("Device already disabled\n");
  2199. goto retry;
  2200. }
  2201. gpu_devices[selected] = false;
  2202. } else if (!strncasecmp(&input, "r", 1)) {
  2203. selected = curses_int("Select GPU to attempt to restart");
  2204. if (selected < 0 || selected >= nDevs) {
  2205. wlogprint("Invalid selection\n");
  2206. goto retry;
  2207. }
  2208. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  2209. reinit_device(&gpus[selected]);
  2210. }
  2211. clear_logwin();
  2212. immedok(logwin, false);
  2213. opt_loginput = false;
  2214. }
  2215. #else
  2216. static void manage_gpu(void)
  2217. {
  2218. }
  2219. #endif
  2220. static void *input_thread(void *userdata)
  2221. {
  2222. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2223. if (!curses_active)
  2224. return NULL;
  2225. while (1) {
  2226. char input;
  2227. input = getch();
  2228. if (!strncasecmp(&input, "q", 1)) {
  2229. kill_work();
  2230. return NULL;
  2231. } else if (!strncasecmp(&input, "d", 1))
  2232. display_options();
  2233. else if (!strncasecmp(&input, "p", 1))
  2234. display_pools();
  2235. else if (!strncasecmp(&input, "s", 1))
  2236. set_options();
  2237. else if (!strncasecmp(&input, "g", 1))
  2238. manage_gpu();
  2239. if (opt_realquiet) {
  2240. disable_curses();
  2241. break;
  2242. }
  2243. }
  2244. return NULL;
  2245. }
  2246. static void *workio_thread(void *userdata)
  2247. {
  2248. struct thr_info *mythr = userdata;
  2249. bool ok = true;
  2250. while (ok) {
  2251. struct workio_cmd *wc;
  2252. if (opt_debug)
  2253. applog(LOG_DEBUG, "Popping work to work thread");
  2254. /* wait for workio_cmd sent to us, on our queue */
  2255. wc = tq_pop(mythr->q, NULL);
  2256. if (unlikely(!wc)) {
  2257. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2258. ok = false;
  2259. break;
  2260. }
  2261. /* process workio_cmd */
  2262. switch (wc->cmd) {
  2263. case WC_GET_WORK:
  2264. ok = workio_get_work(wc);
  2265. break;
  2266. case WC_SUBMIT_WORK:
  2267. ok = workio_submit_work(wc);
  2268. break;
  2269. case WC_DIE:
  2270. default:
  2271. ok = false;
  2272. break;
  2273. }
  2274. }
  2275. tq_freeze(mythr->q);
  2276. return NULL;
  2277. }
  2278. static void thread_reportin(struct thr_info *thr)
  2279. {
  2280. gettimeofday(&thr->last, NULL);
  2281. thr->cgpu->status = LIFE_WELL;
  2282. thr->getwork = false;
  2283. }
  2284. static inline void thread_reportout(struct thr_info *thr)
  2285. {
  2286. thr->getwork = true;
  2287. }
  2288. static void hashmeter(int thr_id, struct timeval *diff,
  2289. unsigned long hashes_done)
  2290. {
  2291. struct timeval temp_tv_end, total_diff;
  2292. double secs;
  2293. double local_secs;
  2294. double utility, efficiency = 0.0;
  2295. static double local_mhashes_done = 0;
  2296. static double rolling = 0;
  2297. double local_mhashes = (double)hashes_done / 1000000.0;
  2298. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2299. bool showlog = false;
  2300. /* Update the last time this thread reported in */
  2301. if (thr_id >= 0)
  2302. gettimeofday(&thr_info[thr_id].last, NULL);
  2303. /* Don't bother calculating anything if we're not displaying it */
  2304. if (opt_realquiet || !opt_log_interval)
  2305. return;
  2306. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2307. /* So we can call hashmeter from a non worker thread */
  2308. if (thr_id >= 0) {
  2309. struct thr_info *thr = &thr_info[thr_id];
  2310. double thread_rolling = 0.0;
  2311. int i;
  2312. if (opt_debug)
  2313. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2314. thr_id, hashes_done, hashes_done / secs);
  2315. /* Rolling average for each thread and each device */
  2316. decay_time(&thr->rolling, local_mhashes / secs);
  2317. for (i = 0; i < mining_threads; i++) {
  2318. struct thr_info *th = &thr_info[i];
  2319. if (th->cgpu == cgpu)
  2320. thread_rolling += th->rolling;
  2321. }
  2322. decay_time(&cgpu->rolling, thread_rolling);
  2323. cgpu->total_mhashes += local_mhashes;
  2324. // If needed, output detailed, per-device stats
  2325. if (want_per_device_stats) {
  2326. struct timeval now;
  2327. struct timeval elapsed;
  2328. gettimeofday(&now, NULL);
  2329. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2330. if (opt_log_interval <= elapsed.tv_sec) {
  2331. thr->cgpu->last_message_tv = now;
  2332. sprintf(
  2333. statusline,
  2334. "[%sPU%d (%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2335. thr->cgpu->is_gpu ? "G" : "C",
  2336. thr->cgpu->cpu_gpu,
  2337. opt_log_interval,
  2338. thr->cgpu->rolling,
  2339. thr->cgpu->total_mhashes / total_secs,
  2340. thr->cgpu->getworks,
  2341. thr->cgpu->accepted,
  2342. thr->cgpu->rejected,
  2343. thr->cgpu->hw_errors,
  2344. thr->cgpu->efficiency,
  2345. thr->cgpu->utility
  2346. );
  2347. if (!curses_active) {
  2348. printf("%s \r", statusline);
  2349. fflush(stdout);
  2350. } else
  2351. applog(LOG_INFO, "%s", statusline);
  2352. }
  2353. }
  2354. }
  2355. /* Totals are updated by all threads so can race without locking */
  2356. mutex_lock(&hash_lock);
  2357. gettimeofday(&temp_tv_end, NULL);
  2358. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2359. total_mhashes_done += local_mhashes;
  2360. local_mhashes_done += local_mhashes;
  2361. if (total_diff.tv_sec < opt_log_interval)
  2362. /* Only update the total every opt_log_interval seconds */
  2363. goto out_unlock;
  2364. showlog = true;
  2365. gettimeofday(&total_tv_end, NULL);
  2366. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2367. decay_time(&rolling, local_mhashes_done / local_secs);
  2368. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2369. total_secs = (double)total_diff.tv_sec +
  2370. ((double)total_diff.tv_usec / 1000000.0);
  2371. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2372. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2373. sprintf(statusline, "[%s(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2374. want_per_device_stats ? "ALL " : "",
  2375. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2376. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2377. local_mhashes_done = 0;
  2378. out_unlock:
  2379. mutex_unlock(&hash_lock);
  2380. if (showlog) {
  2381. if (!curses_active) {
  2382. printf("%s \r", statusline);
  2383. fflush(stdout);
  2384. } else
  2385. applog(LOG_INFO, "%s", statusline);
  2386. }
  2387. }
  2388. /* This is overkill, but at least we'll know accurately how much work is
  2389. * queued to prevent ever being left without work */
  2390. static void inc_queued(void)
  2391. {
  2392. mutex_lock(&qd_lock);
  2393. total_queued++;
  2394. mutex_unlock(&qd_lock);
  2395. }
  2396. static void dec_queued(void)
  2397. {
  2398. mutex_lock(&qd_lock);
  2399. if (total_queued > 0)
  2400. total_queued--;
  2401. mutex_unlock(&qd_lock);
  2402. dec_staged(1);
  2403. }
  2404. static int requests_queued(void)
  2405. {
  2406. int ret;
  2407. mutex_lock(&qd_lock);
  2408. ret = total_queued;
  2409. mutex_unlock(&qd_lock);
  2410. return ret;
  2411. }
  2412. static bool pool_active(struct pool *pool, bool pinging)
  2413. {
  2414. bool ret = false;
  2415. json_t *val;
  2416. CURL *curl;
  2417. bool rolltime;
  2418. curl = curl_easy_init();
  2419. if (unlikely(!curl)) {
  2420. applog(LOG_ERR, "CURL initialisation failed");
  2421. return false;
  2422. }
  2423. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2424. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2425. true, false, &rolltime, pool);
  2426. if (val) {
  2427. struct work *work = make_work();
  2428. bool rc;
  2429. rc = work_decode(json_object_get(val, "result"), work);
  2430. if (rc) {
  2431. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2432. pool->pool_no, pool->rpc_url);
  2433. work->pool = pool;
  2434. work->rolltime = rolltime;
  2435. if (opt_debug)
  2436. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2437. tq_push(thr_info[stage_thr_id].q, work);
  2438. total_getworks++;
  2439. pool->getwork_requested++;
  2440. inc_queued();
  2441. ret = true;
  2442. gettimeofday(&pool->tv_idle, NULL);
  2443. } else {
  2444. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2445. pool->pool_no, pool->rpc_url);
  2446. free_work(work);
  2447. }
  2448. json_decref(val);
  2449. } else {
  2450. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2451. pool->pool_no, pool->rpc_url);
  2452. if (!pinging)
  2453. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  2454. }
  2455. curl_easy_cleanup(curl);
  2456. return ret;
  2457. }
  2458. static void pool_died(struct pool *pool)
  2459. {
  2460. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2461. gettimeofday(&pool->tv_idle, NULL);
  2462. switch_pools(NULL);
  2463. }
  2464. static void pool_resus(struct pool *pool)
  2465. {
  2466. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  2467. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  2468. switch_pools(NULL);
  2469. }
  2470. static bool queue_request(struct thr_info *thr, bool needed)
  2471. {
  2472. int maxq = opt_queue + mining_threads;
  2473. struct workio_cmd *wc;
  2474. int rq, rs;
  2475. rq = requests_queued();
  2476. rs = real_staged();
  2477. /* If we've been generating lots of local work we may already have
  2478. * enough in the queue */
  2479. if (rq >= maxq || rs >= maxq)
  2480. return true;
  2481. /* fill out work request message */
  2482. wc = calloc(1, sizeof(*wc));
  2483. if (unlikely(!wc)) {
  2484. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2485. return false;
  2486. }
  2487. wc->cmd = WC_GET_WORK;
  2488. if (thr)
  2489. wc->thr = thr;
  2490. else
  2491. wc->thr = NULL;
  2492. /* If we're queueing work faster than we can stage it, consider the
  2493. * system lagging and allow work to be gathered from another pool if
  2494. * possible */
  2495. if (!rs && rq && needed)
  2496. wc->lagging = true;
  2497. if (opt_debug)
  2498. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2499. /* send work request to workio thread */
  2500. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2501. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2502. workio_cmd_free(wc);
  2503. return false;
  2504. }
  2505. inc_queued();
  2506. return true;
  2507. }
  2508. static void discard_work(struct work *work)
  2509. {
  2510. if (!work->clone && !work->rolls && !work->mined) {
  2511. if (work->pool)
  2512. work->pool->discarded_work++;
  2513. total_discarded++;
  2514. if (opt_debug)
  2515. applog(LOG_DEBUG, "Discarded work");
  2516. } else if (opt_debug)
  2517. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2518. free_work(work);
  2519. }
  2520. static void discard_staged(void)
  2521. {
  2522. struct timespec abstime = {};
  2523. struct timeval now;
  2524. struct work *work_heap;
  2525. /* Just in case we fell in a hole and missed a queue filling */
  2526. if (unlikely(!requests_staged()))
  2527. return;
  2528. gettimeofday(&now, NULL);
  2529. abstime.tv_sec = now.tv_sec + 60;
  2530. if (opt_debug)
  2531. applog(LOG_DEBUG, "Popping work to discard staged");
  2532. work_heap = tq_pop(getq, &abstime);
  2533. if (unlikely(!work_heap))
  2534. return;
  2535. discard_work(work_heap);
  2536. dec_queued();
  2537. }
  2538. static void flush_requests(void)
  2539. {
  2540. struct pool *pool = current_pool();
  2541. int i, stale;
  2542. /* We should have one fresh work item staged from the block change. */
  2543. stale = requests_staged() - 1;
  2544. /* Temporarily increase the staged count so that get_work thinks there
  2545. * is work available instead of making threads reuse existing work */
  2546. inc_staged(pool, mining_threads, true);
  2547. for (i = 0; i < stale; i++) {
  2548. /* Queue a whole batch of new requests */
  2549. if (unlikely(!queue_request(NULL, true))) {
  2550. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  2551. kill_work();
  2552. break;
  2553. }
  2554. /* Pop off the old requests. Cancelling the requests would be better
  2555. * but is tricky */
  2556. discard_staged();
  2557. }
  2558. }
  2559. static inline bool should_roll(struct work *work)
  2560. {
  2561. int rs;
  2562. rs = real_staged();
  2563. if (rs >= opt_queue + mining_threads)
  2564. return false;
  2565. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  2566. return true;
  2567. return false;
  2568. }
  2569. static inline bool can_roll(struct work *work)
  2570. {
  2571. return (work->pool && !stale_work(work) && work->rolltime &&
  2572. work->rolls < 11 && !work->clone);
  2573. }
  2574. static void roll_work(struct work *work)
  2575. {
  2576. uint32_t *work_ntime;
  2577. uint32_t ntime;
  2578. work_ntime = (uint32_t *)(work->data + 68);
  2579. ntime = be32toh(*work_ntime);
  2580. ntime++;
  2581. *work_ntime = htobe32(ntime);
  2582. local_work++;
  2583. work->rolls++;
  2584. work->blk.nonce = 0;
  2585. if (opt_debug)
  2586. applog(LOG_DEBUG, "Successfully rolled work");
  2587. }
  2588. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  2589. * giving it to will not finish scanning it. We keep the master copy to be
  2590. * recycled more rapidly and discard the clone to avoid repeating work */
  2591. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  2592. {
  2593. uint64_t hash_inc;
  2594. if (work->clone)
  2595. return false;
  2596. hash_inc = MAXTHREADS / hash_div * 2;
  2597. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  2598. /* Okay we can divide it up */
  2599. work->blk.nonce += hash_inc;
  2600. work->cloned = true;
  2601. local_work++;
  2602. if (opt_debug)
  2603. applog(LOG_DEBUG, "Successfully divided work");
  2604. return true;
  2605. } else if (can_roll(work) && should_roll(work)) {
  2606. roll_work(work);
  2607. return true;
  2608. }
  2609. return false;
  2610. }
  2611. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2612. const int thr_id, uint32_t hash_div)
  2613. {
  2614. struct timespec abstime = {};
  2615. struct timeval now;
  2616. struct work *work_heap;
  2617. struct pool *pool;
  2618. bool ret = false;
  2619. int failures = 0;
  2620. /* Tell the watchdog thread this thread is waiting on getwork and
  2621. * should not be restarted */
  2622. thread_reportout(thr);
  2623. retry:
  2624. pool = current_pool();
  2625. if (unlikely(!requested && !queue_request(thr, true))) {
  2626. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2627. goto out;
  2628. }
  2629. requested = false;
  2630. if (!requests_staged() && can_roll(work)) {
  2631. /* Only print this message once each time we shift to localgen */
  2632. if (!pool_tset(pool, &pool->idle)) {
  2633. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  2634. pool->pool_no);
  2635. pool->localgen_occasions++;
  2636. total_lo++;
  2637. gettimeofday(&pool->tv_idle, NULL);
  2638. } else {
  2639. struct timeval tv_now, diff;
  2640. gettimeofday(&tv_now, NULL);
  2641. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  2642. /* Attempt to switch pools if this one has been unresponsive for >half
  2643. * a block's duration */
  2644. if (diff.tv_sec > 300) {
  2645. pool_died(pool);
  2646. goto retry;
  2647. }
  2648. }
  2649. roll_work(work);
  2650. ret = true;
  2651. goto out;
  2652. }
  2653. gettimeofday(&now, NULL);
  2654. abstime.tv_sec = now.tv_sec + 60;
  2655. if (opt_debug)
  2656. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2657. /* wait for 1st response, or get cached response */
  2658. work_heap = tq_pop(getq, &abstime);
  2659. if (unlikely(!work_heap)) {
  2660. /* Attempt to switch pools if this one has mandatory work that
  2661. * has timed out or does not support rolltime */
  2662. pool->localgen_occasions++;
  2663. total_lo++;
  2664. pool_died(pool);
  2665. goto retry;
  2666. }
  2667. if (stale_work(work_heap)) {
  2668. dec_queued();
  2669. discard_work(work_heap);
  2670. goto retry;
  2671. }
  2672. pool = work_heap->pool;
  2673. /* If we make it here we have succeeded in getting fresh work */
  2674. if (pool_tclear(pool, &pool->idle))
  2675. pool_resus(pool);
  2676. memcpy(work, work_heap, sizeof(*work));
  2677. /* Copy the res nonce back so we know to start at a higher baseline
  2678. * should we divide the same work up again. Make the work we're
  2679. * handing out be clone */
  2680. if (divide_work(&now, work_heap, hash_div)) {
  2681. if (opt_debug)
  2682. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2683. tq_push_head(getq, work_heap);
  2684. work->clone = true;
  2685. } else {
  2686. dec_queued();
  2687. free_work(work_heap);
  2688. }
  2689. ret = true;
  2690. out:
  2691. if (unlikely(ret == false)) {
  2692. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2693. applog(LOG_ERR, "Failed %d times to get_work");
  2694. return ret;
  2695. }
  2696. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  2697. sleep(opt_fail_pause);
  2698. goto retry;
  2699. }
  2700. work->thr_id = thr_id;
  2701. thread_reportin(thr);
  2702. if (ret)
  2703. work->mined = true;
  2704. return ret;
  2705. }
  2706. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2707. {
  2708. struct workio_cmd *wc;
  2709. /* fill out work request message */
  2710. wc = calloc(1, sizeof(*wc));
  2711. if (unlikely(!wc)) {
  2712. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2713. return false;
  2714. }
  2715. wc->u.work = make_work();
  2716. wc->cmd = WC_SUBMIT_WORK;
  2717. wc->thr = thr;
  2718. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2719. if (opt_debug)
  2720. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2721. /* send solution to workio thread */
  2722. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2723. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2724. goto err_out;
  2725. }
  2726. return true;
  2727. err_out:
  2728. workio_cmd_free(wc);
  2729. return false;
  2730. }
  2731. struct swa {
  2732. struct thr_info *thr;
  2733. const struct work *work_in;
  2734. };
  2735. static void *swasync_thread(void *userdata)
  2736. {
  2737. struct swa *swa = (struct swa *)userdata;
  2738. /* Return value ignored */
  2739. submit_work_sync(swa->thr, swa->work_in);
  2740. free(swa);
  2741. return NULL;
  2742. }
  2743. static bool submit_work_async(struct thr_info *thr, const struct work *work_in)
  2744. {
  2745. pthread_t sw_thread;
  2746. struct swa *swa;
  2747. swa = malloc(sizeof(struct swa));
  2748. if (unlikely(!swa)) {
  2749. applog(LOG_ERR, "Failed to malloc swa in submit_work_async");
  2750. return false;
  2751. }
  2752. swa->thr = thr;
  2753. swa->work_in = work_in;
  2754. if (unlikely(pthread_create(&sw_thread, NULL, swasync_thread, (void *)swa))) {
  2755. applog(LOG_ERR, "Failed to create swasync_thread");
  2756. return false;
  2757. }
  2758. return true;
  2759. }
  2760. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2761. {
  2762. work->data[64+12+0] = (nonce>>0) & 0xff;
  2763. work->data[64+12+1] = (nonce>>8) & 0xff;
  2764. work->data[64+12+2] = (nonce>>16) & 0xff;
  2765. work->data[64+12+3] = (nonce>>24) & 0xff;
  2766. /* Do one last check before attempting to submit the work */
  2767. if (!fulltest(work->data + 64, work->target))
  2768. return true;
  2769. return submit_work_sync(thr, work);
  2770. }
  2771. static void *miner_thread(void *userdata)
  2772. {
  2773. struct work *work = make_work();
  2774. struct thr_info *mythr = userdata;
  2775. const int thr_id = mythr->id;
  2776. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  2777. unsigned long hashes_done = max_nonce;
  2778. bool needs_work = true;
  2779. /* Try to cycle approximately 5 times before each log update */
  2780. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2781. int request_interval;
  2782. bool requested = false;
  2783. uint32_t hash_div = 1;
  2784. double hash_divfloat = 1.0;
  2785. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2786. /* Request the next work item just before the end of the scantime. We
  2787. * don't want the work lying around too long since the CPU will always
  2788. * spend the full scantime */
  2789. request_interval = opt_scantime - 5;
  2790. if (request_interval < 1)
  2791. request_interval = 1;
  2792. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  2793. * and if that fails, then SCHED_BATCH. No need for this to be an
  2794. * error if it fails */
  2795. setpriority(PRIO_PROCESS, 0, 19);
  2796. drop_policy();
  2797. /* Cpu affinity only makes sense if the number of threads is a multiple
  2798. * of the number of CPUs */
  2799. if (!(opt_n_threads % num_processors))
  2800. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  2801. /* Invalidate pool so it fails can_roll() test */
  2802. work->pool = NULL;
  2803. while (1) {
  2804. struct timeval tv_workstart, tv_start, tv_end, diff;
  2805. uint64_t max64;
  2806. bool rc;
  2807. if (needs_work) {
  2808. gettimeofday(&tv_workstart, NULL);
  2809. /* obtain new work from internal workio thread */
  2810. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2811. applog(LOG_ERR, "work retrieval failed, exiting "
  2812. "mining thread %d", thr_id);
  2813. goto out;
  2814. }
  2815. needs_work = requested = false;
  2816. total_hashes = 0;
  2817. max_nonce = work->blk.nonce + hashes_done;
  2818. }
  2819. hashes_done = 0;
  2820. gettimeofday(&tv_start, NULL);
  2821. /* scan nonces for a proof-of-work hash */
  2822. switch (opt_algo) {
  2823. case ALGO_C:
  2824. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  2825. work->hash1, work->hash, work->target,
  2826. max_nonce, &hashes_done,
  2827. work->blk.nonce);
  2828. break;
  2829. #ifdef WANT_X8664_SSE2
  2830. case ALGO_SSE2_64: {
  2831. unsigned int rc5 =
  2832. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  2833. work->hash1, work->hash,
  2834. work->target,
  2835. max_nonce, &hashes_done,
  2836. work->blk.nonce);
  2837. rc = (rc5 == -1) ? false : true;
  2838. }
  2839. break;
  2840. #endif
  2841. #ifdef WANT_X8664_SSE4
  2842. case ALGO_SSE4_64: {
  2843. unsigned int rc5 =
  2844. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  2845. work->hash1, work->hash,
  2846. work->target,
  2847. max_nonce, &hashes_done,
  2848. work->blk.nonce);
  2849. rc = (rc5 == -1) ? false : true;
  2850. }
  2851. break;
  2852. #endif
  2853. #ifdef WANT_SSE2_4WAY
  2854. case ALGO_4WAY: {
  2855. unsigned int rc4 =
  2856. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  2857. work->hash1, work->hash,
  2858. work->target,
  2859. max_nonce, &hashes_done,
  2860. work->blk.nonce);
  2861. rc = (rc4 == -1) ? false : true;
  2862. }
  2863. break;
  2864. #endif
  2865. #ifdef WANT_VIA_PADLOCK
  2866. case ALGO_VIA:
  2867. rc = scanhash_via(thr_id, work->data, work->target,
  2868. max_nonce, &hashes_done,
  2869. work->blk.nonce);
  2870. break;
  2871. #endif
  2872. case ALGO_CRYPTOPP:
  2873. rc = scanhash_cryptopp(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. #ifdef WANT_CRYPTOPP_ASM32
  2879. case ALGO_CRYPTOPP_ASM32:
  2880. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  2881. work->hash1, work->hash, work->target,
  2882. max_nonce, &hashes_done,
  2883. work->blk.nonce);
  2884. break;
  2885. #endif
  2886. default:
  2887. /* should never happen */
  2888. goto out;
  2889. }
  2890. /* record scanhash elapsed time */
  2891. gettimeofday(&tv_end, NULL);
  2892. timeval_subtract(&diff, &tv_end, &tv_start);
  2893. hashes_done -= work->blk.nonce;
  2894. hashmeter(thr_id, &diff, hashes_done);
  2895. total_hashes += hashes_done;
  2896. work->blk.nonce += hashes_done;
  2897. /* adjust max_nonce to meet target cycle time */
  2898. if (diff.tv_usec > 500000)
  2899. diff.tv_sec++;
  2900. if (diff.tv_sec && diff.tv_sec != cycle) {
  2901. max64 = work->blk.nonce +
  2902. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  2903. } else if (!diff.tv_sec)
  2904. max64 = work->blk.nonce + (hashes_done * 2);
  2905. else
  2906. max64 = work->blk.nonce + hashes_done;
  2907. if (max64 > 0xfffffffaULL)
  2908. max64 = 0xfffffffaULL;
  2909. max_nonce = max64;
  2910. /* if nonce found, submit work */
  2911. if (unlikely(rc)) {
  2912. if (opt_debug)
  2913. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  2914. if (unlikely(!submit_work_async(mythr, work))) {
  2915. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  2916. break;
  2917. }
  2918. work->blk.nonce += 4;
  2919. }
  2920. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2921. if (!requested && (diff.tv_sec >= request_interval)) {
  2922. thread_reportout(mythr);
  2923. if (unlikely(!queue_request(mythr, false))) {
  2924. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2925. goto out;
  2926. }
  2927. thread_reportin(mythr);
  2928. requested = true;
  2929. }
  2930. if (diff.tv_sec > opt_scantime) {
  2931. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  2932. hash_div = hash_divfloat;
  2933. needs_work = true;
  2934. } else if (work_restart[thr_id].restart || stale_work(work) ||
  2935. work->blk.nonce >= MAXTHREADS - hashes_done)
  2936. needs_work = true;
  2937. }
  2938. out:
  2939. thread_reportin(mythr);
  2940. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2941. tq_freeze(mythr->q);
  2942. return NULL;
  2943. }
  2944. enum {
  2945. STAT_SLEEP_INTERVAL = 1,
  2946. STAT_CTR_INTERVAL = 10000000,
  2947. FAILURE_INTERVAL = 30,
  2948. };
  2949. #ifdef HAVE_OPENCL
  2950. static _clState *clStates[16];
  2951. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  2952. {
  2953. cl_kernel *kernel = &clState->kernel;
  2954. cl_int status = 0;
  2955. int num = 0;
  2956. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2957. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2958. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2959. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2960. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2961. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2962. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2963. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2964. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2965. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2966. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  2967. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2968. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2969. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2970. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2971. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  2972. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  2973. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  2974. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  2975. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  2976. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  2977. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  2978. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  2979. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2980. (void *)&clState->outputBuffer);
  2981. return status;
  2982. }
  2983. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  2984. {
  2985. cl_uint vwidth = clState->preferred_vwidth;
  2986. cl_kernel *kernel = &clState->kernel;
  2987. cl_int status = 0;
  2988. int i, num = 0;
  2989. uint *nonces;
  2990. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2991. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2992. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2993. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2994. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2995. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2996. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2997. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2998. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2999. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3000. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3001. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3002. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3003. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3004. nonces = alloca(sizeof(uint) * vwidth);
  3005. for (i = 0; i < vwidth; i++)
  3006. nonces[i] = blk->nonce + i;
  3007. status |= clSetKernelArg(*kernel, num++, vwidth * sizeof(uint), (void *)nonces);
  3008. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  3009. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  3010. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4_2);
  3011. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal0);
  3012. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW18);
  3013. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW19);
  3014. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW31);
  3015. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW32);
  3016. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3017. (void *)&clState->outputBuffer);
  3018. return status;
  3019. }
  3020. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  3021. unsigned int *hashes, size_t *globalThreads,
  3022. unsigned int minthreads)
  3023. {
  3024. *threads = 1 << (15 + scan_intensity);
  3025. if (*threads < minthreads)
  3026. *threads = minthreads;
  3027. *globalThreads = *threads;
  3028. *hashes = *threads * vectors;
  3029. }
  3030. static void *gpuminer_thread(void *userdata)
  3031. {
  3032. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  3033. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3034. struct timeval tv_start, tv_end, diff, tv_workstart;
  3035. struct thr_info *mythr = userdata;
  3036. const int thr_id = mythr->id;
  3037. uint32_t *res, *blank_res;
  3038. double gpu_ms_average = 7;
  3039. int gpu = dev_from_id(thr_id);
  3040. size_t globalThreads[1];
  3041. size_t localThreads[1];
  3042. cl_int status;
  3043. _clState *clState = clStates[thr_id];
  3044. const cl_kernel *kernel = &clState->kernel;
  3045. struct work *work = make_work();
  3046. unsigned int threads;
  3047. unsigned const int vectors = clState->preferred_vwidth;
  3048. unsigned int hashes;
  3049. unsigned int hashes_done = 0;
  3050. /* Request the next work item at 2/3 of the scantime */
  3051. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3052. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3053. bool requested = false;
  3054. uint32_t total_hashes = 0, hash_div = 1;
  3055. switch (chosen_kernel) {
  3056. case KL_POCLBM:
  3057. queue_kernel_parameters = &queue_poclbm_kernel;
  3058. break;
  3059. case KL_PHATK:
  3060. default:
  3061. queue_kernel_parameters = &queue_phatk_kernel;
  3062. break;
  3063. }
  3064. if (opt_dynamic) {
  3065. /* Minimise impact on desktop if we want dynamic mode */
  3066. setpriority(PRIO_PROCESS, 0, 19);
  3067. drop_policy();
  3068. }
  3069. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3070. res = calloc(BUFFERSIZE, 1);
  3071. blank_res = calloc(BUFFERSIZE, 1);
  3072. if (!res || !blank_res) {
  3073. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  3074. goto out;
  3075. }
  3076. gettimeofday(&tv_start, NULL);
  3077. localThreads[0] = clState->work_size;
  3078. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  3079. localThreads[0]);
  3080. diff.tv_sec = 0;
  3081. gettimeofday(&tv_end, NULL);
  3082. work->pool = NULL;
  3083. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  3084. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3085. if (unlikely(status != CL_SUCCESS))
  3086. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3087. mythr->cgpu->status = LIFE_WELL;
  3088. if (opt_debug)
  3089. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  3090. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3091. gettimeofday(&tv_workstart, NULL);
  3092. /* obtain new work from internal workio thread */
  3093. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3094. applog(LOG_ERR, "work retrieval failed, exiting "
  3095. "gpu mining thread %d", thr_id);
  3096. goto out;
  3097. }
  3098. requested = false;
  3099. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3100. work->blk.nonce = 0;
  3101. while (1) {
  3102. struct timeval tv_gpustart, tv_gpuend;
  3103. suseconds_t gpu_us;
  3104. gettimeofday(&tv_gpustart, NULL);
  3105. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  3106. /* This finish flushes the readbuffer set with CL_FALSE later */
  3107. clFinish(clState->commandQueue);
  3108. gettimeofday(&tv_gpuend, NULL);
  3109. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  3110. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  3111. decay_time(&gpu_ms_average, gpu_us / 1000);
  3112. if (opt_dynamic) {
  3113. /* Try to not let the GPU be out for longer than 6ms, but
  3114. * increase intensity when the system is idle, unless
  3115. * dynamic is disabled. */
  3116. if (gpu_ms_average > 7) {
  3117. if (scan_intensity > -10)
  3118. scan_intensity--;
  3119. } else if (gpu_ms_average < 3) {
  3120. if (scan_intensity < 10)
  3121. scan_intensity++;
  3122. }
  3123. }
  3124. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  3125. if (diff.tv_sec > opt_scantime ||
  3126. work->blk.nonce >= MAXTHREADS - hashes ||
  3127. work_restart[thr_id].restart ||
  3128. stale_work(work)) {
  3129. /* Ignore any reads since we're getting new work and queue a clean buffer */
  3130. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3131. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3132. if (unlikely(status != CL_SUCCESS))
  3133. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3134. memset(res, 0, BUFFERSIZE);
  3135. gettimeofday(&tv_workstart, NULL);
  3136. if (opt_debug)
  3137. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  3138. /* obtain new work from internal workio thread */
  3139. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3140. applog(LOG_ERR, "work retrieval failed, exiting "
  3141. "gpu mining thread %d", thr_id);
  3142. goto out;
  3143. }
  3144. requested = false;
  3145. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3146. work_restart[thr_id].restart = 0;
  3147. /* Flushes the writebuffer set with CL_FALSE above */
  3148. clFinish(clState->commandQueue);
  3149. }
  3150. status = queue_kernel_parameters(clState, &work->blk);
  3151. if (unlikely(status != CL_SUCCESS))
  3152. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  3153. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  3154. if (res[FOUND]) {
  3155. /* Clear the buffer again */
  3156. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3157. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3158. if (unlikely(status != CL_SUCCESS))
  3159. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3160. if (opt_debug)
  3161. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  3162. postcalc_hash_async(mythr, work, res);
  3163. memset(res, 0, BUFFERSIZE);
  3164. clFinish(clState->commandQueue);
  3165. }
  3166. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  3167. globalThreads, localThreads, 0, NULL, NULL);
  3168. if (unlikely(status != CL_SUCCESS))
  3169. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  3170. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3171. BUFFERSIZE, res, 0, NULL, NULL);
  3172. if (unlikely(status != CL_SUCCESS))
  3173. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  3174. gettimeofday(&tv_end, NULL);
  3175. timeval_subtract(&diff, &tv_end, &tv_start);
  3176. hashes_done += hashes;
  3177. total_hashes += hashes;
  3178. work->blk.nonce += hashes;
  3179. if (diff.tv_sec >= cycle) {
  3180. hashmeter(thr_id, &diff, hashes_done);
  3181. gettimeofday(&tv_start, NULL);
  3182. hashes_done = 0;
  3183. }
  3184. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3185. if (!requested) {
  3186. #if 0
  3187. if (diff.tv_sec > request_interval)
  3188. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  3189. #endif
  3190. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3191. thread_reportout(mythr);
  3192. if (unlikely(!queue_request(mythr, false))) {
  3193. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  3194. goto out;
  3195. }
  3196. thread_reportin(mythr);
  3197. requested = true;
  3198. }
  3199. }
  3200. if (unlikely(!gpu_devices[gpu])) {
  3201. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3202. mythr->rolling = mythr->cgpu->rolling = 0;
  3203. if (opt_debug)
  3204. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  3205. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3206. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3207. }
  3208. }
  3209. out:
  3210. clReleaseCommandQueue(clState->commandQueue);
  3211. clReleaseKernel(clState->kernel);
  3212. clReleaseProgram(clState->program);
  3213. clReleaseContext(clState->context);
  3214. thread_reportin(mythr);
  3215. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3216. tq_freeze(mythr->q);
  3217. return NULL;
  3218. }
  3219. #endif /* HAVE_OPENCL */
  3220. static void restart_threads(void)
  3221. {
  3222. int i;
  3223. if (block_changed == BLOCK_DETECT)
  3224. block_changed = BLOCK_NONE;
  3225. /* Discard old queued requests and get new ones */
  3226. flush_requests();
  3227. for (i = 0; i < mining_threads; i++)
  3228. work_restart[i].restart = 1;
  3229. }
  3230. /* Stage another work item from the work returned in a longpoll */
  3231. static void convert_to_work(json_t *val, bool rolltime)
  3232. {
  3233. struct work *work;
  3234. bool rc;
  3235. work = make_work();
  3236. rc= work_decode(json_object_get(val, "result"), work);
  3237. if (unlikely(!rc)) {
  3238. applog(LOG_ERR, "Could not convert longpoll data to work");
  3239. return;
  3240. }
  3241. work->pool = current_pool();
  3242. work->rolltime = rolltime;
  3243. if (opt_debug)
  3244. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3245. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  3246. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  3247. else if (opt_debug)
  3248. applog(LOG_DEBUG, "Converted longpoll data to work");
  3249. }
  3250. static void *longpoll_thread(void *userdata)
  3251. {
  3252. struct thr_info *mythr = userdata;
  3253. CURL *curl = NULL;
  3254. char *copy_start, *hdr_path, *lp_url = NULL;
  3255. bool need_slash = false;
  3256. int failures = 0;
  3257. struct pool *pool = current_pool();
  3258. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3259. curl = curl_easy_init();
  3260. if (unlikely(!curl)) {
  3261. applog(LOG_ERR, "CURL initialisation failed");
  3262. goto out;
  3263. }
  3264. tq_pop(mythr->q, NULL);
  3265. if (!pool->hdr_path) {
  3266. applog(LOG_WARNING, "No long-poll found on this server");
  3267. goto out;
  3268. }
  3269. hdr_path = pool->hdr_path;
  3270. /* full URL */
  3271. if (strstr(hdr_path, "://")) {
  3272. lp_url = hdr_path;
  3273. hdr_path = NULL;
  3274. }
  3275. /* absolute path, on current server */
  3276. else {
  3277. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3278. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3279. need_slash = true;
  3280. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3281. if (!lp_url)
  3282. goto out;
  3283. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3284. }
  3285. have_longpoll = true;
  3286. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  3287. while (1) {
  3288. struct timeval start, end;
  3289. bool rolltime;
  3290. json_t *val;
  3291. gettimeofday(&start, NULL);
  3292. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3293. false, true, &rolltime, pool);
  3294. if (likely(val)) {
  3295. /* Keep track of who ordered a restart_threads to make
  3296. * sure it's only done once per new block */
  3297. if (block_changed != BLOCK_DETECT) {
  3298. block_changed = BLOCK_LP;
  3299. new_blocks++;
  3300. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  3301. restart_threads();
  3302. } else {
  3303. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  3304. block_changed = BLOCK_NONE;
  3305. }
  3306. convert_to_work(val, rolltime);
  3307. failures = 0;
  3308. json_decref(val);
  3309. } else {
  3310. /* Some pools regularly drop the longpoll request so
  3311. * only see this as longpoll failure if it happens
  3312. * immediately and just restart it the rest of the
  3313. * time. */
  3314. gettimeofday(&end, NULL);
  3315. if (end.tv_sec - start.tv_sec > 30)
  3316. continue;
  3317. if (failures++ < 10) {
  3318. sleep(30);
  3319. applog(LOG_WARNING,
  3320. "longpoll failed, sleeping for 30s");
  3321. } else {
  3322. applog(LOG_ERR,
  3323. "longpoll failed, ending thread");
  3324. goto out;
  3325. }
  3326. }
  3327. }
  3328. out:
  3329. have_longpoll = false;
  3330. free(lp_url);
  3331. tq_freeze(mythr->q);
  3332. if (curl)
  3333. curl_easy_cleanup(curl);
  3334. return NULL;
  3335. }
  3336. static void stop_longpoll(void)
  3337. {
  3338. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3339. tq_freeze(thr->q);
  3340. pthread_cancel(*thr->pth);
  3341. have_longpoll = false;
  3342. }
  3343. static void start_longpoll(void)
  3344. {
  3345. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3346. tq_thaw(thr->q);
  3347. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3348. quit(1, "longpoll thread create failed");
  3349. pthread_detach(*thr->pth);
  3350. if (opt_debug)
  3351. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3352. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3353. }
  3354. static void restart_longpoll(void)
  3355. {
  3356. stop_longpoll();
  3357. if (want_longpoll)
  3358. start_longpoll();
  3359. }
  3360. static void *reinit_cpu(void *userdata)
  3361. {
  3362. pthread_detach(pthread_self());
  3363. #if 0
  3364. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  3365. int cpu = cgpu->cpu_gpu;
  3366. long thr_id = ....(long)userdata;
  3367. struct thr_info *thr = &thr_info[thr_id];
  3368. int cpu = dev_from_id(thr_id);
  3369. cpus[cpu].alive = false;
  3370. thr->rolling = thr->cgpu->rolling = 0;
  3371. tq_freeze(thr->q);
  3372. if (!pthread_cancel(*thr->pth))
  3373. pthread_join(*thr->pth, NULL);
  3374. free(thr->q);
  3375. thr->q = tq_new();
  3376. if (!thr->q)
  3377. quit(1, "Failed to tq_new in reinit_cputhread");
  3378. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  3379. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  3380. applog(LOG_ERR, "thread %d create failed", thr_id);
  3381. return NULL;
  3382. }
  3383. tq_push(thr->q, &ping);
  3384. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3385. #endif
  3386. return NULL;
  3387. }
  3388. #ifdef HAVE_OPENCL
  3389. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  3390. * init command fails due to a completely wedged GPU, the thread will never
  3391. * return, unable to harm other GPUs. If it does return, it means we only had
  3392. * a soft failure and then the reinit_gpu thread is ready to tackle another
  3393. * GPU */
  3394. static void *reinit_gpu(void *userdata)
  3395. {
  3396. struct thr_info *mythr = userdata;
  3397. struct cgpu_info *cgpu;
  3398. struct thr_info *thr;
  3399. struct timeval now;
  3400. char name[256];
  3401. int thr_id;
  3402. int gpu;
  3403. pthread_detach(pthread_self());
  3404. select_cgpu:
  3405. cgpu = tq_pop(mythr->q, NULL);
  3406. if (!cgpu)
  3407. goto out;
  3408. if (clDevicesNum() != nDevs) {
  3409. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  3410. goto out;
  3411. }
  3412. gpu = cgpu->cpu_gpu;
  3413. gpu_devices[gpu] = false;
  3414. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3415. if (dev_from_id(thr_id) != gpu)
  3416. continue;
  3417. thr = &thr_info[thr_id];
  3418. thr->rolling = thr->cgpu->rolling = 0;
  3419. /* Reports the last time we tried to revive a sick GPU */
  3420. gettimeofday(&thr->sick, NULL);
  3421. if (!pthread_cancel(*thr->pth)) {
  3422. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  3423. } else
  3424. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  3425. }
  3426. gpu_devices[gpu] = true;
  3427. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3428. if (dev_from_id(thr_id) != gpu)
  3429. continue;
  3430. thr = &thr_info[thr_id];
  3431. /* Lose this ram cause we may get stuck here! */
  3432. //tq_freeze(thr->q);
  3433. thr->q = tq_new();
  3434. if (!thr->q)
  3435. quit(1, "Failed to tq_new in reinit_gpu");
  3436. /* Lose this ram cause we may dereference in the dying thread! */
  3437. //free(clState);
  3438. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  3439. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  3440. if (!clStates[thr_id]) {
  3441. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  3442. goto select_cgpu;
  3443. }
  3444. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3445. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  3446. applog(LOG_ERR, "thread %d create failed", thr_id);
  3447. return NULL;
  3448. }
  3449. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3450. }
  3451. gettimeofday(&now, NULL);
  3452. get_datestamp(cgpu->init, &now);
  3453. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3454. if (dev_from_id(thr_id) != gpu)
  3455. continue;
  3456. thr = &thr_info[thr_id];
  3457. tq_push(thr->q, &ping);
  3458. }
  3459. goto select_cgpu;
  3460. out:
  3461. return NULL;
  3462. }
  3463. #else
  3464. static void *reinit_gpu(void *userdata)
  3465. {
  3466. }
  3467. #endif
  3468. static void reinit_device(struct cgpu_info *cgpu)
  3469. {
  3470. if (cgpu->is_gpu)
  3471. tq_push(thr_info[gpur_thr_id].q, cgpu);
  3472. else
  3473. tq_push(thr_info[cpur_thr_id].q, cgpu);
  3474. }
  3475. /* Determine which are the first threads belonging to a device and if they're
  3476. * active */
  3477. static bool active_device(int thr_id)
  3478. {
  3479. if (thr_id < gpu_threads) {
  3480. if (thr_id >= total_devices)
  3481. return false;
  3482. if (!gpu_devices[dev_from_id(thr_id)])
  3483. return false;
  3484. } else if (thr_id > gpu_threads + num_processors)
  3485. return false;
  3486. return true;
  3487. }
  3488. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3489. * the screen at regular intervals, and restarts threads if they appear to have
  3490. * died. */
  3491. static void *watchdog_thread(void *userdata)
  3492. {
  3493. const unsigned int interval = opt_log_interval / 2 ? : 1;
  3494. static struct timeval rotate_tv;
  3495. struct timeval zero_tv;
  3496. bool statwin = false;
  3497. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3498. memset(&zero_tv, 0, sizeof(struct timeval));
  3499. gettimeofday(&rotate_tv, NULL);
  3500. while (1) {
  3501. int i;
  3502. struct timeval now;
  3503. sleep(interval);
  3504. if (requests_queued() < opt_queue)
  3505. queue_request(NULL, false);
  3506. hashmeter(-1, &zero_tv, 0);
  3507. if (curses_active) {
  3508. statwin ^= true;
  3509. mutex_lock(&curses_lock);
  3510. for (i = 0; i < mining_threads; i++)
  3511. curses_print_status(i);
  3512. if (statwin)
  3513. redrawwin(statuswin);
  3514. else {
  3515. check_logwinsize();
  3516. redrawwin(logwin);
  3517. }
  3518. mutex_unlock(&curses_lock);
  3519. }
  3520. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  3521. restart_threads();
  3522. work_restart[watchdog_thr_id].restart = 0;
  3523. }
  3524. gettimeofday(&now, NULL);
  3525. for (i = 0; i < total_pools; i++) {
  3526. struct pool *pool = pools[i];
  3527. if (!pool->enabled)
  3528. continue;
  3529. /* Test pool is idle once every minute */
  3530. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3531. gettimeofday(&pool->tv_idle, NULL);
  3532. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3533. pool_resus(pool);
  3534. }
  3535. }
  3536. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3537. gettimeofday(&rotate_tv, NULL);
  3538. switch_pools(NULL);
  3539. }
  3540. //for (i = 0; i < mining_threads; i++) {
  3541. for (i = 0; i < gpu_threads; i++) {
  3542. struct thr_info *thr = &thr_info[i];
  3543. int gpu = thr->cgpu->cpu_gpu;
  3544. /* Thread is waiting on getwork or disabled */
  3545. if (thr->getwork || !gpu_devices[gpu])
  3546. continue;
  3547. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3548. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  3549. gpus[gpu].status = LIFE_WELL;
  3550. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3551. thr->rolling = thr->cgpu->rolling = 0;
  3552. gpus[gpu].status = LIFE_SICK;
  3553. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3554. applog(LOG_ERR, "Attempting to restart GPU");
  3555. gettimeofday(&thr->sick, NULL);
  3556. reinit_device(thr->cgpu);
  3557. } else if (now.tv_sec - thr->sick.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  3558. gpus[gpu].status = LIFE_DEAD;
  3559. applog(LOG_ERR, "Thread %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  3560. } else if (now.tv_sec - thr->sick.tv_sec > 60 && gpus[i].status == LIFE_SICK) {
  3561. /* Attempt to restart a GPU once every minute */
  3562. reinit_device(thr->cgpu);
  3563. }
  3564. }
  3565. }
  3566. return NULL;
  3567. }
  3568. static void log_print_status(int thr_id)
  3569. {
  3570. struct cgpu_info *cgpu;
  3571. cgpu = thr_info[thr_id].cgpu;
  3572. applog(LOG_WARNING, " %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  3573. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  3574. cgpu->total_mhashes / total_secs, cgpu->getworks,
  3575. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  3576. cgpu->efficiency, cgpu->utility);
  3577. }
  3578. static void print_summary(void)
  3579. {
  3580. struct timeval diff;
  3581. int hours, mins, secs, i;
  3582. double utility, efficiency = 0.0;
  3583. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3584. hours = diff.tv_sec / 3600;
  3585. mins = (diff.tv_sec % 3600) / 60;
  3586. secs = diff.tv_sec % 60;
  3587. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3588. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3589. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  3590. applog(LOG_WARNING, "Started at %s", datestamp);
  3591. if (opt_n_threads)
  3592. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  3593. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  3594. if (total_secs)
  3595. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  3596. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  3597. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  3598. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  3599. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  3600. if (total_accepted || total_rejected)
  3601. applog(LOG_WARNING, "Reject ratio: %.1f", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3602. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  3603. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  3604. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  3605. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  3606. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  3607. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_lo);
  3608. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  3609. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  3610. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  3611. if (total_pools > 1) {
  3612. for (i = 0; i < total_pools; i++) {
  3613. struct pool *pool = pools[i];
  3614. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  3615. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  3616. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  3617. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  3618. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  3619. if (pool->accepted || pool->rejected)
  3620. applog(LOG_WARNING, " Reject ratio: %.1f", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3621. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3622. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  3623. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  3624. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  3625. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->localgen_occasions);
  3626. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  3627. }
  3628. }
  3629. applog(LOG_WARNING, "Summary of per device statistics:\n");
  3630. for (i = 0; i < mining_threads; i++) {
  3631. if (active_device(i))
  3632. log_print_status(i);
  3633. }
  3634. fflush(stdout);
  3635. fflush(stderr);
  3636. }
  3637. void quit(int status, const char *format, ...)
  3638. {
  3639. va_list ap;
  3640. disable_curses();
  3641. if (format) {
  3642. va_start(ap, format);
  3643. vfprintf(stderr, format, ap);
  3644. va_end(ap);
  3645. }
  3646. fprintf(stderr, "\n");
  3647. fflush(stderr);
  3648. exit(status);
  3649. }
  3650. static char *curses_input(const char *query)
  3651. {
  3652. char *input;
  3653. echo();
  3654. input = malloc(255);
  3655. if (!input)
  3656. quit(1, "Failed to malloc input");
  3657. leaveok(logwin, false);
  3658. wlogprint("%s: ", query);
  3659. wgetnstr(logwin, input, 255);
  3660. leaveok(logwin, true);
  3661. noecho();
  3662. return input;
  3663. }
  3664. static bool input_pool(bool live)
  3665. {
  3666. char *url = NULL, *user = NULL, *pass = NULL;
  3667. struct pool *pool = NULL;
  3668. bool ret = false;
  3669. immedok(logwin, true);
  3670. if (total_pools == MAX_POOLS) {
  3671. wlogprint("Reached maximum number of pools.\n");
  3672. goto out;
  3673. }
  3674. wlogprint("Input server details.\n");
  3675. url = curses_input("URL");
  3676. if (!url)
  3677. goto out;
  3678. if (strncmp(url, "http://", 7) &&
  3679. strncmp(url, "https://", 8)) {
  3680. char *httpinput;
  3681. httpinput = malloc(255);
  3682. if (!httpinput)
  3683. quit(1, "Failed to malloc httpinput");
  3684. strcpy(httpinput, "http://");
  3685. strncat(httpinput, url, 248);
  3686. free(url);
  3687. url = httpinput;
  3688. }
  3689. user = curses_input("Username");
  3690. if (!user)
  3691. goto out;
  3692. pass = curses_input("Password");
  3693. if (!pass)
  3694. goto out;
  3695. pool = calloc(sizeof(struct pool), 1);
  3696. if (!pool)
  3697. quit(1, "Failed to realloc pools in input_pool");
  3698. pool->pool_no = total_pools;
  3699. pool->prio = total_pools;
  3700. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3701. quit (1, "Failed to pthread_mutex_init in input_pool");
  3702. pool->rpc_url = url;
  3703. pool->rpc_user = user;
  3704. pool->rpc_pass = pass;
  3705. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3706. if (!pool->rpc_userpass)
  3707. quit(1, "Failed to malloc userpass");
  3708. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3709. pool->tv_idle.tv_sec = ~0UL;
  3710. /* Test the pool is not idle if we're live running, otherwise
  3711. * it will be tested separately */
  3712. ret = true;
  3713. pool->enabled = true;
  3714. if (live && !pool_active(pool, false))
  3715. pool->idle = true;
  3716. pools[total_pools++] = pool;
  3717. out:
  3718. immedok(logwin, false);
  3719. if (!ret) {
  3720. if (url)
  3721. free(url);
  3722. if (user)
  3723. free(user);
  3724. if (pass)
  3725. free(pass);
  3726. if (pool)
  3727. free(pool);
  3728. }
  3729. return ret;
  3730. }
  3731. #if defined(unix)
  3732. static void fork_monitor()
  3733. {
  3734. // Make a pipe: [readFD, writeFD]
  3735. int pfd[2];
  3736. int r = pipe(pfd);
  3737. if (r<0) {
  3738. perror("pipe - failed to create pipe for --monitor");
  3739. exit(1);
  3740. }
  3741. // Make stderr write end of pipe
  3742. fflush(stderr);
  3743. r = dup2(pfd[1], 2);
  3744. if (r<0) {
  3745. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3746. exit(1);
  3747. }
  3748. r = close(pfd[1]);
  3749. if (r<0) {
  3750. perror("close - failed to close write end of pipe for --monitor");
  3751. exit(1);
  3752. }
  3753. // Don't allow a dying monitor to kill the main process
  3754. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3755. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3756. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3757. perror("signal - failed to edit signal mask for --monitor");
  3758. exit(1);
  3759. }
  3760. // Fork a child process
  3761. r = fork();
  3762. if (r<0) {
  3763. perror("fork - failed to fork child process for --monitor");
  3764. exit(1);
  3765. }
  3766. // Child: launch monitor command
  3767. if (0==r) {
  3768. // Make stdin read end of pipe
  3769. r = dup2(pfd[0], 0);
  3770. if (r<0) {
  3771. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3772. exit(1);
  3773. }
  3774. close(pfd[0]);
  3775. if (r<0) {
  3776. perror("close - in child, failed to close read end of pipe for --monitor");
  3777. exit(1);
  3778. }
  3779. // Launch user specified command
  3780. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3781. perror("execl - in child failed to exec user specified command for --monitor");
  3782. exit(1);
  3783. }
  3784. // Parent: clean up unused fds and bail
  3785. r = close(pfd[0]);
  3786. if (r<0) {
  3787. perror("close - failed to close read end of pipe for --monitor");
  3788. exit(1);
  3789. }
  3790. }
  3791. #endif // defined(unix)
  3792. int main (int argc, char *argv[])
  3793. {
  3794. unsigned int i, x, y, pools_active = 0;
  3795. struct sigaction handler;
  3796. struct thr_info *thr;
  3797. char name[256];
  3798. /* This dangerous functions tramples random dynamically allocated
  3799. * variables so do it before anything at all */
  3800. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3801. quit(1, "Failed to curl_global_init");
  3802. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  3803. quit(1, "Failed to pthread_mutex_init");
  3804. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  3805. quit(1, "Failed to pthread_mutex_init");
  3806. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  3807. quit(1, "Failed to pthread_mutex_init");
  3808. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  3809. quit(1, "Failed to pthread_mutex_init");
  3810. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  3811. quit(1, "Failed to pthread_mutex_init");
  3812. init_max_name_len();
  3813. handler.sa_handler = &sighandler;
  3814. sigaction(SIGTERM, &handler, &termhandler);
  3815. sigaction(SIGINT, &handler, &inthandler);
  3816. gettimeofday(&total_tv_start, NULL);
  3817. gettimeofday(&total_tv_end, NULL);
  3818. get_datestamp(datestamp, &total_tv_start);
  3819. // Hack to make cgminer silent when called recursively on WIN32
  3820. int skip_to_bench = 0;
  3821. #if defined(WIN32)
  3822. char buf[32];
  3823. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  3824. skip_to_bench = 1;
  3825. #endif // defined(WIN32)
  3826. for (i = 0; i < 36; i++)
  3827. strcat(current_block, "0");
  3828. current_hash = calloc(sizeof(current_hash), 1);
  3829. if (unlikely(!current_hash))
  3830. quit (1, "main OOM");
  3831. // Reckon number of cores in the box
  3832. #if defined(WIN32)
  3833. DWORD system_am;
  3834. DWORD process_am;
  3835. BOOL ok = GetProcessAffinityMask(
  3836. GetCurrentProcess(),
  3837. &system_am,
  3838. &process_am
  3839. );
  3840. if (!ok) {
  3841. applog(LOG_ERR, "couldn't figure out number of processors :(");
  3842. num_processors = 1;
  3843. } else {
  3844. size_t n = 32;
  3845. num_processors = 0;
  3846. while (n--)
  3847. if (process_am & (1<<n))
  3848. ++num_processors;
  3849. }
  3850. #else
  3851. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  3852. #endif /* !WIN32 */
  3853. opt_n_threads = num_processors;
  3854. #ifdef HAVE_OPENCL
  3855. if (!skip_to_bench) {
  3856. for (i = 0; i < 16; i++)
  3857. gpu_devices[i] = false;
  3858. nDevs = clDevicesNum();
  3859. if (nDevs < 0) {
  3860. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  3861. nDevs = 0;
  3862. }
  3863. }
  3864. #endif
  3865. if (nDevs)
  3866. opt_n_threads = 0;
  3867. trpc_url = strdup(DEF_RPC_URL);
  3868. /* parse command line */
  3869. opt_register_table(opt_config_table,
  3870. "Options for both config file and command line");
  3871. opt_register_table(opt_cmdline_table,
  3872. "Options for command line only");
  3873. opt_parse(&argc, argv, applog_and_exit);
  3874. if (argc != 1)
  3875. quit(1, "Unexpected extra commandline arguments");
  3876. if (want_per_device_stats)
  3877. opt_log_output = true;
  3878. if (0<=opt_bench_algo) {
  3879. double rate = bench_algo_stage3(opt_bench_algo);
  3880. if (!skip_to_bench) {
  3881. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  3882. } else {
  3883. // Write result to shared memory for parent
  3884. #if defined(WIN32)
  3885. char unique_name[64];
  3886. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  3887. HANDLE map_handle = CreateFileMapping(
  3888. INVALID_HANDLE_VALUE, // use paging file
  3889. NULL, // default security attributes
  3890. PAGE_READWRITE, // read/write access
  3891. 0, // size: high 32-bits
  3892. 4096, // size: low 32-bits
  3893. unique_name // name of map object
  3894. );
  3895. if (NULL!=map_handle) {
  3896. void *shared_mem = MapViewOfFile(
  3897. map_handle, // object to map view of
  3898. FILE_MAP_WRITE, // read/write access
  3899. 0, // high offset: map from
  3900. 0, // low offset: beginning
  3901. 0 // default: map entire file
  3902. );
  3903. if (NULL!=shared_mem)
  3904. CopyMemory(shared_mem, &rate, sizeof(rate));
  3905. (void)UnmapViewOfFile(shared_mem);
  3906. }
  3907. (void)CloseHandle(map_handle);
  3908. }
  3909. #endif
  3910. }
  3911. exit(0);
  3912. }
  3913. if (opt_kernel) {
  3914. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  3915. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  3916. if (!strcmp(opt_kernel, "poclbm"))
  3917. chosen_kernel = KL_POCLBM;
  3918. else
  3919. chosen_kernel = KL_PHATK;
  3920. } else
  3921. chosen_kernel = KL_NONE;
  3922. gpu_threads = nDevs * opt_g_threads;
  3923. if (total_devices) {
  3924. if (total_devices > nDevs)
  3925. quit(1, "More devices specified than exist");
  3926. for (i = 0; i < 16; i++)
  3927. if (gpu_devices[i] && i + 1 > nDevs)
  3928. quit (1, "Command line options set a device that doesn't exist");
  3929. } else {
  3930. for (i = 0; i < nDevs; i++)
  3931. gpu_devices[i] = true;
  3932. total_devices = nDevs;
  3933. }
  3934. if (!gpu_threads && !forced_n_threads) {
  3935. /* Maybe they turned GPU off; restore default CPU threads. */
  3936. opt_n_threads = num_processors;
  3937. }
  3938. logcursor = 8;
  3939. gpucursor = logcursor;
  3940. cpucursor = gpucursor + nDevs;
  3941. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  3942. logcursor = logstart + 1;
  3943. /* Set up the ncurses interface */
  3944. if (!opt_realquiet && use_curses) {
  3945. mainwin = initscr();
  3946. getmaxyx(mainwin, y, x);
  3947. statuswin = newwin(logstart, x, 0, 0);
  3948. leaveok(statuswin, true);
  3949. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3950. idlok(logwin, true);
  3951. scrollok(logwin, true);
  3952. leaveok(logwin, true);
  3953. cbreak();
  3954. noecho();
  3955. test_and_set(&curses_active);
  3956. }
  3957. if (!total_pools) {
  3958. if (curses_active) {
  3959. if (!input_pool(false))
  3960. quit(1, "Pool setup failed");
  3961. } else
  3962. quit(1, "No server specified");
  3963. }
  3964. for (i = 0; i < total_pools; i++) {
  3965. struct pool *pool = pools[i];
  3966. if (!pool->rpc_userpass) {
  3967. if (!pool->rpc_user || !pool->rpc_pass)
  3968. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3969. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3970. if (!pool->rpc_userpass)
  3971. quit(1, "Failed to malloc userpass");
  3972. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3973. } else {
  3974. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  3975. if (!pool->rpc_user)
  3976. quit(1, "Failed to malloc user");
  3977. strcpy(pool->rpc_user, pool->rpc_userpass);
  3978. pool->rpc_user = strtok(pool->rpc_user, ":");
  3979. if (!pool->rpc_user)
  3980. quit(1, "Failed to find colon delimiter in userpass");
  3981. }
  3982. }
  3983. /* Set the currentpool to pool 0 */
  3984. currentpool = pools[0];
  3985. #ifdef HAVE_SYSLOG_H
  3986. if (use_syslog)
  3987. openlog(PROGRAM_NAME, LOG_PID, LOG_USER);
  3988. #endif
  3989. #if defined(unix)
  3990. if (opt_stderr_cmd)
  3991. fork_monitor();
  3992. #endif // defined(unix)
  3993. mining_threads = opt_n_threads + gpu_threads;
  3994. total_threads = mining_threads + 7;
  3995. work_restart = calloc(total_threads, sizeof(*work_restart));
  3996. if (!work_restart)
  3997. quit(1, "Failed to calloc work_restart");
  3998. thr_info = calloc(total_threads, sizeof(*thr));
  3999. if (!thr_info)
  4000. quit(1, "Failed to calloc thr_info");
  4001. /* init workio thread info */
  4002. work_thr_id = mining_threads;
  4003. thr = &thr_info[work_thr_id];
  4004. thr->id = work_thr_id;
  4005. thr->q = tq_new();
  4006. if (!thr->q)
  4007. quit(1, "Failed to tq_new");
  4008. /* start work I/O thread */
  4009. if (thr_info_create(thr, NULL, workio_thread, thr))
  4010. quit(1, "workio thread create failed");
  4011. /* init longpoll thread info */
  4012. longpoll_thr_id = mining_threads + 1;
  4013. thr = &thr_info[longpoll_thr_id];
  4014. thr->id = longpoll_thr_id;
  4015. thr->q = tq_new();
  4016. if (!thr->q)
  4017. quit(1, "Failed to tq_new");
  4018. if (opt_n_threads ) {
  4019. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  4020. if (unlikely(!cpus))
  4021. quit(1, "Failed to calloc cpus");
  4022. }
  4023. if (gpu_threads) {
  4024. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  4025. if (unlikely(!gpus))
  4026. quit(1, "Failed to calloc gpus");
  4027. }
  4028. stage_thr_id = mining_threads + 3;
  4029. thr = &thr_info[stage_thr_id];
  4030. thr->q = tq_new();
  4031. if (!thr->q)
  4032. quit(1, "Failed to tq_new");
  4033. /* start stage thread */
  4034. if (thr_info_create(thr, NULL, stage_thread, thr))
  4035. quit(1, "stage thread create failed");
  4036. pthread_detach(*thr->pth);
  4037. /* Create a unique get work queue */
  4038. getq = tq_new();
  4039. if (!getq)
  4040. quit(1, "Failed to create getq");
  4041. /* Test each pool to see if we can retrieve and use work and for what
  4042. * it supports */
  4043. for (i = 0; i < total_pools; i++) {
  4044. struct pool *pool;
  4045. pool = pools[i];
  4046. pool->enabled = true;
  4047. if (pool_active(pool, false)) {
  4048. if (!currentpool)
  4049. currentpool = pool;
  4050. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4051. pools_active++;
  4052. } else {
  4053. if (pool == currentpool)
  4054. currentpool = NULL;
  4055. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4056. pool->idle = true;
  4057. }
  4058. }
  4059. if (!pools_active)
  4060. quit(0, "No pools active! Exiting.");
  4061. if (want_longpoll)
  4062. start_longpoll();
  4063. #ifdef HAVE_OPENCL
  4064. /* start GPU mining threads */
  4065. for (i = 0; i < nDevs * opt_g_threads; i++) {
  4066. int gpu = i % nDevs;
  4067. struct cgpu_info *cgpu;
  4068. struct timeval now;
  4069. gpus[gpu].is_gpu = 1;
  4070. gpus[gpu].cpu_gpu = gpu;
  4071. thr = &thr_info[i];
  4072. thr->id = i;
  4073. cgpu = thr->cgpu = &gpus[gpu];
  4074. thr->q = tq_new();
  4075. if (!thr->q)
  4076. quit(1, "tq_new failed in starting gpu mining threads");
  4077. /* Enable threads for devices set not to mine but disable
  4078. * their queue in case we wish to enable them later*/
  4079. if (gpu_devices[gpu]) {
  4080. if (opt_debug)
  4081. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4082. tq_push(thr->q, &ping);
  4083. }
  4084. applog(LOG_INFO, "Init GPU thread %i", i);
  4085. clStates[i] = initCl(gpu, name, sizeof(name));
  4086. if (!clStates[i]) {
  4087. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  4088. gpu_devices[i] = false;
  4089. continue;
  4090. }
  4091. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4092. gettimeofday(&now, NULL);
  4093. get_datestamp(cgpu->init, &now);
  4094. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  4095. quit(1, "thread %d create failed", i);
  4096. }
  4097. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4098. #else
  4099. opt_g_threads = 0;
  4100. #endif
  4101. /* start CPU mining threads */
  4102. for (i = gpu_threads; i < mining_threads; i++) {
  4103. int cpu = (i - gpu_threads) % num_processors;
  4104. thr = &thr_info[i];
  4105. thr->id = i;
  4106. cpus[cpu].cpu_gpu = cpu;
  4107. thr->cgpu = &cpus[cpu];
  4108. thr->q = tq_new();
  4109. if (!thr->q)
  4110. quit(1, "tq_new failed in starting cpu mining threads");
  4111. thread_reportin(thr);
  4112. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4113. quit(1, "thread %d create failed", i);
  4114. }
  4115. applog(LOG_INFO, "%d cpu miner threads started, "
  4116. "using SHA256 '%s' algorithm.",
  4117. opt_n_threads,
  4118. algo_names[opt_algo]);
  4119. watchdog_thr_id = mining_threads + 2;
  4120. thr = &thr_info[watchdog_thr_id];
  4121. /* start wakeup thread */
  4122. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4123. quit(1, "wakeup thread create failed");
  4124. /* Create curses input thread for keyboard input */
  4125. input_thr_id = mining_threads + 4;
  4126. thr = &thr_info[input_thr_id];
  4127. if (thr_info_create(thr, NULL, input_thread, thr))
  4128. quit(1, "input thread create failed");
  4129. pthread_detach(*thr->pth);
  4130. /* Create reinit cpu thread */
  4131. cpur_thr_id = mining_threads + 5;
  4132. thr = &thr_info[cpur_thr_id];
  4133. thr->q = tq_new();
  4134. if (!thr->q)
  4135. quit(1, "tq_new failed for cpur_thr_id");
  4136. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  4137. quit(1, "reinit_cpu thread create failed");
  4138. /* Create reinit gpu thread */
  4139. gpur_thr_id = mining_threads + 6;
  4140. thr = &thr_info[gpur_thr_id];
  4141. thr->q = tq_new();
  4142. if (!thr->q)
  4143. quit(1, "tq_new failed for gpur_thr_id");
  4144. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4145. quit(1, "reinit_gpu thread create failed");
  4146. /* main loop - simply wait for workio thread to exit */
  4147. pthread_join(*thr_info[work_thr_id].pth, NULL);
  4148. applog(LOG_INFO, "workio thread dead, exiting.");
  4149. gettimeofday(&total_tv_end, NULL);
  4150. disable_curses();
  4151. if (!opt_realquiet && successful_connect)
  4152. print_summary();
  4153. if (gpu_threads)
  4154. free(gpus);
  4155. if (opt_n_threads)
  4156. free(cpus);
  4157. curl_global_cleanup();
  4158. return 0;
  4159. }