main.c 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769
  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. bool want_longpoll = true;
  156. 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");
  1142. else
  1143. wprintw(statuswin, " Connected to %s as user %s", pool->rpc_url, pool->rpc_user);
  1144. wclrtoeol(statuswin);
  1145. wmove(statuswin, 5, 0);
  1146. wprintw(statuswin, " Block: %s... Started: %s", current_hash, blocktime);
  1147. wmove(statuswin, 6, 0);
  1148. whline(statuswin, '-', 80);
  1149. wmove(statuswin, logstart - 1, 0);
  1150. whline(statuswin, '-', 80);
  1151. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1152. opt_g_threads ? "[G]PU management " : "");
  1153. if (thr_id >= 0 && thr_id < gpu_threads) {
  1154. int gpu = dev_from_id(thr_id);
  1155. struct cgpu_info *cgpu = &gpus[gpu];
  1156. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1157. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1158. wmove(statuswin, gpucursor + gpu, 0);
  1159. if (cgpu->status == LIFE_DEAD)
  1160. wprintw(statuswin, " GPU %d: [DEAD / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1161. gpu, cgpu->total_mhashes / total_secs,
  1162. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1163. cgpu->efficiency, cgpu->utility);
  1164. else if (cgpu->status == LIFE_SICK)
  1165. wprintw(statuswin, " GPU %d: [SICK / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1166. gpu, cgpu->total_mhashes / total_secs,
  1167. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1168. cgpu->efficiency, cgpu->utility);
  1169. else if (!gpu_devices[gpu])
  1170. wprintw(statuswin, " GPU %d: [DISABLED / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1171. gpu, cgpu->total_mhashes / total_secs,
  1172. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1173. cgpu->efficiency, cgpu->utility);
  1174. else
  1175. wprintw(statuswin, " GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1176. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1177. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1178. cgpu->efficiency, cgpu->utility);
  1179. wclrtoeol(statuswin);
  1180. } else if (thr_id >= gpu_threads) {
  1181. int cpu = dev_from_id(thr_id);
  1182. struct cgpu_info *cgpu = &cpus[cpu];
  1183. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1184. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1185. wmove(statuswin, cpucursor + cpu, 0);
  1186. wprintw(statuswin, " CPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1187. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1188. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1189. cgpu->efficiency, cgpu->utility);
  1190. wclrtoeol(statuswin);
  1191. }
  1192. wrefresh(statuswin);
  1193. }
  1194. static void print_status(int thr_id)
  1195. {
  1196. if (!curses_active)
  1197. text_print_status(thr_id);
  1198. else {
  1199. mutex_lock(&curses_lock);
  1200. curses_print_status(thr_id);
  1201. mutex_unlock(&curses_lock);
  1202. }
  1203. }
  1204. /* Check for window resize. Called with curses mutex locked */
  1205. static inline void check_logwinsize(void)
  1206. {
  1207. int x, y, logx, logy;
  1208. getmaxyx(mainwin, y, x);
  1209. getmaxyx(logwin, logy, logx);
  1210. y -= logcursor;
  1211. /* Detect screen size change */
  1212. if ((x != logx || y != logy) && x >= 80 && y >= 25)
  1213. wresize(logwin, y, x);
  1214. }
  1215. /* For mandatory printing when mutex is already locked */
  1216. static void wlog(const char *f, ...)
  1217. {
  1218. va_list ap;
  1219. va_start(ap, f);
  1220. vw_printw(logwin, f, ap);
  1221. va_end(ap);
  1222. }
  1223. /* Mandatory printing */
  1224. static void wlogprint(const char *f, ...)
  1225. {
  1226. va_list ap;
  1227. mutex_lock(&curses_lock);
  1228. va_start(ap, f);
  1229. vw_printw(logwin, f, ap);
  1230. va_end(ap);
  1231. wrefresh(logwin);
  1232. mutex_unlock(&curses_lock);
  1233. }
  1234. void log_curses(int prio, const char *f, va_list ap)
  1235. {
  1236. if (opt_quiet && prio != LOG_ERR)
  1237. return;
  1238. if (curses_active) {
  1239. if (!opt_loginput) {
  1240. mutex_lock(&curses_lock);
  1241. vw_printw(logwin, f, ap);
  1242. wrefresh(logwin);
  1243. mutex_unlock(&curses_lock);
  1244. }
  1245. } else
  1246. vprintf(f, ap);
  1247. }
  1248. static void clear_logwin(void)
  1249. {
  1250. mutex_lock(&curses_lock);
  1251. wclear(logwin);
  1252. wrefresh(logwin);
  1253. mutex_unlock(&curses_lock);
  1254. }
  1255. static bool submit_upstream_work(const struct work *work)
  1256. {
  1257. char *hexstr = NULL;
  1258. json_t *val, *res;
  1259. char s[345], sd[345];
  1260. bool rc = false;
  1261. int thr_id = work->thr_id;
  1262. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1263. CURL *curl = curl_easy_init();
  1264. struct pool *pool = work->pool;
  1265. bool rolltime;
  1266. if (unlikely(!curl)) {
  1267. applog(LOG_ERR, "CURL initialisation failed");
  1268. return rc;
  1269. }
  1270. /* build hex string */
  1271. hexstr = bin2hex(work->data, sizeof(work->data));
  1272. if (unlikely(!hexstr)) {
  1273. applog(LOG_ERR, "submit_upstream_work OOM");
  1274. goto out_nofree;
  1275. }
  1276. /* build JSON-RPC request */
  1277. sprintf(s,
  1278. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1279. hexstr);
  1280. sprintf(sd,
  1281. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1282. hexstr);
  1283. if (opt_debug)
  1284. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1285. /* issue JSON-RPC request */
  1286. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool);
  1287. if (unlikely(!val)) {
  1288. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1289. if (!pool_tset(pool, &pool->submit_fail)) {
  1290. total_ro++;
  1291. pool->remotefail_occasions++;
  1292. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1293. }
  1294. goto out;
  1295. } else if (pool_tclear(pool, &pool->submit_fail))
  1296. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1297. res = json_object_get(val, "result");
  1298. /* Theoretically threads could race when modifying accepted and
  1299. * rejected values but the chance of two submits completing at the
  1300. * same time is zero so there is no point adding extra locking */
  1301. if (json_is_true(res)) {
  1302. cgpu->accepted++;
  1303. total_accepted++;
  1304. pool->accepted++;
  1305. if (opt_debug)
  1306. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1307. if (!QUIET) {
  1308. if (total_pools > 1)
  1309. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  1310. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1311. else
  1312. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  1313. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1314. }
  1315. } else {
  1316. cgpu->rejected++;
  1317. total_rejected++;
  1318. pool->rejected++;
  1319. if (opt_debug)
  1320. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1321. if (!QUIET) {
  1322. if (total_pools > 1)
  1323. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  1324. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1325. else
  1326. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  1327. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1328. }
  1329. }
  1330. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1331. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1332. if (!opt_realquiet)
  1333. print_status(thr_id);
  1334. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  1335. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  1336. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  1337. json_decref(val);
  1338. rc = true;
  1339. out:
  1340. free(hexstr);
  1341. out_nofree:
  1342. curl_easy_cleanup(curl);
  1343. return rc;
  1344. }
  1345. static const char *rpc_req =
  1346. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1347. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1348. static inline struct pool *select_pool(bool lagging)
  1349. {
  1350. static int rotating_pool = 0;
  1351. struct pool *pool, *cp;
  1352. cp = current_pool();
  1353. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1354. pool = cp;
  1355. else
  1356. pool = NULL;
  1357. while (!pool) {
  1358. if (++rotating_pool >= total_pools)
  1359. rotating_pool = 0;
  1360. pool = pools[rotating_pool];
  1361. if ((!pool->idle && pool->enabled) || pool == cp)
  1362. break;
  1363. pool = NULL;
  1364. }
  1365. return pool;
  1366. }
  1367. static bool get_upstream_work(struct work *work, bool lagging)
  1368. {
  1369. struct pool *pool;
  1370. json_t *val;
  1371. bool rc = false;
  1372. CURL *curl;
  1373. curl = curl_easy_init();
  1374. if (unlikely(!curl)) {
  1375. applog(LOG_ERR, "CURL initialisation failed");
  1376. return rc;
  1377. }
  1378. pool = select_pool(lagging);
  1379. if (opt_debug)
  1380. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1381. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1382. want_longpoll, false, &work->rolltime, pool);
  1383. if (unlikely(!val)) {
  1384. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1385. goto out;
  1386. }
  1387. rc = work_decode(json_object_get(val, "result"), work);
  1388. work->pool = pool;
  1389. total_getworks++;
  1390. pool->getwork_requested++;
  1391. if (work->thr)
  1392. work->thr->cgpu->getworks++;
  1393. json_decref(val);
  1394. out:
  1395. curl_easy_cleanup(curl);
  1396. return rc;
  1397. }
  1398. static struct work *make_work(void)
  1399. {
  1400. struct work *work = calloc(1, sizeof(struct work));
  1401. if (unlikely(!work))
  1402. quit(1, "Failed to calloc work in make_work");
  1403. return work;
  1404. }
  1405. static void free_work(struct work *work)
  1406. {
  1407. free(work);
  1408. }
  1409. static void workio_cmd_free(struct workio_cmd *wc)
  1410. {
  1411. if (!wc)
  1412. return;
  1413. switch (wc->cmd) {
  1414. case WC_SUBMIT_WORK:
  1415. free_work(wc->u.work);
  1416. break;
  1417. default: /* do nothing */
  1418. break;
  1419. }
  1420. memset(wc, 0, sizeof(*wc)); /* poison */
  1421. free(wc);
  1422. }
  1423. static void disable_curses(void)
  1424. {
  1425. if (test_and_clear(&curses_active)) {
  1426. leaveok(logwin, false);
  1427. leaveok(statuswin, false);
  1428. leaveok(mainwin, false);
  1429. nocbreak();
  1430. echo();
  1431. delwin(logwin);
  1432. delwin(statuswin);
  1433. delwin(mainwin);
  1434. endwin();
  1435. refresh();
  1436. #ifdef WIN32
  1437. // Move the cursor to after curses output.
  1438. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1439. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1440. COORD coord;
  1441. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1442. coord.X = 0;
  1443. coord.Y = csbi.dwSize.Y - 1;
  1444. SetConsoleCursorPosition(hout, coord);
  1445. }
  1446. #endif
  1447. }
  1448. }
  1449. void kill_work(void)
  1450. {
  1451. struct workio_cmd *wc;
  1452. struct thr_info *thr;
  1453. unsigned int i;
  1454. disable_curses();
  1455. applog(LOG_INFO, "Received kill message");
  1456. /* Kill the watchdog thread */
  1457. thr = &thr_info[watchdog_thr_id];
  1458. pthread_cancel(*thr->pth);
  1459. /* Stop the mining threads*/
  1460. for (i = 0; i < mining_threads; i++) {
  1461. thr = &thr_info[i];
  1462. if (!thr->pth)
  1463. continue;
  1464. tq_freeze(thr->q);
  1465. /* No need to check if this succeeds or not */
  1466. pthread_cancel(*thr->pth);
  1467. }
  1468. /* Stop the others */
  1469. thr = &thr_info[stage_thr_id];
  1470. pthread_cancel(*thr->pth);
  1471. thr = &thr_info[longpoll_thr_id];
  1472. pthread_cancel(*thr->pth);
  1473. wc = calloc(1, sizeof(*wc));
  1474. if (unlikely(!wc)) {
  1475. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  1476. /* We're just trying to die anyway, so forget graceful */
  1477. exit (1);
  1478. }
  1479. wc->cmd = WC_DIE;
  1480. wc->thr = 0;
  1481. if (opt_debug)
  1482. applog(LOG_DEBUG, "Pushing die request to work thread");
  1483. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1484. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  1485. exit (1);
  1486. }
  1487. }
  1488. static void sighandler(int sig)
  1489. {
  1490. /* Restore signal handlers so we can still quit if kill_work fails */
  1491. sigaction(SIGTERM, &termhandler, NULL);
  1492. sigaction(SIGINT, &inthandler, NULL);
  1493. kill_work();
  1494. }
  1495. static void *get_work_thread(void *userdata)
  1496. {
  1497. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1498. struct work *ret_work;
  1499. int failures = 0;
  1500. pthread_detach(pthread_self());
  1501. ret_work = make_work();
  1502. if (wc->thr)
  1503. ret_work->thr = wc->thr;
  1504. else
  1505. ret_work->thr = NULL;
  1506. /* obtain new work from bitcoin via JSON-RPC */
  1507. while (!get_upstream_work(ret_work, wc->lagging)) {
  1508. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1509. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1510. free_work(ret_work);
  1511. kill_work();
  1512. goto out;
  1513. }
  1514. /* pause, then restart work-request loop */
  1515. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1516. opt_fail_pause);
  1517. sleep(opt_fail_pause);
  1518. }
  1519. if (opt_debug)
  1520. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1521. /* send work to requesting thread */
  1522. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1523. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1524. kill_work();
  1525. free_work(ret_work);
  1526. }
  1527. out:
  1528. workio_cmd_free(wc);
  1529. return NULL;
  1530. }
  1531. static bool workio_get_work(struct workio_cmd *wc)
  1532. {
  1533. pthread_t get_thread;
  1534. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1535. applog(LOG_ERR, "Failed to create get_work_thread");
  1536. return false;
  1537. }
  1538. return true;
  1539. }
  1540. static bool stale_work(struct work *work)
  1541. {
  1542. struct timeval now;
  1543. bool ret = false;
  1544. char *hexstr;
  1545. gettimeofday(&now, NULL);
  1546. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1547. return true;
  1548. /* Only use the primary pool for determination as the work may
  1549. * interleave at times of new blocks */
  1550. if (work->pool != current_pool())
  1551. return ret;
  1552. hexstr = bin2hex(work->data, 36);
  1553. if (unlikely(!hexstr)) {
  1554. applog(LOG_ERR, "submit_work_thread OOM");
  1555. return ret;
  1556. }
  1557. if (strncmp(hexstr, current_block, 36))
  1558. ret = true;
  1559. free(hexstr);
  1560. return ret;
  1561. }
  1562. static void *submit_work_thread(void *userdata)
  1563. {
  1564. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1565. struct work *work = wc->u.work;
  1566. struct pool *pool = work->pool;
  1567. int failures = 0;
  1568. pthread_detach(pthread_self());
  1569. if (!opt_submit_stale && stale_work(work)) {
  1570. applog(LOG_WARNING, "Stale share detected, discarding");
  1571. total_stale++;
  1572. pool->stale_shares++;
  1573. goto out;
  1574. }
  1575. /* submit solution to bitcoin via JSON-RPC */
  1576. while (!submit_upstream_work(work)) {
  1577. if (!opt_submit_stale && stale_work(work)) {
  1578. applog(LOG_WARNING, "Stale share detected, discarding");
  1579. total_stale++;
  1580. pool->stale_shares++;
  1581. break;
  1582. }
  1583. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1584. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1585. kill_work();
  1586. break;
  1587. }
  1588. /* pause, then restart work-request loop */
  1589. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1590. opt_fail_pause);
  1591. sleep(opt_fail_pause);
  1592. }
  1593. out:
  1594. workio_cmd_free(wc);
  1595. return NULL;
  1596. }
  1597. static bool workio_submit_work(struct workio_cmd *wc)
  1598. {
  1599. pthread_t submit_thread;
  1600. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1601. applog(LOG_ERR, "Failed to create submit_work_thread");
  1602. return false;
  1603. }
  1604. return true;
  1605. }
  1606. static void inc_staged(struct pool *pool, int inc, bool lp)
  1607. {
  1608. mutex_lock(&stgd_lock);
  1609. if (lp) {
  1610. lp_staged += inc;
  1611. total_staged += inc;
  1612. } else if (lp_staged)
  1613. --lp_staged;
  1614. else
  1615. total_staged += inc;
  1616. mutex_unlock(&stgd_lock);
  1617. }
  1618. static void dec_staged(int inc)
  1619. {
  1620. mutex_lock(&stgd_lock);
  1621. total_staged -= inc;
  1622. mutex_unlock(&stgd_lock);
  1623. }
  1624. static int requests_staged(void)
  1625. {
  1626. int ret;
  1627. mutex_lock(&stgd_lock);
  1628. ret = total_staged;
  1629. mutex_unlock(&stgd_lock);
  1630. return ret;
  1631. }
  1632. static int real_staged(void)
  1633. {
  1634. int ret;
  1635. mutex_lock(&stgd_lock);
  1636. ret = total_staged - lp_staged;
  1637. mutex_unlock(&stgd_lock);
  1638. return ret;
  1639. }
  1640. /* Find the pool that currently has the highest priority */
  1641. static struct pool *priority_pool(int choice)
  1642. {
  1643. struct pool *ret = NULL;
  1644. int i;
  1645. for (i = 0; i < total_pools; i++) {
  1646. struct pool *pool = pools[i];
  1647. if (pool->prio == choice) {
  1648. ret = pool;
  1649. break;
  1650. }
  1651. }
  1652. if (unlikely(!ret)) {
  1653. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1654. return pools[choice];
  1655. }
  1656. return ret;
  1657. }
  1658. static void restart_longpoll(void);
  1659. static void switch_pools(struct pool *selected)
  1660. {
  1661. struct pool *pool, *last_pool;
  1662. int i, pool_no;
  1663. mutex_lock(&control_lock);
  1664. last_pool = currentpool;
  1665. pool_no = currentpool->pool_no;
  1666. /* Switch selected to pool number 0 and move the rest down */
  1667. if (selected) {
  1668. if (selected->prio != 0) {
  1669. for (i = 0; i < total_pools; i++) {
  1670. pool = pools[i];
  1671. if (pool->prio < selected->prio)
  1672. pool->prio++;
  1673. }
  1674. selected->prio = 0;
  1675. }
  1676. }
  1677. switch (pool_strategy) {
  1678. /* Both of these set to the master pool */
  1679. case POOL_FAILOVER:
  1680. case POOL_LOADBALANCE:
  1681. for (i = 0; i < total_pools; i++) {
  1682. pool = priority_pool(i);
  1683. if (!pool->idle && pool->enabled) {
  1684. pool_no = pool->pool_no;
  1685. break;
  1686. }
  1687. }
  1688. break;
  1689. /* Both of these simply increment and cycle */
  1690. case POOL_ROUNDROBIN:
  1691. case POOL_ROTATE:
  1692. if (selected) {
  1693. pool_no = selected->pool_no;
  1694. break;
  1695. }
  1696. pool_no++;
  1697. if (pool_no >= total_pools)
  1698. pool_no = 0;
  1699. break;
  1700. default:
  1701. break;
  1702. }
  1703. currentpool = pools[pool_no];
  1704. pool = currentpool;
  1705. mutex_unlock(&control_lock);
  1706. if (pool != last_pool) {
  1707. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1708. restart_longpoll();
  1709. }
  1710. /* Reset the queued amount to allow more to be queued for the new pool */
  1711. mutex_lock(&qd_lock);
  1712. total_queued = 0;
  1713. mutex_unlock(&qd_lock);
  1714. inc_staged(pool, 1, true);
  1715. }
  1716. static void set_curblock(char *hexstr, unsigned char *hash)
  1717. {
  1718. unsigned char hash_swap[32];
  1719. char *old_hash = NULL;
  1720. struct timeval tv_now;
  1721. /* Don't free current_hash directly to avoid dereferencing it when
  1722. * we might be accessing its data elsewhere */
  1723. if (current_hash)
  1724. old_hash = current_hash;
  1725. memcpy(current_block, hexstr, 36);
  1726. gettimeofday(&tv_now, NULL);
  1727. get_timestamp(blocktime, &tv_now);
  1728. swap256(hash_swap, hash);
  1729. current_hash = bin2hex(hash_swap, 16);
  1730. if (unlikely(!current_hash))
  1731. quit (1, "set_curblock OOM");
  1732. if (old_hash)
  1733. free(old_hash);
  1734. }
  1735. static void test_work_current(struct work *work)
  1736. {
  1737. char *hexstr;
  1738. /* Only use the primary pool for determination */
  1739. if (work->pool != current_pool() || work->cloned || work->rolls || work->clone)
  1740. return;
  1741. hexstr = bin2hex(work->data, 36);
  1742. if (unlikely(!hexstr)) {
  1743. applog(LOG_ERR, "stage_thread OOM");
  1744. return;
  1745. }
  1746. /* current_block is blanked out on successful longpoll */
  1747. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1748. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1749. block_changed = BLOCK_DETECT;
  1750. new_blocks++;
  1751. if (have_longpoll)
  1752. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1753. else
  1754. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1755. /* As we can't flush the work from here, signal the
  1756. * wakeup thread to restart all the threads */
  1757. work_restart[watchdog_thr_id].restart = 1;
  1758. } else
  1759. block_changed = BLOCK_NONE;
  1760. set_curblock(hexstr, work->data);
  1761. }
  1762. free(hexstr);
  1763. }
  1764. static void *stage_thread(void *userdata)
  1765. {
  1766. struct thr_info *mythr = userdata;
  1767. bool ok = true;
  1768. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1769. while (ok) {
  1770. struct work *work = NULL;
  1771. if (opt_debug)
  1772. applog(LOG_DEBUG, "Popping work to stage thread");
  1773. work = tq_pop(mythr->q, NULL);
  1774. if (unlikely(!work)) {
  1775. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1776. ok = false;
  1777. break;
  1778. }
  1779. test_work_current(work);
  1780. if (opt_debug)
  1781. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1782. if (unlikely(!tq_push(getq, work))) {
  1783. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1784. ok = false;
  1785. break;
  1786. }
  1787. inc_staged(work->pool, 1, false);
  1788. }
  1789. tq_freeze(mythr->q);
  1790. return NULL;
  1791. }
  1792. static char *curses_input(const char *query);
  1793. static int curses_int(const char *query)
  1794. {
  1795. int ret;
  1796. char *cvar;
  1797. cvar = curses_input(query);
  1798. ret = atoi(cvar);
  1799. free(cvar);
  1800. return ret;
  1801. }
  1802. static bool input_pool(bool live);
  1803. static int active_pools(void)
  1804. {
  1805. int ret = 0;
  1806. int i;
  1807. for (i = 0; i < total_pools; i++) {
  1808. if ((pools[i])->enabled)
  1809. ret++;
  1810. }
  1811. return ret;
  1812. }
  1813. static void display_pool_summary(struct pool *pool)
  1814. {
  1815. double efficiency = 0.0;
  1816. mutex_lock(&curses_lock);
  1817. wlog("Pool: %s\n", pool->rpc_url);
  1818. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1819. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1820. wlog(" Accepted shares: %d\n", pool->accepted);
  1821. wlog(" Rejected shares: %d\n", pool->rejected);
  1822. if (pool->accepted || pool->rejected)
  1823. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1824. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1825. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1826. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1827. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1828. wlog(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1829. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1830. wrefresh(logwin);
  1831. mutex_unlock(&curses_lock);
  1832. }
  1833. /* We can't remove the memory used for this struct pool because there may
  1834. * still be work referencing it. We just remove it from the pools list */
  1835. static void remove_pool(struct pool *pool)
  1836. {
  1837. int i, last_pool = total_pools - 1;
  1838. struct pool *other;
  1839. /* Boost priority of any lower prio than this one */
  1840. for (i = 0; i < total_pools; i++) {
  1841. other = pools[i];
  1842. if (other->prio > pool->prio)
  1843. other->prio--;
  1844. }
  1845. if (pool->pool_no < last_pool) {
  1846. /* Swap the last pool for this one */
  1847. (pools[last_pool])->pool_no = pool->pool_no;
  1848. pools[pool->pool_no] = pools[last_pool];
  1849. }
  1850. /* Give it an invalid number */
  1851. pool->pool_no = total_pools;
  1852. total_pools--;
  1853. }
  1854. static void display_pools(void)
  1855. {
  1856. struct pool *pool;
  1857. int selected, i;
  1858. char input;
  1859. opt_loginput = true;
  1860. immedok(logwin, true);
  1861. updated:
  1862. clear_logwin();
  1863. for (i = 0; i < total_pools; i++) {
  1864. pool = pools[i];
  1865. if (pool == current_pool())
  1866. wattron(logwin, A_BOLD);
  1867. if (!pool->enabled)
  1868. wattron(logwin, A_DIM);
  1869. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  1870. pool->pool_no,
  1871. pool->enabled? "Enabled" : "Disabled",
  1872. pool->idle? "Dead" : "Alive",
  1873. pool->prio,
  1874. pool->rpc_url, pool->rpc_user);
  1875. wattroff(logwin, A_BOLD | A_DIM);
  1876. }
  1877. retry:
  1878. wlogprint("\nCurrent pool management strategy: %s\n",
  1879. strategies[pool_strategy]);
  1880. if (pool_strategy == POOL_ROTATE)
  1881. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  1882. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  1883. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  1884. wlogprint("Or press any other key to continue\n");
  1885. input = getch();
  1886. if (!strncasecmp(&input, "a", 1)) {
  1887. input_pool(true);
  1888. goto updated;
  1889. } else if (!strncasecmp(&input, "r", 1)) {
  1890. if (total_pools <= 1) {
  1891. wlogprint("Cannot remove last pool");
  1892. goto retry;
  1893. }
  1894. selected = curses_int("Select pool number");
  1895. if (selected < 0 || selected >= total_pools) {
  1896. wlogprint("Invalid selection\n");
  1897. goto retry;
  1898. }
  1899. pool = pools[selected];
  1900. if (pool == current_pool())
  1901. switch_pools(NULL);
  1902. if (pool == current_pool()) {
  1903. wlogprint("Unable to remove pool due to activity\n");
  1904. goto retry;
  1905. }
  1906. pool->enabled = false;
  1907. remove_pool(pool);
  1908. goto updated;
  1909. } else if (!strncasecmp(&input, "s", 1)) {
  1910. selected = curses_int("Select pool number");
  1911. if (selected < 0 || selected >= total_pools) {
  1912. wlogprint("Invalid selection\n");
  1913. goto retry;
  1914. }
  1915. pool = pools[selected];
  1916. pool->enabled = true;
  1917. switch_pools(pool);
  1918. goto updated;
  1919. } else if (!strncasecmp(&input, "d", 1)) {
  1920. if (active_pools() <= 1) {
  1921. wlogprint("Cannot disable last pool");
  1922. goto retry;
  1923. }
  1924. selected = curses_int("Select pool number");
  1925. if (selected < 0 || selected >= total_pools) {
  1926. wlogprint("Invalid selection\n");
  1927. goto retry;
  1928. }
  1929. pool = pools[selected];
  1930. pool->enabled = false;
  1931. if (pool == current_pool())
  1932. switch_pools(NULL);
  1933. goto updated;
  1934. } else if (!strncasecmp(&input, "e", 1)) {
  1935. selected = curses_int("Select pool number");
  1936. if (selected < 0 || selected >= total_pools) {
  1937. wlogprint("Invalid selection\n");
  1938. goto retry;
  1939. }
  1940. pool = pools[selected];
  1941. pool->enabled = true;
  1942. if (pool->prio < current_pool()->prio)
  1943. switch_pools(pool);
  1944. goto updated;
  1945. } else if (!strncasecmp(&input, "c", 1)) {
  1946. for (i = 0; i <= TOP_STRATEGY; i++)
  1947. wlogprint("%d: %s\n", i, strategies[i]);
  1948. selected = curses_int("Select strategy number type");
  1949. if (selected < 0 || selected > TOP_STRATEGY) {
  1950. wlogprint("Invalid selection\n");
  1951. goto retry;
  1952. }
  1953. if (selected == POOL_ROTATE) {
  1954. opt_rotate_period = curses_int("Select interval in minutes");
  1955. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  1956. opt_rotate_period = 0;
  1957. wlogprint("Invalid selection\n");
  1958. goto retry;
  1959. }
  1960. }
  1961. pool_strategy = selected;
  1962. switch_pools(NULL);
  1963. goto updated;
  1964. } else if (!strncasecmp(&input, "i", 1)) {
  1965. selected = curses_int("Select pool number");
  1966. if (selected < 0 || selected >= total_pools) {
  1967. wlogprint("Invalid selection\n");
  1968. goto retry;
  1969. }
  1970. pool = pools[selected];
  1971. display_pool_summary(pool);
  1972. goto retry;
  1973. }
  1974. clear_logwin();
  1975. immedok(logwin, false);
  1976. opt_loginput = false;
  1977. }
  1978. static void display_options(void)
  1979. {
  1980. int selected;
  1981. char input;
  1982. opt_loginput = true;
  1983. immedok(logwin, true);
  1984. retry:
  1985. clear_logwin();
  1986. wlogprint("\n[D]ebug:%s [Q]uiet:%s [V]erbose:%s [R]PC debug:%s [L]og interval:%d\n",
  1987. opt_debug ? "on" : "off",
  1988. opt_quiet ? "on" : "off",
  1989. opt_log_output ? "on" : "off",
  1990. opt_protocol ? "on" : "off",
  1991. opt_log_interval);
  1992. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  1993. wlogprint("Select an option or any other key to return\n");
  1994. input = getch();
  1995. if (!strncasecmp(&input, "q", 1)) {
  1996. opt_quiet ^= true;
  1997. clear_logwin();
  1998. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  1999. } else if (!strncasecmp(&input, "v", 1)) {
  2000. opt_log_output ^= true;
  2001. if (opt_log_output)
  2002. opt_quiet = false;
  2003. clear_logwin();
  2004. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2005. } else if (!strncasecmp(&input, "n", 1)) {
  2006. opt_log_output = false;
  2007. opt_debug = false;
  2008. opt_quiet = false;
  2009. opt_protocol = false;
  2010. clear_logwin();
  2011. wlogprint("Output mode reset to normal\n");
  2012. } else if (!strncasecmp(&input, "d", 1)) {
  2013. opt_debug ^= true;
  2014. if (opt_debug) {
  2015. opt_log_output = true;
  2016. opt_quiet = false;
  2017. }
  2018. clear_logwin();
  2019. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2020. } else if (!strncasecmp(&input, "r", 1)) {
  2021. opt_protocol ^= true;
  2022. if (opt_protocol)
  2023. opt_quiet = false;
  2024. clear_logwin();
  2025. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2026. } else if (!strncasecmp(&input, "c", 1))
  2027. clear_logwin();
  2028. else if (!strncasecmp(&input, "l", 1)) {
  2029. selected = curses_int("Interval in seconds");
  2030. if (selected < 0 || selected > 9999) {
  2031. wlogprint("Invalid selection\n");
  2032. goto retry;
  2033. }
  2034. opt_log_interval = selected;
  2035. clear_logwin();
  2036. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2037. } else if (!strncasecmp(&input, "s", 1)) {
  2038. opt_realquiet = true;
  2039. clear_logwin();
  2040. } else clear_logwin();
  2041. immedok(logwin, false);
  2042. opt_loginput = false;
  2043. }
  2044. static void set_options(void)
  2045. {
  2046. int selected;
  2047. char input;
  2048. opt_loginput = true;
  2049. immedok(logwin, true);
  2050. retry:
  2051. clear_logwin();
  2052. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  2053. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  2054. if (opt_dynamic)
  2055. wlogprint("[I]ntensity: Dynamic\n");
  2056. else
  2057. wlogprint("[I]ntensity: %d\n", scan_intensity);
  2058. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  2059. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  2060. wlogprint("Select an option or any other key to return\n");
  2061. input = getch();
  2062. if (!strncasecmp(&input, "q", 1)) {
  2063. selected = curses_int("Extra work items to queue");
  2064. if (selected < 0 || selected > 9999) {
  2065. wlogprint("Invalid selection\n");
  2066. goto retry;
  2067. }
  2068. opt_queue = selected;
  2069. goto retry;
  2070. } else if (!strncasecmp(&input, "d", 1)) {
  2071. opt_dynamic ^= true;
  2072. goto retry;
  2073. } else if (!strncasecmp(&input, "l", 1)) {
  2074. want_longpoll ^= true;
  2075. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2076. restart_longpoll();
  2077. goto retry;
  2078. } else if (!strncasecmp(&input, "i", 1)) {
  2079. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  2080. if (selected < -10 || selected > 10) {
  2081. wlogprint("Invalid selection\n");
  2082. goto retry;
  2083. }
  2084. opt_dynamic = false;
  2085. scan_intensity = selected;
  2086. goto retry;
  2087. } else if (!strncasecmp(&input, "s", 1)) {
  2088. selected = curses_int("Set scantime in seconds");
  2089. if (selected < 0 || selected > 9999) {
  2090. wlogprint("Invalid selection\n");
  2091. goto retry;
  2092. }
  2093. opt_scantime = selected;
  2094. goto retry;
  2095. } else if (!strncasecmp(&input, "r", 1)) {
  2096. selected = curses_int("Retries before failing (-1 infinite)");
  2097. if (selected < -1 || selected > 9999) {
  2098. wlogprint("Invalid selection\n");
  2099. goto retry;
  2100. }
  2101. opt_retries = selected;
  2102. goto retry;
  2103. } else if (!strncasecmp(&input, "p", 1)) {
  2104. selected = curses_int("Seconds to pause before network retries");
  2105. if (selected < 1 || selected > 9999) {
  2106. wlogprint("Invalid selection\n");
  2107. goto retry;
  2108. }
  2109. opt_fail_pause = selected;
  2110. goto retry;
  2111. }
  2112. clear_logwin();
  2113. immedok(logwin, false);
  2114. opt_loginput = false;
  2115. }
  2116. #ifdef HAVE_OPENCL
  2117. static void reinit_device(struct cgpu_info *cgpu);
  2118. static void manage_gpu(void)
  2119. {
  2120. struct thr_info *thr;
  2121. int selected, gpu, i;
  2122. char checkin[40];
  2123. char input;
  2124. if (!opt_g_threads)
  2125. return;
  2126. opt_loginput = true;
  2127. immedok(logwin, true);
  2128. clear_logwin();
  2129. retry:
  2130. for (gpu = 0; gpu < nDevs; gpu++) {
  2131. struct cgpu_info *cgpu = &gpus[gpu];
  2132. wlog("GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  2133. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  2134. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  2135. cgpu->efficiency, cgpu->utility);
  2136. wlog("Last initialised: %s\n", cgpu->init);
  2137. for (i = 0; i < mining_threads; i++) {
  2138. thr = &thr_info[i];
  2139. if (thr->cgpu != cgpu)
  2140. continue;
  2141. get_datestamp(checkin, &thr->last);
  2142. switch (cgpu->status) {
  2143. case LIFE_WELL:
  2144. wlog("Thread %d: %.1f Mh/s %s ALIVE\n", i,
  2145. thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  2146. break;
  2147. case LIFE_SICK:
  2148. wlog("Thread %d: %.1f Mh/s %s SICK reported in %s\n", i,
  2149. thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled",
  2150. checkin);
  2151. break;
  2152. case LIFE_DEAD:
  2153. wlog("Thread %d: %.1f Mh/s %s DEAD reported in %s\n", i,
  2154. thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled",
  2155. checkin);
  2156. break;
  2157. }
  2158. }
  2159. }
  2160. wlogprint("[E]nable [D]isable [R]estart GPU\n");
  2161. wlogprint("Or press any other key to continue\n");
  2162. input = getch();
  2163. if (!strncasecmp(&input, "e", 1)) {
  2164. selected = curses_int("Select GPU to enable");
  2165. if (selected < 0 || selected >= nDevs) {
  2166. wlogprint("Invalid selection\n");
  2167. goto retry;
  2168. }
  2169. if (gpu_devices[selected]) {
  2170. wlogprint("Device already enabled\n");
  2171. goto retry;
  2172. }
  2173. gpu_devices[selected] = true;
  2174. for (i = 0; i < gpu_threads; i++) {
  2175. if (dev_from_id(i) != selected)
  2176. continue;
  2177. thr = &thr_info[i];
  2178. if (opt_debug)
  2179. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  2180. tq_push(thr->q, &ping);
  2181. }
  2182. } if (!strncasecmp(&input, "d", 1)) {
  2183. selected = curses_int("Select GPU to disable");
  2184. if (selected < 0 || selected >= nDevs) {
  2185. wlogprint("Invalid selection\n");
  2186. goto retry;
  2187. }
  2188. if (!gpu_devices[selected]) {
  2189. wlogprint("Device already disabled\n");
  2190. goto retry;
  2191. }
  2192. gpu_devices[selected] = false;
  2193. } else if (!strncasecmp(&input, "r", 1)) {
  2194. selected = curses_int("Select GPU to attempt to restart");
  2195. if (selected < 0 || selected >= nDevs) {
  2196. wlogprint("Invalid selection\n");
  2197. goto retry;
  2198. }
  2199. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  2200. reinit_device(&gpus[selected]);
  2201. }
  2202. clear_logwin();
  2203. immedok(logwin, false);
  2204. opt_loginput = false;
  2205. }
  2206. #else
  2207. static void manage_gpu(void)
  2208. {
  2209. }
  2210. #endif
  2211. static void *input_thread(void *userdata)
  2212. {
  2213. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2214. if (!curses_active)
  2215. return NULL;
  2216. while (1) {
  2217. char input;
  2218. input = getch();
  2219. if (!strncasecmp(&input, "q", 1)) {
  2220. kill_work();
  2221. return NULL;
  2222. } else if (!strncasecmp(&input, "d", 1))
  2223. display_options();
  2224. else if (!strncasecmp(&input, "p", 1))
  2225. display_pools();
  2226. else if (!strncasecmp(&input, "s", 1))
  2227. set_options();
  2228. else if (!strncasecmp(&input, "g", 1))
  2229. manage_gpu();
  2230. if (opt_realquiet) {
  2231. disable_curses();
  2232. break;
  2233. }
  2234. }
  2235. return NULL;
  2236. }
  2237. static void *workio_thread(void *userdata)
  2238. {
  2239. struct thr_info *mythr = userdata;
  2240. bool ok = true;
  2241. while (ok) {
  2242. struct workio_cmd *wc;
  2243. if (opt_debug)
  2244. applog(LOG_DEBUG, "Popping work to work thread");
  2245. /* wait for workio_cmd sent to us, on our queue */
  2246. wc = tq_pop(mythr->q, NULL);
  2247. if (unlikely(!wc)) {
  2248. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2249. ok = false;
  2250. break;
  2251. }
  2252. /* process workio_cmd */
  2253. switch (wc->cmd) {
  2254. case WC_GET_WORK:
  2255. ok = workio_get_work(wc);
  2256. break;
  2257. case WC_SUBMIT_WORK:
  2258. ok = workio_submit_work(wc);
  2259. break;
  2260. case WC_DIE:
  2261. default:
  2262. ok = false;
  2263. break;
  2264. }
  2265. }
  2266. tq_freeze(mythr->q);
  2267. return NULL;
  2268. }
  2269. static void thread_reportin(struct thr_info *thr)
  2270. {
  2271. gettimeofday(&thr->last, NULL);
  2272. thr->cgpu->status = LIFE_WELL;
  2273. thr->getwork = false;
  2274. }
  2275. static inline void thread_reportout(struct thr_info *thr)
  2276. {
  2277. thr->getwork = true;
  2278. }
  2279. static void hashmeter(int thr_id, struct timeval *diff,
  2280. unsigned long hashes_done)
  2281. {
  2282. struct timeval temp_tv_end, total_diff;
  2283. double secs;
  2284. double local_secs;
  2285. double utility, efficiency = 0.0;
  2286. static double local_mhashes_done = 0;
  2287. static double rolling = 0;
  2288. double local_mhashes = (double)hashes_done / 1000000.0;
  2289. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2290. bool showlog = false;
  2291. /* Update the last time this thread reported in */
  2292. if (thr_id >= 0)
  2293. gettimeofday(&thr_info[thr_id].last, NULL);
  2294. /* Don't bother calculating anything if we're not displaying it */
  2295. if (opt_realquiet || !opt_log_interval)
  2296. return;
  2297. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2298. /* So we can call hashmeter from a non worker thread */
  2299. if (thr_id >= 0) {
  2300. struct thr_info *thr = &thr_info[thr_id];
  2301. double thread_rolling = 0.0;
  2302. int i;
  2303. if (opt_debug)
  2304. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2305. thr_id, hashes_done, hashes_done / secs);
  2306. /* Rolling average for each thread and each device */
  2307. decay_time(&thr->rolling, local_mhashes / secs);
  2308. for (i = 0; i < mining_threads; i++) {
  2309. struct thr_info *th = &thr_info[i];
  2310. if (th->cgpu == cgpu)
  2311. thread_rolling += th->rolling;
  2312. }
  2313. decay_time(&cgpu->rolling, thread_rolling);
  2314. cgpu->total_mhashes += local_mhashes;
  2315. }
  2316. /* Totals are updated by all threads so can race without locking */
  2317. mutex_lock(&hash_lock);
  2318. gettimeofday(&temp_tv_end, NULL);
  2319. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2320. total_mhashes_done += local_mhashes;
  2321. local_mhashes_done += local_mhashes;
  2322. if (total_diff.tv_sec < opt_log_interval)
  2323. /* Only update the total every opt_log_interval seconds */
  2324. goto out_unlock;
  2325. showlog = true;
  2326. gettimeofday(&total_tv_end, NULL);
  2327. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2328. decay_time(&rolling, local_mhashes_done / local_secs);
  2329. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2330. total_secs = (double)total_diff.tv_sec +
  2331. ((double)total_diff.tv_usec / 1000000.0);
  2332. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2333. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2334. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2335. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2336. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2337. local_mhashes_done = 0;
  2338. out_unlock:
  2339. mutex_unlock(&hash_lock);
  2340. if (showlog) {
  2341. if (!curses_active) {
  2342. printf("%s \r", statusline);
  2343. fflush(stdout);
  2344. } else
  2345. applog(LOG_INFO, "%s", statusline);
  2346. }
  2347. }
  2348. /* This is overkill, but at least we'll know accurately how much work is
  2349. * queued to prevent ever being left without work */
  2350. static void inc_queued(void)
  2351. {
  2352. mutex_lock(&qd_lock);
  2353. total_queued++;
  2354. mutex_unlock(&qd_lock);
  2355. }
  2356. static void dec_queued(void)
  2357. {
  2358. mutex_lock(&qd_lock);
  2359. if (total_queued > 0)
  2360. total_queued--;
  2361. mutex_unlock(&qd_lock);
  2362. dec_staged(1);
  2363. }
  2364. static int requests_queued(void)
  2365. {
  2366. int ret;
  2367. mutex_lock(&qd_lock);
  2368. ret = total_queued;
  2369. mutex_unlock(&qd_lock);
  2370. return ret;
  2371. }
  2372. static bool pool_active(struct pool *pool, bool pinging)
  2373. {
  2374. bool ret = false;
  2375. json_t *val;
  2376. CURL *curl;
  2377. bool rolltime;
  2378. curl = curl_easy_init();
  2379. if (unlikely(!curl)) {
  2380. applog(LOG_ERR, "CURL initialisation failed");
  2381. return false;
  2382. }
  2383. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2384. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2385. true, false, &rolltime, pool);
  2386. if (val) {
  2387. struct work *work = make_work();
  2388. bool rc;
  2389. rc = work_decode(json_object_get(val, "result"), work);
  2390. if (rc) {
  2391. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2392. pool->pool_no, pool->rpc_url);
  2393. work->pool = pool;
  2394. work->rolltime = rolltime;
  2395. if (opt_debug)
  2396. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2397. tq_push(thr_info[stage_thr_id].q, work);
  2398. total_getworks++;
  2399. pool->getwork_requested++;
  2400. inc_queued();
  2401. ret = true;
  2402. gettimeofday(&pool->tv_idle, NULL);
  2403. } else {
  2404. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2405. pool->pool_no, pool->rpc_url);
  2406. free_work(work);
  2407. }
  2408. json_decref(val);
  2409. } else {
  2410. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2411. pool->pool_no, pool->rpc_url);
  2412. if (!pinging)
  2413. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  2414. }
  2415. curl_easy_cleanup(curl);
  2416. return ret;
  2417. }
  2418. static void pool_died(struct pool *pool)
  2419. {
  2420. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2421. gettimeofday(&pool->tv_idle, NULL);
  2422. switch_pools(NULL);
  2423. }
  2424. static void pool_resus(struct pool *pool)
  2425. {
  2426. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  2427. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  2428. switch_pools(NULL);
  2429. }
  2430. static bool queue_request(struct thr_info *thr, bool needed)
  2431. {
  2432. int maxq = opt_queue + mining_threads;
  2433. struct workio_cmd *wc;
  2434. int rq, rs;
  2435. rq = requests_queued();
  2436. rs = real_staged();
  2437. /* If we've been generating lots of local work we may already have
  2438. * enough in the queue */
  2439. if (rq >= maxq || rs >= maxq)
  2440. return true;
  2441. /* fill out work request message */
  2442. wc = calloc(1, sizeof(*wc));
  2443. if (unlikely(!wc)) {
  2444. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2445. return false;
  2446. }
  2447. wc->cmd = WC_GET_WORK;
  2448. if (thr)
  2449. wc->thr = thr;
  2450. else
  2451. wc->thr = NULL;
  2452. /* If we're queueing work faster than we can stage it, consider the
  2453. * system lagging and allow work to be gathered from another pool if
  2454. * possible */
  2455. if (!rs && rq && needed)
  2456. wc->lagging = true;
  2457. if (opt_debug)
  2458. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2459. /* send work request to workio thread */
  2460. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2461. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2462. workio_cmd_free(wc);
  2463. return false;
  2464. }
  2465. inc_queued();
  2466. return true;
  2467. }
  2468. static void discard_work(struct work *work)
  2469. {
  2470. if (!work->clone && !work->rolls && !work->mined) {
  2471. if (work->pool)
  2472. work->pool->discarded_work++;
  2473. total_discarded++;
  2474. if (opt_debug)
  2475. applog(LOG_DEBUG, "Discarded work");
  2476. } else if (opt_debug)
  2477. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2478. free_work(work);
  2479. }
  2480. static void discard_staged(void)
  2481. {
  2482. struct timespec abstime = {};
  2483. struct timeval now;
  2484. struct work *work_heap;
  2485. /* Just in case we fell in a hole and missed a queue filling */
  2486. if (unlikely(!requests_staged()))
  2487. return;
  2488. gettimeofday(&now, NULL);
  2489. abstime.tv_sec = now.tv_sec + 60;
  2490. if (opt_debug)
  2491. applog(LOG_DEBUG, "Popping work to discard staged");
  2492. work_heap = tq_pop(getq, &abstime);
  2493. if (unlikely(!work_heap))
  2494. return;
  2495. discard_work(work_heap);
  2496. dec_queued();
  2497. }
  2498. static void flush_requests(void)
  2499. {
  2500. struct pool *pool = current_pool();
  2501. int i, stale;
  2502. /* We should have one fresh work item staged from the block change. */
  2503. stale = requests_staged() - 1;
  2504. /* Temporarily increase the staged count so that get_work thinks there
  2505. * is work available instead of making threads reuse existing work */
  2506. inc_staged(pool, mining_threads, true);
  2507. for (i = 0; i < stale; i++) {
  2508. /* Queue a whole batch of new requests */
  2509. if (unlikely(!queue_request(NULL, true))) {
  2510. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  2511. kill_work();
  2512. break;
  2513. }
  2514. /* Pop off the old requests. Cancelling the requests would be better
  2515. * but is tricky */
  2516. discard_staged();
  2517. }
  2518. }
  2519. static inline bool should_roll(struct work *work)
  2520. {
  2521. int rs;
  2522. rs = real_staged();
  2523. if (rs >= opt_queue + mining_threads)
  2524. return false;
  2525. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  2526. return true;
  2527. return false;
  2528. }
  2529. static inline bool can_roll(struct work *work)
  2530. {
  2531. return (work->pool && !stale_work(work) && work->rolltime &&
  2532. work->rolls < 11 && !work->clone);
  2533. }
  2534. static void roll_work(struct work *work)
  2535. {
  2536. uint32_t *work_ntime;
  2537. uint32_t ntime;
  2538. work_ntime = (uint32_t *)(work->data + 68);
  2539. ntime = be32toh(*work_ntime);
  2540. ntime++;
  2541. *work_ntime = htobe32(ntime);
  2542. local_work++;
  2543. work->rolls++;
  2544. work->blk.nonce = 0;
  2545. if (opt_debug)
  2546. applog(LOG_DEBUG, "Successfully rolled work");
  2547. }
  2548. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  2549. * giving it to will not finish scanning it. We keep the master copy to be
  2550. * recycled more rapidly and discard the clone to avoid repeating work */
  2551. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  2552. {
  2553. uint64_t hash_inc;
  2554. if (work->clone)
  2555. return false;
  2556. hash_inc = MAXTHREADS / hash_div * 2;
  2557. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  2558. /* Okay we can divide it up */
  2559. work->blk.nonce += hash_inc;
  2560. work->cloned = true;
  2561. local_work++;
  2562. if (opt_debug)
  2563. applog(LOG_DEBUG, "Successfully divided work");
  2564. return true;
  2565. } else if (can_roll(work) && should_roll(work)) {
  2566. roll_work(work);
  2567. return true;
  2568. }
  2569. return false;
  2570. }
  2571. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2572. const int thr_id, uint32_t hash_div)
  2573. {
  2574. struct timespec abstime = {};
  2575. struct timeval now;
  2576. struct work *work_heap;
  2577. struct pool *pool;
  2578. bool ret = false;
  2579. int failures = 0;
  2580. /* Tell the watchdog thread this thread is waiting on getwork and
  2581. * should not be restarted */
  2582. thread_reportout(thr);
  2583. retry:
  2584. pool = current_pool();
  2585. if (unlikely(!requested && !queue_request(thr, true))) {
  2586. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2587. goto out;
  2588. }
  2589. requested = false;
  2590. if (!requests_staged() && can_roll(work)) {
  2591. /* Only print this message once each time we shift to localgen */
  2592. if (!pool_tset(pool, &pool->idle)) {
  2593. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  2594. pool->pool_no);
  2595. pool->localgen_occasions++;
  2596. total_lo++;
  2597. gettimeofday(&pool->tv_idle, NULL);
  2598. } else {
  2599. struct timeval tv_now, diff;
  2600. gettimeofday(&tv_now, NULL);
  2601. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  2602. /* Attempt to switch pools if this one has been unresponsive for >half
  2603. * a block's duration */
  2604. if (diff.tv_sec > 300) {
  2605. pool_died(pool);
  2606. goto retry;
  2607. }
  2608. }
  2609. roll_work(work);
  2610. ret = true;
  2611. goto out;
  2612. }
  2613. gettimeofday(&now, NULL);
  2614. abstime.tv_sec = now.tv_sec + 60;
  2615. if (opt_debug)
  2616. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2617. /* wait for 1st response, or get cached response */
  2618. work_heap = tq_pop(getq, &abstime);
  2619. if (unlikely(!work_heap)) {
  2620. /* Attempt to switch pools if this one has mandatory work that
  2621. * has timed out or does not support rolltime */
  2622. pool->localgen_occasions++;
  2623. total_lo++;
  2624. pool_died(pool);
  2625. goto retry;
  2626. }
  2627. if (stale_work(work_heap)) {
  2628. dec_queued();
  2629. discard_work(work_heap);
  2630. goto retry;
  2631. }
  2632. pool = work_heap->pool;
  2633. /* If we make it here we have succeeded in getting fresh work */
  2634. if (pool_tclear(pool, &pool->idle))
  2635. pool_resus(pool);
  2636. memcpy(work, work_heap, sizeof(*work));
  2637. /* Copy the res nonce back so we know to start at a higher baseline
  2638. * should we divide the same work up again. Make the work we're
  2639. * handing out be clone */
  2640. if (divide_work(&now, work_heap, hash_div)) {
  2641. if (opt_debug)
  2642. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2643. tq_push_head(getq, work_heap);
  2644. work->clone = true;
  2645. } else {
  2646. dec_queued();
  2647. free_work(work_heap);
  2648. }
  2649. ret = true;
  2650. out:
  2651. if (unlikely(ret == false)) {
  2652. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2653. applog(LOG_ERR, "Failed %d times to get_work");
  2654. return ret;
  2655. }
  2656. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  2657. sleep(opt_fail_pause);
  2658. goto retry;
  2659. }
  2660. work->thr_id = thr_id;
  2661. thread_reportin(thr);
  2662. if (ret)
  2663. work->mined = true;
  2664. return ret;
  2665. }
  2666. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2667. {
  2668. struct workio_cmd *wc;
  2669. /* fill out work request message */
  2670. wc = calloc(1, sizeof(*wc));
  2671. if (unlikely(!wc)) {
  2672. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2673. return false;
  2674. }
  2675. wc->u.work = make_work();
  2676. wc->cmd = WC_SUBMIT_WORK;
  2677. wc->thr = thr;
  2678. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2679. if (opt_debug)
  2680. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2681. /* send solution to workio thread */
  2682. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2683. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2684. goto err_out;
  2685. }
  2686. return true;
  2687. err_out:
  2688. workio_cmd_free(wc);
  2689. return false;
  2690. }
  2691. struct swa {
  2692. struct thr_info *thr;
  2693. const struct work *work_in;
  2694. };
  2695. static void *swasync_thread(void *userdata)
  2696. {
  2697. struct swa *swa = (struct swa *)userdata;
  2698. /* Return value ignored */
  2699. submit_work_sync(swa->thr, swa->work_in);
  2700. free(swa);
  2701. return NULL;
  2702. }
  2703. static bool submit_work_async(struct thr_info *thr, const struct work *work_in)
  2704. {
  2705. pthread_t sw_thread;
  2706. struct swa *swa;
  2707. swa = malloc(sizeof(struct swa));
  2708. if (unlikely(!swa)) {
  2709. applog(LOG_ERR, "Failed to malloc swa in submit_work_async");
  2710. return false;
  2711. }
  2712. swa->thr = thr;
  2713. swa->work_in = work_in;
  2714. if (unlikely(pthread_create(&sw_thread, NULL, swasync_thread, (void *)swa))) {
  2715. applog(LOG_ERR, "Failed to create swasync_thread");
  2716. return false;
  2717. }
  2718. return true;
  2719. }
  2720. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2721. {
  2722. work->data[64+12+0] = (nonce>>0) & 0xff;
  2723. work->data[64+12+1] = (nonce>>8) & 0xff;
  2724. work->data[64+12+2] = (nonce>>16) & 0xff;
  2725. work->data[64+12+3] = (nonce>>24) & 0xff;
  2726. /* Do one last check before attempting to submit the work */
  2727. if (!fulltest(work->data + 64, work->target))
  2728. return true;
  2729. return submit_work_sync(thr, work);
  2730. }
  2731. static void *miner_thread(void *userdata)
  2732. {
  2733. struct work *work = make_work();
  2734. struct thr_info *mythr = userdata;
  2735. const int thr_id = mythr->id;
  2736. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  2737. unsigned long hashes_done = max_nonce;
  2738. bool needs_work = true;
  2739. /* Try to cycle approximately 5 times before each log update */
  2740. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2741. int request_interval;
  2742. bool requested = false;
  2743. uint32_t hash_div = 1;
  2744. double hash_divfloat = 1.0;
  2745. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2746. /* Request the next work item just before the end of the scantime. We
  2747. * don't want the work lying around too long since the CPU will always
  2748. * spend the full scantime */
  2749. request_interval = opt_scantime - 5;
  2750. if (request_interval < 1)
  2751. request_interval = 1;
  2752. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  2753. * and if that fails, then SCHED_BATCH. No need for this to be an
  2754. * error if it fails */
  2755. setpriority(PRIO_PROCESS, 0, 19);
  2756. drop_policy();
  2757. /* Cpu affinity only makes sense if the number of threads is a multiple
  2758. * of the number of CPUs */
  2759. if (!(opt_n_threads % num_processors))
  2760. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  2761. /* Invalidate pool so it fails can_roll() test */
  2762. work->pool = NULL;
  2763. while (1) {
  2764. struct timeval tv_workstart, tv_start, tv_end, diff;
  2765. uint64_t max64;
  2766. bool rc;
  2767. if (needs_work) {
  2768. gettimeofday(&tv_workstart, NULL);
  2769. /* obtain new work from internal workio thread */
  2770. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2771. applog(LOG_ERR, "work retrieval failed, exiting "
  2772. "mining thread %d", thr_id);
  2773. goto out;
  2774. }
  2775. needs_work = requested = false;
  2776. total_hashes = 0;
  2777. max_nonce = work->blk.nonce + hashes_done;
  2778. }
  2779. hashes_done = 0;
  2780. gettimeofday(&tv_start, NULL);
  2781. /* scan nonces for a proof-of-work hash */
  2782. switch (opt_algo) {
  2783. case ALGO_C:
  2784. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  2785. work->hash1, work->hash, work->target,
  2786. max_nonce, &hashes_done,
  2787. work->blk.nonce);
  2788. break;
  2789. #ifdef WANT_X8664_SSE2
  2790. case ALGO_SSE2_64: {
  2791. unsigned int rc5 =
  2792. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  2793. work->hash1, work->hash,
  2794. work->target,
  2795. max_nonce, &hashes_done,
  2796. work->blk.nonce);
  2797. rc = (rc5 == -1) ? false : true;
  2798. }
  2799. break;
  2800. #endif
  2801. #ifdef WANT_X8664_SSE4
  2802. case ALGO_SSE4_64: {
  2803. unsigned int rc5 =
  2804. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  2805. work->hash1, work->hash,
  2806. work->target,
  2807. max_nonce, &hashes_done,
  2808. work->blk.nonce);
  2809. rc = (rc5 == -1) ? false : true;
  2810. }
  2811. break;
  2812. #endif
  2813. #ifdef WANT_SSE2_4WAY
  2814. case ALGO_4WAY: {
  2815. unsigned int rc4 =
  2816. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  2817. work->hash1, work->hash,
  2818. work->target,
  2819. max_nonce, &hashes_done,
  2820. work->blk.nonce);
  2821. rc = (rc4 == -1) ? false : true;
  2822. }
  2823. break;
  2824. #endif
  2825. #ifdef WANT_VIA_PADLOCK
  2826. case ALGO_VIA:
  2827. rc = scanhash_via(thr_id, work->data, work->target,
  2828. max_nonce, &hashes_done,
  2829. work->blk.nonce);
  2830. break;
  2831. #endif
  2832. case ALGO_CRYPTOPP:
  2833. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  2834. work->hash1, work->hash, work->target,
  2835. max_nonce, &hashes_done,
  2836. work->blk.nonce);
  2837. break;
  2838. #ifdef WANT_CRYPTOPP_ASM32
  2839. case ALGO_CRYPTOPP_ASM32:
  2840. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  2841. work->hash1, work->hash, work->target,
  2842. max_nonce, &hashes_done,
  2843. work->blk.nonce);
  2844. break;
  2845. #endif
  2846. default:
  2847. /* should never happen */
  2848. goto out;
  2849. }
  2850. /* record scanhash elapsed time */
  2851. gettimeofday(&tv_end, NULL);
  2852. timeval_subtract(&diff, &tv_end, &tv_start);
  2853. hashes_done -= work->blk.nonce;
  2854. hashmeter(thr_id, &diff, hashes_done);
  2855. total_hashes += hashes_done;
  2856. work->blk.nonce += hashes_done;
  2857. /* adjust max_nonce to meet target cycle time */
  2858. if (diff.tv_usec > 500000)
  2859. diff.tv_sec++;
  2860. if (diff.tv_sec && diff.tv_sec != cycle) {
  2861. max64 = work->blk.nonce +
  2862. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  2863. } else if (!diff.tv_sec)
  2864. max64 = work->blk.nonce + (hashes_done * 2);
  2865. else
  2866. max64 = work->blk.nonce + hashes_done;
  2867. if (max64 > 0xfffffffaULL)
  2868. max64 = 0xfffffffaULL;
  2869. max_nonce = max64;
  2870. /* if nonce found, submit work */
  2871. if (unlikely(rc)) {
  2872. if (opt_debug)
  2873. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  2874. if (unlikely(!submit_work_async(mythr, work))) {
  2875. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  2876. break;
  2877. }
  2878. work->blk.nonce += 4;
  2879. }
  2880. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2881. if (!requested && (diff.tv_sec >= request_interval)) {
  2882. thread_reportout(mythr);
  2883. if (unlikely(!queue_request(mythr, false))) {
  2884. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2885. goto out;
  2886. }
  2887. thread_reportin(mythr);
  2888. requested = true;
  2889. }
  2890. if (diff.tv_sec > opt_scantime) {
  2891. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  2892. hash_div = hash_divfloat;
  2893. needs_work = true;
  2894. } else if (work_restart[thr_id].restart || stale_work(work) ||
  2895. work->blk.nonce >= MAXTHREADS - hashes_done)
  2896. needs_work = true;
  2897. }
  2898. out:
  2899. thread_reportin(mythr);
  2900. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2901. tq_freeze(mythr->q);
  2902. return NULL;
  2903. }
  2904. enum {
  2905. STAT_SLEEP_INTERVAL = 1,
  2906. STAT_CTR_INTERVAL = 10000000,
  2907. FAILURE_INTERVAL = 30,
  2908. };
  2909. #ifdef HAVE_OPENCL
  2910. static _clState *clStates[16];
  2911. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  2912. {
  2913. cl_kernel *kernel = &clState->kernel;
  2914. cl_int status = 0;
  2915. int num = 0;
  2916. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2917. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2918. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2919. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2920. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2921. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2922. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2923. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2924. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2925. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2926. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  2927. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2928. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2929. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2930. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2931. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  2932. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  2933. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  2934. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  2935. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  2936. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  2937. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  2938. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  2939. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2940. (void *)&clState->outputBuffer);
  2941. return status;
  2942. }
  2943. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  2944. {
  2945. cl_kernel *kernel = &clState->kernel;
  2946. cl_int status = 0;
  2947. int num = 0;
  2948. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2949. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2950. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2951. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2952. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2953. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2954. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2955. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2956. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2957. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2958. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->C1addK5);
  2959. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->D1A);
  2960. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2961. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2962. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2963. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2964. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2A);
  2965. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  2966. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  2967. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17_2);
  2968. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4addT1);
  2969. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1substate0);
  2970. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2971. (void *)&clState->outputBuffer);
  2972. return status;
  2973. }
  2974. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  2975. unsigned int *hashes, size_t *globalThreads,
  2976. unsigned int minthreads)
  2977. {
  2978. *threads = 1 << (15 + scan_intensity);
  2979. if (*threads < minthreads)
  2980. *threads = minthreads;
  2981. *globalThreads = *threads;
  2982. *hashes = *threads * vectors;
  2983. }
  2984. static void *gpuminer_thread(void *userdata)
  2985. {
  2986. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  2987. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2988. struct timeval tv_start, tv_end, diff, tv_workstart;
  2989. struct thr_info *mythr = userdata;
  2990. const int thr_id = mythr->id;
  2991. uint32_t *res, *blank_res;
  2992. double gpu_ms_average = 7;
  2993. int gpu = dev_from_id(thr_id);
  2994. size_t globalThreads[1];
  2995. size_t localThreads[1];
  2996. cl_int status;
  2997. _clState *clState = clStates[thr_id];
  2998. const cl_kernel *kernel = &clState->kernel;
  2999. struct work *work = make_work();
  3000. unsigned int threads;
  3001. unsigned const int vectors = clState->preferred_vwidth;
  3002. unsigned int hashes;
  3003. unsigned int hashes_done = 0;
  3004. /* Request the next work item at 2/3 of the scantime */
  3005. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3006. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3007. bool requested = false;
  3008. uint32_t total_hashes = 0, hash_div = 1;
  3009. switch (chosen_kernel) {
  3010. case KL_POCLBM:
  3011. queue_kernel_parameters = &queue_poclbm_kernel;
  3012. break;
  3013. case KL_PHATK:
  3014. default:
  3015. queue_kernel_parameters = &queue_phatk_kernel;
  3016. break;
  3017. }
  3018. if (opt_dynamic) {
  3019. /* Minimise impact on desktop if we want dynamic mode */
  3020. setpriority(PRIO_PROCESS, 0, 19);
  3021. drop_policy();
  3022. }
  3023. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3024. res = calloc(BUFFERSIZE, 1);
  3025. blank_res = calloc(BUFFERSIZE, 1);
  3026. if (!res || !blank_res) {
  3027. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  3028. goto out;
  3029. }
  3030. gettimeofday(&tv_start, NULL);
  3031. localThreads[0] = clState->work_size;
  3032. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  3033. localThreads[0]);
  3034. diff.tv_sec = 0;
  3035. gettimeofday(&tv_end, NULL);
  3036. work->pool = NULL;
  3037. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  3038. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3039. if (unlikely(status != CL_SUCCESS))
  3040. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3041. mythr->cgpu->status = LIFE_WELL;
  3042. if (opt_debug)
  3043. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  3044. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3045. gettimeofday(&tv_workstart, NULL);
  3046. /* obtain new work from internal workio thread */
  3047. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3048. applog(LOG_ERR, "work retrieval failed, exiting "
  3049. "gpu mining thread %d", thr_id);
  3050. goto out;
  3051. }
  3052. requested = false;
  3053. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3054. work->blk.nonce = 0;
  3055. while (1) {
  3056. struct timeval tv_gpustart, tv_gpuend;
  3057. suseconds_t gpu_us;
  3058. gettimeofday(&tv_gpustart, NULL);
  3059. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  3060. /* This finish flushes the readbuffer set with CL_FALSE later */
  3061. clFinish(clState->commandQueue);
  3062. gettimeofday(&tv_gpuend, NULL);
  3063. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  3064. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  3065. decay_time(&gpu_ms_average, gpu_us / 1000);
  3066. if (opt_dynamic) {
  3067. /* Try to not let the GPU be out for longer than 6ms, but
  3068. * increase intensity when the system is idle, unless
  3069. * dynamic is disabled. */
  3070. if (gpu_ms_average > 7) {
  3071. if (scan_intensity > -10)
  3072. scan_intensity--;
  3073. } else if (gpu_ms_average < 3) {
  3074. if (scan_intensity < 10)
  3075. scan_intensity++;
  3076. }
  3077. }
  3078. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  3079. if (diff.tv_sec > opt_scantime ||
  3080. work->blk.nonce >= MAXTHREADS - hashes ||
  3081. work_restart[thr_id].restart ||
  3082. stale_work(work)) {
  3083. /* Ignore any reads since we're getting new work and queue a clean buffer */
  3084. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3085. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3086. if (unlikely(status != CL_SUCCESS))
  3087. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3088. memset(res, 0, BUFFERSIZE);
  3089. gettimeofday(&tv_workstart, NULL);
  3090. if (opt_debug)
  3091. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  3092. /* obtain new work from internal workio thread */
  3093. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3094. applog(LOG_ERR, "work retrieval failed, exiting "
  3095. "gpu mining thread %d", thr_id);
  3096. goto out;
  3097. }
  3098. requested = false;
  3099. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3100. work_restart[thr_id].restart = 0;
  3101. /* Flushes the writebuffer set with CL_FALSE above */
  3102. clFinish(clState->commandQueue);
  3103. }
  3104. status = queue_kernel_parameters(clState, &work->blk);
  3105. if (unlikely(status != CL_SUCCESS))
  3106. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  3107. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  3108. if (res[MAXBUFFERS]) {
  3109. /* Clear the buffer again */
  3110. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3111. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3112. if (unlikely(status != CL_SUCCESS))
  3113. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3114. if (opt_debug)
  3115. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  3116. postcalc_hash_async(mythr, work, res);
  3117. memset(res, 0, BUFFERSIZE);
  3118. clFinish(clState->commandQueue);
  3119. }
  3120. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  3121. globalThreads, localThreads, 0, NULL, NULL);
  3122. if (unlikely(status != CL_SUCCESS))
  3123. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  3124. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3125. BUFFERSIZE, res, 0, NULL, NULL);
  3126. if (unlikely(status != CL_SUCCESS))
  3127. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  3128. gettimeofday(&tv_end, NULL);
  3129. timeval_subtract(&diff, &tv_end, &tv_start);
  3130. hashes_done += hashes;
  3131. total_hashes += hashes;
  3132. work->blk.nonce += hashes;
  3133. if (diff.tv_sec >= cycle) {
  3134. hashmeter(thr_id, &diff, hashes_done);
  3135. gettimeofday(&tv_start, NULL);
  3136. hashes_done = 0;
  3137. }
  3138. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3139. if (!requested) {
  3140. #if 0
  3141. if (diff.tv_sec > request_interval)
  3142. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  3143. #endif
  3144. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3145. thread_reportout(mythr);
  3146. if (unlikely(!queue_request(mythr, false))) {
  3147. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  3148. goto out;
  3149. }
  3150. thread_reportin(mythr);
  3151. requested = true;
  3152. }
  3153. }
  3154. if (unlikely(!gpu_devices[gpu])) {
  3155. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3156. mythr->rolling = mythr->cgpu->rolling = 0;
  3157. if (opt_debug)
  3158. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  3159. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3160. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3161. }
  3162. }
  3163. out:
  3164. thread_reportin(mythr);
  3165. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3166. tq_freeze(mythr->q);
  3167. return NULL;
  3168. }
  3169. #endif /* HAVE_OPENCL */
  3170. static void restart_threads(void)
  3171. {
  3172. int i;
  3173. if (block_changed == BLOCK_DETECT)
  3174. block_changed = BLOCK_NONE;
  3175. /* Discard old queued requests and get new ones */
  3176. flush_requests();
  3177. for (i = 0; i < mining_threads; i++)
  3178. work_restart[i].restart = 1;
  3179. }
  3180. /* Stage another work item from the work returned in a longpoll */
  3181. static void convert_to_work(json_t *val, bool rolltime)
  3182. {
  3183. struct work *work;
  3184. bool rc;
  3185. work = make_work();
  3186. rc= work_decode(json_object_get(val, "result"), work);
  3187. if (unlikely(!rc)) {
  3188. applog(LOG_ERR, "Could not convert longpoll data to work");
  3189. return;
  3190. }
  3191. work->pool = current_pool();
  3192. work->rolltime = rolltime;
  3193. if (opt_debug)
  3194. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3195. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  3196. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  3197. else if (opt_debug)
  3198. applog(LOG_DEBUG, "Converted longpoll data to work");
  3199. }
  3200. static void *longpoll_thread(void *userdata)
  3201. {
  3202. struct thr_info *mythr = userdata;
  3203. CURL *curl = NULL;
  3204. char *copy_start, *hdr_path, *lp_url = NULL;
  3205. bool need_slash = false;
  3206. int failures = 0;
  3207. struct pool *pool = current_pool();
  3208. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3209. curl = curl_easy_init();
  3210. if (unlikely(!curl)) {
  3211. applog(LOG_ERR, "CURL initialisation failed");
  3212. goto out;
  3213. }
  3214. if (opt_debug)
  3215. applog(LOG_DEBUG, "Popping hdr path in longpoll thread");
  3216. hdr_path = tq_pop(mythr->q, NULL);
  3217. if (!hdr_path) {
  3218. applog(LOG_WARNING, "No long-poll found on this server");
  3219. goto out;
  3220. }
  3221. /* full URL */
  3222. if (strstr(hdr_path, "://")) {
  3223. lp_url = hdr_path;
  3224. hdr_path = NULL;
  3225. }
  3226. /* absolute path, on current server */
  3227. else {
  3228. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3229. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3230. need_slash = true;
  3231. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3232. if (!lp_url)
  3233. goto out;
  3234. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3235. }
  3236. free(hdr_path);
  3237. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  3238. while (1) {
  3239. struct timeval start, end;
  3240. bool rolltime;
  3241. json_t *val;
  3242. gettimeofday(&start, NULL);
  3243. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3244. false, true, &rolltime, pool);
  3245. if (likely(val)) {
  3246. /* Keep track of who ordered a restart_threads to make
  3247. * sure it's only done once per new block */
  3248. if (block_changed != BLOCK_DETECT) {
  3249. block_changed = BLOCK_LP;
  3250. new_blocks++;
  3251. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  3252. restart_threads();
  3253. } else {
  3254. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  3255. block_changed = BLOCK_NONE;
  3256. }
  3257. convert_to_work(val, rolltime);
  3258. failures = 0;
  3259. json_decref(val);
  3260. } else {
  3261. /* Some pools regularly drop the longpoll request so
  3262. * only see this as longpoll failure if it happens
  3263. * immediately and just restart it the rest of the
  3264. * time. */
  3265. gettimeofday(&end, NULL);
  3266. if (end.tv_sec - start.tv_sec > 30)
  3267. continue;
  3268. if (failures++ < 10) {
  3269. sleep(30);
  3270. applog(LOG_WARNING,
  3271. "longpoll failed, sleeping for 30s");
  3272. } else {
  3273. applog(LOG_ERR,
  3274. "longpoll failed, ending thread");
  3275. goto out;
  3276. }
  3277. }
  3278. }
  3279. out:
  3280. free(lp_url);
  3281. tq_freeze(mythr->q);
  3282. if (curl)
  3283. curl_easy_cleanup(curl);
  3284. return NULL;
  3285. }
  3286. static void stop_longpoll(void)
  3287. {
  3288. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3289. tq_freeze(thr->q);
  3290. pthread_cancel(*thr->pth);
  3291. have_longpoll = false;
  3292. }
  3293. static void start_longpoll(void)
  3294. {
  3295. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3296. tq_thaw(thr->q);
  3297. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3298. quit(1, "longpoll thread create failed");
  3299. pthread_detach(*thr->pth);
  3300. }
  3301. static void restart_longpoll(void)
  3302. {
  3303. stop_longpoll();
  3304. if (want_longpoll)
  3305. start_longpoll();
  3306. }
  3307. static void *reinit_cpu(void *userdata)
  3308. {
  3309. pthread_detach(pthread_self());
  3310. #if 0
  3311. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  3312. int cpu = cgpu->cpu_gpu;
  3313. long thr_id = ....(long)userdata;
  3314. struct thr_info *thr = &thr_info[thr_id];
  3315. int cpu = dev_from_id(thr_id);
  3316. cpus[cpu].alive = false;
  3317. thr->rolling = thr->cgpu->rolling = 0;
  3318. tq_freeze(thr->q);
  3319. if (!pthread_cancel(*thr->pth))
  3320. pthread_join(*thr->pth, NULL);
  3321. free(thr->q);
  3322. thr->q = tq_new();
  3323. if (!thr->q)
  3324. quit(1, "Failed to tq_new in reinit_cputhread");
  3325. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  3326. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  3327. applog(LOG_ERR, "thread %d create failed", thr_id);
  3328. return NULL;
  3329. }
  3330. tq_push(thr->q, &ping);
  3331. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3332. #endif
  3333. return NULL;
  3334. }
  3335. #ifdef HAVE_OPENCL
  3336. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  3337. * init command fails due to a completely wedged GPU, the thread will never
  3338. * return, unable to harm other GPUs. If it does return, it means we only had
  3339. * a soft failure and then the reinit_gpu thread is ready to tackle another
  3340. * GPU */
  3341. static void *reinit_gpu(void *userdata)
  3342. {
  3343. struct thr_info *mythr = userdata;
  3344. struct cgpu_info *cgpu;
  3345. struct thr_info *thr;
  3346. struct timeval now;
  3347. char name[256];
  3348. int thr_id;
  3349. int gpu;
  3350. pthread_detach(pthread_self());
  3351. select_cgpu:
  3352. cgpu = tq_pop(mythr->q, NULL);
  3353. if (!cgpu)
  3354. goto out;
  3355. if (clDevicesNum() != nDevs) {
  3356. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  3357. goto out;
  3358. }
  3359. gpu = cgpu->cpu_gpu;
  3360. gpu_devices[gpu] = false;
  3361. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3362. if (dev_from_id(thr_id) != gpu)
  3363. continue;
  3364. thr = &thr_info[thr_id];
  3365. thr->rolling = thr->cgpu->rolling = 0;
  3366. if (!pthread_cancel(*thr->pth)) {
  3367. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  3368. } else
  3369. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  3370. }
  3371. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3372. if (dev_from_id(thr_id) != gpu)
  3373. continue;
  3374. thr = &thr_info[thr_id];
  3375. /* Lose this ram cause we may get stuck here! */
  3376. //tq_freeze(thr->q);
  3377. thr->q = tq_new();
  3378. if (!thr->q)
  3379. quit(1, "Failed to tq_new in reinit_gpu");
  3380. /* Lose this ram cause we may dereference in the dying thread! */
  3381. //free(clState);
  3382. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  3383. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  3384. if (!clStates[thr_id]) {
  3385. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  3386. goto out;
  3387. }
  3388. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3389. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  3390. applog(LOG_ERR, "thread %d create failed", thr_id);
  3391. return NULL;
  3392. }
  3393. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3394. }
  3395. gettimeofday(&now, NULL);
  3396. get_datestamp(cgpu->init, &now);
  3397. gpu_devices[gpu] = true;
  3398. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3399. if (dev_from_id(thr_id) != gpu)
  3400. continue;
  3401. thr = &thr_info[thr_id];
  3402. tq_push(thr->q, &ping);
  3403. }
  3404. goto select_cgpu;
  3405. out:
  3406. return NULL;
  3407. }
  3408. #else
  3409. static void *reinit_gpu(void *userdata)
  3410. {
  3411. }
  3412. #endif
  3413. static void reinit_device(struct cgpu_info *cgpu)
  3414. {
  3415. if (cgpu->is_gpu)
  3416. tq_push(thr_info[gpur_thr_id].q, cgpu);
  3417. else
  3418. tq_push(thr_info[cpur_thr_id].q, cgpu);
  3419. }
  3420. /* Determine which are the first threads belonging to a device and if they're
  3421. * active */
  3422. static bool active_device(int thr_id)
  3423. {
  3424. if (thr_id < gpu_threads) {
  3425. if (thr_id >= total_devices)
  3426. return false;
  3427. if (!gpu_devices[dev_from_id(thr_id)])
  3428. return false;
  3429. } else if (thr_id > gpu_threads + num_processors)
  3430. return false;
  3431. return true;
  3432. }
  3433. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3434. * the screen at regular intervals, and restarts threads if they appear to have
  3435. * died. */
  3436. static void *watchdog_thread(void *userdata)
  3437. {
  3438. const unsigned int interval = opt_log_interval / 2 ? : 1;
  3439. static struct timeval rotate_tv;
  3440. struct timeval zero_tv;
  3441. bool statwin = false;
  3442. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3443. memset(&zero_tv, 0, sizeof(struct timeval));
  3444. gettimeofday(&rotate_tv, NULL);
  3445. while (1) {
  3446. int i;
  3447. struct timeval now;
  3448. sleep(interval);
  3449. if (requests_queued() < opt_queue)
  3450. queue_request(NULL, false);
  3451. hashmeter(-1, &zero_tv, 0);
  3452. if (curses_active) {
  3453. statwin ^= true;
  3454. mutex_lock(&curses_lock);
  3455. for (i = 0; i < mining_threads; i++)
  3456. curses_print_status(i);
  3457. if (statwin)
  3458. redrawwin(statuswin);
  3459. else {
  3460. check_logwinsize();
  3461. redrawwin(logwin);
  3462. }
  3463. mutex_unlock(&curses_lock);
  3464. }
  3465. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  3466. restart_threads();
  3467. work_restart[watchdog_thr_id].restart = 0;
  3468. }
  3469. gettimeofday(&now, NULL);
  3470. for (i = 0; i < total_pools; i++) {
  3471. struct pool *pool = pools[i];
  3472. if (!pool->enabled)
  3473. continue;
  3474. /* Test pool is idle once every minute */
  3475. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3476. gettimeofday(&pool->tv_idle, NULL);
  3477. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3478. pool_resus(pool);
  3479. }
  3480. }
  3481. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3482. gettimeofday(&rotate_tv, NULL);
  3483. switch_pools(NULL);
  3484. }
  3485. //for (i = 0; i < mining_threads; i++) {
  3486. for (i = 0; i < gpu_threads; i++) {
  3487. struct thr_info *thr = &thr_info[i];
  3488. int gpu = thr->cgpu->cpu_gpu;
  3489. /* Thread is waiting on getwork or disabled */
  3490. if (thr->getwork || !gpu_devices[gpu])
  3491. continue;
  3492. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3493. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  3494. gpus[gpu].status = LIFE_WELL;
  3495. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3496. thr->rolling = thr->cgpu->rolling = 0;
  3497. gpus[gpu].status = LIFE_SICK;
  3498. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3499. /* Sent it a ping, it might respond */
  3500. tq_push(thr->q, &ping);
  3501. } else if (now.tv_sec - thr->last.tv_sec > 300 && gpus[i].status == LIFE_SICK) {
  3502. gpus[gpu].status = LIFE_DEAD;
  3503. applog(LOG_ERR, "Thread %d idle for more than 5 minutes, GPU %d declared DEAD!", i, gpu);
  3504. applog(LOG_ERR, "Attempting to restart GPU");
  3505. reinit_device(thr->cgpu);
  3506. break;
  3507. }
  3508. }
  3509. }
  3510. return NULL;
  3511. }
  3512. static void print_summary(void)
  3513. {
  3514. struct timeval diff;
  3515. int hours, mins, secs, i;
  3516. double utility, efficiency = 0.0;
  3517. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3518. hours = diff.tv_sec / 3600;
  3519. mins = (diff.tv_sec % 3600) / 60;
  3520. secs = diff.tv_sec % 60;
  3521. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3522. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3523. printf("\nSummary of runtime statistics:\n\n");
  3524. printf("Started at %s\n", datestamp);
  3525. printf("CPU hasher algorithm used: %s\n", algo_names[opt_algo]);
  3526. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  3527. if (total_secs)
  3528. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  3529. printf("Queued work requests: %d\n", total_getworks);
  3530. printf("Share submissions: %d\n", total_accepted + total_rejected);
  3531. printf("Accepted shares: %d\n", total_accepted);
  3532. printf("Rejected shares: %d\n", total_rejected);
  3533. if (total_accepted || total_rejected)
  3534. printf("Reject ratio: %.1f\n", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3535. printf("Hardware errors: %d\n", hw_errors);
  3536. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3537. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  3538. printf("Discarded work due to new blocks: %d\n", total_discarded);
  3539. printf("Stale submissions discarded due to new blocks: %d\n", total_stale);
  3540. printf("Unable to get work from server occasions: %d\n", total_lo);
  3541. printf("Work items generated locally: %d\n", local_work);
  3542. printf("Submitting work remotely delay occasions: %d\n", total_ro);
  3543. printf("New blocks detected on network: %d\n\n", new_blocks);
  3544. if (total_pools > 1) {
  3545. for (i = 0; i < total_pools; i++) {
  3546. struct pool *pool = pools[i];
  3547. printf("Pool: %s\n", pool->rpc_url);
  3548. printf(" Queued work requests: %d\n", pool->getwork_requested);
  3549. printf(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3550. printf(" Accepted shares: %d\n", pool->accepted);
  3551. printf(" Rejected shares: %d\n", pool->rejected);
  3552. if (pool->accepted || pool->rejected)
  3553. printf(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3554. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3555. printf(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3556. printf(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3557. printf(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3558. printf(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  3559. printf(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3560. }
  3561. }
  3562. printf("Summary of per device statistics:\n\n");
  3563. for (i = 0; i < mining_threads; i++) {
  3564. if (active_device(i))
  3565. print_status(i);
  3566. }
  3567. printf("\n");
  3568. fflush(stdout);
  3569. }
  3570. void quit(int status, const char *format, ...)
  3571. {
  3572. va_list ap;
  3573. disable_curses();
  3574. if (format) {
  3575. va_start(ap, format);
  3576. vfprintf(stderr, format, ap);
  3577. va_end(ap);
  3578. }
  3579. fprintf(stderr, "\n");
  3580. fflush(stderr);
  3581. exit(status);
  3582. }
  3583. static char *curses_input(const char *query)
  3584. {
  3585. char *input;
  3586. echo();
  3587. input = malloc(255);
  3588. if (!input)
  3589. quit(1, "Failed to malloc input");
  3590. leaveok(logwin, false);
  3591. wlogprint("%s: ", query);
  3592. wgetnstr(logwin, input, 255);
  3593. leaveok(logwin, true);
  3594. noecho();
  3595. return input;
  3596. }
  3597. static bool input_pool(bool live)
  3598. {
  3599. char *url = NULL, *user = NULL, *pass = NULL;
  3600. struct pool *pool = NULL;
  3601. bool ret = false;
  3602. immedok(logwin, true);
  3603. if (total_pools == MAX_POOLS) {
  3604. wlogprint("Reached maximum number of pools.\n");
  3605. goto out;
  3606. }
  3607. wlogprint("Input server details.\n");
  3608. url = curses_input("URL");
  3609. if (!url)
  3610. goto out;
  3611. if (strncmp(url, "http://", 7) &&
  3612. strncmp(url, "https://", 8)) {
  3613. char *httpinput;
  3614. httpinput = malloc(255);
  3615. if (!httpinput)
  3616. quit(1, "Failed to malloc httpinput");
  3617. strcpy(httpinput, "http://");
  3618. strncat(httpinput, url, 248);
  3619. free(url);
  3620. url = httpinput;
  3621. }
  3622. user = curses_input("Username");
  3623. if (!user)
  3624. goto out;
  3625. pass = curses_input("Password");
  3626. if (!pass)
  3627. goto out;
  3628. pool = calloc(sizeof(struct pool), 1);
  3629. if (!pool)
  3630. quit(1, "Failed to realloc pools in input_pool");
  3631. pool->pool_no = total_pools;
  3632. pool->prio = total_pools;
  3633. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3634. quit (1, "Failed to pthread_mutex_init in input_pool");
  3635. pool->rpc_url = url;
  3636. pool->rpc_user = user;
  3637. pool->rpc_pass = pass;
  3638. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3639. if (!pool->rpc_userpass)
  3640. quit(1, "Failed to malloc userpass");
  3641. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3642. pool->tv_idle.tv_sec = ~0UL;
  3643. /* Test the pool before we enable it if we're live running, otherwise
  3644. * it will be tested separately */
  3645. ret = true;
  3646. if (live && pool_active(pool, false))
  3647. pool->enabled = true;
  3648. pools[total_pools++] = pool;
  3649. out:
  3650. immedok(logwin, false);
  3651. if (!ret) {
  3652. if (url)
  3653. free(url);
  3654. if (user)
  3655. free(user);
  3656. if (pass)
  3657. free(pass);
  3658. if (pool)
  3659. free(pool);
  3660. }
  3661. return ret;
  3662. }
  3663. #if defined(unix)
  3664. static void fork_monitor()
  3665. {
  3666. // Make a pipe: [readFD, writeFD]
  3667. int pfd[2];
  3668. int r = pipe(pfd);
  3669. if (r<0) {
  3670. perror("pipe - failed to create pipe for --monitor");
  3671. exit(1);
  3672. }
  3673. // Make stderr write end of pipe
  3674. fflush(stderr);
  3675. r = dup2(pfd[1], 2);
  3676. if (r<0) {
  3677. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3678. exit(1);
  3679. }
  3680. r = close(pfd[1]);
  3681. if (r<0) {
  3682. perror("close - failed to close write end of pipe for --monitor");
  3683. exit(1);
  3684. }
  3685. // Don't allow a dying monitor to kill the main process
  3686. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3687. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3688. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3689. perror("signal - failed to edit signal mask for --monitor");
  3690. exit(1);
  3691. }
  3692. // Fork a child process
  3693. r = fork();
  3694. if (r<0) {
  3695. perror("fork - failed to fork child process for --monitor");
  3696. exit(1);
  3697. }
  3698. // Child: launch monitor command
  3699. if (0==r) {
  3700. // Make stdin read end of pipe
  3701. r = dup2(pfd[0], 0);
  3702. if (r<0) {
  3703. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3704. exit(1);
  3705. }
  3706. close(pfd[0]);
  3707. if (r<0) {
  3708. perror("close - in child, failed to close read end of pipe for --monitor");
  3709. exit(1);
  3710. }
  3711. // Launch user specified command
  3712. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3713. perror("execl - in child failed to exec user specified command for --monitor");
  3714. exit(1);
  3715. }
  3716. // Parent: clean up unused fds and bail
  3717. r = close(pfd[0]);
  3718. if (r<0) {
  3719. perror("close - failed to close read end of pipe for --monitor");
  3720. exit(1);
  3721. }
  3722. }
  3723. #endif // defined(unix)
  3724. int main (int argc, char *argv[])
  3725. {
  3726. unsigned int i, x, y, pools_active = 0;
  3727. struct sigaction handler;
  3728. struct thr_info *thr;
  3729. char name[256];
  3730. /* This dangerous functions tramples random dynamically allocated
  3731. * variables so do it before anything at all */
  3732. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3733. quit(1, "Failed to curl_global_init");
  3734. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  3735. quit(1, "Failed to pthread_mutex_init");
  3736. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  3737. quit(1, "Failed to pthread_mutex_init");
  3738. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  3739. quit(1, "Failed to pthread_mutex_init");
  3740. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  3741. quit(1, "Failed to pthread_mutex_init");
  3742. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  3743. quit(1, "Failed to pthread_mutex_init");
  3744. init_max_name_len();
  3745. handler.sa_handler = &sighandler;
  3746. sigaction(SIGTERM, &handler, &termhandler);
  3747. sigaction(SIGINT, &handler, &inthandler);
  3748. gettimeofday(&total_tv_start, NULL);
  3749. gettimeofday(&total_tv_end, NULL);
  3750. get_datestamp(datestamp, &total_tv_start);
  3751. // Hack to make cgminer silent when called recursively on WIN32
  3752. int skip_to_bench = 0;
  3753. #if defined(WIN32)
  3754. char buf[32];
  3755. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  3756. skip_to_bench = 1;
  3757. #endif // defined(WIN32)
  3758. for (i = 0; i < 36; i++)
  3759. strcat(current_block, "0");
  3760. current_hash = calloc(sizeof(current_hash), 1);
  3761. if (unlikely(!current_hash))
  3762. quit (1, "main OOM");
  3763. // Reckon number of cores in the box
  3764. #if defined(WIN32)
  3765. DWORD system_am;
  3766. DWORD process_am;
  3767. BOOL ok = GetProcessAffinityMask(
  3768. GetCurrentProcess(),
  3769. &system_am,
  3770. &process_am
  3771. );
  3772. if (!ok) {
  3773. applog(LOG_ERR, "couldn't figure out number of processors :(");
  3774. num_processors = 1;
  3775. } else {
  3776. size_t n = 32;
  3777. num_processors = 0;
  3778. while (n--)
  3779. if (process_am & (1<<n))
  3780. ++num_processors;
  3781. }
  3782. #else
  3783. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  3784. #endif /* !WIN32 */
  3785. opt_n_threads = num_processors;
  3786. #ifdef HAVE_OPENCL
  3787. if (!skip_to_bench) {
  3788. for (i = 0; i < 16; i++)
  3789. gpu_devices[i] = false;
  3790. nDevs = clDevicesNum();
  3791. if (nDevs < 0) {
  3792. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  3793. nDevs = 0;
  3794. }
  3795. }
  3796. #endif
  3797. if (nDevs)
  3798. opt_n_threads = 0;
  3799. trpc_url = strdup(DEF_RPC_URL);
  3800. /* parse command line */
  3801. opt_register_table(opt_config_table,
  3802. "Options for both config file and command line");
  3803. opt_register_table(opt_cmdline_table,
  3804. "Options for command line only");
  3805. opt_parse(&argc, argv, applog_and_exit);
  3806. if (argc != 1)
  3807. quit(1, "Unexpected extra commandline arguments");
  3808. if (0<=opt_bench_algo) {
  3809. double rate = bench_algo_stage3(opt_bench_algo);
  3810. if (!skip_to_bench) {
  3811. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  3812. } else {
  3813. // Write result to shared memory for parent
  3814. #if defined(WIN32)
  3815. char unique_name[64];
  3816. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  3817. HANDLE map_handle = CreateFileMapping(
  3818. INVALID_HANDLE_VALUE, // use paging file
  3819. NULL, // default security attributes
  3820. PAGE_READWRITE, // read/write access
  3821. 0, // size: high 32-bits
  3822. 4096, // size: low 32-bits
  3823. unique_name // name of map object
  3824. );
  3825. if (NULL!=map_handle) {
  3826. void *shared_mem = MapViewOfFile(
  3827. map_handle, // object to map view of
  3828. FILE_MAP_WRITE, // read/write access
  3829. 0, // high offset: map from
  3830. 0, // low offset: beginning
  3831. 0 // default: map entire file
  3832. );
  3833. if (NULL!=shared_mem)
  3834. CopyMemory(shared_mem, &rate, sizeof(rate));
  3835. (void)UnmapViewOfFile(shared_mem);
  3836. }
  3837. (void)CloseHandle(map_handle);
  3838. }
  3839. #endif
  3840. }
  3841. exit(0);
  3842. }
  3843. if (opt_kernel) {
  3844. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  3845. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  3846. if (!strcmp(opt_kernel, "poclbm"))
  3847. chosen_kernel = KL_POCLBM;
  3848. else
  3849. chosen_kernel = KL_PHATK;
  3850. } else
  3851. chosen_kernel = KL_NONE;
  3852. gpu_threads = nDevs * opt_g_threads;
  3853. if (total_devices) {
  3854. if (total_devices > nDevs)
  3855. quit(1, "More devices specified than exist");
  3856. for (i = 0; i < 16; i++)
  3857. if (gpu_devices[i] && i + 1 > nDevs)
  3858. quit (1, "Command line options set a device that doesn't exist");
  3859. } else {
  3860. for (i = 0; i < nDevs; i++)
  3861. gpu_devices[i] = true;
  3862. total_devices = nDevs;
  3863. }
  3864. if (!gpu_threads && !forced_n_threads) {
  3865. /* Maybe they turned GPU off; restore default CPU threads. */
  3866. opt_n_threads = num_processors;
  3867. }
  3868. logcursor = 8;
  3869. gpucursor = logcursor;
  3870. cpucursor = gpucursor + nDevs;
  3871. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  3872. logcursor = logstart + 1;
  3873. /* Set up the ncurses interface */
  3874. if (!opt_realquiet && use_curses) {
  3875. mainwin = initscr();
  3876. getmaxyx(mainwin, y, x);
  3877. statuswin = newwin(logstart, x, 0, 0);
  3878. leaveok(statuswin, true);
  3879. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3880. idlok(logwin, true);
  3881. scrollok(logwin, true);
  3882. leaveok(logwin, true);
  3883. cbreak();
  3884. noecho();
  3885. test_and_set(&curses_active);
  3886. }
  3887. if (!total_pools) {
  3888. if (curses_active) {
  3889. if (!input_pool(false))
  3890. quit(1, "Pool setup failed");
  3891. } else
  3892. quit(1, "No server specified");
  3893. }
  3894. for (i = 0; i < total_pools; i++) {
  3895. struct pool *pool = pools[i];
  3896. if (!pool->rpc_userpass) {
  3897. if (!pool->rpc_user || !pool->rpc_pass)
  3898. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3899. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3900. if (!pool->rpc_userpass)
  3901. quit(1, "Failed to malloc userpass");
  3902. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3903. } else {
  3904. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  3905. if (!pool->rpc_user)
  3906. quit(1, "Failed to malloc user");
  3907. strcpy(pool->rpc_user, pool->rpc_userpass);
  3908. pool->rpc_user = strtok(pool->rpc_user, ":");
  3909. if (!pool->rpc_user)
  3910. quit(1, "Failed to find colon delimiter in userpass");
  3911. }
  3912. }
  3913. /* Set the currentpool to pool 0 */
  3914. currentpool = pools[0];
  3915. #ifdef HAVE_SYSLOG_H
  3916. if (use_syslog)
  3917. openlog(PROGRAM_NAME, LOG_PID, LOG_USER);
  3918. #endif
  3919. #if defined(unix)
  3920. if (opt_stderr_cmd)
  3921. fork_monitor();
  3922. #endif // defined(unix)
  3923. mining_threads = opt_n_threads + gpu_threads;
  3924. total_threads = mining_threads + 7;
  3925. work_restart = calloc(total_threads, sizeof(*work_restart));
  3926. if (!work_restart)
  3927. quit(1, "Failed to calloc work_restart");
  3928. thr_info = calloc(total_threads, sizeof(*thr));
  3929. if (!thr_info)
  3930. quit(1, "Failed to calloc thr_info");
  3931. /* init workio thread info */
  3932. work_thr_id = mining_threads;
  3933. thr = &thr_info[work_thr_id];
  3934. thr->id = work_thr_id;
  3935. thr->q = tq_new();
  3936. if (!thr->q)
  3937. quit(1, "Failed to tq_new");
  3938. /* start work I/O thread */
  3939. if (thr_info_create(thr, NULL, workio_thread, thr))
  3940. quit(1, "workio thread create failed");
  3941. /* init longpoll thread info */
  3942. longpoll_thr_id = mining_threads + 1;
  3943. thr = &thr_info[longpoll_thr_id];
  3944. thr->id = longpoll_thr_id;
  3945. thr->q = tq_new();
  3946. if (!thr->q)
  3947. quit(1, "Failed to tq_new");
  3948. if (want_longpoll)
  3949. start_longpoll();
  3950. if (opt_n_threads ) {
  3951. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  3952. if (unlikely(!cpus))
  3953. quit(1, "Failed to calloc cpus");
  3954. }
  3955. if (gpu_threads) {
  3956. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  3957. if (unlikely(!gpus))
  3958. quit(1, "Failed to calloc gpus");
  3959. }
  3960. stage_thr_id = mining_threads + 3;
  3961. thr = &thr_info[stage_thr_id];
  3962. thr->q = tq_new();
  3963. if (!thr->q)
  3964. quit(1, "Failed to tq_new");
  3965. /* start stage thread */
  3966. if (thr_info_create(thr, NULL, stage_thread, thr))
  3967. quit(1, "stage thread create failed");
  3968. pthread_detach(*thr->pth);
  3969. /* Create a unique get work queue */
  3970. getq = tq_new();
  3971. if (!getq)
  3972. quit(1, "Failed to create getq");
  3973. /* Test each pool to see if we can retrieve and use work and for what
  3974. * it supports */
  3975. for (i = 0; i < total_pools; i++) {
  3976. struct pool *pool;
  3977. pool = pools[i];
  3978. if (pool_active(pool, false)) {
  3979. if (!currentpool)
  3980. currentpool = pool;
  3981. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  3982. pools_active++;
  3983. pool->enabled = true;
  3984. } else {
  3985. if (pool == currentpool)
  3986. currentpool = NULL;
  3987. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  3988. }
  3989. }
  3990. if (!pools_active)
  3991. quit(0, "No pools active! Exiting.");
  3992. #ifdef HAVE_OPENCL
  3993. /* start GPU mining threads */
  3994. for (i = 0; i < nDevs * opt_g_threads; i++) {
  3995. int gpu = i % nDevs;
  3996. struct cgpu_info *cgpu;
  3997. struct timeval now;
  3998. gpus[gpu].is_gpu = 1;
  3999. gpus[gpu].cpu_gpu = gpu;
  4000. thr = &thr_info[i];
  4001. thr->id = i;
  4002. cgpu = thr->cgpu = &gpus[gpu];
  4003. thr->q = tq_new();
  4004. if (!thr->q)
  4005. quit(1, "tq_new failed in starting gpu mining threads");
  4006. /* Enable threads for devices set not to mine but disable
  4007. * their queue in case we wish to enable them later*/
  4008. if (gpu_devices[gpu]) {
  4009. if (opt_debug)
  4010. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4011. tq_push(thr->q, &ping);
  4012. }
  4013. applog(LOG_INFO, "Init GPU thread %i", i);
  4014. clStates[i] = initCl(gpu, name, sizeof(name));
  4015. if (!clStates[i]) {
  4016. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  4017. gpu_devices[i] = false;
  4018. continue;
  4019. }
  4020. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4021. gettimeofday(&now, NULL);
  4022. get_datestamp(cgpu->init, &now);
  4023. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  4024. quit(1, "thread %d create failed", i);
  4025. }
  4026. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4027. #else
  4028. opt_g_threads = 0;
  4029. #endif
  4030. /* start CPU mining threads */
  4031. for (i = gpu_threads; i < mining_threads; i++) {
  4032. int cpu = (i - gpu_threads) % num_processors;
  4033. thr = &thr_info[i];
  4034. thr->id = i;
  4035. cpus[cpu].cpu_gpu = cpu;
  4036. thr->cgpu = &cpus[cpu];
  4037. thr->q = tq_new();
  4038. if (!thr->q)
  4039. quit(1, "tq_new failed in starting cpu mining threads");
  4040. thread_reportin(thr);
  4041. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4042. quit(1, "thread %d create failed", i);
  4043. }
  4044. applog(LOG_INFO, "%d cpu miner threads started, "
  4045. "using SHA256 '%s' algorithm.",
  4046. opt_n_threads,
  4047. algo_names[opt_algo]);
  4048. watchdog_thr_id = mining_threads + 2;
  4049. thr = &thr_info[watchdog_thr_id];
  4050. /* start wakeup thread */
  4051. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4052. quit(1, "wakeup thread create failed");
  4053. /* Create curses input thread for keyboard input */
  4054. input_thr_id = mining_threads + 4;
  4055. thr = &thr_info[input_thr_id];
  4056. if (thr_info_create(thr, NULL, input_thread, thr))
  4057. quit(1, "input thread create failed");
  4058. pthread_detach(*thr->pth);
  4059. /* Create reinit cpu thread */
  4060. cpur_thr_id = mining_threads + 5;
  4061. thr = &thr_info[cpur_thr_id];
  4062. thr->q = tq_new();
  4063. if (!thr->q)
  4064. quit(1, "tq_new failed for cpur_thr_id");
  4065. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  4066. quit(1, "reinit_cpu thread create failed");
  4067. /* Create reinit gpu thread */
  4068. gpur_thr_id = mining_threads + 6;
  4069. thr = &thr_info[gpur_thr_id];
  4070. thr->q = tq_new();
  4071. if (!thr->q)
  4072. quit(1, "tq_new failed for gpur_thr_id");
  4073. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4074. quit(1, "reinit_gpu thread create failed");
  4075. /* main loop - simply wait for workio thread to exit */
  4076. pthread_join(*thr_info[work_thr_id].pth, NULL);
  4077. applog(LOG_INFO, "workio thread dead, exiting.");
  4078. gettimeofday(&total_tv_end, NULL);
  4079. disable_curses();
  4080. if (!opt_realquiet && successful_connect)
  4081. print_summary();
  4082. if (gpu_threads)
  4083. free(gpus);
  4084. if (opt_n_threads)
  4085. free(cpus);
  4086. curl_global_cleanup();
  4087. return 0;
  4088. }