main.c 128 KB

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