miner.c 196 KB

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