miner.c 155 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #ifdef HAVE_CURSES
  13. #include <curses.h>
  14. #endif
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <time.h>
  23. #include <math.h>
  24. #include <stdarg.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27. #include <sys/stat.h>
  28. #include <sys/types.h>
  29. #ifndef WIN32
  30. #include <sys/resource.h>
  31. #endif
  32. #include <ccan/opt/opt.h>
  33. #include <jansson.h>
  34. #include <curl/curl.h>
  35. #include <libgen.h>
  36. #include <sha2.h>
  37. #include "compat.h"
  38. #include "miner.h"
  39. #include "findnonce.h"
  40. #include "adl.h"
  41. #include "driver-cpu.h"
  42. #include "driver-opencl.h"
  43. #include "bench_block.h"
  44. #if defined(unix)
  45. #include <errno.h>
  46. #include <fcntl.h>
  47. #include <sys/wait.h>
  48. #endif
  49. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER)
  50. # define USE_FPGA
  51. # define USE_FPGA_SERIAL
  52. #elif defined(USE_ZTEX)
  53. # define USE_FPGA
  54. #endif
  55. enum workio_commands {
  56. WC_GET_WORK,
  57. WC_SUBMIT_WORK,
  58. };
  59. struct workio_cmd {
  60. enum workio_commands cmd;
  61. struct thr_info *thr;
  62. struct work *work;
  63. bool lagging;
  64. };
  65. struct strategies strategies[] = {
  66. { "Failover" },
  67. { "Round Robin" },
  68. { "Rotate" },
  69. { "Load Balance" },
  70. };
  71. static char packagename[255];
  72. bool opt_protocol;
  73. static bool opt_benchmark;
  74. static bool want_longpoll = true;
  75. static bool have_longpoll;
  76. static bool want_per_device_stats;
  77. bool use_syslog;
  78. bool opt_quiet;
  79. static bool opt_realquiet;
  80. bool opt_loginput;
  81. const int opt_cutofftemp = 95;
  82. static int opt_retries = -1;
  83. int opt_fail_pause = 5;
  84. static int fail_pause = 5;
  85. int opt_log_interval = 5;
  86. static int opt_queue = 1;
  87. int opt_scantime = 60;
  88. int opt_expiry = 120;
  89. int opt_bench_algo = -1;
  90. static const bool opt_time = true;
  91. unsigned long long global_hashrate;
  92. #ifdef HAVE_OPENCL
  93. int opt_dynamic_interval = 7;
  94. int nDevs;
  95. int opt_g_threads = 2;
  96. int gpu_threads;
  97. #endif
  98. #ifdef USE_SCRYPT
  99. static char detect_algo = 1;
  100. bool opt_scrypt;
  101. #else
  102. static char detect_algo;
  103. #endif
  104. bool opt_restart = true;
  105. static bool opt_nogpu;
  106. struct list_head scan_devices;
  107. static signed int devices_enabled;
  108. static bool opt_removedisabled;
  109. int total_devices;
  110. struct cgpu_info **devices;
  111. bool have_opencl;
  112. int opt_n_threads = -1;
  113. int mining_threads;
  114. int num_processors;
  115. #ifdef HAVE_CURSES
  116. bool use_curses = true;
  117. #else
  118. bool use_curses;
  119. #endif
  120. static bool opt_submit_stale = true;
  121. static int opt_shares;
  122. static bool opt_fail_only;
  123. bool opt_autofan;
  124. bool opt_autoengine;
  125. bool opt_noadl;
  126. char *opt_api_allow = NULL;
  127. char *opt_api_groups;
  128. char *opt_api_description = PACKAGE_STRING;
  129. int opt_api_port = 4028;
  130. bool opt_api_listen;
  131. bool opt_api_network;
  132. bool opt_delaynet;
  133. bool opt_disable_pool = true;
  134. char *opt_icarus_options = NULL;
  135. char *opt_icarus_timing = NULL;
  136. char *opt_kernel_path;
  137. char *cgminer_path;
  138. #if defined(USE_BITFORCE)
  139. bool opt_bfl_noncerange;
  140. #endif
  141. #define QUIET (opt_quiet || opt_realquiet)
  142. struct thr_info *thr_info;
  143. static int work_thr_id;
  144. static int stage_thr_id;
  145. static int watchpool_thr_id;
  146. static int watchdog_thr_id;
  147. #ifdef HAVE_CURSES
  148. static int input_thr_id;
  149. #endif
  150. int gpur_thr_id;
  151. static int api_thr_id;
  152. static int total_threads;
  153. static pthread_mutex_t hash_lock;
  154. static pthread_mutex_t qd_lock;
  155. static pthread_mutex_t *stgd_lock;
  156. pthread_mutex_t console_lock;
  157. static pthread_mutex_t ch_lock;
  158. static pthread_rwlock_t blk_lock;
  159. pthread_rwlock_t netacc_lock;
  160. static pthread_mutex_t lp_lock;
  161. static pthread_cond_t lp_cond;
  162. pthread_mutex_t restart_lock;
  163. pthread_cond_t restart_cond;
  164. double total_mhashes_done;
  165. static struct timeval total_tv_start, total_tv_end;
  166. static struct timeval miner_started;
  167. pthread_mutex_t control_lock;
  168. int hw_errors;
  169. int total_accepted, total_rejected;
  170. float total_accepted_weighed;
  171. int total_getworks, total_stale, total_discarded;
  172. static int total_queued;
  173. unsigned int new_blocks;
  174. unsigned int found_blocks;
  175. unsigned int local_work;
  176. unsigned int total_go, total_ro;
  177. struct pool **pools;
  178. static struct pool *currentpool = NULL;
  179. int total_pools, enabled_pools;
  180. enum pool_strategy pool_strategy = POOL_FAILOVER;
  181. int opt_rotate_period;
  182. static int total_urls, total_users, total_passes, total_userpasses;
  183. static
  184. #ifndef HAVE_CURSES
  185. const
  186. #endif
  187. bool curses_active;
  188. static char current_block[37];
  189. static char *current_hash;
  190. static uint32_t current_block_id;
  191. static char datestamp[40];
  192. static char blocktime[30];
  193. struct block {
  194. char hash[37];
  195. UT_hash_handle hh;
  196. };
  197. static struct block *blocks = NULL;
  198. char *opt_socks_proxy = NULL;
  199. static const char def_conf[] = "bfgminer.conf";
  200. static bool config_loaded;
  201. static int include_count;
  202. #define JSON_INCLUDE_CONF "include"
  203. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  204. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  205. #define JSON_MAX_DEPTH 10
  206. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  207. #if defined(unix)
  208. static char *opt_stderr_cmd = NULL;
  209. static int forkpid;
  210. #endif // defined(unix)
  211. bool ping = true;
  212. struct sigaction termhandler, inthandler;
  213. struct thread_q *getq;
  214. static int total_work;
  215. struct work *staged_work = NULL;
  216. struct schedtime {
  217. bool enable;
  218. struct tm tm;
  219. };
  220. struct schedtime schedstart;
  221. struct schedtime schedstop;
  222. bool sched_paused;
  223. static bool time_before(struct tm *tm1, struct tm *tm2)
  224. {
  225. if (tm1->tm_hour < tm2->tm_hour)
  226. return true;
  227. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  228. return true;
  229. return false;
  230. }
  231. static bool should_run(void)
  232. {
  233. struct timeval tv;
  234. struct tm *tm;
  235. if (!schedstart.enable && !schedstop.enable)
  236. return true;
  237. gettimeofday(&tv, NULL);
  238. tm = localtime(&tv.tv_sec);
  239. if (schedstart.enable) {
  240. if (!schedstop.enable) {
  241. if (time_before(tm, &schedstart.tm))
  242. return false;
  243. /* This is a once off event with no stop time set */
  244. schedstart.enable = false;
  245. return true;
  246. }
  247. if (time_before(&schedstart.tm, &schedstop.tm)) {
  248. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  249. return true;
  250. return false;
  251. } /* Times are reversed */
  252. if (time_before(tm, &schedstart.tm)) {
  253. if (time_before(tm, &schedstop.tm))
  254. return true;
  255. return false;
  256. }
  257. return true;
  258. }
  259. /* only schedstop.enable == true */
  260. if (!time_before(tm, &schedstop.tm))
  261. return false;
  262. return true;
  263. }
  264. void get_datestamp(char *f, struct timeval *tv)
  265. {
  266. struct tm *tm;
  267. tm = localtime(&tv->tv_sec);
  268. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  269. tm->tm_year + 1900,
  270. tm->tm_mon + 1,
  271. tm->tm_mday,
  272. tm->tm_hour,
  273. tm->tm_min,
  274. tm->tm_sec);
  275. }
  276. void get_timestamp(char *f, struct timeval *tv)
  277. {
  278. struct tm *tm;
  279. tm = localtime(&tv->tv_sec);
  280. sprintf(f, "[%02d:%02d:%02d]",
  281. tm->tm_hour,
  282. tm->tm_min,
  283. tm->tm_sec);
  284. }
  285. static void applog_and_exit(const char *fmt, ...)
  286. {
  287. va_list ap;
  288. va_start(ap, fmt);
  289. vapplog(LOG_ERR, fmt, ap);
  290. va_end(ap);
  291. exit(1);
  292. }
  293. static pthread_mutex_t sharelog_lock;
  294. static FILE *sharelog_file = NULL;
  295. static void sharelog(const char*disposition, const struct work*work)
  296. {
  297. char *target, *hash, *data;
  298. struct cgpu_info *cgpu;
  299. unsigned long int t;
  300. struct pool *pool;
  301. int thr_id, rv;
  302. char s[1024];
  303. size_t ret;
  304. if (!sharelog_file)
  305. return;
  306. thr_id = work->thr_id;
  307. cgpu = thr_info[thr_id].cgpu;
  308. pool = work->pool;
  309. t = (unsigned long int)work->share_found_time;
  310. target = bin2hex(work->target, sizeof(work->target));
  311. if (unlikely(!target)) {
  312. applog(LOG_ERR, "sharelog target OOM");
  313. return;
  314. }
  315. hash = bin2hex(work->hash, sizeof(work->hash));
  316. if (unlikely(!hash)) {
  317. free(target);
  318. applog(LOG_ERR, "sharelog hash OOM");
  319. return;
  320. }
  321. data = bin2hex(work->data, sizeof(work->data));
  322. if (unlikely(!data)) {
  323. free(target);
  324. free(hash);
  325. applog(LOG_ERR, "sharelog data OOM");
  326. return;
  327. }
  328. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  329. rv = snprintf(s, sizeof(s), "%lu,%s,%s,%s,%s%u,%u,%s,%s\n", t, disposition, target, pool->rpc_url, cgpu->api->name, cgpu->device_id, thr_id, hash, data);
  330. free(target);
  331. free(hash);
  332. free(data);
  333. if (rv >= (int)(sizeof(s)))
  334. s[sizeof(s) - 1] = '\0';
  335. else if (rv < 0) {
  336. applog(LOG_ERR, "sharelog printf error");
  337. return;
  338. }
  339. mutex_lock(&sharelog_lock);
  340. ret = fwrite(s, rv, 1, sharelog_file);
  341. fflush(sharelog_file);
  342. mutex_unlock(&sharelog_lock);
  343. if (ret != 1)
  344. applog(LOG_ERR, "sharelog fwrite error");
  345. }
  346. /* Return value is ignored if not called from add_pool_details */
  347. static struct pool *add_pool(void)
  348. {
  349. struct pool *pool;
  350. pool = calloc(sizeof(struct pool), 1);
  351. if (!pool)
  352. quit(1, "Failed to malloc pool in add_pool");
  353. pool->pool_no = pool->prio = total_pools;
  354. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  355. quit(1, "Failed to pthread_mutex_init in add_pool");
  356. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  357. quit(1, "Failed to pthread_cond_init in add_pool");
  358. INIT_LIST_HEAD(&pool->curlring);
  359. /* Make sure the pool doesn't think we've been idle since time 0 */
  360. pool->tv_idle.tv_sec = ~0UL;
  361. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  362. pools[total_pools++] = pool;
  363. return pool;
  364. }
  365. /* Pool variant of test and set */
  366. static bool pool_tset(struct pool *pool, bool *var)
  367. {
  368. bool ret;
  369. mutex_lock(&pool->pool_lock);
  370. ret = *var;
  371. *var = true;
  372. mutex_unlock(&pool->pool_lock);
  373. return ret;
  374. }
  375. bool pool_tclear(struct pool *pool, bool *var)
  376. {
  377. bool ret;
  378. mutex_lock(&pool->pool_lock);
  379. ret = *var;
  380. *var = false;
  381. mutex_unlock(&pool->pool_lock);
  382. return ret;
  383. }
  384. struct pool *current_pool(void)
  385. {
  386. struct pool *pool;
  387. mutex_lock(&control_lock);
  388. pool = currentpool;
  389. mutex_unlock(&control_lock);
  390. return pool;
  391. }
  392. char *set_int_range(const char *arg, int *i, int min, int max)
  393. {
  394. char *err = opt_set_intval(arg, i);
  395. if (err)
  396. return err;
  397. if (*i < min || *i > max)
  398. return "Value out of range";
  399. return NULL;
  400. }
  401. static char *set_int_0_to_9999(const char *arg, int *i)
  402. {
  403. return set_int_range(arg, i, 0, 9999);
  404. }
  405. static char *set_int_1_to_65535(const char *arg, int *i)
  406. {
  407. return set_int_range(arg, i, 1, 65535);
  408. }
  409. static char *set_int_0_to_10(const char *arg, int *i)
  410. {
  411. return set_int_range(arg, i, 0, 10);
  412. }
  413. static char *set_int_1_to_10(const char *arg, int *i)
  414. {
  415. return set_int_range(arg, i, 1, 10);
  416. }
  417. #ifdef USE_FPGA_SERIAL
  418. static char *add_serial(char *arg)
  419. {
  420. string_elist_add(arg, &scan_devices);
  421. return NULL;
  422. }
  423. #endif
  424. static char *set_devices(char *arg)
  425. {
  426. int i = strtol(arg, &arg, 0);
  427. if (*arg) {
  428. if (*arg == '?') {
  429. devices_enabled = -1;
  430. return NULL;
  431. }
  432. return "Invalid device number";
  433. }
  434. if (i < 0 || i >= (int)(sizeof(devices_enabled) * 8) - 1)
  435. return "Invalid device number";
  436. devices_enabled |= 1 << i;
  437. return NULL;
  438. }
  439. static char *set_loadbalance(enum pool_strategy *strategy)
  440. {
  441. *strategy = POOL_LOADBALANCE;
  442. return NULL;
  443. }
  444. static char *set_rotate(const char *arg, int *i)
  445. {
  446. pool_strategy = POOL_ROTATE;
  447. return set_int_range(arg, i, 0, 9999);
  448. }
  449. static char *set_rr(enum pool_strategy *strategy)
  450. {
  451. *strategy = POOL_ROUNDROBIN;
  452. return NULL;
  453. }
  454. static char *set_url(char *arg)
  455. {
  456. struct pool *pool;
  457. total_urls++;
  458. if (total_urls > total_pools)
  459. add_pool();
  460. pool = pools[total_urls - 1];
  461. opt_set_charp(arg, &pool->rpc_url);
  462. if (strncmp(arg, "http://", 7) &&
  463. strncmp(arg, "https://", 8)) {
  464. char *httpinput;
  465. httpinput = malloc(255);
  466. if (!httpinput)
  467. quit(1, "Failed to malloc httpinput");
  468. strcpy(httpinput, "http://");
  469. strncat(httpinput, arg, 248);
  470. pool->rpc_url = httpinput;
  471. }
  472. return NULL;
  473. }
  474. static char *set_user(const char *arg)
  475. {
  476. struct pool *pool;
  477. if (total_userpasses)
  478. return "Use only user + pass or userpass, but not both";
  479. total_users++;
  480. if (total_users > total_pools)
  481. add_pool();
  482. pool = pools[total_users - 1];
  483. opt_set_charp(arg, &pool->rpc_user);
  484. return NULL;
  485. }
  486. static char *set_pass(const char *arg)
  487. {
  488. struct pool *pool;
  489. if (total_userpasses)
  490. return "Use only user + pass or userpass, but not both";
  491. total_passes++;
  492. if (total_passes > total_pools)
  493. add_pool();
  494. pool = pools[total_passes - 1];
  495. opt_set_charp(arg, &pool->rpc_pass);
  496. return NULL;
  497. }
  498. static char *set_userpass(const char *arg)
  499. {
  500. struct pool *pool;
  501. if (total_users || total_passes)
  502. return "Use only user + pass or userpass, but not both";
  503. total_userpasses++;
  504. if (total_userpasses > total_pools)
  505. add_pool();
  506. pool = pools[total_userpasses - 1];
  507. opt_set_charp(arg, &pool->rpc_userpass);
  508. return NULL;
  509. }
  510. static char *enable_debug(bool *flag)
  511. {
  512. *flag = true;
  513. /* Turn on verbose output, too. */
  514. opt_log_output = true;
  515. return NULL;
  516. }
  517. static char *set_schedtime(const char *arg, struct schedtime *st)
  518. {
  519. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  520. return "Invalid time set, should be HH:MM";
  521. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  522. return "Invalid time set.";
  523. st->enable = true;
  524. return NULL;
  525. }
  526. static char* set_sharelog(char *arg)
  527. {
  528. char *r = "";
  529. long int i = strtol(arg, &r, 10);
  530. if ((!*r) && i >= 0 && i <= INT_MAX) {
  531. sharelog_file = fdopen((int)i, "a");
  532. if (!sharelog_file)
  533. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  534. } else if (!strcmp(arg, "-")) {
  535. sharelog_file = stdout;
  536. if (!sharelog_file)
  537. applog(LOG_ERR, "Standard output missing for share log");
  538. } else {
  539. sharelog_file = fopen(arg, "a");
  540. if (!sharelog_file)
  541. applog(LOG_ERR, "Failed to open %s for share log", arg);
  542. }
  543. return NULL;
  544. }
  545. static char *temp_cutoff_str = NULL;
  546. char *set_temp_cutoff(char *arg)
  547. {
  548. int val;
  549. if (!(arg && arg[0]))
  550. return "Invalid parameters for set temp cutoff";
  551. val = atoi(arg);
  552. if (val < 0 || val > 200)
  553. return "Invalid value passed to set temp cutoff";
  554. temp_cutoff_str = arg;
  555. return NULL;
  556. }
  557. static void load_temp_cutoffs()
  558. {
  559. int i, val = 0, device = 0;
  560. char *nextptr;
  561. if (temp_cutoff_str) {
  562. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  563. if (device >= total_devices)
  564. quit(1, "Too many values passed to set temp cutoff");
  565. val = atoi(nextptr);
  566. if (val < 0 || val > 200)
  567. quit(1, "Invalid value passed to set temp cutoff");
  568. devices[device]->cutofftemp = val;
  569. }
  570. } else {
  571. for (i = device; i < total_devices; ++i) {
  572. if (!devices[i]->cutofftemp)
  573. devices[i]->cutofftemp = opt_cutofftemp;
  574. }
  575. return;
  576. }
  577. if (device <= 1) {
  578. for (i = device; i < total_devices; ++i)
  579. devices[i]->cutofftemp = val;
  580. }
  581. }
  582. static char *set_api_allow(const char *arg)
  583. {
  584. opt_set_charp(arg, &opt_api_allow);
  585. return NULL;
  586. }
  587. static char *set_api_groups(const char *arg)
  588. {
  589. opt_set_charp(arg, &opt_api_groups);
  590. return NULL;
  591. }
  592. static char *set_api_description(const char *arg)
  593. {
  594. opt_set_charp(arg, &opt_api_description);
  595. return NULL;
  596. }
  597. #ifdef USE_ICARUS
  598. static char *set_icarus_options(const char *arg)
  599. {
  600. opt_set_charp(arg, &opt_icarus_options);
  601. return NULL;
  602. }
  603. static char *set_icarus_timing(const char *arg)
  604. {
  605. opt_set_charp(arg, &opt_icarus_timing);
  606. return NULL;
  607. }
  608. #endif
  609. /* These options are available from config file or commandline */
  610. static struct opt_table opt_config_table[] = {
  611. #ifdef WANT_CPUMINE
  612. OPT_WITH_ARG("--algo|-a",
  613. set_algo, show_algo, &opt_algo,
  614. "Specify sha256 implementation for CPU mining:\n"
  615. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  616. "\n\tc\t\tLinux kernel sha256, implemented in C"
  617. #ifdef WANT_SSE2_4WAY
  618. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  619. #endif
  620. #ifdef WANT_VIA_PADLOCK
  621. "\n\tvia\t\tVIA padlock implementation"
  622. #endif
  623. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  624. #ifdef WANT_CRYPTOPP_ASM32
  625. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  626. #endif
  627. #ifdef WANT_X8632_SSE2
  628. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  629. #endif
  630. #ifdef WANT_X8664_SSE2
  631. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  632. #endif
  633. #ifdef WANT_X8664_SSE4
  634. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  635. #endif
  636. #ifdef WANT_ALTIVEC_4WAY
  637. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  638. #endif
  639. ),
  640. #endif
  641. OPT_WITH_ARG("--api-allow",
  642. set_api_allow, NULL, NULL,
  643. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  644. OPT_WITH_ARG("--api-description",
  645. set_api_description, NULL, NULL,
  646. "Description placed in the API status header, default: BFGMiner version"),
  647. OPT_WITH_ARG("--api-groups",
  648. set_api_groups, NULL, NULL,
  649. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  650. OPT_WITHOUT_ARG("--api-listen",
  651. opt_set_bool, &opt_api_listen,
  652. "Enable API, default: disabled"),
  653. OPT_WITHOUT_ARG("--api-network",
  654. opt_set_bool, &opt_api_network,
  655. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  656. OPT_WITH_ARG("--api-port",
  657. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  658. "Port number of miner API"),
  659. #ifdef HAVE_ADL
  660. OPT_WITHOUT_ARG("--auto-fan",
  661. opt_set_bool, &opt_autofan,
  662. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  663. OPT_WITHOUT_ARG("--auto-gpu",
  664. opt_set_bool, &opt_autoengine,
  665. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  666. #endif
  667. OPT_WITHOUT_ARG("--benchmark",
  668. opt_set_bool, &opt_benchmark,
  669. "Run BFGMiner in benchmark mode - produces no shares"),
  670. #if defined(USE_BITFORCE)
  671. OPT_WITHOUT_ARG("--bfl-range",
  672. opt_set_bool, &opt_bfl_noncerange,
  673. "Use nonce range on bitforce devices if supported"),
  674. #endif
  675. #ifdef WANT_CPUMINE
  676. OPT_WITH_ARG("--bench-algo|-b",
  677. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  678. opt_hidden),
  679. OPT_WITH_ARG("--cpu-threads|-t",
  680. force_nthreads_int, opt_show_intval, &opt_n_threads,
  681. "Number of miner CPU threads"),
  682. #endif
  683. OPT_WITHOUT_ARG("--debug|-D",
  684. enable_debug, &opt_debug,
  685. "Enable debug output"),
  686. OPT_WITH_ARG("--device|-d",
  687. set_devices, NULL, NULL,
  688. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  689. OPT_WITHOUT_ARG("--disable-gpu|-G",
  690. opt_set_bool, &opt_nogpu,
  691. #ifdef HAVE_OPENCL
  692. "Disable GPU mining even if suitable devices exist"
  693. #else
  694. opt_hidden
  695. #endif
  696. ),
  697. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  698. OPT_WITHOUT_ARG("--enable-cpu|-C",
  699. opt_set_bool, &opt_usecpu,
  700. "Enable CPU mining with other mining (default: no CPU mining if other devices exist)"),
  701. #endif
  702. OPT_WITH_ARG("--expiry|-E",
  703. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  704. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  705. OPT_WITHOUT_ARG("--failover-only",
  706. opt_set_bool, &opt_fail_only,
  707. "Don't leak work to backup pools when primary pool is lagging"),
  708. #ifdef HAVE_OPENCL
  709. OPT_WITH_ARG("--gpu-dyninterval",
  710. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  711. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  712. OPT_WITH_ARG("--gpu-platform",
  713. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  714. "Select OpenCL platform ID to use for GPU mining"),
  715. OPT_WITH_ARG("--gpu-threads|-g",
  716. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  717. "Number of threads per GPU (1 - 10)"),
  718. #ifdef HAVE_ADL
  719. OPT_WITH_ARG("--gpu-engine",
  720. set_gpu_engine, NULL, NULL,
  721. "GPU engine (over)clock range in Mhz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  722. OPT_WITH_ARG("--gpu-fan",
  723. set_gpu_fan, NULL, NULL,
  724. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  725. OPT_WITH_ARG("--gpu-map",
  726. set_gpu_map, NULL, NULL,
  727. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  728. OPT_WITH_ARG("--gpu-memclock",
  729. set_gpu_memclock, NULL, NULL,
  730. "Set the GPU memory (over)clock in Mhz - one value for all or separate by commas for per card"),
  731. OPT_WITH_ARG("--gpu-memdiff",
  732. set_gpu_memdiff, NULL, NULL,
  733. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  734. OPT_WITH_ARG("--gpu-powertune",
  735. set_gpu_powertune, NULL, NULL,
  736. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  737. OPT_WITHOUT_ARG("--gpu-reorder",
  738. opt_set_bool, &opt_reorder,
  739. "Attempt to reorder GPU devices according to PCI Bus ID"),
  740. OPT_WITH_ARG("--gpu-vddc",
  741. set_gpu_vddc, NULL, NULL,
  742. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  743. #endif
  744. #ifdef USE_SCRYPT
  745. OPT_WITH_ARG("--lookup-gap",
  746. set_lookup_gap, NULL, NULL,
  747. "Set GPU lookup gap for scrypt mining, comma separated"),
  748. #endif
  749. OPT_WITH_ARG("--intensity|-I",
  750. set_intensity, NULL, NULL,
  751. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  752. #endif
  753. #if defined(HAVE_OPENCL) || defined(HAVE_MODMINER)
  754. OPT_WITH_ARG("--kernel-path|-K",
  755. opt_set_charp, opt_show_charp, &opt_kernel_path,
  756. "Specify a path to where bitstream and kernel files are"),
  757. #endif
  758. #ifdef HAVE_OPENCL
  759. OPT_WITH_ARG("--kernel|-k",
  760. set_kernel, NULL, NULL,
  761. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  762. #endif
  763. #ifdef USE_ICARUS
  764. OPT_WITH_ARG("--icarus-options",
  765. set_icarus_options, NULL, NULL,
  766. opt_hidden),
  767. OPT_WITH_ARG("--icarus-timing",
  768. set_icarus_timing, NULL, NULL,
  769. opt_hidden),
  770. #endif
  771. OPT_WITHOUT_ARG("--load-balance",
  772. set_loadbalance, &pool_strategy,
  773. "Change multipool strategy from failover to even load balance"),
  774. OPT_WITH_ARG("--log|-l",
  775. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  776. "Interval in seconds between log output"),
  777. #if defined(unix)
  778. OPT_WITH_ARG("--monitor|-m",
  779. opt_set_charp, NULL, &opt_stderr_cmd,
  780. "Use custom pipe cmd for output messages"),
  781. #endif // defined(unix)
  782. OPT_WITHOUT_ARG("--net-delay",
  783. opt_set_bool, &opt_delaynet,
  784. "Impose small delays in networking to not overload slow routers"),
  785. OPT_WITHOUT_ARG("--no-adl",
  786. opt_set_bool, &opt_noadl,
  787. #ifdef HAVE_ADL
  788. "Disable the ATI display library used for monitoring and setting GPU parameters"
  789. #else
  790. opt_hidden
  791. #endif
  792. ),
  793. OPT_WITHOUT_ARG("--no-longpoll",
  794. opt_set_invbool, &want_longpoll,
  795. "Disable X-Long-Polling support"),
  796. OPT_WITHOUT_ARG("--no-pool-disable",
  797. opt_set_invbool, &opt_disable_pool,
  798. "Do not automatically disable pools that continually reject shares"),
  799. OPT_WITHOUT_ARG("--no-restart",
  800. opt_set_invbool, &opt_restart,
  801. #ifdef HAVE_OPENCL
  802. "Do not attempt to restart GPUs that hang"
  803. #else
  804. opt_hidden
  805. #endif
  806. ),
  807. OPT_WITHOUT_ARG("--no-submit-stale",
  808. opt_set_invbool, &opt_submit_stale,
  809. "Don't submit shares if they are detected as stale"),
  810. OPT_WITH_ARG("--pass|-p",
  811. set_pass, NULL, NULL,
  812. "Password for bitcoin JSON-RPC server"),
  813. OPT_WITHOUT_ARG("--per-device-stats",
  814. opt_set_bool, &want_per_device_stats,
  815. "Force verbose mode and output per-device statistics"),
  816. OPT_WITHOUT_ARG("--protocol-dump|-P",
  817. opt_set_bool, &opt_protocol,
  818. "Verbose dump of protocol-level activities"),
  819. OPT_WITH_ARG("--queue|-Q",
  820. set_int_0_to_9999, opt_show_intval, &opt_queue,
  821. "Minimum number of work items to have queued (0+)"),
  822. OPT_WITHOUT_ARG("--quiet|-q",
  823. opt_set_bool, &opt_quiet,
  824. "Disable logging output, display status and errors"),
  825. OPT_WITHOUT_ARG("--real-quiet",
  826. opt_set_bool, &opt_realquiet,
  827. "Disable all output"),
  828. OPT_WITHOUT_ARG("--remove-disabled",
  829. opt_set_bool, &opt_removedisabled,
  830. "Remove disabled devices entirely, as if they didn't exist"),
  831. OPT_WITH_ARG("--retries|-r",
  832. opt_set_intval, opt_show_intval, &opt_retries,
  833. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  834. OPT_WITH_ARG("--retry-pause|-R",
  835. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  836. "Number of seconds to pause, between retries"),
  837. OPT_WITH_ARG("--rotate",
  838. set_rotate, opt_show_intval, &opt_rotate_period,
  839. "Change multipool strategy from failover to regularly rotate at N minutes"),
  840. OPT_WITHOUT_ARG("--round-robin",
  841. set_rr, &pool_strategy,
  842. "Change multipool strategy from failover to round robin on failure"),
  843. #ifdef USE_FPGA_SERIAL
  844. OPT_WITH_ARG("--scan-serial|-S",
  845. add_serial, NULL, NULL,
  846. "Serial port to probe for FPGA Mining device"),
  847. #endif
  848. OPT_WITH_ARG("--scan-time|-s",
  849. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  850. "Upper bound on time spent scanning current work, in seconds"),
  851. OPT_WITH_ARG("--sched-start",
  852. set_schedtime, NULL, &schedstart,
  853. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  854. OPT_WITH_ARG("--sched-stop",
  855. set_schedtime, NULL, &schedstop,
  856. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  857. #ifdef USE_SCRYPT
  858. OPT_WITHOUT_ARG("--scrypt",
  859. opt_set_bool, &opt_scrypt,
  860. "Use the scrypt algorithm for mining (non-bitcoin)"),
  861. #ifdef HAVE_OPENCL
  862. OPT_WITH_ARG("--shaders",
  863. set_shaders, NULL, NULL,
  864. "GPU shaders per card for tuning scrypt, comma separated"),
  865. #endif
  866. #endif
  867. OPT_WITH_ARG("--sharelog",
  868. set_sharelog, NULL, NULL,
  869. "Append share log to file"),
  870. OPT_WITH_ARG("--shares",
  871. opt_set_intval, NULL, &opt_shares,
  872. "Quit after mining N shares (default: unlimited)"),
  873. OPT_WITH_ARG("--socks-proxy",
  874. opt_set_charp, NULL, &opt_socks_proxy,
  875. "Set socks4 proxy (host:port)"),
  876. OPT_WITHOUT_ARG("--submit-stale",
  877. opt_set_bool, &opt_submit_stale,
  878. opt_hidden),
  879. #ifdef HAVE_SYSLOG_H
  880. OPT_WITHOUT_ARG("--syslog",
  881. opt_set_bool, &use_syslog,
  882. "Use system log for output messages (default: standard error)"),
  883. #endif
  884. #if defined(HAVE_ADL) || defined(USE_BITFORCE) || defined(USE_MODMINER)
  885. OPT_WITH_ARG("--temp-cutoff",
  886. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  887. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  888. #endif
  889. #ifdef HAVE_ADL
  890. OPT_WITH_ARG("--temp-hysteresis",
  891. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  892. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  893. OPT_WITH_ARG("--temp-overheat",
  894. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  895. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  896. OPT_WITH_ARG("--temp-target",
  897. set_temp_target, opt_show_intval, &opt_targettemp,
  898. "Target temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  899. #endif
  900. OPT_WITHOUT_ARG("--text-only|-T",
  901. opt_set_invbool, &use_curses,
  902. #ifdef HAVE_CURSES
  903. "Disable ncurses formatted screen output"
  904. #else
  905. opt_hidden
  906. #endif
  907. ),
  908. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  909. OPT_WITH_ARG("--thread-concurrency",
  910. set_thread_concurrency, NULL, NULL,
  911. "Set GPU thread concurrency for scrypt mining, comma separated"),
  912. #endif
  913. OPT_WITH_ARG("--url|-o",
  914. set_url, NULL, NULL,
  915. "URL for bitcoin JSON-RPC server"),
  916. OPT_WITH_ARG("--user|-u",
  917. set_user, NULL, NULL,
  918. "Username for bitcoin JSON-RPC server"),
  919. #ifdef HAVE_OPENCL
  920. OPT_WITH_ARG("--vectors|-v",
  921. set_vector, NULL, NULL,
  922. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  923. #endif
  924. OPT_WITHOUT_ARG("--verbose",
  925. opt_set_bool, &opt_log_output,
  926. "Log verbose output to stderr as well as status output"),
  927. #ifdef HAVE_OPENCL
  928. OPT_WITH_ARG("--worksize|-w",
  929. set_worksize, NULL, NULL,
  930. "Override detected optimal worksize - one value or comma separated list"),
  931. #endif
  932. OPT_WITH_ARG("--userpass|-O",
  933. set_userpass, NULL, NULL,
  934. "Username:Password pair for bitcoin JSON-RPC server"),
  935. OPT_WITH_ARG("--pools",
  936. opt_set_bool, NULL, NULL, opt_hidden),
  937. OPT_ENDTABLE
  938. };
  939. static char *load_config(const char *arg, void __maybe_unused *unused);
  940. static int fileconf_load;
  941. static char *parse_config(json_t *config, bool fileconf)
  942. {
  943. static char err_buf[200];
  944. struct opt_table *opt;
  945. json_t *val;
  946. if (fileconf && !fileconf_load)
  947. fileconf_load = 1;
  948. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  949. char *p, *name;
  950. /* We don't handle subtables. */
  951. assert(!(opt->type & OPT_SUBTABLE));
  952. /* Pull apart the option name(s). */
  953. name = strdup(opt->names);
  954. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  955. char *err = "Invalid value";
  956. /* Ignore short options. */
  957. if (p[1] != '-')
  958. continue;
  959. val = json_object_get(config, p+2);
  960. if (!val)
  961. continue;
  962. if (opt->type & OPT_HASARG) {
  963. if (json_is_string(val)) {
  964. err = opt->cb_arg(json_string_value(val),
  965. opt->u.arg);
  966. } else if (json_is_number(val)) {
  967. char buf[256], *p, *q;
  968. snprintf(buf, 256, "%f", json_number_value(val));
  969. if ( (p = strchr(buf, '.')) ) {
  970. // Trim /\.0*$/ to work properly with integer-only arguments
  971. q = p;
  972. while (*(++q) == '0') {}
  973. if (*q == '\0')
  974. *p = '\0';
  975. }
  976. err = opt->cb_arg(buf, opt->u.arg);
  977. } else if (json_is_array(val)) {
  978. int n, size = json_array_size(val);
  979. err = NULL;
  980. for (n = 0; n < size && !err; n++) {
  981. if (json_is_string(json_array_get(val, n)))
  982. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  983. else if (json_is_object(json_array_get(val, n)))
  984. err = parse_config(json_array_get(val, n), false);
  985. }
  986. }
  987. } else if (opt->type & OPT_NOARG) {
  988. if (json_is_true(val))
  989. err = opt->cb(opt->u.arg);
  990. else if (json_is_boolean(val)) {
  991. if (opt->cb == (void*)opt_set_bool)
  992. err = opt_set_invbool(opt->u.arg);
  993. else if (opt->cb == (void*)opt_set_invbool)
  994. err = opt_set_bool(opt->u.arg);
  995. }
  996. }
  997. if (err) {
  998. /* Allow invalid values to be in configuration
  999. * file, just skipping over them provided the
  1000. * JSON is still valid after that. */
  1001. if (fileconf) {
  1002. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1003. fileconf_load = -1;
  1004. } else {
  1005. sprintf(err_buf, "Parsing JSON option %s: %s",
  1006. p, err);
  1007. return err_buf;
  1008. }
  1009. }
  1010. }
  1011. free(name);
  1012. }
  1013. val = json_object_get(config, JSON_INCLUDE_CONF);
  1014. if (val && json_is_string(val))
  1015. return load_config(json_string_value(val), NULL);
  1016. return NULL;
  1017. }
  1018. char *cnfbuf = NULL;
  1019. static char *load_config(const char *arg, void __maybe_unused *unused)
  1020. {
  1021. json_error_t err;
  1022. json_t *config;
  1023. char *json_error;
  1024. if (!cnfbuf)
  1025. cnfbuf = strdup(arg);
  1026. if (++include_count > JSON_MAX_DEPTH)
  1027. return JSON_MAX_DEPTH_ERR;
  1028. #if JANSSON_MAJOR_VERSION > 1
  1029. config = json_load_file(arg, 0, &err);
  1030. #else
  1031. config = json_load_file(arg, &err);
  1032. #endif
  1033. if (!json_is_object(config)) {
  1034. json_error = malloc(JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text));
  1035. if (!json_error)
  1036. quit(1, "Malloc failure in json error");
  1037. sprintf(json_error, JSON_LOAD_ERROR, arg, err.text);
  1038. return json_error;
  1039. }
  1040. config_loaded = true;
  1041. /* Parse the config now, so we can override it. That can keep pointers
  1042. * so don't free config object. */
  1043. return parse_config(config, true);
  1044. }
  1045. static void load_default_config(void)
  1046. {
  1047. cnfbuf = malloc(PATH_MAX);
  1048. #if defined(unix)
  1049. if (getenv("HOME") && *getenv("HOME")) {
  1050. strcpy(cnfbuf, getenv("HOME"));
  1051. strcat(cnfbuf, "/");
  1052. } else
  1053. strcpy(cnfbuf, "");
  1054. char *dirp = cnfbuf + strlen(cnfbuf);
  1055. strcpy(dirp, ".bfgminer/");
  1056. strcat(dirp, def_conf);
  1057. if (access(cnfbuf, R_OK))
  1058. // No BFGMiner config, try Cgminer's...
  1059. strcpy(dirp, ".cgminer/cgminer.conf");
  1060. #else
  1061. strcpy(cnfbuf, "");
  1062. strcat(cnfbuf, def_conf);
  1063. #endif
  1064. if (!access(cnfbuf, R_OK))
  1065. load_config(cnfbuf, NULL);
  1066. else {
  1067. free(cnfbuf);
  1068. cnfbuf = NULL;
  1069. }
  1070. }
  1071. extern const char *opt_argv0;
  1072. static char *opt_verusage_and_exit(const char *extra)
  1073. {
  1074. printf("%s\nBuilt with "
  1075. #ifdef HAVE_OPENCL
  1076. "GPU "
  1077. #endif
  1078. #ifdef WANT_CPUMINE
  1079. "CPU "
  1080. #endif
  1081. #ifdef USE_BITFORCE
  1082. "bitforce "
  1083. #endif
  1084. #ifdef USE_ICARUS
  1085. "icarus "
  1086. #endif
  1087. #ifdef USE_MODMINER
  1088. "modminer "
  1089. #endif
  1090. #ifdef USE_ZTEX
  1091. "ztex "
  1092. #endif
  1093. #ifdef USE_SCRYPT
  1094. "scrypt "
  1095. #endif
  1096. "mining support.\n"
  1097. , packagename);
  1098. printf("%s", opt_usage(opt_argv0, extra));
  1099. fflush(stdout);
  1100. exit(0);
  1101. }
  1102. /* These options are available from commandline only */
  1103. static struct opt_table opt_cmdline_table[] = {
  1104. OPT_WITH_ARG("--config|-c",
  1105. load_config, NULL, NULL,
  1106. "Load a JSON-format configuration file\n"
  1107. "See example.conf for an example configuration."),
  1108. OPT_WITHOUT_ARG("--help|-h",
  1109. opt_verusage_and_exit, NULL,
  1110. "Print this message"),
  1111. #ifdef HAVE_OPENCL
  1112. OPT_WITHOUT_ARG("--ndevs|-n",
  1113. print_ndevs_and_exit, &nDevs,
  1114. "Display number of detected GPUs, OpenCL platform information, and exit"),
  1115. #endif
  1116. OPT_WITHOUT_ARG("--version|-V",
  1117. opt_version_and_exit, packagename,
  1118. "Display version and exit"),
  1119. OPT_ENDTABLE
  1120. };
  1121. static bool jobj_binary(const json_t *obj, const char *key,
  1122. void *buf, size_t buflen, bool required)
  1123. {
  1124. const char *hexstr;
  1125. json_t *tmp;
  1126. tmp = json_object_get(obj, key);
  1127. if (unlikely(!tmp)) {
  1128. if (unlikely(required))
  1129. applog(LOG_ERR, "JSON key '%s' not found", key);
  1130. return false;
  1131. }
  1132. hexstr = json_string_value(tmp);
  1133. if (unlikely(!hexstr)) {
  1134. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1135. return false;
  1136. }
  1137. if (!hex2bin(buf, hexstr, buflen))
  1138. return false;
  1139. return true;
  1140. }
  1141. static void calc_midstate(struct work *work)
  1142. {
  1143. union {
  1144. unsigned char c[64];
  1145. uint32_t i[16];
  1146. } data;
  1147. swap32yes(&data.i[0], work->data, 16);
  1148. sha2_context ctx;
  1149. sha2_starts( &ctx, 0 );
  1150. sha2_update( &ctx, data.c, 64 );
  1151. memcpy(work->midstate, ctx.state, sizeof(work->midstate));
  1152. swap32tole(work->midstate, work->midstate, 8);
  1153. }
  1154. static bool work_decode(const json_t *val, struct work *work)
  1155. {
  1156. unsigned char bits = 0, i;
  1157. if (unlikely(detect_algo == 1)) {
  1158. json_t *tmp = json_object_get(val, "algorithm");
  1159. const char *v = tmp ? json_string_value(tmp) : "";
  1160. if (strncasecmp(v, "scrypt", 6))
  1161. detect_algo = 2;
  1162. }
  1163. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data), true))) {
  1164. applog(LOG_ERR, "JSON inval data");
  1165. goto err_out;
  1166. }
  1167. if (!jobj_binary(val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  1168. // Calculate it ourselves
  1169. applog(LOG_DEBUG, "Calculating midstate locally");
  1170. calc_midstate(work);
  1171. }
  1172. if (!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1), false)) {
  1173. // Always the same anyway
  1174. memcpy(work->hash1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x80\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0", 64);
  1175. }
  1176. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target), true))) {
  1177. applog(LOG_ERR, "JSON inval target");
  1178. goto err_out;
  1179. }
  1180. for (i = 32; i--; )
  1181. {
  1182. if (work->target[i])
  1183. {
  1184. unsigned char j = ~work->target[i];
  1185. while (j & 0x80)
  1186. {
  1187. ++bits;
  1188. j <<= 1;
  1189. }
  1190. break;
  1191. }
  1192. bits += 8;
  1193. }
  1194. work->difficulty = pow(2, bits - 32);
  1195. memset(work->hash, 0, sizeof(work->hash));
  1196. gettimeofday(&work->tv_staged, NULL);
  1197. return true;
  1198. err_out:
  1199. return false;
  1200. }
  1201. int dev_from_id(int thr_id)
  1202. {
  1203. return thr_info[thr_id].cgpu->device_id;
  1204. }
  1205. /* Make the change in the recent value adjust dynamically when the difference
  1206. * is large, but damp it when the values are closer together. This allows the
  1207. * value to change quickly, but not fluctuate too dramatically when it has
  1208. * stabilised. */
  1209. void decay_time(double *f, double fadd)
  1210. {
  1211. double ratio = 0;
  1212. if (likely(*f > 0)) {
  1213. ratio = fadd / *f;
  1214. if (ratio > 1)
  1215. ratio = 1 / ratio;
  1216. }
  1217. if (ratio > 0.63)
  1218. *f = (fadd * 0.58 + *f) / 1.58;
  1219. else
  1220. *f = (fadd + *f * 0.58) / 1.58;
  1221. }
  1222. static int total_staged(void)
  1223. {
  1224. int ret;
  1225. mutex_lock(stgd_lock);
  1226. ret = HASH_COUNT(staged_work);
  1227. mutex_unlock(stgd_lock);
  1228. return ret;
  1229. }
  1230. static int pool_staged(struct pool *pool)
  1231. {
  1232. int ret;
  1233. mutex_lock(stgd_lock);
  1234. ret = pool->staged;
  1235. mutex_unlock(stgd_lock);
  1236. return ret;
  1237. }
  1238. static int current_staged(void)
  1239. {
  1240. struct pool *pool = current_pool();
  1241. return pool_staged(pool);
  1242. }
  1243. #ifdef HAVE_CURSES
  1244. WINDOW *mainwin, *statuswin, *logwin;
  1245. #endif
  1246. double total_secs = 0.1;
  1247. static char statusline[256];
  1248. /* logstart is where the log window should start */
  1249. static int devcursor, logstart, logcursor;
  1250. #ifdef HAVE_CURSES
  1251. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  1252. static int statusy;
  1253. static int devsummaryYOffset;
  1254. #endif
  1255. #ifdef HAVE_OPENCL
  1256. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  1257. #endif
  1258. struct cgpu_info *cpus;
  1259. #ifdef HAVE_CURSES
  1260. static inline void unlock_curses(void)
  1261. {
  1262. mutex_unlock(&console_lock);
  1263. }
  1264. static inline void lock_curses(void)
  1265. {
  1266. mutex_lock(&console_lock);
  1267. }
  1268. static bool curses_active_locked(void)
  1269. {
  1270. bool ret;
  1271. lock_curses();
  1272. ret = curses_active;
  1273. if (!ret)
  1274. unlock_curses();
  1275. return ret;
  1276. }
  1277. #endif
  1278. void tailsprintf(char *f, const char *fmt, ...)
  1279. {
  1280. va_list ap;
  1281. va_start(ap, fmt);
  1282. vsprintf(f + strlen(f), fmt, ap);
  1283. va_end(ap);
  1284. }
  1285. static float
  1286. utility_to_hashrate(double utility)
  1287. {
  1288. return utility * 0x4444444;
  1289. }
  1290. static const char*_unitchar = "kMGTPEZY?";
  1291. static void
  1292. hashrate_pick_unit(float hashrate, unsigned char*unit)
  1293. {
  1294. unsigned char i;
  1295. for (i = 0; i <= *unit; ++i)
  1296. hashrate /= 1e3;
  1297. while (hashrate >= 1000)
  1298. {
  1299. hashrate /= 1e3;
  1300. if (likely(_unitchar[*unit] != '?'))
  1301. ++*unit;
  1302. }
  1303. }
  1304. enum h2bs_fmt {
  1305. H2B_NOUNIT, // "xxx.x"
  1306. H2B_SHORT, // "xxx.xMH/s"
  1307. H2B_SPACED, // "xxx.x MH/s"
  1308. };
  1309. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  1310. static char*
  1311. hashrate_to_bufstr(char*buf, float hashrate, signed char unitin, enum h2bs_fmt fmt)
  1312. {
  1313. unsigned char prec, i, ucp, unit;
  1314. if (unitin == -1)
  1315. {
  1316. unit = 0;
  1317. hashrate_pick_unit(hashrate, &unit);
  1318. }
  1319. else
  1320. unit = unitin;
  1321. i = 5;
  1322. switch (fmt) {
  1323. case H2B_SPACED:
  1324. buf[i++] = ' ';
  1325. case H2B_SHORT:
  1326. buf[i++] = _unitchar[unit];
  1327. strcpy(&buf[i], "h/s");
  1328. default:
  1329. break;
  1330. }
  1331. for (i = 0; i <= unit; ++i)
  1332. hashrate /= 1000;
  1333. if (hashrate >= 100 || unit < 2)
  1334. prec = 1;
  1335. else
  1336. if (hashrate >= 10)
  1337. prec = 2;
  1338. else
  1339. prec = 3;
  1340. ucp = (fmt == H2B_NOUNIT ? '\0' : buf[5]);
  1341. sprintf(buf, "%5.*f", prec, hashrate);
  1342. buf[5] = ucp;
  1343. return buf;
  1344. }
  1345. static void
  1346. ti_hashrate_bufstr(char**out, float current, float average, float sharebased, enum h2bs_fmt longfmt)
  1347. {
  1348. unsigned char unit = 0;
  1349. hashrate_pick_unit(current, &unit);
  1350. hashrate_pick_unit(average, &unit);
  1351. hashrate_pick_unit(sharebased, &unit);
  1352. hashrate_to_bufstr(out[0], current, unit, H2B_NOUNIT);
  1353. hashrate_to_bufstr(out[1], average, unit, H2B_NOUNIT);
  1354. hashrate_to_bufstr(out[2], sharebased, unit, longfmt);
  1355. }
  1356. static void get_statline(char *buf, struct cgpu_info *cgpu)
  1357. {
  1358. sprintf(buf, "%s%d ", cgpu->api->name, cgpu->device_id);
  1359. if (cgpu->api->get_statline_before)
  1360. cgpu->api->get_statline_before(buf, cgpu);
  1361. else
  1362. tailsprintf(buf, " | ");
  1363. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  1364. ti_hashrate_bufstr(
  1365. (char*[]){cHr, aHr, uHr},
  1366. 1e6*cgpu->rolling,
  1367. 1e6*cgpu->total_mhashes / total_secs,
  1368. utility_to_hashrate(cgpu->utility_diff1),
  1369. H2B_SPACED);
  1370. tailsprintf(buf, "%ds:%s avg:%s u:%s | A:%d R:%d HW:%d U:%.1f/m",
  1371. opt_log_interval,
  1372. cHr, aHr,
  1373. uHr,
  1374. cgpu->accepted,
  1375. cgpu->rejected,
  1376. cgpu->hw_errors,
  1377. cgpu->utility);
  1378. if (cgpu->api->get_statline)
  1379. cgpu->api->get_statline(buf, cgpu);
  1380. }
  1381. static void text_print_status(int thr_id)
  1382. {
  1383. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1384. char logline[255];
  1385. if (cgpu) {
  1386. get_statline(logline, cgpu);
  1387. printf("%s\n", logline);
  1388. }
  1389. }
  1390. static int global_queued(void);
  1391. #ifdef HAVE_CURSES
  1392. /* Must be called with curses mutex lock held and curses_active */
  1393. static void curses_print_status(void)
  1394. {
  1395. struct pool *pool = current_pool();
  1396. struct timeval now, tv;
  1397. wattron(statuswin, A_BOLD);
  1398. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1399. if (!gettimeofday(&now, NULL))
  1400. {
  1401. unsigned int days, hours;
  1402. div_t d;
  1403. timersub(&now, &miner_started, &tv);
  1404. d = div(tv.tv_sec, 86400);
  1405. days = d.quot;
  1406. d = div(d.rem, 3600);
  1407. hours = d.quot;
  1408. d = div(d.rem, 60);
  1409. wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  1410. , days
  1411. , (days == 1) ? ' ' : 's'
  1412. , hours
  1413. , d.quot
  1414. , d.rem
  1415. );
  1416. }
  1417. wattroff(statuswin, A_BOLD);
  1418. mvwhline(statuswin, 1, 0, '-', 80);
  1419. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1420. wclrtoeol(statuswin);
  1421. mvwprintw(statuswin, 3, 0, " TQ: %d ST: %d SS: %d DW: %d NB: %d GW: %d LW: %d GF: %d RF: %d",
  1422. global_queued(), total_staged(), total_stale, total_discarded, new_blocks,
  1423. total_getworks,
  1424. local_work, total_go, total_ro);
  1425. wclrtoeol(statuswin);
  1426. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1427. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1428. have_longpoll ? "": "out");
  1429. else
  1430. mvwprintw(statuswin, 4, 0, " Connected to %s with%s LP as user %s",
  1431. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1432. wclrtoeol(statuswin);
  1433. mvwprintw(statuswin, 5, 0, " Block: %s... Started: %s", current_hash, blocktime);
  1434. mvwhline(statuswin, 6, 0, '-', 80);
  1435. mvwhline(statuswin, statusy - 1, 0, '-', 80);
  1436. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1437. have_opencl ? "[G]PU management " : "");
  1438. }
  1439. static void adj_width(int var, int *length)
  1440. {
  1441. if ((int)(log10(var) + 1) > *length)
  1442. (*length)++;
  1443. }
  1444. static int dev_width;
  1445. static void curses_print_devstatus(int thr_id)
  1446. {
  1447. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1448. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1449. char logline[255];
  1450. int ypos;
  1451. /* Check this isn't out of the window size */
  1452. ypos = cgpu->cgminer_id;
  1453. ypos += devsummaryYOffset;
  1454. if (ypos < 0)
  1455. return;
  1456. ypos += devcursor;
  1457. if (ypos >= statusy - 1)
  1458. return;
  1459. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1460. cgpu->utility_diff1 = cgpu->accepted_weighed / ( total_secs ?: 1 ) * 60;
  1461. if (wmove(statuswin, ypos, 0) == ERR)
  1462. return;
  1463. wprintw(statuswin, " %s %*d: ", cgpu->api->name, dev_width, cgpu->device_id);
  1464. if (cgpu->api->get_statline_before) {
  1465. logline[0] = '\0';
  1466. cgpu->api->get_statline_before(logline, cgpu);
  1467. wprintw(statuswin, "%s", logline);
  1468. }
  1469. else
  1470. wprintw(statuswin, " | ");
  1471. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SHORT]];
  1472. ti_hashrate_bufstr(
  1473. (char*[]){cHr, aHr, uHr},
  1474. 1e6*cgpu->rolling,
  1475. 1e6*cgpu->total_mhashes / total_secs,
  1476. utility_to_hashrate(cgpu->utility_diff1),
  1477. H2B_SHORT);
  1478. if (cgpu->status == LIFE_DEAD)
  1479. wprintw(statuswin, "DEAD ");
  1480. else if (cgpu->status == LIFE_SICK)
  1481. wprintw(statuswin, "SICK ");
  1482. else if (cgpu->status == LIFE_WAIT)
  1483. wprintw(statuswin, "WAIT ");
  1484. else if (cgpu->deven == DEV_DISABLED)
  1485. wprintw(statuswin, "OFF ");
  1486. else if (cgpu->deven == DEV_RECOVER)
  1487. wprintw(statuswin, "REST ");
  1488. else
  1489. wprintw(statuswin, "%s", cHr);
  1490. adj_width(cgpu->accepted, &awidth);
  1491. adj_width(cgpu->rejected, &rwidth);
  1492. adj_width(cgpu->hw_errors, &hwwidth);
  1493. adj_width(cgpu->utility, &uwidth);
  1494. wprintw(statuswin, "/%s/%s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1495. aHr,
  1496. uHr,
  1497. awidth, cgpu->accepted,
  1498. rwidth, cgpu->rejected,
  1499. hwwidth, cgpu->hw_errors,
  1500. uwidth + 3, cgpu->utility);
  1501. if (cgpu->api->get_statline) {
  1502. logline[0] = '\0';
  1503. cgpu->api->get_statline(logline, cgpu);
  1504. wprintw(statuswin, "%s", logline);
  1505. }
  1506. wclrtoeol(statuswin);
  1507. }
  1508. #endif
  1509. static void print_status(int thr_id)
  1510. {
  1511. if (!curses_active)
  1512. text_print_status(thr_id);
  1513. }
  1514. #ifdef HAVE_CURSES
  1515. /* Check for window resize. Called with curses mutex locked */
  1516. static inline bool change_logwinsize(void)
  1517. {
  1518. int x, y, logx, logy;
  1519. bool ret = false;
  1520. getmaxyx(mainwin, y, x);
  1521. if (x < 80 || y < 25)
  1522. return ret;
  1523. if (y > statusy + 2 && statusy < logstart) {
  1524. if (y - 2 < logstart)
  1525. statusy = y - 2;
  1526. else
  1527. statusy = logstart;
  1528. logcursor = statusy + 1;
  1529. mvwin(logwin, logcursor, 0);
  1530. wresize(statuswin, statusy, x);
  1531. ret = true;
  1532. }
  1533. y -= logcursor;
  1534. getmaxyx(logwin, logy, logx);
  1535. /* Detect screen size change */
  1536. if (x != logx || y != logy) {
  1537. wresize(logwin, y, x);
  1538. ret = true;
  1539. }
  1540. return ret;
  1541. }
  1542. static void check_winsizes(void)
  1543. {
  1544. if (!use_curses)
  1545. return;
  1546. if (curses_active_locked()) {
  1547. int y, x;
  1548. x = getmaxx(statuswin);
  1549. if (logstart > LINES - 2)
  1550. statusy = LINES - 2;
  1551. else
  1552. statusy = logstart;
  1553. logcursor = statusy + 1;
  1554. wresize(statuswin, statusy, x);
  1555. getmaxyx(mainwin, y, x);
  1556. y -= logcursor;
  1557. wresize(logwin, y, x);
  1558. mvwin(logwin, logcursor, 0);
  1559. unlock_curses();
  1560. }
  1561. }
  1562. /* For mandatory printing when mutex is already locked */
  1563. void wlog(const char *f, ...)
  1564. {
  1565. va_list ap;
  1566. va_start(ap, f);
  1567. vw_printw(logwin, f, ap);
  1568. va_end(ap);
  1569. }
  1570. /* Mandatory printing */
  1571. void wlogprint(const char *f, ...)
  1572. {
  1573. va_list ap;
  1574. if (curses_active_locked()) {
  1575. va_start(ap, f);
  1576. vw_printw(logwin, f, ap);
  1577. va_end(ap);
  1578. unlock_curses();
  1579. }
  1580. }
  1581. #endif
  1582. #ifdef HAVE_CURSES
  1583. bool log_curses_only(int prio, const char *f, va_list ap)
  1584. {
  1585. bool high_prio;
  1586. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  1587. if (curses_active_locked()) {
  1588. if (!opt_loginput || high_prio) {
  1589. vw_printw(logwin, f, ap);
  1590. if (high_prio) {
  1591. touchwin(logwin);
  1592. wrefresh(logwin);
  1593. }
  1594. }
  1595. unlock_curses();
  1596. return true;
  1597. }
  1598. return false;
  1599. }
  1600. void clear_logwin(void)
  1601. {
  1602. if (curses_active_locked()) {
  1603. wclear(logwin);
  1604. unlock_curses();
  1605. }
  1606. }
  1607. #endif
  1608. /* regenerate the full work->hash value and also return true if it's a block */
  1609. bool regeneratehash(const struct work *work)
  1610. {
  1611. uint32_t *data32 = (uint32_t *)(work->data);
  1612. unsigned char swap[128];
  1613. uint32_t *swap32 = (uint32_t *)swap;
  1614. unsigned char hash1[32];
  1615. uint32_t *hash32 = (uint32_t *)(work->hash);
  1616. uint32_t difficulty = 0;
  1617. uint32_t diffbytes = 0;
  1618. uint32_t diffvalue = 0;
  1619. uint32_t diffcmp[8];
  1620. int diffshift = 0;
  1621. int i;
  1622. swap32yes(swap32, data32, 80 / 4);
  1623. sha2(swap, 80, hash1, false);
  1624. sha2(hash1, 32, (unsigned char *)(work->hash), false);
  1625. difficulty = be32toh(*((uint32_t *)(work->data + 72)));
  1626. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1627. diffvalue = difficulty & 0x00ffffff;
  1628. diffshift = (diffbytes % 4) * 8;
  1629. if (diffshift == 0) {
  1630. diffshift = 32;
  1631. diffbytes--;
  1632. }
  1633. memset(diffcmp, 0, 32);
  1634. diffcmp[(diffbytes >> 2) + 1] = diffvalue >> (32 - diffshift);
  1635. diffcmp[diffbytes >> 2] = diffvalue << diffshift;
  1636. for (i = 7; i >= 0; i--) {
  1637. uint32_t hash32i = be32toh(hash32[i]);
  1638. if (hash32i > diffcmp[i])
  1639. return false;
  1640. if (hash32i < diffcmp[i])
  1641. return true;
  1642. }
  1643. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1644. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1645. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1646. return true;
  1647. }
  1648. static void enable_pool(struct pool *pool)
  1649. {
  1650. if (pool->enabled != POOL_ENABLED) {
  1651. enabled_pools++;
  1652. pool->enabled = POOL_ENABLED;
  1653. }
  1654. }
  1655. static void disable_pool(struct pool *pool)
  1656. {
  1657. if (pool->enabled == POOL_ENABLED)
  1658. enabled_pools--;
  1659. pool->enabled = POOL_DISABLED;
  1660. }
  1661. static void reject_pool(struct pool *pool)
  1662. {
  1663. if (pool->enabled == POOL_ENABLED)
  1664. enabled_pools--;
  1665. pool->enabled = POOL_REJECTING;
  1666. }
  1667. static bool submit_upstream_work(const struct work *work, CURL *curl)
  1668. {
  1669. char *hexstr = NULL;
  1670. json_t *val, *res;
  1671. char s[345], sd[345];
  1672. bool rc = false;
  1673. int thr_id = work->thr_id;
  1674. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1675. struct pool *pool = work->pool;
  1676. int rolltime;
  1677. uint32_t *hash32;
  1678. char hashshow[64+1] = "";
  1679. /* build hex string */
  1680. hexstr = bin2hex(work->data, sizeof(work->data));
  1681. if (unlikely(!hexstr)) {
  1682. applog(LOG_ERR, "submit_upstream_work OOM");
  1683. goto out_nofree;
  1684. }
  1685. /* build JSON-RPC request */
  1686. sprintf(s,
  1687. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1688. hexstr);
  1689. sprintf(sd,
  1690. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1691. hexstr);
  1692. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1693. /* issue JSON-RPC request */
  1694. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  1695. if (unlikely(!val)) {
  1696. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1697. if (!pool_tset(pool, &pool->submit_fail)) {
  1698. total_ro++;
  1699. pool->remotefail_occasions++;
  1700. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1701. }
  1702. goto out;
  1703. } else if (pool_tclear(pool, &pool->submit_fail))
  1704. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1705. res = json_object_get(val, "result");
  1706. if (!QUIET) {
  1707. hash32 = (uint32_t *)(work->hash);
  1708. if (opt_scrypt)
  1709. sprintf(hashshow, "%08lx.%08lx", (unsigned long)(hash32[7]), (unsigned long)(hash32[6]));
  1710. else {
  1711. sprintf(hashshow, "%08lx.%08lx%s", (unsigned long)(hash32[6]), (unsigned long)(hash32[5]),
  1712. work->block? " BLOCK!" : "");
  1713. }
  1714. }
  1715. /* Theoretically threads could race when modifying accepted and
  1716. * rejected values but the chance of two submits completing at the
  1717. * same time is zero so there is no point adding extra locking */
  1718. if (json_is_true(res)) {
  1719. cgpu->accepted++;
  1720. cgpu->accepted_weighed += work->difficulty;
  1721. total_accepted++;
  1722. total_accepted_weighed += work->difficulty;
  1723. pool->accepted++;
  1724. pool->seq_rejects = 0;
  1725. cgpu->last_share_pool = pool->pool_no;
  1726. cgpu->last_share_pool_time = time(NULL);
  1727. pool->last_share_time = cgpu->last_share_pool_time;
  1728. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1729. if (!QUIET) {
  1730. if (total_pools > 1)
  1731. applog(LOG_NOTICE, "Accepted %s %s %d pool %d",
  1732. hashshow, cgpu->api->name, cgpu->device_id, work->pool->pool_no);
  1733. else
  1734. applog(LOG_NOTICE, "Accepted %s %s %d",
  1735. hashshow, cgpu->api->name, cgpu->device_id);
  1736. }
  1737. sharelog("accept", work);
  1738. if (opt_shares && total_accepted >= opt_shares) {
  1739. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  1740. kill_work();
  1741. goto out;
  1742. }
  1743. /* Detect if a pool that has been temporarily disabled for
  1744. * continually rejecting shares has started accepting shares.
  1745. * This will only happen with the work returned from a
  1746. * longpoll */
  1747. if (unlikely(pool->enabled == POOL_REJECTING)) {
  1748. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  1749. enable_pool(pool);
  1750. switch_pools(NULL);
  1751. }
  1752. } else {
  1753. cgpu->rejected++;
  1754. total_rejected++;
  1755. pool->rejected++;
  1756. pool->seq_rejects++;
  1757. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1758. if (!QUIET) {
  1759. char where[17];
  1760. char disposition[36] = "reject";
  1761. char reason[32];
  1762. if (total_pools > 1)
  1763. sprintf(where, "pool %d", work->pool->pool_no);
  1764. else
  1765. strcpy(where, "");
  1766. res = json_object_get(val, "reject-reason");
  1767. if (res) {
  1768. const char *reasontmp = json_string_value(res);
  1769. size_t reasonLen = strlen(reasontmp);
  1770. if (reasonLen > 28)
  1771. reasonLen = 28;
  1772. reason[0] = ' '; reason[1] = '(';
  1773. memcpy(2 + reason, reasontmp, reasonLen);
  1774. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  1775. memcpy(disposition + 7, reasontmp, reasonLen);
  1776. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  1777. } else
  1778. strcpy(reason, "");
  1779. applog(LOG_NOTICE, "Rejected %s %s %d %s%s",
  1780. hashshow, cgpu->api->name, cgpu->device_id, where, reason);
  1781. sharelog(disposition, work);
  1782. }
  1783. /* Once we have more than a nominal amount of sequential rejects,
  1784. * at least 10 and more than 3 mins at the current utility,
  1785. * disable the pool because some pool error is likely to have
  1786. * ensued. Do not do this if we know the share just happened to
  1787. * be stale due to networking delays.
  1788. */
  1789. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  1790. double utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1791. if (pool->seq_rejects > utility * 3) {
  1792. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  1793. pool->pool_no, pool->seq_rejects);
  1794. reject_pool(pool);
  1795. if (pool == current_pool())
  1796. switch_pools(NULL);
  1797. pool->seq_rejects = 0;
  1798. }
  1799. }
  1800. }
  1801. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1802. cgpu->utility_diff1 = cgpu->accepted_weighed / ( total_secs ?: 1 ) * 60;
  1803. if (!opt_realquiet)
  1804. print_status(thr_id);
  1805. if (!want_per_device_stats) {
  1806. char logline[255];
  1807. get_statline(logline, cgpu);
  1808. applog(LOG_INFO, "%s", logline);
  1809. }
  1810. json_decref(val);
  1811. rc = true;
  1812. out:
  1813. free(hexstr);
  1814. out_nofree:
  1815. return rc;
  1816. }
  1817. static const char *rpc_req =
  1818. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1819. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1820. static inline struct pool *select_pool(bool lagging)
  1821. {
  1822. static int rotating_pool = 0;
  1823. struct pool *pool, *cp;
  1824. cp = current_pool();
  1825. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1826. pool = cp;
  1827. else
  1828. pool = NULL;
  1829. while (!pool) {
  1830. if (++rotating_pool >= total_pools)
  1831. rotating_pool = 0;
  1832. pool = pools[rotating_pool];
  1833. if ((!pool->idle && pool->enabled == POOL_ENABLED) || pool == cp)
  1834. break;
  1835. pool = NULL;
  1836. }
  1837. return pool;
  1838. }
  1839. static void get_benchmark_work(struct work *work)
  1840. {
  1841. // Use a random work block pulled from a pool
  1842. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  1843. size_t bench_size = sizeof(work);
  1844. size_t work_size = sizeof(bench_block);
  1845. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  1846. memset(work, 0, sizeof(work));
  1847. memcpy(work, &bench_block, min_size);
  1848. work->mandatory = true;
  1849. work->pool = pools[0];
  1850. }
  1851. static bool get_upstream_work(struct work *work, CURL *curl)
  1852. {
  1853. struct pool *pool = work->pool;
  1854. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  1855. struct timeval tv_start, tv_end, tv_elapsed;
  1856. json_t *val = NULL;
  1857. bool rc = false;
  1858. int retries = 0;
  1859. char *url;
  1860. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1861. url = pool->rpc_url;
  1862. gettimeofday(&tv_start, NULL);
  1863. retry:
  1864. /* A single failure response here might be reported as a dead pool and
  1865. * there may be temporary denied messages etc. falsely reporting
  1866. * failure so retry a few times before giving up */
  1867. while (!val && retries++ < 3) {
  1868. pool_stats->getwork_attempts++;
  1869. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req,
  1870. false, false, &work->rolltime, pool, false);
  1871. }
  1872. if (unlikely(!val)) {
  1873. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1874. goto out;
  1875. }
  1876. rc = work_decode(json_object_get(val, "result"), work);
  1877. if (!rc && retries < 3)
  1878. goto retry;
  1879. gettimeofday(&tv_end, NULL);
  1880. timersub(&tv_end, &tv_start, &tv_elapsed);
  1881. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  1882. pool_stats->getwork_wait_rolling /= 1.63;
  1883. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  1884. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  1885. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  1886. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  1887. }
  1888. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  1889. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  1890. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  1891. }
  1892. pool_stats->getwork_calls++;
  1893. work->pool = pool;
  1894. work->longpoll = false;
  1895. total_getworks++;
  1896. pool->getwork_requested++;
  1897. json_decref(val);
  1898. out:
  1899. return rc;
  1900. }
  1901. static struct work *make_work(void)
  1902. {
  1903. struct work *work = calloc(1, sizeof(struct work));
  1904. if (unlikely(!work))
  1905. quit(1, "Failed to calloc work in make_work");
  1906. work->id = total_work++;
  1907. return work;
  1908. }
  1909. static void free_work(struct work *work)
  1910. {
  1911. free(work);
  1912. }
  1913. static void workio_cmd_free(struct workio_cmd *wc)
  1914. {
  1915. if (!wc)
  1916. return;
  1917. switch (wc->cmd) {
  1918. case WC_SUBMIT_WORK:
  1919. free_work(wc->work);
  1920. break;
  1921. default: /* do nothing */
  1922. break;
  1923. }
  1924. memset(wc, 0, sizeof(*wc)); /* poison */
  1925. free(wc);
  1926. }
  1927. #ifdef HAVE_CURSES
  1928. static void disable_curses(void)
  1929. {
  1930. if (curses_active_locked()) {
  1931. curses_active = false;
  1932. leaveok(logwin, false);
  1933. leaveok(statuswin, false);
  1934. leaveok(mainwin, false);
  1935. nocbreak();
  1936. echo();
  1937. delwin(logwin);
  1938. delwin(statuswin);
  1939. delwin(mainwin);
  1940. endwin();
  1941. #ifdef WIN32
  1942. // Move the cursor to after curses output.
  1943. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1944. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1945. COORD coord;
  1946. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1947. coord.X = 0;
  1948. coord.Y = csbi.dwSize.Y - 1;
  1949. SetConsoleCursorPosition(hout, coord);
  1950. }
  1951. #endif
  1952. unlock_curses();
  1953. }
  1954. }
  1955. #endif
  1956. static void print_summary(void);
  1957. static void __kill_work(void)
  1958. {
  1959. struct thr_info *thr;
  1960. int i;
  1961. if (!successful_connect)
  1962. return;
  1963. applog(LOG_INFO, "Received kill message");
  1964. applog(LOG_DEBUG, "Killing off watchpool thread");
  1965. /* Kill the watchpool thread */
  1966. thr = &thr_info[watchpool_thr_id];
  1967. thr_info_cancel(thr);
  1968. applog(LOG_DEBUG, "Killing off watchdog thread");
  1969. /* Kill the watchdog thread */
  1970. thr = &thr_info[watchdog_thr_id];
  1971. thr_info_cancel(thr);
  1972. applog(LOG_DEBUG, "Stopping mining threads");
  1973. /* Stop the mining threads*/
  1974. for (i = 0; i < mining_threads; i++) {
  1975. thr = &thr_info[i];
  1976. thr_info_freeze(thr);
  1977. thr->pause = true;
  1978. }
  1979. sleep(1);
  1980. applog(LOG_DEBUG, "Killing off mining threads");
  1981. /* Kill the mining threads*/
  1982. for (i = 0; i < mining_threads; i++) {
  1983. thr = &thr_info[i];
  1984. thr_info_cancel(thr);
  1985. }
  1986. applog(LOG_DEBUG, "Killing off stage thread");
  1987. /* Stop the others */
  1988. thr = &thr_info[stage_thr_id];
  1989. thr_info_cancel(thr);
  1990. applog(LOG_DEBUG, "Killing off API thread");
  1991. thr = &thr_info[api_thr_id];
  1992. thr_info_cancel(thr);
  1993. }
  1994. /* This should be the common exit path */
  1995. void kill_work(void)
  1996. {
  1997. __kill_work();
  1998. quit(0, "Shutdown signal received.");
  1999. }
  2000. static
  2001. #ifdef WIN32
  2002. const
  2003. #endif
  2004. char **initial_args;
  2005. static void clean_up(void);
  2006. void app_restart(void)
  2007. {
  2008. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2009. __kill_work();
  2010. clean_up();
  2011. #if defined(unix)
  2012. if (forkpid > 0) {
  2013. kill(forkpid, SIGTERM);
  2014. forkpid = 0;
  2015. }
  2016. #endif
  2017. execv(initial_args[0], initial_args);
  2018. applog(LOG_WARNING, "Failed to restart application");
  2019. }
  2020. static void sighandler(int __maybe_unused sig)
  2021. {
  2022. /* Restore signal handlers so we can still quit if kill_work fails */
  2023. sigaction(SIGTERM, &termhandler, NULL);
  2024. sigaction(SIGINT, &inthandler, NULL);
  2025. kill_work();
  2026. }
  2027. static void start_longpoll(void);
  2028. static void stop_longpoll(void);
  2029. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2030. * this pool. */
  2031. static void recruit_curl(struct pool *pool)
  2032. {
  2033. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2034. ce->curl = curl_easy_init();
  2035. if (unlikely(!ce || !ce->curl))
  2036. quit(1, "Failed to init in recruit_curl");
  2037. list_add(&ce->node, &pool->curlring);
  2038. pool->curls++;
  2039. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  2040. }
  2041. /* Grab an available curl if there is one. If not, then recruit extra curls
  2042. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2043. * and there are already 5 curls in circulation. Limit total number to the
  2044. * number of mining threads per pool as well to prevent blasting a pool during
  2045. * network delays/outages. */
  2046. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2047. {
  2048. int curl_limit = opt_delaynet ? 5 : mining_threads * 4 / 3;
  2049. struct curl_ent *ce;
  2050. mutex_lock(&pool->pool_lock);
  2051. if (!pool->curls)
  2052. recruit_curl(pool);
  2053. else if (list_empty(&pool->curlring)) {
  2054. if (pool->submit_fail || pool->curls >= curl_limit)
  2055. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2056. else
  2057. recruit_curl(pool);
  2058. }
  2059. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2060. list_del(&ce->node);
  2061. mutex_unlock(&pool->pool_lock);
  2062. return ce;
  2063. }
  2064. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2065. {
  2066. mutex_lock(&pool->pool_lock);
  2067. if (!ce || !ce->curl)
  2068. quit(1, "Attempted to add NULL in push_curl_entry");
  2069. list_add_tail(&ce->node, &pool->curlring);
  2070. gettimeofday(&ce->tv, NULL);
  2071. pthread_cond_signal(&pool->cr_cond);
  2072. mutex_unlock(&pool->pool_lock);
  2073. }
  2074. /* This is overkill, but at least we'll know accurately how much work is
  2075. * queued to prevent ever being left without work */
  2076. static void inc_queued(struct pool *pool)
  2077. {
  2078. if (unlikely(!pool))
  2079. return;
  2080. mutex_lock(&qd_lock);
  2081. pool->queued++;
  2082. total_queued++;
  2083. mutex_unlock(&qd_lock);
  2084. }
  2085. static void dec_queued(struct pool *pool)
  2086. {
  2087. if (unlikely(!pool))
  2088. return;
  2089. mutex_lock(&qd_lock);
  2090. pool->queued--;
  2091. total_queued--;
  2092. mutex_unlock(&qd_lock);
  2093. }
  2094. static int current_queued(void)
  2095. {
  2096. struct pool *pool = current_pool();
  2097. int ret;
  2098. mutex_lock(&qd_lock);
  2099. ret = pool->queued;
  2100. mutex_unlock(&qd_lock);
  2101. return ret;
  2102. }
  2103. static int global_queued(void)
  2104. {
  2105. int ret;
  2106. mutex_lock(&qd_lock);
  2107. ret = total_queued;
  2108. mutex_unlock(&qd_lock);
  2109. return ret;
  2110. }
  2111. /* ce and pool may appear uninitialised at push_curl_entry, but they're always
  2112. * set when we don't have opt_benchmark enabled */
  2113. static void *get_work_thread(void *userdata)
  2114. {
  2115. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2116. struct curl_ent * uninitialised_var(ce);
  2117. struct pool * uninitialised_var(pool);
  2118. struct work *ret_work = make_work();
  2119. int failures = 0;
  2120. pthread_detach(pthread_self());
  2121. applog(LOG_DEBUG, "Creating extra get work thread");
  2122. if (wc->thr)
  2123. ret_work->thr = wc->thr;
  2124. else
  2125. ret_work->thr = NULL;
  2126. if (opt_benchmark)
  2127. get_benchmark_work(ret_work);
  2128. else {
  2129. pool = ret_work->pool = select_pool(wc->lagging);
  2130. inc_queued(pool);
  2131. ce = pop_curl_entry(pool);
  2132. /* obtain new work from bitcoin via JSON-RPC */
  2133. while (!get_upstream_work(ret_work, ce->curl)) {
  2134. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2135. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  2136. free_work(ret_work);
  2137. kill_work();
  2138. goto out;
  2139. }
  2140. /* pause, then restart work-request loop */
  2141. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  2142. fail_pause);
  2143. sleep(fail_pause);
  2144. fail_pause += opt_fail_pause;
  2145. }
  2146. fail_pause = opt_fail_pause;
  2147. dec_queued(pool);
  2148. }
  2149. applog(LOG_DEBUG, "Pushing work to requesting thread");
  2150. /* send work to requesting thread */
  2151. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  2152. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  2153. kill_work();
  2154. free_work(ret_work);
  2155. }
  2156. out:
  2157. workio_cmd_free(wc);
  2158. if (!opt_benchmark)
  2159. push_curl_entry(ce, pool);
  2160. return NULL;
  2161. }
  2162. /* As per the submit work system, we try to reuse the existing curl handles,
  2163. * but start recruiting extra connections if we start accumulating queued
  2164. * requests */
  2165. static bool workio_get_work(struct workio_cmd *wc)
  2166. {
  2167. pthread_t get_thread;
  2168. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  2169. applog(LOG_ERR, "Failed to create get_work_thread");
  2170. return false;
  2171. }
  2172. return true;
  2173. }
  2174. static bool stale_work(struct work *work, bool share)
  2175. {
  2176. struct timeval now;
  2177. time_t work_expiry;
  2178. struct pool *pool;
  2179. uint32_t block_id;
  2180. int getwork_delay;
  2181. if (work->mandatory)
  2182. return false;
  2183. block_id = ((uint32_t*)work->data)[1];
  2184. pool = work->pool;
  2185. if (share) {
  2186. /* If the share isn't on this pool's latest block, it's stale */
  2187. if (pool->block_id != block_id)
  2188. {
  2189. applog(LOG_DEBUG, "Share stale due to block mismatch");
  2190. return true;
  2191. }
  2192. /* If the pool doesn't want old shares, then any found in work before
  2193. * the most recent longpoll is stale */
  2194. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  2195. {
  2196. applog(LOG_DEBUG, "Share stale due to work restart");
  2197. return true;
  2198. }
  2199. /* Technically the rolltime should be correct but some pools
  2200. * advertise a broken expire= that is lower than a meaningful
  2201. * scantime */
  2202. if (work->rolltime > opt_scantime)
  2203. work_expiry = work->rolltime;
  2204. else
  2205. work_expiry = opt_expiry;
  2206. } else {
  2207. /* If this work isn't for the latest Bitcoin block, it's stale */
  2208. /* But only care about the current pool if failover-only */
  2209. if (block_id != (opt_fail_only ? pool->block_id : current_block_id))
  2210. {
  2211. applog(LOG_DEBUG, "Work stale due to block mismatch");
  2212. return true;
  2213. }
  2214. /* If the pool has asked us to restart since this work, it's stale */
  2215. if (work->work_restart_id != pool->work_restart_id)
  2216. {
  2217. applog(LOG_DEBUG, "Share stale due to work restart");
  2218. return true;
  2219. }
  2220. /* Don't keep rolling work right up to the expiration */
  2221. if (work->rolltime > opt_scantime)
  2222. work_expiry = (work->rolltime - opt_scantime) * 2 / 3 + opt_scantime;
  2223. else /* Shouldn't happen unless someone increases scantime */
  2224. work_expiry = opt_scantime;
  2225. /* Factor in the average getwork delay of this pool, rounding it up to
  2226. * the nearest second */
  2227. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2228. work_expiry -= getwork_delay;
  2229. if (unlikely(work_expiry < 5))
  2230. work_expiry = 5;
  2231. }
  2232. gettimeofday(&now, NULL);
  2233. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2234. applog(LOG_DEBUG, "%s stale due to expiry", share?"Share":"Work");
  2235. return true;
  2236. }
  2237. /* If the user only wants strict failover, any work from a pool other than
  2238. * the current one is always considered stale */
  2239. if (opt_fail_only && !share && pool != current_pool() && pool->enabled != POOL_REJECTING) {
  2240. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  2241. return true;
  2242. }
  2243. return false;
  2244. }
  2245. static void check_solve(struct work *work)
  2246. {
  2247. work->block = regeneratehash(work);
  2248. if (unlikely(work->block)) {
  2249. work->pool->solved++;
  2250. found_blocks++;
  2251. work->mandatory = true;
  2252. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  2253. }
  2254. }
  2255. static void submit_discard_share(struct work *work)
  2256. {
  2257. sharelog("discard", work);
  2258. ++total_stale;
  2259. ++(work->pool->stale_shares);
  2260. }
  2261. static void *submit_work_thread(void *userdata)
  2262. {
  2263. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2264. struct work *work = wc->work;
  2265. struct pool *pool = work->pool;
  2266. struct curl_ent *ce;
  2267. int failures = 0;
  2268. time_t staleexpire;
  2269. pthread_detach(pthread_self());
  2270. applog(LOG_DEBUG, "Creating extra submit work thread");
  2271. check_solve(work);
  2272. if (stale_work(work, true)) {
  2273. work->stale = true;
  2274. if (opt_submit_stale)
  2275. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  2276. else if (pool->submit_old)
  2277. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  2278. else {
  2279. applog(LOG_NOTICE, "Stale share detected, discarding");
  2280. submit_discard_share(work);
  2281. goto out;
  2282. }
  2283. staleexpire = time(NULL) + 300;
  2284. }
  2285. ce = pop_curl_entry(pool);
  2286. /* submit solution to bitcoin via JSON-RPC */
  2287. while (!submit_upstream_work(work, ce->curl)) {
  2288. if ((!work->stale) && stale_work(work, true)) {
  2289. work->stale = true;
  2290. if (opt_submit_stale)
  2291. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as user requested");
  2292. else if (pool->submit_old)
  2293. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as pool requested");
  2294. else {
  2295. applog(LOG_NOTICE, "Share become stale during submission failure, discarding");
  2296. submit_discard_share(work);
  2297. break;
  2298. }
  2299. staleexpire = time(NULL) + 300;
  2300. }
  2301. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2302. applog(LOG_ERR, "Failed %d retries, discarding", opt_retries);
  2303. submit_discard_share(work);
  2304. break;
  2305. }
  2306. else if (unlikely(work->stale && opt_retries < 0)) {
  2307. if (staleexpire <= time(NULL)) {
  2308. applog(LOG_NOTICE, "Stale share failed to submit for 5 minutes, discarding");
  2309. submit_discard_share(work);
  2310. break;
  2311. }
  2312. }
  2313. /* pause, then restart work-request loop */
  2314. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  2315. fail_pause);
  2316. sleep(fail_pause);
  2317. fail_pause += opt_fail_pause;
  2318. }
  2319. fail_pause = opt_fail_pause;
  2320. push_curl_entry(ce, pool);
  2321. out:
  2322. workio_cmd_free(wc);
  2323. return NULL;
  2324. }
  2325. /* We try to reuse curl handles as much as possible, but if there is already
  2326. * work queued to be submitted, we start generating extra handles to submit
  2327. * the shares to avoid ever increasing backlogs. This allows us to scale to
  2328. * any size hardware */
  2329. static bool workio_submit_work(struct workio_cmd *wc)
  2330. {
  2331. pthread_t submit_thread;
  2332. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2333. applog(LOG_ERR, "Failed to create submit_work_thread");
  2334. return false;
  2335. }
  2336. return true;
  2337. }
  2338. /* Find the pool that currently has the highest priority */
  2339. static struct pool *priority_pool(int choice)
  2340. {
  2341. struct pool *ret = NULL;
  2342. int i;
  2343. for (i = 0; i < total_pools; i++) {
  2344. struct pool *pool = pools[i];
  2345. if (pool->prio == choice) {
  2346. ret = pool;
  2347. break;
  2348. }
  2349. }
  2350. if (unlikely(!ret)) {
  2351. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2352. return pools[choice];
  2353. }
  2354. return ret;
  2355. }
  2356. void switch_pools(struct pool *selected)
  2357. {
  2358. struct pool *pool, *last_pool;
  2359. int i, pool_no, next_pool;
  2360. mutex_lock(&control_lock);
  2361. last_pool = currentpool;
  2362. pool_no = currentpool->pool_no;
  2363. /* Switch selected to pool number 0 and move the rest down */
  2364. if (selected) {
  2365. if (selected->prio != 0) {
  2366. for (i = 0; i < total_pools; i++) {
  2367. pool = pools[i];
  2368. if (pool->prio < selected->prio)
  2369. pool->prio++;
  2370. }
  2371. selected->prio = 0;
  2372. }
  2373. }
  2374. switch (pool_strategy) {
  2375. /* Both of these set to the master pool */
  2376. case POOL_FAILOVER:
  2377. case POOL_LOADBALANCE:
  2378. for (i = 0; i < total_pools; i++) {
  2379. pool = priority_pool(i);
  2380. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2381. pool_no = pool->pool_no;
  2382. break;
  2383. }
  2384. }
  2385. break;
  2386. /* Both of these simply increment and cycle */
  2387. case POOL_ROUNDROBIN:
  2388. case POOL_ROTATE:
  2389. if (selected && !selected->idle) {
  2390. pool_no = selected->pool_no;
  2391. break;
  2392. }
  2393. next_pool = pool_no;
  2394. /* Select the next alive pool */
  2395. for (i = 1; i < total_pools; i++) {
  2396. next_pool++;
  2397. if (next_pool >= total_pools)
  2398. next_pool = 0;
  2399. pool = pools[next_pool];
  2400. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2401. pool_no = next_pool;
  2402. break;
  2403. }
  2404. }
  2405. break;
  2406. default:
  2407. break;
  2408. }
  2409. currentpool = pools[pool_no];
  2410. pool = currentpool;
  2411. pool->block_id = 0;
  2412. mutex_unlock(&control_lock);
  2413. if (pool != last_pool)
  2414. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2415. mutex_lock(&lp_lock);
  2416. pthread_cond_broadcast(&lp_cond);
  2417. mutex_unlock(&lp_lock);
  2418. queue_request(NULL, false);
  2419. }
  2420. static void discard_work(struct work *work)
  2421. {
  2422. if (!work->clone && !work->rolls && !work->mined) {
  2423. if (work->pool)
  2424. work->pool->discarded_work++;
  2425. total_discarded++;
  2426. applog(LOG_DEBUG, "Discarded work");
  2427. } else
  2428. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2429. free_work(work);
  2430. }
  2431. bool queue_request(struct thr_info *thr, bool needed);
  2432. static void discard_stale(void)
  2433. {
  2434. struct work *work, *tmp;
  2435. int stale = 0;
  2436. mutex_lock(stgd_lock);
  2437. HASH_ITER(hh, staged_work, work, tmp) {
  2438. if (stale_work(work, false)) {
  2439. HASH_DEL(staged_work, work);
  2440. work->pool->staged--;
  2441. discard_work(work);
  2442. stale++;
  2443. }
  2444. }
  2445. mutex_unlock(stgd_lock);
  2446. if (stale) {
  2447. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2448. queue_request(NULL, false);
  2449. }
  2450. }
  2451. void ms_to_abstime(unsigned int mstime, struct timespec *abstime)
  2452. {
  2453. struct timeval now, then, tdiff;
  2454. tdiff.tv_sec = mstime / 1000;
  2455. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  2456. gettimeofday(&now, NULL);
  2457. timeradd(&now, &tdiff, &then);
  2458. abstime->tv_sec = then.tv_sec;
  2459. abstime->tv_nsec = then.tv_usec * 1000;
  2460. }
  2461. /* A generic wait function for threads that poll that will wait a specified
  2462. * time tdiff waiting on the pthread conditional that is broadcast when a
  2463. * work restart is required. Returns the value of pthread_cond_timedwait
  2464. * which is zero if the condition was met or ETIMEDOUT if not.
  2465. */
  2466. int restart_wait(unsigned int mstime)
  2467. {
  2468. struct timespec abstime;
  2469. int rc;
  2470. ms_to_abstime(mstime, &abstime);
  2471. mutex_lock(&restart_lock);
  2472. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  2473. mutex_unlock(&restart_lock);
  2474. return rc;
  2475. }
  2476. /* A generic wait function for threads that poll that will wait a specified
  2477. * time waiting on a share to become stale. Returns positive if the share
  2478. * became stale or zero if the timer expired first. If checkend is true, will
  2479. * immediatley return negative if the share is guaranteed to become stale
  2480. * before the timer expires.
  2481. */
  2482. int stale_wait(unsigned int mstime, struct work*work, bool checkend)
  2483. {
  2484. struct timespec abstime;
  2485. int rc;
  2486. if (checkend) {
  2487. struct timeval tv, orig;
  2488. ldiv_t d;
  2489. d = ldiv(mstime, 1000);
  2490. tv.tv_sec = d.quot;
  2491. tv.tv_usec = d.rem * 1000;
  2492. orig = work->tv_staged;
  2493. timersub(&orig, &tv, &work->tv_staged);
  2494. rc = stale_work(work, true);
  2495. work->tv_staged = orig;
  2496. if (rc)
  2497. return -1;
  2498. }
  2499. ms_to_abstime(mstime, &abstime);
  2500. rc = -1;
  2501. while (1) {
  2502. mutex_lock(&restart_lock);
  2503. if (stale_work(work, true)) {
  2504. rc = 1;
  2505. } else if (pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime)) {
  2506. rc = 0;
  2507. }
  2508. mutex_unlock(&restart_lock);
  2509. if (rc != -1)
  2510. return rc;
  2511. }
  2512. }
  2513. static void restart_threads(void)
  2514. {
  2515. int i, fd;
  2516. struct thr_info *thr;
  2517. /* Discard staged work that is now stale */
  2518. discard_stale();
  2519. queue_request(NULL, true);
  2520. for (i = 0; i < mining_threads; i++)
  2521. {
  2522. thr = &thr_info[i];
  2523. fd = thr->_work_restart_fd_w;
  2524. thr->work_restart = true;
  2525. if (fd != -1)
  2526. write(fd, "\0", 1);
  2527. }
  2528. mutex_lock(&restart_lock);
  2529. pthread_cond_broadcast(&restart_cond);
  2530. mutex_unlock(&restart_lock);
  2531. }
  2532. static void set_curblock(char *hexstr, unsigned char *hash)
  2533. {
  2534. unsigned char hash_swap[32];
  2535. struct timeval tv_now;
  2536. char *old_hash;
  2537. current_block_id = ((uint32_t*)hash)[1];
  2538. strcpy(current_block, hexstr);
  2539. gettimeofday(&tv_now, NULL);
  2540. get_timestamp(blocktime, &tv_now);
  2541. swap256(hash_swap, hash);
  2542. /* Don't free current_hash directly to avoid dereferencing when read
  2543. * elsewhere */
  2544. mutex_lock(&ch_lock);
  2545. old_hash = current_hash;
  2546. current_hash = bin2hex(hash_swap, 16);
  2547. free(old_hash);
  2548. mutex_unlock(&ch_lock);
  2549. if (unlikely(!current_hash))
  2550. quit (1, "set_curblock OOM");
  2551. applog(LOG_INFO, "New block: %s...", current_hash);
  2552. }
  2553. /* Search to see if this string is from a block that has been seen before */
  2554. static bool block_exists(char *hexstr)
  2555. {
  2556. struct block *s;
  2557. rd_lock(&blk_lock);
  2558. HASH_FIND_STR(blocks, hexstr, s);
  2559. rd_unlock(&blk_lock);
  2560. if (s)
  2561. return true;
  2562. return false;
  2563. }
  2564. /* Tests if this work is from a block that has been seen before */
  2565. static inline bool from_existing_block(struct work *work)
  2566. {
  2567. char *hexstr = bin2hex(work->data, 18);
  2568. bool ret;
  2569. if (unlikely(!hexstr)) {
  2570. applog(LOG_ERR, "from_existing_block OOM");
  2571. return true;
  2572. }
  2573. ret = block_exists(hexstr);
  2574. free(hexstr);
  2575. return ret;
  2576. }
  2577. static void test_work_current(struct work *work)
  2578. {
  2579. char *hexstr;
  2580. if (work->mandatory)
  2581. return;
  2582. uint32_t block_id = ((uint32_t*)(work->data))[1];
  2583. hexstr = bin2hex(work->data, 18);
  2584. if (unlikely(!hexstr)) {
  2585. applog(LOG_ERR, "stage_thread OOM");
  2586. return;
  2587. }
  2588. /* Search to see if this block exists yet and if not, consider it a
  2589. * new block and set the current block details to this one */
  2590. if (!block_exists(hexstr)) {
  2591. struct block *s = calloc(sizeof(struct block), 1);
  2592. if (unlikely(!s))
  2593. quit (1, "test_work_current OOM");
  2594. strcpy(s->hash, hexstr);
  2595. wr_lock(&blk_lock);
  2596. HASH_ADD_STR(blocks, hash, s);
  2597. wr_unlock(&blk_lock);
  2598. work->pool->block_id = block_id;
  2599. set_curblock(hexstr, work->data);
  2600. if (unlikely(++new_blocks == 1))
  2601. goto out_free;
  2602. if (work->longpoll) {
  2603. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  2604. work->pool->pool_no);
  2605. work->longpoll = false;
  2606. } else if (have_longpoll)
  2607. applog(LOG_NOTICE, "New block detected on network before longpoll");
  2608. else
  2609. applog(LOG_NOTICE, "New block detected on network");
  2610. restart_threads();
  2611. } else {
  2612. bool restart = false;
  2613. struct pool *curpool = NULL;
  2614. if (unlikely(work->pool->block_id != block_id && block_id == current_block_id)) {
  2615. bool was_active = work->pool->block_id != 0;
  2616. work->pool->block_id = block_id;
  2617. if (was_active && work->pool == (curpool = current_pool())) {
  2618. applog(LOG_NOTICE, "%s %d caught up to new block",
  2619. work->longpoll ? "LONGPOLL from pool" : "Pool",
  2620. work->pool->pool_no);
  2621. restart = true;
  2622. }
  2623. }
  2624. if (work->longpoll) {
  2625. work->longpoll = false;
  2626. ++work->pool->work_restart_id;
  2627. if ((!restart) && work->pool == current_pool()) {
  2628. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  2629. work->pool->pool_no);
  2630. restart = true;
  2631. }
  2632. }
  2633. if (restart)
  2634. restart_threads();
  2635. }
  2636. out_free:
  2637. free(hexstr);
  2638. }
  2639. static int tv_sort(struct work *worka, struct work *workb)
  2640. {
  2641. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2642. }
  2643. static bool hash_push(struct work *work)
  2644. {
  2645. bool rc = true;
  2646. mutex_lock(stgd_lock);
  2647. if (likely(!getq->frozen)) {
  2648. HASH_ADD_INT(staged_work, id, work);
  2649. work->pool->staged++;
  2650. HASH_SORT(staged_work, tv_sort);
  2651. } else
  2652. rc = false;
  2653. pthread_cond_signal(&getq->cond);
  2654. mutex_unlock(stgd_lock);
  2655. return rc;
  2656. }
  2657. static void *stage_thread(void *userdata)
  2658. {
  2659. struct thr_info *mythr = userdata;
  2660. bool ok = true;
  2661. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2662. while (ok) {
  2663. struct work *work = NULL;
  2664. applog(LOG_DEBUG, "Popping work to stage thread");
  2665. work = tq_pop(mythr->q, NULL);
  2666. if (unlikely(!work)) {
  2667. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2668. ok = false;
  2669. break;
  2670. }
  2671. work->work_restart_id = work->pool->work_restart_id;
  2672. test_work_current(work);
  2673. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2674. if (unlikely(!hash_push(work))) {
  2675. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2676. continue;
  2677. }
  2678. }
  2679. tq_freeze(mythr->q);
  2680. return NULL;
  2681. }
  2682. static bool stage_work(struct work *work)
  2683. {
  2684. applog(LOG_DEBUG, "Pushing work to stage thread");
  2685. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  2686. applog(LOG_ERR, "Could not tq_push work in stage_work");
  2687. return false;
  2688. }
  2689. return true;
  2690. }
  2691. #ifdef HAVE_CURSES
  2692. int curses_int(const char *query)
  2693. {
  2694. int ret;
  2695. char *cvar;
  2696. cvar = curses_input(query);
  2697. ret = atoi(cvar);
  2698. free(cvar);
  2699. return ret;
  2700. }
  2701. #endif
  2702. #ifdef HAVE_CURSES
  2703. static bool input_pool(bool live);
  2704. #endif
  2705. #ifdef HAVE_CURSES
  2706. static void display_pool_summary(struct pool *pool)
  2707. {
  2708. double efficiency = 0.0;
  2709. if (curses_active_locked()) {
  2710. wlog("Pool: %s\n", pool->rpc_url);
  2711. if (pool->solved)
  2712. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  2713. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2714. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2715. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2716. wlog(" Accepted shares: %d\n", pool->accepted);
  2717. wlog(" Rejected shares: %d\n", pool->rejected);
  2718. if (pool->accepted || pool->rejected)
  2719. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2720. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2721. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2722. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2723. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2724. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2725. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2726. unlock_curses();
  2727. }
  2728. }
  2729. #endif
  2730. /* We can't remove the memory used for this struct pool because there may
  2731. * still be work referencing it. We just remove it from the pools list */
  2732. void remove_pool(struct pool *pool)
  2733. {
  2734. int i, last_pool = total_pools - 1;
  2735. struct pool *other;
  2736. /* Boost priority of any lower prio than this one */
  2737. for (i = 0; i < total_pools; i++) {
  2738. other = pools[i];
  2739. if (other->prio > pool->prio)
  2740. other->prio--;
  2741. }
  2742. if (pool->pool_no < last_pool) {
  2743. /* Swap the last pool for this one */
  2744. (pools[last_pool])->pool_no = pool->pool_no;
  2745. pools[pool->pool_no] = pools[last_pool];
  2746. }
  2747. /* Give it an invalid number */
  2748. pool->pool_no = total_pools;
  2749. pool->removed = true;
  2750. total_pools--;
  2751. }
  2752. void write_config(FILE *fcfg)
  2753. {
  2754. int i;
  2755. /* Write pool values */
  2756. fputs("{\n\"pools\" : [", fcfg);
  2757. for(i = 0; i < total_pools; i++) {
  2758. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", pools[i]->rpc_url);
  2759. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", pools[i]->rpc_user);
  2760. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", pools[i]->rpc_pass);
  2761. }
  2762. fputs("\n]\n", fcfg);
  2763. #ifdef HAVE_OPENCL
  2764. if (nDevs) {
  2765. /* Write GPU device values */
  2766. fputs(",\n\"intensity\" : \"", fcfg);
  2767. for(i = 0; i < nDevs; i++)
  2768. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  2769. fputs("\",\n\"vectors\" : \"", fcfg);
  2770. for(i = 0; i < nDevs; i++)
  2771. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2772. gpus[i].vwidth);
  2773. fputs("\",\n\"worksize\" : \"", fcfg);
  2774. for(i = 0; i < nDevs; i++)
  2775. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2776. (int)gpus[i].work_size);
  2777. fputs("\",\n\"kernel\" : \"", fcfg);
  2778. for(i = 0; i < nDevs; i++) {
  2779. fprintf(fcfg, "%s", i > 0 ? "," : "");
  2780. switch (gpus[i].kernel) {
  2781. case KL_NONE: // Shouldn't happen
  2782. break;
  2783. case KL_POCLBM:
  2784. fprintf(fcfg, "poclbm");
  2785. break;
  2786. case KL_PHATK:
  2787. fprintf(fcfg, "phatk");
  2788. break;
  2789. case KL_DIAKGCN:
  2790. fprintf(fcfg, "diakgcn");
  2791. break;
  2792. case KL_DIABLO:
  2793. fprintf(fcfg, "diablo");
  2794. break;
  2795. case KL_SCRYPT:
  2796. fprintf(fcfg, "scrypt");
  2797. break;
  2798. }
  2799. }
  2800. #ifdef USE_SCRYPT
  2801. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  2802. for(i = 0; i < nDevs; i++)
  2803. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2804. (int)gpus[i].opt_lg);
  2805. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  2806. for(i = 0; i < nDevs; i++)
  2807. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2808. (int)gpus[i].opt_tc);
  2809. fputs("\",\n\"shaders\" : \"", fcfg);
  2810. for(i = 0; i < nDevs; i++)
  2811. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2812. (int)gpus[i].shaders);
  2813. #endif
  2814. #ifdef HAVE_ADL
  2815. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  2816. for(i = 0; i < nDevs; i++)
  2817. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  2818. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  2819. for(i = 0; i < nDevs; i++)
  2820. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  2821. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  2822. for(i = 0; i < nDevs; i++)
  2823. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  2824. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  2825. for(i = 0; i < nDevs; i++)
  2826. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  2827. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  2828. for(i = 0; i < nDevs; i++)
  2829. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  2830. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  2831. for(i = 0; i < nDevs; i++)
  2832. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  2833. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  2834. for(i = 0; i < nDevs; i++)
  2835. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  2836. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  2837. for(i = 0; i < nDevs; i++)
  2838. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  2839. fputs("\",\n\"temp-target\" : \"", fcfg);
  2840. for(i = 0; i < nDevs; i++)
  2841. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  2842. #endif
  2843. fputs("\"", fcfg);
  2844. }
  2845. #endif
  2846. #ifdef HAVE_ADL
  2847. if (opt_reorder)
  2848. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  2849. #endif
  2850. #ifdef WANT_CPUMINE
  2851. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  2852. #endif
  2853. /* Simple bool and int options */
  2854. struct opt_table *opt;
  2855. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2856. char *p, *name = strdup(opt->names);
  2857. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  2858. if (p[1] != '-')
  2859. continue;
  2860. if (opt->type & OPT_NOARG &&
  2861. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  2862. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  2863. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  2864. if (opt->type & OPT_HASARG &&
  2865. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  2866. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  2867. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  2868. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  2869. opt->desc != opt_hidden &&
  2870. 0 <= *(int *)opt->u.arg)
  2871. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  2872. }
  2873. }
  2874. /* Special case options */
  2875. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  2876. if (pool_strategy == POOL_LOADBALANCE)
  2877. fputs(",\n\"load-balance\" : true", fcfg);
  2878. if (pool_strategy == POOL_ROUNDROBIN)
  2879. fputs(",\n\"round-robin\" : true", fcfg);
  2880. if (pool_strategy == POOL_ROTATE)
  2881. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  2882. #if defined(unix)
  2883. if (opt_stderr_cmd && *opt_stderr_cmd)
  2884. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", opt_stderr_cmd);
  2885. #endif // defined(unix)
  2886. if (opt_kernel_path && *opt_kernel_path) {
  2887. char *kpath = strdup(opt_kernel_path);
  2888. if (kpath[strlen(kpath)-1] == '/')
  2889. kpath[strlen(kpath)-1] = 0;
  2890. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", kpath);
  2891. }
  2892. if (schedstart.enable)
  2893. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  2894. if (schedstop.enable)
  2895. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  2896. if (opt_socks_proxy && *opt_socks_proxy)
  2897. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", opt_socks_proxy);
  2898. #ifdef HAVE_OPENCL
  2899. for(i = 0; i < nDevs; i++)
  2900. if (gpus[i].deven == DEV_DISABLED)
  2901. break;
  2902. if (i < nDevs)
  2903. for (i = 0; i < nDevs; i++)
  2904. if (gpus[i].deven != DEV_DISABLED)
  2905. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  2906. #endif
  2907. if (opt_api_allow)
  2908. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", opt_api_allow);
  2909. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  2910. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", opt_api_description);
  2911. if (opt_api_groups)
  2912. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", opt_api_groups);
  2913. if (opt_icarus_options)
  2914. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", opt_icarus_options);
  2915. if (opt_icarus_timing)
  2916. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", opt_icarus_timing);
  2917. fputs("\n}", fcfg);
  2918. }
  2919. #ifdef HAVE_CURSES
  2920. static void display_pools(void)
  2921. {
  2922. struct pool *pool;
  2923. int selected, i;
  2924. char input;
  2925. opt_loginput = true;
  2926. immedok(logwin, true);
  2927. clear_logwin();
  2928. updated:
  2929. for (i = 0; i < total_pools; i++) {
  2930. pool = pools[i];
  2931. if (pool == current_pool())
  2932. wattron(logwin, A_BOLD);
  2933. if (pool->enabled != POOL_ENABLED)
  2934. wattron(logwin, A_DIM);
  2935. wlogprint("%d: ", pool->pool_no);
  2936. switch (pool->enabled) {
  2937. case POOL_ENABLED:
  2938. wlogprint("Enabled ");
  2939. break;
  2940. case POOL_DISABLED:
  2941. wlogprint("Disabled ");
  2942. break;
  2943. case POOL_REJECTING:
  2944. wlogprint("Rejecting ");
  2945. break;
  2946. }
  2947. wlogprint("%s Priority %d: %s User:%s\n",
  2948. pool->idle? "Dead" : "Alive",
  2949. pool->prio,
  2950. pool->rpc_url, pool->rpc_user);
  2951. wattroff(logwin, A_BOLD | A_DIM);
  2952. }
  2953. retry:
  2954. wlogprint("\nCurrent pool management strategy: %s\n",
  2955. strategies[pool_strategy]);
  2956. if (pool_strategy == POOL_ROTATE)
  2957. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2958. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  2959. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2960. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2961. wlogprint("Or press any other key to continue\n");
  2962. input = getch();
  2963. if (!strncasecmp(&input, "a", 1)) {
  2964. input_pool(true);
  2965. goto updated;
  2966. } else if (!strncasecmp(&input, "r", 1)) {
  2967. if (total_pools <= 1) {
  2968. wlogprint("Cannot remove last pool");
  2969. goto retry;
  2970. }
  2971. selected = curses_int("Select pool number");
  2972. if (selected < 0 || selected >= total_pools) {
  2973. wlogprint("Invalid selection\n");
  2974. goto retry;
  2975. }
  2976. pool = pools[selected];
  2977. if (pool == current_pool())
  2978. switch_pools(NULL);
  2979. if (pool == current_pool()) {
  2980. wlogprint("Unable to remove pool due to activity\n");
  2981. goto retry;
  2982. }
  2983. disable_pool(pool);
  2984. remove_pool(pool);
  2985. goto updated;
  2986. } else if (!strncasecmp(&input, "s", 1)) {
  2987. selected = curses_int("Select pool number");
  2988. if (selected < 0 || selected >= total_pools) {
  2989. wlogprint("Invalid selection\n");
  2990. goto retry;
  2991. }
  2992. pool = pools[selected];
  2993. enable_pool(pool);
  2994. switch_pools(pool);
  2995. goto updated;
  2996. } else if (!strncasecmp(&input, "d", 1)) {
  2997. if (enabled_pools <= 1) {
  2998. wlogprint("Cannot disable last pool");
  2999. goto retry;
  3000. }
  3001. selected = curses_int("Select pool number");
  3002. if (selected < 0 || selected >= total_pools) {
  3003. wlogprint("Invalid selection\n");
  3004. goto retry;
  3005. }
  3006. pool = pools[selected];
  3007. disable_pool(pool);
  3008. if (pool == current_pool())
  3009. switch_pools(NULL);
  3010. goto updated;
  3011. } else if (!strncasecmp(&input, "e", 1)) {
  3012. selected = curses_int("Select pool number");
  3013. if (selected < 0 || selected >= total_pools) {
  3014. wlogprint("Invalid selection\n");
  3015. goto retry;
  3016. }
  3017. pool = pools[selected];
  3018. enable_pool(pool);
  3019. if (pool->prio < current_pool()->prio)
  3020. switch_pools(pool);
  3021. goto updated;
  3022. } else if (!strncasecmp(&input, "c", 1)) {
  3023. for (i = 0; i <= TOP_STRATEGY; i++)
  3024. wlogprint("%d: %s\n", i, strategies[i]);
  3025. selected = curses_int("Select strategy number type");
  3026. if (selected < 0 || selected > TOP_STRATEGY) {
  3027. wlogprint("Invalid selection\n");
  3028. goto retry;
  3029. }
  3030. if (selected == POOL_ROTATE) {
  3031. opt_rotate_period = curses_int("Select interval in minutes");
  3032. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3033. opt_rotate_period = 0;
  3034. wlogprint("Invalid selection\n");
  3035. goto retry;
  3036. }
  3037. }
  3038. pool_strategy = selected;
  3039. switch_pools(NULL);
  3040. goto updated;
  3041. } else if (!strncasecmp(&input, "i", 1)) {
  3042. selected = curses_int("Select pool number");
  3043. if (selected < 0 || selected >= total_pools) {
  3044. wlogprint("Invalid selection\n");
  3045. goto retry;
  3046. }
  3047. pool = pools[selected];
  3048. display_pool_summary(pool);
  3049. goto retry;
  3050. } else if (!strncasecmp(&input, "f", 1)) {
  3051. opt_fail_only ^= true;
  3052. goto updated;
  3053. } else
  3054. clear_logwin();
  3055. immedok(logwin, false);
  3056. opt_loginput = false;
  3057. }
  3058. static void display_options(void)
  3059. {
  3060. int selected;
  3061. char input;
  3062. opt_loginput = true;
  3063. immedok(logwin, true);
  3064. clear_logwin();
  3065. retry:
  3066. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3067. 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",
  3068. opt_debug ? "on" : "off",
  3069. want_per_device_stats? "on" : "off",
  3070. opt_quiet ? "on" : "off",
  3071. opt_log_output ? "on" : "off",
  3072. opt_protocol ? "on" : "off",
  3073. opt_log_interval);
  3074. wlogprint("Select an option or any other key to return\n");
  3075. input = getch();
  3076. if (!strncasecmp(&input, "q", 1)) {
  3077. opt_quiet ^= true;
  3078. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3079. goto retry;
  3080. } else if (!strncasecmp(&input, "v", 1)) {
  3081. opt_log_output ^= true;
  3082. if (opt_log_output)
  3083. opt_quiet = false;
  3084. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3085. goto retry;
  3086. } else if (!strncasecmp(&input, "n", 1)) {
  3087. opt_log_output = false;
  3088. opt_debug = false;
  3089. opt_quiet = false;
  3090. opt_protocol = false;
  3091. want_per_device_stats = false;
  3092. wlogprint("Output mode reset to normal\n");
  3093. goto retry;
  3094. } else if (!strncasecmp(&input, "d", 1)) {
  3095. opt_debug ^= true;
  3096. opt_log_output = opt_debug;
  3097. if (opt_debug)
  3098. opt_quiet = false;
  3099. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  3100. goto retry;
  3101. } else if (!strncasecmp(&input, "p", 1)) {
  3102. want_per_device_stats ^= true;
  3103. opt_log_output = want_per_device_stats;
  3104. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3105. goto retry;
  3106. } else if (!strncasecmp(&input, "r", 1)) {
  3107. opt_protocol ^= true;
  3108. if (opt_protocol)
  3109. opt_quiet = false;
  3110. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3111. goto retry;
  3112. } else if (!strncasecmp(&input, "c", 1))
  3113. clear_logwin();
  3114. else if (!strncasecmp(&input, "l", 1)) {
  3115. selected = curses_int("Interval in seconds");
  3116. if (selected < 0 || selected > 9999) {
  3117. wlogprint("Invalid selection\n");
  3118. goto retry;
  3119. }
  3120. opt_log_interval = selected;
  3121. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3122. goto retry;
  3123. } else if (!strncasecmp(&input, "s", 1)) {
  3124. opt_realquiet = true;
  3125. } else
  3126. clear_logwin();
  3127. immedok(logwin, false);
  3128. opt_loginput = false;
  3129. }
  3130. #endif
  3131. void default_save_file(char *filename)
  3132. {
  3133. #if defined(unix)
  3134. if (getenv("HOME") && *getenv("HOME")) {
  3135. strcpy(filename, getenv("HOME"));
  3136. strcat(filename, "/");
  3137. }
  3138. else
  3139. strcpy(filename, "");
  3140. strcat(filename, ".bfgminer/");
  3141. mkdir(filename, 0777);
  3142. #else
  3143. strcpy(filename, "");
  3144. #endif
  3145. strcat(filename, def_conf);
  3146. }
  3147. #ifdef HAVE_CURSES
  3148. static void set_options(void)
  3149. {
  3150. int selected;
  3151. char input;
  3152. opt_loginput = true;
  3153. immedok(logwin, true);
  3154. clear_logwin();
  3155. retry:
  3156. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  3157. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  3158. "[P]ause: %d\n[W]rite config file\n[B]FGMiner restart\n",
  3159. opt_queue, opt_scantime, opt_expiry, opt_retries, opt_fail_pause);
  3160. wlogprint("Select an option or any other key to return\n");
  3161. input = getch();
  3162. if (!strncasecmp(&input, "q", 1)) {
  3163. selected = curses_int("Extra work items to queue");
  3164. if (selected < 0 || selected > 9999) {
  3165. wlogprint("Invalid selection\n");
  3166. goto retry;
  3167. }
  3168. opt_queue = selected;
  3169. goto retry;
  3170. } else if (!strncasecmp(&input, "l", 1)) {
  3171. if (want_longpoll)
  3172. stop_longpoll();
  3173. else
  3174. start_longpoll();
  3175. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  3176. goto retry;
  3177. } else if (!strncasecmp(&input, "s", 1)) {
  3178. selected = curses_int("Set scantime in seconds");
  3179. if (selected < 0 || selected > 9999) {
  3180. wlogprint("Invalid selection\n");
  3181. goto retry;
  3182. }
  3183. opt_scantime = selected;
  3184. goto retry;
  3185. } else if (!strncasecmp(&input, "e", 1)) {
  3186. selected = curses_int("Set expiry time in seconds");
  3187. if (selected < 0 || selected > 9999) {
  3188. wlogprint("Invalid selection\n");
  3189. goto retry;
  3190. }
  3191. opt_expiry = selected;
  3192. goto retry;
  3193. } else if (!strncasecmp(&input, "r", 1)) {
  3194. selected = curses_int("Retries before failing (-1 infinite)");
  3195. if (selected < -1 || selected > 9999) {
  3196. wlogprint("Invalid selection\n");
  3197. goto retry;
  3198. }
  3199. opt_retries = selected;
  3200. goto retry;
  3201. } else if (!strncasecmp(&input, "p", 1)) {
  3202. selected = curses_int("Seconds to pause before network retries");
  3203. if (selected < 1 || selected > 9999) {
  3204. wlogprint("Invalid selection\n");
  3205. goto retry;
  3206. }
  3207. opt_fail_pause = selected;
  3208. goto retry;
  3209. } else if (!strncasecmp(&input, "w", 1)) {
  3210. FILE *fcfg;
  3211. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3212. default_save_file(filename);
  3213. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3214. str = curses_input(prompt);
  3215. if (strcmp(str, "-1")) {
  3216. struct stat statbuf;
  3217. strcpy(filename, str);
  3218. if (!stat(filename, &statbuf)) {
  3219. wlogprint("File exists, overwrite?\n");
  3220. input = getch();
  3221. if (strncasecmp(&input, "y", 1))
  3222. goto retry;
  3223. }
  3224. }
  3225. fcfg = fopen(filename, "w");
  3226. if (!fcfg) {
  3227. wlogprint("Cannot open or create file\n");
  3228. goto retry;
  3229. }
  3230. write_config(fcfg);
  3231. fclose(fcfg);
  3232. goto retry;
  3233. } else if (!strncasecmp(&input, "b", 1)) {
  3234. wlogprint("Are you sure?\n");
  3235. input = getch();
  3236. if (!strncasecmp(&input, "y", 1))
  3237. app_restart();
  3238. else
  3239. clear_logwin();
  3240. } else
  3241. clear_logwin();
  3242. immedok(logwin, false);
  3243. opt_loginput = false;
  3244. }
  3245. static void *input_thread(void __maybe_unused *userdata)
  3246. {
  3247. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3248. if (!curses_active)
  3249. return NULL;
  3250. while (1) {
  3251. int input;
  3252. input = getch();
  3253. switch (input) {
  3254. case 'q': case 'Q':
  3255. kill_work();
  3256. return NULL;
  3257. case 'd': case 'D':
  3258. display_options();
  3259. break;
  3260. case 'p': case 'P':
  3261. display_pools();
  3262. break;
  3263. case 's': case 'S':
  3264. set_options();
  3265. break;
  3266. case 'g': case 'G':
  3267. if (have_opencl)
  3268. manage_gpu();
  3269. break;
  3270. #ifdef HAVE_CURSES
  3271. case KEY_DOWN:
  3272. if (devsummaryYOffset < -(total_devices + devcursor - statusy))
  3273. break;
  3274. devsummaryYOffset -= 2;
  3275. case KEY_UP:
  3276. if (devsummaryYOffset == 0)
  3277. break;
  3278. ++devsummaryYOffset;
  3279. if (curses_active_locked()) {
  3280. int i;
  3281. for (i = 0; i < mining_threads; i++)
  3282. curses_print_devstatus(i);
  3283. touchwin(statuswin);
  3284. wrefresh(statuswin);
  3285. unlock_curses();
  3286. }
  3287. break;
  3288. #endif
  3289. }
  3290. if (opt_realquiet) {
  3291. disable_curses();
  3292. break;
  3293. }
  3294. }
  3295. return NULL;
  3296. }
  3297. #endif
  3298. /* This thread should not be shut down unless a problem occurs */
  3299. static void *workio_thread(void *userdata)
  3300. {
  3301. struct thr_info *mythr = userdata;
  3302. bool ok = true;
  3303. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3304. while (ok) {
  3305. struct workio_cmd *wc;
  3306. applog(LOG_DEBUG, "Popping work to work thread");
  3307. /* wait for workio_cmd sent to us, on our queue */
  3308. wc = tq_pop(mythr->q, NULL);
  3309. if (unlikely(!wc)) {
  3310. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  3311. ok = false;
  3312. break;
  3313. }
  3314. /* process workio_cmd */
  3315. switch (wc->cmd) {
  3316. case WC_GET_WORK:
  3317. ok = workio_get_work(wc);
  3318. break;
  3319. case WC_SUBMIT_WORK:
  3320. ok = workio_submit_work(wc);
  3321. break;
  3322. default:
  3323. ok = false;
  3324. break;
  3325. }
  3326. }
  3327. tq_freeze(mythr->q);
  3328. return NULL;
  3329. }
  3330. static void *api_thread(void *userdata)
  3331. {
  3332. struct thr_info *mythr = userdata;
  3333. pthread_detach(pthread_self());
  3334. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3335. api(api_thr_id);
  3336. PTH(mythr) = 0L;
  3337. return NULL;
  3338. }
  3339. void thread_reportin(struct thr_info *thr)
  3340. {
  3341. gettimeofday(&thr->last, NULL);
  3342. thr->cgpu->status = LIFE_WELL;
  3343. thr->getwork = 0;
  3344. thr->cgpu->device_last_well = time(NULL);
  3345. }
  3346. static inline void thread_reportout(struct thr_info *thr)
  3347. {
  3348. thr->getwork = time(NULL);
  3349. }
  3350. static void hashmeter(int thr_id, struct timeval *diff,
  3351. unsigned long long hashes_done)
  3352. {
  3353. struct timeval temp_tv_end, total_diff;
  3354. double secs;
  3355. double local_secs;
  3356. double utility, efficiency = 0.0;
  3357. static double local_mhashes_done = 0;
  3358. static double rolling = 0;
  3359. double local_mhashes = (double)hashes_done / 1000000.0;
  3360. bool showlog = false;
  3361. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  3362. /* Update the last time this thread reported in */
  3363. if (thr_id >= 0) {
  3364. gettimeofday(&thr_info[thr_id].last, NULL);
  3365. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  3366. }
  3367. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3368. /* So we can call hashmeter from a non worker thread */
  3369. if (thr_id >= 0) {
  3370. struct thr_info *thr = &thr_info[thr_id];
  3371. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  3372. double thread_rolling = 0.0;
  3373. int i;
  3374. applog(LOG_DEBUG, "[thread %d: %llu hashes, %.1f khash/sec]",
  3375. thr_id, hashes_done, hashes_done / 1000 / secs);
  3376. /* Rolling average for each thread and each device */
  3377. decay_time(&thr->rolling, local_mhashes / secs);
  3378. for (i = 0; i < cgpu->threads; i++)
  3379. thread_rolling += cgpu->thr[i]->rolling;
  3380. mutex_lock(&hash_lock);
  3381. decay_time(&cgpu->rolling, thread_rolling);
  3382. cgpu->total_mhashes += local_mhashes;
  3383. mutex_unlock(&hash_lock);
  3384. // If needed, output detailed, per-device stats
  3385. if (want_per_device_stats) {
  3386. struct timeval now;
  3387. struct timeval elapsed;
  3388. gettimeofday(&now, NULL);
  3389. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  3390. if (opt_log_interval <= elapsed.tv_sec) {
  3391. struct cgpu_info *cgpu = thr->cgpu;
  3392. char logline[255];
  3393. cgpu->last_message_tv = now;
  3394. get_statline(logline, cgpu);
  3395. if (!curses_active) {
  3396. printf("%s \r", logline);
  3397. fflush(stdout);
  3398. } else
  3399. applog(LOG_INFO, "%s", logline);
  3400. }
  3401. }
  3402. }
  3403. /* Totals are updated by all threads so can race without locking */
  3404. mutex_lock(&hash_lock);
  3405. gettimeofday(&temp_tv_end, NULL);
  3406. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  3407. total_mhashes_done += local_mhashes;
  3408. local_mhashes_done += local_mhashes;
  3409. if (total_diff.tv_sec < opt_log_interval)
  3410. /* Only update the total every opt_log_interval seconds */
  3411. goto out_unlock;
  3412. showlog = true;
  3413. gettimeofday(&total_tv_end, NULL);
  3414. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3415. decay_time(&rolling, local_mhashes_done / local_secs);
  3416. global_hashrate = roundl(rolling) * 1000000;
  3417. timersub(&total_tv_end, &total_tv_start, &total_diff);
  3418. total_secs = (double)total_diff.tv_sec +
  3419. ((double)total_diff.tv_usec / 1000000.0);
  3420. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3421. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3422. ti_hashrate_bufstr(
  3423. (char*[]){cHr, aHr, uHr},
  3424. 1e6*rolling,
  3425. 1e6*total_mhashes_done / total_secs,
  3426. utility_to_hashrate(total_accepted_weighed / (total_secs ?: 1) * 60),
  3427. H2B_SPACED);
  3428. sprintf(statusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  3429. want_per_device_stats ? "ALL " : "",
  3430. opt_log_interval,
  3431. cHr, aHr,
  3432. uHr,
  3433. total_accepted, total_rejected, hw_errors, efficiency, utility);
  3434. local_mhashes_done = 0;
  3435. out_unlock:
  3436. mutex_unlock(&hash_lock);
  3437. if (showlog) {
  3438. if (!curses_active) {
  3439. printf("%s \r", statusline);
  3440. fflush(stdout);
  3441. } else
  3442. applog(LOG_INFO, "%s", statusline);
  3443. }
  3444. }
  3445. static void *longpoll_thread(void *userdata);
  3446. static bool pool_active(struct pool *pool, bool pinging)
  3447. {
  3448. bool ret = false;
  3449. json_t *val;
  3450. CURL *curl;
  3451. int rolltime;
  3452. curl = curl_easy_init();
  3453. if (unlikely(!curl)) {
  3454. applog(LOG_ERR, "CURL initialisation failed");
  3455. return false;
  3456. }
  3457. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  3458. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  3459. true, false, &rolltime, pool, false);
  3460. if (val) {
  3461. struct work *work = make_work();
  3462. bool rc;
  3463. rc = work_decode(json_object_get(val, "result"), work);
  3464. if (rc) {
  3465. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  3466. pool->pool_no, pool->rpc_url);
  3467. work->pool = pool;
  3468. work->rolltime = rolltime;
  3469. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  3470. tq_push(thr_info[stage_thr_id].q, work);
  3471. total_getworks++;
  3472. pool->getwork_requested++;
  3473. ret = true;
  3474. gettimeofday(&pool->tv_idle, NULL);
  3475. } else {
  3476. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  3477. pool->pool_no, pool->rpc_url);
  3478. free_work(work);
  3479. }
  3480. json_decref(val);
  3481. if (pool->lp_url)
  3482. goto out;
  3483. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  3484. if (pool->hdr_path) {
  3485. char *copy_start, *hdr_path;
  3486. bool need_slash = false;
  3487. hdr_path = pool->hdr_path;
  3488. if (strstr(hdr_path, "://")) {
  3489. pool->lp_url = hdr_path;
  3490. hdr_path = NULL;
  3491. } else {
  3492. /* absolute path, on current server */
  3493. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3494. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3495. need_slash = true;
  3496. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3497. if (!pool->lp_url) {
  3498. applog(LOG_ERR, "Malloc failure in pool_active");
  3499. return false;
  3500. }
  3501. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3502. }
  3503. } else
  3504. pool->lp_url = NULL;
  3505. if (want_longpoll && !pool->lp_started) {
  3506. pool->lp_started = true;
  3507. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  3508. quit(1, "Failed to create pool longpoll thread");
  3509. }
  3510. } else {
  3511. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  3512. pool->pool_no, pool->rpc_url);
  3513. if (!pinging)
  3514. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  3515. }
  3516. out:
  3517. curl_easy_cleanup(curl);
  3518. return ret;
  3519. }
  3520. static void pool_died(struct pool *pool)
  3521. {
  3522. if (!pool_tset(pool, &pool->idle)) {
  3523. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3524. gettimeofday(&pool->tv_idle, NULL);
  3525. switch_pools(NULL);
  3526. }
  3527. }
  3528. static inline int cp_prio(void)
  3529. {
  3530. int prio;
  3531. mutex_lock(&control_lock);
  3532. prio = currentpool->prio;
  3533. mutex_unlock(&control_lock);
  3534. return prio;
  3535. }
  3536. static void pool_resus(struct pool *pool)
  3537. {
  3538. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  3539. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  3540. switch_pools(NULL);
  3541. }
  3542. bool queue_request(struct thr_info *thr, bool needed)
  3543. {
  3544. int cq, cs, ts, tq, maxq = opt_queue + mining_threads;
  3545. struct workio_cmd *wc;
  3546. bool lag = false;
  3547. cq = current_queued();
  3548. cs = current_staged();
  3549. ts = total_staged();
  3550. tq = global_queued();
  3551. if (needed && cq >= maxq && !ts && !opt_fail_only) {
  3552. /* If we're queueing work faster than we can stage it, consider
  3553. * the system lagging and allow work to be gathered from
  3554. * another pool if possible */
  3555. lag = true;
  3556. } else {
  3557. /* Test to make sure we have enough work for pools without rolltime
  3558. * and enough original work for pools with rolltime */
  3559. if (((cs || cq >= opt_queue) && ts >= maxq) ||
  3560. ((cs || cq) && tq >= maxq))
  3561. return true;
  3562. }
  3563. /* fill out work request message */
  3564. wc = calloc(1, sizeof(*wc));
  3565. if (unlikely(!wc)) {
  3566. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  3567. return false;
  3568. }
  3569. wc->cmd = WC_GET_WORK;
  3570. wc->thr = thr;
  3571. wc->lagging = lag;
  3572. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  3573. /* send work request to workio thread */
  3574. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3575. applog(LOG_ERR, "Failed to tq_push in queue_request");
  3576. workio_cmd_free(wc);
  3577. return false;
  3578. }
  3579. return true;
  3580. }
  3581. static struct work *hash_pop(const struct timespec *abstime)
  3582. {
  3583. struct work *work = NULL;
  3584. bool queue = false;
  3585. int rc = 0;
  3586. mutex_lock(stgd_lock);
  3587. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  3588. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  3589. if (HASH_COUNT(staged_work)) {
  3590. work = staged_work;
  3591. HASH_DEL(staged_work, work);
  3592. work->pool->staged--;
  3593. if (HASH_COUNT(staged_work) < (unsigned int)mining_threads)
  3594. queue = true;
  3595. }
  3596. mutex_unlock(stgd_lock);
  3597. if (queue)
  3598. queue_request(NULL, false);
  3599. return work;
  3600. }
  3601. static inline bool should_roll(struct work *work)
  3602. {
  3603. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE)
  3604. return true;
  3605. return false;
  3606. }
  3607. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3608. * reject blocks as invalid. */
  3609. static inline bool can_roll(struct work *work)
  3610. {
  3611. return (work->pool && work->rolltime && !work->clone &&
  3612. work->rolls < 7000 && !stale_work(work, false));
  3613. }
  3614. static void roll_work(struct work *work)
  3615. {
  3616. uint32_t *work_ntime;
  3617. uint32_t ntime;
  3618. work_ntime = (uint32_t *)(work->data + 68);
  3619. ntime = be32toh(*work_ntime);
  3620. ntime++;
  3621. *work_ntime = htobe32(ntime);
  3622. local_work++;
  3623. work->rolls++;
  3624. work->blk.nonce = 0;
  3625. applog(LOG_DEBUG, "Successfully rolled work");
  3626. /* This is now a different work item so it needs a different ID for the
  3627. * hashtable */
  3628. work->id = total_work++;
  3629. }
  3630. static bool reuse_work(struct work *work)
  3631. {
  3632. if (can_roll(work) && should_roll(work)) {
  3633. roll_work(work);
  3634. return true;
  3635. }
  3636. return false;
  3637. }
  3638. static struct work *make_clone(struct work *work)
  3639. {
  3640. struct work *work_clone = make_work();
  3641. memcpy(work_clone, work, sizeof(struct work));
  3642. work_clone->clone = true;
  3643. work_clone->longpoll = false;
  3644. /* Make cloned work appear slightly older to bias towards keeping the
  3645. * master work item which can be further rolled */
  3646. work_clone->tv_staged.tv_sec -= 1;
  3647. return work_clone;
  3648. }
  3649. /* Clones work by rolling it if possible, and returning a clone instead of the
  3650. * original work item which gets staged again to possibly be rolled again in
  3651. * the future */
  3652. static struct work *clone_work(struct work *work)
  3653. {
  3654. int mrs = mining_threads + opt_queue - total_staged();
  3655. struct work *work_clone;
  3656. bool cloned;
  3657. if (mrs < 1)
  3658. return work;
  3659. cloned = false;
  3660. work_clone = make_clone(work);
  3661. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  3662. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  3663. if (unlikely(!stage_work(work_clone))) {
  3664. cloned = false;
  3665. break;
  3666. }
  3667. roll_work(work);
  3668. work_clone = make_clone(work);
  3669. /* Roll it again to prevent duplicates should this be used
  3670. * directly later on */
  3671. roll_work(work);
  3672. cloned = true;
  3673. }
  3674. if (cloned) {
  3675. stage_work(work);
  3676. return work_clone;
  3677. }
  3678. free_work(work_clone);
  3679. return work;
  3680. }
  3681. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  3682. const int thr_id)
  3683. {
  3684. bool newreq = false, ret = false;
  3685. struct timespec abstime = {0, 0};
  3686. struct timeval now;
  3687. struct work *work_heap;
  3688. int failures = 0, cq;
  3689. struct pool *pool;
  3690. /* Tell the watchdog thread this thread is waiting on getwork and
  3691. * should not be restarted */
  3692. thread_reportout(thr);
  3693. if (opt_benchmark) {
  3694. get_benchmark_work(work);
  3695. thread_reportin(thr);
  3696. return true;
  3697. }
  3698. cq = current_queued();
  3699. retry:
  3700. pool = current_pool();
  3701. if (!requested || cq < opt_queue) {
  3702. if (unlikely(!queue_request(thr, true))) {
  3703. applog(LOG_WARNING, "Failed to queue_request in get_work");
  3704. goto out;
  3705. }
  3706. newreq = true;
  3707. }
  3708. if (reuse_work(work)) {
  3709. ret = true;
  3710. goto out;
  3711. }
  3712. if (!pool->lagging && requested && !newreq && !pool_staged(pool) && cq >= mining_threads + opt_queue) {
  3713. struct cgpu_info *cgpu = thr->cgpu;
  3714. bool stalled = true;
  3715. int i;
  3716. /* Check to see if all the threads on the device that called
  3717. * get_work are waiting on work and only consider the pool
  3718. * lagging if true */
  3719. for (i = 0; i < cgpu->threads; i++) {
  3720. if (!cgpu->thr[i]->getwork) {
  3721. stalled = false;
  3722. break;
  3723. }
  3724. }
  3725. if (stalled && !pool_tset(pool, &pool->lagging)) {
  3726. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  3727. pool->getfail_occasions++;
  3728. total_go++;
  3729. }
  3730. }
  3731. newreq = requested = false;
  3732. gettimeofday(&now, NULL);
  3733. abstime.tv_sec = now.tv_sec + 60;
  3734. applog(LOG_DEBUG, "Popping work from get queue to get work");
  3735. /* wait for 1st response, or get cached response */
  3736. work_heap = hash_pop(&abstime);
  3737. if (unlikely(!work_heap)) {
  3738. /* Attempt to switch pools if this one times out */
  3739. pool_died(pool);
  3740. goto retry;
  3741. }
  3742. if (stale_work(work_heap, false)) {
  3743. discard_work(work_heap);
  3744. goto retry;
  3745. }
  3746. pool = work_heap->pool;
  3747. /* If we make it here we have succeeded in getting fresh work */
  3748. if (!work_heap->mined) {
  3749. pool_tclear(pool, &pool->lagging);
  3750. if (pool_tclear(pool, &pool->idle))
  3751. pool_resus(pool);
  3752. }
  3753. work_heap = clone_work(work_heap);
  3754. memcpy(work, work_heap, sizeof(struct work));
  3755. free_work(work_heap);
  3756. ret = true;
  3757. out:
  3758. if (unlikely(ret == false)) {
  3759. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  3760. applog(LOG_ERR, "Failed %d times to get_work");
  3761. return ret;
  3762. }
  3763. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  3764. sleep(fail_pause);
  3765. fail_pause += opt_fail_pause;
  3766. goto retry;
  3767. }
  3768. fail_pause = opt_fail_pause;
  3769. work->thr_id = thr_id;
  3770. thread_reportin(thr);
  3771. if (ret)
  3772. work->mined = true;
  3773. return ret;
  3774. }
  3775. bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  3776. {
  3777. struct workio_cmd *wc;
  3778. /* fill out work request message */
  3779. wc = calloc(1, sizeof(*wc));
  3780. if (unlikely(!wc)) {
  3781. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  3782. return false;
  3783. }
  3784. wc->work = make_work();
  3785. wc->cmd = WC_SUBMIT_WORK;
  3786. wc->thr = thr;
  3787. memcpy(wc->work, work_in, sizeof(*work_in));
  3788. wc->work->share_found_time = time(NULL);
  3789. applog(LOG_DEBUG, "Pushing submit work to work thread");
  3790. /* send solution to workio thread */
  3791. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3792. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  3793. goto err_out;
  3794. }
  3795. return true;
  3796. err_out:
  3797. workio_cmd_free(wc);
  3798. return false;
  3799. }
  3800. bool hashtest(const struct work *work, bool checktarget)
  3801. {
  3802. uint32_t *data32 = (uint32_t *)(work->data);
  3803. unsigned char swap[128];
  3804. uint32_t *swap32 = (uint32_t *)swap;
  3805. unsigned char hash1[32];
  3806. unsigned char hash2[32];
  3807. uint32_t *hash2_32 = (uint32_t *)hash2;
  3808. swap32yes(swap32, data32, 80 / 4);
  3809. sha2(swap, 80, hash1, false);
  3810. sha2(hash1, 32, hash2, false);
  3811. if (!checktarget)
  3812. return hash2_32[7] == 0;
  3813. swap32yes(hash2_32, hash2_32, 32 / 4);
  3814. memcpy((void*)work->hash, hash2, 32);
  3815. return fulltest(work->hash, work->target);
  3816. }
  3817. bool test_nonce(struct work *work, uint32_t nonce, bool checktarget)
  3818. {
  3819. if (opt_scrypt) {
  3820. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  3821. *work_nonce = nonce;
  3822. return true;
  3823. }
  3824. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  3825. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  3826. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  3827. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  3828. return hashtest(work, checktarget);
  3829. }
  3830. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  3831. {
  3832. /* Do one last check before attempting to submit the work */
  3833. /* Side effect: sets work->data for us */
  3834. if (!test_nonce(work, nonce, true)) {
  3835. applog(LOG_INFO, "Pool %d share below target", work->pool->pool_no);
  3836. return true;
  3837. }
  3838. return submit_work_sync(thr, work);
  3839. }
  3840. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  3841. {
  3842. if (wdiff->tv_sec > opt_scantime ||
  3843. work->blk.nonce >= MAXTHREADS - hashes ||
  3844. hashes >= 0xfffffffe ||
  3845. stale_work(work, false))
  3846. return true;
  3847. return false;
  3848. }
  3849. static void mt_disable(struct thr_info *mythr, const int thr_id,
  3850. const struct device_api *api)
  3851. {
  3852. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3853. mythr->rolling = mythr->cgpu->rolling = 0;
  3854. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3855. thread_reportout(mythr);
  3856. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3857. thread_reportin(mythr);
  3858. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3859. if (api->thread_enable)
  3860. api->thread_enable(mythr);
  3861. }
  3862. void *miner_thread(void *userdata)
  3863. {
  3864. struct thr_info *mythr = userdata;
  3865. const int thr_id = mythr->id;
  3866. struct cgpu_info *cgpu = mythr->cgpu;
  3867. const struct device_api *api = cgpu->api;
  3868. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  3869. struct cgminer_stats *pool_stats;
  3870. struct timeval getwork_start;
  3871. /* Try to cycle approximately 5 times before each log update */
  3872. const long cycle = opt_log_interval / 5 ? : 1;
  3873. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  3874. struct timeval diff, sdiff, wdiff = {0, 0};
  3875. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  3876. int64_t hashes_done = 0;
  3877. int64_t hashes;
  3878. struct work *work = make_work();
  3879. const time_t request_interval = opt_scantime * 2 / 3 ? : 1;
  3880. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3881. bool requested = false;
  3882. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  3883. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3884. gettimeofday(&getwork_start, NULL);
  3885. if (api->thread_init && !api->thread_init(mythr)) {
  3886. cgpu->device_last_not_well = time(NULL);
  3887. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  3888. cgpu->thread_fail_init_count++;
  3889. goto out;
  3890. }
  3891. thread_reportout(mythr);
  3892. applog(LOG_DEBUG, "Popping ping in miner thread");
  3893. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3894. sdiff.tv_sec = sdiff.tv_usec = 0;
  3895. gettimeofday(&tv_lastupdate, NULL);
  3896. while (1) {
  3897. mythr->work_restart = false;
  3898. if (api->free_work && likely(work->pool))
  3899. api->free_work(mythr, work);
  3900. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  3901. applog(LOG_ERR, "work retrieval failed, exiting "
  3902. "mining thread %d", thr_id);
  3903. break;
  3904. }
  3905. requested = false;
  3906. gettimeofday(&tv_workstart, NULL);
  3907. work->blk.nonce = 0;
  3908. cgpu->max_hashes = 0;
  3909. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  3910. applog(LOG_ERR, "work prepare failed, exiting "
  3911. "mining thread %d", thr_id);
  3912. break;
  3913. }
  3914. do {
  3915. gettimeofday(&tv_start, NULL);
  3916. timersub(&tv_start, &getwork_start, &getwork_start);
  3917. timeradd(&getwork_start,
  3918. &(dev_stats->getwork_wait),
  3919. &(dev_stats->getwork_wait));
  3920. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  3921. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  3922. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  3923. }
  3924. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  3925. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  3926. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  3927. }
  3928. dev_stats->getwork_calls++;
  3929. pool_stats = &(work->pool->cgminer_stats);
  3930. timeradd(&getwork_start,
  3931. &(pool_stats->getwork_wait),
  3932. &(pool_stats->getwork_wait));
  3933. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  3934. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  3935. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  3936. }
  3937. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  3938. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  3939. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  3940. }
  3941. pool_stats->getwork_calls++;
  3942. thread_reportin(mythr);
  3943. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  3944. thread_reportin(mythr);
  3945. gettimeofday(&getwork_start, NULL);
  3946. if (unlikely(hashes == -1)) {
  3947. applog(LOG_ERR, "%s %d failure, disabling!", api->name, cgpu->device_id);
  3948. cgpu->deven = DEV_DISABLED;
  3949. cgpu->device_last_not_well = time(NULL);
  3950. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  3951. cgpu->thread_zero_hash_count++;
  3952. mt_disable(mythr, thr_id, api);
  3953. }
  3954. hashes_done += hashes;
  3955. if (hashes > cgpu->max_hashes)
  3956. cgpu->max_hashes = hashes;
  3957. gettimeofday(&tv_end, NULL);
  3958. timersub(&tv_end, &tv_start, &diff);
  3959. sdiff.tv_sec += diff.tv_sec;
  3960. sdiff.tv_usec += diff.tv_usec;
  3961. if (sdiff.tv_usec > 1000000) {
  3962. ++sdiff.tv_sec;
  3963. sdiff.tv_usec -= 1000000;
  3964. }
  3965. timersub(&tv_end, &tv_workstart, &wdiff);
  3966. if (!requested) {
  3967. if (wdiff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3968. thread_reportout(mythr);
  3969. if (unlikely(!queue_request(mythr, false))) {
  3970. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  3971. cgpu->device_last_not_well = time(NULL);
  3972. cgpu->device_not_well_reason = REASON_THREAD_FAIL_QUEUE;
  3973. cgpu->thread_fail_queue_count++;
  3974. goto out;
  3975. }
  3976. thread_reportin(mythr);
  3977. requested = true;
  3978. }
  3979. }
  3980. if (unlikely((long)sdiff.tv_sec < cycle)) {
  3981. int mult;
  3982. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  3983. continue;
  3984. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  3985. mult *= cycle;
  3986. if (max_nonce > (0xffffffff * 0x400) / mult)
  3987. max_nonce = 0xffffffff;
  3988. else
  3989. max_nonce = (max_nonce * mult) / 0x400;
  3990. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work)
  3991. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  3992. else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work)
  3993. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  3994. timersub(&tv_end, &tv_lastupdate, &diff);
  3995. if (diff.tv_sec >= opt_log_interval) {
  3996. hashmeter(thr_id, &diff, hashes_done);
  3997. hashes_done = 0;
  3998. tv_lastupdate = tv_end;
  3999. }
  4000. if (unlikely(mythr->work_restart)) {
  4001. /* Apart from device_thread 0, we stagger the
  4002. * starting of every next thread to try and get
  4003. * all devices busy before worrying about
  4004. * getting work for their extra threads */
  4005. if (!primary) {
  4006. struct timespec rgtp;
  4007. rgtp.tv_sec = 0;
  4008. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  4009. nanosleep(&rgtp, NULL);
  4010. }
  4011. break;
  4012. }
  4013. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  4014. mt_disable(mythr, thr_id, api);
  4015. sdiff.tv_sec = sdiff.tv_usec = 0;
  4016. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  4017. }
  4018. out:
  4019. if (api->thread_shutdown)
  4020. api->thread_shutdown(mythr);
  4021. thread_reportin(mythr);
  4022. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  4023. tq_freeze(mythr->q);
  4024. return NULL;
  4025. }
  4026. enum {
  4027. STAT_SLEEP_INTERVAL = 1,
  4028. STAT_CTR_INTERVAL = 10000000,
  4029. FAILURE_INTERVAL = 30,
  4030. };
  4031. /* Stage another work item from the work returned in a longpoll */
  4032. static void convert_to_work(json_t *val, int rolltime, struct pool *pool)
  4033. {
  4034. struct work *work;
  4035. bool rc;
  4036. work = make_work();
  4037. rc = work_decode(json_object_get(val, "result"), work);
  4038. if (unlikely(!rc)) {
  4039. applog(LOG_ERR, "Could not convert longpoll data to work");
  4040. free_work(work);
  4041. return;
  4042. }
  4043. work->pool = pool;
  4044. work->rolltime = rolltime;
  4045. work->longpoll = true;
  4046. if (pool->enabled == POOL_REJECTING)
  4047. work->mandatory = true;
  4048. /* We'll be checking this work item twice, but we already know it's
  4049. * from a new block so explicitly force the new block detection now
  4050. * rather than waiting for it to hit the stage thread. This also
  4051. * allows testwork to know whether LP discovered the block or not. */
  4052. test_work_current(work);
  4053. /* Don't use backup LPs as work if we have failover-only enabled. Use
  4054. * the longpoll work from a pool that has been rejecting shares as a
  4055. * way to detect when the pool has recovered.
  4056. */
  4057. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  4058. free_work(work);
  4059. return;
  4060. }
  4061. work = clone_work(work);
  4062. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  4063. if (unlikely(!stage_work(work)))
  4064. free_work(work);
  4065. else
  4066. applog(LOG_DEBUG, "Converted longpoll data to work");
  4067. }
  4068. /* If we want longpoll, enable it for the chosen default pool, or, if
  4069. * the pool does not support longpoll, find the first one that does
  4070. * and use its longpoll support */
  4071. static struct pool *select_longpoll_pool(struct pool *cp)
  4072. {
  4073. int i;
  4074. if (cp->hdr_path)
  4075. return cp;
  4076. for (i = 0; i < total_pools; i++) {
  4077. struct pool *pool = pools[i];
  4078. if (pool->hdr_path)
  4079. return pool;
  4080. }
  4081. return NULL;
  4082. }
  4083. /* This will make the longpoll thread wait till it's the current pool, or it
  4084. * has been flagged as rejecting, before attempting to open any connections.
  4085. */
  4086. static void wait_lpcurrent(struct pool *pool)
  4087. {
  4088. if (pool->enabled == POOL_REJECTING || pool_strategy == POOL_LOADBALANCE)
  4089. return;
  4090. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE) {
  4091. mutex_lock(&lp_lock);
  4092. pthread_cond_wait(&lp_cond, &lp_lock);
  4093. mutex_unlock(&lp_lock);
  4094. }
  4095. }
  4096. static void *longpoll_thread(void *userdata)
  4097. {
  4098. struct pool *cp = (struct pool *)userdata;
  4099. /* This *pool is the source of the actual longpoll, not the pool we've
  4100. * tied it to */
  4101. struct pool *pool = NULL;
  4102. struct timeval start, end;
  4103. CURL *curl = NULL;
  4104. int failures = 0;
  4105. int rolltime;
  4106. curl = curl_easy_init();
  4107. if (unlikely(!curl)) {
  4108. applog(LOG_ERR, "CURL initialisation failed");
  4109. goto out;
  4110. }
  4111. retry_pool:
  4112. pool = select_longpoll_pool(cp);
  4113. if (!pool) {
  4114. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  4115. while (!pool) {
  4116. sleep(60);
  4117. pool = select_longpoll_pool(cp);
  4118. }
  4119. }
  4120. /* Any longpoll from any pool is enough for this to be true */
  4121. have_longpoll = true;
  4122. wait_lpcurrent(cp);
  4123. if (cp == pool)
  4124. applog(LOG_WARNING, "Long-polling activated for %s", pool->lp_url);
  4125. else
  4126. applog(LOG_WARNING, "Long-polling activated for pool %s via %s", cp->rpc_url, pool->lp_url);
  4127. while (42) {
  4128. json_t *val, *soval;
  4129. wait_lpcurrent(cp);
  4130. gettimeofday(&start, NULL);
  4131. /* Longpoll connections can be persistent for a very long time
  4132. * and any number of issues could have come up in the meantime
  4133. * so always establish a fresh connection instead of relying on
  4134. * a persistent one. */
  4135. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  4136. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  4137. false, true, &rolltime, pool, false);
  4138. if (likely(val)) {
  4139. soval = json_object_get(json_object_get(val, "result"), "submitold");
  4140. if (soval)
  4141. pool->submit_old = json_is_true(soval);
  4142. else
  4143. pool->submit_old = false;
  4144. convert_to_work(val, rolltime, pool);
  4145. failures = 0;
  4146. json_decref(val);
  4147. } else {
  4148. /* Some pools regularly drop the longpoll request so
  4149. * only see this as longpoll failure if it happens
  4150. * immediately and just restart it the rest of the
  4151. * time. */
  4152. gettimeofday(&end, NULL);
  4153. if (end.tv_sec - start.tv_sec > 30)
  4154. continue;
  4155. if (opt_retries == -1 || failures++ < opt_retries) {
  4156. if (failures == 1)
  4157. applog(LOG_WARNING,
  4158. "longpoll failed for %s, retrying every 30s", pool->lp_url);
  4159. sleep(30);
  4160. } else {
  4161. applog(LOG_ERR,
  4162. "longpoll failed for %s, ending thread", pool->lp_url);
  4163. goto out;
  4164. }
  4165. }
  4166. if (pool != cp) {
  4167. pool = select_longpoll_pool(cp);
  4168. if (unlikely(!pool))
  4169. goto retry_pool;
  4170. }
  4171. if (unlikely(pool->removed))
  4172. break;
  4173. }
  4174. out:
  4175. if (curl)
  4176. curl_easy_cleanup(curl);
  4177. return NULL;
  4178. }
  4179. static void stop_longpoll(void)
  4180. {
  4181. int i;
  4182. want_longpoll = false;
  4183. for (i = 0; i < total_pools; ++i)
  4184. {
  4185. struct pool *pool = pools[i];
  4186. if (unlikely(!pool->lp_started))
  4187. continue;
  4188. pool->lp_started = false;
  4189. pthread_cancel(pool->longpoll_thread);
  4190. }
  4191. have_longpoll = false;
  4192. }
  4193. static void start_longpoll(void)
  4194. {
  4195. int i;
  4196. want_longpoll = true;
  4197. for (i = 0; i < total_pools; ++i)
  4198. {
  4199. struct pool *pool = pools[i];
  4200. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  4201. continue;
  4202. pool->lp_started = true;
  4203. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4204. quit(1, "Failed to create pool longpoll thread");
  4205. }
  4206. }
  4207. void reinit_device(struct cgpu_info *cgpu)
  4208. {
  4209. if (cgpu->api->reinit_device)
  4210. cgpu->api->reinit_device(cgpu);
  4211. }
  4212. static struct timeval rotate_tv;
  4213. /* We reap curls if they are unused for over a minute */
  4214. static void reap_curl(struct pool *pool)
  4215. {
  4216. struct curl_ent *ent, *iter;
  4217. struct timeval now;
  4218. gettimeofday(&now, NULL);
  4219. mutex_lock(&pool->pool_lock);
  4220. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  4221. if (now.tv_sec - ent->tv.tv_sec > 60) {
  4222. applog(LOG_DEBUG, "Reaped curl %d from pool %d", pool->curls, pool->pool_no);
  4223. pool->curls--;
  4224. list_del(&ent->node);
  4225. curl_easy_cleanup(ent->curl);
  4226. free(ent);
  4227. }
  4228. }
  4229. mutex_unlock(&pool->pool_lock);
  4230. }
  4231. static void *watchpool_thread(void __maybe_unused *userdata)
  4232. {
  4233. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4234. while (42) {
  4235. struct timeval now;
  4236. int i;
  4237. gettimeofday(&now, NULL);
  4238. for (i = 0; i < total_pools; i++) {
  4239. struct pool *pool = pools[i];
  4240. if (!opt_benchmark)
  4241. reap_curl(pool);
  4242. if (pool->enabled == POOL_DISABLED)
  4243. continue;
  4244. /* Test pool is idle once every minute */
  4245. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  4246. gettimeofday(&pool->tv_idle, NULL);
  4247. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  4248. pool_resus(pool);
  4249. }
  4250. }
  4251. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  4252. gettimeofday(&rotate_tv, NULL);
  4253. switch_pools(NULL);
  4254. }
  4255. sleep(30);
  4256. }
  4257. return NULL;
  4258. }
  4259. /* Work is sorted according to age, so discard the oldest work items, leaving
  4260. * only 1/3 more staged work item than mining threads */
  4261. static void age_work(void)
  4262. {
  4263. int discarded = 0, maxq = (mining_threads + opt_queue) * 4 / 3;
  4264. while (total_staged() > maxq) {
  4265. struct work *work = hash_pop(NULL);
  4266. if (unlikely(!work))
  4267. break;
  4268. discard_work(work);
  4269. discarded++;
  4270. }
  4271. if (discarded)
  4272. applog(LOG_DEBUG, "Aged %d work items", discarded);
  4273. }
  4274. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  4275. * the screen at regular intervals, and restarts threads if they appear to have
  4276. * died. */
  4277. #define WATCHDOG_INTERVAL 3
  4278. #define WATCHDOG_SICK_TIME 60
  4279. #define WATCHDOG_DEAD_TIME 600
  4280. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  4281. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  4282. static void *watchdog_thread(void __maybe_unused *userdata)
  4283. {
  4284. const unsigned int interval = WATCHDOG_INTERVAL;
  4285. struct timeval zero_tv;
  4286. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4287. memset(&zero_tv, 0, sizeof(struct timeval));
  4288. gettimeofday(&rotate_tv, NULL);
  4289. while (1) {
  4290. int i;
  4291. struct timeval now;
  4292. sleep(interval);
  4293. discard_stale();
  4294. age_work();
  4295. queue_request(NULL, false);
  4296. hashmeter(-1, &zero_tv, 0);
  4297. #ifdef HAVE_CURSES
  4298. if (curses_active_locked()) {
  4299. change_logwinsize();
  4300. curses_print_status();
  4301. for (i = 0; i < mining_threads; i++)
  4302. curses_print_devstatus(i);
  4303. touchwin(statuswin);
  4304. wrefresh(statuswin);
  4305. touchwin(logwin);
  4306. wrefresh(logwin);
  4307. unlock_curses();
  4308. }
  4309. #endif
  4310. gettimeofday(&now, NULL);
  4311. if (!sched_paused && !should_run()) {
  4312. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  4313. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4314. if (!schedstart.enable) {
  4315. quit(0, "Terminating execution as planned");
  4316. break;
  4317. }
  4318. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  4319. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4320. sched_paused = true;
  4321. for (i = 0; i < mining_threads; i++) {
  4322. struct thr_info *thr;
  4323. thr = &thr_info[i];
  4324. thr->pause = true;
  4325. }
  4326. } else if (sched_paused && should_run()) {
  4327. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  4328. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4329. if (schedstop.enable)
  4330. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  4331. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4332. sched_paused = false;
  4333. for (i = 0; i < mining_threads; i++) {
  4334. struct thr_info *thr;
  4335. thr = &thr_info[i];
  4336. /* Don't touch disabled devices */
  4337. if (thr->cgpu->deven == DEV_DISABLED)
  4338. continue;
  4339. thr->pause = false;
  4340. tq_push(thr->q, &ping);
  4341. }
  4342. }
  4343. for (i = 0; i < total_devices; ++i) {
  4344. struct cgpu_info *cgpu = devices[i];
  4345. struct thr_info *thr = cgpu->thr[0];
  4346. enum dev_enable *denable;
  4347. char dev_str[8];
  4348. int gpu;
  4349. if (cgpu->api->get_stats)
  4350. cgpu->api->get_stats(cgpu);
  4351. gpu = cgpu->device_id;
  4352. denable = &cgpu->deven;
  4353. sprintf(dev_str, "%s%d", cgpu->api->name, gpu);
  4354. #ifdef HAVE_ADL
  4355. if (adl_active && cgpu->has_adl)
  4356. gpu_autotune(gpu, denable);
  4357. if (opt_debug && cgpu->has_adl) {
  4358. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  4359. float temp = 0, vddc = 0;
  4360. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  4361. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  4362. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  4363. }
  4364. #endif
  4365. /* Thread is disabled */
  4366. if (*denable == DEV_DISABLED)
  4367. continue;
  4368. if (thr->getwork) {
  4369. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  4370. int thrid;
  4371. bool cgpu_idle = true;
  4372. thr->rolling = 0;
  4373. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  4374. if (!cgpu->thr[thrid]->getwork)
  4375. cgpu_idle = false;
  4376. if (cgpu_idle) {
  4377. cgpu->rolling = 0;
  4378. cgpu->status = LIFE_WAIT;
  4379. }
  4380. }
  4381. continue;
  4382. }
  4383. else if (cgpu->status == LIFE_WAIT)
  4384. cgpu->status = LIFE_WELL;
  4385. #ifdef WANT_CPUMINE
  4386. if (!strcmp(cgpu->api->dname, "cpu"))
  4387. continue;
  4388. #endif
  4389. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  4390. if (cgpu->status != LIFE_INIT)
  4391. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  4392. cgpu->status = LIFE_WELL;
  4393. cgpu->device_last_well = time(NULL);
  4394. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  4395. thr->rolling = cgpu->rolling = 0;
  4396. cgpu->status = LIFE_SICK;
  4397. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  4398. gettimeofday(&thr->sick, NULL);
  4399. cgpu->device_last_not_well = time(NULL);
  4400. cgpu->device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  4401. cgpu->dev_sick_idle_60_count++;
  4402. #ifdef HAVE_ADL
  4403. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4404. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  4405. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  4406. } else
  4407. #endif
  4408. if (opt_restart) {
  4409. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  4410. reinit_device(cgpu);
  4411. }
  4412. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  4413. cgpu->status = LIFE_DEAD;
  4414. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  4415. gettimeofday(&thr->sick, NULL);
  4416. cgpu->device_last_not_well = time(NULL);
  4417. cgpu->device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  4418. cgpu->dev_dead_idle_600_count++;
  4419. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  4420. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  4421. /* Attempt to restart a GPU that's sick or dead once every minute */
  4422. gettimeofday(&thr->sick, NULL);
  4423. #ifdef HAVE_ADL
  4424. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4425. /* Again do not attempt to restart a device that may have hard hung */
  4426. } else
  4427. #endif
  4428. if (opt_restart)
  4429. reinit_device(cgpu);
  4430. }
  4431. }
  4432. }
  4433. return NULL;
  4434. }
  4435. static void log_print_status(struct cgpu_info *cgpu)
  4436. {
  4437. char logline[255];
  4438. get_statline(logline, cgpu);
  4439. applog(LOG_WARNING, "%s", logline);
  4440. }
  4441. static void print_summary(void)
  4442. {
  4443. struct timeval diff;
  4444. int hours, mins, secs, i;
  4445. double utility, efficiency = 0.0;
  4446. timersub(&total_tv_end, &total_tv_start, &diff);
  4447. hours = diff.tv_sec / 3600;
  4448. mins = (diff.tv_sec % 3600) / 60;
  4449. secs = diff.tv_sec % 60;
  4450. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  4451. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4452. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4453. applog(LOG_WARNING, "Started at %s", datestamp);
  4454. if (total_pools == 1)
  4455. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  4456. #ifdef WANT_CPUMINE
  4457. if (opt_n_threads)
  4458. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4459. #endif
  4460. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4461. if (total_secs)
  4462. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  4463. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  4464. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4465. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4466. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4467. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4468. if (total_accepted || total_rejected)
  4469. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4470. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4471. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4472. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  4473. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4474. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4475. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4476. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4477. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4478. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4479. if (total_pools > 1) {
  4480. for (i = 0; i < total_pools; i++) {
  4481. struct pool *pool = pools[i];
  4482. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4483. if (pool->solved)
  4484. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  4485. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4486. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4487. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4488. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4489. if (pool->accepted || pool->rejected)
  4490. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4491. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4492. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4493. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4494. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4495. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4496. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4497. }
  4498. }
  4499. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4500. for (i = 0; i < total_devices; ++i)
  4501. log_print_status(devices[i]);
  4502. if (opt_shares)
  4503. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4504. fflush(stdout);
  4505. fflush(stderr);
  4506. if (opt_shares > total_accepted)
  4507. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  4508. }
  4509. static void clean_up(void)
  4510. {
  4511. #ifdef HAVE_OPENCL
  4512. clear_adl(nDevs);
  4513. #endif
  4514. #ifdef HAVE_LIBUSB
  4515. libusb_exit(NULL);
  4516. #endif
  4517. gettimeofday(&total_tv_end, NULL);
  4518. #ifdef HAVE_CURSES
  4519. disable_curses();
  4520. #endif
  4521. if (!opt_realquiet && successful_connect)
  4522. print_summary();
  4523. if (opt_n_threads)
  4524. free(cpus);
  4525. curl_global_cleanup();
  4526. }
  4527. void quit(int status, const char *format, ...)
  4528. {
  4529. va_list ap;
  4530. clean_up();
  4531. if (format) {
  4532. va_start(ap, format);
  4533. vfprintf(stderr, format, ap);
  4534. va_end(ap);
  4535. }
  4536. fprintf(stderr, "\n");
  4537. fflush(stderr);
  4538. if (status) {
  4539. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  4540. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  4541. const char **p = NULL;
  4542. // NOTE debugger can bypass with: p = &p
  4543. *p = format; // Segfault, hopefully dumping core
  4544. }
  4545. }
  4546. #if defined(unix)
  4547. if (forkpid > 0) {
  4548. kill(forkpid, SIGTERM);
  4549. forkpid = 0;
  4550. }
  4551. #endif
  4552. exit(status);
  4553. }
  4554. #ifdef HAVE_CURSES
  4555. char *curses_input(const char *query)
  4556. {
  4557. char *input;
  4558. echo();
  4559. input = malloc(255);
  4560. if (!input)
  4561. quit(1, "Failed to malloc input");
  4562. leaveok(logwin, false);
  4563. wlogprint("%s:\n", query);
  4564. wgetnstr(logwin, input, 255);
  4565. if (!strlen(input))
  4566. strcpy(input, "-1");
  4567. leaveok(logwin, true);
  4568. noecho();
  4569. return input;
  4570. }
  4571. #endif
  4572. void add_pool_details(bool live, char *url, char *user, char *pass)
  4573. {
  4574. struct pool *pool;
  4575. pool = add_pool();
  4576. pool->rpc_url = url;
  4577. pool->rpc_user = user;
  4578. pool->rpc_pass = pass;
  4579. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4580. if (!pool->rpc_userpass)
  4581. quit(1, "Failed to malloc userpass");
  4582. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4583. /* Test the pool is not idle if we're live running, otherwise
  4584. * it will be tested separately */
  4585. enable_pool(pool);
  4586. if (live && !pool_active(pool, false))
  4587. pool->idle = true;
  4588. }
  4589. #ifdef HAVE_CURSES
  4590. static bool input_pool(bool live)
  4591. {
  4592. char *url = NULL, *user = NULL, *pass = NULL;
  4593. bool ret = false;
  4594. immedok(logwin, true);
  4595. wlogprint("Input server details.\n");
  4596. url = curses_input("URL");
  4597. if (!url)
  4598. goto out;
  4599. if (strncmp(url, "http://", 7) &&
  4600. strncmp(url, "https://", 8)) {
  4601. char *httpinput;
  4602. httpinput = malloc(255);
  4603. if (!httpinput)
  4604. quit(1, "Failed to malloc httpinput");
  4605. strcpy(httpinput, "http://");
  4606. strncat(httpinput, url, 248);
  4607. free(url);
  4608. url = httpinput;
  4609. }
  4610. user = curses_input("Username");
  4611. if (!user)
  4612. goto out;
  4613. pass = curses_input("Password");
  4614. if (!pass)
  4615. goto out;
  4616. add_pool_details(live, url, user, pass);
  4617. ret = true;
  4618. out:
  4619. immedok(logwin, false);
  4620. if (!ret) {
  4621. if (url)
  4622. free(url);
  4623. if (user)
  4624. free(user);
  4625. if (pass)
  4626. free(pass);
  4627. }
  4628. return ret;
  4629. }
  4630. #endif
  4631. #if defined(unix)
  4632. static void fork_monitor()
  4633. {
  4634. // Make a pipe: [readFD, writeFD]
  4635. int pfd[2];
  4636. int r = pipe(pfd);
  4637. if (r < 0) {
  4638. perror("pipe - failed to create pipe for --monitor");
  4639. exit(1);
  4640. }
  4641. // Make stderr write end of pipe
  4642. fflush(stderr);
  4643. r = dup2(pfd[1], 2);
  4644. if (r < 0) {
  4645. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  4646. exit(1);
  4647. }
  4648. r = close(pfd[1]);
  4649. if (r < 0) {
  4650. perror("close - failed to close write end of pipe for --monitor");
  4651. exit(1);
  4652. }
  4653. // Don't allow a dying monitor to kill the main process
  4654. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  4655. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  4656. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  4657. perror("signal - failed to edit signal mask for --monitor");
  4658. exit(1);
  4659. }
  4660. // Fork a child process
  4661. forkpid = fork();
  4662. if (forkpid < 0) {
  4663. perror("fork - failed to fork child process for --monitor");
  4664. exit(1);
  4665. }
  4666. // Child: launch monitor command
  4667. if (0 == forkpid) {
  4668. // Make stdin read end of pipe
  4669. r = dup2(pfd[0], 0);
  4670. if (r < 0) {
  4671. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  4672. exit(1);
  4673. }
  4674. close(pfd[0]);
  4675. if (r < 0) {
  4676. perror("close - in child, failed to close read end of pipe for --monitor");
  4677. exit(1);
  4678. }
  4679. // Launch user specified command
  4680. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  4681. perror("execl - in child failed to exec user specified command for --monitor");
  4682. exit(1);
  4683. }
  4684. // Parent: clean up unused fds and bail
  4685. r = close(pfd[0]);
  4686. if (r < 0) {
  4687. perror("close - failed to close read end of pipe for --monitor");
  4688. exit(1);
  4689. }
  4690. }
  4691. #endif // defined(unix)
  4692. #ifdef HAVE_CURSES
  4693. void enable_curses(void) {
  4694. int x,y;
  4695. lock_curses();
  4696. if (curses_active) {
  4697. unlock_curses();
  4698. return;
  4699. }
  4700. mainwin = initscr();
  4701. keypad(mainwin, true);
  4702. getmaxyx(mainwin, y, x);
  4703. statuswin = newwin(logstart, x, 0, 0);
  4704. leaveok(statuswin, true);
  4705. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  4706. // We resize the window later anyway, so just start it off at 1 :)
  4707. logwin = newwin(1, 0, logcursor, 0);
  4708. idlok(logwin, true);
  4709. scrollok(logwin, true);
  4710. leaveok(logwin, true);
  4711. cbreak();
  4712. noecho();
  4713. curses_active = true;
  4714. statusy = logstart;
  4715. unlock_curses();
  4716. }
  4717. #endif
  4718. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  4719. #ifndef WANT_CPUMINE
  4720. struct device_api cpu_api;
  4721. struct device_api cpu_api = {
  4722. .name = "CPU",
  4723. };
  4724. #endif
  4725. #ifdef USE_BITFORCE
  4726. extern struct device_api bitforce_api;
  4727. #endif
  4728. #ifdef USE_ICARUS
  4729. extern struct device_api icarus_api;
  4730. #endif
  4731. #ifdef USE_MODMINER
  4732. extern struct device_api modminer_api;
  4733. #endif
  4734. #ifdef USE_ZTEX
  4735. extern struct device_api ztex_api;
  4736. #endif
  4737. static int cgminer_id_count = 0;
  4738. void enable_device(struct cgpu_info *cgpu)
  4739. {
  4740. cgpu->deven = DEV_ENABLED;
  4741. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  4742. mining_threads += cgpu->threads;
  4743. #ifdef HAVE_CURSES
  4744. adj_width(mining_threads, &dev_width);
  4745. #endif
  4746. #ifdef HAVE_OPENCL
  4747. if (cgpu->api == &opencl_api) {
  4748. gpu_threads += cgpu->threads;
  4749. }
  4750. #endif
  4751. }
  4752. struct _cgpu_devid_counter {
  4753. char name[4];
  4754. int lastid;
  4755. UT_hash_handle hh;
  4756. };
  4757. bool add_cgpu(struct cgpu_info*cgpu)
  4758. {
  4759. static struct _cgpu_devid_counter *devids = NULL;
  4760. struct _cgpu_devid_counter *d;
  4761. HASH_FIND_STR(devids, cgpu->api->name, d);
  4762. if (d)
  4763. cgpu->device_id = ++d->lastid;
  4764. else {
  4765. d = malloc(sizeof(*d));
  4766. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  4767. cgpu->device_id = d->lastid = 0;
  4768. HASH_ADD_STR(devids, name, d);
  4769. }
  4770. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + 2));
  4771. devices[total_devices++] = cgpu;
  4772. return true;
  4773. }
  4774. int main(int argc, char *argv[])
  4775. {
  4776. struct block *block, *tmpblock;
  4777. struct work *work, *tmpwork;
  4778. bool pools_active = false;
  4779. struct sigaction handler;
  4780. struct thr_info *thr;
  4781. char *s;
  4782. unsigned int k;
  4783. int i, j;
  4784. /* This dangerous functions tramples random dynamically allocated
  4785. * variables so do it before anything at all */
  4786. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4787. quit(1, "Failed to curl_global_init");
  4788. initial_args = malloc(sizeof(char *) * (argc + 1));
  4789. for (i = 0; i < argc; i++)
  4790. initial_args[i] = strdup(argv[i]);
  4791. initial_args[argc] = NULL;
  4792. #ifdef HAVE_LIBUSB
  4793. libusb_init(NULL);
  4794. #endif
  4795. mutex_init(&hash_lock);
  4796. mutex_init(&qd_lock);
  4797. mutex_init(&console_lock);
  4798. mutex_init(&control_lock);
  4799. mutex_init(&sharelog_lock);
  4800. mutex_init(&ch_lock);
  4801. rwlock_init(&blk_lock);
  4802. rwlock_init(&netacc_lock);
  4803. mutex_init(&lp_lock);
  4804. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  4805. quit(1, "Failed to pthread_cond_init lp_cond");
  4806. mutex_init(&restart_lock);
  4807. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  4808. quit(1, "Failed to pthread_cond_init restart_cond");
  4809. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4810. #ifdef WANT_CPUMINE
  4811. init_max_name_len();
  4812. #endif
  4813. handler.sa_handler = &sighandler;
  4814. handler.sa_flags = 0;
  4815. sigemptyset(&handler.sa_mask);
  4816. sigaction(SIGTERM, &handler, &termhandler);
  4817. sigaction(SIGINT, &handler, &inthandler);
  4818. opt_kernel_path = alloca(PATH_MAX);
  4819. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4820. cgminer_path = alloca(PATH_MAX);
  4821. s = strdup(argv[0]);
  4822. strcpy(cgminer_path, dirname(s));
  4823. free(s);
  4824. strcat(cgminer_path, "/");
  4825. #ifdef WANT_CPUMINE
  4826. // Hack to make cgminer silent when called recursively on WIN32
  4827. int skip_to_bench = 0;
  4828. #if defined(WIN32)
  4829. char buf[32];
  4830. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  4831. skip_to_bench = 1;
  4832. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4833. skip_to_bench = 1;
  4834. #endif // defined(WIN32)
  4835. #endif
  4836. devcursor = 8;
  4837. logstart = devcursor + 1;
  4838. logcursor = logstart + 1;
  4839. block = calloc(sizeof(struct block), 1);
  4840. if (unlikely(!block))
  4841. quit (1, "main OOM");
  4842. for (i = 0; i < 36; i++)
  4843. strcat(block->hash, "0");
  4844. HASH_ADD_STR(blocks, hash, block);
  4845. strcpy(current_block, block->hash);
  4846. INIT_LIST_HEAD(&scan_devices);
  4847. #ifdef HAVE_OPENCL
  4848. memset(gpus, 0, sizeof(gpus));
  4849. for (i = 0; i < MAX_GPUDEVICES; i++)
  4850. gpus[i].dynamic = true;
  4851. #endif
  4852. /* parse command line */
  4853. opt_register_table(opt_config_table,
  4854. "Options for both config file and command line");
  4855. opt_register_table(opt_cmdline_table,
  4856. "Options for command line only");
  4857. opt_parse(&argc, argv, applog_and_exit);
  4858. if (argc != 1)
  4859. quit(1, "Unexpected extra commandline arguments");
  4860. if (!config_loaded)
  4861. load_default_config();
  4862. if (opt_benchmark) {
  4863. struct pool *pool;
  4864. want_longpoll = false;
  4865. pool = add_pool();
  4866. pool->rpc_url = malloc(255);
  4867. strcpy(pool->rpc_url, "Benchmark");
  4868. pool->rpc_user = pool->rpc_url;
  4869. pool->rpc_pass = pool->rpc_url;
  4870. enable_pool(pool);
  4871. pool->idle = false;
  4872. successful_connect = true;
  4873. }
  4874. #ifdef HAVE_CURSES
  4875. if (opt_realquiet || devices_enabled == -1)
  4876. use_curses = false;
  4877. if (use_curses)
  4878. enable_curses();
  4879. #endif
  4880. applog(LOG_WARNING, "Started %s", packagename);
  4881. if (cnfbuf) {
  4882. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  4883. switch (fileconf_load) {
  4884. case 0:
  4885. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  4886. applog(LOG_WARNING, "Configuration file could not be used.");
  4887. break;
  4888. case -1:
  4889. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  4890. if (use_curses)
  4891. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  4892. break;
  4893. default:
  4894. break;
  4895. }
  4896. free(cnfbuf);
  4897. cnfbuf = NULL;
  4898. }
  4899. strcat(opt_kernel_path, "/");
  4900. if (want_per_device_stats)
  4901. opt_log_output = true;
  4902. #ifdef WANT_CPUMINE
  4903. #ifdef USE_SCRYPT
  4904. if (opt_scrypt)
  4905. set_scrypt_algo(&opt_algo);
  4906. else
  4907. #endif
  4908. if (0 <= opt_bench_algo) {
  4909. double rate = bench_algo_stage3(opt_bench_algo);
  4910. if (!skip_to_bench)
  4911. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4912. else {
  4913. // Write result to shared memory for parent
  4914. #if defined(WIN32)
  4915. char unique_name[64];
  4916. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4917. HANDLE map_handle = CreateFileMapping(
  4918. INVALID_HANDLE_VALUE, // use paging file
  4919. NULL, // default security attributes
  4920. PAGE_READWRITE, // read/write access
  4921. 0, // size: high 32-bits
  4922. 4096, // size: low 32-bits
  4923. unique_name // name of map object
  4924. );
  4925. if (NULL != map_handle) {
  4926. void *shared_mem = MapViewOfFile(
  4927. map_handle, // object to map view of
  4928. FILE_MAP_WRITE, // read/write access
  4929. 0, // high offset: map from
  4930. 0, // low offset: beginning
  4931. 0 // default: map entire file
  4932. );
  4933. if (NULL != shared_mem)
  4934. CopyMemory(shared_mem, &rate, sizeof(rate));
  4935. (void)UnmapViewOfFile(shared_mem);
  4936. }
  4937. (void)CloseHandle(map_handle);
  4938. }
  4939. #endif
  4940. }
  4941. exit(0);
  4942. }
  4943. #endif
  4944. #ifdef HAVE_OPENCL
  4945. if (!opt_nogpu)
  4946. opencl_api.api_detect();
  4947. gpu_threads = 0;
  4948. #endif
  4949. #ifdef USE_ICARUS
  4950. icarus_api.api_detect();
  4951. #endif
  4952. #ifdef USE_BITFORCE
  4953. bitforce_api.api_detect();
  4954. #endif
  4955. #ifdef USE_MODMINER
  4956. modminer_api.api_detect();
  4957. #endif
  4958. #ifdef USE_ZTEX
  4959. ztex_api.api_detect();
  4960. #endif
  4961. #ifdef WANT_CPUMINE
  4962. cpu_api.api_detect();
  4963. #endif
  4964. for (i = 0; i < total_devices; ++i)
  4965. if (!devices[i]->devtype)
  4966. devices[i]->devtype = "PGA";
  4967. if (devices_enabled == -1) {
  4968. applog(LOG_ERR, "Devices detected:");
  4969. for (i = 0; i < total_devices; ++i) {
  4970. struct cgpu_info *cgpu = devices[i];
  4971. if (cgpu->name)
  4972. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  4973. else
  4974. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  4975. }
  4976. quit(0, "%d devices listed", total_devices);
  4977. }
  4978. mining_threads = 0;
  4979. if (devices_enabled) {
  4980. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  4981. if (devices_enabled & (1 << i)) {
  4982. if (i >= total_devices)
  4983. quit (1, "Command line options set a device that doesn't exist");
  4984. enable_device(devices[i]);
  4985. } else if (i < total_devices) {
  4986. if (opt_removedisabled) {
  4987. if (devices[i]->api == &cpu_api)
  4988. --opt_n_threads;
  4989. } else {
  4990. enable_device(devices[i]);
  4991. }
  4992. devices[i]->deven = DEV_DISABLED;
  4993. }
  4994. }
  4995. total_devices = cgminer_id_count;
  4996. } else {
  4997. for (i = 0; i < total_devices; ++i)
  4998. enable_device(devices[i]);
  4999. }
  5000. if (!total_devices)
  5001. quit(1, "All devices disabled, cannot mine!");
  5002. load_temp_cutoffs();
  5003. for (i = 0; i < total_devices; ++i)
  5004. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5005. logstart += total_devices;
  5006. logcursor = logstart + 1;
  5007. #ifdef HAVE_CURSES
  5008. check_winsizes();
  5009. #endif
  5010. if (!total_pools) {
  5011. applog(LOG_WARNING, "Need to specify at least one pool server.");
  5012. #ifdef HAVE_CURSES
  5013. if (!use_curses || !input_pool(false))
  5014. #endif
  5015. quit(1, "Pool setup failed");
  5016. }
  5017. for (i = 0; i < total_pools; i++) {
  5018. struct pool *pool = pools[i];
  5019. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5020. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5021. if (!pool->rpc_userpass) {
  5022. if (!pool->rpc_user || !pool->rpc_pass)
  5023. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  5024. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5025. if (!pool->rpc_userpass)
  5026. quit(1, "Failed to malloc userpass");
  5027. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5028. } else {
  5029. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  5030. if (!pool->rpc_user)
  5031. quit(1, "Failed to malloc user");
  5032. strcpy(pool->rpc_user, pool->rpc_userpass);
  5033. pool->rpc_user = strtok(pool->rpc_user, ":");
  5034. if (!pool->rpc_user)
  5035. quit(1, "Failed to find colon delimiter in userpass");
  5036. }
  5037. }
  5038. /* Set the currentpool to pool 0 */
  5039. currentpool = pools[0];
  5040. #ifdef HAVE_SYSLOG_H
  5041. if (use_syslog)
  5042. openlog(PACKAGE, LOG_PID, LOG_USER);
  5043. #endif
  5044. #if defined(unix)
  5045. if (opt_stderr_cmd)
  5046. fork_monitor();
  5047. #endif // defined(unix)
  5048. total_threads = mining_threads + 7;
  5049. thr_info = calloc(total_threads, sizeof(*thr));
  5050. if (!thr_info)
  5051. quit(1, "Failed to calloc thr_info");
  5052. /* init workio thread info */
  5053. work_thr_id = mining_threads;
  5054. thr = &thr_info[work_thr_id];
  5055. thr->id = work_thr_id;
  5056. thr->q = tq_new();
  5057. if (!thr->q)
  5058. quit(1, "Failed to tq_new");
  5059. /* start work I/O thread */
  5060. if (thr_info_create(thr, NULL, workio_thread, thr))
  5061. quit(1, "workio thread create failed");
  5062. stage_thr_id = mining_threads + 1;
  5063. thr = &thr_info[stage_thr_id];
  5064. thr->q = tq_new();
  5065. if (!thr->q)
  5066. quit(1, "Failed to tq_new");
  5067. /* start stage thread */
  5068. if (thr_info_create(thr, NULL, stage_thread, thr))
  5069. quit(1, "stage thread create failed");
  5070. pthread_detach(thr->pth);
  5071. /* Create a unique get work queue */
  5072. getq = tq_new();
  5073. if (!getq)
  5074. quit(1, "Failed to create getq");
  5075. /* We use the getq mutex as the staged lock */
  5076. stgd_lock = &getq->mutex;
  5077. if (opt_benchmark)
  5078. goto begin_bench;
  5079. for (i = 0; i < total_pools; i++) {
  5080. struct pool *pool = pools[i];
  5081. enable_pool(pool);
  5082. pool->idle = true;
  5083. }
  5084. applog(LOG_NOTICE, "Probing for an alive pool");
  5085. do {
  5086. /* Look for at least one active pool before starting */
  5087. for (i = 0; i < total_pools; i++) {
  5088. struct pool *pool = pools[i];
  5089. if (pool_active(pool, false)) {
  5090. if (!currentpool)
  5091. currentpool = pool;
  5092. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  5093. pools_active = true;
  5094. break;
  5095. } else {
  5096. if (pool == currentpool)
  5097. currentpool = NULL;
  5098. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  5099. }
  5100. }
  5101. if (!pools_active) {
  5102. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  5103. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  5104. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  5105. for (i = 0; i < total_pools; i++) {
  5106. struct pool *pool;
  5107. pool = pools[i];
  5108. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  5109. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  5110. }
  5111. #ifdef HAVE_CURSES
  5112. if (use_curses) {
  5113. halfdelay(150);
  5114. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  5115. if (getch() != ERR)
  5116. quit(0, "No servers could be used! Exiting.");
  5117. nocbreak();
  5118. } else
  5119. #endif
  5120. quit(0, "No servers could be used! Exiting.");
  5121. }
  5122. } while (!pools_active);
  5123. #ifdef USE_SCRYPT
  5124. if (detect_algo == 1 && !opt_scrypt) {
  5125. applog(LOG_NOTICE, "Detected scrypt algorithm");
  5126. opt_scrypt = true;
  5127. }
  5128. #endif
  5129. detect_algo = 0;
  5130. begin_bench:
  5131. total_mhashes_done = 0;
  5132. for (i = 0; i < total_devices; i++) {
  5133. struct cgpu_info *cgpu = devices[i];
  5134. cgpu->rolling = cgpu->total_mhashes = 0;
  5135. }
  5136. gettimeofday(&total_tv_start, NULL);
  5137. gettimeofday(&total_tv_end, NULL);
  5138. miner_started = total_tv_start;
  5139. get_datestamp(datestamp, &total_tv_start);
  5140. // Start threads
  5141. k = 0;
  5142. for (i = 0; i < total_devices; ++i) {
  5143. struct cgpu_info *cgpu = devices[i];
  5144. cgpu->thr = calloc(cgpu->threads+1, sizeof(*cgpu->thr));
  5145. cgpu->thr[cgpu->threads] = NULL;
  5146. cgpu->status = LIFE_INIT;
  5147. // Setup thread structs before starting any of the threads, in case they try to interact
  5148. for (j = 0; j < cgpu->threads; ++j, ++k) {
  5149. thr = &thr_info[k];
  5150. thr->id = k;
  5151. thr->cgpu = cgpu;
  5152. thr->device_thread = j;
  5153. thr->work_restart_fd = thr->_work_restart_fd_w = -1;
  5154. thr->q = tq_new();
  5155. if (!thr->q)
  5156. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  5157. /* Enable threads for devices set not to mine but disable
  5158. * their queue in case we wish to enable them later */
  5159. if (cgpu->deven != DEV_DISABLED) {
  5160. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  5161. tq_push(thr->q, &ping);
  5162. }
  5163. cgpu->thr[j] = thr;
  5164. }
  5165. for (j = 0; j < cgpu->threads; ++j) {
  5166. thr = cgpu->thr[j];
  5167. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  5168. continue;
  5169. if (!thr->work_restart_fd)
  5170. {
  5171. #if defined(unix)
  5172. int pipefd[2];
  5173. if (!pipe(pipefd))
  5174. {
  5175. thr->work_restart_fd = pipefd[0];
  5176. thr->_work_restart_fd_w = pipefd[1];
  5177. }
  5178. else
  5179. #endif
  5180. thr->work_restart_fd = -1;
  5181. }
  5182. thread_reportout(thr);
  5183. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  5184. quit(1, "thread %d create failed", thr->id);
  5185. }
  5186. }
  5187. #ifdef HAVE_OPENCL
  5188. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  5189. for (i = 0; i < nDevs; i++)
  5190. pause_dynamic_threads(i);
  5191. #endif
  5192. #ifdef WANT_CPUMINE
  5193. applog(LOG_INFO, "%d cpu miner threads started, "
  5194. "using SHA256 '%s' algorithm.",
  5195. opt_n_threads,
  5196. algo_names[opt_algo]);
  5197. #endif
  5198. gettimeofday(&total_tv_start, NULL);
  5199. gettimeofday(&total_tv_end, NULL);
  5200. watchpool_thr_id = mining_threads + 2;
  5201. thr = &thr_info[watchpool_thr_id];
  5202. /* start watchpool thread */
  5203. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  5204. quit(1, "watchpool thread create failed");
  5205. pthread_detach(thr->pth);
  5206. watchdog_thr_id = mining_threads + 3;
  5207. thr = &thr_info[watchdog_thr_id];
  5208. /* start watchdog thread */
  5209. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  5210. quit(1, "watchdog thread create failed");
  5211. pthread_detach(thr->pth);
  5212. #ifdef HAVE_OPENCL
  5213. /* Create reinit gpu thread */
  5214. gpur_thr_id = mining_threads + 4;
  5215. thr = &thr_info[gpur_thr_id];
  5216. thr->q = tq_new();
  5217. if (!thr->q)
  5218. quit(1, "tq_new failed for gpur_thr_id");
  5219. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  5220. quit(1, "reinit_gpu thread create failed");
  5221. #endif
  5222. /* Create API socket thread */
  5223. api_thr_id = mining_threads + 5;
  5224. thr = &thr_info[api_thr_id];
  5225. if (thr_info_create(thr, NULL, api_thread, thr))
  5226. quit(1, "API thread create failed");
  5227. #ifdef HAVE_CURSES
  5228. /* Create curses input thread for keyboard input. Create this last so
  5229. * that we know all threads are created since this can call kill_work
  5230. * to try and shut down ll previous threads. */
  5231. input_thr_id = mining_threads + 6;
  5232. thr = &thr_info[input_thr_id];
  5233. if (thr_info_create(thr, NULL, input_thread, thr))
  5234. quit(1, "input thread create failed");
  5235. pthread_detach(thr->pth);
  5236. #endif
  5237. /* main loop - simply wait for workio thread to exit. This is not the
  5238. * normal exit path and only occurs should the workio_thread die
  5239. * unexpectedly */
  5240. pthread_join(thr_info[work_thr_id].pth, NULL);
  5241. applog(LOG_INFO, "workio thread dead, exiting.");
  5242. clean_up();
  5243. /* Not really necessary, but let's clean this up too anyway */
  5244. HASH_ITER(hh, staged_work, work, tmpwork) {
  5245. HASH_DEL(staged_work, work);
  5246. free_work(work);
  5247. }
  5248. HASH_ITER(hh, blocks, block, tmpblock) {
  5249. HASH_DEL(blocks, block);
  5250. free(block);
  5251. }
  5252. #if defined(unix)
  5253. if (forkpid > 0) {
  5254. kill(forkpid, SIGTERM);
  5255. forkpid = 0;
  5256. }
  5257. #endif
  5258. return 0;
  5259. }