main.c 125 KB

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