main.c 126 KB

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