main.c 140 KB

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