main.c 141 KB

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