main.c 122 KB

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