main.c 138 KB

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