main.c 132 KB

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