main.c 131 KB

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