miner.c 174 KB

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