main.c 144 KB

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