main.c 126 KB

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