main.c 127 KB

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