miner.c 161 KB

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