main.c 133 KB

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