main.c 140 KB

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