main.c 133 KB

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