main.c 123 KB

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