main.c 127 KB

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