main.c 140 KB

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