main.c 127 KB

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