main.c 124 KB

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