miner.c 175 KB

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