miner.c 345 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2012-2013 Andrew Smith
  6. * Copyright 2010 Jeff Garzik
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #ifdef HAVE_CURSES
  15. #ifdef USE_UNICODE
  16. #define PDC_WIDE
  17. #endif
  18. // Must be before stdbool, since pdcurses typedefs bool :/
  19. #include <curses.h>
  20. #endif
  21. #include <ctype.h>
  22. #include <float.h>
  23. #include <limits.h>
  24. #include <locale.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <stdbool.h>
  29. #include <stdint.h>
  30. #include <unistd.h>
  31. #include <sys/time.h>
  32. #include <time.h>
  33. #include <math.h>
  34. #include <stdarg.h>
  35. #include <assert.h>
  36. #include <signal.h>
  37. #include <wctype.h>
  38. #include <sys/stat.h>
  39. #include <sys/types.h>
  40. #include <dirent.h>
  41. #ifdef HAVE_PWD_H
  42. #include <pwd.h>
  43. #endif
  44. #ifndef WIN32
  45. #include <sys/resource.h>
  46. #include <sys/socket.h>
  47. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  48. #include <libudev.h>
  49. #include <sys/epoll.h>
  50. #define HAVE_BFG_HOTPLUG
  51. #endif
  52. #else
  53. #include <winsock2.h>
  54. #include <windows.h>
  55. #include <dbt.h>
  56. #define HAVE_BFG_HOTPLUG
  57. #endif
  58. #include <ccan/opt/opt.h>
  59. #include <jansson.h>
  60. #include <curl/curl.h>
  61. #include <libgen.h>
  62. #include <sha2.h>
  63. #include <utlist.h>
  64. #include <blkmaker.h>
  65. #include <blkmaker_jansson.h>
  66. #include <blktemplate.h>
  67. #include <libbase58.h>
  68. #include "compat.h"
  69. #include "deviceapi.h"
  70. #include "logging.h"
  71. #include "miner.h"
  72. #include "adl.h"
  73. #include "driver-cpu.h"
  74. #include "driver-opencl.h"
  75. #include "scrypt.h"
  76. #include "util.h"
  77. #ifdef USE_AVALON
  78. #include "driver-avalon.h"
  79. #endif
  80. #ifdef HAVE_BFG_LOWLEVEL
  81. #include "lowlevel.h"
  82. #endif
  83. #if defined(unix) || defined(__APPLE__)
  84. #include <errno.h>
  85. #include <fcntl.h>
  86. #include <sys/wait.h>
  87. #endif
  88. #ifdef USE_SCRYPT
  89. #include "scrypt.h"
  90. #endif
  91. #include "version.h"
  92. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  93. # define USE_FPGA
  94. #endif
  95. enum bfg_quit_summary {
  96. BQS_DEFAULT,
  97. BQS_NONE,
  98. BQS_DEVS,
  99. BQS_PROCS,
  100. BQS_DETAILED,
  101. };
  102. struct strategies strategies[] = {
  103. { "Failover" },
  104. { "Round Robin" },
  105. { "Rotate" },
  106. { "Load Balance" },
  107. { "Balance" },
  108. };
  109. static char packagename[256];
  110. bool opt_protocol;
  111. bool opt_dev_protocol;
  112. static bool opt_benchmark, opt_benchmark_intense;
  113. static bool want_longpoll = true;
  114. static bool want_gbt = true;
  115. static bool want_getwork = true;
  116. #if BLKMAKER_VERSION > 1
  117. static bool opt_load_bitcoin_conf = true;
  118. static bool have_at_least_one_getcbaddr;
  119. static bytes_t opt_coinbase_script = BYTES_INIT;
  120. static uint32_t coinbase_script_block_id;
  121. static uint32_t template_nonce;
  122. #endif
  123. #if BLKMAKER_VERSION > 0
  124. char *opt_coinbase_sig;
  125. #endif
  126. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  127. static bool include_serial_in_statline;
  128. char *request_target_str;
  129. float request_pdiff = 1.0;
  130. double request_bdiff;
  131. static bool want_stratum = true;
  132. bool have_longpoll;
  133. int opt_skip_checks;
  134. bool want_per_device_stats;
  135. bool use_syslog;
  136. bool opt_quiet_work_updates = true;
  137. bool opt_quiet;
  138. bool opt_realquiet;
  139. int loginput_size;
  140. bool opt_compact;
  141. bool opt_show_procs;
  142. const int opt_cutofftemp = 95;
  143. int opt_hysteresis = 3;
  144. static int opt_retries = -1;
  145. int opt_fail_pause = 5;
  146. int opt_log_interval = 20;
  147. int opt_queue = 1;
  148. int opt_scantime = 60;
  149. int opt_expiry = 120;
  150. int opt_expiry_lp = 3600;
  151. unsigned long long global_hashrate;
  152. static bool opt_unittest = false;
  153. unsigned unittest_failures;
  154. unsigned long global_quota_gcd = 1;
  155. time_t last_getwork;
  156. #ifdef HAVE_OPENCL
  157. int opt_dynamic_interval = 7;
  158. int nDevs;
  159. int opt_g_threads = -1;
  160. #endif
  161. #ifdef USE_SCRYPT
  162. static char detect_algo = 1;
  163. bool opt_scrypt;
  164. #else
  165. static char detect_algo;
  166. #endif
  167. bool opt_restart = true;
  168. #ifdef USE_LIBMICROHTTPD
  169. #include "httpsrv.h"
  170. int httpsrv_port = -1;
  171. #endif
  172. #ifdef USE_LIBEVENT
  173. int stratumsrv_port = -1;
  174. #endif
  175. const
  176. int rescan_delay_ms = 1000;
  177. #ifdef HAVE_BFG_HOTPLUG
  178. bool opt_hotplug = 1;
  179. const
  180. int hotplug_delay_ms = 100;
  181. #else
  182. const bool opt_hotplug;
  183. #endif
  184. struct string_elist *scan_devices;
  185. static struct string_elist *opt_set_device_list;
  186. bool opt_force_dev_init;
  187. static struct string_elist *opt_devices_enabled_list;
  188. static bool opt_display_devs;
  189. int total_devices;
  190. struct cgpu_info **devices;
  191. int total_devices_new;
  192. struct cgpu_info **devices_new;
  193. bool have_opencl;
  194. int opt_n_threads = -1;
  195. int mining_threads;
  196. int base_queue;
  197. int num_processors;
  198. #ifdef HAVE_CURSES
  199. bool use_curses = true;
  200. #else
  201. bool use_curses;
  202. #endif
  203. int last_logstatusline_len;
  204. #ifdef HAVE_LIBUSB
  205. bool have_libusb;
  206. #endif
  207. static bool opt_submit_stale = true;
  208. static float opt_shares;
  209. static int opt_submit_threads = 0x40;
  210. bool opt_fail_only;
  211. int opt_fail_switch_delay = 300;
  212. bool opt_autofan;
  213. bool opt_autoengine;
  214. bool opt_noadl;
  215. char *opt_api_allow = NULL;
  216. char *opt_api_groups;
  217. char *opt_api_description = PACKAGE_STRING;
  218. int opt_api_port = 4028;
  219. bool opt_api_listen;
  220. bool opt_api_mcast;
  221. char *opt_api_mcast_addr = API_MCAST_ADDR;
  222. char *opt_api_mcast_code = API_MCAST_CODE;
  223. char *opt_api_mcast_des = "";
  224. int opt_api_mcast_port = 4028;
  225. bool opt_api_network;
  226. bool opt_delaynet;
  227. bool opt_disable_pool;
  228. bool opt_disable_client_reconnect = false;
  229. static bool no_work;
  230. bool opt_worktime;
  231. bool opt_weighed_stats;
  232. char *opt_kernel_path;
  233. char *cgminer_path;
  234. #if defined(USE_BITFORCE)
  235. bool opt_bfl_noncerange;
  236. #endif
  237. #define QUIET (opt_quiet || opt_realquiet)
  238. struct thr_info *control_thr;
  239. struct thr_info **mining_thr;
  240. static int watchpool_thr_id;
  241. static int watchdog_thr_id;
  242. #ifdef HAVE_CURSES
  243. static int input_thr_id;
  244. #endif
  245. int gpur_thr_id;
  246. static int api_thr_id;
  247. static int total_control_threads;
  248. pthread_mutex_t hash_lock;
  249. static pthread_mutex_t *stgd_lock;
  250. pthread_mutex_t console_lock;
  251. cglock_t ch_lock;
  252. static pthread_rwlock_t blk_lock;
  253. static pthread_mutex_t sshare_lock;
  254. pthread_rwlock_t netacc_lock;
  255. pthread_rwlock_t mining_thr_lock;
  256. pthread_rwlock_t devices_lock;
  257. static pthread_mutex_t lp_lock;
  258. static pthread_cond_t lp_cond;
  259. pthread_cond_t gws_cond;
  260. bool shutting_down;
  261. double total_rolling;
  262. double total_mhashes_done;
  263. static struct timeval total_tv_start, total_tv_end;
  264. static struct timeval miner_started;
  265. cglock_t control_lock;
  266. pthread_mutex_t stats_lock;
  267. static pthread_mutex_t submitting_lock;
  268. static int total_submitting;
  269. static struct work *submit_waiting;
  270. notifier_t submit_waiting_notifier;
  271. int hw_errors;
  272. int total_accepted, total_rejected;
  273. int total_getworks, total_stale, total_discarded;
  274. uint64_t total_bytes_rcvd, total_bytes_sent;
  275. double total_diff1, total_bad_diff1;
  276. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  277. static int staged_rollable;
  278. unsigned int new_blocks;
  279. unsigned int found_blocks;
  280. unsigned int local_work;
  281. unsigned int total_go, total_ro;
  282. struct pool **pools;
  283. static struct pool *currentpool = NULL;
  284. int total_pools, enabled_pools;
  285. enum pool_strategy pool_strategy = POOL_FAILOVER;
  286. int opt_rotate_period;
  287. static int total_urls, total_users, total_passes;
  288. static
  289. #ifndef HAVE_CURSES
  290. const
  291. #endif
  292. bool curses_active;
  293. #ifdef HAVE_CURSES
  294. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  295. const
  296. #endif
  297. short default_bgcolor = COLOR_BLACK;
  298. static int attr_title = A_BOLD;
  299. #endif
  300. static
  301. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  302. bool use_unicode;
  303. static
  304. bool have_unicode_degrees;
  305. static
  306. wchar_t unicode_micro = 'u';
  307. #else
  308. const bool use_unicode;
  309. static
  310. const bool have_unicode_degrees;
  311. #ifdef HAVE_CURSES
  312. static
  313. const char unicode_micro = 'u';
  314. #endif
  315. #endif
  316. #ifdef HAVE_CURSES
  317. #define U8_BAD_START "\xef\x80\x81"
  318. #define U8_BAD_END "\xef\x80\x80"
  319. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  320. /* logstart is where the log window should start */
  321. static int devcursor, logstart, logcursor;
  322. bool selecting_device;
  323. unsigned selected_device;
  324. #endif
  325. static int max_lpdigits;
  326. // current_hash was replaced with goal->current_goal_detail
  327. // current_block_id was replaced with blkchain->currentblk->block_id
  328. static char datestamp[40];
  329. static char best_share[ALLOC_H2B_SHORTV] = "0";
  330. double best_diff = 0;
  331. struct mining_goal_info *mining_goals;
  332. int active_goals = 1;
  333. int swork_id;
  334. /* For creating a hash database of stratum shares submitted that have not had
  335. * a response yet */
  336. struct stratum_share {
  337. UT_hash_handle hh;
  338. bool block;
  339. struct work *work;
  340. int id;
  341. };
  342. static struct stratum_share *stratum_shares = NULL;
  343. char *opt_socks_proxy = NULL;
  344. static const char def_conf[] = "bfgminer.conf";
  345. static bool config_loaded;
  346. static int include_count;
  347. #define JSON_INCLUDE_CONF "include"
  348. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  349. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  350. #define JSON_MAX_DEPTH 10
  351. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  352. char *cmd_idle, *cmd_sick, *cmd_dead;
  353. #if defined(unix) || defined(__APPLE__)
  354. static char *opt_stderr_cmd = NULL;
  355. static int forkpid;
  356. #endif // defined(unix)
  357. #ifdef HAVE_CHROOT
  358. char *chroot_dir;
  359. #endif
  360. #ifdef HAVE_PWD_H
  361. char *opt_setuid;
  362. #endif
  363. struct sigaction termhandler, inthandler;
  364. struct thread_q *getq;
  365. static int total_work;
  366. static bool staged_full;
  367. struct work *staged_work = NULL;
  368. struct schedtime {
  369. bool enable;
  370. struct tm tm;
  371. };
  372. struct schedtime schedstart;
  373. struct schedtime schedstop;
  374. bool sched_paused;
  375. static bool time_before(struct tm *tm1, struct tm *tm2)
  376. {
  377. if (tm1->tm_hour < tm2->tm_hour)
  378. return true;
  379. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  380. return true;
  381. return false;
  382. }
  383. static bool should_run(void)
  384. {
  385. struct tm tm;
  386. time_t tt;
  387. bool within_range;
  388. if (!schedstart.enable && !schedstop.enable)
  389. return true;
  390. tt = time(NULL);
  391. localtime_r(&tt, &tm);
  392. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  393. if (time_before(&schedstop.tm, &schedstart.tm))
  394. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  395. else
  396. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  397. if (within_range && !schedstop.enable)
  398. /* This is a once off event with no stop time set */
  399. schedstart.enable = false;
  400. return within_range;
  401. }
  402. void get_datestamp(char *f, size_t fsiz, time_t tt)
  403. {
  404. struct tm _tm;
  405. struct tm *tm = &_tm;
  406. if (tt == INVALID_TIMESTAMP)
  407. tt = time(NULL);
  408. localtime_r(&tt, tm);
  409. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  410. tm->tm_year + 1900,
  411. tm->tm_mon + 1,
  412. tm->tm_mday,
  413. tm->tm_hour,
  414. tm->tm_min,
  415. tm->tm_sec);
  416. }
  417. static
  418. void get_timestamp(char *f, size_t fsiz, time_t tt)
  419. {
  420. struct tm _tm;
  421. struct tm *tm = &_tm;
  422. localtime_r(&tt, tm);
  423. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  424. tm->tm_hour,
  425. tm->tm_min,
  426. tm->tm_sec);
  427. }
  428. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  429. static char exit_buf[512];
  430. static void applog_and_exit(const char *fmt, ...)
  431. {
  432. va_list ap;
  433. va_start(ap, fmt);
  434. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  435. va_end(ap);
  436. _applog(LOG_ERR, exit_buf);
  437. exit(1);
  438. }
  439. char *devpath_to_devid(const char *devpath)
  440. {
  441. #ifndef WIN32
  442. if (devpath[0] != '/')
  443. return NULL;
  444. struct stat my_stat;
  445. if (stat(devpath, &my_stat))
  446. return NULL;
  447. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  448. memcpy(devs, "dev_t:", 6);
  449. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  450. #else
  451. if (!strncmp(devpath, "\\\\.\\", 4))
  452. devpath += 4;
  453. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  454. return NULL;
  455. devpath += 3;
  456. char *p;
  457. strtol(devpath, &p, 10);
  458. if (p[0])
  459. return NULL;
  460. const int sz = (p - devpath);
  461. char *devs = malloc(4 + sz + 1);
  462. sprintf(devs, "com:%s", devpath);
  463. #endif
  464. return devs;
  465. }
  466. static
  467. bool devpaths_match(const char * const ap, const char * const bp)
  468. {
  469. char * const a = devpath_to_devid(ap);
  470. if (!a)
  471. return false;
  472. char * const b = devpath_to_devid(bp);
  473. bool rv = false;
  474. if (b)
  475. {
  476. rv = !strcmp(a, b);
  477. free(b);
  478. }
  479. free(a);
  480. return rv;
  481. }
  482. static
  483. int proc_letter_to_number(const char *s, const char ** const rem)
  484. {
  485. int n = 0, c;
  486. for ( ; s[0]; ++s)
  487. {
  488. if (unlikely(n > INT_MAX / 26))
  489. break;
  490. c = tolower(s[0]) - 'a';
  491. if (unlikely(c < 0 || c > 25))
  492. break;
  493. if (unlikely(INT_MAX - c < n))
  494. break;
  495. n = (n * 26) + c;
  496. }
  497. *rem = s;
  498. return n;
  499. }
  500. static
  501. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  502. {
  503. // all - matches anything
  504. // d0 - matches all processors of device 0
  505. // d0-3 - matches all processors of device 0, 1, 2, or 3
  506. // d0a - matches first processor of device 0
  507. // 0 - matches processor 0
  508. // 0-4 - matches processors 0, 1, 2, 3, or 4
  509. // ___ - matches all processors on all devices using driver/name ___
  510. // ___0 - matches all processors of 0th device using driver/name ___
  511. // ___0a - matches first processor of 0th device using driver/name ___
  512. // @* - matches device with serial or path *
  513. // @*@a - matches first processor of device with serial or path *
  514. // ___@* - matches device with serial or path * using driver/name ___
  515. if (!strcasecmp(pattern, "all"))
  516. return true;
  517. const struct device_drv * const drv = cgpu->drv;
  518. const char *p = pattern, *p2;
  519. size_t L;
  520. int n, i, c = -1;
  521. int n2;
  522. int proc_first = -1, proc_last = -1;
  523. struct cgpu_info *device;
  524. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  525. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  526. // dname or name
  527. p = &pattern[L];
  528. else
  529. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  530. // d#
  531. ++p;
  532. else
  533. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  534. // # or @
  535. {}
  536. else
  537. return false;
  538. L = p - pattern;
  539. while (isspace(p[0]))
  540. ++p;
  541. if (p[0] == '@')
  542. {
  543. // Serial/path
  544. const char * const ser = &p[1];
  545. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  546. {}
  547. p2 = (p[0] == '@') ? &p[1] : p;
  548. const size_t serlen = (p - ser);
  549. p = "";
  550. n = n2 = 0;
  551. const char * const devpath = cgpu->device_path ?: "";
  552. const char * const devser = cgpu->dev_serial ?: "";
  553. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  554. {} // Match
  555. else
  556. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  557. {} // Match
  558. else
  559. {
  560. char devpath2[serlen + 1];
  561. memcpy(devpath2, ser, serlen);
  562. devpath2[serlen] = '\0';
  563. if (!devpaths_match(devpath, ser))
  564. return false;
  565. }
  566. }
  567. else
  568. {
  569. if (isdigit(p[0]))
  570. n = strtol(p, (void*)&p2, 0);
  571. else
  572. {
  573. n = 0;
  574. p2 = p;
  575. }
  576. if (p2[0] == '-')
  577. {
  578. ++p2;
  579. if (p2[0] && isdigit(p2[0]))
  580. n2 = strtol(p2, (void*)&p2, 0);
  581. else
  582. n2 = INT_MAX;
  583. }
  584. else
  585. n2 = n;
  586. if (p == pattern)
  587. {
  588. if (!p[0])
  589. return true;
  590. if (p2 && p2[0])
  591. goto invsyntax;
  592. for (i = n; i <= n2; ++i)
  593. {
  594. if (i >= total_devices)
  595. break;
  596. if (cgpu == devices[i])
  597. return true;
  598. }
  599. return false;
  600. }
  601. }
  602. if (p2[0])
  603. {
  604. proc_first = proc_letter_to_number(&p2[0], &p2);
  605. if (p2[0] == '-')
  606. {
  607. ++p2;
  608. if (p2[0])
  609. proc_last = proc_letter_to_number(p2, &p2);
  610. else
  611. proc_last = INT_MAX;
  612. }
  613. else
  614. proc_last = proc_first;
  615. if (p2[0])
  616. goto invsyntax;
  617. }
  618. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  619. {
  620. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  621. (!L) ||
  622. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  623. {} // Matched name or dname
  624. else
  625. return false;
  626. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  627. return false;
  628. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  629. return false;
  630. return true;
  631. }
  632. // d#
  633. c = -1;
  634. for (i = 0; ; ++i)
  635. {
  636. if (i == total_devices)
  637. return false;
  638. if (devices[i]->device != devices[i])
  639. continue;
  640. ++c;
  641. if (c < n)
  642. continue;
  643. if (c > n2)
  644. break;
  645. for (device = devices[i]; device; device = device->next_proc)
  646. {
  647. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  648. continue;
  649. if (device == cgpu)
  650. return true;
  651. }
  652. }
  653. return false;
  654. invsyntax:
  655. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  656. return false;
  657. }
  658. #define TEST_CGPU_MATCH(pattern) \
  659. if (!cgpu_match(pattern, &cgpu)) \
  660. { \
  661. ++unittest_failures; \
  662. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  663. } \
  664. // END TEST_CGPU_MATCH
  665. #define TEST_CGPU_NOMATCH(pattern) \
  666. if (cgpu_match(pattern, &cgpu)) \
  667. { \
  668. ++unittest_failures; \
  669. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  670. } \
  671. // END TEST_CGPU_MATCH
  672. static __maybe_unused
  673. void test_cgpu_match()
  674. {
  675. struct device_drv drv = {
  676. .dname = "test",
  677. .name = "TST",
  678. };
  679. struct cgpu_info cgpu = {
  680. .drv = &drv,
  681. .device = &cgpu,
  682. .device_id = 1,
  683. .proc_id = 1,
  684. .proc_repr = "TST 1b",
  685. }, cgpu0a = {
  686. .drv = &drv,
  687. .device = &cgpu0a,
  688. .device_id = 0,
  689. .proc_id = 0,
  690. .proc_repr = "TST 0a",
  691. }, cgpu1a = {
  692. .drv = &drv,
  693. .device = &cgpu0a,
  694. .device_id = 1,
  695. .proc_id = 0,
  696. .proc_repr = "TST 1a",
  697. };
  698. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  699. devices = devices_list;
  700. total_devices = 3;
  701. TEST_CGPU_MATCH("all")
  702. TEST_CGPU_MATCH("d1")
  703. TEST_CGPU_NOMATCH("d2")
  704. TEST_CGPU_MATCH("d0-5")
  705. TEST_CGPU_NOMATCH("d0-0")
  706. TEST_CGPU_NOMATCH("d2-5")
  707. TEST_CGPU_MATCH("d-1")
  708. TEST_CGPU_MATCH("d1-")
  709. TEST_CGPU_NOMATCH("d-0")
  710. TEST_CGPU_NOMATCH("d2-")
  711. TEST_CGPU_MATCH("2")
  712. TEST_CGPU_NOMATCH("3")
  713. TEST_CGPU_MATCH("1-2")
  714. TEST_CGPU_MATCH("2-3")
  715. TEST_CGPU_NOMATCH("1-1")
  716. TEST_CGPU_NOMATCH("3-4")
  717. TEST_CGPU_MATCH("TST")
  718. TEST_CGPU_MATCH("test")
  719. TEST_CGPU_MATCH("tst")
  720. TEST_CGPU_MATCH("TEST")
  721. TEST_CGPU_NOMATCH("TSF")
  722. TEST_CGPU_NOMATCH("TS")
  723. TEST_CGPU_NOMATCH("TSTF")
  724. TEST_CGPU_MATCH("TST1")
  725. TEST_CGPU_MATCH("test1")
  726. TEST_CGPU_MATCH("TST0-1")
  727. TEST_CGPU_MATCH("TST 1")
  728. TEST_CGPU_MATCH("TST 1-2")
  729. TEST_CGPU_MATCH("TEST 1-2")
  730. TEST_CGPU_NOMATCH("TST2")
  731. TEST_CGPU_NOMATCH("TST2-3")
  732. TEST_CGPU_NOMATCH("TST0-0")
  733. TEST_CGPU_MATCH("TST1b")
  734. TEST_CGPU_MATCH("tst1b")
  735. TEST_CGPU_NOMATCH("TST1c")
  736. TEST_CGPU_NOMATCH("TST1bb")
  737. TEST_CGPU_MATCH("TST0-1b")
  738. TEST_CGPU_NOMATCH("TST0-1c")
  739. TEST_CGPU_MATCH("TST1a-d")
  740. TEST_CGPU_NOMATCH("TST1a-a")
  741. TEST_CGPU_NOMATCH("TST1-a")
  742. TEST_CGPU_NOMATCH("TST1c-z")
  743. TEST_CGPU_NOMATCH("TST1c-")
  744. TEST_CGPU_MATCH("@")
  745. TEST_CGPU_NOMATCH("@abc")
  746. TEST_CGPU_MATCH("@@b")
  747. TEST_CGPU_NOMATCH("@@c")
  748. TEST_CGPU_MATCH("TST@")
  749. TEST_CGPU_NOMATCH("TST@abc")
  750. TEST_CGPU_MATCH("TST@@b")
  751. TEST_CGPU_NOMATCH("TST@@c")
  752. TEST_CGPU_MATCH("TST@@b-f")
  753. TEST_CGPU_NOMATCH("TST@@c-f")
  754. TEST_CGPU_NOMATCH("TST@@-a")
  755. cgpu.device_path = "/dev/test";
  756. cgpu.dev_serial = "testy";
  757. TEST_CGPU_MATCH("TST@/dev/test")
  758. TEST_CGPU_MATCH("TST@testy")
  759. TEST_CGPU_NOMATCH("TST@")
  760. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  761. TEST_CGPU_NOMATCH("TST@testy3@b")
  762. TEST_CGPU_MATCH("TST@/dev/test@b")
  763. TEST_CGPU_MATCH("TST@testy@b")
  764. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  765. TEST_CGPU_NOMATCH("TST@testy@c")
  766. cgpu.device_path = "usb:000:999";
  767. TEST_CGPU_MATCH("TST@usb:000:999")
  768. drv.dname = "test7";
  769. TEST_CGPU_MATCH("test7")
  770. TEST_CGPU_MATCH("TEST7")
  771. TEST_CGPU_NOMATCH("test&")
  772. TEST_CGPU_MATCH("test7 1-2")
  773. TEST_CGPU_MATCH("test7@testy@b")
  774. }
  775. static
  776. int cgpu_search(const char * const pattern, const int first)
  777. {
  778. int i;
  779. struct cgpu_info *cgpu;
  780. #define CHECK_CGPU_SEARCH do{ \
  781. cgpu = get_devices(i); \
  782. if (cgpu_match(pattern, cgpu)) \
  783. return i; \
  784. }while(0)
  785. for (i = first; i < total_devices; ++i)
  786. CHECK_CGPU_SEARCH;
  787. for (i = 0; i < first; ++i)
  788. CHECK_CGPU_SEARCH;
  789. #undef CHECK_CGPU_SEARCH
  790. return -1;
  791. }
  792. static pthread_mutex_t sharelog_lock;
  793. static FILE *sharelog_file = NULL;
  794. struct thr_info *get_thread(int thr_id)
  795. {
  796. struct thr_info *thr;
  797. rd_lock(&mining_thr_lock);
  798. thr = mining_thr[thr_id];
  799. rd_unlock(&mining_thr_lock);
  800. return thr;
  801. }
  802. static struct cgpu_info *get_thr_cgpu(int thr_id)
  803. {
  804. struct thr_info *thr = get_thread(thr_id);
  805. return thr->cgpu;
  806. }
  807. struct cgpu_info *get_devices(int id)
  808. {
  809. struct cgpu_info *cgpu;
  810. rd_lock(&devices_lock);
  811. cgpu = devices[id];
  812. rd_unlock(&devices_lock);
  813. return cgpu;
  814. }
  815. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  816. static FILE *noncelog_file = NULL;
  817. static
  818. void noncelog(const struct work * const work)
  819. {
  820. const int thr_id = work->thr_id;
  821. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  822. char buf[0x200], hash[65], data[161], midstate[65];
  823. int rv;
  824. size_t ret;
  825. bin2hex(hash, work->hash, 32);
  826. bin2hex(data, work->data, 80);
  827. bin2hex(midstate, work->midstate, 32);
  828. // timestamp,proc,hash,data,midstate
  829. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  830. (unsigned long)time(NULL), proc->proc_repr_ns,
  831. hash, data, midstate);
  832. if (unlikely(rv < 1))
  833. {
  834. applog(LOG_ERR, "noncelog printf error");
  835. return;
  836. }
  837. mutex_lock(&noncelog_lock);
  838. ret = fwrite(buf, rv, 1, noncelog_file);
  839. fflush(noncelog_file);
  840. mutex_unlock(&noncelog_lock);
  841. if (ret != 1)
  842. applog(LOG_ERR, "noncelog fwrite error");
  843. }
  844. static void sharelog(const char*disposition, const struct work*work)
  845. {
  846. char target[(sizeof(work->target) * 2) + 1];
  847. char hash[(sizeof(work->hash) * 2) + 1];
  848. char data[(sizeof(work->data) * 2) + 1];
  849. struct cgpu_info *cgpu;
  850. unsigned long int t;
  851. struct pool *pool;
  852. int thr_id, rv;
  853. char s[1024];
  854. size_t ret;
  855. if (!sharelog_file)
  856. return;
  857. thr_id = work->thr_id;
  858. cgpu = get_thr_cgpu(thr_id);
  859. pool = work->pool;
  860. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  861. bin2hex(target, work->target, sizeof(work->target));
  862. bin2hex(hash, work->hash, sizeof(work->hash));
  863. bin2hex(data, work->data, sizeof(work->data));
  864. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  865. rv = snprintf(s, sizeof(s), "%lu,%s,%s,%s,%s,%u,%s,%s\n", t, disposition, target, pool->rpc_url, cgpu->proc_repr_ns, thr_id, hash, data);
  866. if (rv >= (int)(sizeof(s)))
  867. s[sizeof(s) - 1] = '\0';
  868. else if (rv < 0) {
  869. applog(LOG_ERR, "sharelog printf error");
  870. return;
  871. }
  872. mutex_lock(&sharelog_lock);
  873. ret = fwrite(s, rv, 1, sharelog_file);
  874. fflush(sharelog_file);
  875. mutex_unlock(&sharelog_lock);
  876. if (ret != 1)
  877. applog(LOG_ERR, "sharelog fwrite error");
  878. }
  879. #ifdef HAVE_CURSES
  880. static void switch_logsize(void);
  881. #endif
  882. static
  883. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  884. {
  885. // default always goes first
  886. if (a->is_default)
  887. return -1;
  888. if (b->is_default)
  889. return 1;
  890. return strcmp(a->name, b->name);
  891. }
  892. struct mining_goal_info *get_mining_goal(const char * const name)
  893. {
  894. static unsigned next_goal_id;
  895. struct mining_goal_info *goal;
  896. HASH_FIND_STR(mining_goals, name, goal);
  897. if (!goal)
  898. {
  899. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  900. memset(dummy_block->prevblkhash, 0, 0x20);
  901. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  902. goal = (void*)(&blkchain[1]);
  903. *blkchain = (struct blockchain_info){
  904. .currentblk = dummy_block,
  905. };
  906. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  907. *goal = (struct mining_goal_info){
  908. .id = next_goal_id++,
  909. .name = strdup(name),
  910. .is_default = !strcmp(name, "default"),
  911. .blkchain = blkchain,
  912. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  913. };
  914. HASH_ADD_STR(mining_goals, name, goal);
  915. HASH_SORT(mining_goals, mining_goals_name_cmp);
  916. #ifdef HAVE_CURSES
  917. devcursor = 7 + active_goals;
  918. switch_logsize();
  919. #endif
  920. }
  921. return goal;
  922. }
  923. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  924. /* Adjust all the pools' quota to the greatest common denominator after a pool
  925. * has been added or the quotas changed. */
  926. void adjust_quota_gcd(void)
  927. {
  928. unsigned long gcd, lowest_quota = ~0UL, quota;
  929. struct pool *pool;
  930. int i;
  931. for (i = 0; i < total_pools; i++) {
  932. pool = pools[i];
  933. quota = pool->quota;
  934. if (!quota)
  935. continue;
  936. if (quota < lowest_quota)
  937. lowest_quota = quota;
  938. }
  939. if (likely(lowest_quota < ~0UL)) {
  940. gcd = lowest_quota;
  941. for (i = 0; i < total_pools; i++) {
  942. pool = pools[i];
  943. quota = pool->quota;
  944. if (!quota)
  945. continue;
  946. while (quota % gcd)
  947. gcd--;
  948. }
  949. } else
  950. gcd = 1;
  951. for (i = 0; i < total_pools; i++) {
  952. pool = pools[i];
  953. pool->quota_used *= global_quota_gcd;
  954. pool->quota_used /= gcd;
  955. pool->quota_gcd = pool->quota / gcd;
  956. }
  957. global_quota_gcd = gcd;
  958. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  959. }
  960. /* Return value is ignored if not called from add_pool_details */
  961. struct pool *add_pool(void)
  962. {
  963. struct pool *pool;
  964. pool = calloc(sizeof(struct pool), 1);
  965. if (!pool)
  966. quit(1, "Failed to malloc pool in add_pool");
  967. pool->pool_no = pool->prio = total_pools;
  968. mutex_init(&pool->last_work_lock);
  969. mutex_init(&pool->pool_lock);
  970. mutex_init(&pool->pool_test_lock);
  971. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  972. quit(1, "Failed to pthread_cond_init in add_pool");
  973. cglock_init(&pool->data_lock);
  974. mutex_init(&pool->stratum_lock);
  975. timer_unset(&pool->swork.tv_transparency);
  976. pool->swork.pool = pool;
  977. pool->goal = get_mining_goal("default");
  978. pool->idle = true;
  979. /* Make sure the pool doesn't think we've been idle since time 0 */
  980. pool->tv_idle.tv_sec = ~0UL;
  981. cgtime(&pool->cgminer_stats.start_tv);
  982. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  983. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  984. pool->rpc_proxy = NULL;
  985. pool->quota = 1;
  986. pool->sock = INVSOCK;
  987. pool->lp_socket = CURL_SOCKET_BAD;
  988. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  989. pools[total_pools++] = pool;
  990. if (opt_benchmark)
  991. {
  992. // Immediately remove it
  993. remove_pool(pool);
  994. return pool;
  995. }
  996. adjust_quota_gcd();
  997. if (!currentpool)
  998. currentpool = pool;
  999. enable_pool(pool);
  1000. return pool;
  1001. }
  1002. static
  1003. void pool_set_uri(struct pool * const pool, char * const uri)
  1004. {
  1005. pool->rpc_url = uri;
  1006. #if BLKMAKER_VERSION > 1
  1007. if (uri_get_param_bool(uri, "getcbaddr", false))
  1008. have_at_least_one_getcbaddr = true;
  1009. #endif
  1010. }
  1011. /* Pool variant of test and set */
  1012. static bool pool_tset(struct pool *pool, bool *var)
  1013. {
  1014. bool ret;
  1015. mutex_lock(&pool->pool_lock);
  1016. ret = *var;
  1017. *var = true;
  1018. mutex_unlock(&pool->pool_lock);
  1019. return ret;
  1020. }
  1021. bool pool_tclear(struct pool *pool, bool *var)
  1022. {
  1023. bool ret;
  1024. mutex_lock(&pool->pool_lock);
  1025. ret = *var;
  1026. *var = false;
  1027. mutex_unlock(&pool->pool_lock);
  1028. return ret;
  1029. }
  1030. struct pool *current_pool(void)
  1031. {
  1032. struct pool *pool;
  1033. cg_rlock(&control_lock);
  1034. pool = currentpool;
  1035. cg_runlock(&control_lock);
  1036. return pool;
  1037. }
  1038. static
  1039. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1040. {
  1041. return opt_set_bool(b);
  1042. }
  1043. char *set_int_range(const char *arg, int *i, int min, int max)
  1044. {
  1045. char *err = opt_set_intval(arg, i);
  1046. if (err)
  1047. return err;
  1048. if (*i < min || *i > max)
  1049. return "Value out of range";
  1050. return NULL;
  1051. }
  1052. static char *set_int_0_to_9999(const char *arg, int *i)
  1053. {
  1054. return set_int_range(arg, i, 0, 9999);
  1055. }
  1056. static char *set_int_1_to_65535(const char *arg, int *i)
  1057. {
  1058. return set_int_range(arg, i, 1, 65535);
  1059. }
  1060. static char *set_int_0_to_10(const char *arg, int *i)
  1061. {
  1062. return set_int_range(arg, i, 0, 10);
  1063. }
  1064. static char *set_int_1_to_10(const char *arg, int *i)
  1065. {
  1066. return set_int_range(arg, i, 1, 10);
  1067. }
  1068. char *set_strdup(const char *arg, char **p)
  1069. {
  1070. *p = strdup((char *)arg);
  1071. return NULL;
  1072. }
  1073. #if BLKMAKER_VERSION > 1
  1074. static
  1075. char *set_b58addr(const char * const arg, bytes_t * const b)
  1076. {
  1077. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1078. if (!scriptsz)
  1079. return "Invalid address";
  1080. char *script = malloc(scriptsz);
  1081. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1082. free(script);
  1083. return "Failed to convert address to script";
  1084. }
  1085. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1086. return NULL;
  1087. }
  1088. #endif
  1089. static
  1090. char *set_quit_summary(const char * const arg)
  1091. {
  1092. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1093. opt_quit_summary = BQS_NONE;
  1094. else
  1095. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1096. opt_quit_summary = BQS_DEVS;
  1097. else
  1098. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1099. opt_quit_summary = BQS_PROCS;
  1100. else
  1101. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1102. opt_quit_summary = BQS_DETAILED;
  1103. else
  1104. return "Quit summary must be one of none/devs/procs/detailed";
  1105. return NULL;
  1106. }
  1107. static void pdiff_target_leadzero(void *, double);
  1108. char *set_request_diff(const char *arg, float *p)
  1109. {
  1110. unsigned char target[32];
  1111. char *e = opt_set_floatval(arg, p);
  1112. if (e)
  1113. return e;
  1114. request_bdiff = (double)*p * 0.9999847412109375;
  1115. pdiff_target_leadzero(target, *p);
  1116. request_target_str = malloc(65);
  1117. bin2hex(request_target_str, target, 32);
  1118. return NULL;
  1119. }
  1120. #ifdef NEED_BFG_LOWL_VCOM
  1121. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1122. #ifdef WIN32
  1123. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1124. {
  1125. char dev[PATH_MAX];
  1126. char *devp = dev;
  1127. size_t bufLen = 0x100;
  1128. tryagain: ;
  1129. char buf[bufLen];
  1130. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1131. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1132. bufLen *= 2;
  1133. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1134. goto tryagain;
  1135. }
  1136. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1137. }
  1138. size_t tLen;
  1139. memcpy(devp, "\\\\.\\", 4);
  1140. devp = &devp[4];
  1141. for (char *t = buf; *t; t += tLen) {
  1142. tLen = strlen(t) + 1;
  1143. if (strncmp("COM", t, 3))
  1144. continue;
  1145. memcpy(devp, t, tLen);
  1146. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1147. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1148. }
  1149. }
  1150. #else
  1151. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1152. {
  1153. char dev[PATH_MAX];
  1154. char *devp = dev;
  1155. DIR *D;
  1156. struct dirent *de;
  1157. const char devdir[] = "/dev";
  1158. const size_t devdirlen = sizeof(devdir) - 1;
  1159. char *devpath = devp;
  1160. char *devfile = devpath + devdirlen + 1;
  1161. D = opendir(devdir);
  1162. if (!D)
  1163. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1164. memcpy(devpath, devdir, devdirlen);
  1165. devpath[devdirlen] = '/';
  1166. while ( (de = readdir(D)) ) {
  1167. if (!strncmp(de->d_name, "cu.", 3)
  1168. //don't probe Bluetooth devices - causes bus errors and segfaults
  1169. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1170. goto trydev;
  1171. if (strncmp(de->d_name, "tty", 3))
  1172. continue;
  1173. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1174. continue;
  1175. trydev:
  1176. strcpy(devfile, de->d_name);
  1177. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1178. }
  1179. closedir(D);
  1180. }
  1181. #endif
  1182. #endif
  1183. static char *add_serial(const char *arg)
  1184. {
  1185. string_elist_add(arg, &scan_devices);
  1186. return NULL;
  1187. }
  1188. static
  1189. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1190. {
  1191. string_elist_add(arg, elist);
  1192. return NULL;
  1193. }
  1194. bool get_intrange(const char *arg, int *val1, int *val2)
  1195. {
  1196. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1197. char *p, *p2;
  1198. *val1 = strtol(arg, &p, 0);
  1199. if (arg == p)
  1200. // Zero-length ending number, invalid
  1201. return false;
  1202. while (true)
  1203. {
  1204. if (!p[0])
  1205. {
  1206. *val2 = *val1;
  1207. return true;
  1208. }
  1209. if (p[0] == '-')
  1210. break;
  1211. if (!isspace(p[0]))
  1212. // Garbage, invalid
  1213. return false;
  1214. ++p;
  1215. }
  1216. p2 = &p[1];
  1217. *val2 = strtol(p2, &p, 0);
  1218. if (p2 == p)
  1219. // Zero-length ending number, invalid
  1220. return false;
  1221. while (true)
  1222. {
  1223. if (!p[0])
  1224. return true;
  1225. if (!isspace(p[0]))
  1226. // Garbage, invalid
  1227. return false;
  1228. ++p;
  1229. }
  1230. }
  1231. static
  1232. void _test_intrange(const char *s, const int v[2])
  1233. {
  1234. int a[2];
  1235. if (!get_intrange(s, &a[0], &a[1]))
  1236. {
  1237. ++unittest_failures;
  1238. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1239. }
  1240. for (int i = 0; i < 2; ++i)
  1241. if (unlikely(a[i] != v[i]))
  1242. {
  1243. ++unittest_failures;
  1244. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1245. }
  1246. }
  1247. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1248. static
  1249. void _test_intrange_fail(const char *s)
  1250. {
  1251. int a[2];
  1252. if (get_intrange(s, &a[0], &a[1]))
  1253. {
  1254. ++unittest_failures;
  1255. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1256. }
  1257. }
  1258. static
  1259. void test_intrange()
  1260. {
  1261. _test_intrange("-1--2", -1, -2);
  1262. _test_intrange("-1-2", -1, 2);
  1263. _test_intrange("1--2", 1, -2);
  1264. _test_intrange("1-2", 1, 2);
  1265. _test_intrange("111-222", 111, 222);
  1266. _test_intrange(" 11 - 22 ", 11, 22);
  1267. _test_intrange("+11-+22", 11, 22);
  1268. _test_intrange("-1", -1, -1);
  1269. _test_intrange_fail("all");
  1270. _test_intrange_fail("1-");
  1271. _test_intrange_fail("");
  1272. _test_intrange_fail("1-54x");
  1273. }
  1274. static char *set_devices(char *arg)
  1275. {
  1276. if (*arg) {
  1277. if (*arg == '?') {
  1278. opt_display_devs = true;
  1279. return NULL;
  1280. }
  1281. } else
  1282. return "Invalid device parameters";
  1283. string_elist_add(arg, &opt_devices_enabled_list);
  1284. return NULL;
  1285. }
  1286. static char *set_balance(enum pool_strategy *strategy)
  1287. {
  1288. *strategy = POOL_BALANCE;
  1289. return NULL;
  1290. }
  1291. static char *set_loadbalance(enum pool_strategy *strategy)
  1292. {
  1293. *strategy = POOL_LOADBALANCE;
  1294. return NULL;
  1295. }
  1296. static char *set_rotate(const char *arg, int *i)
  1297. {
  1298. pool_strategy = POOL_ROTATE;
  1299. return set_int_range(arg, i, 0, 9999);
  1300. }
  1301. static char *set_rr(enum pool_strategy *strategy)
  1302. {
  1303. *strategy = POOL_ROUNDROBIN;
  1304. return NULL;
  1305. }
  1306. static
  1307. char *set_benchmark_intense()
  1308. {
  1309. opt_benchmark = true;
  1310. opt_benchmark_intense = true;
  1311. return NULL;
  1312. }
  1313. /* Detect that url is for a stratum protocol either via the presence of
  1314. * stratum+tcp or by detecting a stratum server response */
  1315. bool detect_stratum(struct pool *pool, char *url)
  1316. {
  1317. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1318. return false;
  1319. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1320. pool_set_uri(pool, strdup(url));
  1321. pool->has_stratum = true;
  1322. pool->stratum_url = pool->sockaddr_url;
  1323. return true;
  1324. }
  1325. return false;
  1326. }
  1327. static struct pool *add_url(void)
  1328. {
  1329. total_urls++;
  1330. if (total_urls > total_pools)
  1331. add_pool();
  1332. return pools[total_urls - 1];
  1333. }
  1334. static void setup_url(struct pool *pool, char *arg)
  1335. {
  1336. if (detect_stratum(pool, arg))
  1337. return;
  1338. opt_set_charp(arg, &pool->rpc_url);
  1339. if (strncmp(arg, "http://", 7) &&
  1340. strncmp(arg, "https://", 8)) {
  1341. const size_t L = strlen(arg);
  1342. char *httpinput;
  1343. httpinput = malloc(8 + L);
  1344. if (!httpinput)
  1345. quit(1, "Failed to malloc httpinput");
  1346. sprintf(httpinput, "http://%s", arg);
  1347. pool_set_uri(pool, httpinput);
  1348. }
  1349. }
  1350. static char *set_url(char *arg)
  1351. {
  1352. struct pool *pool = add_url();
  1353. setup_url(pool, arg);
  1354. return NULL;
  1355. }
  1356. static char *set_quota(char *arg)
  1357. {
  1358. char *semicolon = strchr(arg, ';'), *url;
  1359. int len, qlen, quota;
  1360. struct pool *pool;
  1361. if (!semicolon)
  1362. return "No semicolon separated quota;URL pair found";
  1363. len = strlen(arg);
  1364. *semicolon = '\0';
  1365. qlen = strlen(arg);
  1366. if (!qlen)
  1367. return "No parameter for quota found";
  1368. len -= qlen + 1;
  1369. if (len < 1)
  1370. return "No parameter for URL found";
  1371. quota = atoi(arg);
  1372. if (quota < 0)
  1373. return "Invalid negative parameter for quota set";
  1374. url = arg + qlen + 1;
  1375. pool = add_url();
  1376. setup_url(pool, url);
  1377. pool->quota = quota;
  1378. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1379. adjust_quota_gcd();
  1380. return NULL;
  1381. }
  1382. static char *set_user(const char *arg)
  1383. {
  1384. struct pool *pool;
  1385. total_users++;
  1386. if (total_users > total_pools)
  1387. add_pool();
  1388. pool = pools[total_users - 1];
  1389. opt_set_charp(arg, &pool->rpc_user);
  1390. return NULL;
  1391. }
  1392. static char *set_pass(const char *arg)
  1393. {
  1394. struct pool *pool;
  1395. total_passes++;
  1396. if (total_passes > total_pools)
  1397. add_pool();
  1398. pool = pools[total_passes - 1];
  1399. opt_set_charp(arg, &pool->rpc_pass);
  1400. return NULL;
  1401. }
  1402. static char *set_userpass(const char *arg)
  1403. {
  1404. struct pool *pool;
  1405. char *updup;
  1406. if (total_users != total_passes)
  1407. return "User + pass options must be balanced before userpass";
  1408. ++total_users;
  1409. ++total_passes;
  1410. if (total_users > total_pools)
  1411. add_pool();
  1412. pool = pools[total_users - 1];
  1413. updup = strdup(arg);
  1414. opt_set_charp(arg, &pool->rpc_userpass);
  1415. pool->rpc_user = updup;
  1416. pool->rpc_pass = strchr(updup, ':');
  1417. if (pool->rpc_pass)
  1418. pool->rpc_pass++[0] = '\0';
  1419. else
  1420. pool->rpc_pass = &updup[strlen(updup)];
  1421. return NULL;
  1422. }
  1423. static char *set_cbcaddr(char *arg)
  1424. {
  1425. struct pool *pool;
  1426. char *p, *addr;
  1427. bytes_t target_script = BYTES_INIT;
  1428. if (!total_pools)
  1429. return "Define pool first, then the --coinbase-check-addr list";
  1430. pool = pools[total_pools - 1];
  1431. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1432. * need support it later, but now leave the code just so.
  1433. *
  1434. * Regarding details of address prefix 'x', check the below URL:
  1435. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1436. */
  1437. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1438. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1439. {
  1440. struct bytes_hashtbl *ah;
  1441. if (set_b58addr(addr, &target_script))
  1442. /* No bother to free memory since we are going to exit anyway */
  1443. return "Invalid address in --coinbase-check-address list";
  1444. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1445. if (!ah)
  1446. {
  1447. /* Note: for the below allocated memory we have good way to release its memory
  1448. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1449. * get called.
  1450. *
  1451. * We just hope the remove_pool() would not be called many many times during
  1452. * the whole running life of this program.
  1453. */
  1454. ah = malloc(sizeof(*ah));
  1455. bytes_init(&ah->b);
  1456. bytes_assimilate(&ah->b, &target_script);
  1457. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1458. }
  1459. }
  1460. bytes_free(&target_script);
  1461. return NULL;
  1462. }
  1463. static char *set_cbctotal(const char *arg)
  1464. {
  1465. struct pool *pool;
  1466. if (!total_pools)
  1467. return "Define pool first, then the --coinbase-check-total argument";
  1468. pool = pools[total_pools - 1];
  1469. pool->cb_param.total = atoll(arg);
  1470. if (pool->cb_param.total < 0)
  1471. return "The total payout amount in coinbase should be greater than 0";
  1472. return NULL;
  1473. }
  1474. static char *set_cbcperc(const char *arg)
  1475. {
  1476. struct pool *pool;
  1477. if (!total_pools)
  1478. return "Define pool first, then the --coinbase-check-percent argument";
  1479. pool = pools[total_pools - 1];
  1480. if (!pool->cb_param.scripts)
  1481. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1482. pool->cb_param.perc = atof(arg) / 100;
  1483. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1484. return "The percentage should be between 0 and 100";
  1485. return NULL;
  1486. }
  1487. static
  1488. char *set_pool_goal(const char * const arg)
  1489. {
  1490. struct pool *pool;
  1491. if (!total_pools)
  1492. return "Usage of --pool-goal before pools are defined does not make sense";
  1493. pool = pools[total_pools - 1];
  1494. pool->goal = get_mining_goal(arg);
  1495. return NULL;
  1496. }
  1497. static char *set_pool_priority(const char *arg)
  1498. {
  1499. struct pool *pool;
  1500. if (!total_pools)
  1501. return "Usage of --pool-priority before pools are defined does not make sense";
  1502. pool = pools[total_pools - 1];
  1503. opt_set_intval(arg, &pool->prio);
  1504. return NULL;
  1505. }
  1506. static char *set_pool_proxy(const char *arg)
  1507. {
  1508. struct pool *pool;
  1509. if (!total_pools)
  1510. return "Usage of --pool-proxy before pools are defined does not make sense";
  1511. if (!our_curl_supports_proxy_uris())
  1512. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1513. pool = pools[total_pools - 1];
  1514. opt_set_charp(arg, &pool->rpc_proxy);
  1515. return NULL;
  1516. }
  1517. static char *set_pool_force_rollntime(const char *arg)
  1518. {
  1519. struct pool *pool;
  1520. if (!total_pools)
  1521. return "Usage of --force-rollntime before pools are defined does not make sense";
  1522. pool = pools[total_pools - 1];
  1523. opt_set_intval(arg, &pool->force_rollntime);
  1524. return NULL;
  1525. }
  1526. static char *enable_debug(bool *flag)
  1527. {
  1528. *flag = true;
  1529. opt_debug_console = true;
  1530. /* Turn on verbose output, too. */
  1531. opt_log_output = true;
  1532. return NULL;
  1533. }
  1534. static char *set_schedtime(const char *arg, struct schedtime *st)
  1535. {
  1536. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1537. {
  1538. if (strcasecmp(arg, "now"))
  1539. return "Invalid time set, should be HH:MM";
  1540. } else
  1541. schedstop.tm.tm_sec = 0;
  1542. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1543. return "Invalid time set.";
  1544. st->enable = true;
  1545. return NULL;
  1546. }
  1547. static
  1548. char *set_log_file(char *arg)
  1549. {
  1550. char *r = "";
  1551. long int i = strtol(arg, &r, 10);
  1552. int fd, stderr_fd = fileno(stderr);
  1553. if ((!*r) && i >= 0 && i <= INT_MAX)
  1554. fd = i;
  1555. else
  1556. if (!strcmp(arg, "-"))
  1557. {
  1558. fd = fileno(stdout);
  1559. if (unlikely(fd == -1))
  1560. return "Standard output missing for log-file";
  1561. }
  1562. else
  1563. {
  1564. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1565. if (unlikely(fd == -1))
  1566. return "Failed to open log-file";
  1567. }
  1568. close(stderr_fd);
  1569. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1570. return "Failed to dup2 for log-file";
  1571. close(fd);
  1572. return NULL;
  1573. }
  1574. static
  1575. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1576. {
  1577. char *r = "";
  1578. long int i = strtol(arg, &r, 10);
  1579. static char *err = NULL;
  1580. const size_t errbufsz = 0x100;
  1581. free(err);
  1582. err = NULL;
  1583. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1584. *F = fdopen((int)i, mode);
  1585. if (!*F)
  1586. {
  1587. err = malloc(errbufsz);
  1588. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1589. (int)i, purpose);
  1590. return err;
  1591. }
  1592. } else if (!strcmp(arg, "-")) {
  1593. *F = (mode[0] == 'a') ? stdout : stdin;
  1594. if (!*F)
  1595. {
  1596. err = malloc(errbufsz);
  1597. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1598. (mode[0] == 'a') ? "out" : "in", purpose);
  1599. return err;
  1600. }
  1601. } else {
  1602. *F = fopen(arg, mode);
  1603. if (!*F)
  1604. {
  1605. err = malloc(errbufsz);
  1606. snprintf(err, errbufsz, "Failed to open %s for %s",
  1607. arg, purpose);
  1608. return err;
  1609. }
  1610. }
  1611. return NULL;
  1612. }
  1613. static char *set_noncelog(char *arg)
  1614. {
  1615. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1616. }
  1617. static char *set_sharelog(char *arg)
  1618. {
  1619. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1620. }
  1621. static
  1622. void _add_set_device_option(const char * const func, const char * const buf)
  1623. {
  1624. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1625. string_elist_add(buf, &opt_set_device_list);
  1626. }
  1627. #define add_set_device_option(...) do{ \
  1628. char _tmp1718[0x100]; \
  1629. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1630. _add_set_device_option(__func__, _tmp1718); \
  1631. }while(0)
  1632. char *set_temp_cutoff(char *arg)
  1633. {
  1634. if (strchr(arg, ','))
  1635. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1636. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1637. add_set_device_option("all:temp-cutoff=%s", arg);
  1638. return NULL;
  1639. }
  1640. char *set_temp_target(char *arg)
  1641. {
  1642. if (strchr(arg, ','))
  1643. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1644. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1645. add_set_device_option("all:temp-target=%s", arg);
  1646. return NULL;
  1647. }
  1648. #ifdef HAVE_OPENCL
  1649. static
  1650. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1651. {
  1652. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1653. add_set_device_option("OCL:binary=no");
  1654. return NULL;
  1655. }
  1656. #endif
  1657. static
  1658. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1659. {
  1660. opt_disable_client_reconnect = true;
  1661. want_stratum = false;
  1662. return NULL;
  1663. }
  1664. static char *set_api_allow(const char *arg)
  1665. {
  1666. opt_set_charp(arg, &opt_api_allow);
  1667. return NULL;
  1668. }
  1669. static char *set_api_groups(const char *arg)
  1670. {
  1671. opt_set_charp(arg, &opt_api_groups);
  1672. return NULL;
  1673. }
  1674. static char *set_api_description(const char *arg)
  1675. {
  1676. opt_set_charp(arg, &opt_api_description);
  1677. return NULL;
  1678. }
  1679. static char *set_api_mcast_des(const char *arg)
  1680. {
  1681. opt_set_charp(arg, &opt_api_mcast_des);
  1682. return NULL;
  1683. }
  1684. #ifdef USE_ICARUS
  1685. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1686. static char *set_icarus_options(const char *arg)
  1687. {
  1688. if (strchr(arg, ','))
  1689. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1690. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1691. char *opts = strdup(arg), *argdup;
  1692. argdup = opts;
  1693. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1694. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1695. char *saveptr, *opt;
  1696. for (int i = 0; i < 4; ++i, ++sdf)
  1697. {
  1698. opt = strtok_r(opts, ":", &saveptr);
  1699. opts = NULL;
  1700. if (!opt)
  1701. break;
  1702. if (!opt[0])
  1703. continue;
  1704. for (int j = 0; j < 4; ++j)
  1705. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1706. }
  1707. free(argdup);
  1708. return NULL;
  1709. }
  1710. static char *set_icarus_timing(const char *arg)
  1711. {
  1712. if (strchr(arg, ','))
  1713. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1714. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1715. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1716. for (int j = 0; j < 4; ++j)
  1717. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1718. return NULL;
  1719. }
  1720. #endif
  1721. #ifdef USE_AVALON
  1722. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1723. static char *set_avalon_options(const char *arg)
  1724. {
  1725. if (strchr(arg, ','))
  1726. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1727. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1728. char *opts = strdup(arg), *argdup;
  1729. argdup = opts;
  1730. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1731. char *saveptr, *opt;
  1732. for (int i = 0; i < 5; ++i, ++sdf)
  1733. {
  1734. opt = strtok_r(opts, ":", &saveptr);
  1735. opts = NULL;
  1736. if (!opt)
  1737. break;
  1738. if (!opt[0])
  1739. continue;
  1740. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1741. }
  1742. free(argdup);
  1743. return NULL;
  1744. }
  1745. #endif
  1746. #ifdef USE_KLONDIKE
  1747. static char *set_klondike_options(const char *arg)
  1748. {
  1749. int hashclock;
  1750. double temptarget;
  1751. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1752. {
  1753. default:
  1754. return "Unrecognised --klondike-options";
  1755. case 2:
  1756. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1757. // fallthru
  1758. case 1:
  1759. add_set_device_option("klondike:clock=%d", hashclock);
  1760. }
  1761. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1762. return NULL;
  1763. }
  1764. #endif
  1765. __maybe_unused
  1766. static char *set_null(const char __maybe_unused *arg)
  1767. {
  1768. return NULL;
  1769. }
  1770. /* These options are available from config file or commandline */
  1771. static struct opt_table opt_config_table[] = {
  1772. #ifdef WANT_CPUMINE
  1773. OPT_WITH_ARG("--algo",
  1774. set_algo, show_algo, &opt_algo,
  1775. "Specify sha256 implementation for CPU mining:\n"
  1776. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1777. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1778. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1779. #ifdef WANT_SSE2_4WAY
  1780. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1781. #endif
  1782. #ifdef WANT_VIA_PADLOCK
  1783. "\n\tvia\t\tVIA padlock implementation"
  1784. #endif
  1785. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1786. #ifdef WANT_CRYPTOPP_ASM32
  1787. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1788. #endif
  1789. #ifdef WANT_X8632_SSE2
  1790. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1791. #endif
  1792. #ifdef WANT_X8664_SSE2
  1793. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1794. #endif
  1795. #ifdef WANT_X8664_SSE4
  1796. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1797. #endif
  1798. #ifdef WANT_ALTIVEC_4WAY
  1799. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1800. #endif
  1801. ),
  1802. OPT_WITH_ARG("-a",
  1803. set_algo, show_algo, &opt_algo,
  1804. opt_hidden),
  1805. #endif
  1806. OPT_WITH_ARG("--api-allow",
  1807. set_api_allow, NULL, NULL,
  1808. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1809. OPT_WITH_ARG("--api-description",
  1810. set_api_description, NULL, NULL,
  1811. "Description placed in the API status header, default: BFGMiner version"),
  1812. OPT_WITH_ARG("--api-groups",
  1813. set_api_groups, NULL, NULL,
  1814. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1815. OPT_WITHOUT_ARG("--api-listen",
  1816. opt_set_bool, &opt_api_listen,
  1817. "Enable API, default: disabled"),
  1818. OPT_WITHOUT_ARG("--api-mcast",
  1819. opt_set_bool, &opt_api_mcast,
  1820. "Enable API Multicast listener, default: disabled"),
  1821. OPT_WITH_ARG("--api-mcast-addr",
  1822. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1823. "API Multicast listen address"),
  1824. OPT_WITH_ARG("--api-mcast-code",
  1825. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1826. "Code expected in the API Multicast message, don't use '-'"),
  1827. OPT_WITH_ARG("--api-mcast-des",
  1828. set_api_mcast_des, NULL, NULL,
  1829. "Description appended to the API Multicast reply, default: ''"),
  1830. OPT_WITH_ARG("--api-mcast-port",
  1831. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1832. "API Multicast listen port"),
  1833. OPT_WITHOUT_ARG("--api-network",
  1834. opt_set_bool, &opt_api_network,
  1835. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1836. OPT_WITH_ARG("--api-port",
  1837. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1838. "Port number of miner API"),
  1839. #ifdef HAVE_ADL
  1840. OPT_WITHOUT_ARG("--auto-fan",
  1841. opt_set_bool, &opt_autofan,
  1842. opt_hidden),
  1843. OPT_WITHOUT_ARG("--auto-gpu",
  1844. opt_set_bool, &opt_autoengine,
  1845. opt_hidden),
  1846. #endif
  1847. OPT_WITHOUT_ARG("--balance",
  1848. set_balance, &pool_strategy,
  1849. "Change multipool strategy from failover to even share balance"),
  1850. OPT_WITHOUT_ARG("--benchmark",
  1851. opt_set_bool, &opt_benchmark,
  1852. "Run BFGMiner in benchmark mode - produces no shares"),
  1853. OPT_WITHOUT_ARG("--benchmark-intense",
  1854. set_benchmark_intense, &opt_benchmark_intense,
  1855. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  1856. #if defined(USE_BITFORCE)
  1857. OPT_WITHOUT_ARG("--bfl-range",
  1858. opt_set_bool, &opt_bfl_noncerange,
  1859. "Use nonce range on bitforce devices if supported"),
  1860. #endif
  1861. #ifdef HAVE_CHROOT
  1862. OPT_WITH_ARG("--chroot-dir",
  1863. opt_set_charp, NULL, &chroot_dir,
  1864. "Chroot to a directory right after startup"),
  1865. #endif
  1866. OPT_WITH_ARG("--cmd-idle",
  1867. opt_set_charp, NULL, &cmd_idle,
  1868. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1869. OPT_WITH_ARG("--cmd-sick",
  1870. opt_set_charp, NULL, &cmd_sick,
  1871. "Execute a command when a device is declared sick"),
  1872. OPT_WITH_ARG("--cmd-dead",
  1873. opt_set_charp, NULL, &cmd_dead,
  1874. "Execute a command when a device is declared dead"),
  1875. #if BLKMAKER_VERSION > 1
  1876. OPT_WITH_ARG("--coinbase-addr",
  1877. set_b58addr, NULL, &opt_coinbase_script,
  1878. "Set coinbase payout address for solo mining"),
  1879. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1880. set_b58addr, NULL, &opt_coinbase_script,
  1881. opt_hidden),
  1882. #endif
  1883. #if BLKMAKER_VERSION > 0
  1884. OPT_WITH_ARG("--coinbase-sig",
  1885. set_strdup, NULL, &opt_coinbase_sig,
  1886. "Set coinbase signature when possible"),
  1887. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1888. set_strdup, NULL, &opt_coinbase_sig,
  1889. opt_hidden),
  1890. #endif
  1891. #ifdef HAVE_CURSES
  1892. OPT_WITHOUT_ARG("--compact",
  1893. opt_set_bool, &opt_compact,
  1894. "Use compact display without per device statistics"),
  1895. #endif
  1896. #ifdef WANT_CPUMINE
  1897. OPT_WITH_ARG("--cpu-threads",
  1898. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1899. "Number of miner CPU threads"),
  1900. OPT_WITH_ARG("-t",
  1901. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1902. opt_hidden),
  1903. #endif
  1904. OPT_WITHOUT_ARG("--debug|-D",
  1905. enable_debug, &opt_debug,
  1906. "Enable debug output"),
  1907. OPT_WITHOUT_ARG("--debuglog",
  1908. opt_set_bool, &opt_debug,
  1909. "Enable debug logging"),
  1910. OPT_WITHOUT_ARG("--device-protocol-dump",
  1911. opt_set_bool, &opt_dev_protocol,
  1912. "Verbose dump of device protocol-level activities"),
  1913. OPT_WITH_ARG("--device|-d",
  1914. set_devices, NULL, NULL,
  1915. "Enable only devices matching pattern (default: all)"),
  1916. OPT_WITHOUT_ARG("--disable-rejecting",
  1917. opt_set_bool, &opt_disable_pool,
  1918. "Automatically disable pools that continually reject shares"),
  1919. #ifdef USE_LIBMICROHTTPD
  1920. OPT_WITH_ARG("--http-port",
  1921. opt_set_intval, opt_show_intval, &httpsrv_port,
  1922. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1923. #endif
  1924. OPT_WITH_ARG("--expiry",
  1925. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1926. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1927. OPT_WITH_ARG("-E",
  1928. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1929. opt_hidden),
  1930. OPT_WITH_ARG("--expiry-lp",
  1931. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1932. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1933. OPT_WITHOUT_ARG("--failover-only",
  1934. opt_set_bool, &opt_fail_only,
  1935. "Don't leak work to backup pools when primary pool is lagging"),
  1936. OPT_WITH_ARG("--failover-switch-delay",
  1937. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  1938. "Delay in seconds before switching back to a failed pool"),
  1939. #ifdef USE_FPGA
  1940. OPT_WITHOUT_ARG("--force-dev-init",
  1941. opt_set_bool, &opt_force_dev_init,
  1942. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1943. #endif
  1944. #ifdef HAVE_OPENCL
  1945. OPT_WITH_ARG("--gpu-dyninterval",
  1946. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1947. opt_hidden),
  1948. OPT_WITH_ARG("--gpu-platform",
  1949. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1950. "Select OpenCL platform ID to use for GPU mining"),
  1951. OPT_WITH_ARG("--gpu-threads|-g",
  1952. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1953. opt_hidden),
  1954. #ifdef HAVE_ADL
  1955. OPT_WITH_ARG("--gpu-engine",
  1956. set_gpu_engine, NULL, NULL,
  1957. opt_hidden),
  1958. OPT_WITH_ARG("--gpu-fan",
  1959. set_gpu_fan, NULL, NULL,
  1960. opt_hidden),
  1961. OPT_WITH_ARG("--gpu-map",
  1962. set_gpu_map, NULL, NULL,
  1963. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1964. OPT_WITH_ARG("--gpu-memclock",
  1965. set_gpu_memclock, NULL, NULL,
  1966. opt_hidden),
  1967. OPT_WITH_ARG("--gpu-memdiff",
  1968. set_gpu_memdiff, NULL, NULL,
  1969. opt_hidden),
  1970. OPT_WITH_ARG("--gpu-powertune",
  1971. set_gpu_powertune, NULL, NULL,
  1972. opt_hidden),
  1973. OPT_WITHOUT_ARG("--gpu-reorder",
  1974. opt_set_bool, &opt_reorder,
  1975. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1976. OPT_WITH_ARG("--gpu-vddc",
  1977. set_gpu_vddc, NULL, NULL,
  1978. opt_hidden),
  1979. #endif
  1980. #ifdef USE_SCRYPT
  1981. OPT_WITH_ARG("--lookup-gap",
  1982. set_lookup_gap, NULL, NULL,
  1983. opt_hidden),
  1984. #endif
  1985. OPT_WITH_ARG("--intensity|-I",
  1986. set_intensity, NULL, NULL,
  1987. opt_hidden),
  1988. #endif
  1989. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1990. OPT_WITH_ARG("--kernel-path",
  1991. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1992. "Specify a path to where bitstream and kernel files are"),
  1993. OPT_WITH_ARG("-K",
  1994. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1995. opt_hidden),
  1996. #endif
  1997. #ifdef HAVE_OPENCL
  1998. OPT_WITH_ARG("--kernel|-k",
  1999. set_kernel, NULL, NULL,
  2000. opt_hidden),
  2001. #endif
  2002. #ifdef USE_ICARUS
  2003. OPT_WITH_ARG("--icarus-options",
  2004. set_icarus_options, NULL, NULL,
  2005. opt_hidden),
  2006. OPT_WITH_ARG("--icarus-timing",
  2007. set_icarus_timing, NULL, NULL,
  2008. opt_hidden),
  2009. #endif
  2010. #ifdef USE_AVALON
  2011. OPT_WITH_ARG("--avalon-options",
  2012. set_avalon_options, NULL, NULL,
  2013. opt_hidden),
  2014. #endif
  2015. #ifdef USE_KLONDIKE
  2016. OPT_WITH_ARG("--klondike-options",
  2017. set_klondike_options, NULL, NULL,
  2018. "Set klondike options clock:temptarget"),
  2019. #endif
  2020. OPT_WITHOUT_ARG("--load-balance",
  2021. set_loadbalance, &pool_strategy,
  2022. "Change multipool strategy from failover to quota based balance"),
  2023. OPT_WITH_ARG("--log|-l",
  2024. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2025. "Interval in seconds between log output"),
  2026. OPT_WITH_ARG("--log-file|-L",
  2027. set_log_file, NULL, NULL,
  2028. "Append log file for output messages"),
  2029. OPT_WITH_ARG("--logfile",
  2030. set_log_file, NULL, NULL,
  2031. opt_hidden),
  2032. OPT_WITHOUT_ARG("--log-microseconds",
  2033. opt_set_bool, &opt_log_microseconds,
  2034. "Include microseconds in log output"),
  2035. #if defined(unix) || defined(__APPLE__)
  2036. OPT_WITH_ARG("--monitor|-m",
  2037. opt_set_charp, NULL, &opt_stderr_cmd,
  2038. "Use custom pipe cmd for output messages"),
  2039. #endif // defined(unix)
  2040. OPT_WITHOUT_ARG("--net-delay",
  2041. opt_set_bool, &opt_delaynet,
  2042. "Impose small delays in networking to avoid overloading slow routers"),
  2043. OPT_WITHOUT_ARG("--no-adl",
  2044. opt_set_bool, &opt_noadl,
  2045. #ifdef HAVE_ADL
  2046. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2047. #else
  2048. opt_hidden
  2049. #endif
  2050. ),
  2051. OPT_WITHOUT_ARG("--no-gbt",
  2052. opt_set_invbool, &want_gbt,
  2053. "Disable getblocktemplate support"),
  2054. OPT_WITHOUT_ARG("--no-getwork",
  2055. opt_set_invbool, &want_getwork,
  2056. "Disable getwork support"),
  2057. OPT_WITHOUT_ARG("--no-hotplug",
  2058. #ifdef HAVE_BFG_HOTPLUG
  2059. opt_set_invbool, &opt_hotplug,
  2060. "Disable hotplug detection"
  2061. #else
  2062. set_null, &opt_hotplug,
  2063. opt_hidden
  2064. #endif
  2065. ),
  2066. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2067. #if BLKMAKER_VERSION > 1
  2068. opt_set_invbool, &opt_load_bitcoin_conf,
  2069. "Disable adding pools for local bitcoin RPC servers"),
  2070. #else
  2071. set_null, NULL, opt_hidden),
  2072. #endif
  2073. OPT_WITHOUT_ARG("--no-longpoll",
  2074. opt_set_invbool, &want_longpoll,
  2075. "Disable X-Long-Polling support"),
  2076. OPT_WITHOUT_ARG("--no-pool-disable",
  2077. opt_set_invbool, &opt_disable_pool,
  2078. opt_hidden),
  2079. OPT_WITHOUT_ARG("--no-client-reconnect",
  2080. opt_set_invbool, &opt_disable_client_reconnect,
  2081. opt_hidden),
  2082. OPT_WITHOUT_ARG("--no-pool-redirect",
  2083. disable_pool_redirect, NULL,
  2084. "Ignore pool requests to redirect to another server"),
  2085. OPT_WITHOUT_ARG("--no-restart",
  2086. opt_set_invbool, &opt_restart,
  2087. "Do not attempt to restart devices that hang"
  2088. ),
  2089. OPT_WITHOUT_ARG("--no-show-processors",
  2090. opt_set_invbool, &opt_show_procs,
  2091. opt_hidden),
  2092. OPT_WITHOUT_ARG("--no-show-procs",
  2093. opt_set_invbool, &opt_show_procs,
  2094. opt_hidden),
  2095. OPT_WITHOUT_ARG("--no-stratum",
  2096. opt_set_invbool, &want_stratum,
  2097. "Disable Stratum detection"),
  2098. OPT_WITHOUT_ARG("--no-submit-stale",
  2099. opt_set_invbool, &opt_submit_stale,
  2100. "Don't submit shares if they are detected as stale"),
  2101. #ifdef HAVE_OPENCL
  2102. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2103. set_no_opencl_binaries, NULL,
  2104. opt_hidden),
  2105. #endif
  2106. OPT_WITHOUT_ARG("--no-unicode",
  2107. #ifdef USE_UNICODE
  2108. opt_set_invbool, &use_unicode,
  2109. "Don't use Unicode characters in TUI"
  2110. #else
  2111. set_null, &use_unicode,
  2112. opt_hidden
  2113. #endif
  2114. ),
  2115. OPT_WITH_ARG("--noncelog",
  2116. set_noncelog, NULL, NULL,
  2117. "Create log of all nonces found"),
  2118. OPT_WITH_ARG("--pass|-p",
  2119. set_pass, NULL, NULL,
  2120. "Password for bitcoin JSON-RPC server"),
  2121. OPT_WITHOUT_ARG("--per-device-stats",
  2122. opt_set_bool, &want_per_device_stats,
  2123. "Force verbose mode and output per-device statistics"),
  2124. OPT_WITH_ARG("--userpass|-O",
  2125. set_userpass, NULL, NULL,
  2126. "Username:Password pair for bitcoin JSON-RPC server"),
  2127. OPT_WITH_ARG("--pool-goal",
  2128. set_pool_goal, NULL, NULL,
  2129. "Named goal for the previous-defined pool"),
  2130. OPT_WITH_ARG("--pool-priority",
  2131. set_pool_priority, NULL, NULL,
  2132. "Priority for just the previous-defined pool"),
  2133. OPT_WITH_ARG("--pool-proxy|-x",
  2134. set_pool_proxy, NULL, NULL,
  2135. "Proxy URI to use for connecting to just the previous-defined pool"),
  2136. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2137. set_pool_force_rollntime, NULL, NULL,
  2138. opt_hidden),
  2139. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2140. opt_set_bool, &opt_protocol,
  2141. "Verbose dump of protocol-level activities"),
  2142. OPT_WITH_ARG("--queue|-Q",
  2143. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2144. "Minimum number of work items to have queued (0+)"),
  2145. OPT_WITHOUT_ARG("--quiet|-q",
  2146. opt_set_bool, &opt_quiet,
  2147. "Disable logging output, display status and errors"),
  2148. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2149. opt_set_bool, &opt_quiet_work_updates,
  2150. opt_hidden),
  2151. OPT_WITH_ARG("--quit-summary",
  2152. set_quit_summary, NULL, NULL,
  2153. "Summary printed when you quit: none/devs/procs/detailed"),
  2154. OPT_WITH_ARG("--quota|-U",
  2155. set_quota, NULL, NULL,
  2156. "quota;URL combination for server with load-balance strategy quotas"),
  2157. OPT_WITHOUT_ARG("--real-quiet",
  2158. opt_set_bool, &opt_realquiet,
  2159. "Disable all output"),
  2160. OPT_WITH_ARG("--request-diff",
  2161. set_request_diff, opt_show_floatval, &request_pdiff,
  2162. "Request a specific difficulty from pools"),
  2163. OPT_WITH_ARG("--retries",
  2164. opt_set_intval, opt_show_intval, &opt_retries,
  2165. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2166. OPT_WITH_ARG("--retry-pause",
  2167. set_null, NULL, NULL,
  2168. opt_hidden),
  2169. OPT_WITH_ARG("--rotate",
  2170. set_rotate, opt_show_intval, &opt_rotate_period,
  2171. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2172. OPT_WITHOUT_ARG("--round-robin",
  2173. set_rr, &pool_strategy,
  2174. "Change multipool strategy from failover to round robin on failure"),
  2175. OPT_WITH_ARG("--scan|-S",
  2176. add_serial, NULL, NULL,
  2177. "Configure how to scan for mining devices"),
  2178. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2179. add_serial, NULL, NULL,
  2180. opt_hidden),
  2181. OPT_WITH_ARG("--scan-time",
  2182. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2183. "Upper bound on time spent scanning current work, in seconds"),
  2184. OPT_WITH_ARG("-s",
  2185. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2186. opt_hidden),
  2187. OPT_WITH_ARG("--scantime",
  2188. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2189. opt_hidden),
  2190. OPT_WITH_ARG("--sched-start",
  2191. set_schedtime, NULL, &schedstart,
  2192. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2193. OPT_WITH_ARG("--sched-stop",
  2194. set_schedtime, NULL, &schedstop,
  2195. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2196. #ifdef USE_SCRYPT
  2197. OPT_WITHOUT_ARG("--scrypt",
  2198. opt_set_bool, &opt_scrypt,
  2199. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2200. #endif
  2201. OPT_WITH_ARG("--set-device|--set",
  2202. opt_string_elist_add, NULL, &opt_set_device_list,
  2203. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2204. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2205. OPT_WITH_ARG("--shaders",
  2206. set_shaders, NULL, NULL,
  2207. opt_hidden),
  2208. #endif
  2209. #ifdef HAVE_PWD_H
  2210. OPT_WITH_ARG("--setuid",
  2211. opt_set_charp, NULL, &opt_setuid,
  2212. "Username of an unprivileged user to run as"),
  2213. #endif
  2214. OPT_WITH_ARG("--sharelog",
  2215. set_sharelog, NULL, NULL,
  2216. "Append share log to file"),
  2217. OPT_WITH_ARG("--shares",
  2218. opt_set_floatval, NULL, &opt_shares,
  2219. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2220. OPT_WITHOUT_ARG("--show-processors",
  2221. opt_set_bool, &opt_show_procs,
  2222. "Show per processor statistics in summary"),
  2223. OPT_WITHOUT_ARG("--show-procs",
  2224. opt_set_bool, &opt_show_procs,
  2225. opt_hidden),
  2226. OPT_WITH_ARG("--skip-security-checks",
  2227. set_int_0_to_9999, NULL, &opt_skip_checks,
  2228. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2229. OPT_WITH_ARG("--socks-proxy",
  2230. opt_set_charp, NULL, &opt_socks_proxy,
  2231. "Set socks proxy (host:port)"),
  2232. #ifdef USE_LIBEVENT
  2233. OPT_WITH_ARG("--stratum-port",
  2234. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2235. "Port number to listen on for stratum miners (-1 means disabled)"),
  2236. #endif
  2237. OPT_WITHOUT_ARG("--submit-stale",
  2238. opt_set_bool, &opt_submit_stale,
  2239. opt_hidden),
  2240. OPT_WITH_ARG("--submit-threads",
  2241. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2242. "Minimum number of concurrent share submissions (default: 64)"),
  2243. #ifdef HAVE_SYSLOG_H
  2244. OPT_WITHOUT_ARG("--syslog",
  2245. opt_set_bool, &use_syslog,
  2246. "Use system log for output messages (default: standard error)"),
  2247. #endif
  2248. OPT_WITH_ARG("--temp-cutoff",
  2249. set_temp_cutoff, NULL, &opt_cutofftemp,
  2250. opt_hidden),
  2251. OPT_WITH_ARG("--temp-hysteresis",
  2252. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2253. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2254. #ifdef HAVE_ADL
  2255. OPT_WITH_ARG("--temp-overheat",
  2256. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2257. opt_hidden),
  2258. #endif
  2259. OPT_WITH_ARG("--temp-target",
  2260. set_temp_target, NULL, NULL,
  2261. opt_hidden),
  2262. OPT_WITHOUT_ARG("--text-only|-T",
  2263. opt_set_invbool, &use_curses,
  2264. #ifdef HAVE_CURSES
  2265. "Disable ncurses formatted screen output"
  2266. #else
  2267. opt_hidden
  2268. #endif
  2269. ),
  2270. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2271. OPT_WITH_ARG("--thread-concurrency",
  2272. set_thread_concurrency, NULL, NULL,
  2273. opt_hidden),
  2274. #endif
  2275. #ifdef USE_UNICODE
  2276. OPT_WITHOUT_ARG("--unicode",
  2277. opt_set_bool, &use_unicode,
  2278. "Use Unicode characters in TUI"),
  2279. #endif
  2280. OPT_WITH_ARG("--url|-o",
  2281. set_url, NULL, NULL,
  2282. "URL for bitcoin JSON-RPC server"),
  2283. OPT_WITH_ARG("--user|-u",
  2284. set_user, NULL, NULL,
  2285. "Username for bitcoin JSON-RPC server"),
  2286. #ifdef HAVE_OPENCL
  2287. OPT_WITH_ARG("--vectors|-v",
  2288. set_vector, NULL, NULL,
  2289. opt_hidden),
  2290. #endif
  2291. OPT_WITHOUT_ARG("--verbose",
  2292. opt_set_bool, &opt_log_output,
  2293. "Log verbose output to stderr as well as status output"),
  2294. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2295. opt_set_invbool, &opt_quiet_work_updates,
  2296. opt_hidden),
  2297. OPT_WITHOUT_ARG("--weighed-stats",
  2298. opt_set_bool, &opt_weighed_stats,
  2299. "Display statistics weighed to difficulty 1"),
  2300. #ifdef HAVE_OPENCL
  2301. OPT_WITH_ARG("--worksize|-w",
  2302. set_worksize, NULL, NULL,
  2303. opt_hidden),
  2304. #endif
  2305. OPT_WITHOUT_ARG("--unittest",
  2306. opt_set_bool, &opt_unittest, opt_hidden),
  2307. OPT_WITH_ARG("--coinbase-check-addr",
  2308. set_cbcaddr, NULL, NULL,
  2309. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2310. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2311. set_cbcaddr, NULL, NULL,
  2312. opt_hidden),
  2313. OPT_WITH_ARG("--coinbase-check-total",
  2314. set_cbctotal, NULL, NULL,
  2315. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2316. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2317. set_cbctotal, NULL, NULL,
  2318. opt_hidden),
  2319. OPT_WITH_ARG("--coinbase-check-percent",
  2320. set_cbcperc, NULL, NULL,
  2321. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2322. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2323. set_cbcperc, NULL, NULL,
  2324. opt_hidden),
  2325. OPT_WITHOUT_ARG("--worktime",
  2326. opt_set_bool, &opt_worktime,
  2327. "Display extra work time debug information"),
  2328. OPT_WITH_ARG("--pools",
  2329. opt_set_bool, NULL, NULL, opt_hidden),
  2330. OPT_ENDTABLE
  2331. };
  2332. static char *load_config(const char *arg, void __maybe_unused *unused);
  2333. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2334. {
  2335. static char err_buf[200];
  2336. struct opt_table *opt;
  2337. json_t *val;
  2338. if (fileconf && !*fileconf_load_p)
  2339. *fileconf_load_p = 1;
  2340. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2341. char *p, *name, *sp;
  2342. /* We don't handle subtables. */
  2343. assert(!(opt->type & OPT_SUBTABLE));
  2344. if (!opt->names)
  2345. continue;
  2346. /* Pull apart the option name(s). */
  2347. name = strdup(opt->names);
  2348. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2349. char *err = "Invalid value";
  2350. /* Ignore short options. */
  2351. if (p[1] != '-')
  2352. continue;
  2353. val = json_object_get(config, p+2);
  2354. if (!val)
  2355. continue;
  2356. if (opt->type & OPT_HASARG) {
  2357. if (json_is_string(val)) {
  2358. err = opt->cb_arg(json_string_value(val),
  2359. opt->u.arg);
  2360. } else if (json_is_number(val)) {
  2361. char buf[256], *p, *q;
  2362. snprintf(buf, 256, "%f", json_number_value(val));
  2363. if ( (p = strchr(buf, '.')) ) {
  2364. // Trim /\.0*$/ to work properly with integer-only arguments
  2365. q = p;
  2366. while (*(++q) == '0') {}
  2367. if (*q == '\0')
  2368. *p = '\0';
  2369. }
  2370. err = opt->cb_arg(buf, opt->u.arg);
  2371. } else if (json_is_array(val)) {
  2372. int n, size = json_array_size(val);
  2373. err = NULL;
  2374. for (n = 0; n < size && !err; n++) {
  2375. if (json_is_string(json_array_get(val, n)))
  2376. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2377. else if (json_is_object(json_array_get(val, n)))
  2378. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2379. }
  2380. }
  2381. } else if (opt->type & OPT_NOARG) {
  2382. if (json_is_true(val))
  2383. err = opt->cb(opt->u.arg);
  2384. else if (json_is_boolean(val)) {
  2385. if (opt->cb == (void*)opt_set_bool)
  2386. err = opt_set_invbool(opt->u.arg);
  2387. else if (opt->cb == (void*)opt_set_invbool)
  2388. err = opt_set_bool(opt->u.arg);
  2389. }
  2390. }
  2391. if (err) {
  2392. /* Allow invalid values to be in configuration
  2393. * file, just skipping over them provided the
  2394. * JSON is still valid after that. */
  2395. if (fileconf) {
  2396. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2397. *fileconf_load_p = -1;
  2398. } else {
  2399. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2400. p, err);
  2401. return err_buf;
  2402. }
  2403. }
  2404. }
  2405. free(name);
  2406. }
  2407. val = json_object_get(config, JSON_INCLUDE_CONF);
  2408. if (val && json_is_string(val))
  2409. return load_config(json_string_value(val), NULL);
  2410. return NULL;
  2411. }
  2412. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2413. static char *load_config(const char *arg, void __maybe_unused *unused)
  2414. {
  2415. json_error_t err;
  2416. json_t *config;
  2417. char *json_error;
  2418. size_t siz;
  2419. struct bfg_loaded_configfile *cfginfo;
  2420. cfginfo = malloc(sizeof(*cfginfo));
  2421. *cfginfo = (struct bfg_loaded_configfile){
  2422. .filename = strdup(arg),
  2423. };
  2424. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2425. if (++include_count > JSON_MAX_DEPTH)
  2426. return JSON_MAX_DEPTH_ERR;
  2427. #if JANSSON_MAJOR_VERSION > 1
  2428. config = json_load_file(arg, 0, &err);
  2429. #else
  2430. config = json_load_file(arg, &err);
  2431. #endif
  2432. if (!json_is_object(config)) {
  2433. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2434. json_error = malloc(siz);
  2435. if (!json_error)
  2436. quit(1, "Malloc failure in json error");
  2437. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2438. return json_error;
  2439. }
  2440. config_loaded = true;
  2441. /* Parse the config now, so we can override it. That can keep pointers
  2442. * so don't free config object. */
  2443. return parse_config(config, true, &cfginfo->fileconf_load);
  2444. }
  2445. static
  2446. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2447. {
  2448. bool * const found_defcfg_p = userp;
  2449. *found_defcfg_p = true;
  2450. load_config(filepath, NULL);
  2451. // Regardless of status of loading the config file, we should continue loading other defaults
  2452. return false;
  2453. }
  2454. static void load_default_config(void)
  2455. {
  2456. bool found_defcfg = false;
  2457. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2458. if (!found_defcfg)
  2459. {
  2460. // No BFGMiner config, try Cgminer's...
  2461. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2462. }
  2463. }
  2464. extern const char *opt_argv0;
  2465. static char *opt_verusage_and_exit(const char *extra)
  2466. {
  2467. puts(packagename);
  2468. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2469. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2470. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2471. printf(" Options:%s\n", BFG_OPTLIST);
  2472. printf("%s", opt_usage(opt_argv0, extra));
  2473. fflush(stdout);
  2474. exit(0);
  2475. }
  2476. /* These options are parsed before anything else */
  2477. static struct opt_table opt_early_table[] = {
  2478. // Default config is loaded in command line order, like a regular config
  2479. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2480. set_bool_ignore_arg, NULL, &config_loaded,
  2481. opt_hidden),
  2482. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2483. opt_set_bool, &config_loaded,
  2484. "Inhibit loading default config file"),
  2485. OPT_ENDTABLE
  2486. };
  2487. /* These options are available from commandline only */
  2488. static struct opt_table opt_cmdline_table[] = {
  2489. OPT_WITH_ARG("--config|-c",
  2490. load_config, NULL, NULL,
  2491. "Load a JSON-format configuration file\n"
  2492. "See example.conf for an example configuration."),
  2493. OPT_EARLY_WITHOUT_ARG("--no-config",
  2494. opt_set_bool, &config_loaded,
  2495. opt_hidden),
  2496. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2497. opt_set_bool, &config_loaded,
  2498. "Inhibit loading default config file"),
  2499. OPT_WITHOUT_ARG("--default-config",
  2500. load_default_config, NULL,
  2501. "Always load the default config file"),
  2502. OPT_WITHOUT_ARG("--help|-h",
  2503. opt_verusage_and_exit, NULL,
  2504. "Print this message"),
  2505. #ifdef HAVE_OPENCL
  2506. OPT_WITHOUT_ARG("--ndevs|-n",
  2507. print_ndevs_and_exit, &nDevs,
  2508. opt_hidden),
  2509. #endif
  2510. OPT_WITHOUT_ARG("--version|-V",
  2511. opt_version_and_exit, packagename,
  2512. "Display version and exit"),
  2513. OPT_ENDTABLE
  2514. };
  2515. static bool jobj_binary(const json_t *obj, const char *key,
  2516. void *buf, size_t buflen, bool required)
  2517. {
  2518. const char *hexstr;
  2519. json_t *tmp;
  2520. tmp = json_object_get(obj, key);
  2521. if (unlikely(!tmp)) {
  2522. if (unlikely(required))
  2523. applog(LOG_ERR, "JSON key '%s' not found", key);
  2524. return false;
  2525. }
  2526. hexstr = json_string_value(tmp);
  2527. if (unlikely(!hexstr)) {
  2528. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2529. return false;
  2530. }
  2531. if (!hex2bin(buf, hexstr, buflen))
  2532. return false;
  2533. return true;
  2534. }
  2535. static void calc_midstate(struct work *work)
  2536. {
  2537. union {
  2538. unsigned char c[64];
  2539. uint32_t i[16];
  2540. } data;
  2541. swap32yes(&data.i[0], work->data, 16);
  2542. sha256_ctx ctx;
  2543. sha256_init(&ctx);
  2544. sha256_update(&ctx, data.c, 64);
  2545. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2546. swap32tole(work->midstate, work->midstate, 8);
  2547. }
  2548. static
  2549. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2550. {
  2551. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2552. *tr = (struct bfg_tmpl_ref){
  2553. .tmpl = tmpl,
  2554. .refcount = 1,
  2555. };
  2556. mutex_init(&tr->mutex);
  2557. return tr;
  2558. }
  2559. static
  2560. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2561. {
  2562. mutex_lock(&tr->mutex);
  2563. ++tr->refcount;
  2564. mutex_unlock(&tr->mutex);
  2565. }
  2566. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2567. {
  2568. mutex_lock(&tr->mutex);
  2569. bool free_tmpl = !--tr->refcount;
  2570. mutex_unlock(&tr->mutex);
  2571. if (free_tmpl)
  2572. {
  2573. blktmpl_free(tr->tmpl);
  2574. mutex_destroy(&tr->mutex);
  2575. free(tr);
  2576. }
  2577. }
  2578. static struct work *make_work(void)
  2579. {
  2580. struct work *work = calloc(1, sizeof(struct work));
  2581. if (unlikely(!work))
  2582. quit(1, "Failed to calloc work in make_work");
  2583. cg_wlock(&control_lock);
  2584. work->id = total_work++;
  2585. cg_wunlock(&control_lock);
  2586. return work;
  2587. }
  2588. /* This is the central place all work that is about to be retired should be
  2589. * cleaned to remove any dynamically allocated arrays within the struct */
  2590. void clean_work(struct work *work)
  2591. {
  2592. free(work->job_id);
  2593. bytes_free(&work->nonce2);
  2594. free(work->nonce1);
  2595. if (work->device_data_free_func)
  2596. work->device_data_free_func(work);
  2597. if (work->tr)
  2598. tmpl_decref(work->tr);
  2599. memset(work, 0, sizeof(struct work));
  2600. }
  2601. /* All dynamically allocated work structs should be freed here to not leak any
  2602. * ram from arrays allocated within the work struct */
  2603. void free_work(struct work *work)
  2604. {
  2605. clean_work(work);
  2606. free(work);
  2607. }
  2608. const char *bfg_workpadding_bin = "\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";
  2609. #define workpadding_bin bfg_workpadding_bin
  2610. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2611. static
  2612. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2613. {
  2614. unsigned char hash_swap[32];
  2615. swap256(hash_swap, blkinfo->prevblkhash);
  2616. swap32tole(hash_swap, hash_swap, 32 / 4);
  2617. memset(out, '.', 3);
  2618. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2619. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2620. {
  2621. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2622. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2623. }
  2624. else
  2625. bin2hex(&out[3], &hash_swap[0x18], 8);
  2626. }
  2627. #ifdef HAVE_CURSES
  2628. static void update_block_display(void);
  2629. #endif
  2630. // Must only be called with ch_lock held!
  2631. static
  2632. void __update_block_title(struct mining_goal_info * const goal)
  2633. {
  2634. struct blockchain_info * const blkchain = goal->blkchain;
  2635. if (!goal->current_goal_detail)
  2636. goal->current_goal_detail = malloc(block_info_str_sz);
  2637. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2638. #ifdef HAVE_CURSES
  2639. update_block_display();
  2640. #endif
  2641. }
  2642. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2643. static
  2644. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2645. {
  2646. struct blockchain_info * const blkchain = goal->blkchain;
  2647. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2648. if ((!blkinfo) || blkinfo->height)
  2649. return;
  2650. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2651. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2652. cg_wlock(&ch_lock);
  2653. blkinfo->height = blkheight;
  2654. if (blkinfo == blkchain->currentblk)
  2655. {
  2656. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2657. __update_block_title(goal);
  2658. }
  2659. cg_wunlock(&ch_lock);
  2660. }
  2661. static
  2662. void pool_set_opaque(struct pool *pool, bool opaque)
  2663. {
  2664. if (pool->swork.opaque == opaque)
  2665. return;
  2666. pool->swork.opaque = opaque;
  2667. if (opaque)
  2668. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2669. pool->pool_no);
  2670. else
  2671. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2672. pool->pool_no);
  2673. }
  2674. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2675. {
  2676. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2677. return true;
  2678. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2679. }
  2680. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2681. {
  2682. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2683. {}
  2684. else
  2685. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2686. {
  2687. if (pool->enabled == POOL_ENABLED)
  2688. {
  2689. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2690. disable_pool(pool, POOL_MISBEHAVING);
  2691. }
  2692. }
  2693. else
  2694. if (pool->enabled == POOL_MISBEHAVING)
  2695. {
  2696. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2697. enable_pool(pool);
  2698. }
  2699. }
  2700. void set_simple_ntime_roll_limit(struct ntime_roll_limits * const nrl, const uint32_t ntime_base, const int ntime_roll, const struct timeval * const tvp_ref)
  2701. {
  2702. const int offsets = max(ntime_roll, 60);
  2703. *nrl = (struct ntime_roll_limits){
  2704. .min = ntime_base,
  2705. .max = ntime_base + ntime_roll,
  2706. .tv_ref = *tvp_ref,
  2707. .minoff = -offsets,
  2708. .maxoff = offsets,
  2709. };
  2710. }
  2711. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2712. {
  2713. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2714. }
  2715. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2716. {
  2717. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2718. const uint32_t ref_ntime = work_get_ntime(work);
  2719. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2720. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2721. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2722. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2723. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2724. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2725. if (max_ntime < min_ntime)
  2726. return -1;
  2727. if (max_ntime - min_ntime > desired_roll)
  2728. {
  2729. // Adjust min_ntime upward for accuracy, when possible
  2730. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2731. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2732. if (ideal_ntime > min_ntime)
  2733. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2734. }
  2735. work_set_ntime(work, min_ntime);
  2736. return max_ntime - min_ntime;
  2737. }
  2738. #if BLKMAKER_VERSION > 1
  2739. static
  2740. void refresh_bitcoind_address(const bool fresh)
  2741. {
  2742. struct mining_goal_info * const goal = get_mining_goal("default");
  2743. struct blockchain_info * const blkchain = goal->blkchain;
  2744. if (!have_at_least_one_getcbaddr)
  2745. return;
  2746. char getcbaddr_req[60];
  2747. CURL *curl = NULL;
  2748. json_t *json, *j2;
  2749. const char *s, *s2;
  2750. bytes_t newscript = BYTES_INIT;
  2751. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2752. for (int i = 0; i < total_pools; ++i)
  2753. {
  2754. struct pool * const pool = pools[i];
  2755. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2756. continue;
  2757. if (pool->goal != goal)
  2758. // TODO: Multi-blockchain support
  2759. continue;
  2760. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2761. if (!curl)
  2762. {
  2763. curl = curl_easy_init();
  2764. if (unlikely(!curl))
  2765. {
  2766. applogfail(LOG_ERR, "curl_easy_init");
  2767. break;
  2768. }
  2769. }
  2770. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2771. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2772. {
  2773. const char *estrc;
  2774. char *estr = NULL;
  2775. if (!(json && j2))
  2776. estrc = NULL;
  2777. else
  2778. {
  2779. estrc = json_string_value(j2);
  2780. if (!estrc)
  2781. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2782. }
  2783. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2784. free(estr);
  2785. continue;
  2786. }
  2787. s = bfg_json_obj_string(json, "result", NULL);
  2788. if (unlikely(!s))
  2789. {
  2790. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2791. continue;
  2792. }
  2793. s2 = set_b58addr(s, &newscript);
  2794. if (unlikely(s2))
  2795. {
  2796. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2797. continue;
  2798. }
  2799. if (bytes_eq(&newscript, &opt_coinbase_script))
  2800. {
  2801. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2802. break;
  2803. }
  2804. bytes_assimilate(&opt_coinbase_script, &newscript);
  2805. coinbase_script_block_id = blkchain->currentblk->block_id;
  2806. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2807. break;
  2808. }
  2809. bytes_free(&newscript);
  2810. if (curl)
  2811. curl_easy_cleanup(curl);
  2812. }
  2813. #endif
  2814. #define GBT_XNONCESZ (sizeof(uint32_t))
  2815. #if BLKMAKER_VERSION > 4
  2816. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2817. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2818. #endif
  2819. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2820. {
  2821. json_t *res_val = json_object_get(val, "result");
  2822. json_t *tmp_val;
  2823. bool ret = false;
  2824. struct timeval tv_now;
  2825. if (unlikely(detect_algo == 1)) {
  2826. json_t *tmp = json_object_get(res_val, "algorithm");
  2827. const char *v = tmp ? json_string_value(tmp) : "";
  2828. if (strncasecmp(v, "scrypt", 6))
  2829. detect_algo = 2;
  2830. }
  2831. timer_set_now(&tv_now);
  2832. if (work->tr)
  2833. {
  2834. blktemplate_t * const tmpl = work->tr->tmpl;
  2835. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  2836. if (err) {
  2837. applog(LOG_ERR, "blktmpl error: %s", err);
  2838. return false;
  2839. }
  2840. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  2841. #if BLKMAKER_VERSION > 1
  2842. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  2843. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  2844. refresh_bitcoind_address(false);
  2845. if (bytes_len(&opt_coinbase_script) && get_mining_goal("default") == pool->goal)
  2846. {
  2847. bool newcb;
  2848. #if BLKMAKER_VERSION > 2
  2849. blkmk_init_generation2(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script), &newcb);
  2850. #else
  2851. newcb = !tmpl->cbtxn;
  2852. blkmk_init_generation(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script));
  2853. #endif
  2854. if (newcb)
  2855. {
  2856. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  2857. if (ae < (ssize_t)sizeof(template_nonce))
  2858. applog(LOG_WARNING, "Cannot append template-nonce to coinbase on pool %u (%"PRId64") - you might be wasting hashing!", work->pool->pool_no, (int64_t)ae);
  2859. ++template_nonce;
  2860. }
  2861. }
  2862. #endif
  2863. #if BLKMAKER_VERSION > 0
  2864. {
  2865. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  2866. static bool appenderr = false;
  2867. if (ae <= 0) {
  2868. if (opt_coinbase_sig) {
  2869. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2870. appenderr = true;
  2871. }
  2872. } else if (ae >= 3 || opt_coinbase_sig) {
  2873. const char *cbappend = opt_coinbase_sig;
  2874. const char full[] = PACKAGE " " VERSION;
  2875. char *need_free = NULL;
  2876. if (!cbappend) {
  2877. if ((size_t)ae >= sizeof(full) - 1)
  2878. cbappend = full;
  2879. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2880. {
  2881. const char *pos = strchr(full, '-');
  2882. size_t sz = (pos - full);
  2883. if (pos && ae > sz)
  2884. {
  2885. cbappend = need_free = malloc(sz + 1);
  2886. memcpy(need_free, full, sz);
  2887. need_free[sz] = '\0';
  2888. }
  2889. else
  2890. cbappend = PACKAGE;
  2891. }
  2892. else
  2893. cbappend = "BFG";
  2894. }
  2895. size_t cbappendsz = strlen(cbappend);
  2896. static bool truncatewarning = false;
  2897. if (cbappendsz <= (size_t)ae) {
  2898. if (cbappendsz < (size_t)ae)
  2899. // If we have space, include the trailing \0
  2900. ++cbappendsz;
  2901. ae = cbappendsz;
  2902. truncatewarning = false;
  2903. } else {
  2904. char *tmp = malloc(ae + 1);
  2905. memcpy(tmp, opt_coinbase_sig, ae);
  2906. tmp[ae] = '\0';
  2907. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2908. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2909. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2910. free(tmp);
  2911. truncatewarning = true;
  2912. }
  2913. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  2914. free(need_free);
  2915. if (ae <= 0) {
  2916. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2917. appenderr = true;
  2918. } else
  2919. appenderr = false;
  2920. }
  2921. }
  2922. #endif
  2923. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2924. return false;
  2925. swap32yes(work->data, work->data, 80 / 4);
  2926. memcpy(&work->data[80], workpadding_bin, 48);
  2927. work->ntime_roll_limits = (struct ntime_roll_limits){
  2928. .min = tmpl->mintime,
  2929. .max = tmpl->maxtime,
  2930. .tv_ref = tv_now,
  2931. .minoff = tmpl->mintimeoff,
  2932. .maxoff = tmpl->maxtimeoff,
  2933. };
  2934. const struct blktmpl_longpoll_req *lp;
  2935. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2936. free(pool->lp_id);
  2937. pool->lp_id = strdup(lp->id);
  2938. #if 0 /* This just doesn't work :( */
  2939. curl_socket_t sock = pool->lp_socket;
  2940. if (sock != CURL_SOCKET_BAD) {
  2941. pool->lp_socket = CURL_SOCKET_BAD;
  2942. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2943. shutdown(sock, SHUT_RDWR);
  2944. }
  2945. #endif
  2946. }
  2947. }
  2948. else
  2949. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2950. applog(LOG_ERR, "JSON inval data");
  2951. return false;
  2952. }
  2953. else
  2954. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  2955. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2956. // Calculate it ourselves
  2957. applog(LOG_DEBUG, "Calculating midstate locally");
  2958. calc_midstate(work);
  2959. }
  2960. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2961. applog(LOG_ERR, "JSON inval target");
  2962. return false;
  2963. }
  2964. if (work->tr)
  2965. {
  2966. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2967. {
  2968. int p = (sizeof(work->target) - 1) - i;
  2969. unsigned char c = work->target[i];
  2970. work->target[i] = work->target[p];
  2971. work->target[p] = c;
  2972. }
  2973. }
  2974. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2975. struct mining_goal_info * const goal = pool->goal;
  2976. uint32_t blkheight = json_number_value(tmp_val);
  2977. const void * const prevblkhash = &work->data[4];
  2978. have_block_height(goal, prevblkhash, blkheight);
  2979. }
  2980. memset(work->hash, 0, sizeof(work->hash));
  2981. work->tv_staged = tv_now;
  2982. #if BLKMAKER_VERSION > 4
  2983. if (work->tr)
  2984. {
  2985. blktemplate_t * const tmpl = work->tr->tmpl;
  2986. uint8_t buf[80];
  2987. int16_t expire;
  2988. uint8_t *cbtxn;
  2989. size_t cbtxnsz;
  2990. size_t cbextranonceoffset;
  2991. int branchcount;
  2992. libblkmaker_hash_t *branches;
  2993. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  2994. {
  2995. struct stratum_work * const swork = &pool->swork;
  2996. const size_t branchdatasz = branchcount * 0x20;
  2997. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  2998. cg_wlock(&pool->data_lock);
  2999. swork->tr = work->tr;
  3000. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3001. swork->nonce2_offset = cbextranonceoffset;
  3002. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3003. swork->merkles = branchcount;
  3004. memcpy(swork->header1, &buf[0], 36);
  3005. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3006. swork->tv_received = tv_now;
  3007. memcpy(swork->diffbits, &buf[72], 4);
  3008. memcpy(swork->target, work->target, sizeof(swork->target));
  3009. free(swork->job_id);
  3010. swork->job_id = NULL;
  3011. swork->clean = true;
  3012. swork->work_restart_id = pool->work_restart_id;
  3013. // FIXME: Do something with expire
  3014. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3015. pool->nonce2 = 0;
  3016. cg_wunlock(&pool->data_lock);
  3017. }
  3018. else
  3019. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3020. }
  3021. #endif // BLKMAKER_VERSION > 4
  3022. pool_set_opaque(pool, !work->tr);
  3023. ret = true;
  3024. return ret;
  3025. }
  3026. /* Returns whether the pool supports local work generation or not. */
  3027. static bool pool_localgen(struct pool *pool)
  3028. {
  3029. return (pool->last_work_copy || pool->has_stratum);
  3030. }
  3031. int dev_from_id(int thr_id)
  3032. {
  3033. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3034. return cgpu->device_id;
  3035. }
  3036. /* Create an exponentially decaying average over the opt_log_interval */
  3037. void decay_time(double *f, double fadd, double fsecs)
  3038. {
  3039. double ftotal, fprop;
  3040. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3041. ftotal = 1.0 + fprop;
  3042. *f += (fadd * fprop);
  3043. *f /= ftotal;
  3044. }
  3045. static int __total_staged(void)
  3046. {
  3047. return HASH_COUNT(staged_work);
  3048. }
  3049. static int total_staged(void)
  3050. {
  3051. int ret;
  3052. mutex_lock(stgd_lock);
  3053. ret = __total_staged();
  3054. mutex_unlock(stgd_lock);
  3055. return ret;
  3056. }
  3057. #ifdef HAVE_CURSES
  3058. WINDOW *mainwin, *statuswin, *logwin;
  3059. #endif
  3060. double total_secs = 1.0;
  3061. #ifdef HAVE_CURSES
  3062. static char statusline[256];
  3063. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3064. static int statusy;
  3065. static int devsummaryYOffset;
  3066. static int total_lines;
  3067. #endif
  3068. #ifdef HAVE_OPENCL
  3069. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3070. #endif
  3071. struct cgpu_info *cpus;
  3072. bool _bfg_console_cancel_disabled;
  3073. int _bfg_console_prev_cancelstate;
  3074. #ifdef HAVE_CURSES
  3075. #define lock_curses() bfg_console_lock()
  3076. #define unlock_curses() bfg_console_unlock()
  3077. static bool curses_active_locked(void)
  3078. {
  3079. bool ret;
  3080. lock_curses();
  3081. ret = curses_active;
  3082. if (!ret)
  3083. unlock_curses();
  3084. return ret;
  3085. }
  3086. // Cancellable getch
  3087. int my_cancellable_getch(void)
  3088. {
  3089. // This only works because the macro only hits direct getch() calls
  3090. typedef int (*real_getch_t)(void);
  3091. const real_getch_t real_getch = __real_getch;
  3092. int type, rv;
  3093. bool sct;
  3094. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3095. rv = real_getch();
  3096. if (sct)
  3097. pthread_setcanceltype(type, &type);
  3098. return rv;
  3099. }
  3100. #ifdef PDCURSES
  3101. static
  3102. int bfg_wresize(WINDOW *win, int lines, int columns)
  3103. {
  3104. int rv = wresize(win, lines, columns);
  3105. int x, y;
  3106. getyx(win, y, x);
  3107. if (unlikely(y >= lines || x >= columns))
  3108. {
  3109. if (y >= lines)
  3110. y = lines - 1;
  3111. if (x >= columns)
  3112. x = columns - 1;
  3113. wmove(win, y, x);
  3114. }
  3115. return rv;
  3116. }
  3117. #else
  3118. # define bfg_wresize wresize
  3119. #endif
  3120. #endif
  3121. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3122. {
  3123. va_list ap;
  3124. size_t presz = strlen(buf);
  3125. va_start(ap, fmt);
  3126. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3127. va_end(ap);
  3128. }
  3129. double stats_elapsed(struct cgminer_stats *stats)
  3130. {
  3131. struct timeval now;
  3132. double elapsed;
  3133. if (stats->start_tv.tv_sec == 0)
  3134. elapsed = total_secs;
  3135. else {
  3136. cgtime(&now);
  3137. elapsed = tdiff(&now, &stats->start_tv);
  3138. }
  3139. if (elapsed < 1.0)
  3140. elapsed = 1.0;
  3141. return elapsed;
  3142. }
  3143. bool drv_ready(struct cgpu_info *cgpu)
  3144. {
  3145. switch (cgpu->status) {
  3146. case LIFE_INIT:
  3147. case LIFE_DEAD2:
  3148. return false;
  3149. default:
  3150. return true;
  3151. }
  3152. }
  3153. double cgpu_utility(struct cgpu_info *cgpu)
  3154. {
  3155. double dev_runtime = cgpu_runtime(cgpu);
  3156. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3157. }
  3158. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3159. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3160. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3161. }while(0)
  3162. static float
  3163. utility_to_hashrate(double utility)
  3164. {
  3165. return utility * 0x4444444;
  3166. }
  3167. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3168. static const int _unitbase = 4;
  3169. static
  3170. void pick_unit(float hashrate, unsigned char *unit)
  3171. {
  3172. unsigned char i;
  3173. if (hashrate == 0 || !isfinite(hashrate))
  3174. {
  3175. if (*unit < _unitbase)
  3176. *unit = _unitbase;
  3177. return;
  3178. }
  3179. hashrate *= 1e12;
  3180. for (i = 0; i < *unit; ++i)
  3181. hashrate /= 1e3;
  3182. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3183. while (hashrate >= 999.95)
  3184. {
  3185. hashrate /= 1e3;
  3186. if (likely(_unitchar[*unit] != '?'))
  3187. ++*unit;
  3188. }
  3189. }
  3190. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3191. enum h2bs_fmt {
  3192. H2B_NOUNIT, // "xxx.x"
  3193. H2B_SHORT, // "xxx.xMH/s"
  3194. H2B_SPACED, // "xxx.x MH/s"
  3195. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3196. };
  3197. enum bfu_floatprec {
  3198. FUP_INTEGER,
  3199. FUP_HASHES,
  3200. FUP_BTC,
  3201. FUP_DIFF,
  3202. };
  3203. static
  3204. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3205. {
  3206. char *s = buf;
  3207. unsigned char prec, i, unit;
  3208. int rv = 0;
  3209. if (unitin == -1)
  3210. {
  3211. unit = 0;
  3212. hashrate_pick_unit(hashrate, &unit);
  3213. }
  3214. else
  3215. unit = unitin;
  3216. hashrate *= 1e12;
  3217. for (i = 0; i < unit; ++i)
  3218. hashrate /= 1000;
  3219. switch (fprec)
  3220. {
  3221. case FUP_HASHES:
  3222. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3223. if (hashrate >= 99.995 || unit < 6)
  3224. prec = 1;
  3225. else
  3226. prec = 2;
  3227. _SNP("%5.*f", prec, hashrate);
  3228. break;
  3229. case FUP_INTEGER:
  3230. _SNP("%3d", (int)hashrate);
  3231. break;
  3232. case FUP_BTC:
  3233. if (hashrate >= 99.995)
  3234. prec = 0;
  3235. else
  3236. prec = 2;
  3237. _SNP("%5.*f", prec, hashrate);
  3238. break;
  3239. case FUP_DIFF:
  3240. if (unit > _unitbase)
  3241. _SNP("%.3g", hashrate);
  3242. else
  3243. _SNP("%u", (unsigned int)hashrate);
  3244. }
  3245. if (fmt != H2B_NOUNIT)
  3246. {
  3247. char uc[3] = {_unitchar[unit], '\0'};
  3248. switch (fmt) {
  3249. case H2B_SPACED:
  3250. _SNP(" ");
  3251. default:
  3252. break;
  3253. case H2B_SHORTV:
  3254. if (isspace(uc[0]))
  3255. uc[0] = '\0';
  3256. }
  3257. if (uc[0] == '\xb5')
  3258. // Convert to UTF-8
  3259. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3260. _SNP("%s%s", uc, measurement);
  3261. }
  3262. return rv;
  3263. }
  3264. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3265. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3266. static
  3267. char *_multi_format_unit(char **buflist, size_t *bufszlist, bool floatprec, const char *measurement, enum h2bs_fmt fmt, const char *delim, int count, const float *numbers, bool isarray)
  3268. {
  3269. unsigned char unit = 0;
  3270. bool allzero = true;
  3271. int i;
  3272. size_t delimsz = 0;
  3273. char *buf = buflist[0];
  3274. size_t bufsz = bufszlist[0];
  3275. size_t itemwidth = (floatprec ? 5 : 3);
  3276. if (!isarray)
  3277. delimsz = strlen(delim);
  3278. for (i = 0; i < count; ++i)
  3279. if (numbers[i] != 0)
  3280. {
  3281. pick_unit(numbers[i], &unit);
  3282. allzero = false;
  3283. }
  3284. if (allzero)
  3285. unit = _unitbase;
  3286. --count;
  3287. for (i = 0; i < count; ++i)
  3288. {
  3289. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3290. if (isarray)
  3291. {
  3292. buf = buflist[i + 1];
  3293. bufsz = bufszlist[i + 1];
  3294. }
  3295. else
  3296. {
  3297. buf += itemwidth;
  3298. bufsz -= itemwidth;
  3299. if (delimsz > bufsz)
  3300. delimsz = bufsz;
  3301. memcpy(buf, delim, delimsz);
  3302. buf += delimsz;
  3303. bufsz -= delimsz;
  3304. }
  3305. }
  3306. // Last entry has the unit
  3307. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3308. return buflist[0];
  3309. }
  3310. #define multi_format_unit2(buf, bufsz, floatprec, measurement, fmt, delim, count, ...) _multi_format_unit((char *[]){buf}, (size_t[]){bufsz}, floatprec, measurement, fmt, delim, count, (float[]){ __VA_ARGS__ }, false)
  3311. #define multi_format_unit_array2(buflist, bufszlist, floatprec, measurement, fmt, count, ...) (void)_multi_format_unit(buflist, bufszlist, floatprec, measurement, fmt, NULL, count, (float[]){ __VA_ARGS__ }, true)
  3312. static
  3313. int percentf3(char * const buf, size_t sz, double p, const double t)
  3314. {
  3315. char *s = buf;
  3316. int rv = 0;
  3317. if (!p)
  3318. _SNP("none");
  3319. else
  3320. if (t <= p)
  3321. _SNP("100%%");
  3322. else
  3323. {
  3324. p /= t;
  3325. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3326. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3327. else
  3328. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3329. _SNP("%.1f%%", p * 100); // "9.1%"
  3330. else
  3331. _SNP("%3.0f%%", p * 100); // " 99%"
  3332. }
  3333. return rv;
  3334. }
  3335. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3336. static
  3337. void test_decimal_width()
  3338. {
  3339. // The pipe character at end of each line should perfectly line up
  3340. char printbuf[512];
  3341. char testbuf1[64];
  3342. char testbuf2[64];
  3343. char testbuf3[64];
  3344. char testbuf4[64];
  3345. double testn;
  3346. int width;
  3347. int saved;
  3348. // Hotspots around 0.1 and 0.01
  3349. saved = -1;
  3350. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3351. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3352. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3353. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3354. if (unlikely((saved != -1) && (width != saved))) {
  3355. ++unittest_failures;
  3356. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3357. applog(LOG_ERR, "%s", printbuf);
  3358. }
  3359. saved = width;
  3360. }
  3361. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3362. saved = -1;
  3363. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3364. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3365. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3366. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3367. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3368. width = utf8_strlen(printbuf);
  3369. if (unlikely((saved != -1) && (width != saved))) {
  3370. ++unittest_failures;
  3371. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3372. applog(LOG_ERR, "%s", printbuf);
  3373. }
  3374. saved = width;
  3375. }
  3376. // Hotspot around unit transition boundary in pick_unit
  3377. saved = -1;
  3378. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3379. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3380. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3381. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3382. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3383. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3384. width = utf8_strlen(printbuf);
  3385. if (unlikely((saved != -1) && (width != saved))) {
  3386. ++unittest_failures;
  3387. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3388. applog(LOG_ERR, "%s", printbuf);
  3389. }
  3390. saved = width;
  3391. }
  3392. }
  3393. #ifdef HAVE_CURSES
  3394. static void adj_width(int var, int *length);
  3395. #endif
  3396. #ifdef HAVE_CURSES
  3397. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3398. static
  3399. void format_statline(char *buf, size_t bufsz, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, double wnotaccepted, double waccepted, int hwerrs, double bad_diff1, double allnonces)
  3400. {
  3401. char rejpcbuf[6];
  3402. char bnbuf[6];
  3403. adj_width(accepted, &awidth);
  3404. adj_width(rejected, &rwidth);
  3405. adj_width(stale, &swidth);
  3406. adj_width(hwerrs, &hwwidth);
  3407. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3408. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3409. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3410. cHr, aHr, uHr,
  3411. awidth, accepted,
  3412. rwidth, rejected,
  3413. swidth, stale,
  3414. rejpcbuf,
  3415. hwwidth, hwerrs,
  3416. bnbuf
  3417. );
  3418. }
  3419. static
  3420. const char *pool_proto_str(const struct pool * const pool)
  3421. {
  3422. if (pool->idle)
  3423. return "Dead ";
  3424. if (pool->has_stratum)
  3425. return "Strtm";
  3426. if (pool->lp_url && pool->proto != pool->lp_proto)
  3427. return "Mixed";
  3428. switch (pool->proto)
  3429. {
  3430. case PLP_GETBLOCKTEMPLATE:
  3431. return " GBT ";
  3432. case PLP_GETWORK:
  3433. return "GWork";
  3434. default:
  3435. return "Alive";
  3436. }
  3437. }
  3438. #endif
  3439. static inline
  3440. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3441. {
  3442. if (!(use_unicode && have_unicode_degrees))
  3443. maybe_unicode = false;
  3444. if (temp && *temp > 0.)
  3445. if (maybe_unicode)
  3446. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3447. else
  3448. snprintf(buf, bufsz, "%4.1fC", *temp);
  3449. else
  3450. {
  3451. if (temp)
  3452. snprintf(buf, bufsz, " ");
  3453. if (maybe_unicode)
  3454. tailsprintf(buf, bufsz, " ");
  3455. }
  3456. tailsprintf(buf, bufsz, " | ");
  3457. }
  3458. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3459. {
  3460. #ifndef HAVE_CURSES
  3461. assert(for_curses == false);
  3462. #endif
  3463. struct device_drv *drv = cgpu->drv;
  3464. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3465. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3466. char rejpcbuf[6];
  3467. char bnbuf[6];
  3468. double dev_runtime;
  3469. if (!opt_show_procs)
  3470. cgpu = cgpu->device;
  3471. dev_runtime = cgpu_runtime(cgpu);
  3472. double rolling, mhashes;
  3473. int accepted, rejected, stale;
  3474. double waccepted;
  3475. double wnotaccepted;
  3476. int hwerrs;
  3477. double bad_diff1, good_diff1;
  3478. rolling = mhashes = waccepted = wnotaccepted = 0;
  3479. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3480. {
  3481. struct cgpu_info *slave = cgpu;
  3482. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3483. {
  3484. slave->utility = slave->accepted / dev_runtime * 60;
  3485. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3486. rolling += slave->rolling;
  3487. mhashes += slave->total_mhashes;
  3488. if (opt_weighed_stats)
  3489. {
  3490. accepted += slave->diff_accepted;
  3491. rejected += slave->diff_rejected;
  3492. stale += slave->diff_stale;
  3493. }
  3494. else
  3495. {
  3496. accepted += slave->accepted;
  3497. rejected += slave->rejected;
  3498. stale += slave->stale;
  3499. }
  3500. waccepted += slave->diff_accepted;
  3501. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3502. hwerrs += slave->hw_errors;
  3503. bad_diff1 += slave->bad_diff1;
  3504. good_diff1 += slave->diff1;
  3505. if (opt_show_procs)
  3506. break;
  3507. }
  3508. }
  3509. double wtotal = (waccepted + wnotaccepted);
  3510. multi_format_unit_array2(
  3511. ((char*[]){cHr, aHr, uHr}),
  3512. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3513. true, "h/s", hashrate_style,
  3514. 3,
  3515. 1e6*rolling,
  3516. 1e6*mhashes / dev_runtime,
  3517. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3518. // Processor representation
  3519. #ifdef HAVE_CURSES
  3520. if (for_curses)
  3521. {
  3522. if (opt_show_procs)
  3523. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3524. else
  3525. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3526. }
  3527. else
  3528. #endif
  3529. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3530. if (include_serial_in_statline && cgpu->dev_serial)
  3531. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3532. if (unlikely(cgpu->status == LIFE_INIT))
  3533. {
  3534. tailsprintf(buf, bufsz, "Initializing...");
  3535. return;
  3536. }
  3537. {
  3538. const size_t bufln = strlen(buf);
  3539. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3540. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3541. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3542. else
  3543. {
  3544. float temp = cgpu->temp;
  3545. if (!opt_show_procs)
  3546. {
  3547. // Find the highest temperature of all processors
  3548. struct cgpu_info *proc = cgpu;
  3549. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3550. if (proc->temp > temp)
  3551. temp = proc->temp;
  3552. }
  3553. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3554. }
  3555. }
  3556. #ifdef HAVE_CURSES
  3557. if (for_curses)
  3558. {
  3559. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3560. const char *cHrStats;
  3561. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3562. bool all_dead = true, all_off = true, all_rdrv = true;
  3563. struct cgpu_info *proc = cgpu;
  3564. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3565. {
  3566. switch (cHrStatsI) {
  3567. default:
  3568. if (proc->status == LIFE_WAIT)
  3569. cHrStatsI = 5;
  3570. case 5:
  3571. if (proc->deven == DEV_RECOVER_ERR)
  3572. cHrStatsI = 4;
  3573. case 4:
  3574. if (proc->deven == DEV_RECOVER)
  3575. cHrStatsI = 3;
  3576. case 3:
  3577. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3578. {
  3579. cHrStatsI = 1;
  3580. all_off = false;
  3581. }
  3582. else
  3583. {
  3584. if (likely(proc->deven == DEV_ENABLED))
  3585. all_off = false;
  3586. if (proc->deven != DEV_RECOVER_DRV)
  3587. all_rdrv = false;
  3588. }
  3589. case 1:
  3590. break;
  3591. }
  3592. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3593. all_dead = false;
  3594. if (opt_show_procs)
  3595. break;
  3596. }
  3597. if (unlikely(all_dead))
  3598. cHrStatsI = 0;
  3599. else
  3600. if (unlikely(all_off))
  3601. cHrStatsI = 2;
  3602. cHrStats = cHrStatsOpt[cHrStatsI];
  3603. if (cHrStatsI == 2 && all_rdrv)
  3604. cHrStats = " RST ";
  3605. format_statline(buf, bufsz,
  3606. cHrStats,
  3607. aHr, uHr,
  3608. accepted, rejected, stale,
  3609. wnotaccepted, waccepted,
  3610. hwerrs,
  3611. bad_diff1, bad_diff1 + good_diff1);
  3612. }
  3613. else
  3614. #endif
  3615. {
  3616. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3617. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3618. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3619. opt_log_interval,
  3620. cHr, aHr, uHr,
  3621. accepted,
  3622. rejected,
  3623. stale,
  3624. rejpcbuf,
  3625. hwerrs,
  3626. bnbuf
  3627. );
  3628. }
  3629. }
  3630. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3631. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3632. static void text_print_status(int thr_id)
  3633. {
  3634. struct cgpu_info *cgpu;
  3635. char logline[256];
  3636. cgpu = get_thr_cgpu(thr_id);
  3637. if (cgpu) {
  3638. get_statline(logline, sizeof(logline), cgpu);
  3639. printf("\n%s\r", logline);
  3640. fflush(stdout);
  3641. }
  3642. }
  3643. #ifdef HAVE_CURSES
  3644. static int attr_bad = A_BOLD;
  3645. #ifdef WIN32
  3646. #define swprintf snwprintf
  3647. #endif
  3648. static
  3649. void bfg_waddstr(WINDOW *win, const char *s)
  3650. {
  3651. const char *p = s;
  3652. int32_t w;
  3653. int wlen;
  3654. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3655. while (true)
  3656. {
  3657. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3658. {
  3659. // Printable ASCII
  3660. ++p;
  3661. }
  3662. if (p != s)
  3663. waddnstr(win, s, p - s);
  3664. w = utf8_decode(p, &wlen);
  3665. s = p += wlen;
  3666. switch(w)
  3667. {
  3668. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3669. case '\0':
  3670. return;
  3671. case 0xb5: // micro symbol
  3672. w = unicode_micro;
  3673. goto default_addch;
  3674. case 0xf000: // "bad" off
  3675. wattroff(win, attr_bad);
  3676. break;
  3677. case 0xf001: // "bad" on
  3678. wattron(win, attr_bad);
  3679. break;
  3680. #ifdef USE_UNICODE
  3681. case '|':
  3682. wadd_wch(win, WACS_VLINE);
  3683. break;
  3684. #endif
  3685. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3686. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3687. if (!use_unicode)
  3688. {
  3689. waddch(win, '-');
  3690. break;
  3691. }
  3692. #ifdef USE_UNICODE
  3693. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3694. break;
  3695. #endif
  3696. case 0x2022:
  3697. if (w > WCHAR_MAX || !iswprint(w))
  3698. w = '*';
  3699. default:
  3700. default_addch:
  3701. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3702. {
  3703. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3704. if (iswprint(REPLACEMENT_CHAR))
  3705. w = REPLACEMENT_CHAR;
  3706. else
  3707. #endif
  3708. w = '?';
  3709. }
  3710. {
  3711. #ifdef USE_UNICODE
  3712. wchar_t wbuf[0x10];
  3713. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3714. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3715. waddnwstr(win, wbuf, wbuflen);
  3716. #else
  3717. wprintw(win, "%lc", (wint_t)w);
  3718. #endif
  3719. }
  3720. }
  3721. }
  3722. }
  3723. static inline
  3724. void bfg_hline(WINDOW *win, int y)
  3725. {
  3726. int maxx, __maybe_unused maxy;
  3727. getmaxyx(win, maxy, maxx);
  3728. #ifdef USE_UNICODE
  3729. if (use_unicode)
  3730. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3731. else
  3732. #endif
  3733. mvwhline(win, y, 0, '-', maxx);
  3734. }
  3735. static
  3736. int bfg_win_linelen(WINDOW * const win)
  3737. {
  3738. int maxx;
  3739. int __maybe_unused y;
  3740. getmaxyx(win, y, maxx);
  3741. return maxx;
  3742. }
  3743. // Spaces until end of line, using current attributes (ie, not completely clear)
  3744. static
  3745. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3746. {
  3747. int x, maxx;
  3748. int __maybe_unused y;
  3749. getmaxyx(win, y, maxx);
  3750. getyx(win, y, x);
  3751. const int space_count = (maxx - x) - offset;
  3752. // Check for negative - terminal too narrow
  3753. if (space_count <= 0)
  3754. return;
  3755. char buf[space_count];
  3756. memset(buf, ' ', space_count);
  3757. waddnstr(win, buf, space_count);
  3758. }
  3759. static int menu_attr = A_REVERSE;
  3760. #define CURBUFSIZ 256
  3761. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3762. char tmp42[CURBUFSIZ]; \
  3763. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3764. wmove(win, y, x); \
  3765. bfg_waddstr(win, tmp42); \
  3766. } while (0)
  3767. #define cg_wprintw(win, fmt, ...) do { \
  3768. char tmp42[CURBUFSIZ]; \
  3769. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3770. bfg_waddstr(win, tmp42); \
  3771. } while (0)
  3772. static
  3773. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3774. {
  3775. struct blockchain_info * const blkchain = goal->blkchain;
  3776. struct block_info * const blkinfo = blkchain->currentblk;
  3777. double income;
  3778. char incomestr[ALLOC_H2B_SHORT+6+1];
  3779. if (blkinfo->height)
  3780. {
  3781. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  3782. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3783. }
  3784. else
  3785. strcpy(incomestr, "?");
  3786. int linelen = bfg_win_linelen(statuswin);
  3787. wmove(statuswin, blky, 0);
  3788. bfg_waddstr(statuswin, " Block");
  3789. if (!goal->is_default)
  3790. linelen -= strlen(goal->name) + 1;
  3791. linelen -= 6; // " Block"
  3792. if (blkinfo->height && blkinfo->height < 1000000)
  3793. {
  3794. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  3795. linelen -= 8;
  3796. }
  3797. bfg_waddstr(statuswin, ":");
  3798. if (linelen > 55)
  3799. bfg_waddstr(statuswin, " ");
  3800. if (linelen >= 65)
  3801. bfg_waddstr(statuswin, "...");
  3802. {
  3803. char hexpbh[0x11];
  3804. if (!(blkinfo->height && blkinfo->height < 1000000))
  3805. {
  3806. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  3807. bfg_waddstr(statuswin, hexpbh);
  3808. }
  3809. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  3810. bfg_waddstr(statuswin, hexpbh);
  3811. }
  3812. if (linelen >= 55)
  3813. bfg_waddstr(statuswin, " ");
  3814. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  3815. if (linelen >= 69)
  3816. bfg_waddstr(statuswin, " ");
  3817. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  3818. if (linelen >= 62)
  3819. {
  3820. if (linelen >= 69)
  3821. bfg_waddstr(statuswin, " ");
  3822. bfg_waddstr(statuswin, "Started:");
  3823. }
  3824. else
  3825. bfg_waddstr(statuswin, "S:");
  3826. if (linelen >= 69)
  3827. bfg_waddstr(statuswin, " ");
  3828. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  3829. if (linelen >= 69)
  3830. bfg_waddstr(statuswin, " ");
  3831. cg_wprintw(statuswin, " I:%s", incomestr);
  3832. if (!goal->is_default)
  3833. cg_wprintw(statuswin, " %s", goal->name);
  3834. wclrtoeol(statuswin);
  3835. }
  3836. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  3837. static
  3838. void update_block_display(void)
  3839. {
  3840. struct mining_goal_info *goal, *tmpgoal;
  3841. int blky = 3, i, total_found_goals = 0;
  3842. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  3843. {
  3844. for (i = 0; i < total_pools; ++i)
  3845. {
  3846. struct pool * const pool = pools[i];
  3847. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  3848. break;
  3849. }
  3850. if (i >= total_pools)
  3851. // no pools using this goal, so it's probably stale anyway
  3852. continue;
  3853. update_block_display_line(blky++, goal);
  3854. ++total_found_goals;
  3855. }
  3856. if (total_found_goals != active_goals)
  3857. {
  3858. active_goals = total_found_goals;
  3859. devcursor = 7 + active_goals;
  3860. switch_logsize();
  3861. }
  3862. }
  3863. static bool pool_unworkable(const struct pool *);
  3864. /* Must be called with curses mutex lock held and curses_active */
  3865. static void curses_print_status(const int ts)
  3866. {
  3867. struct pool *pool = currentpool;
  3868. struct timeval now, tv;
  3869. float efficiency;
  3870. int logdiv;
  3871. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3872. wattron(statuswin, attr_title);
  3873. const int linelen = bfg_win_linelen(statuswin);
  3874. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  3875. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  3876. if (titlelen + 17 < linelen)
  3877. cg_wprintw(statuswin, "version ");
  3878. cg_wprintw(statuswin, VERSION " - ");
  3879. if (titlelen + 9 < linelen)
  3880. cg_wprintw(statuswin, "Started: ");
  3881. else
  3882. if (titlelen + 7 <= linelen)
  3883. cg_wprintw(statuswin, "Start: ");
  3884. cg_wprintw(statuswin, "%s", datestamp);
  3885. timer_set_now(&now);
  3886. {
  3887. unsigned int days, hours;
  3888. div_t d;
  3889. timersub(&now, &miner_started, &tv);
  3890. d = div(tv.tv_sec, 86400);
  3891. days = d.quot;
  3892. d = div(d.rem, 3600);
  3893. hours = d.quot;
  3894. d = div(d.rem, 60);
  3895. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3896. , days
  3897. , (days == 1) ? ' ' : 's'
  3898. , hours
  3899. , d.quot
  3900. , d.rem
  3901. );
  3902. }
  3903. bfg_wspctoeol(statuswin, 0);
  3904. wattroff(statuswin, attr_title);
  3905. wattron(statuswin, menu_attr);
  3906. wmove(statuswin, 1, 0);
  3907. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3908. bfg_wspctoeol(statuswin, 14);
  3909. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3910. wattroff(statuswin, menu_attr);
  3911. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  3912. char poolinfo[20], poolinfo2[20];
  3913. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  3914. double lowdiff = DBL_MAX, highdiff = -1;
  3915. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  3916. time_t oldest_work_restart = time(NULL) + 1;
  3917. struct pool *oldest_work_restart_pool = pools[0];
  3918. for (int i = 0; i < total_pools; ++i)
  3919. {
  3920. if (pool_unworkable(pools[i]))
  3921. continue;
  3922. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  3923. pool = pools[i];
  3924. ++workable_pools;
  3925. if (poolinfooff < sizeof(poolinfo))
  3926. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  3927. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  3928. if (pool_stats->last_diff < lowdiff)
  3929. {
  3930. lowdiff = pool_stats->last_diff;
  3931. lowdiff_pool = pool;
  3932. }
  3933. if (pool_stats->last_diff > highdiff)
  3934. {
  3935. highdiff = pool_stats->last_diff;
  3936. highdiff_pool = pool;
  3937. }
  3938. if (oldest_work_restart >= pool->work_restart_time)
  3939. {
  3940. oldest_work_restart = pool->work_restart_time;
  3941. oldest_work_restart_pool = pool;
  3942. }
  3943. }
  3944. if (unlikely(!workable_pools))
  3945. goto no_workable_pools;
  3946. if (workable_pools == 1)
  3947. goto one_workable_pool;
  3948. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  3949. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  3950. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  3951. else
  3952. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  3953. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  3954. poolinfo2,
  3955. lowdiff_pool->diff,
  3956. (lowdiff == highdiff) ? "" : "-",
  3957. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  3958. have_longpoll ? '+' : '-',
  3959. oldest_work_restart_pool->work_restart_timestamp);
  3960. }
  3961. else
  3962. if (pool_unworkable(pool))
  3963. {
  3964. no_workable_pools: ;
  3965. wattron(statuswin, attr_bad);
  3966. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  3967. wattroff(statuswin, attr_bad);
  3968. }
  3969. else
  3970. {
  3971. one_workable_pool: ;
  3972. char pooladdr[19];
  3973. {
  3974. const char *rawaddr = pool->sockaddr_url;
  3975. BFGINIT(rawaddr, pool->rpc_url);
  3976. size_t pooladdrlen = strlen(rawaddr);
  3977. if (pooladdrlen > 20)
  3978. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  3979. else
  3980. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  3981. }
  3982. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  3983. pool->pool_no, pooladdr, pool->diff,
  3984. have_longpoll ? '+' : '-', pool_proto_str(pool),
  3985. pool->work_restart_timestamp,
  3986. pool->rpc_user);
  3987. }
  3988. wclrtoeol(statuswin);
  3989. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  3990. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  3991. ts,
  3992. total_go + total_ro,
  3993. new_blocks,
  3994. total_submitting,
  3995. multi_format_unit2(bwstr, sizeof(bwstr),
  3996. false, "B/s", H2B_SHORT, "/", 2,
  3997. (float)(total_bytes_rcvd / total_secs),
  3998. (float)(total_bytes_sent / total_secs)),
  3999. efficiency,
  4000. best_share);
  4001. wclrtoeol(statuswin);
  4002. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4003. bfg_waddstr(statuswin, statusline);
  4004. wclrtoeol(statuswin);
  4005. int devdiv = devcursor - 2;
  4006. logdiv = statusy - 1;
  4007. bfg_hline(statuswin, devdiv);
  4008. bfg_hline(statuswin, logdiv);
  4009. #ifdef USE_UNICODE
  4010. if (use_unicode)
  4011. {
  4012. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4013. if (opt_show_procs && !opt_compact)
  4014. offset += max_lpdigits; // proc letter(s)
  4015. if (have_unicode_degrees)
  4016. ++offset; // degrees symbol
  4017. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4018. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4019. offset += 24; // hashrates etc
  4020. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4021. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4022. }
  4023. #endif
  4024. }
  4025. static void adj_width(int var, int *length)
  4026. {
  4027. if ((int)(log10(var) + 1) > *length)
  4028. (*length)++;
  4029. }
  4030. static int dev_width;
  4031. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4032. {
  4033. char logline[256];
  4034. int ypos;
  4035. if (opt_compact)
  4036. return;
  4037. /* Check this isn't out of the window size */
  4038. if (opt_show_procs)
  4039. ypos = cgpu->cgminer_id;
  4040. else
  4041. {
  4042. if (cgpu->proc_id)
  4043. return;
  4044. ypos = cgpu->device_line_id;
  4045. }
  4046. ypos += devsummaryYOffset;
  4047. if (ypos < 0)
  4048. return;
  4049. ypos += devcursor - 1;
  4050. if (ypos >= statusy - 1)
  4051. return;
  4052. if (wmove(statuswin, ypos, 0) == ERR)
  4053. return;
  4054. get_statline2(logline, sizeof(logline), cgpu, true);
  4055. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4056. wattron(statuswin, A_REVERSE);
  4057. bfg_waddstr(statuswin, logline);
  4058. wattroff(statuswin, A_REVERSE);
  4059. wclrtoeol(statuswin);
  4060. }
  4061. static
  4062. void _refresh_devstatus(const bool already_have_lock) {
  4063. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4064. int i;
  4065. if (unlikely(!total_devices))
  4066. {
  4067. const int ypos = devcursor - 1;
  4068. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4069. {
  4070. wattron(statuswin, attr_bad);
  4071. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4072. wclrtoeol(statuswin);
  4073. wattroff(statuswin, attr_bad);
  4074. }
  4075. }
  4076. for (i = 0; i < total_devices; i++)
  4077. curses_print_devstatus(get_devices(i));
  4078. touchwin(statuswin);
  4079. wrefresh(statuswin);
  4080. if (!already_have_lock)
  4081. unlock_curses();
  4082. }
  4083. }
  4084. #define refresh_devstatus() _refresh_devstatus(false)
  4085. #endif
  4086. static void print_status(int thr_id)
  4087. {
  4088. if (!curses_active)
  4089. text_print_status(thr_id);
  4090. }
  4091. #ifdef HAVE_CURSES
  4092. static
  4093. bool set_statusy(int maxy)
  4094. {
  4095. if (loginput_size)
  4096. {
  4097. maxy -= loginput_size;
  4098. if (maxy < 0)
  4099. maxy = 0;
  4100. }
  4101. if (logstart < maxy)
  4102. maxy = logstart;
  4103. if (statusy == maxy)
  4104. return false;
  4105. statusy = maxy;
  4106. logcursor = statusy;
  4107. return true;
  4108. }
  4109. /* Check for window resize. Called with curses mutex locked */
  4110. static inline void change_logwinsize(void)
  4111. {
  4112. int x, y, logx, logy;
  4113. getmaxyx(mainwin, y, x);
  4114. if (x < 80 || y < 25)
  4115. return;
  4116. if (y > statusy + 2 && statusy < logstart) {
  4117. set_statusy(y - 2);
  4118. mvwin(logwin, logcursor, 0);
  4119. bfg_wresize(statuswin, statusy, x);
  4120. }
  4121. y -= logcursor;
  4122. getmaxyx(logwin, logy, logx);
  4123. /* Detect screen size change */
  4124. if (x != logx || y != logy)
  4125. bfg_wresize(logwin, y, x);
  4126. }
  4127. static void check_winsizes(void)
  4128. {
  4129. if (!use_curses)
  4130. return;
  4131. if (curses_active_locked()) {
  4132. int y, x;
  4133. x = getmaxx(statuswin);
  4134. if (set_statusy(LINES - 2))
  4135. {
  4136. erase();
  4137. bfg_wresize(statuswin, statusy, x);
  4138. getmaxyx(mainwin, y, x);
  4139. y -= logcursor;
  4140. bfg_wresize(logwin, y, x);
  4141. mvwin(logwin, logcursor, 0);
  4142. }
  4143. unlock_curses();
  4144. }
  4145. }
  4146. static int device_line_id_count;
  4147. static void switch_logsize(void)
  4148. {
  4149. if (curses_active_locked()) {
  4150. if (opt_compact) {
  4151. logstart = devcursor - 1;
  4152. logcursor = logstart + 1;
  4153. } else {
  4154. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4155. logstart = devcursor + total_lines;
  4156. logcursor = logstart;
  4157. }
  4158. unlock_curses();
  4159. }
  4160. check_winsizes();
  4161. update_block_display();
  4162. }
  4163. /* For mandatory printing when mutex is already locked */
  4164. void _wlog(const char *str)
  4165. {
  4166. static bool newline;
  4167. size_t end = strlen(str) - 1;
  4168. if (newline)
  4169. bfg_waddstr(logwin, "\n");
  4170. if (str[end] == '\n')
  4171. {
  4172. char *s;
  4173. newline = true;
  4174. s = alloca(end + 1);
  4175. memcpy(s, str, end);
  4176. s[end] = '\0';
  4177. str = s;
  4178. }
  4179. else
  4180. newline = false;
  4181. bfg_waddstr(logwin, str);
  4182. }
  4183. /* Mandatory printing */
  4184. void _wlogprint(const char *str)
  4185. {
  4186. if (curses_active_locked()) {
  4187. _wlog(str);
  4188. unlock_curses();
  4189. }
  4190. }
  4191. #endif
  4192. #ifdef HAVE_CURSES
  4193. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4194. {
  4195. bool high_prio;
  4196. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4197. if (curses_active)
  4198. {
  4199. if (!loginput_size || high_prio) {
  4200. wlog(" %s %s\n", datetime, str);
  4201. if (high_prio) {
  4202. touchwin(logwin);
  4203. wrefresh(logwin);
  4204. }
  4205. }
  4206. return true;
  4207. }
  4208. return false;
  4209. }
  4210. void clear_logwin(void)
  4211. {
  4212. if (curses_active_locked()) {
  4213. wclear(logwin);
  4214. unlock_curses();
  4215. }
  4216. }
  4217. void logwin_update(void)
  4218. {
  4219. if (curses_active_locked()) {
  4220. touchwin(logwin);
  4221. wrefresh(logwin);
  4222. unlock_curses();
  4223. }
  4224. }
  4225. #endif
  4226. void enable_pool(struct pool * const pool)
  4227. {
  4228. if (pool->enabled != POOL_ENABLED) {
  4229. mutex_lock(&lp_lock);
  4230. enabled_pools++;
  4231. pool->enabled = POOL_ENABLED;
  4232. pthread_cond_broadcast(&lp_cond);
  4233. mutex_unlock(&lp_lock);
  4234. if (pool->prio < current_pool()->prio)
  4235. switch_pools(pool);
  4236. }
  4237. }
  4238. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4239. {
  4240. if (pool->enabled == POOL_DISABLED)
  4241. /* had been manually disabled before */
  4242. return;
  4243. if (pool->enabled != POOL_ENABLED)
  4244. {
  4245. /* has been programmatically disabled already, just change to the new status directly */
  4246. pool->enabled = enable_status;
  4247. return;
  4248. }
  4249. /* Fall into the lock area */
  4250. mutex_lock(&lp_lock);
  4251. --enabled_pools;
  4252. pool->enabled = enable_status;
  4253. mutex_unlock(&lp_lock);
  4254. if (pool == current_pool())
  4255. switch_pools(NULL);
  4256. }
  4257. static
  4258. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4259. struct cgpu_info *cgpu;
  4260. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  4261. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4262. const double tgtdiff = work->work_difficulty;
  4263. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4264. char where[20];
  4265. cgpu = get_thr_cgpu(work->thr_id);
  4266. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4267. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4268. if (total_pools > 1)
  4269. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4270. else
  4271. where[0] = '\0';
  4272. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4273. disp,
  4274. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4275. cgpu->proc_repr,
  4276. where,
  4277. shrdiffdisp, tgtdiffdisp,
  4278. reason,
  4279. resubmit ? "(resubmit)" : "",
  4280. worktime
  4281. );
  4282. }
  4283. static bool test_work_current(struct work *);
  4284. static void _submit_work_async(struct work *);
  4285. static
  4286. void maybe_local_submit(const struct work *work)
  4287. {
  4288. #if BLKMAKER_VERSION > 3
  4289. if (unlikely(work->block && work->tr))
  4290. {
  4291. // This is a block with a full template (GBT)
  4292. // Regardless of the result, submit to local bitcoind(s) as well
  4293. struct work *work_cp;
  4294. for (int i = 0; i < total_pools; ++i)
  4295. {
  4296. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4297. continue;
  4298. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4299. work_cp = copy_work(work);
  4300. work_cp->pool = pools[i];
  4301. work_cp->do_foreign_submit = true;
  4302. _submit_work_async(work_cp);
  4303. }
  4304. }
  4305. #endif
  4306. }
  4307. static
  4308. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4309. {
  4310. if (json_is_string(res))
  4311. return res;
  4312. if ( (res = json_object_get(val, "reject-reason")) )
  4313. return res;
  4314. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4315. return res;
  4316. return NULL;
  4317. }
  4318. static
  4319. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4320. {
  4321. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4322. return j ? json_string_value(j) : NULL;
  4323. }
  4324. static
  4325. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4326. {
  4327. if (!s)
  4328. {
  4329. if (bufsz)
  4330. buf[0] = '\0';
  4331. return 0;
  4332. }
  4333. int p = snprintf(buf, bufsz, " (%s", s);
  4334. if (p >= bufsz - 1)
  4335. p = bufsz - 2;
  4336. strcpy(&buf[p], ")");
  4337. return p + 1;
  4338. }
  4339. /* Theoretically threads could race when modifying accepted and
  4340. * rejected values but the chance of two submits completing at the
  4341. * same time is zero so there is no point adding extra locking */
  4342. static void
  4343. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4344. /*char *hashshow,*/ bool resubmit, char *worktime)
  4345. {
  4346. struct pool *pool = work->pool;
  4347. struct cgpu_info *cgpu;
  4348. cgpu = get_thr_cgpu(work->thr_id);
  4349. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4350. struct mining_goal_info * const goal = pool->goal;
  4351. mutex_lock(&stats_lock);
  4352. cgpu->accepted++;
  4353. total_accepted++;
  4354. pool->accepted++;
  4355. cgpu->diff_accepted += work->work_difficulty;
  4356. total_diff_accepted += work->work_difficulty;
  4357. pool->diff_accepted += work->work_difficulty;
  4358. goal->diff_accepted += work->work_difficulty;
  4359. mutex_unlock(&stats_lock);
  4360. pool->seq_rejects = 0;
  4361. cgpu->last_share_pool = pool->pool_no;
  4362. cgpu->last_share_pool_time = time(NULL);
  4363. cgpu->last_share_diff = work->work_difficulty;
  4364. pool->last_share_time = cgpu->last_share_pool_time;
  4365. pool->last_share_diff = work->work_difficulty;
  4366. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4367. if (!QUIET) {
  4368. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4369. }
  4370. sharelog("accept", work);
  4371. if (opt_shares && total_diff_accepted >= opt_shares) {
  4372. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4373. kill_work();
  4374. return;
  4375. }
  4376. /* Detect if a pool that has been temporarily disabled for
  4377. * continually rejecting shares has started accepting shares.
  4378. * This will only happen with the work returned from a
  4379. * longpoll */
  4380. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4381. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4382. enable_pool(pool);
  4383. }
  4384. if (unlikely(work->block)) {
  4385. // Force moving on to this new block :)
  4386. struct work fakework;
  4387. memset(&fakework, 0, sizeof(fakework));
  4388. fakework.pool = work->pool;
  4389. // Copy block version, bits, and time from share
  4390. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4391. memcpy(&fakework.data[68], &work->data[68], 8);
  4392. // Set prevblock to winning hash (swap32'd)
  4393. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4394. test_work_current(&fakework);
  4395. }
  4396. }
  4397. else
  4398. if (!hash_target_check(work->hash, work->target))
  4399. {
  4400. // This was submitted despite failing the proper target
  4401. // Quietly ignore the reject
  4402. char reason[32];
  4403. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4404. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4405. } else {
  4406. mutex_lock(&stats_lock);
  4407. cgpu->rejected++;
  4408. total_rejected++;
  4409. pool->rejected++;
  4410. cgpu->diff_rejected += work->work_difficulty;
  4411. total_diff_rejected += work->work_difficulty;
  4412. pool->diff_rejected += work->work_difficulty;
  4413. pool->seq_rejects++;
  4414. mutex_unlock(&stats_lock);
  4415. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4416. if (!QUIET) {
  4417. char disposition[36] = "reject";
  4418. char reason[32];
  4419. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4420. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4421. if (reason[0])
  4422. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4423. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4424. sharelog(disposition, work);
  4425. }
  4426. /* Once we have more than a nominal amount of sequential rejects,
  4427. * at least 10 and more than 3 mins at the current utility,
  4428. * disable the pool because some pool error is likely to have
  4429. * ensued. Do not do this if we know the share just happened to
  4430. * be stale due to networking delays.
  4431. */
  4432. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4433. double utility = total_accepted / total_secs * 60;
  4434. if (pool->seq_rejects > utility * 3) {
  4435. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4436. pool->pool_no, pool->seq_rejects);
  4437. disable_pool(pool, POOL_REJECTING);
  4438. pool->seq_rejects = 0;
  4439. }
  4440. }
  4441. }
  4442. maybe_local_submit(work);
  4443. }
  4444. static char *submit_upstream_work_request(struct work *work)
  4445. {
  4446. char *hexstr = NULL;
  4447. char *s, *sd;
  4448. struct pool *pool = work->pool;
  4449. if (work->tr)
  4450. {
  4451. blktemplate_t * const tmpl = work->tr->tmpl;
  4452. json_t *req;
  4453. unsigned char data[80];
  4454. swap32yes(data, work->data, 80 / 4);
  4455. #if BLKMAKER_VERSION > 3
  4456. if (work->do_foreign_submit)
  4457. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4458. else
  4459. #endif
  4460. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4461. s = json_dumps(req, 0);
  4462. json_decref(req);
  4463. sd = malloc(161);
  4464. bin2hex(sd, data, 80);
  4465. } else {
  4466. /* build hex string */
  4467. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4468. bin2hex(hexstr, work->data, sizeof(work->data));
  4469. /* build JSON-RPC request */
  4470. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4471. s = realloc_strcat(s, hexstr);
  4472. s = realloc_strcat(s, "\" ], \"id\":1}");
  4473. free(hexstr);
  4474. sd = s;
  4475. }
  4476. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4477. if (work->tr)
  4478. free(sd);
  4479. else
  4480. s = realloc_strcat(s, "\n");
  4481. return s;
  4482. }
  4483. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4484. json_t *res, *err;
  4485. bool rc = false;
  4486. int thr_id = work->thr_id;
  4487. struct pool *pool = work->pool;
  4488. struct timeval tv_submit_reply;
  4489. time_t ts_submit_reply;
  4490. char worktime[200] = "";
  4491. cgtime(&tv_submit_reply);
  4492. ts_submit_reply = time(NULL);
  4493. if (unlikely(!val)) {
  4494. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4495. if (!pool_tset(pool, &pool->submit_fail)) {
  4496. total_ro++;
  4497. pool->remotefail_occasions++;
  4498. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4499. }
  4500. goto out;
  4501. } else if (pool_tclear(pool, &pool->submit_fail))
  4502. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4503. res = json_object_get(val, "result");
  4504. err = json_object_get(val, "error");
  4505. if (!QUIET) {
  4506. if (opt_worktime) {
  4507. char workclone[20];
  4508. struct tm _tm;
  4509. struct tm *tm, tm_getwork, tm_submit_reply;
  4510. tm = &_tm;
  4511. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4512. (struct timeval *)&(work->tv_getwork));
  4513. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4514. (struct timeval *)&(work->tv_getwork_reply));
  4515. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4516. (struct timeval *)&(work->tv_work_start));
  4517. double work_to_submit = tdiff(ptv_submit,
  4518. (struct timeval *)&(work->tv_work_found));
  4519. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4520. int diffplaces = 3;
  4521. localtime_r(&work->ts_getwork, tm);
  4522. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4523. localtime_r(&ts_submit_reply, tm);
  4524. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4525. if (work->clone) {
  4526. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4527. tdiff((struct timeval *)&(work->tv_cloned),
  4528. (struct timeval *)&(work->tv_getwork_reply)));
  4529. }
  4530. else
  4531. strcpy(workclone, "O");
  4532. if (work->work_difficulty < 1)
  4533. diffplaces = 6;
  4534. snprintf(worktime, sizeof(worktime),
  4535. " <-%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",
  4536. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  4537. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  4538. work->getwork_mode, diffplaces, work->work_difficulty,
  4539. tm_getwork.tm_hour, tm_getwork.tm_min,
  4540. tm_getwork.tm_sec, getwork_time, workclone,
  4541. getwork_to_work, work_time, work_to_submit, submit_time,
  4542. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4543. tm_submit_reply.tm_sec);
  4544. }
  4545. }
  4546. share_result(val, res, err, work, resubmit, worktime);
  4547. if (!opt_realquiet)
  4548. print_status(thr_id);
  4549. if (!want_per_device_stats) {
  4550. char logline[256];
  4551. struct cgpu_info *cgpu;
  4552. cgpu = get_thr_cgpu(thr_id);
  4553. get_statline(logline, sizeof(logline), cgpu);
  4554. applog(LOG_INFO, "%s", logline);
  4555. }
  4556. json_decref(val);
  4557. rc = true;
  4558. out:
  4559. return rc;
  4560. }
  4561. /* Specifies whether we can use this pool for work or not. */
  4562. static bool pool_unworkable(const struct pool * const pool)
  4563. {
  4564. if (pool->idle)
  4565. return true;
  4566. if (pool->enabled != POOL_ENABLED)
  4567. return true;
  4568. if (pool->has_stratum && !pool->stratum_active)
  4569. return true;
  4570. return false;
  4571. }
  4572. static
  4573. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4574. {
  4575. if (pool->enabled != POOL_ENABLED)
  4576. return false;
  4577. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4578. return true;
  4579. if (!cp)
  4580. cp = current_pool();
  4581. return (pool == cp);
  4582. }
  4583. static
  4584. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4585. {
  4586. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4587. }
  4588. static
  4589. bool pool_supports_block_change_notification(struct pool * const pool)
  4590. {
  4591. return pool->has_stratum || pool->lp_url;
  4592. }
  4593. static
  4594. bool pool_has_active_block_change_notification(struct pool * const pool)
  4595. {
  4596. return pool->stratum_active || pool->lp_active;
  4597. }
  4598. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4599. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4600. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4601. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4602. * rolling average per 10 minutes and if pools start getting more, it biases
  4603. * away from them to distribute work evenly. The share count is reset to the
  4604. * rolling average every 10 minutes to not send all work to one pool after it
  4605. * has been disabled/out for an extended period. */
  4606. static struct pool *select_balanced(struct pool *cp)
  4607. {
  4608. int i, lowest = cp->shares;
  4609. struct pool *ret = cp, *failover_pool = NULL;
  4610. for (i = 0; i < total_pools; i++) {
  4611. struct pool *pool = pools[i];
  4612. if (pool_unworkable(pool))
  4613. continue;
  4614. if (pool->failover_only)
  4615. {
  4616. BFGINIT(failover_pool, pool);
  4617. continue;
  4618. }
  4619. if (pool->shares < lowest) {
  4620. lowest = pool->shares;
  4621. ret = pool;
  4622. }
  4623. }
  4624. if (pool_unworkable(ret) && failover_pool)
  4625. ret = failover_pool;
  4626. ret->shares++;
  4627. return ret;
  4628. }
  4629. static bool pool_active(struct pool *, bool pinging);
  4630. static void pool_died(struct pool *);
  4631. static struct pool *priority_pool(int choice);
  4632. static bool pool_unusable(struct pool *pool);
  4633. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4634. * it has any quota left. */
  4635. static inline struct pool *select_pool(bool lagging)
  4636. {
  4637. static int rotating_pool = 0;
  4638. struct pool *pool, *cp;
  4639. bool avail = false;
  4640. int tested, i;
  4641. retry:
  4642. cp = current_pool();
  4643. if (pool_strategy == POOL_BALANCE) {
  4644. pool = select_balanced(cp);
  4645. if (pool_unworkable(pool))
  4646. goto simple_failover;
  4647. goto out;
  4648. }
  4649. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4650. pool = cp;
  4651. goto out;
  4652. } else
  4653. pool = NULL;
  4654. for (i = 0; i < total_pools; i++) {
  4655. struct pool *tp = pools[i];
  4656. if (tp->quota_used < tp->quota_gcd) {
  4657. avail = true;
  4658. break;
  4659. }
  4660. }
  4661. /* There are no pools with quota, so reset them. */
  4662. if (!avail) {
  4663. for (i = 0; i < total_pools; i++)
  4664. pools[i]->quota_used = 0;
  4665. if (++rotating_pool >= total_pools)
  4666. rotating_pool = 0;
  4667. }
  4668. /* Try to find the first pool in the rotation that is usable */
  4669. tested = 0;
  4670. while (!pool && tested++ < total_pools) {
  4671. pool = pools[rotating_pool];
  4672. if (pool->quota_used++ < pool->quota_gcd) {
  4673. if (!pool_unworkable(pool))
  4674. break;
  4675. /* Failover-only flag for load-balance means distribute
  4676. * unused quota to priority pool 0. */
  4677. if (opt_fail_only)
  4678. priority_pool(0)->quota_used--;
  4679. }
  4680. pool = NULL;
  4681. if (++rotating_pool >= total_pools)
  4682. rotating_pool = 0;
  4683. }
  4684. simple_failover:
  4685. /* If there are no alive pools with quota, choose according to
  4686. * priority. */
  4687. if (!pool) {
  4688. for (i = 0; i < total_pools; i++) {
  4689. struct pool *tp = priority_pool(i);
  4690. if (!pool_unusable(tp)) {
  4691. pool = tp;
  4692. break;
  4693. }
  4694. }
  4695. }
  4696. /* If still nothing is usable, use the current pool */
  4697. if (!pool)
  4698. pool = cp;
  4699. out:
  4700. if (!pool_actively_in_use(pool, cp))
  4701. {
  4702. if (!pool_active(pool, false))
  4703. {
  4704. pool_died(pool);
  4705. goto retry;
  4706. }
  4707. pool_tclear(pool, &pool->idle);
  4708. }
  4709. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4710. return pool;
  4711. }
  4712. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4713. double target_diff(const unsigned char *target)
  4714. {
  4715. double targ = 0;
  4716. signed int i;
  4717. for (i = 31; i >= 0; --i)
  4718. targ = (targ * 0x100) + target[i];
  4719. return DIFFEXACTONE / (targ ?: 1);
  4720. }
  4721. /*
  4722. * Calculate the work share difficulty
  4723. */
  4724. static void calc_diff(struct work *work, int known)
  4725. {
  4726. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4727. double difficulty;
  4728. if (!known) {
  4729. work->work_difficulty = target_diff(work->target);
  4730. } else
  4731. work->work_difficulty = known;
  4732. difficulty = work->work_difficulty;
  4733. pool_stats->last_diff = difficulty;
  4734. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4735. if (difficulty == pool_stats->min_diff)
  4736. pool_stats->min_diff_count++;
  4737. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4738. pool_stats->min_diff = difficulty;
  4739. pool_stats->min_diff_count = 1;
  4740. }
  4741. if (difficulty == pool_stats->max_diff)
  4742. pool_stats->max_diff_count++;
  4743. else if (difficulty > pool_stats->max_diff) {
  4744. pool_stats->max_diff = difficulty;
  4745. pool_stats->max_diff_count = 1;
  4746. }
  4747. }
  4748. static void gen_stratum_work(struct pool *, struct work *);
  4749. static void pool_update_work_restart_time(struct pool *);
  4750. static void restart_threads(void);
  4751. static uint32_t benchmark_blkhdr[20];
  4752. static const int benchmark_update_interval = 1;
  4753. static
  4754. void *benchmark_intense_work_update_thread(void *userp)
  4755. {
  4756. pthread_detach(pthread_self());
  4757. RenameThread("benchmark-intense");
  4758. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4759. struct pool * const pool = userp;
  4760. struct stratum_work * const swork = &pool->swork;
  4761. uint8_t * const blkhdr = swork->header1;
  4762. while (true)
  4763. {
  4764. sleep(benchmark_update_interval);
  4765. cg_wlock(&pool->data_lock);
  4766. for (int i = 36; --i >= 0; )
  4767. if (++blkhdr[i])
  4768. break;
  4769. cg_wunlock(&pool->data_lock);
  4770. struct work *work = make_work();
  4771. gen_stratum_work(pool, work);
  4772. pool->swork.work_restart_id = ++pool->work_restart_id;
  4773. pool_update_work_restart_time(pool);
  4774. test_work_current(work);
  4775. free_work(work);
  4776. restart_threads();
  4777. }
  4778. return NULL;
  4779. }
  4780. static
  4781. void setup_benchmark_pool()
  4782. {
  4783. struct pool *pool;
  4784. want_longpoll = false;
  4785. // Temporarily disable opt_benchmark to avoid auto-removal
  4786. opt_benchmark = false;
  4787. pool = add_pool();
  4788. opt_benchmark = true;
  4789. pool->rpc_url = malloc(255);
  4790. strcpy(pool->rpc_url, "Benchmark");
  4791. pool_set_uri(pool, pool->rpc_url);
  4792. pool->rpc_user = pool->rpc_url;
  4793. pool->rpc_pass = pool->rpc_url;
  4794. enable_pool(pool);
  4795. pool->idle = false;
  4796. successful_connect = true;
  4797. {
  4798. uint32_t * const blkhdr = benchmark_blkhdr;
  4799. blkhdr[2] = htobe32(1);
  4800. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  4801. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  4802. }
  4803. {
  4804. struct stratum_work * const swork = &pool->swork;
  4805. const int branchcount = 15; // 1 MB block
  4806. const size_t branchdatasz = branchcount * 0x20;
  4807. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  4808. bytes_resize(&swork->coinbase, coinbase_sz);
  4809. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  4810. swork->nonce2_offset = 0;
  4811. bytes_resize(&swork->merkle_bin, branchdatasz);
  4812. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  4813. swork->merkles = branchcount;
  4814. swork->header1[0] = '\xff';
  4815. memset(&swork->header1[1], '\0', 34);
  4816. swork->header1[35] = '\x01';
  4817. swork->ntime = 0x7fffffff;
  4818. timer_unset(&swork->tv_received);
  4819. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  4820. set_target_to_pdiff(swork->target, opt_scrypt ? (1./0x10000) : 1.);
  4821. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  4822. pool->nonce2 = 0;
  4823. }
  4824. if (opt_benchmark_intense)
  4825. {
  4826. pthread_t pth;
  4827. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  4828. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  4829. }
  4830. }
  4831. void get_benchmark_work(struct work *work, bool use_swork)
  4832. {
  4833. if (use_swork)
  4834. {
  4835. struct timeval tv_now;
  4836. timer_set_now(&tv_now);
  4837. gen_stratum_work(pools[0], work);
  4838. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4839. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  4840. return;
  4841. }
  4842. struct pool * const pool = pools[0];
  4843. uint32_t * const blkhdr = benchmark_blkhdr;
  4844. for (int i = 16; i >= 0; --i)
  4845. if (++blkhdr[i])
  4846. break;
  4847. memcpy(&work->data[ 0], blkhdr, 80);
  4848. memcpy(&work->data[80], workpadding_bin, 48);
  4849. char hex[161];
  4850. bin2hex(hex, work->data, 80);
  4851. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  4852. calc_midstate(work);
  4853. memcpy(work->target, pool->swork.target, sizeof(work->target));
  4854. work->mandatory = true;
  4855. work->pool = pools[0];
  4856. cgtime(&work->tv_getwork);
  4857. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4858. copy_time(&work->tv_staged, &work->tv_getwork);
  4859. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4860. calc_diff(work, 0);
  4861. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  4862. }
  4863. static void wake_gws(void);
  4864. static void update_last_work(struct work *work)
  4865. {
  4866. if (!work->tr)
  4867. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4868. return;
  4869. struct pool *pool = work->pool;
  4870. mutex_lock(&pool->last_work_lock);
  4871. if (pool->last_work_copy)
  4872. free_work(pool->last_work_copy);
  4873. pool->last_work_copy = copy_work(work);
  4874. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4875. mutex_unlock(&pool->last_work_lock);
  4876. }
  4877. static
  4878. void gbt_req_target(json_t *req)
  4879. {
  4880. json_t *j;
  4881. json_t *n;
  4882. if (!request_target_str)
  4883. return;
  4884. j = json_object_get(req, "params");
  4885. if (!j)
  4886. {
  4887. n = json_array();
  4888. if (!n)
  4889. return;
  4890. if (json_object_set_new(req, "params", n))
  4891. goto erradd;
  4892. j = n;
  4893. }
  4894. n = json_array_get(j, 0);
  4895. if (!n)
  4896. {
  4897. n = json_object();
  4898. if (!n)
  4899. return;
  4900. if (json_array_append_new(j, n))
  4901. goto erradd;
  4902. }
  4903. j = n;
  4904. n = json_string(request_target_str);
  4905. if (!n)
  4906. return;
  4907. if (json_object_set_new(j, "target", n))
  4908. goto erradd;
  4909. return;
  4910. erradd:
  4911. json_decref(n);
  4912. }
  4913. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  4914. {
  4915. char *rpc_req;
  4916. clean_work(work);
  4917. switch (proto) {
  4918. case PLP_GETWORK:
  4919. work->getwork_mode = GETWORK_MODE_POOL;
  4920. return strdup(getwork_req);
  4921. case PLP_GETBLOCKTEMPLATE:
  4922. work->getwork_mode = GETWORK_MODE_GBT;
  4923. blktemplate_t * const tmpl = blktmpl_create();
  4924. if (!tmpl)
  4925. goto gbtfail2;
  4926. work->tr = tmpl_makeref(tmpl);
  4927. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  4928. if (!caps)
  4929. goto gbtfail;
  4930. caps |= GBT_LONGPOLL;
  4931. #if BLKMAKER_VERSION > 1
  4932. if ((bytes_len(&opt_coinbase_script) || have_at_least_one_getcbaddr) && get_mining_goal("default") == pool->goal)
  4933. caps |= GBT_CBVALUE;
  4934. #endif
  4935. json_t *req = blktmpl_request_jansson(caps, lpid);
  4936. if (!req)
  4937. goto gbtfail;
  4938. if (probe)
  4939. gbt_req_target(req);
  4940. rpc_req = json_dumps(req, 0);
  4941. if (!rpc_req)
  4942. goto gbtfail;
  4943. json_decref(req);
  4944. return rpc_req;
  4945. default:
  4946. return NULL;
  4947. }
  4948. return NULL;
  4949. gbtfail:
  4950. tmpl_decref(work->tr);
  4951. work->tr = NULL;
  4952. gbtfail2:
  4953. return NULL;
  4954. }
  4955. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  4956. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  4957. static const char *pool_protocol_name(enum pool_protocol proto)
  4958. {
  4959. switch (proto) {
  4960. case PLP_GETBLOCKTEMPLATE:
  4961. return "getblocktemplate";
  4962. case PLP_GETWORK:
  4963. return "getwork";
  4964. default:
  4965. return "UNKNOWN";
  4966. }
  4967. }
  4968. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4969. {
  4970. switch (proto) {
  4971. case PLP_GETBLOCKTEMPLATE:
  4972. if (want_getwork)
  4973. return PLP_GETWORK;
  4974. default:
  4975. return PLP_NONE;
  4976. }
  4977. }
  4978. static bool get_upstream_work(struct work *work, CURL *curl)
  4979. {
  4980. struct pool *pool = work->pool;
  4981. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4982. struct timeval tv_elapsed;
  4983. json_t *val = NULL;
  4984. bool rc = false;
  4985. char *url;
  4986. enum pool_protocol proto;
  4987. char *rpc_req;
  4988. if (pool->proto == PLP_NONE)
  4989. pool->proto = PLP_GETBLOCKTEMPLATE;
  4990. tryagain:
  4991. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  4992. work->pool = pool;
  4993. if (!rpc_req)
  4994. return false;
  4995. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4996. url = pool->rpc_url;
  4997. cgtime(&work->tv_getwork);
  4998. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4999. false, &work->rolltime, pool, false);
  5000. pool_stats->getwork_attempts++;
  5001. free(rpc_req);
  5002. if (likely(val)) {
  5003. rc = work_decode(pool, work, val);
  5004. if (unlikely(!rc))
  5005. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5006. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5007. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5008. pool->proto = proto;
  5009. goto tryagain;
  5010. } else
  5011. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5012. cgtime(&work->tv_getwork_reply);
  5013. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5014. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5015. pool_stats->getwork_wait_rolling /= 1.63;
  5016. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5017. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5018. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5019. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5020. }
  5021. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5022. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5023. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5024. }
  5025. pool_stats->getwork_calls++;
  5026. work->pool = pool;
  5027. work->longpoll = false;
  5028. calc_diff(work, 0);
  5029. total_getworks++;
  5030. pool->getwork_requested++;
  5031. if (rc)
  5032. update_last_work(work);
  5033. if (likely(val))
  5034. json_decref(val);
  5035. return rc;
  5036. }
  5037. #ifdef HAVE_CURSES
  5038. static void disable_curses(void)
  5039. {
  5040. if (curses_active_locked()) {
  5041. use_curses = false;
  5042. curses_active = false;
  5043. leaveok(logwin, false);
  5044. leaveok(statuswin, false);
  5045. leaveok(mainwin, false);
  5046. nocbreak();
  5047. echo();
  5048. delwin(logwin);
  5049. delwin(statuswin);
  5050. delwin(mainwin);
  5051. endwin();
  5052. #ifdef WIN32
  5053. // Move the cursor to after curses output.
  5054. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5055. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5056. COORD coord;
  5057. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5058. coord.X = 0;
  5059. coord.Y = csbi.dwSize.Y - 1;
  5060. SetConsoleCursorPosition(hout, coord);
  5061. }
  5062. #endif
  5063. unlock_curses();
  5064. }
  5065. }
  5066. #endif
  5067. static void __kill_work(void)
  5068. {
  5069. struct cgpu_info *cgpu;
  5070. struct thr_info *thr;
  5071. int i;
  5072. if (!successful_connect)
  5073. return;
  5074. applog(LOG_INFO, "Received kill message");
  5075. shutting_down = true;
  5076. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5077. notifier_wake(submit_waiting_notifier);
  5078. #ifdef USE_LIBMICROHTTPD
  5079. httpsrv_stop();
  5080. #endif
  5081. applog(LOG_DEBUG, "Killing off watchpool thread");
  5082. /* Kill the watchpool thread */
  5083. thr = &control_thr[watchpool_thr_id];
  5084. thr_info_cancel(thr);
  5085. applog(LOG_DEBUG, "Killing off watchdog thread");
  5086. /* Kill the watchdog thread */
  5087. thr = &control_thr[watchdog_thr_id];
  5088. thr_info_cancel(thr);
  5089. applog(LOG_DEBUG, "Shutting down mining threads");
  5090. for (i = 0; i < mining_threads; i++) {
  5091. thr = get_thread(i);
  5092. if (!thr)
  5093. continue;
  5094. cgpu = thr->cgpu;
  5095. if (!cgpu)
  5096. continue;
  5097. if (!cgpu->threads)
  5098. continue;
  5099. cgpu->shutdown = true;
  5100. thr->work_restart = true;
  5101. notifier_wake(thr->notifier);
  5102. notifier_wake(thr->work_restart_notifier);
  5103. }
  5104. sleep(1);
  5105. applog(LOG_DEBUG, "Killing off mining threads");
  5106. /* Kill the mining threads*/
  5107. for (i = 0; i < mining_threads; i++) {
  5108. thr = get_thread(i);
  5109. if (!thr)
  5110. continue;
  5111. cgpu = thr->cgpu;
  5112. if (cgpu->threads)
  5113. {
  5114. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5115. thr_info_cancel(thr);
  5116. }
  5117. cgpu->status = LIFE_DEAD2;
  5118. }
  5119. /* Stop the others */
  5120. applog(LOG_DEBUG, "Killing off API thread");
  5121. thr = &control_thr[api_thr_id];
  5122. thr_info_cancel(thr);
  5123. }
  5124. /* This should be the common exit path */
  5125. void kill_work(void)
  5126. {
  5127. __kill_work();
  5128. quit(0, "Shutdown signal received.");
  5129. }
  5130. static
  5131. #ifdef WIN32
  5132. #ifndef _WIN64
  5133. const
  5134. #endif
  5135. #endif
  5136. char **initial_args;
  5137. void _bfg_clean_up(bool);
  5138. void app_restart(void)
  5139. {
  5140. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5141. __kill_work();
  5142. _bfg_clean_up(true);
  5143. #if defined(unix) || defined(__APPLE__)
  5144. if (forkpid > 0) {
  5145. kill(forkpid, SIGTERM);
  5146. forkpid = 0;
  5147. }
  5148. #endif
  5149. execv(initial_args[0], initial_args);
  5150. applog(LOG_WARNING, "Failed to restart application");
  5151. }
  5152. static void sighandler(int __maybe_unused sig)
  5153. {
  5154. /* Restore signal handlers so we can still quit if kill_work fails */
  5155. sigaction(SIGTERM, &termhandler, NULL);
  5156. sigaction(SIGINT, &inthandler, NULL);
  5157. kill_work();
  5158. }
  5159. static void start_longpoll(void);
  5160. static void stop_longpoll(void);
  5161. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5162. * this pool. */
  5163. static void recruit_curl(struct pool *pool)
  5164. {
  5165. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5166. if (unlikely(!ce))
  5167. quit(1, "Failed to calloc in recruit_curl");
  5168. ce->curl = curl_easy_init();
  5169. if (unlikely(!ce->curl))
  5170. quit(1, "Failed to init in recruit_curl");
  5171. LL_PREPEND(pool->curllist, ce);
  5172. pool->curls++;
  5173. }
  5174. /* Grab an available curl if there is one. If not, then recruit extra curls
  5175. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5176. * and there are already 5 curls in circulation. Limit total number to the
  5177. * number of mining threads per pool as well to prevent blasting a pool during
  5178. * network delays/outages. */
  5179. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5180. {
  5181. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5182. bool recruited = false;
  5183. struct curl_ent *ce;
  5184. mutex_lock(&pool->pool_lock);
  5185. retry:
  5186. if (!pool->curls) {
  5187. recruit_curl(pool);
  5188. recruited = true;
  5189. } else if (!pool->curllist) {
  5190. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5191. if (!blocking) {
  5192. mutex_unlock(&pool->pool_lock);
  5193. return NULL;
  5194. }
  5195. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5196. goto retry;
  5197. } else {
  5198. recruit_curl(pool);
  5199. recruited = true;
  5200. }
  5201. }
  5202. ce = pool->curllist;
  5203. LL_DELETE(pool->curllist, ce);
  5204. mutex_unlock(&pool->pool_lock);
  5205. if (recruited)
  5206. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5207. return ce;
  5208. }
  5209. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5210. {
  5211. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5212. }
  5213. __maybe_unused
  5214. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5215. {
  5216. return pop_curl_entry3(pool, 1);
  5217. }
  5218. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5219. {
  5220. mutex_lock(&pool->pool_lock);
  5221. if (!ce || !ce->curl)
  5222. quithere(1, "Attempted to add NULL");
  5223. LL_PREPEND(pool->curllist, ce);
  5224. cgtime(&ce->tv);
  5225. pthread_cond_broadcast(&pool->cr_cond);
  5226. mutex_unlock(&pool->pool_lock);
  5227. }
  5228. bool stale_work(struct work *work, bool share);
  5229. static inline bool should_roll(struct work *work)
  5230. {
  5231. struct timeval now;
  5232. time_t expiry;
  5233. if (!pool_actively_in_use(work->pool, NULL))
  5234. return false;
  5235. if (stale_work(work, false))
  5236. return false;
  5237. if (work->rolltime > opt_scantime)
  5238. expiry = work->rolltime;
  5239. else
  5240. expiry = opt_scantime;
  5241. expiry = expiry * 2 / 3;
  5242. /* We shouldn't roll if we're unlikely to get one shares' duration
  5243. * work out of doing so */
  5244. cgtime(&now);
  5245. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5246. return false;
  5247. return true;
  5248. }
  5249. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5250. * reject blocks as invalid. */
  5251. static inline bool can_roll(struct work *work)
  5252. {
  5253. if (work->stratum)
  5254. return false;
  5255. if (!(work->pool && !work->clone))
  5256. return false;
  5257. if (work->tr)
  5258. {
  5259. if (stale_work(work, false))
  5260. return false;
  5261. return blkmk_work_left(work->tr->tmpl);
  5262. }
  5263. return (work->rolltime &&
  5264. work->rolls < 7000 && !stale_work(work, false));
  5265. }
  5266. static void roll_work(struct work *work)
  5267. {
  5268. if (work->tr)
  5269. {
  5270. struct timeval tv_now;
  5271. cgtime(&tv_now);
  5272. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5273. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5274. swap32yes(work->data, work->data, 80 / 4);
  5275. calc_midstate(work);
  5276. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5277. } else {
  5278. uint32_t *work_ntime;
  5279. uint32_t ntime;
  5280. work_ntime = (uint32_t *)(work->data + 68);
  5281. ntime = be32toh(*work_ntime);
  5282. ntime++;
  5283. *work_ntime = htobe32(ntime);
  5284. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5285. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5286. }
  5287. local_work++;
  5288. work->rolls++;
  5289. work->blk.nonce = 0;
  5290. /* This is now a different work item so it needs a different ID for the
  5291. * hashtable */
  5292. work->id = total_work++;
  5293. }
  5294. /* Duplicates any dynamically allocated arrays within the work struct to
  5295. * prevent a copied work struct from freeing ram belonging to another struct */
  5296. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5297. {
  5298. int id = work->id;
  5299. clean_work(work);
  5300. memcpy(work, base_work, sizeof(struct work));
  5301. /* Keep the unique new id assigned during make_work to prevent copied
  5302. * work from having the same id. */
  5303. work->id = id;
  5304. if (base_work->job_id)
  5305. work->job_id = strdup(base_work->job_id);
  5306. if (base_work->nonce1)
  5307. work->nonce1 = strdup(base_work->nonce1);
  5308. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5309. if (base_work->tr)
  5310. tmpl_incref(base_work->tr);
  5311. if (noffset)
  5312. {
  5313. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5314. uint32_t ntime = be32toh(*work_ntime);
  5315. ntime += noffset;
  5316. *work_ntime = htobe32(ntime);
  5317. }
  5318. if (work->device_data_dup_func)
  5319. work->device_data = work->device_data_dup_func(work);
  5320. }
  5321. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5322. * for all dynamically allocated arrays within the struct. noffset is used for
  5323. * when a driver has internally rolled the ntime, noffset is a relative value.
  5324. * The macro copy_work() calls this function with an noffset of 0. */
  5325. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5326. {
  5327. struct work *work = make_work();
  5328. _copy_work(work, base_work, noffset);
  5329. return work;
  5330. }
  5331. void __copy_work(struct work *work, const struct work *base_work)
  5332. {
  5333. _copy_work(work, base_work, 0);
  5334. }
  5335. static struct work *make_clone(struct work *work)
  5336. {
  5337. struct work *work_clone = copy_work(work);
  5338. work_clone->clone = true;
  5339. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5340. work_clone->longpoll = false;
  5341. work_clone->mandatory = false;
  5342. /* Make cloned work appear slightly older to bias towards keeping the
  5343. * master work item which can be further rolled */
  5344. work_clone->tv_staged.tv_sec -= 1;
  5345. return work_clone;
  5346. }
  5347. static void stage_work(struct work *work);
  5348. static bool clone_available(void)
  5349. {
  5350. struct work *work_clone = NULL, *work, *tmp;
  5351. bool cloned = false;
  5352. mutex_lock(stgd_lock);
  5353. if (!staged_rollable)
  5354. goto out_unlock;
  5355. HASH_ITER(hh, staged_work, work, tmp) {
  5356. if (can_roll(work) && should_roll(work)) {
  5357. roll_work(work);
  5358. work_clone = make_clone(work);
  5359. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5360. roll_work(work);
  5361. cloned = true;
  5362. break;
  5363. }
  5364. }
  5365. out_unlock:
  5366. mutex_unlock(stgd_lock);
  5367. if (cloned) {
  5368. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5369. stage_work(work_clone);
  5370. }
  5371. return cloned;
  5372. }
  5373. static void pool_died(struct pool *pool)
  5374. {
  5375. mutex_lock(&lp_lock);
  5376. if (!pool_tset(pool, &pool->idle)) {
  5377. cgtime(&pool->tv_idle);
  5378. pthread_cond_broadcast(&lp_cond);
  5379. mutex_unlock(&lp_lock);
  5380. if (pool == current_pool()) {
  5381. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5382. switch_pools(NULL);
  5383. } else
  5384. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5385. }
  5386. else
  5387. mutex_unlock(&lp_lock);
  5388. }
  5389. bool stale_work(struct work *work, bool share)
  5390. {
  5391. unsigned work_expiry;
  5392. struct pool *pool;
  5393. uint32_t block_id;
  5394. unsigned getwork_delay;
  5395. block_id = ((uint32_t*)work->data)[1];
  5396. pool = work->pool;
  5397. /* Technically the rolltime should be correct but some pools
  5398. * advertise a broken expire= that is lower than a meaningful
  5399. * scantime */
  5400. if (work->rolltime >= opt_scantime || work->tr)
  5401. work_expiry = work->rolltime;
  5402. else
  5403. work_expiry = opt_expiry;
  5404. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  5405. if (work_expiry > max_expiry)
  5406. work_expiry = max_expiry;
  5407. if (share) {
  5408. /* If the share isn't on this pool's latest block, it's stale */
  5409. if (pool->block_id && pool->block_id != block_id)
  5410. {
  5411. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5412. return true;
  5413. }
  5414. /* If the pool doesn't want old shares, then any found in work before
  5415. * the most recent longpoll is stale */
  5416. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5417. {
  5418. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5419. return true;
  5420. }
  5421. } else {
  5422. struct mining_goal_info * const goal = pool->goal;
  5423. struct blockchain_info * const blkchain = goal->blkchain;
  5424. /* If this work isn't for the latest Bitcoin block, it's stale */
  5425. /* But only care about the current pool if failover-only */
  5426. if (enabled_pools <= 1 || opt_fail_only) {
  5427. if (pool->block_id && block_id != pool->block_id)
  5428. {
  5429. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)blkchain->currentblk->block_id);
  5430. return true;
  5431. }
  5432. } else {
  5433. if (block_id != blkchain->currentblk->block_id)
  5434. {
  5435. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)blkchain->currentblk->block_id);
  5436. return true;
  5437. }
  5438. }
  5439. /* If the pool has asked us to restart since this work, it's stale */
  5440. if (work->work_restart_id != pool->work_restart_id)
  5441. {
  5442. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5443. return true;
  5444. }
  5445. if (pool->has_stratum && work->job_id) {
  5446. bool same_job;
  5447. if (!pool->stratum_active || !pool->stratum_notify) {
  5448. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5449. return true;
  5450. }
  5451. same_job = true;
  5452. cg_rlock(&pool->data_lock);
  5453. if (strcmp(work->job_id, pool->swork.job_id))
  5454. same_job = false;
  5455. cg_runlock(&pool->data_lock);
  5456. if (!same_job) {
  5457. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5458. return true;
  5459. }
  5460. }
  5461. /* Factor in the average getwork delay of this pool, rounding it up to
  5462. * the nearest second */
  5463. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5464. if (unlikely(work_expiry <= getwork_delay + 5))
  5465. work_expiry = 5;
  5466. else
  5467. work_expiry -= getwork_delay;
  5468. }
  5469. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5470. if (elapsed_since_staged > work_expiry) {
  5471. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5472. return true;
  5473. }
  5474. /* If the user only wants strict failover, any work from a pool other than
  5475. * the current one is always considered stale */
  5476. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5477. {
  5478. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5479. return true;
  5480. }
  5481. return false;
  5482. }
  5483. double share_diff(const struct work *work)
  5484. {
  5485. double ret;
  5486. bool new_best = false;
  5487. ret = target_diff(work->hash);
  5488. cg_wlock(&control_lock);
  5489. if (unlikely(ret > best_diff)) {
  5490. new_best = true;
  5491. best_diff = ret;
  5492. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5493. }
  5494. if (unlikely(ret > work->pool->best_diff))
  5495. work->pool->best_diff = ret;
  5496. cg_wunlock(&control_lock);
  5497. if (unlikely(new_best))
  5498. applog(LOG_INFO, "New best share: %s", best_share);
  5499. return ret;
  5500. }
  5501. static
  5502. void work_check_for_block(struct work * const work)
  5503. {
  5504. struct pool * const pool = work->pool;
  5505. struct mining_goal_info * const goal = pool->goal;
  5506. work->share_diff = share_diff(work);
  5507. if (unlikely(work->share_diff >= goal->current_diff)) {
  5508. work->block = true;
  5509. work->pool->solved++;
  5510. found_blocks++;
  5511. work->mandatory = true;
  5512. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5513. }
  5514. }
  5515. static void submit_discard_share2(const char *reason, struct work *work)
  5516. {
  5517. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5518. sharelog(reason, work);
  5519. mutex_lock(&stats_lock);
  5520. ++total_stale;
  5521. ++cgpu->stale;
  5522. ++(work->pool->stale_shares);
  5523. total_diff_stale += work->work_difficulty;
  5524. cgpu->diff_stale += work->work_difficulty;
  5525. work->pool->diff_stale += work->work_difficulty;
  5526. mutex_unlock(&stats_lock);
  5527. }
  5528. static void submit_discard_share(struct work *work)
  5529. {
  5530. submit_discard_share2("discard", work);
  5531. }
  5532. struct submit_work_state {
  5533. struct work *work;
  5534. bool resubmit;
  5535. struct curl_ent *ce;
  5536. int failures;
  5537. struct timeval tv_staleexpire;
  5538. char *s;
  5539. struct timeval tv_submit;
  5540. struct submit_work_state *next;
  5541. };
  5542. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5543. {
  5544. long *p_timeout_us = userp;
  5545. const long max_ms = LONG_MAX / 1000;
  5546. if (max_ms < timeout_ms)
  5547. timeout_ms = max_ms;
  5548. *p_timeout_us = timeout_ms * 1000;
  5549. return 0;
  5550. }
  5551. static void sws_has_ce(struct submit_work_state *sws)
  5552. {
  5553. struct pool *pool = sws->work->pool;
  5554. sws->s = submit_upstream_work_request(sws->work);
  5555. cgtime(&sws->tv_submit);
  5556. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5557. }
  5558. static struct submit_work_state *begin_submission(struct work *work)
  5559. {
  5560. struct pool *pool;
  5561. struct submit_work_state *sws = NULL;
  5562. pool = work->pool;
  5563. sws = malloc(sizeof(*sws));
  5564. *sws = (struct submit_work_state){
  5565. .work = work,
  5566. };
  5567. work_check_for_block(work);
  5568. if (stale_work(work, true)) {
  5569. work->stale = true;
  5570. if (opt_submit_stale)
  5571. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5572. else if (pool->submit_old)
  5573. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5574. else {
  5575. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5576. submit_discard_share(work);
  5577. goto out;
  5578. }
  5579. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5580. }
  5581. if (work->stratum) {
  5582. char *s;
  5583. s = malloc(1024);
  5584. sws->s = s;
  5585. } else {
  5586. /* submit solution to bitcoin via JSON-RPC */
  5587. sws->ce = pop_curl_entry2(pool, false);
  5588. if (sws->ce) {
  5589. sws_has_ce(sws);
  5590. } else {
  5591. sws->next = pool->sws_waiting_on_curl;
  5592. pool->sws_waiting_on_curl = sws;
  5593. if (sws->next)
  5594. applog(LOG_DEBUG, "submit_thread queuing submission");
  5595. else
  5596. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5597. }
  5598. }
  5599. return sws;
  5600. out:
  5601. free(sws);
  5602. return NULL;
  5603. }
  5604. static bool retry_submission(struct submit_work_state *sws)
  5605. {
  5606. struct work *work = sws->work;
  5607. struct pool *pool = work->pool;
  5608. sws->resubmit = true;
  5609. if ((!work->stale) && stale_work(work, true)) {
  5610. work->stale = true;
  5611. if (opt_submit_stale)
  5612. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5613. else if (pool->submit_old)
  5614. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5615. else {
  5616. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5617. submit_discard_share(work);
  5618. return false;
  5619. }
  5620. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5621. }
  5622. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5623. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5624. submit_discard_share(work);
  5625. return false;
  5626. }
  5627. else if (work->stale) {
  5628. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5629. {
  5630. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5631. submit_discard_share(work);
  5632. return false;
  5633. }
  5634. }
  5635. /* pause, then restart work-request loop */
  5636. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5637. cgtime(&sws->tv_submit);
  5638. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5639. return true;
  5640. }
  5641. static void free_sws(struct submit_work_state *sws)
  5642. {
  5643. free(sws->s);
  5644. free_work(sws->work);
  5645. free(sws);
  5646. }
  5647. static void *submit_work_thread(__maybe_unused void *userdata)
  5648. {
  5649. int wip = 0;
  5650. CURLM *curlm;
  5651. long curlm_timeout_us = -1;
  5652. struct timeval curlm_timer;
  5653. struct submit_work_state *sws, **swsp;
  5654. struct submit_work_state *write_sws = NULL;
  5655. unsigned tsreduce = 0;
  5656. pthread_detach(pthread_self());
  5657. RenameThread("submit_work");
  5658. applog(LOG_DEBUG, "Creating extra submit work thread");
  5659. curlm = curl_multi_init();
  5660. curlm_timeout_us = -1;
  5661. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5662. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5663. fd_set rfds, wfds, efds;
  5664. int maxfd;
  5665. struct timeval tv_timeout, tv_now;
  5666. int n;
  5667. CURLMsg *cm;
  5668. FD_ZERO(&rfds);
  5669. while (1) {
  5670. mutex_lock(&submitting_lock);
  5671. total_submitting -= tsreduce;
  5672. tsreduce = 0;
  5673. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5674. notifier_read(submit_waiting_notifier);
  5675. }
  5676. // Receive any new submissions
  5677. while (submit_waiting) {
  5678. struct work *work = submit_waiting;
  5679. DL_DELETE(submit_waiting, work);
  5680. if ( (sws = begin_submission(work)) ) {
  5681. if (sws->ce)
  5682. curl_multi_add_handle(curlm, sws->ce->curl);
  5683. else if (sws->s) {
  5684. sws->next = write_sws;
  5685. write_sws = sws;
  5686. }
  5687. ++wip;
  5688. }
  5689. else {
  5690. --total_submitting;
  5691. free_work(work);
  5692. }
  5693. }
  5694. if (unlikely(shutting_down && !wip))
  5695. break;
  5696. mutex_unlock(&submitting_lock);
  5697. FD_ZERO(&rfds);
  5698. FD_ZERO(&wfds);
  5699. FD_ZERO(&efds);
  5700. tv_timeout.tv_sec = -1;
  5701. // Setup cURL with select
  5702. // Need to call perform to ensure the timeout gets updated
  5703. curl_multi_perform(curlm, &n);
  5704. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5705. if (curlm_timeout_us >= 0)
  5706. {
  5707. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5708. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5709. }
  5710. // Setup waiting stratum submissions with select
  5711. for (sws = write_sws; sws; sws = sws->next)
  5712. {
  5713. struct pool *pool = sws->work->pool;
  5714. int fd = pool->sock;
  5715. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5716. continue;
  5717. FD_SET(fd, &wfds);
  5718. set_maxfd(&maxfd, fd);
  5719. }
  5720. // Setup "submit waiting" notifier with select
  5721. FD_SET(submit_waiting_notifier[0], &rfds);
  5722. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5723. // Wait for something interesting to happen :)
  5724. cgtime(&tv_now);
  5725. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5726. FD_ZERO(&rfds);
  5727. continue;
  5728. }
  5729. // Handle any stratum ready-to-write results
  5730. for (swsp = &write_sws; (sws = *swsp); ) {
  5731. struct work *work = sws->work;
  5732. struct pool *pool = work->pool;
  5733. int fd = pool->sock;
  5734. bool sessionid_match;
  5735. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5736. next_write_sws:
  5737. // TODO: Check if stale, possibly discard etc
  5738. swsp = &sws->next;
  5739. continue;
  5740. }
  5741. cg_rlock(&pool->data_lock);
  5742. // NOTE: cgminer only does this check on retries, but BFGMiner does it for even the first/normal submit; therefore, it needs to be such that it always is true on the same connection regardless of session management
  5743. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5744. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  5745. cg_runlock(&pool->data_lock);
  5746. if (!sessionid_match)
  5747. {
  5748. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5749. submit_discard_share2("disconnect", work);
  5750. ++tsreduce;
  5751. next_write_sws_del:
  5752. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5753. FD_CLR(fd, &wfds);
  5754. // Delete sws for this submission, since we're done with it
  5755. *swsp = sws->next;
  5756. free_sws(sws);
  5757. --wip;
  5758. continue;
  5759. }
  5760. char *s = sws->s;
  5761. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5762. int sshare_id;
  5763. uint32_t nonce;
  5764. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  5765. char noncehex[9];
  5766. char ntimehex[9];
  5767. sshare->work = copy_work(work);
  5768. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5769. nonce = *((uint32_t *)(work->data + 76));
  5770. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5771. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5772. mutex_lock(&sshare_lock);
  5773. /* Give the stratum share a unique id */
  5774. sshare_id =
  5775. sshare->id = swork_id++;
  5776. HASH_ADD_INT(stratum_shares, id, sshare);
  5777. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5778. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5779. mutex_unlock(&sshare_lock);
  5780. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5781. if (likely(stratum_send(pool, s, strlen(s)))) {
  5782. if (pool_tclear(pool, &pool->submit_fail))
  5783. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5784. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5785. goto next_write_sws_del;
  5786. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5787. // Undo stuff
  5788. mutex_lock(&sshare_lock);
  5789. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5790. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5791. if (sshare)
  5792. HASH_DEL(stratum_shares, sshare);
  5793. mutex_unlock(&sshare_lock);
  5794. if (sshare)
  5795. {
  5796. free_work(sshare->work);
  5797. free(sshare);
  5798. }
  5799. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5800. total_ro++;
  5801. pool->remotefail_occasions++;
  5802. if (!sshare)
  5803. goto next_write_sws_del;
  5804. goto next_write_sws;
  5805. }
  5806. }
  5807. // Handle any cURL activities
  5808. curl_multi_perform(curlm, &n);
  5809. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5810. if (cm->msg == CURLMSG_DONE)
  5811. {
  5812. bool finished;
  5813. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5814. curl_multi_remove_handle(curlm, cm->easy_handle);
  5815. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5816. if (!finished) {
  5817. if (retry_submission(sws))
  5818. curl_multi_add_handle(curlm, sws->ce->curl);
  5819. else
  5820. finished = true;
  5821. }
  5822. if (finished) {
  5823. --wip;
  5824. ++tsreduce;
  5825. struct pool *pool = sws->work->pool;
  5826. if (pool->sws_waiting_on_curl) {
  5827. pool->sws_waiting_on_curl->ce = sws->ce;
  5828. sws_has_ce(pool->sws_waiting_on_curl);
  5829. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5830. curl_multi_add_handle(curlm, sws->ce->curl);
  5831. } else {
  5832. push_curl_entry(sws->ce, sws->work->pool);
  5833. }
  5834. free_sws(sws);
  5835. }
  5836. }
  5837. }
  5838. }
  5839. assert(!write_sws);
  5840. mutex_unlock(&submitting_lock);
  5841. curl_multi_cleanup(curlm);
  5842. applog(LOG_DEBUG, "submit_work thread exiting");
  5843. return NULL;
  5844. }
  5845. /* Find the pool that currently has the highest priority */
  5846. static struct pool *priority_pool(int choice)
  5847. {
  5848. struct pool *ret = NULL;
  5849. int i;
  5850. for (i = 0; i < total_pools; i++) {
  5851. struct pool *pool = pools[i];
  5852. if (pool->prio == choice) {
  5853. ret = pool;
  5854. break;
  5855. }
  5856. }
  5857. if (unlikely(!ret)) {
  5858. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5859. return pools[choice];
  5860. }
  5861. return ret;
  5862. }
  5863. int prioritize_pools(char *param, int *pid)
  5864. {
  5865. char *ptr, *next;
  5866. int i, pr, prio = 0;
  5867. if (total_pools == 0) {
  5868. return MSG_NOPOOL;
  5869. }
  5870. if (param == NULL || *param == '\0') {
  5871. return MSG_MISPID;
  5872. }
  5873. bool pools_changed[total_pools];
  5874. int new_prio[total_pools];
  5875. for (i = 0; i < total_pools; ++i)
  5876. pools_changed[i] = false;
  5877. next = param;
  5878. while (next && *next) {
  5879. ptr = next;
  5880. next = strchr(ptr, ',');
  5881. if (next)
  5882. *(next++) = '\0';
  5883. i = atoi(ptr);
  5884. if (i < 0 || i >= total_pools) {
  5885. *pid = i;
  5886. return MSG_INVPID;
  5887. }
  5888. if (pools_changed[i]) {
  5889. *pid = i;
  5890. return MSG_DUPPID;
  5891. }
  5892. pools_changed[i] = true;
  5893. new_prio[i] = prio++;
  5894. }
  5895. // Only change them if no errors
  5896. for (i = 0; i < total_pools; i++) {
  5897. if (pools_changed[i])
  5898. pools[i]->prio = new_prio[i];
  5899. }
  5900. // In priority order, cycle through the unchanged pools and append them
  5901. for (pr = 0; pr < total_pools; pr++)
  5902. for (i = 0; i < total_pools; i++) {
  5903. if (!pools_changed[i] && pools[i]->prio == pr) {
  5904. pools[i]->prio = prio++;
  5905. pools_changed[i] = true;
  5906. break;
  5907. }
  5908. }
  5909. if (current_pool()->prio)
  5910. switch_pools(NULL);
  5911. return MSG_POOLPRIO;
  5912. }
  5913. void validate_pool_priorities(void)
  5914. {
  5915. // TODO: this should probably do some sort of logging
  5916. int i, j;
  5917. bool used[total_pools];
  5918. bool valid[total_pools];
  5919. for (i = 0; i < total_pools; i++)
  5920. used[i] = valid[i] = false;
  5921. for (i = 0; i < total_pools; i++) {
  5922. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5923. if (!used[pools[i]->prio]) {
  5924. valid[i] = true;
  5925. used[pools[i]->prio] = true;
  5926. }
  5927. }
  5928. }
  5929. for (i = 0; i < total_pools; i++) {
  5930. if (!valid[i]) {
  5931. for (j = 0; j < total_pools; j++) {
  5932. if (!used[j]) {
  5933. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5934. pools[i]->prio = j;
  5935. used[j] = true;
  5936. break;
  5937. }
  5938. }
  5939. }
  5940. }
  5941. }
  5942. static void clear_pool_work(struct pool *pool);
  5943. /* Specifies whether we can switch to this pool or not. */
  5944. static bool pool_unusable(struct pool *pool)
  5945. {
  5946. if (pool->idle)
  5947. return true;
  5948. if (pool->enabled != POOL_ENABLED)
  5949. return true;
  5950. return false;
  5951. }
  5952. void switch_pools(struct pool *selected)
  5953. {
  5954. struct pool *pool, *last_pool, *failover_pool = NULL;
  5955. int i, pool_no, next_pool;
  5956. if (selected)
  5957. enable_pool(selected);
  5958. cg_wlock(&control_lock);
  5959. last_pool = currentpool;
  5960. pool_no = currentpool->pool_no;
  5961. /* Switch selected to pool number 0 and move the rest down */
  5962. if (selected) {
  5963. if (selected->prio != 0) {
  5964. for (i = 0; i < total_pools; i++) {
  5965. pool = pools[i];
  5966. if (pool->prio < selected->prio)
  5967. pool->prio++;
  5968. }
  5969. selected->prio = 0;
  5970. }
  5971. }
  5972. switch (pool_strategy) {
  5973. /* All of these set to the master pool */
  5974. case POOL_BALANCE:
  5975. case POOL_FAILOVER:
  5976. case POOL_LOADBALANCE:
  5977. for (i = 0; i < total_pools; i++) {
  5978. pool = priority_pool(i);
  5979. if (pool_unusable(pool))
  5980. continue;
  5981. pool_no = pool->pool_no;
  5982. break;
  5983. }
  5984. break;
  5985. /* Both of these simply increment and cycle */
  5986. case POOL_ROUNDROBIN:
  5987. case POOL_ROTATE:
  5988. if (selected && !selected->idle) {
  5989. pool_no = selected->pool_no;
  5990. break;
  5991. }
  5992. next_pool = pool_no;
  5993. /* Select the next alive pool */
  5994. for (i = 1; i < total_pools; i++) {
  5995. next_pool++;
  5996. if (next_pool >= total_pools)
  5997. next_pool = 0;
  5998. pool = pools[next_pool];
  5999. if (pool_unusable(pool))
  6000. continue;
  6001. if (pool->failover_only)
  6002. {
  6003. BFGINIT(failover_pool, pool);
  6004. continue;
  6005. }
  6006. pool_no = next_pool;
  6007. break;
  6008. }
  6009. break;
  6010. default:
  6011. break;
  6012. }
  6013. pool = pools[pool_no];
  6014. if (pool_unusable(pool) && failover_pool)
  6015. pool = failover_pool;
  6016. currentpool = pool;
  6017. cg_wunlock(&control_lock);
  6018. mutex_lock(&lp_lock);
  6019. pthread_cond_broadcast(&lp_cond);
  6020. mutex_unlock(&lp_lock);
  6021. /* Set the lagging flag to avoid pool not providing work fast enough
  6022. * messages in failover only mode since we have to get all fresh work
  6023. * as in restart_threads */
  6024. if (opt_fail_only)
  6025. pool_tset(pool, &pool->lagging);
  6026. if (pool != last_pool)
  6027. {
  6028. pool->block_id = 0;
  6029. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6030. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6031. if (pool_localgen(pool) || opt_fail_only)
  6032. clear_pool_work(last_pool);
  6033. }
  6034. }
  6035. mutex_lock(&lp_lock);
  6036. pthread_cond_broadcast(&lp_cond);
  6037. mutex_unlock(&lp_lock);
  6038. #ifdef HAVE_CURSES
  6039. update_block_display();
  6040. #endif
  6041. }
  6042. static void discard_work(struct work *work)
  6043. {
  6044. if (!work->clone && !work->rolls && !work->mined) {
  6045. if (work->pool) {
  6046. work->pool->discarded_work++;
  6047. work->pool->quota_used--;
  6048. work->pool->works--;
  6049. }
  6050. total_discarded++;
  6051. applog(LOG_DEBUG, "Discarded work");
  6052. } else
  6053. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6054. free_work(work);
  6055. }
  6056. static void wake_gws(void)
  6057. {
  6058. mutex_lock(stgd_lock);
  6059. pthread_cond_signal(&gws_cond);
  6060. mutex_unlock(stgd_lock);
  6061. }
  6062. static void discard_stale(void)
  6063. {
  6064. struct work *work, *tmp;
  6065. int stale = 0;
  6066. mutex_lock(stgd_lock);
  6067. HASH_ITER(hh, staged_work, work, tmp) {
  6068. if (stale_work(work, false)) {
  6069. HASH_DEL(staged_work, work);
  6070. discard_work(work);
  6071. stale++;
  6072. staged_full = false;
  6073. }
  6074. }
  6075. pthread_cond_signal(&gws_cond);
  6076. mutex_unlock(stgd_lock);
  6077. if (stale)
  6078. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6079. }
  6080. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6081. {
  6082. bool rv;
  6083. struct timeval tv, orig;
  6084. ldiv_t d;
  6085. d = ldiv(ustime, 1000000);
  6086. tv = (struct timeval){
  6087. .tv_sec = d.quot,
  6088. .tv_usec = d.rem,
  6089. };
  6090. orig = work->tv_staged;
  6091. timersub(&orig, &tv, &work->tv_staged);
  6092. rv = stale_work(work, share);
  6093. work->tv_staged = orig;
  6094. return rv;
  6095. }
  6096. static
  6097. void pool_update_work_restart_time(struct pool * const pool)
  6098. {
  6099. pool->work_restart_time = time(NULL);
  6100. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6101. }
  6102. static void restart_threads(void)
  6103. {
  6104. struct pool *cp = current_pool();
  6105. int i;
  6106. struct thr_info *thr;
  6107. /* Artificially set the lagging flag to avoid pool not providing work
  6108. * fast enough messages after every long poll */
  6109. pool_tset(cp, &cp->lagging);
  6110. /* Discard staged work that is now stale */
  6111. discard_stale();
  6112. rd_lock(&mining_thr_lock);
  6113. for (i = 0; i < mining_threads; i++)
  6114. {
  6115. thr = mining_thr[i];
  6116. thr->work_restart = true;
  6117. }
  6118. for (i = 0; i < mining_threads; i++)
  6119. {
  6120. thr = mining_thr[i];
  6121. notifier_wake(thr->work_restart_notifier);
  6122. }
  6123. rd_unlock(&mining_thr_lock);
  6124. }
  6125. void blkhashstr(char *rv, const unsigned char *hash)
  6126. {
  6127. unsigned char hash_swap[32];
  6128. swap256(hash_swap, hash);
  6129. swap32tole(hash_swap, hash_swap, 32 / 4);
  6130. bin2hex(rv, hash_swap, 32);
  6131. }
  6132. static
  6133. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6134. {
  6135. struct blockchain_info * const blkchain = goal->blkchain;
  6136. blkchain->currentblk = blkinfo;
  6137. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6138. cg_wlock(&ch_lock);
  6139. __update_block_title(goal);
  6140. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6141. cg_wunlock(&ch_lock);
  6142. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6143. }
  6144. /* Search to see if this prevblkhash has been seen before */
  6145. static
  6146. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6147. {
  6148. struct block_info *s;
  6149. rd_lock(&blk_lock);
  6150. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6151. rd_unlock(&blk_lock);
  6152. return s;
  6153. }
  6154. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6155. {
  6156. return blocka->block_seen_order - blockb->block_seen_order;
  6157. }
  6158. static
  6159. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6160. {
  6161. unsigned char target[32];
  6162. double diff;
  6163. uint64_t diff64;
  6164. real_block_target(target, work->data);
  6165. diff = target_diff(target);
  6166. diff64 = diff;
  6167. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6168. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6169. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6170. if (unlikely(goal->current_diff != diff))
  6171. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6172. goal->current_diff = diff;
  6173. }
  6174. static bool test_work_current(struct work *work)
  6175. {
  6176. bool ret = true;
  6177. if (work->mandatory)
  6178. return ret;
  6179. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6180. const uint8_t * const prevblkhash = &work->data[4];
  6181. {
  6182. /* Hack to work around dud work sneaking into test */
  6183. bool dudwork = true;
  6184. for (int i = 8; i < 26; ++i)
  6185. if (work->data[i])
  6186. {
  6187. dudwork = false;
  6188. break;
  6189. }
  6190. if (dudwork)
  6191. goto out_free;
  6192. }
  6193. struct pool * const pool = work->pool;
  6194. struct mining_goal_info * const goal = pool->goal;
  6195. struct blockchain_info * const blkchain = goal->blkchain;
  6196. /* Search to see if this block exists yet and if not, consider it a
  6197. * new block and set the current block details to this one */
  6198. if (!block_exists(blkchain, prevblkhash))
  6199. {
  6200. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6201. int deleted_block = 0;
  6202. ret = false;
  6203. if (unlikely(!s))
  6204. quit (1, "test_work_current OOM");
  6205. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6206. s->block_id = block_id;
  6207. s->block_seen_order = new_blocks++;
  6208. s->first_seen_time = time(NULL);
  6209. wr_lock(&blk_lock);
  6210. /* Only keep the last hour's worth of blocks in memory since
  6211. * work from blocks before this is virtually impossible and we
  6212. * want to prevent memory usage from continually rising */
  6213. if (HASH_COUNT(blkchain->blocks) > 6)
  6214. {
  6215. struct block_info *oldblock;
  6216. HASH_SORT(blkchain->blocks, block_sort);
  6217. oldblock = blkchain->blocks;
  6218. deleted_block = oldblock->block_seen_order;
  6219. HASH_DEL(blkchain->blocks, oldblock);
  6220. free(oldblock);
  6221. }
  6222. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6223. set_blockdiff(goal, work);
  6224. wr_unlock(&blk_lock);
  6225. pool->block_id = block_id;
  6226. pool_update_work_restart_time(pool);
  6227. if (deleted_block)
  6228. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6229. #if BLKMAKER_VERSION > 1
  6230. template_nonce = 0;
  6231. #endif
  6232. set_curblock(goal, s);
  6233. if (unlikely(new_blocks == 1))
  6234. goto out_free;
  6235. if (!work->stratum)
  6236. {
  6237. if (work->longpoll)
  6238. {
  6239. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6240. pool->pool_no);
  6241. }
  6242. else
  6243. if (have_longpoll)
  6244. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6245. else
  6246. applog(LOG_NOTICE, "New block detected on network");
  6247. }
  6248. restart_threads();
  6249. }
  6250. else
  6251. {
  6252. bool restart = false;
  6253. if (unlikely(pool->block_id != block_id))
  6254. {
  6255. bool was_active = pool->block_id != 0;
  6256. pool->block_id = block_id;
  6257. pool_update_work_restart_time(pool);
  6258. if (!work->longpoll)
  6259. update_last_work(work);
  6260. if (was_active)
  6261. {
  6262. // Pool actively changed block
  6263. if (pool == current_pool())
  6264. restart = true;
  6265. if (block_id == blkchain->currentblk->block_id)
  6266. {
  6267. // Caught up, only announce if this pool is the one in use
  6268. if (restart)
  6269. applog(LOG_NOTICE, "%s %d caught up to new block",
  6270. work->longpoll ? "Longpoll from pool" : "Pool",
  6271. pool->pool_no);
  6272. }
  6273. else
  6274. {
  6275. // Switched to a block we know, but not the latest... why?
  6276. // This might detect pools trying to double-spend or 51%,
  6277. // but let's not make any accusations until it's had time
  6278. // in the real world.
  6279. char hexstr[65];
  6280. blkhashstr(hexstr, prevblkhash);
  6281. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6282. work->longpoll ? "Longpoll from pool" : "Pool",
  6283. pool->pool_no,
  6284. hexstr);
  6285. }
  6286. }
  6287. }
  6288. if (work->longpoll)
  6289. {
  6290. struct pool * const cp = current_pool();
  6291. ++pool->work_restart_id;
  6292. if (work->tr && work->tr == pool->swork.tr)
  6293. pool->swork.work_restart_id = pool->work_restart_id;
  6294. update_last_work(work);
  6295. pool_update_work_restart_time(pool);
  6296. applog(
  6297. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6298. "Longpoll from pool %d requested work update",
  6299. pool->pool_no);
  6300. if ((!restart) && pool == cp)
  6301. restart = true;
  6302. }
  6303. if (restart)
  6304. restart_threads();
  6305. }
  6306. work->longpoll = false;
  6307. out_free:
  6308. return ret;
  6309. }
  6310. static int tv_sort(struct work *worka, struct work *workb)
  6311. {
  6312. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6313. }
  6314. static bool work_rollable(struct work *work)
  6315. {
  6316. return (!work->clone && work->rolltime);
  6317. }
  6318. static bool hash_push(struct work *work)
  6319. {
  6320. bool rc = true;
  6321. mutex_lock(stgd_lock);
  6322. if (work_rollable(work))
  6323. staged_rollable++;
  6324. if (likely(!getq->frozen)) {
  6325. HASH_ADD_INT(staged_work, id, work);
  6326. HASH_SORT(staged_work, tv_sort);
  6327. } else
  6328. rc = false;
  6329. pthread_cond_broadcast(&getq->cond);
  6330. mutex_unlock(stgd_lock);
  6331. return rc;
  6332. }
  6333. static void stage_work(struct work *work)
  6334. {
  6335. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6336. work->id, work->pool->pool_no);
  6337. work->work_restart_id = work->pool->work_restart_id;
  6338. work->pool->last_work_time = time(NULL);
  6339. cgtime(&work->pool->tv_last_work_time);
  6340. test_work_current(work);
  6341. work->pool->works++;
  6342. hash_push(work);
  6343. }
  6344. #ifdef HAVE_CURSES
  6345. int curses_int(const char *query)
  6346. {
  6347. int ret;
  6348. char *cvar;
  6349. cvar = curses_input(query);
  6350. if (unlikely(!cvar))
  6351. return -1;
  6352. ret = atoi(cvar);
  6353. free(cvar);
  6354. return ret;
  6355. }
  6356. #endif
  6357. #ifdef HAVE_CURSES
  6358. static bool input_pool(bool live);
  6359. #endif
  6360. #ifdef HAVE_CURSES
  6361. static void display_pool_summary(struct pool *pool)
  6362. {
  6363. double efficiency = 0.0;
  6364. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6365. int pool_secs;
  6366. if (curses_active_locked()) {
  6367. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6368. if (pool->solved)
  6369. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6370. if (!pool->has_stratum)
  6371. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6372. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6373. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6374. wlog(" Accepted shares: %d\n", pool->accepted);
  6375. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6376. pool->rejected, pool->stale_shares,
  6377. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6378. );
  6379. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6380. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6381. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6382. wlog(" Network transfer: %s (%s)\n",
  6383. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6384. (float)pool->cgminer_pool_stats.net_bytes_received,
  6385. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6386. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6387. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6388. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6389. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6390. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6391. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6392. wlog(" Items worked on: %d\n", pool->works);
  6393. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6394. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6395. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6396. unlock_curses();
  6397. }
  6398. }
  6399. #endif
  6400. /* We can't remove the memory used for this struct pool because there may
  6401. * still be work referencing it. We just remove it from the pools list */
  6402. void remove_pool(struct pool *pool)
  6403. {
  6404. int i, last_pool = total_pools - 1;
  6405. struct pool *other;
  6406. disable_pool(pool, POOL_DISABLED);
  6407. /* Boost priority of any lower prio than this one */
  6408. for (i = 0; i < total_pools; i++) {
  6409. other = pools[i];
  6410. if (other->prio > pool->prio)
  6411. other->prio--;
  6412. }
  6413. if (pool->pool_no < last_pool) {
  6414. /* Swap the last pool for this one */
  6415. (pools[last_pool])->pool_no = pool->pool_no;
  6416. pools[pool->pool_no] = pools[last_pool];
  6417. }
  6418. /* Give it an invalid number */
  6419. pool->pool_no = total_pools;
  6420. pool->removed = true;
  6421. pool->has_stratum = false;
  6422. total_pools--;
  6423. }
  6424. /* add a mutex if this needs to be thread safe in the future */
  6425. static struct JE {
  6426. char *buf;
  6427. struct JE *next;
  6428. } *jedata = NULL;
  6429. static void json_escape_free()
  6430. {
  6431. struct JE *jeptr = jedata;
  6432. struct JE *jenext;
  6433. jedata = NULL;
  6434. while (jeptr) {
  6435. jenext = jeptr->next;
  6436. free(jeptr->buf);
  6437. free(jeptr);
  6438. jeptr = jenext;
  6439. }
  6440. }
  6441. static
  6442. char *json_escape(const char *str)
  6443. {
  6444. struct JE *jeptr;
  6445. char *buf, *ptr;
  6446. /* 2x is the max, may as well just allocate that */
  6447. ptr = buf = malloc(strlen(str) * 2 + 1);
  6448. jeptr = malloc(sizeof(*jeptr));
  6449. jeptr->buf = buf;
  6450. jeptr->next = jedata;
  6451. jedata = jeptr;
  6452. while (*str) {
  6453. if (*str == '\\' || *str == '"')
  6454. *(ptr++) = '\\';
  6455. *(ptr++) = *(str++);
  6456. }
  6457. *ptr = '\0';
  6458. return buf;
  6459. }
  6460. static
  6461. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6462. {
  6463. if (!elist)
  6464. return;
  6465. static struct string_elist *entry;
  6466. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6467. bool first = true;
  6468. DL_FOREACH(elist, entry)
  6469. {
  6470. const char * const s = entry->string;
  6471. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6472. first = false;
  6473. }
  6474. fprintf(fcfg, "\n]");
  6475. }
  6476. void write_config(FILE *fcfg)
  6477. {
  6478. int i;
  6479. /* Write pool values */
  6480. fputs("{\n\"pools\" : [", fcfg);
  6481. for(i = 0; i < total_pools; i++) {
  6482. struct pool *pool = pools[i];
  6483. if (pool->failover_only)
  6484. // Don't write failover-only (automatically added) pools to the config file for now
  6485. continue;
  6486. if (pool->quota != 1) {
  6487. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6488. pool->quota,
  6489. json_escape(pool->rpc_url));
  6490. } else {
  6491. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6492. json_escape(pool->rpc_url));
  6493. }
  6494. if (pool->rpc_proxy)
  6495. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6496. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6497. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6498. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6499. if (pool->force_rollntime)
  6500. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6501. fprintf(fcfg, "\n\t}");
  6502. }
  6503. fputs("\n]\n", fcfg);
  6504. #ifdef HAVE_OPENCL
  6505. write_config_opencl(fcfg);
  6506. #endif
  6507. #ifdef WANT_CPUMINE
  6508. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6509. #endif
  6510. /* Simple bool and int options */
  6511. struct opt_table *opt;
  6512. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6513. char *p, *name = strdup(opt->names);
  6514. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6515. if (p[1] != '-')
  6516. continue;
  6517. if (opt->type & OPT_NOARG &&
  6518. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6519. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6520. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6521. if (opt->type & OPT_HASARG &&
  6522. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6523. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6524. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6525. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6526. opt->desc != opt_hidden &&
  6527. 0 <= *(int *)opt->u.arg)
  6528. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6529. }
  6530. }
  6531. /* Special case options */
  6532. if (request_target_str)
  6533. {
  6534. if (request_pdiff == (long)request_pdiff)
  6535. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6536. else
  6537. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6538. }
  6539. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6540. if (pool_strategy == POOL_BALANCE)
  6541. fputs(",\n\"balance\" : true", fcfg);
  6542. if (pool_strategy == POOL_LOADBALANCE)
  6543. fputs(",\n\"load-balance\" : true", fcfg);
  6544. if (pool_strategy == POOL_ROUNDROBIN)
  6545. fputs(",\n\"round-robin\" : true", fcfg);
  6546. if (pool_strategy == POOL_ROTATE)
  6547. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6548. #if defined(unix) || defined(__APPLE__)
  6549. if (opt_stderr_cmd && *opt_stderr_cmd)
  6550. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6551. #endif // defined(unix)
  6552. if (opt_kernel_path && *opt_kernel_path) {
  6553. char *kpath = strdup(opt_kernel_path);
  6554. if (kpath[strlen(kpath)-1] == '/')
  6555. kpath[strlen(kpath)-1] = 0;
  6556. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6557. free(kpath);
  6558. }
  6559. if (schedstart.enable)
  6560. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6561. if (schedstop.enable)
  6562. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6563. if (opt_socks_proxy && *opt_socks_proxy)
  6564. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6565. _write_config_string_elist(fcfg, "scan", scan_devices);
  6566. #ifdef USE_LIBMICROHTTPD
  6567. if (httpsrv_port != -1)
  6568. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6569. #endif
  6570. #ifdef USE_LIBEVENT
  6571. if (stratumsrv_port != -1)
  6572. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6573. #endif
  6574. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6575. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6576. if (opt_api_allow)
  6577. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6578. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6579. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6580. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6581. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6582. if (*opt_api_mcast_des)
  6583. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6584. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6585. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6586. if (opt_api_groups)
  6587. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6588. fputs("\n}\n", fcfg);
  6589. json_escape_free();
  6590. }
  6591. void zero_bestshare(void)
  6592. {
  6593. int i;
  6594. best_diff = 0;
  6595. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6596. for (i = 0; i < total_pools; i++) {
  6597. struct pool *pool = pools[i];
  6598. pool->best_diff = 0;
  6599. }
  6600. }
  6601. void zero_stats(void)
  6602. {
  6603. int i;
  6604. applog(LOG_DEBUG, "Zeroing stats");
  6605. cgtime(&total_tv_start);
  6606. miner_started = total_tv_start;
  6607. total_rolling = 0;
  6608. total_mhashes_done = 0;
  6609. total_getworks = 0;
  6610. total_accepted = 0;
  6611. total_rejected = 0;
  6612. hw_errors = 0;
  6613. total_stale = 0;
  6614. total_discarded = 0;
  6615. total_bytes_rcvd = total_bytes_sent = 0;
  6616. new_blocks = 0;
  6617. local_work = 0;
  6618. total_go = 0;
  6619. total_ro = 0;
  6620. total_secs = 1.0;
  6621. total_diff1 = 0;
  6622. total_bad_diff1 = 0;
  6623. found_blocks = 0;
  6624. total_diff_accepted = 0;
  6625. total_diff_rejected = 0;
  6626. total_diff_stale = 0;
  6627. #ifdef HAVE_CURSES
  6628. awidth = rwidth = swidth = hwwidth = 1;
  6629. #endif
  6630. struct mining_goal_info *goal, *tmpgoal;
  6631. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6632. {
  6633. goal->diff_accepted = 0;
  6634. }
  6635. for (i = 0; i < total_pools; i++) {
  6636. struct pool *pool = pools[i];
  6637. pool->getwork_requested = 0;
  6638. pool->accepted = 0;
  6639. pool->rejected = 0;
  6640. pool->solved = 0;
  6641. pool->getwork_requested = 0;
  6642. pool->stale_shares = 0;
  6643. pool->discarded_work = 0;
  6644. pool->getfail_occasions = 0;
  6645. pool->remotefail_occasions = 0;
  6646. pool->last_share_time = 0;
  6647. pool->works = 0;
  6648. pool->diff1 = 0;
  6649. pool->diff_accepted = 0;
  6650. pool->diff_rejected = 0;
  6651. pool->diff_stale = 0;
  6652. pool->last_share_diff = 0;
  6653. pool->cgminer_stats.start_tv = total_tv_start;
  6654. pool->cgminer_stats.getwork_calls = 0;
  6655. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6656. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6657. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6658. pool->cgminer_pool_stats.getwork_calls = 0;
  6659. pool->cgminer_pool_stats.getwork_attempts = 0;
  6660. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6661. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6662. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6663. pool->cgminer_pool_stats.min_diff = 0;
  6664. pool->cgminer_pool_stats.max_diff = 0;
  6665. pool->cgminer_pool_stats.min_diff_count = 0;
  6666. pool->cgminer_pool_stats.max_diff_count = 0;
  6667. pool->cgminer_pool_stats.times_sent = 0;
  6668. pool->cgminer_pool_stats.bytes_sent = 0;
  6669. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6670. pool->cgminer_pool_stats.times_received = 0;
  6671. pool->cgminer_pool_stats.bytes_received = 0;
  6672. pool->cgminer_pool_stats.net_bytes_received = 0;
  6673. }
  6674. zero_bestshare();
  6675. for (i = 0; i < total_devices; ++i) {
  6676. struct cgpu_info *cgpu = get_devices(i);
  6677. mutex_lock(&hash_lock);
  6678. cgpu->total_mhashes = 0;
  6679. cgpu->accepted = 0;
  6680. cgpu->rejected = 0;
  6681. cgpu->stale = 0;
  6682. cgpu->hw_errors = 0;
  6683. cgpu->utility = 0.0;
  6684. cgpu->utility_diff1 = 0;
  6685. cgpu->last_share_pool_time = 0;
  6686. cgpu->bad_diff1 = 0;
  6687. cgpu->diff1 = 0;
  6688. cgpu->diff_accepted = 0;
  6689. cgpu->diff_rejected = 0;
  6690. cgpu->diff_stale = 0;
  6691. cgpu->last_share_diff = 0;
  6692. cgpu->thread_fail_init_count = 0;
  6693. cgpu->thread_zero_hash_count = 0;
  6694. cgpu->thread_fail_queue_count = 0;
  6695. cgpu->dev_sick_idle_60_count = 0;
  6696. cgpu->dev_dead_idle_600_count = 0;
  6697. cgpu->dev_nostart_count = 0;
  6698. cgpu->dev_over_heat_count = 0;
  6699. cgpu->dev_thermal_cutoff_count = 0;
  6700. cgpu->dev_comms_error_count = 0;
  6701. cgpu->dev_throttle_count = 0;
  6702. cgpu->cgminer_stats.start_tv = total_tv_start;
  6703. cgpu->cgminer_stats.getwork_calls = 0;
  6704. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6705. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6706. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6707. mutex_unlock(&hash_lock);
  6708. if (cgpu->drv->zero_stats)
  6709. cgpu->drv->zero_stats(cgpu);
  6710. }
  6711. }
  6712. #ifdef HAVE_CURSES
  6713. static
  6714. void loginput_mode(const int size)
  6715. {
  6716. clear_logwin();
  6717. loginput_size = size;
  6718. check_winsizes();
  6719. }
  6720. static void display_pools(void)
  6721. {
  6722. struct pool *pool;
  6723. int selected, i, j;
  6724. char input;
  6725. loginput_mode(7 + total_pools);
  6726. immedok(logwin, true);
  6727. updated:
  6728. for (j = 0; j < total_pools; j++) {
  6729. for (i = 0; i < total_pools; i++) {
  6730. pool = pools[i];
  6731. if (pool->prio != j)
  6732. continue;
  6733. if (pool == current_pool())
  6734. wattron(logwin, A_BOLD);
  6735. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  6736. wattron(logwin, A_DIM);
  6737. wlogprint("%d: ", pool->prio);
  6738. switch (pool->enabled) {
  6739. case POOL_ENABLED:
  6740. if (pool->failover_only)
  6741. wlogprint("Failover ");
  6742. else
  6743. wlogprint("Enabled ");
  6744. break;
  6745. case POOL_DISABLED:
  6746. wlogprint("Disabled ");
  6747. break;
  6748. case POOL_REJECTING:
  6749. wlogprint("Rejectin ");
  6750. break;
  6751. case POOL_MISBEHAVING:
  6752. wlogprint("Misbehav ");
  6753. break;
  6754. }
  6755. _wlogprint(pool_proto_str(pool));
  6756. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  6757. pool->quota,
  6758. pool->pool_no,
  6759. pool->rpc_url, pool->rpc_user);
  6760. wattroff(logwin, A_BOLD | A_DIM);
  6761. break; //for (i = 0; i < total_pools; i++)
  6762. }
  6763. }
  6764. retry:
  6765. wlogprint("\nCurrent pool management strategy: %s\n",
  6766. strategies[pool_strategy].s);
  6767. if (pool_strategy == POOL_ROTATE)
  6768. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6769. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6770. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6771. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6772. wlogprint("Or press any other key to continue\n");
  6773. logwin_update();
  6774. input = getch();
  6775. if (!strncasecmp(&input, "a", 1)) {
  6776. if (opt_benchmark)
  6777. {
  6778. wlogprint("Cannot add pools in benchmark mode");
  6779. goto retry;
  6780. }
  6781. input_pool(true);
  6782. goto updated;
  6783. } else if (!strncasecmp(&input, "r", 1)) {
  6784. if (total_pools <= 1) {
  6785. wlogprint("Cannot remove last pool");
  6786. goto retry;
  6787. }
  6788. selected = curses_int("Select pool number");
  6789. if (selected < 0 || selected >= total_pools) {
  6790. wlogprint("Invalid selection\n");
  6791. goto retry;
  6792. }
  6793. pool = pools[selected];
  6794. if (pool == current_pool())
  6795. switch_pools(NULL);
  6796. if (pool == current_pool()) {
  6797. wlogprint("Unable to remove pool due to activity\n");
  6798. goto retry;
  6799. }
  6800. remove_pool(pool);
  6801. goto updated;
  6802. } else if (!strncasecmp(&input, "s", 1)) {
  6803. selected = curses_int("Select pool number");
  6804. if (selected < 0 || selected >= total_pools) {
  6805. wlogprint("Invalid selection\n");
  6806. goto retry;
  6807. }
  6808. pool = pools[selected];
  6809. pool->failover_only = false;
  6810. switch_pools(pool);
  6811. goto updated;
  6812. } else if (!strncasecmp(&input, "d", 1)) {
  6813. if (enabled_pools <= 1) {
  6814. wlogprint("Cannot disable last pool");
  6815. goto retry;
  6816. }
  6817. selected = curses_int("Select pool number");
  6818. if (selected < 0 || selected >= total_pools) {
  6819. wlogprint("Invalid selection\n");
  6820. goto retry;
  6821. }
  6822. pool = pools[selected];
  6823. disable_pool(pool, POOL_DISABLED);
  6824. goto updated;
  6825. } else if (!strncasecmp(&input, "e", 1)) {
  6826. selected = curses_int("Select pool number");
  6827. if (selected < 0 || selected >= total_pools) {
  6828. wlogprint("Invalid selection\n");
  6829. goto retry;
  6830. }
  6831. pool = pools[selected];
  6832. pool->failover_only = false;
  6833. enable_pool(pool);
  6834. goto updated;
  6835. } else if (!strncasecmp(&input, "c", 1)) {
  6836. for (i = 0; i <= TOP_STRATEGY; i++)
  6837. wlogprint("%d: %s\n", i, strategies[i].s);
  6838. selected = curses_int("Select strategy number type");
  6839. if (selected < 0 || selected > TOP_STRATEGY) {
  6840. wlogprint("Invalid selection\n");
  6841. goto retry;
  6842. }
  6843. if (selected == POOL_ROTATE) {
  6844. opt_rotate_period = curses_int("Select interval in minutes");
  6845. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6846. opt_rotate_period = 0;
  6847. wlogprint("Invalid selection\n");
  6848. goto retry;
  6849. }
  6850. }
  6851. mutex_lock(&lp_lock);
  6852. pool_strategy = selected;
  6853. pthread_cond_broadcast(&lp_cond);
  6854. mutex_unlock(&lp_lock);
  6855. switch_pools(NULL);
  6856. goto updated;
  6857. } else if (!strncasecmp(&input, "i", 1)) {
  6858. selected = curses_int("Select pool number");
  6859. if (selected < 0 || selected >= total_pools) {
  6860. wlogprint("Invalid selection\n");
  6861. goto retry;
  6862. }
  6863. pool = pools[selected];
  6864. display_pool_summary(pool);
  6865. goto retry;
  6866. } else if (!strncasecmp(&input, "q", 1)) {
  6867. selected = curses_int("Select pool number");
  6868. if (selected < 0 || selected >= total_pools) {
  6869. wlogprint("Invalid selection\n");
  6870. goto retry;
  6871. }
  6872. pool = pools[selected];
  6873. selected = curses_int("Set quota");
  6874. if (selected < 0) {
  6875. wlogprint("Invalid negative quota\n");
  6876. goto retry;
  6877. }
  6878. pool->quota = selected;
  6879. adjust_quota_gcd();
  6880. goto updated;
  6881. } else if (!strncasecmp(&input, "f", 1)) {
  6882. opt_fail_only ^= true;
  6883. goto updated;
  6884. } else if (!strncasecmp(&input, "p", 1)) {
  6885. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6886. if (!prilist)
  6887. {
  6888. wlogprint("Not changing priorities\n");
  6889. goto retry;
  6890. }
  6891. int res = prioritize_pools(prilist, &i);
  6892. free(prilist);
  6893. switch (res) {
  6894. case MSG_NOPOOL:
  6895. wlogprint("No pools\n");
  6896. goto retry;
  6897. case MSG_MISPID:
  6898. wlogprint("Missing pool id parameter\n");
  6899. goto retry;
  6900. case MSG_INVPID:
  6901. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6902. goto retry;
  6903. case MSG_DUPPID:
  6904. wlogprint("Duplicate pool specified %d\n", i);
  6905. goto retry;
  6906. case MSG_POOLPRIO:
  6907. default:
  6908. goto updated;
  6909. }
  6910. }
  6911. immedok(logwin, false);
  6912. loginput_mode(0);
  6913. }
  6914. static const char *summary_detail_level_str(void)
  6915. {
  6916. if (opt_compact)
  6917. return "compact";
  6918. if (opt_show_procs)
  6919. return "processors";
  6920. return "devices";
  6921. }
  6922. static void display_options(void)
  6923. {
  6924. int selected;
  6925. char input;
  6926. immedok(logwin, true);
  6927. loginput_mode(12);
  6928. retry:
  6929. clear_logwin();
  6930. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6931. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6932. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6933. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6934. opt_debug_console ? "on" : "off",
  6935. want_per_device_stats? "on" : "off",
  6936. opt_quiet ? "on" : "off",
  6937. opt_log_output ? "on" : "off",
  6938. opt_protocol ? "on" : "off",
  6939. opt_worktime ? "on" : "off",
  6940. summary_detail_level_str(),
  6941. opt_log_interval,
  6942. opt_weighed_stats ? "weighed" : "absolute");
  6943. wlogprint("Select an option or any other key to return\n");
  6944. logwin_update();
  6945. input = getch();
  6946. if (!strncasecmp(&input, "q", 1)) {
  6947. opt_quiet ^= true;
  6948. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6949. goto retry;
  6950. } else if (!strncasecmp(&input, "v", 1)) {
  6951. opt_log_output ^= true;
  6952. if (opt_log_output)
  6953. opt_quiet = false;
  6954. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6955. goto retry;
  6956. } else if (!strncasecmp(&input, "n", 1)) {
  6957. opt_log_output = false;
  6958. opt_debug_console = false;
  6959. opt_quiet = false;
  6960. opt_protocol = false;
  6961. opt_compact = false;
  6962. opt_show_procs = false;
  6963. devsummaryYOffset = 0;
  6964. want_per_device_stats = false;
  6965. wlogprint("Output mode reset to normal\n");
  6966. switch_logsize();
  6967. goto retry;
  6968. } else if (!strncasecmp(&input, "d", 1)) {
  6969. opt_debug = true;
  6970. opt_debug_console ^= true;
  6971. opt_log_output = opt_debug_console;
  6972. if (opt_debug_console)
  6973. opt_quiet = false;
  6974. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6975. goto retry;
  6976. } else if (!strncasecmp(&input, "m", 1)) {
  6977. if (opt_compact)
  6978. opt_compact = false;
  6979. else
  6980. if (!opt_show_procs)
  6981. opt_show_procs = true;
  6982. else
  6983. {
  6984. opt_compact = true;
  6985. opt_show_procs = false;
  6986. devsummaryYOffset = 0;
  6987. }
  6988. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6989. switch_logsize();
  6990. goto retry;
  6991. } else if (!strncasecmp(&input, "p", 1)) {
  6992. want_per_device_stats ^= true;
  6993. opt_log_output = want_per_device_stats;
  6994. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6995. goto retry;
  6996. } else if (!strncasecmp(&input, "r", 1)) {
  6997. opt_protocol ^= true;
  6998. if (opt_protocol)
  6999. opt_quiet = false;
  7000. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7001. goto retry;
  7002. } else if (!strncasecmp(&input, "c", 1))
  7003. clear_logwin();
  7004. else if (!strncasecmp(&input, "l", 1)) {
  7005. selected = curses_int("Interval in seconds");
  7006. if (selected < 0 || selected > 9999) {
  7007. wlogprint("Invalid selection\n");
  7008. goto retry;
  7009. }
  7010. opt_log_interval = selected;
  7011. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7012. goto retry;
  7013. } else if (!strncasecmp(&input, "s", 1)) {
  7014. opt_realquiet = true;
  7015. } else if (!strncasecmp(&input, "w", 1)) {
  7016. opt_worktime ^= true;
  7017. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7018. goto retry;
  7019. } else if (!strncasecmp(&input, "t", 1)) {
  7020. opt_weighed_stats ^= true;
  7021. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7022. goto retry;
  7023. } else if (!strncasecmp(&input, "z", 1)) {
  7024. zero_stats();
  7025. goto retry;
  7026. }
  7027. immedok(logwin, false);
  7028. loginput_mode(0);
  7029. }
  7030. #endif
  7031. void default_save_file(char *filename)
  7032. {
  7033. #if defined(unix) || defined(__APPLE__)
  7034. if (getenv("HOME") && *getenv("HOME")) {
  7035. strcpy(filename, getenv("HOME"));
  7036. strcat(filename, "/");
  7037. }
  7038. else
  7039. strcpy(filename, "");
  7040. strcat(filename, ".bfgminer/");
  7041. mkdir(filename, 0777);
  7042. #else
  7043. strcpy(filename, "");
  7044. #endif
  7045. strcat(filename, def_conf);
  7046. }
  7047. #ifdef HAVE_CURSES
  7048. static void set_options(void)
  7049. {
  7050. int selected;
  7051. char input;
  7052. immedok(logwin, true);
  7053. loginput_mode(8);
  7054. retry:
  7055. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7056. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7057. "[W]rite config file\n[B]FGMiner restart\n",
  7058. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7059. wlogprint("Select an option or any other key to return\n");
  7060. logwin_update();
  7061. input = getch();
  7062. if (!strncasecmp(&input, "q", 1)) {
  7063. selected = curses_int("Extra work items to queue");
  7064. if (selected < 0 || selected > 9999) {
  7065. wlogprint("Invalid selection\n");
  7066. goto retry;
  7067. }
  7068. opt_queue = selected;
  7069. goto retry;
  7070. } else if (!strncasecmp(&input, "l", 1)) {
  7071. if (want_longpoll)
  7072. stop_longpoll();
  7073. else
  7074. start_longpoll();
  7075. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7076. goto retry;
  7077. } else if (!strncasecmp(&input, "s", 1)) {
  7078. selected = curses_int("Set scantime in seconds");
  7079. if (selected < 0 || selected > 9999) {
  7080. wlogprint("Invalid selection\n");
  7081. goto retry;
  7082. }
  7083. opt_scantime = selected;
  7084. goto retry;
  7085. } else if (!strncasecmp(&input, "e", 1)) {
  7086. selected = curses_int("Set expiry time in seconds");
  7087. if (selected < 0 || selected > 9999) {
  7088. wlogprint("Invalid selection\n");
  7089. goto retry;
  7090. }
  7091. opt_expiry = selected;
  7092. goto retry;
  7093. } else if (!strncasecmp(&input, "r", 1)) {
  7094. selected = curses_int("Retries before failing (-1 infinite)");
  7095. if (selected < -1 || selected > 9999) {
  7096. wlogprint("Invalid selection\n");
  7097. goto retry;
  7098. }
  7099. opt_retries = selected;
  7100. goto retry;
  7101. } else if (!strncasecmp(&input, "w", 1)) {
  7102. FILE *fcfg;
  7103. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7104. default_save_file(filename);
  7105. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7106. str = curses_input(prompt);
  7107. if (str) {
  7108. struct stat statbuf;
  7109. strcpy(filename, str);
  7110. free(str);
  7111. if (!stat(filename, &statbuf)) {
  7112. wlogprint("File exists, overwrite?\n");
  7113. input = getch();
  7114. if (strncasecmp(&input, "y", 1))
  7115. goto retry;
  7116. }
  7117. }
  7118. fcfg = fopen(filename, "w");
  7119. if (!fcfg) {
  7120. wlogprint("Cannot open or create file\n");
  7121. goto retry;
  7122. }
  7123. write_config(fcfg);
  7124. fclose(fcfg);
  7125. goto retry;
  7126. } else if (!strncasecmp(&input, "b", 1)) {
  7127. wlogprint("Are you sure?\n");
  7128. input = getch();
  7129. if (!strncasecmp(&input, "y", 1))
  7130. app_restart();
  7131. else
  7132. clear_logwin();
  7133. } else
  7134. clear_logwin();
  7135. loginput_mode(0);
  7136. immedok(logwin, false);
  7137. }
  7138. int scan_serial(const char *);
  7139. static
  7140. void _managetui_msg(const char *repr, const char **msg)
  7141. {
  7142. if (*msg)
  7143. {
  7144. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7145. wattron(logwin, A_BOLD);
  7146. wlogprint("%s", *msg);
  7147. wattroff(logwin, A_BOLD);
  7148. *msg = NULL;
  7149. }
  7150. logwin_update();
  7151. }
  7152. void manage_device(void)
  7153. {
  7154. char logline[256];
  7155. const char *msg = NULL;
  7156. struct cgpu_info *cgpu;
  7157. const struct device_drv *drv;
  7158. selecting_device = true;
  7159. immedok(logwin, true);
  7160. loginput_mode(12);
  7161. devchange:
  7162. if (unlikely(!total_devices))
  7163. {
  7164. clear_logwin();
  7165. wlogprint("(no devices)\n");
  7166. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7167. _managetui_msg("(none)", &msg);
  7168. int input = getch();
  7169. switch (input)
  7170. {
  7171. case '+': case '=': // add new device
  7172. goto addnew;
  7173. default:
  7174. goto out;
  7175. }
  7176. }
  7177. cgpu = devices[selected_device];
  7178. drv = cgpu->drv;
  7179. refresh_devstatus();
  7180. refresh:
  7181. clear_logwin();
  7182. wlogprint("Select processor to manage using up/down arrow keys\n");
  7183. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7184. wattron(logwin, A_BOLD);
  7185. wlogprint("%s", logline);
  7186. wattroff(logwin, A_BOLD);
  7187. wlogprint("\n");
  7188. if (cgpu->dev_manufacturer)
  7189. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7190. else
  7191. if (cgpu->dev_product)
  7192. wlogprint(" %s\n", cgpu->dev_product);
  7193. if (cgpu->dev_serial)
  7194. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7195. if (cgpu->kname)
  7196. wlogprint("Kernel: %s\n", cgpu->kname);
  7197. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7198. drv->proc_wlogprint_status(cgpu);
  7199. wlogprint("\n");
  7200. // TODO: Last share at TIMESTAMP on pool N
  7201. // TODO: Custom device info/commands
  7202. if (cgpu->deven != DEV_ENABLED)
  7203. wlogprint("[E]nable ");
  7204. if (cgpu->deven != DEV_DISABLED)
  7205. wlogprint("[D]isable ");
  7206. if (drv->identify_device)
  7207. wlogprint("[I]dentify ");
  7208. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7209. drv->proc_tui_wlogprint_choices(cgpu);
  7210. wlogprint("\n");
  7211. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7212. _managetui_msg(cgpu->proc_repr, &msg);
  7213. while (true)
  7214. {
  7215. int input = getch();
  7216. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7217. switch (input) {
  7218. case 'd': case 'D':
  7219. if (cgpu->deven == DEV_DISABLED)
  7220. msg = "Processor already disabled\n";
  7221. else
  7222. {
  7223. cgpu->deven = DEV_DISABLED;
  7224. msg = "Processor being disabled\n";
  7225. }
  7226. goto refresh;
  7227. case 'e': case 'E':
  7228. if (cgpu->deven == DEV_ENABLED)
  7229. msg = "Processor already enabled\n";
  7230. else
  7231. {
  7232. proc_enable(cgpu);
  7233. msg = "Processor being enabled\n";
  7234. }
  7235. goto refresh;
  7236. case 'i': case 'I':
  7237. if (drv->identify_device && drv->identify_device(cgpu))
  7238. msg = "Identify command sent\n";
  7239. else
  7240. goto key_default;
  7241. goto refresh;
  7242. case KEY_DOWN:
  7243. if (selected_device >= total_devices - 1)
  7244. break;
  7245. ++selected_device;
  7246. goto devchange;
  7247. case KEY_UP:
  7248. if (selected_device <= 0)
  7249. break;
  7250. --selected_device;
  7251. goto devchange;
  7252. case KEY_NPAGE:
  7253. {
  7254. if (selected_device >= total_devices - 1)
  7255. break;
  7256. struct cgpu_info *mdev = devices[selected_device]->device;
  7257. do {
  7258. ++selected_device;
  7259. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7260. goto devchange;
  7261. }
  7262. case KEY_PPAGE:
  7263. {
  7264. if (selected_device <= 0)
  7265. break;
  7266. struct cgpu_info *mdev = devices[selected_device]->device;
  7267. do {
  7268. --selected_device;
  7269. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7270. goto devchange;
  7271. }
  7272. case '/': case '?': // find device
  7273. {
  7274. static char *pattern = NULL;
  7275. char *newpattern = curses_input("Enter pattern");
  7276. if (newpattern)
  7277. {
  7278. free(pattern);
  7279. pattern = newpattern;
  7280. }
  7281. else
  7282. if (!pattern)
  7283. pattern = calloc(1, 1);
  7284. int match = cgpu_search(pattern, selected_device + 1);
  7285. if (match == -1)
  7286. {
  7287. msg = "Couldn't find device\n";
  7288. goto refresh;
  7289. }
  7290. selected_device = match;
  7291. goto devchange;
  7292. }
  7293. case '+': case '=': // add new device
  7294. {
  7295. addnew:
  7296. clear_logwin();
  7297. _wlogprint(
  7298. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7299. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7300. "For example: erupter:"
  7301. #ifdef WIN32
  7302. "\\\\.\\COM40"
  7303. #elif defined(__APPLE__)
  7304. "/dev/cu.SLAB_USBtoUART"
  7305. #else
  7306. "/dev/ttyUSB39"
  7307. #endif
  7308. "\n"
  7309. );
  7310. char *scanser = curses_input("Enter target");
  7311. if (scan_serial(scanser))
  7312. {
  7313. selected_device = total_devices - 1;
  7314. msg = "Device scan succeeded\n";
  7315. }
  7316. else
  7317. msg = "No new devices found\n";
  7318. goto devchange;
  7319. }
  7320. case 'Q': case 'q':
  7321. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7322. case '\x1b': // ESC
  7323. case KEY_ENTER:
  7324. case '\r': // Ctrl-M on Windows, with nonl
  7325. #ifdef PADENTER
  7326. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7327. #endif
  7328. case '\n':
  7329. goto out;
  7330. default:
  7331. ;
  7332. key_default:
  7333. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7334. {
  7335. msg = drv->proc_tui_handle_choice(cgpu, input);
  7336. if (msg)
  7337. goto refresh;
  7338. }
  7339. }
  7340. }
  7341. out:
  7342. selecting_device = false;
  7343. loginput_mode(0);
  7344. immedok(logwin, false);
  7345. }
  7346. void show_help(void)
  7347. {
  7348. loginput_mode(11);
  7349. // NOTE: wlogprint is a macro with a buffer limit
  7350. _wlogprint(
  7351. "LU: oldest explicit work update currently being used for new work\n"
  7352. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7353. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7354. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7355. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7356. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7357. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7358. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7359. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7360. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7361. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7362. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7363. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7364. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7365. "\n"
  7366. "devices/processors hashing (only for totals line), hottest temperature\n"
  7367. );
  7368. wlogprint(
  7369. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7370. , opt_log_interval);
  7371. _wlogprint(
  7372. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7373. "HW: hardware errors / % nonces invalid\n"
  7374. "\n"
  7375. "Press any key to clear"
  7376. );
  7377. logwin_update();
  7378. getch();
  7379. loginput_mode(0);
  7380. }
  7381. static void *input_thread(void __maybe_unused *userdata)
  7382. {
  7383. RenameThread("input");
  7384. if (!curses_active)
  7385. return NULL;
  7386. while (1) {
  7387. int input;
  7388. input = getch();
  7389. switch (input) {
  7390. case 'h': case 'H': case '?':
  7391. case KEY_F(1):
  7392. show_help();
  7393. break;
  7394. case 'q': case 'Q':
  7395. kill_work();
  7396. return NULL;
  7397. case 'd': case 'D':
  7398. display_options();
  7399. break;
  7400. case 'm': case 'M':
  7401. manage_device();
  7402. break;
  7403. case 'p': case 'P':
  7404. display_pools();
  7405. break;
  7406. case 's': case 'S':
  7407. set_options();
  7408. break;
  7409. #ifdef HAVE_CURSES
  7410. case KEY_DOWN:
  7411. {
  7412. const int visible_lines = logcursor - devcursor;
  7413. const int invisible_lines = total_lines - visible_lines;
  7414. if (devsummaryYOffset <= -invisible_lines)
  7415. break;
  7416. devsummaryYOffset -= 2;
  7417. }
  7418. case KEY_UP:
  7419. if (devsummaryYOffset == 0)
  7420. break;
  7421. ++devsummaryYOffset;
  7422. refresh_devstatus();
  7423. break;
  7424. case KEY_NPAGE:
  7425. {
  7426. const int visible_lines = logcursor - devcursor;
  7427. const int invisible_lines = total_lines - visible_lines;
  7428. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7429. devsummaryYOffset = -invisible_lines;
  7430. else
  7431. devsummaryYOffset -= visible_lines;
  7432. refresh_devstatus();
  7433. break;
  7434. }
  7435. case KEY_PPAGE:
  7436. {
  7437. const int visible_lines = logcursor - devcursor;
  7438. if (devsummaryYOffset + visible_lines >= 0)
  7439. devsummaryYOffset = 0;
  7440. else
  7441. devsummaryYOffset += visible_lines;
  7442. refresh_devstatus();
  7443. break;
  7444. }
  7445. #endif
  7446. }
  7447. if (opt_realquiet) {
  7448. disable_curses();
  7449. break;
  7450. }
  7451. }
  7452. return NULL;
  7453. }
  7454. #endif
  7455. static void *api_thread(void *userdata)
  7456. {
  7457. struct thr_info *mythr = userdata;
  7458. pthread_detach(pthread_self());
  7459. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7460. RenameThread("rpc");
  7461. api(api_thr_id);
  7462. mythr->has_pth = false;
  7463. return NULL;
  7464. }
  7465. void thread_reportin(struct thr_info *thr)
  7466. {
  7467. cgtime(&thr->last);
  7468. thr->cgpu->status = LIFE_WELL;
  7469. thr->getwork = 0;
  7470. thr->cgpu->device_last_well = time(NULL);
  7471. }
  7472. void thread_reportout(struct thr_info *thr)
  7473. {
  7474. thr->getwork = time(NULL);
  7475. }
  7476. static void hashmeter(int thr_id, struct timeval *diff,
  7477. uint64_t hashes_done)
  7478. {
  7479. char logstatusline[256];
  7480. struct timeval temp_tv_end, total_diff;
  7481. double secs;
  7482. double local_secs;
  7483. static double local_mhashes_done = 0;
  7484. double local_mhashes = (double)hashes_done / 1000000.0;
  7485. bool showlog = false;
  7486. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7487. char rejpcbuf[6];
  7488. char bnbuf[6];
  7489. struct thr_info *thr;
  7490. /* Update the last time this thread reported in */
  7491. if (thr_id >= 0) {
  7492. thr = get_thread(thr_id);
  7493. cgtime(&(thr->last));
  7494. thr->cgpu->device_last_well = time(NULL);
  7495. }
  7496. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7497. /* So we can call hashmeter from a non worker thread */
  7498. if (thr_id >= 0) {
  7499. struct cgpu_info *cgpu = thr->cgpu;
  7500. int threadobj = cgpu->threads ?: 1;
  7501. double thread_rolling = 0.0;
  7502. int i;
  7503. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7504. thr_id, hashes_done, hashes_done / 1000 / secs);
  7505. /* Rolling average for each thread and each device */
  7506. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7507. for (i = 0; i < threadobj; i++)
  7508. thread_rolling += cgpu->thr[i]->rolling;
  7509. mutex_lock(&hash_lock);
  7510. decay_time(&cgpu->rolling, thread_rolling, secs);
  7511. cgpu->total_mhashes += local_mhashes;
  7512. mutex_unlock(&hash_lock);
  7513. // If needed, output detailed, per-device stats
  7514. if (want_per_device_stats) {
  7515. struct timeval now;
  7516. struct timeval elapsed;
  7517. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7518. cgtime(&now);
  7519. timersub(&now, last_msg_tv, &elapsed);
  7520. if (opt_log_interval <= elapsed.tv_sec) {
  7521. struct cgpu_info *cgpu = thr->cgpu;
  7522. char logline[255];
  7523. *last_msg_tv = now;
  7524. get_statline(logline, sizeof(logline), cgpu);
  7525. if (!curses_active) {
  7526. printf("\n%s\r", logline);
  7527. fflush(stdout);
  7528. } else
  7529. applog(LOG_INFO, "%s", logline);
  7530. }
  7531. }
  7532. }
  7533. /* Totals are updated by all threads so can race without locking */
  7534. mutex_lock(&hash_lock);
  7535. cgtime(&temp_tv_end);
  7536. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7537. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7538. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7539. total_mhashes_done += local_mhashes;
  7540. local_mhashes_done += local_mhashes;
  7541. /* Only update with opt_log_interval */
  7542. if (total_diff.tv_sec < opt_log_interval)
  7543. goto out_unlock;
  7544. showlog = true;
  7545. cgtime(&total_tv_end);
  7546. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7547. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7548. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7549. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7550. multi_format_unit_array2(
  7551. ((char*[]){cHr, aHr, uHr}),
  7552. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7553. true, "h/s", H2B_SHORT,
  7554. 3,
  7555. 1e6*total_rolling,
  7556. 1e6*total_mhashes_done / total_secs,
  7557. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7558. int ui_accepted, ui_rejected, ui_stale;
  7559. if (opt_weighed_stats)
  7560. {
  7561. ui_accepted = total_diff_accepted;
  7562. ui_rejected = total_diff_rejected;
  7563. ui_stale = total_diff_stale;
  7564. }
  7565. else
  7566. {
  7567. ui_accepted = total_accepted;
  7568. ui_rejected = total_rejected;
  7569. ui_stale = total_stale;
  7570. }
  7571. #ifdef HAVE_CURSES
  7572. if (curses_active_locked()) {
  7573. float temp = 0;
  7574. struct cgpu_info *proc, *last_working_dev = NULL;
  7575. int i, working_devs = 0, working_procs = 0;
  7576. int divx;
  7577. bool bad = false;
  7578. // Find the highest temperature of all processors
  7579. for (i = 0; i < total_devices; ++i)
  7580. {
  7581. proc = get_devices(i);
  7582. if (proc->temp > temp)
  7583. temp = proc->temp;
  7584. if (unlikely(proc->deven == DEV_DISABLED))
  7585. ; // Just need to block it off from both conditions
  7586. else
  7587. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7588. {
  7589. if (proc->rolling > .1)
  7590. {
  7591. ++working_procs;
  7592. if (proc->device != last_working_dev)
  7593. {
  7594. ++working_devs;
  7595. last_working_dev = proc->device;
  7596. }
  7597. }
  7598. }
  7599. else
  7600. bad = true;
  7601. }
  7602. if (working_devs == working_procs)
  7603. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7604. else
  7605. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7606. divx = 7;
  7607. if (opt_show_procs && !opt_compact)
  7608. divx += max_lpdigits;
  7609. if (bad)
  7610. {
  7611. divx += sizeof(U8_BAD_START)-1;
  7612. strcpy(&statusline[divx], U8_BAD_END);
  7613. divx += sizeof(U8_BAD_END)-1;
  7614. }
  7615. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7616. format_statline(statusline, sizeof(statusline),
  7617. cHr, aHr,
  7618. uHr,
  7619. ui_accepted,
  7620. ui_rejected,
  7621. ui_stale,
  7622. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7623. hw_errors,
  7624. total_bad_diff1, total_bad_diff1 + total_diff1);
  7625. unlock_curses();
  7626. }
  7627. #endif
  7628. // Add a space
  7629. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7630. uHr[5] = ' ';
  7631. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7632. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7633. snprintf(logstatusline, sizeof(logstatusline),
  7634. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7635. want_per_device_stats ? "ALL " : "",
  7636. opt_log_interval,
  7637. cHr, aHr,
  7638. uHr,
  7639. ui_accepted,
  7640. ui_rejected,
  7641. ui_stale,
  7642. rejpcbuf,
  7643. hw_errors,
  7644. bnbuf
  7645. );
  7646. local_mhashes_done = 0;
  7647. out_unlock:
  7648. mutex_unlock(&hash_lock);
  7649. if (showlog) {
  7650. if (!curses_active) {
  7651. if (want_per_device_stats)
  7652. printf("\n%s\r", logstatusline);
  7653. else
  7654. {
  7655. const int logstatusline_len = strlen(logstatusline);
  7656. int padding;
  7657. if (last_logstatusline_len > logstatusline_len)
  7658. padding = (last_logstatusline_len - logstatusline_len);
  7659. else
  7660. {
  7661. padding = 0;
  7662. if (last_logstatusline_len == -1)
  7663. puts("");
  7664. }
  7665. printf("%s%*s\r", logstatusline, padding, "");
  7666. last_logstatusline_len = logstatusline_len;
  7667. }
  7668. fflush(stdout);
  7669. } else
  7670. applog(LOG_INFO, "%s", logstatusline);
  7671. }
  7672. }
  7673. void hashmeter2(struct thr_info *thr)
  7674. {
  7675. struct timeval tv_now, tv_elapsed;
  7676. timerclear(&thr->tv_hashes_done);
  7677. cgtime(&tv_now);
  7678. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7679. /* Update the hashmeter at most 5 times per second */
  7680. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7681. tv_elapsed.tv_sec >= opt_log_interval) {
  7682. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7683. thr->hashes_done = 0;
  7684. thr->tv_lastupdate = tv_now;
  7685. }
  7686. }
  7687. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7688. struct stratum_share *sshare)
  7689. {
  7690. struct work *work = sshare->work;
  7691. share_result(val, res_val, err_val, work, false, "");
  7692. }
  7693. /* Parses stratum json responses and tries to find the id that the request
  7694. * matched to and treat it accordingly. */
  7695. bool parse_stratum_response(struct pool *pool, char *s)
  7696. {
  7697. json_t *val = NULL, *err_val, *res_val, *id_val;
  7698. struct stratum_share *sshare;
  7699. json_error_t err;
  7700. bool ret = false;
  7701. int id;
  7702. val = JSON_LOADS(s, &err);
  7703. if (!val) {
  7704. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7705. goto out;
  7706. }
  7707. res_val = json_object_get(val, "result");
  7708. err_val = json_object_get(val, "error");
  7709. id_val = json_object_get(val, "id");
  7710. if (json_is_null(id_val) || !id_val) {
  7711. char *ss;
  7712. if (err_val)
  7713. ss = json_dumps(err_val, JSON_INDENT(3));
  7714. else
  7715. ss = strdup("(unknown reason)");
  7716. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7717. free(ss);
  7718. goto out;
  7719. }
  7720. if (!json_is_integer(id_val)) {
  7721. if (json_is_string(id_val)
  7722. && !strncmp(json_string_value(id_val), "txlist", 6))
  7723. {
  7724. const bool is_array = json_is_array(res_val);
  7725. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7726. is_array ? "transaction list" : "no-transaction-list response",
  7727. pool->pool_no, &json_string_value(id_val)[6]);
  7728. if (!is_array)
  7729. {
  7730. // No need to wait for a timeout
  7731. timer_unset(&pool->swork.tv_transparency);
  7732. pool_set_opaque(pool, true);
  7733. goto fishy;
  7734. }
  7735. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7736. // We only care about a transaction list for the current job id
  7737. goto fishy;
  7738. // Check that the transactions actually hash to the merkle links
  7739. {
  7740. unsigned maxtx = 1 << pool->swork.merkles;
  7741. unsigned mintx = maxtx >> 1;
  7742. --maxtx;
  7743. unsigned acttx = (unsigned)json_array_size(res_val);
  7744. if (acttx < mintx || acttx > maxtx) {
  7745. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7746. pool->pool_no, acttx, mintx, maxtx);
  7747. goto fishy;
  7748. }
  7749. // TODO: Check hashes match actual merkle links
  7750. }
  7751. pool_set_opaque(pool, false);
  7752. timer_unset(&pool->swork.tv_transparency);
  7753. fishy:
  7754. ret = true;
  7755. }
  7756. goto out;
  7757. }
  7758. id = json_integer_value(id_val);
  7759. mutex_lock(&sshare_lock);
  7760. HASH_FIND_INT(stratum_shares, &id, sshare);
  7761. if (sshare)
  7762. HASH_DEL(stratum_shares, sshare);
  7763. mutex_unlock(&sshare_lock);
  7764. if (!sshare) {
  7765. double pool_diff;
  7766. /* Since the share is untracked, we can only guess at what the
  7767. * work difficulty is based on the current pool diff. */
  7768. cg_rlock(&pool->data_lock);
  7769. pool_diff = target_diff(pool->swork.target);
  7770. cg_runlock(&pool->data_lock);
  7771. if (json_is_true(res_val)) {
  7772. struct mining_goal_info * const goal = pool->goal;
  7773. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  7774. /* We don't know what device this came from so we can't
  7775. * attribute the work to the relevant cgpu */
  7776. mutex_lock(&stats_lock);
  7777. total_accepted++;
  7778. pool->accepted++;
  7779. total_diff_accepted += pool_diff;
  7780. pool->diff_accepted += pool_diff;
  7781. goal->diff_accepted += pool_diff;
  7782. mutex_unlock(&stats_lock);
  7783. } else {
  7784. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  7785. mutex_lock(&stats_lock);
  7786. total_rejected++;
  7787. pool->rejected++;
  7788. total_diff_rejected += pool_diff;
  7789. pool->diff_rejected += pool_diff;
  7790. mutex_unlock(&stats_lock);
  7791. }
  7792. goto out;
  7793. }
  7794. else {
  7795. mutex_lock(&submitting_lock);
  7796. --total_submitting;
  7797. mutex_unlock(&submitting_lock);
  7798. }
  7799. stratum_share_result(val, res_val, err_val, sshare);
  7800. free_work(sshare->work);
  7801. free(sshare);
  7802. ret = true;
  7803. out:
  7804. if (val)
  7805. json_decref(val);
  7806. return ret;
  7807. }
  7808. static void shutdown_stratum(struct pool *pool)
  7809. {
  7810. // Shut down Stratum as if we never had it
  7811. pool->stratum_active = false;
  7812. pool->stratum_init = false;
  7813. pool->has_stratum = false;
  7814. shutdown(pool->sock, SHUT_RDWR);
  7815. free(pool->stratum_url);
  7816. if (pool->sockaddr_url == pool->stratum_url)
  7817. pool->sockaddr_url = NULL;
  7818. pool->stratum_url = NULL;
  7819. }
  7820. void clear_stratum_shares(struct pool *pool)
  7821. {
  7822. int my_mining_threads = mining_threads; // Cached outside of locking
  7823. struct stratum_share *sshare, *tmpshare;
  7824. struct work *work;
  7825. struct cgpu_info *cgpu;
  7826. double diff_cleared = 0;
  7827. double thr_diff_cleared[my_mining_threads];
  7828. int cleared = 0;
  7829. int thr_cleared[my_mining_threads];
  7830. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7831. for (int i = 0; i < my_mining_threads; ++i)
  7832. {
  7833. thr_diff_cleared[i] = 0;
  7834. thr_cleared[i] = 0;
  7835. }
  7836. mutex_lock(&sshare_lock);
  7837. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7838. work = sshare->work;
  7839. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7840. HASH_DEL(stratum_shares, sshare);
  7841. sharelog("disconnect", work);
  7842. diff_cleared += sshare->work->work_difficulty;
  7843. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7844. ++thr_cleared[work->thr_id];
  7845. free_work(sshare->work);
  7846. free(sshare);
  7847. cleared++;
  7848. }
  7849. }
  7850. mutex_unlock(&sshare_lock);
  7851. if (cleared) {
  7852. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7853. mutex_lock(&stats_lock);
  7854. pool->stale_shares += cleared;
  7855. total_stale += cleared;
  7856. pool->diff_stale += diff_cleared;
  7857. total_diff_stale += diff_cleared;
  7858. for (int i = 0; i < my_mining_threads; ++i)
  7859. if (thr_cleared[i])
  7860. {
  7861. cgpu = get_thr_cgpu(i);
  7862. cgpu->diff_stale += thr_diff_cleared[i];
  7863. cgpu->stale += thr_cleared[i];
  7864. }
  7865. mutex_unlock(&stats_lock);
  7866. mutex_lock(&submitting_lock);
  7867. total_submitting -= cleared;
  7868. mutex_unlock(&submitting_lock);
  7869. }
  7870. }
  7871. static void resubmit_stratum_shares(struct pool *pool)
  7872. {
  7873. struct stratum_share *sshare, *tmpshare;
  7874. struct work *work;
  7875. unsigned resubmitted = 0;
  7876. mutex_lock(&sshare_lock);
  7877. mutex_lock(&submitting_lock);
  7878. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7879. if (sshare->work->pool != pool)
  7880. continue;
  7881. HASH_DEL(stratum_shares, sshare);
  7882. work = sshare->work;
  7883. DL_APPEND(submit_waiting, work);
  7884. free(sshare);
  7885. ++resubmitted;
  7886. }
  7887. mutex_unlock(&submitting_lock);
  7888. mutex_unlock(&sshare_lock);
  7889. if (resubmitted) {
  7890. notifier_wake(submit_waiting_notifier);
  7891. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7892. }
  7893. }
  7894. static void clear_pool_work(struct pool *pool)
  7895. {
  7896. struct work *work, *tmp;
  7897. int cleared = 0;
  7898. mutex_lock(stgd_lock);
  7899. HASH_ITER(hh, staged_work, work, tmp) {
  7900. if (work->pool == pool) {
  7901. HASH_DEL(staged_work, work);
  7902. free_work(work);
  7903. cleared++;
  7904. staged_full = false;
  7905. }
  7906. }
  7907. mutex_unlock(stgd_lock);
  7908. }
  7909. static int cp_prio(void)
  7910. {
  7911. int prio;
  7912. cg_rlock(&control_lock);
  7913. prio = currentpool->prio;
  7914. cg_runlock(&control_lock);
  7915. return prio;
  7916. }
  7917. /* We only need to maintain a secondary pool connection when we need the
  7918. * capacity to get work from the backup pools while still on the primary */
  7919. static bool cnx_needed(struct pool *pool)
  7920. {
  7921. struct pool *cp;
  7922. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  7923. if (pool->enabled == POOL_DISABLED)
  7924. return false;
  7925. /* Idle stratum pool needs something to kick it alive again */
  7926. if (pool->has_stratum && pool->idle)
  7927. return true;
  7928. /* Getwork pools without opt_fail_only need backup pools up to be able
  7929. * to leak shares */
  7930. cp = current_pool();
  7931. if (pool_actively_desired(pool, cp))
  7932. return true;
  7933. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7934. return true;
  7935. /* Keep the connection open to allow any stray shares to be submitted
  7936. * on switching pools for 2 minutes. */
  7937. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  7938. return true;
  7939. /* If the pool has only just come to life and is higher priority than
  7940. * the current pool keep the connection open so we can fail back to
  7941. * it. */
  7942. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7943. return true;
  7944. if (pool_unworkable(cp))
  7945. return true;
  7946. /* We've run out of work, bring anything back to life. */
  7947. if (no_work)
  7948. return true;
  7949. // If the current pool lacks its own block change detection, see if we are needed for that
  7950. if (pool_active_lp_pool(cp) == pool)
  7951. return true;
  7952. return false;
  7953. }
  7954. static void wait_lpcurrent(struct pool *pool);
  7955. static void pool_resus(struct pool *pool);
  7956. static void stratum_resumed(struct pool *pool)
  7957. {
  7958. if (!pool->stratum_notify)
  7959. return;
  7960. if (pool_tclear(pool, &pool->idle)) {
  7961. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7962. pool_resus(pool);
  7963. }
  7964. }
  7965. static bool supports_resume(struct pool *pool)
  7966. {
  7967. bool ret;
  7968. cg_rlock(&pool->data_lock);
  7969. ret = (pool->sessionid != NULL);
  7970. cg_runlock(&pool->data_lock);
  7971. return ret;
  7972. }
  7973. static bool pools_active;
  7974. /* One stratum thread per pool that has stratum waits on the socket checking
  7975. * for new messages and for the integrity of the socket connection. We reset
  7976. * the connection based on the integrity of the receive side only as the send
  7977. * side will eventually expire data it fails to send. */
  7978. static void *stratum_thread(void *userdata)
  7979. {
  7980. struct pool *pool = (struct pool *)userdata;
  7981. pthread_detach(pthread_self());
  7982. char threadname[20];
  7983. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7984. RenameThread(threadname);
  7985. srand(time(NULL) + (intptr_t)userdata);
  7986. while (42) {
  7987. struct timeval timeout;
  7988. int sel_ret;
  7989. fd_set rd;
  7990. char *s;
  7991. int sock;
  7992. if (unlikely(!pool->has_stratum))
  7993. break;
  7994. /* Check to see whether we need to maintain this connection
  7995. * indefinitely or just bring it up when we switch to this
  7996. * pool */
  7997. while (true)
  7998. {
  7999. sock = pool->sock;
  8000. if (sock == INVSOCK)
  8001. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8002. pool->pool_no);
  8003. else
  8004. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8005. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8006. pool->pool_no);
  8007. else
  8008. break;
  8009. suspend_stratum(pool);
  8010. clear_stratum_shares(pool);
  8011. clear_pool_work(pool);
  8012. wait_lpcurrent(pool);
  8013. if (!restart_stratum(pool)) {
  8014. pool_died(pool);
  8015. while (!restart_stratum(pool)) {
  8016. if (pool->removed)
  8017. goto out;
  8018. cgsleep_ms(30000);
  8019. }
  8020. }
  8021. }
  8022. FD_ZERO(&rd);
  8023. FD_SET(sock, &rd);
  8024. timeout.tv_sec = 120;
  8025. timeout.tv_usec = 0;
  8026. /* If we fail to receive any notify messages for 2 minutes we
  8027. * assume the connection has been dropped and treat this pool
  8028. * as dead */
  8029. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8030. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8031. s = NULL;
  8032. } else
  8033. s = recv_line(pool);
  8034. if (!s) {
  8035. if (!pool->has_stratum)
  8036. break;
  8037. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8038. pool->getfail_occasions++;
  8039. total_go++;
  8040. mutex_lock(&pool->stratum_lock);
  8041. pool->stratum_active = pool->stratum_notify = false;
  8042. pool->sock = INVSOCK;
  8043. mutex_unlock(&pool->stratum_lock);
  8044. /* If the socket to our stratum pool disconnects, all
  8045. * submissions need to be discarded or resent. */
  8046. if (!supports_resume(pool))
  8047. clear_stratum_shares(pool);
  8048. else
  8049. resubmit_stratum_shares(pool);
  8050. clear_pool_work(pool);
  8051. if (pool == current_pool())
  8052. restart_threads();
  8053. if (restart_stratum(pool))
  8054. continue;
  8055. shutdown_stratum(pool);
  8056. pool_died(pool);
  8057. break;
  8058. }
  8059. /* Check this pool hasn't died while being a backup pool and
  8060. * has not had its idle flag cleared */
  8061. stratum_resumed(pool);
  8062. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8063. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8064. free(s);
  8065. if (pool->swork.clean) {
  8066. struct work *work = make_work();
  8067. /* Generate a single work item to update the current
  8068. * block database */
  8069. pool->swork.clean = false;
  8070. gen_stratum_work(pool, work);
  8071. /* Try to extract block height from coinbase scriptSig */
  8072. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8073. unsigned char cb_height_sz;
  8074. cb_height_sz = bin_height[-1];
  8075. if (cb_height_sz == 3) {
  8076. // FIXME: The block number will overflow this by AD 2173
  8077. struct mining_goal_info * const goal = pool->goal;
  8078. const void * const prevblkhash = &work->data[4];
  8079. uint32_t height = 0;
  8080. memcpy(&height, bin_height, 3);
  8081. height = le32toh(height);
  8082. have_block_height(goal, prevblkhash, height);
  8083. }
  8084. pool->swork.work_restart_id =
  8085. ++pool->work_restart_id;
  8086. pool_update_work_restart_time(pool);
  8087. if (test_work_current(work)) {
  8088. /* Only accept a work update if this stratum
  8089. * connection is from the current pool */
  8090. struct pool * const cp = current_pool();
  8091. if (pool == cp)
  8092. restart_threads();
  8093. applog(
  8094. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8095. "Stratum from pool %d requested work update", pool->pool_no);
  8096. } else
  8097. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8098. free_work(work);
  8099. }
  8100. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8101. // More than 4 timmills past since requested transactions
  8102. timer_unset(&pool->swork.tv_transparency);
  8103. pool_set_opaque(pool, true);
  8104. }
  8105. }
  8106. out:
  8107. return NULL;
  8108. }
  8109. static void init_stratum_thread(struct pool *pool)
  8110. {
  8111. have_longpoll = true;
  8112. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8113. quit(1, "Failed to create stratum thread");
  8114. }
  8115. static void *longpoll_thread(void *userdata);
  8116. static bool stratum_works(struct pool *pool)
  8117. {
  8118. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8119. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8120. return false;
  8121. if (pool->stratum_active)
  8122. return true;
  8123. if (!initiate_stratum(pool))
  8124. return false;
  8125. return true;
  8126. }
  8127. static
  8128. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8129. {
  8130. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8131. }
  8132. static bool pool_active(struct pool *pool, bool pinging)
  8133. {
  8134. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8135. bool ret = false;
  8136. json_t *val;
  8137. CURL *curl = NULL;
  8138. int rolltime;
  8139. char *rpc_req;
  8140. struct work *work;
  8141. enum pool_protocol proto;
  8142. if (pool->stratum_init)
  8143. {
  8144. if (pool->stratum_active)
  8145. return true;
  8146. }
  8147. else
  8148. if (!pool->idle)
  8149. {
  8150. timer_set_now(&tv_now);
  8151. if (pool_recently_got_work(pool, &tv_now))
  8152. return true;
  8153. }
  8154. mutex_lock(&pool->pool_test_lock);
  8155. if (pool->stratum_init)
  8156. {
  8157. ret = pool->stratum_active;
  8158. goto out;
  8159. }
  8160. timer_set_now(&tv_now);
  8161. if (pool->idle)
  8162. {
  8163. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8164. goto out;
  8165. }
  8166. else
  8167. if (pool_recently_got_work(pool, &tv_now))
  8168. {
  8169. ret = true;
  8170. goto out;
  8171. }
  8172. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8173. /* This is the central point we activate stratum when we can */
  8174. curl = curl_easy_init();
  8175. if (unlikely(!curl)) {
  8176. applog(LOG_ERR, "CURL initialisation failed");
  8177. goto out;
  8178. }
  8179. if (!(want_gbt || want_getwork))
  8180. goto nohttp;
  8181. work = make_work();
  8182. /* Probe for GBT support on first pass */
  8183. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8184. tryagain:
  8185. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8186. work->pool = pool;
  8187. if (!rpc_req)
  8188. goto out;
  8189. pool->probed = false;
  8190. cgtime(&tv_getwork);
  8191. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8192. true, false, &rolltime, pool, false);
  8193. cgtime(&tv_getwork_reply);
  8194. free(rpc_req);
  8195. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8196. * and if so, switch to that in preference to getwork if it works */
  8197. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8198. if (!pool->has_stratum) {
  8199. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8200. if (!pool->rpc_url)
  8201. pool_set_uri(pool, strdup(pool->stratum_url));
  8202. pool->has_stratum = true;
  8203. }
  8204. free_work(work);
  8205. if (val)
  8206. json_decref(val);
  8207. retry_stratum:
  8208. ;
  8209. /* We create the stratum thread for each pool just after
  8210. * successful authorisation. Once the init flag has been set
  8211. * we never unset it and the stratum thread is responsible for
  8212. * setting/unsetting the active flag */
  8213. bool init = pool_tset(pool, &pool->stratum_init);
  8214. if (!init) {
  8215. ret = initiate_stratum(pool) && auth_stratum(pool);
  8216. if (ret)
  8217. {
  8218. detect_algo = 2;
  8219. init_stratum_thread(pool);
  8220. }
  8221. else
  8222. {
  8223. pool_tclear(pool, &pool->stratum_init);
  8224. pool->tv_idle = tv_getwork_reply;
  8225. }
  8226. goto out;
  8227. }
  8228. ret = pool->stratum_active;
  8229. goto out;
  8230. }
  8231. else if (pool->has_stratum)
  8232. shutdown_stratum(pool);
  8233. if (val) {
  8234. bool rc;
  8235. json_t *res;
  8236. res = json_object_get(val, "result");
  8237. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8238. goto badwork;
  8239. work->rolltime = rolltime;
  8240. rc = work_decode(pool, work, val);
  8241. if (rc) {
  8242. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8243. pool->pool_no, pool->rpc_url);
  8244. work->pool = pool;
  8245. copy_time(&work->tv_getwork, &tv_getwork);
  8246. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8247. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8248. calc_diff(work, 0);
  8249. update_last_work(work);
  8250. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8251. stage_work(work);
  8252. total_getworks++;
  8253. pool->getwork_requested++;
  8254. ret = true;
  8255. pool->tv_idle = tv_getwork_reply;
  8256. } else {
  8257. badwork:
  8258. json_decref(val);
  8259. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8260. pool->pool_no, pool->rpc_url);
  8261. pool->proto = proto = pool_protocol_fallback(proto);
  8262. if (PLP_NONE != proto)
  8263. goto tryagain;
  8264. pool->tv_idle = tv_getwork_reply;
  8265. free_work(work);
  8266. goto out;
  8267. }
  8268. json_decref(val);
  8269. if (proto != pool->proto) {
  8270. pool->proto = proto;
  8271. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8272. }
  8273. if (pool->lp_url)
  8274. goto out;
  8275. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8276. const struct blktmpl_longpoll_req *lp;
  8277. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8278. // NOTE: work_decode takes care of lp id
  8279. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8280. if (!pool->lp_url)
  8281. {
  8282. ret = false;
  8283. goto out;
  8284. }
  8285. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8286. }
  8287. else
  8288. if (pool->hdr_path && want_getwork) {
  8289. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8290. if (!pool->lp_url)
  8291. {
  8292. ret = false;
  8293. goto out;
  8294. }
  8295. pool->lp_proto = PLP_GETWORK;
  8296. } else
  8297. pool->lp_url = NULL;
  8298. if (want_longpoll && !pool->lp_started) {
  8299. pool->lp_started = true;
  8300. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8301. quit(1, "Failed to create pool longpoll thread");
  8302. }
  8303. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8304. pool->proto = proto;
  8305. goto tryagain;
  8306. } else {
  8307. pool->tv_idle = tv_getwork_reply;
  8308. free_work(work);
  8309. nohttp:
  8310. /* If we failed to parse a getwork, this could be a stratum
  8311. * url without the prefix stratum+tcp:// so let's check it */
  8312. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8313. pool->has_stratum = true;
  8314. goto retry_stratum;
  8315. }
  8316. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8317. pool->pool_no, pool->rpc_url);
  8318. if (!pinging)
  8319. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8320. }
  8321. out:
  8322. if (curl)
  8323. curl_easy_cleanup(curl);
  8324. mutex_unlock(&pool->pool_test_lock);
  8325. return ret;
  8326. }
  8327. static void pool_resus(struct pool *pool)
  8328. {
  8329. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8330. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8331. else
  8332. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8333. }
  8334. static
  8335. void *cmd_idle_thread(void * const __maybe_unused userp)
  8336. {
  8337. pthread_detach(pthread_self());
  8338. RenameThread("cmd-idle");
  8339. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8340. sleep(opt_log_interval);
  8341. pthread_testcancel();
  8342. run_cmd(cmd_idle);
  8343. return NULL;
  8344. }
  8345. static struct work *hash_pop(void)
  8346. {
  8347. struct work *work = NULL, *tmp;
  8348. int hc;
  8349. bool did_cmd_idle = false;
  8350. pthread_t cmd_idle_thr;
  8351. retry:
  8352. mutex_lock(stgd_lock);
  8353. while (!HASH_COUNT(staged_work))
  8354. {
  8355. if (unlikely(staged_full))
  8356. {
  8357. if (likely(opt_queue < 10 + mining_threads))
  8358. {
  8359. ++opt_queue;
  8360. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8361. }
  8362. else
  8363. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8364. staged_full = false; // Let it fill up before triggering an underrun again
  8365. no_work = true;
  8366. }
  8367. pthread_cond_signal(&gws_cond);
  8368. if (cmd_idle && !did_cmd_idle)
  8369. {
  8370. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8371. did_cmd_idle = true;
  8372. }
  8373. pthread_cond_wait(&getq->cond, stgd_lock);
  8374. }
  8375. if (did_cmd_idle)
  8376. pthread_cancel(cmd_idle_thr);
  8377. no_work = false;
  8378. hc = HASH_COUNT(staged_work);
  8379. /* Find clone work if possible, to allow masters to be reused */
  8380. if (hc > staged_rollable) {
  8381. HASH_ITER(hh, staged_work, work, tmp) {
  8382. if (!work_rollable(work))
  8383. break;
  8384. }
  8385. } else
  8386. work = staged_work;
  8387. if (can_roll(work) && should_roll(work))
  8388. {
  8389. // Instead of consuming it, force it to be cloned and grab the clone
  8390. mutex_unlock(stgd_lock);
  8391. clone_available();
  8392. goto retry;
  8393. }
  8394. HASH_DEL(staged_work, work);
  8395. if (work_rollable(work))
  8396. staged_rollable--;
  8397. /* Signal the getwork scheduler to look for more work */
  8398. pthread_cond_signal(&gws_cond);
  8399. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8400. pthread_cond_signal(&getq->cond);
  8401. mutex_unlock(stgd_lock);
  8402. work->pool->last_work_time = time(NULL);
  8403. cgtime(&work->pool->tv_last_work_time);
  8404. return work;
  8405. }
  8406. /* Clones work by rolling it if possible, and returning a clone instead of the
  8407. * original work item which gets staged again to possibly be rolled again in
  8408. * the future */
  8409. static struct work *clone_work(struct work *work)
  8410. {
  8411. int mrs = mining_threads + opt_queue - total_staged();
  8412. struct work *work_clone;
  8413. bool cloned;
  8414. if (mrs < 1)
  8415. return work;
  8416. cloned = false;
  8417. work_clone = make_clone(work);
  8418. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8419. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8420. stage_work(work_clone);
  8421. roll_work(work);
  8422. work_clone = make_clone(work);
  8423. /* Roll it again to prevent duplicates should this be used
  8424. * directly later on */
  8425. roll_work(work);
  8426. cloned = true;
  8427. }
  8428. if (cloned) {
  8429. stage_work(work);
  8430. return work_clone;
  8431. }
  8432. free_work(work_clone);
  8433. return work;
  8434. }
  8435. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8436. {
  8437. unsigned char hash1[32];
  8438. sha256(data, len, hash1);
  8439. sha256(hash1, 32, hash);
  8440. }
  8441. /* PDiff 1 is a 256 bit unsigned integer of
  8442. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8443. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8444. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8445. static void pdiff_target_leadzero(void * const target_p, double diff)
  8446. {
  8447. uint8_t *target = target_p;
  8448. diff *= 0x100000000;
  8449. int skip = log2(diff) / 8;
  8450. if (skip)
  8451. {
  8452. if (skip > 0x1c)
  8453. skip = 0x1c;
  8454. diff /= pow(0x100, skip);
  8455. memset(target, 0, skip);
  8456. }
  8457. uint32_t n = 0xffffffff;
  8458. n = (double)n / diff;
  8459. n = htobe32(n);
  8460. memcpy(&target[skip], &n, sizeof(n));
  8461. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8462. }
  8463. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8464. {
  8465. unsigned char rtarget[32];
  8466. pdiff_target_leadzero(rtarget, pdiff);
  8467. swab256(dest_target, rtarget);
  8468. if (opt_debug) {
  8469. char htarget[65];
  8470. bin2hex(htarget, rtarget, 32);
  8471. applog(LOG_DEBUG, "Generated target %s", htarget);
  8472. }
  8473. }
  8474. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8475. {
  8476. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8477. }
  8478. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8479. {
  8480. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8481. int off;
  8482. void (*func)(void *, double) = funcp;
  8483. func(little_endian ? bufr : buf, diff);
  8484. if (little_endian)
  8485. swab256(buf, bufr);
  8486. swap32tobe(expect, expectp, 256/32);
  8487. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8488. for (off = 0; off < 28 && !buf[off]; ++off)
  8489. {}
  8490. if (memcmp(&buf[off], &expect[off], 4))
  8491. {
  8492. testfail: ;
  8493. ++unittest_failures;
  8494. char hexbuf[65], expectbuf[65];
  8495. bin2hex(hexbuf, buf, 32);
  8496. bin2hex(expectbuf, expect, 32);
  8497. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8498. funcname, diff, hexbuf, expectbuf);
  8499. }
  8500. if (!little_endian)
  8501. swab256(bufr, buf);
  8502. swab256(expectr, expect);
  8503. if (!hash_target_check(expectr, bufr))
  8504. goto testfail;
  8505. }
  8506. #define TEST_TARGET(func, le, expect, diff) \
  8507. _test_target(func, #func, le, expect, diff)
  8508. void test_target()
  8509. {
  8510. uint32_t expect[8] = {0};
  8511. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8512. expect[0] = 0x0000ffff;
  8513. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8514. expect[0] = 0;
  8515. expect[1] = 0xffff0000;
  8516. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8517. expect[1] >>= 1;
  8518. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8519. expect[1] >>= 3;
  8520. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8521. expect[1] >>= 4;
  8522. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8523. memset(&expect[1], '\xff', 28);
  8524. expect[0] = 0x0000ffff;
  8525. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8526. expect[0] = 0;
  8527. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8528. expect[1] >>= 1;
  8529. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8530. expect[1] >>= 3;
  8531. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8532. expect[1] >>= 4;
  8533. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8534. }
  8535. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8536. {
  8537. *dst = *src;
  8538. if (dst->tr)
  8539. tmpl_incref(dst->tr);
  8540. dst->nonce1 = maybe_strdup(src->nonce1);
  8541. dst->job_id = maybe_strdup(src->job_id);
  8542. bytes_cpy(&dst->coinbase, &src->coinbase);
  8543. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8544. }
  8545. void stratum_work_clean(struct stratum_work * const swork)
  8546. {
  8547. if (swork->tr)
  8548. tmpl_decref(swork->tr);
  8549. free(swork->nonce1);
  8550. free(swork->job_id);
  8551. bytes_free(&swork->coinbase);
  8552. bytes_free(&swork->merkle_bin);
  8553. }
  8554. bool pool_has_usable_swork(const struct pool * const pool)
  8555. {
  8556. if (opt_benchmark)
  8557. return true;
  8558. if (pool->swork.tr)
  8559. {
  8560. // GBT
  8561. struct timeval tv_now;
  8562. timer_set_now(&tv_now);
  8563. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8564. }
  8565. return pool->stratum_notify;
  8566. }
  8567. /* Generates stratum based work based on the most recent notify information
  8568. * from the pool. This will keep generating work while a pool is down so we use
  8569. * other means to detect when the pool has died in stratum_thread */
  8570. static void gen_stratum_work(struct pool *pool, struct work *work)
  8571. {
  8572. clean_work(work);
  8573. cg_wlock(&pool->data_lock);
  8574. pool->swork.data_lock_p = &pool->data_lock;
  8575. const int n2size = pool->swork.n2size;
  8576. bytes_resize(&work->nonce2, n2size);
  8577. if (pool->nonce2sz < n2size)
  8578. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8579. memcpy(bytes_buf(&work->nonce2),
  8580. #ifdef WORDS_BIGENDIAN
  8581. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8582. &((char*)&pool->nonce2)[pool->nonce2off],
  8583. #else
  8584. &pool->nonce2,
  8585. #endif
  8586. pool->nonce2sz);
  8587. pool->nonce2++;
  8588. work->pool = pool;
  8589. work->work_restart_id = pool->swork.work_restart_id;
  8590. gen_stratum_work2(work, &pool->swork);
  8591. cgtime(&work->tv_staged);
  8592. }
  8593. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8594. {
  8595. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8596. uint8_t *merkle_bin;
  8597. uint32_t *data32, *swap32;
  8598. int i;
  8599. /* Generate coinbase */
  8600. coinbase = bytes_buf(&swork->coinbase);
  8601. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8602. /* Downgrade to a read lock to read off the variables */
  8603. if (swork->data_lock_p)
  8604. cg_dwlock(swork->data_lock_p);
  8605. /* Generate merkle root */
  8606. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8607. memcpy(merkle_sha, merkle_root, 32);
  8608. merkle_bin = bytes_buf(&swork->merkle_bin);
  8609. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8610. memcpy(merkle_sha + 32, merkle_bin, 32);
  8611. gen_hash(merkle_sha, merkle_root, 64);
  8612. memcpy(merkle_sha, merkle_root, 32);
  8613. }
  8614. data32 = (uint32_t *)merkle_sha;
  8615. swap32 = (uint32_t *)merkle_root;
  8616. flip32(swap32, data32);
  8617. memcpy(&work->data[0], swork->header1, 36);
  8618. memcpy(&work->data[36], merkle_root, 32);
  8619. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8620. memcpy(&work->data[72], swork->diffbits, 4);
  8621. memset(&work->data[76], 0, 4); // nonce
  8622. memcpy(&work->data[80], workpadding_bin, 48);
  8623. work->ntime_roll_limits = swork->ntime_roll_limits;
  8624. /* Copy parameters required for share submission */
  8625. memcpy(work->target, swork->target, sizeof(work->target));
  8626. work->job_id = maybe_strdup(swork->job_id);
  8627. work->nonce1 = maybe_strdup(swork->nonce1);
  8628. if (swork->data_lock_p)
  8629. cg_runlock(swork->data_lock_p);
  8630. if (opt_debug)
  8631. {
  8632. char header[161];
  8633. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8634. bin2hex(header, work->data, 80);
  8635. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8636. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8637. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8638. }
  8639. calc_midstate(work);
  8640. local_work++;
  8641. work->stratum = true;
  8642. work->blk.nonce = 0;
  8643. work->id = total_work++;
  8644. work->longpoll = false;
  8645. work->getwork_mode = GETWORK_MODE_STRATUM;
  8646. calc_diff(work, 0);
  8647. }
  8648. void request_work(struct thr_info *thr)
  8649. {
  8650. struct cgpu_info *cgpu = thr->cgpu;
  8651. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8652. /* Tell the watchdog thread this thread is waiting on getwork and
  8653. * should not be restarted */
  8654. thread_reportout(thr);
  8655. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8656. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8657. {
  8658. if (proc->threads)
  8659. break;
  8660. thread_reportout(proc->thr[0]);
  8661. }
  8662. cgtime(&dev_stats->_get_start);
  8663. }
  8664. // FIXME: Make this non-blocking (and remove HACK above)
  8665. struct work *get_work(struct thr_info *thr)
  8666. {
  8667. const int thr_id = thr->id;
  8668. struct cgpu_info *cgpu = thr->cgpu;
  8669. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8670. struct cgminer_stats *pool_stats;
  8671. struct timeval tv_get;
  8672. struct work *work = NULL;
  8673. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8674. while (!work) {
  8675. work = hash_pop();
  8676. if (stale_work(work, false)) {
  8677. staged_full = false; // It wasn't really full, since it was stale :(
  8678. discard_work(work);
  8679. work = NULL;
  8680. wake_gws();
  8681. }
  8682. }
  8683. last_getwork = time(NULL);
  8684. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8685. cgpu->proc_repr, work->id, thr_id);
  8686. work->thr_id = thr_id;
  8687. thread_reportin(thr);
  8688. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8689. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8690. {
  8691. if (proc->threads)
  8692. break;
  8693. thread_reportin(proc->thr[0]);
  8694. }
  8695. work->mined = true;
  8696. work->blk.nonce = 0;
  8697. cgtime(&tv_get);
  8698. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8699. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8700. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8701. dev_stats->getwork_wait_max = tv_get;
  8702. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8703. dev_stats->getwork_wait_min = tv_get;
  8704. ++dev_stats->getwork_calls;
  8705. pool_stats = &(work->pool->cgminer_stats);
  8706. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8707. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8708. pool_stats->getwork_wait_max = tv_get;
  8709. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8710. pool_stats->getwork_wait_min = tv_get;
  8711. ++pool_stats->getwork_calls;
  8712. if (work->work_difficulty < 1)
  8713. {
  8714. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  8715. {
  8716. if (cgpu->min_nonce_diff - work->work_difficulty > 1./0x10000000)
  8717. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  8718. cgpu->proc_repr);
  8719. work->nonce_diff = cgpu->min_nonce_diff;
  8720. }
  8721. else
  8722. work->nonce_diff = work->work_difficulty;
  8723. }
  8724. else
  8725. work->nonce_diff = 1;
  8726. return work;
  8727. }
  8728. struct dupe_hash_elem {
  8729. uint8_t hash[0x20];
  8730. struct timeval tv_prune;
  8731. UT_hash_handle hh;
  8732. };
  8733. static
  8734. void _submit_work_async(struct work *work)
  8735. {
  8736. applog(LOG_DEBUG, "Pushing submit work to work thread");
  8737. if (opt_benchmark)
  8738. {
  8739. json_t * const jn = json_null(), *result = NULL;
  8740. work_check_for_block(work);
  8741. {
  8742. static struct dupe_hash_elem *dupe_hashes;
  8743. struct dupe_hash_elem *dhe, *dhetmp;
  8744. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  8745. if (dhe)
  8746. result = json_string("duplicate");
  8747. else
  8748. {
  8749. struct timeval tv_now;
  8750. timer_set_now(&tv_now);
  8751. // Prune old entries
  8752. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  8753. {
  8754. if (!timer_passed(&dhe->tv_prune, &tv_now))
  8755. break;
  8756. HASH_DEL(dupe_hashes, dhe);
  8757. free(dhe);
  8758. }
  8759. dhe = malloc(sizeof(*dhe));
  8760. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  8761. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  8762. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  8763. }
  8764. }
  8765. if (result)
  8766. {}
  8767. else
  8768. if (stale_work(work, true))
  8769. {
  8770. char stalemsg[0x10];
  8771. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  8772. result = json_string(stalemsg);
  8773. }
  8774. else
  8775. result = json_incref(jn);
  8776. share_result(jn, result, jn, work, false, "");
  8777. free_work(work);
  8778. json_decref(result);
  8779. json_decref(jn);
  8780. return;
  8781. }
  8782. mutex_lock(&submitting_lock);
  8783. ++total_submitting;
  8784. DL_APPEND(submit_waiting, work);
  8785. mutex_unlock(&submitting_lock);
  8786. notifier_wake(submit_waiting_notifier);
  8787. }
  8788. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  8789. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  8790. {
  8791. if (tv_work_found)
  8792. copy_time(&work->tv_work_found, tv_work_found);
  8793. _submit_work_async(work);
  8794. }
  8795. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  8796. {
  8797. struct cgpu_info * const cgpu = thr->cgpu;
  8798. if (bad_nonce_p)
  8799. {
  8800. if (bad_nonce_p == UNKNOWN_NONCE)
  8801. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  8802. cgpu->proc_repr);
  8803. else
  8804. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  8805. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  8806. }
  8807. mutex_lock(&stats_lock);
  8808. hw_errors++;
  8809. ++cgpu->hw_errors;
  8810. if (bad_nonce_p)
  8811. {
  8812. total_bad_diff1 += nonce_diff;
  8813. cgpu->bad_diff1 += nonce_diff;
  8814. }
  8815. mutex_unlock(&stats_lock);
  8816. if (thr->cgpu->drv->hw_error)
  8817. thr->cgpu->drv->hw_error(thr);
  8818. }
  8819. void work_hash(struct work * const work)
  8820. {
  8821. #ifdef USE_SCRYPT
  8822. if (opt_scrypt)
  8823. scrypt_hash_data(work->hash, work->data);
  8824. else
  8825. #endif
  8826. hash_data(work->hash, work->data);
  8827. }
  8828. static
  8829. bool test_hash(const void * const phash, const float diff)
  8830. {
  8831. const uint32_t * const hash = phash;
  8832. if (diff >= 1.)
  8833. // FIXME: > 1 should check more
  8834. return !hash[7];
  8835. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  8836. const uint32_t tmp_hash7 = le32toh(hash[7]);
  8837. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  8838. (long unsigned int)Htarg,
  8839. (long unsigned int)tmp_hash7);
  8840. return (tmp_hash7 <= Htarg);
  8841. }
  8842. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  8843. {
  8844. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8845. *work_nonce = htole32(nonce);
  8846. work_hash(work);
  8847. if (!test_hash(work->hash, work->nonce_diff))
  8848. return TNR_BAD;
  8849. if (checktarget && !hash_target_check_v(work->hash, work->target))
  8850. {
  8851. bool high_hash = true;
  8852. struct pool * const pool = work->pool;
  8853. if (pool->stratum_active)
  8854. {
  8855. // Some stratum pools are buggy and expect difficulty changes to be immediate retroactively, so if the target has changed, check and submit just in case
  8856. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  8857. {
  8858. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  8859. pool->pool_no);
  8860. if (hash_target_check_v(work->hash, pool->next_target))
  8861. high_hash = false;
  8862. }
  8863. }
  8864. if (high_hash)
  8865. return TNR_HIGH;
  8866. }
  8867. return TNR_GOOD;
  8868. }
  8869. /* Returns true if nonce for work was a valid share */
  8870. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  8871. {
  8872. return submit_noffset_nonce(thr, work, nonce, 0);
  8873. }
  8874. /* Allows drivers to submit work items where the driver has changed the ntime
  8875. * value by noffset. Must be only used with a work protocol that does not ntime
  8876. * roll itself intrinsically to generate work (eg stratum). We do not touch
  8877. * the original work struct, but the copy of it only. */
  8878. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  8879. int noffset)
  8880. {
  8881. struct work *work = make_work();
  8882. _copy_work(work, work_in, noffset);
  8883. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8884. struct timeval tv_work_found;
  8885. enum test_nonce2_result res;
  8886. bool ret = true;
  8887. thread_reportout(thr);
  8888. cgtime(&tv_work_found);
  8889. *work_nonce = htole32(nonce);
  8890. work->thr_id = thr->id;
  8891. /* Do one last check before attempting to submit the work */
  8892. /* Side effect: sets work->data and work->hash for us */
  8893. res = test_nonce2(work, nonce);
  8894. if (unlikely(res == TNR_BAD))
  8895. {
  8896. inc_hw_errors(thr, work, nonce);
  8897. ret = false;
  8898. goto out;
  8899. }
  8900. mutex_lock(&stats_lock);
  8901. total_diff1 += work->nonce_diff;
  8902. thr ->cgpu->diff1 += work->nonce_diff;
  8903. work->pool->diff1 += work->nonce_diff;
  8904. thr->cgpu->last_device_valid_work = time(NULL);
  8905. mutex_unlock(&stats_lock);
  8906. if (noncelog_file)
  8907. noncelog(work);
  8908. if (res == TNR_HIGH)
  8909. {
  8910. // Share above target, normal
  8911. /* Check the diff of the share, even if it didn't reach the
  8912. * target, just to set the best share value if it's higher. */
  8913. share_diff(work);
  8914. goto out;
  8915. }
  8916. submit_work_async2(work, &tv_work_found);
  8917. work = NULL; // Taken by submit_work_async2
  8918. out:
  8919. if (work)
  8920. free_work(work);
  8921. thread_reportin(thr);
  8922. return ret;
  8923. }
  8924. // return true of we should stop working on this piece of work
  8925. // returning false means we will keep scanning for a nonce
  8926. // assumptions: work->blk.nonce is the number of nonces completed in the work
  8927. // see minerloop_scanhash comments for more details & usage
  8928. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  8929. {
  8930. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  8931. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  8932. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  8933. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  8934. stale_work(work, false)) // work is stale
  8935. return true;
  8936. return false;
  8937. }
  8938. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  8939. {
  8940. struct cgpu_info *proc = thr->cgpu;
  8941. if (proc->threads > 1)
  8942. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  8943. else
  8944. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  8945. }
  8946. // Called by asynchronous minerloops, when they find their processor should be disabled
  8947. void mt_disable_start(struct thr_info *mythr)
  8948. {
  8949. struct cgpu_info *cgpu = mythr->cgpu;
  8950. struct device_drv *drv = cgpu->drv;
  8951. if (drv->thread_disable)
  8952. drv->thread_disable(mythr);
  8953. hashmeter2(mythr);
  8954. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  8955. mythr->rolling = mythr->cgpu->rolling = 0;
  8956. thread_reportout(mythr);
  8957. mythr->_mt_disable_called = true;
  8958. }
  8959. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  8960. * the driver tells us it's full so that it may extract the work item using
  8961. * the get_queued() function which adds it to the hashtable on
  8962. * cgpu->queued_work. */
  8963. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  8964. {
  8965. thread_reportout(mythr);
  8966. do {
  8967. bool need_work;
  8968. /* Do this lockless just to know if we need more unqueued work. */
  8969. need_work = (!cgpu->unqueued_work);
  8970. /* get_work is a blocking function so do it outside of lock
  8971. * to prevent deadlocks with other locks. */
  8972. if (need_work) {
  8973. struct work *work = get_work(mythr);
  8974. wr_lock(&cgpu->qlock);
  8975. /* Check we haven't grabbed work somehow between
  8976. * checking and picking up the lock. */
  8977. if (likely(!cgpu->unqueued_work))
  8978. cgpu->unqueued_work = work;
  8979. else
  8980. need_work = false;
  8981. wr_unlock(&cgpu->qlock);
  8982. if (unlikely(!need_work))
  8983. discard_work(work);
  8984. }
  8985. /* The queue_full function should be used by the driver to
  8986. * actually place work items on the physical device if it
  8987. * does have a queue. */
  8988. } while (drv->queue_full && !drv->queue_full(cgpu));
  8989. }
  8990. /* Add a work item to a cgpu's queued hashlist */
  8991. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  8992. {
  8993. cgpu->queued_count++;
  8994. HASH_ADD_INT(cgpu->queued_work, id, work);
  8995. }
  8996. /* This function is for retrieving one work item from the unqueued pointer and
  8997. * adding it to the hashtable of queued work. Code using this function must be
  8998. * able to handle NULL as a return which implies there is no work available. */
  8999. struct work *get_queued(struct cgpu_info *cgpu)
  9000. {
  9001. struct work *work = NULL;
  9002. wr_lock(&cgpu->qlock);
  9003. if (cgpu->unqueued_work) {
  9004. work = cgpu->unqueued_work;
  9005. if (unlikely(stale_work(work, false))) {
  9006. discard_work(work);
  9007. work = NULL;
  9008. wake_gws();
  9009. } else
  9010. __add_queued(cgpu, work);
  9011. cgpu->unqueued_work = NULL;
  9012. }
  9013. wr_unlock(&cgpu->qlock);
  9014. return work;
  9015. }
  9016. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9017. {
  9018. wr_lock(&cgpu->qlock);
  9019. __add_queued(cgpu, work);
  9020. wr_unlock(&cgpu->qlock);
  9021. }
  9022. /* Get fresh work and add it to cgpu's queued hashlist */
  9023. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9024. {
  9025. struct work *work = get_work(thr);
  9026. add_queued(cgpu, work);
  9027. return work;
  9028. }
  9029. /* This function is for finding an already queued work item in the
  9030. * given que hashtable. Code using this function must be able
  9031. * to handle NULL as a return which implies there is no matching work.
  9032. * The calling function must lock access to the que if it is required.
  9033. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9034. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9035. {
  9036. struct work *work, *tmp, *ret = NULL;
  9037. HASH_ITER(hh, que, work, tmp) {
  9038. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9039. memcmp(work->data + offset, data, datalen) == 0) {
  9040. ret = work;
  9041. break;
  9042. }
  9043. }
  9044. return ret;
  9045. }
  9046. /* This function is for finding an already queued work item in the
  9047. * device's queued_work hashtable. Code using this function must be able
  9048. * to handle NULL as a return which implies there is no matching work.
  9049. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9050. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9051. {
  9052. struct work *ret;
  9053. rd_lock(&cgpu->qlock);
  9054. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9055. rd_unlock(&cgpu->qlock);
  9056. return ret;
  9057. }
  9058. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9059. {
  9060. struct work *work, *ret = NULL;
  9061. rd_lock(&cgpu->qlock);
  9062. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9063. if (work)
  9064. ret = copy_work(work);
  9065. rd_unlock(&cgpu->qlock);
  9066. return ret;
  9067. }
  9068. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9069. {
  9070. cgpu->queued_count--;
  9071. HASH_DEL(cgpu->queued_work, work);
  9072. }
  9073. /* This iterates over a queued hashlist finding work started more than secs
  9074. * seconds ago and discards the work as completed. The driver must set the
  9075. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9076. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9077. {
  9078. struct work *work, *tmp;
  9079. struct timeval tv_now;
  9080. int aged = 0;
  9081. cgtime(&tv_now);
  9082. wr_lock(&cgpu->qlock);
  9083. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9084. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9085. __work_completed(cgpu, work);
  9086. aged++;
  9087. }
  9088. }
  9089. wr_unlock(&cgpu->qlock);
  9090. return aged;
  9091. }
  9092. /* This function should be used by queued device drivers when they're sure
  9093. * the work struct is no longer in use. */
  9094. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9095. {
  9096. wr_lock(&cgpu->qlock);
  9097. __work_completed(cgpu, work);
  9098. wr_unlock(&cgpu->qlock);
  9099. free_work(work);
  9100. }
  9101. /* Combines find_queued_work_bymidstate and work_completed in one function
  9102. * withOUT destroying the work so the driver must free it. */
  9103. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9104. {
  9105. struct work *work;
  9106. wr_lock(&cgpu->qlock);
  9107. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9108. if (work)
  9109. __work_completed(cgpu, work);
  9110. wr_unlock(&cgpu->qlock);
  9111. return work;
  9112. }
  9113. void flush_queue(struct cgpu_info *cgpu)
  9114. {
  9115. struct work *work = NULL;
  9116. wr_lock(&cgpu->qlock);
  9117. work = cgpu->unqueued_work;
  9118. cgpu->unqueued_work = NULL;
  9119. wr_unlock(&cgpu->qlock);
  9120. if (work) {
  9121. free_work(work);
  9122. applog(LOG_DEBUG, "Discarded queued work item");
  9123. }
  9124. }
  9125. /* This version of hash work is for devices that are fast enough to always
  9126. * perform a full nonce range and need a queue to maintain the device busy.
  9127. * Work creation and destruction is not done from within this function
  9128. * directly. */
  9129. void hash_queued_work(struct thr_info *mythr)
  9130. {
  9131. const long cycle = opt_log_interval / 5 ? : 1;
  9132. struct timeval tv_start = {0, 0}, tv_end;
  9133. struct cgpu_info *cgpu = mythr->cgpu;
  9134. struct device_drv *drv = cgpu->drv;
  9135. const int thr_id = mythr->id;
  9136. int64_t hashes_done = 0;
  9137. if (unlikely(cgpu->deven != DEV_ENABLED))
  9138. mt_disable(mythr);
  9139. while (likely(!cgpu->shutdown)) {
  9140. struct timeval diff;
  9141. int64_t hashes;
  9142. fill_queue(mythr, cgpu, drv, thr_id);
  9143. thread_reportin(mythr);
  9144. hashes = drv->scanwork(mythr);
  9145. /* Reset the bool here in case the driver looks for it
  9146. * synchronously in the scanwork loop. */
  9147. mythr->work_restart = false;
  9148. if (unlikely(hashes == -1 )) {
  9149. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9150. cgpu->deven = DEV_DISABLED;
  9151. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9152. mt_disable(mythr);
  9153. }
  9154. hashes_done += hashes;
  9155. cgtime(&tv_end);
  9156. timersub(&tv_end, &tv_start, &diff);
  9157. if (diff.tv_sec >= cycle) {
  9158. hashmeter(thr_id, &diff, hashes_done);
  9159. hashes_done = 0;
  9160. copy_time(&tv_start, &tv_end);
  9161. }
  9162. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9163. mt_disable(mythr);
  9164. if (unlikely(mythr->work_restart)) {
  9165. flush_queue(cgpu);
  9166. if (drv->flush_work)
  9167. drv->flush_work(cgpu);
  9168. }
  9169. }
  9170. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9171. }
  9172. // Called by minerloop, when it is re-enabling a processor
  9173. void mt_disable_finish(struct thr_info *mythr)
  9174. {
  9175. struct device_drv *drv = mythr->cgpu->drv;
  9176. thread_reportin(mythr);
  9177. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9178. if (drv->thread_enable)
  9179. drv->thread_enable(mythr);
  9180. mythr->_mt_disable_called = false;
  9181. }
  9182. // Called by synchronous minerloops, when they find their processor should be disabled
  9183. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9184. void mt_disable(struct thr_info *mythr)
  9185. {
  9186. const struct cgpu_info * const cgpu = mythr->cgpu;
  9187. mt_disable_start(mythr);
  9188. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9189. do {
  9190. notifier_read(mythr->notifier);
  9191. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9192. mt_disable_finish(mythr);
  9193. }
  9194. enum {
  9195. STAT_SLEEP_INTERVAL = 1,
  9196. STAT_CTR_INTERVAL = 10000000,
  9197. FAILURE_INTERVAL = 30,
  9198. };
  9199. /* Stage another work item from the work returned in a longpoll */
  9200. 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)
  9201. {
  9202. bool rc;
  9203. work->rolltime = rolltime;
  9204. rc = work_decode(pool, work, val);
  9205. if (unlikely(!rc)) {
  9206. applog(LOG_ERR, "Could not convert longpoll data to work");
  9207. free_work(work);
  9208. return;
  9209. }
  9210. total_getworks++;
  9211. pool->getwork_requested++;
  9212. work->pool = pool;
  9213. copy_time(&work->tv_getwork, tv_lp);
  9214. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9215. calc_diff(work, 0);
  9216. if (pool->enabled == POOL_REJECTING)
  9217. work->mandatory = true;
  9218. work->longpoll = true;
  9219. work->getwork_mode = GETWORK_MODE_LP;
  9220. update_last_work(work);
  9221. /* We'll be checking this work item twice, but we already know it's
  9222. * from a new block so explicitly force the new block detection now
  9223. * rather than waiting for it to hit the stage thread. This also
  9224. * allows testwork to know whether LP discovered the block or not. */
  9225. test_work_current(work);
  9226. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9227. * the longpoll work from a pool that has been rejecting shares as a
  9228. * way to detect when the pool has recovered.
  9229. */
  9230. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9231. free_work(work);
  9232. return;
  9233. }
  9234. work = clone_work(work);
  9235. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9236. stage_work(work);
  9237. applog(LOG_DEBUG, "Converted longpoll data to work");
  9238. }
  9239. /* If we want longpoll, enable it for the chosen default pool, or, if
  9240. * the pool does not support longpoll, find the first one that does
  9241. * and use its longpoll support */
  9242. static
  9243. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9244. {
  9245. int i;
  9246. if (func(cp))
  9247. return cp;
  9248. for (i = 0; i < total_pools; i++) {
  9249. struct pool *pool = pools[i];
  9250. if (func(pool))
  9251. return pool;
  9252. }
  9253. return NULL;
  9254. }
  9255. /* This will make the longpoll thread wait till it's the current pool, or it
  9256. * has been flagged as rejecting, before attempting to open any connections.
  9257. */
  9258. static void wait_lpcurrent(struct pool *pool)
  9259. {
  9260. mutex_lock(&lp_lock);
  9261. while (!cnx_needed(pool))
  9262. {
  9263. pool->lp_active = false;
  9264. pthread_cond_wait(&lp_cond, &lp_lock);
  9265. }
  9266. mutex_unlock(&lp_lock);
  9267. }
  9268. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9269. struct pool *pool = vpool;
  9270. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9271. pool->lp_socket = sock;
  9272. return sock;
  9273. }
  9274. static void *longpoll_thread(void *userdata)
  9275. {
  9276. struct pool *cp = (struct pool *)userdata;
  9277. /* This *pool is the source of the actual longpoll, not the pool we've
  9278. * tied it to */
  9279. struct timeval start, reply, end;
  9280. struct pool *pool = NULL;
  9281. char threadname[20];
  9282. CURL *curl = NULL;
  9283. int failures = 0;
  9284. char *lp_url;
  9285. int rolltime;
  9286. #ifndef HAVE_PTHREAD_CANCEL
  9287. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9288. #endif
  9289. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9290. RenameThread(threadname);
  9291. curl = curl_easy_init();
  9292. if (unlikely(!curl)) {
  9293. applog(LOG_ERR, "CURL initialisation failed");
  9294. return NULL;
  9295. }
  9296. retry_pool:
  9297. pool = select_longpoll_pool(cp);
  9298. if (!pool) {
  9299. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9300. while (!pool) {
  9301. cgsleep_ms(60000);
  9302. pool = select_longpoll_pool(cp);
  9303. }
  9304. }
  9305. if (pool->has_stratum) {
  9306. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9307. cp->rpc_url, pool->rpc_url);
  9308. goto out;
  9309. }
  9310. /* Any longpoll from any pool is enough for this to be true */
  9311. have_longpoll = true;
  9312. wait_lpcurrent(cp);
  9313. {
  9314. lp_url = pool->lp_url;
  9315. if (cp == pool)
  9316. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9317. else
  9318. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9319. }
  9320. while (42) {
  9321. json_t *val, *soval;
  9322. struct work *work = make_work();
  9323. char *lpreq;
  9324. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9325. work->pool = pool;
  9326. if (!lpreq)
  9327. {
  9328. free_work(work);
  9329. goto lpfail;
  9330. }
  9331. wait_lpcurrent(cp);
  9332. cgtime(&start);
  9333. /* Longpoll connections can be persistent for a very long time
  9334. * and any number of issues could have come up in the meantime
  9335. * so always establish a fresh connection instead of relying on
  9336. * a persistent one. */
  9337. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9338. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9339. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9340. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9341. lpreq, false, true, &rolltime, pool, false);
  9342. pool->lp_socket = CURL_SOCKET_BAD;
  9343. cgtime(&reply);
  9344. free(lpreq);
  9345. if (likely(val)) {
  9346. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9347. if (soval)
  9348. pool->submit_old = json_is_true(soval);
  9349. else
  9350. pool->submit_old = false;
  9351. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9352. failures = 0;
  9353. json_decref(val);
  9354. } else {
  9355. /* Some pools regularly drop the longpoll request so
  9356. * only see this as longpoll failure if it happens
  9357. * immediately and just restart it the rest of the
  9358. * time. */
  9359. cgtime(&end);
  9360. free_work(work);
  9361. if (end.tv_sec - start.tv_sec <= 30)
  9362. {
  9363. if (failures == 1)
  9364. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9365. lpfail:
  9366. cgsleep_ms(30000);
  9367. }
  9368. }
  9369. if (pool != cp) {
  9370. pool = select_longpoll_pool(cp);
  9371. if (pool->has_stratum) {
  9372. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9373. cp->rpc_url, pool->rpc_url);
  9374. break;
  9375. }
  9376. if (unlikely(!pool))
  9377. goto retry_pool;
  9378. }
  9379. if (unlikely(pool->removed))
  9380. break;
  9381. }
  9382. out:
  9383. pool->lp_active = false;
  9384. curl_easy_cleanup(curl);
  9385. return NULL;
  9386. }
  9387. static void stop_longpoll(void)
  9388. {
  9389. int i;
  9390. want_longpoll = false;
  9391. for (i = 0; i < total_pools; ++i)
  9392. {
  9393. struct pool *pool = pools[i];
  9394. if (unlikely(!pool->lp_started))
  9395. continue;
  9396. pool->lp_started = false;
  9397. pthread_cancel(pool->longpoll_thread);
  9398. }
  9399. have_longpoll = false;
  9400. }
  9401. static void start_longpoll(void)
  9402. {
  9403. int i;
  9404. want_longpoll = true;
  9405. for (i = 0; i < total_pools; ++i)
  9406. {
  9407. struct pool *pool = pools[i];
  9408. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9409. continue;
  9410. pool->lp_started = true;
  9411. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9412. quit(1, "Failed to create pool longpoll thread");
  9413. }
  9414. }
  9415. void reinit_device(struct cgpu_info *cgpu)
  9416. {
  9417. if (cgpu->drv->reinit_device)
  9418. cgpu->drv->reinit_device(cgpu);
  9419. }
  9420. static struct timeval rotate_tv;
  9421. /* We reap curls if they are unused for over a minute */
  9422. static void reap_curl(struct pool *pool)
  9423. {
  9424. struct curl_ent *ent, *iter;
  9425. struct timeval now;
  9426. int reaped = 0;
  9427. cgtime(&now);
  9428. mutex_lock(&pool->pool_lock);
  9429. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9430. if (pool->curls < 2)
  9431. break;
  9432. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9433. reaped++;
  9434. pool->curls--;
  9435. LL_DELETE(pool->curllist, ent);
  9436. curl_easy_cleanup(ent->curl);
  9437. free(ent);
  9438. }
  9439. }
  9440. mutex_unlock(&pool->pool_lock);
  9441. if (reaped)
  9442. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9443. }
  9444. static void *watchpool_thread(void __maybe_unused *userdata)
  9445. {
  9446. int intervals = 0;
  9447. #ifndef HAVE_PTHREAD_CANCEL
  9448. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9449. #endif
  9450. RenameThread("watchpool");
  9451. while (42) {
  9452. struct timeval now;
  9453. int i;
  9454. if (++intervals > 20)
  9455. intervals = 0;
  9456. cgtime(&now);
  9457. for (i = 0; i < total_pools; i++) {
  9458. struct pool *pool = pools[i];
  9459. if (!opt_benchmark)
  9460. reap_curl(pool);
  9461. /* Get a rolling utility per pool over 10 mins */
  9462. if (intervals > 19) {
  9463. int shares = pool->diff1 - pool->last_shares;
  9464. pool->last_shares = pool->diff1;
  9465. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9466. pool->shares = pool->utility;
  9467. }
  9468. if (pool->enabled == POOL_DISABLED)
  9469. continue;
  9470. /* Don't start testing any pools if the test threads
  9471. * from startup are still doing their first attempt. */
  9472. if (unlikely(pool->testing)) {
  9473. pthread_join(pool->test_thread, NULL);
  9474. }
  9475. /* Test pool is idle once every minute */
  9476. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9477. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9478. pool_resus(pool);
  9479. }
  9480. /* Only switch pools if the failback pool has been
  9481. * alive for more than 5 minutes (default) to prevent
  9482. * intermittently failing pools from being used. */
  9483. if (!pool->idle && pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() && now.tv_sec - pool->tv_idle.tv_sec > opt_fail_switch_delay)
  9484. {
  9485. if (opt_fail_switch_delay % 60)
  9486. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9487. pool->pool_no, pool->rpc_url,
  9488. opt_fail_switch_delay,
  9489. (opt_fail_switch_delay == 1 ? "" : "s"));
  9490. else
  9491. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9492. pool->pool_no, pool->rpc_url,
  9493. opt_fail_switch_delay / 60,
  9494. (opt_fail_switch_delay == 60 ? "" : "s"));
  9495. switch_pools(NULL);
  9496. }
  9497. }
  9498. if (current_pool()->idle)
  9499. switch_pools(NULL);
  9500. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9501. cgtime(&rotate_tv);
  9502. switch_pools(NULL);
  9503. }
  9504. cgsleep_ms(30000);
  9505. }
  9506. return NULL;
  9507. }
  9508. void mt_enable(struct thr_info *thr)
  9509. {
  9510. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9511. notifier_wake(thr->notifier);
  9512. }
  9513. void proc_enable(struct cgpu_info *cgpu)
  9514. {
  9515. int j;
  9516. cgpu->deven = DEV_ENABLED;
  9517. for (j = cgpu->threads ?: 1; j--; )
  9518. mt_enable(cgpu->thr[j]);
  9519. }
  9520. #define device_recovered(cgpu) proc_enable(cgpu)
  9521. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9522. {
  9523. struct string_elist *setstr_elist;
  9524. const char *p, *p2;
  9525. char replybuf[0x2000];
  9526. size_t L;
  9527. DL_FOREACH(opt_set_device_list, setstr_elist)
  9528. {
  9529. const char * const setstr = setstr_elist->string;
  9530. p = strchr(setstr, ':');
  9531. if (!p)
  9532. p = setstr;
  9533. {
  9534. L = p - setstr;
  9535. char pattern[L + 1];
  9536. if (L)
  9537. memcpy(pattern, setstr, L);
  9538. pattern[L] = '\0';
  9539. if (!cgpu_match(pattern, cgpu))
  9540. continue;
  9541. }
  9542. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9543. cgpu->proc_repr, __func__, setstr);
  9544. if (p[0] == ':')
  9545. ++p;
  9546. p2 = strchr(p, '=');
  9547. if (!p2)
  9548. {
  9549. L = strlen(p);
  9550. p2 = "";
  9551. }
  9552. else
  9553. {
  9554. L = p2 - p;
  9555. ++p2;
  9556. }
  9557. char opt[L + 1];
  9558. if (L)
  9559. memcpy(opt, p, L);
  9560. opt[L] = '\0';
  9561. L = strlen(p2);
  9562. char setval[L + 1];
  9563. if (L)
  9564. memcpy(setval, p2, L);
  9565. setval[L] = '\0';
  9566. enum bfg_set_device_replytype success;
  9567. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9568. switch (success)
  9569. {
  9570. case SDR_OK:
  9571. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9572. cgpu->proc_repr, setstr,
  9573. p ? ": " : "", p ?: "");
  9574. break;
  9575. case SDR_ERR:
  9576. case SDR_HELP:
  9577. case SDR_UNKNOWN:
  9578. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9579. cgpu->proc_repr, setstr, p);
  9580. break;
  9581. case SDR_AUTO:
  9582. case SDR_NOSUPP:
  9583. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9584. cgpu->proc_repr, setstr);
  9585. }
  9586. }
  9587. cgpu->already_set_defaults = true;
  9588. }
  9589. void drv_set_defaults(const struct device_drv * const drv, const void *datap, void *userp, const char * const devpath, const char * const serial, const int mode)
  9590. {
  9591. struct device_drv dummy_drv = *drv;
  9592. struct cgpu_info dummy_cgpu = {
  9593. .drv = &dummy_drv,
  9594. .device = &dummy_cgpu,
  9595. .device_id = -1,
  9596. .proc_id = -1,
  9597. .device_data = userp,
  9598. .device_path = devpath,
  9599. .dev_serial = serial,
  9600. };
  9601. strcpy(dummy_cgpu.proc_repr, drv->name);
  9602. switch (mode)
  9603. {
  9604. case 0:
  9605. dummy_drv.set_device = datap;
  9606. break;
  9607. case 1:
  9608. dummy_drv.set_device = NULL;
  9609. dummy_cgpu.set_device_funcs = datap;
  9610. break;
  9611. }
  9612. cgpu_set_defaults(&dummy_cgpu);
  9613. }
  9614. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9615. * the screen at regular intervals, and restarts threads if they appear to have
  9616. * died. */
  9617. #define WATCHDOG_SICK_TIME 60
  9618. #define WATCHDOG_DEAD_TIME 600
  9619. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9620. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9621. static void *watchdog_thread(void __maybe_unused *userdata)
  9622. {
  9623. const unsigned int interval = WATCHDOG_INTERVAL;
  9624. struct timeval zero_tv;
  9625. #ifndef HAVE_PTHREAD_CANCEL
  9626. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9627. #endif
  9628. RenameThread("watchdog");
  9629. memset(&zero_tv, 0, sizeof(struct timeval));
  9630. cgtime(&rotate_tv);
  9631. while (1) {
  9632. int i;
  9633. struct timeval now;
  9634. sleep(interval);
  9635. discard_stale();
  9636. hashmeter(-1, &zero_tv, 0);
  9637. #ifdef HAVE_CURSES
  9638. const int ts = total_staged();
  9639. if (curses_active_locked()) {
  9640. change_logwinsize();
  9641. curses_print_status(ts);
  9642. _refresh_devstatus(true);
  9643. touchwin(logwin);
  9644. wrefresh(logwin);
  9645. unlock_curses();
  9646. }
  9647. #endif
  9648. cgtime(&now);
  9649. if (!sched_paused && !should_run()) {
  9650. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9651. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9652. if (!schedstart.enable) {
  9653. quit(0, "Terminating execution as planned");
  9654. break;
  9655. }
  9656. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9657. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9658. sched_paused = true;
  9659. rd_lock(&mining_thr_lock);
  9660. for (i = 0; i < mining_threads; i++)
  9661. mining_thr[i]->pause = true;
  9662. rd_unlock(&mining_thr_lock);
  9663. } else if (sched_paused && should_run()) {
  9664. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9665. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9666. if (schedstop.enable)
  9667. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9668. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9669. sched_paused = false;
  9670. for (i = 0; i < mining_threads; i++) {
  9671. struct thr_info *thr;
  9672. thr = get_thread(i);
  9673. thr->pause = false;
  9674. }
  9675. for (i = 0; i < total_devices; ++i)
  9676. {
  9677. struct cgpu_info *cgpu = get_devices(i);
  9678. /* Don't touch disabled devices */
  9679. if (cgpu->deven == DEV_DISABLED)
  9680. continue;
  9681. proc_enable(cgpu);
  9682. }
  9683. }
  9684. for (i = 0; i < total_devices; ++i) {
  9685. struct cgpu_info *cgpu = get_devices(i);
  9686. if (!cgpu->disable_watchdog)
  9687. bfg_watchdog(cgpu, &now);
  9688. }
  9689. }
  9690. return NULL;
  9691. }
  9692. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  9693. {
  9694. struct thr_info *thr = cgpu->thr[0];
  9695. enum dev_enable *denable;
  9696. char *dev_str = cgpu->proc_repr;
  9697. if (likely(drv_ready(cgpu)))
  9698. {
  9699. if (unlikely(!cgpu->already_set_defaults))
  9700. cgpu_set_defaults(cgpu);
  9701. if (cgpu->drv->get_stats)
  9702. cgpu->drv->get_stats(cgpu);
  9703. }
  9704. denable = &cgpu->deven;
  9705. if (cgpu->drv->watchdog)
  9706. cgpu->drv->watchdog(cgpu, tvp_now);
  9707. /* Thread is disabled */
  9708. if (*denable == DEV_DISABLED)
  9709. return;
  9710. else
  9711. if (*denable == DEV_RECOVER_ERR) {
  9712. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  9713. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  9714. dev_str);
  9715. if (cgpu->reinit_backoff < 300)
  9716. cgpu->reinit_backoff *= 2;
  9717. device_recovered(cgpu);
  9718. }
  9719. return;
  9720. }
  9721. else
  9722. if (*denable == DEV_RECOVER) {
  9723. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  9724. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  9725. dev_str);
  9726. device_recovered(cgpu);
  9727. }
  9728. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9729. return;
  9730. }
  9731. else
  9732. if (cgpu->temp > cgpu->cutofftemp)
  9733. {
  9734. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  9735. dev_str, (int)cgpu->temp);
  9736. *denable = DEV_RECOVER;
  9737. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9738. run_cmd(cmd_idle);
  9739. }
  9740. if (thr->getwork) {
  9741. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  9742. int thrid;
  9743. bool cgpu_idle = true;
  9744. thr->rolling = 0;
  9745. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  9746. if (!cgpu->thr[thrid]->getwork)
  9747. cgpu_idle = false;
  9748. if (cgpu_idle) {
  9749. cgpu->rolling = 0;
  9750. cgpu->status = LIFE_WAIT;
  9751. }
  9752. }
  9753. return;
  9754. }
  9755. else if (cgpu->status == LIFE_WAIT)
  9756. cgpu->status = LIFE_WELL;
  9757. #ifdef WANT_CPUMINE
  9758. if (!strcmp(cgpu->drv->dname, "cpu"))
  9759. return;
  9760. #endif
  9761. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  9762. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  9763. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  9764. cgpu->status = LIFE_WELL;
  9765. cgpu->device_last_well = time(NULL);
  9766. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  9767. thr->rolling = cgpu->rolling = 0;
  9768. cgpu->status = LIFE_SICK;
  9769. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  9770. cgtime(&thr->sick);
  9771. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  9772. run_cmd(cmd_sick);
  9773. if (opt_restart && cgpu->drv->reinit_device) {
  9774. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  9775. reinit_device(cgpu);
  9776. }
  9777. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  9778. cgpu->status = LIFE_DEAD;
  9779. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  9780. cgtime(&thr->sick);
  9781. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  9782. run_cmd(cmd_dead);
  9783. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  9784. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  9785. /* Attempt to restart a GPU that's sick or dead once every minute */
  9786. cgtime(&thr->sick);
  9787. if (opt_restart)
  9788. reinit_device(cgpu);
  9789. }
  9790. }
  9791. static void log_print_status(struct cgpu_info *cgpu)
  9792. {
  9793. char logline[255];
  9794. get_statline(logline, sizeof(logline), cgpu);
  9795. applog(LOG_WARNING, "%s", logline);
  9796. }
  9797. void print_summary(void)
  9798. {
  9799. struct timeval diff;
  9800. int hours, mins, secs, i;
  9801. double utility, efficiency = 0.0;
  9802. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  9803. int pool_secs;
  9804. timersub(&total_tv_end, &total_tv_start, &diff);
  9805. hours = diff.tv_sec / 3600;
  9806. mins = (diff.tv_sec % 3600) / 60;
  9807. secs = diff.tv_sec % 60;
  9808. utility = total_accepted / total_secs * 60;
  9809. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  9810. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  9811. applog(LOG_WARNING, "Started at %s", datestamp);
  9812. if (total_pools == 1)
  9813. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  9814. #ifdef WANT_CPUMINE
  9815. if (opt_n_threads > 0)
  9816. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  9817. #endif
  9818. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  9819. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  9820. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  9821. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  9822. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  9823. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  9824. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  9825. total_rejected, total_stale,
  9826. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  9827. );
  9828. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  9829. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  9830. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  9831. applog(LOG_WARNING, "Network transfer: %s (%s)",
  9832. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9833. (float)total_bytes_rcvd,
  9834. (float)total_bytes_sent),
  9835. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9836. (float)(total_bytes_rcvd / total_secs),
  9837. (float)(total_bytes_sent / total_secs)));
  9838. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  9839. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  9840. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  9841. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  9842. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  9843. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  9844. if (total_pools > 1) {
  9845. for (i = 0; i < total_pools; i++) {
  9846. struct pool *pool = pools[i];
  9847. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  9848. if (pool->solved)
  9849. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  9850. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  9851. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  9852. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  9853. pool->rejected, pool->stale_shares,
  9854. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  9855. );
  9856. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  9857. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  9858. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  9859. applog(LOG_WARNING, " Network transfer: %s (%s)",
  9860. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9861. (float)pool->cgminer_pool_stats.net_bytes_received,
  9862. (float)pool->cgminer_pool_stats.net_bytes_sent),
  9863. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9864. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  9865. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  9866. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  9867. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  9868. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  9869. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  9870. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  9871. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  9872. }
  9873. }
  9874. if (opt_quit_summary != BQS_NONE)
  9875. {
  9876. if (opt_quit_summary == BQS_DEFAULT)
  9877. {
  9878. if (total_devices < 25)
  9879. opt_quit_summary = BQS_PROCS;
  9880. else
  9881. opt_quit_summary = BQS_DEVS;
  9882. }
  9883. if (opt_quit_summary == BQS_DETAILED)
  9884. include_serial_in_statline = true;
  9885. applog(LOG_WARNING, "Summary of per device statistics:\n");
  9886. for (i = 0; i < total_devices; ++i) {
  9887. struct cgpu_info *cgpu = get_devices(i);
  9888. if (!cgpu->proc_id)
  9889. {
  9890. // Device summary line
  9891. opt_show_procs = false;
  9892. log_print_status(cgpu);
  9893. opt_show_procs = true;
  9894. }
  9895. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  9896. log_print_status(cgpu);
  9897. }
  9898. }
  9899. if (opt_shares) {
  9900. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  9901. if (opt_shares > total_diff_accepted)
  9902. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  9903. }
  9904. applog(LOG_WARNING, " ");
  9905. fflush(stderr);
  9906. fflush(stdout);
  9907. }
  9908. void _bfg_clean_up(bool restarting)
  9909. {
  9910. #ifdef HAVE_OPENCL
  9911. clear_adl(nDevs);
  9912. #endif
  9913. #ifdef HAVE_LIBUSB
  9914. if (likely(have_libusb))
  9915. libusb_exit(NULL);
  9916. #endif
  9917. cgtime(&total_tv_end);
  9918. #ifdef WIN32
  9919. timeEndPeriod(1);
  9920. #endif
  9921. if (!restarting) {
  9922. /* Attempting to disable curses or print a summary during a
  9923. * restart can lead to a deadlock. */
  9924. #ifdef HAVE_CURSES
  9925. disable_curses();
  9926. #endif
  9927. if (!opt_realquiet && successful_connect)
  9928. print_summary();
  9929. }
  9930. if (opt_n_threads > 0)
  9931. free(cpus);
  9932. curl_global_cleanup();
  9933. #ifdef WIN32
  9934. WSACleanup();
  9935. #endif
  9936. }
  9937. void _quit(int status)
  9938. {
  9939. if (status) {
  9940. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  9941. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  9942. int *p = NULL;
  9943. // NOTE debugger can bypass with: p = &p
  9944. *p = status; // Segfault, hopefully dumping core
  9945. }
  9946. }
  9947. #if defined(unix) || defined(__APPLE__)
  9948. if (forkpid > 0) {
  9949. kill(forkpid, SIGTERM);
  9950. forkpid = 0;
  9951. }
  9952. #endif
  9953. exit(status);
  9954. }
  9955. #ifdef HAVE_CURSES
  9956. char *curses_input(const char *query)
  9957. {
  9958. char *input;
  9959. echo();
  9960. input = malloc(255);
  9961. if (!input)
  9962. quit(1, "Failed to malloc input");
  9963. leaveok(logwin, false);
  9964. wlogprint("%s:\n", query);
  9965. wgetnstr(logwin, input, 255);
  9966. if (!strlen(input))
  9967. {
  9968. free(input);
  9969. input = NULL;
  9970. }
  9971. leaveok(logwin, true);
  9972. noecho();
  9973. return input;
  9974. }
  9975. #endif
  9976. static void *test_pool_thread(void *arg)
  9977. {
  9978. struct pool *pool = (struct pool *)arg;
  9979. if (pool_active(pool, false)) {
  9980. pool_tset(pool, &pool->lagging);
  9981. pool_tclear(pool, &pool->idle);
  9982. bool first_pool = false;
  9983. cg_wlock(&control_lock);
  9984. if (!pools_active) {
  9985. currentpool = pool;
  9986. if (pool->pool_no != 0)
  9987. first_pool = true;
  9988. pools_active = true;
  9989. }
  9990. cg_wunlock(&control_lock);
  9991. if (unlikely(first_pool))
  9992. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  9993. else
  9994. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  9995. switch_pools(NULL);
  9996. } else
  9997. pool_died(pool);
  9998. pool->testing = false;
  9999. return NULL;
  10000. }
  10001. /* Always returns true that the pool details were added unless we are not
  10002. * live, implying this is the only pool being added, so if no pools are
  10003. * active it returns false. */
  10004. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10005. {
  10006. size_t siz;
  10007. pool_set_uri(pool, url);
  10008. pool->rpc_user = user;
  10009. pool->rpc_pass = pass;
  10010. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10011. pool->rpc_userpass = malloc(siz);
  10012. if (!pool->rpc_userpass)
  10013. quit(1, "Failed to malloc userpass");
  10014. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10015. pool->testing = true;
  10016. pool->idle = true;
  10017. enable_pool(pool);
  10018. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10019. if (!live) {
  10020. pthread_join(pool->test_thread, NULL);
  10021. return pools_active;
  10022. }
  10023. return true;
  10024. }
  10025. #ifdef HAVE_CURSES
  10026. static bool input_pool(bool live)
  10027. {
  10028. char *url = NULL, *user = NULL, *pass = NULL;
  10029. struct pool *pool;
  10030. bool ret = false;
  10031. immedok(logwin, true);
  10032. wlogprint("Input server details.\n");
  10033. url = curses_input("URL");
  10034. if (!url)
  10035. goto out;
  10036. user = curses_input("Username");
  10037. if (!user)
  10038. goto out;
  10039. pass = curses_input("Password");
  10040. if (!pass)
  10041. pass = calloc(1, 1);
  10042. pool = add_pool();
  10043. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10044. strncmp(url, "https://", 8)) {
  10045. char *httpinput;
  10046. httpinput = malloc(256);
  10047. if (!httpinput)
  10048. quit(1, "Failed to malloc httpinput");
  10049. strcpy(httpinput, "http://");
  10050. strncat(httpinput, url, 248);
  10051. free(url);
  10052. url = httpinput;
  10053. }
  10054. ret = add_pool_details(pool, live, url, user, pass);
  10055. out:
  10056. immedok(logwin, false);
  10057. if (!ret) {
  10058. if (url)
  10059. free(url);
  10060. if (user)
  10061. free(user);
  10062. if (pass)
  10063. free(pass);
  10064. }
  10065. return ret;
  10066. }
  10067. #endif
  10068. #if BLKMAKER_VERSION > 1
  10069. static
  10070. bool _add_local_gbt(const char * const filepath, void *userp)
  10071. {
  10072. const bool * const live_p = userp;
  10073. struct pool *pool;
  10074. char buf[0x100];
  10075. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10076. int rpcport = 0, rpcssl = -101;
  10077. FILE * const F = fopen(filepath, "r");
  10078. if (!F)
  10079. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10080. while (fgets(buf, sizeof(buf), F))
  10081. {
  10082. if (!strncasecmp(buf, "rpcuser=", 8))
  10083. rpcuser = trimmed_strdup(&buf[8]);
  10084. else
  10085. if (!strncasecmp(buf, "rpcpassword=", 12))
  10086. rpcpass = trimmed_strdup(&buf[12]);
  10087. else
  10088. if (!strncasecmp(buf, "rpcport=", 8))
  10089. rpcport = atoi(&buf[8]);
  10090. else
  10091. if (!strncasecmp(buf, "rpcssl=", 7))
  10092. rpcssl = atoi(&buf[7]);
  10093. else
  10094. if (!strncasecmp(buf, "rpcconnect=", 11))
  10095. rpcconnect = trimmed_strdup(&buf[11]);
  10096. else
  10097. continue;
  10098. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10099. break;
  10100. }
  10101. fclose(F);
  10102. if (!rpcpass)
  10103. {
  10104. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10105. err:
  10106. free(rpcuser);
  10107. free(rpcpass);
  10108. goto out;
  10109. }
  10110. if (!rpcport)
  10111. rpcport = 8332;
  10112. if (rpcssl == -101)
  10113. rpcssl = 0;
  10114. const bool have_cbaddr = bytes_len(&opt_coinbase_script);
  10115. const int uri_sz = 0x30;
  10116. char * const uri = malloc(uri_sz);
  10117. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10118. char hfuri[0x40];
  10119. if (rpcconnect)
  10120. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10121. else
  10122. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10123. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10124. for (int i = 0; i < total_pools; ++i)
  10125. {
  10126. struct pool *pool = pools[i];
  10127. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10128. {
  10129. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10130. free(uri);
  10131. goto err;
  10132. }
  10133. }
  10134. pool = add_pool();
  10135. if (!pool)
  10136. {
  10137. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10138. goto err;
  10139. }
  10140. if (!rpcuser)
  10141. rpcuser = "";
  10142. pool->quota = 0;
  10143. adjust_quota_gcd();
  10144. pool->failover_only = true;
  10145. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10146. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10147. out:
  10148. return false;
  10149. }
  10150. static
  10151. void add_local_gbt(bool live)
  10152. {
  10153. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10154. }
  10155. #endif
  10156. #if defined(unix) || defined(__APPLE__)
  10157. static void fork_monitor()
  10158. {
  10159. // Make a pipe: [readFD, writeFD]
  10160. int pfd[2];
  10161. int r = pipe(pfd);
  10162. if (r < 0) {
  10163. perror("pipe - failed to create pipe for --monitor");
  10164. exit(1);
  10165. }
  10166. // Make stderr write end of pipe
  10167. fflush(stderr);
  10168. r = dup2(pfd[1], 2);
  10169. if (r < 0) {
  10170. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10171. exit(1);
  10172. }
  10173. r = close(pfd[1]);
  10174. if (r < 0) {
  10175. perror("close - failed to close write end of pipe for --monitor");
  10176. exit(1);
  10177. }
  10178. // Don't allow a dying monitor to kill the main process
  10179. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10180. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10181. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10182. perror("signal - failed to edit signal mask for --monitor");
  10183. exit(1);
  10184. }
  10185. // Fork a child process
  10186. forkpid = fork();
  10187. if (forkpid < 0) {
  10188. perror("fork - failed to fork child process for --monitor");
  10189. exit(1);
  10190. }
  10191. // Child: launch monitor command
  10192. if (0 == forkpid) {
  10193. // Make stdin read end of pipe
  10194. r = dup2(pfd[0], 0);
  10195. if (r < 0) {
  10196. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10197. exit(1);
  10198. }
  10199. close(pfd[0]);
  10200. if (r < 0) {
  10201. perror("close - in child, failed to close read end of pipe for --monitor");
  10202. exit(1);
  10203. }
  10204. // Launch user specified command
  10205. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10206. perror("execl - in child failed to exec user specified command for --monitor");
  10207. exit(1);
  10208. }
  10209. // Parent: clean up unused fds and bail
  10210. r = close(pfd[0]);
  10211. if (r < 0) {
  10212. perror("close - failed to close read end of pipe for --monitor");
  10213. exit(1);
  10214. }
  10215. }
  10216. #endif // defined(unix)
  10217. #ifdef HAVE_CURSES
  10218. #ifdef USE_UNICODE
  10219. static
  10220. wchar_t select_unicode_char(const wchar_t *opt)
  10221. {
  10222. for ( ; *opt; ++opt)
  10223. if (iswprint(*opt))
  10224. return *opt;
  10225. return '?';
  10226. }
  10227. #endif
  10228. void enable_curses(void) {
  10229. int x;
  10230. __maybe_unused int y;
  10231. lock_curses();
  10232. if (curses_active) {
  10233. unlock_curses();
  10234. return;
  10235. }
  10236. #ifdef USE_UNICODE
  10237. if (use_unicode)
  10238. {
  10239. setlocale(LC_CTYPE, "");
  10240. if (iswprint(0xb0))
  10241. have_unicode_degrees = true;
  10242. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10243. }
  10244. #endif
  10245. mainwin = initscr();
  10246. start_color();
  10247. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10248. if (ERR != use_default_colors())
  10249. default_bgcolor = -1;
  10250. #endif
  10251. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10252. {
  10253. menu_attr = COLOR_PAIR(1);
  10254. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10255. attr_bad |= COLOR_PAIR(2);
  10256. }
  10257. keypad(mainwin, true);
  10258. getmaxyx(mainwin, y, x);
  10259. statuswin = newwin(logstart, x, 0, 0);
  10260. leaveok(statuswin, true);
  10261. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10262. // We resize the window later anyway, so just start it off at 1 :)
  10263. logwin = newwin(1, 0, logcursor, 0);
  10264. idlok(logwin, true);
  10265. scrollok(logwin, true);
  10266. leaveok(logwin, true);
  10267. cbreak();
  10268. noecho();
  10269. nonl();
  10270. curses_active = true;
  10271. statusy = logstart;
  10272. unlock_curses();
  10273. }
  10274. #endif
  10275. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10276. #ifndef WANT_CPUMINE
  10277. struct device_drv cpu_drv;
  10278. struct device_drv cpu_drv = {
  10279. .name = "CPU",
  10280. };
  10281. #endif
  10282. static int cgminer_id_count = 0;
  10283. static int device_line_id_count;
  10284. void register_device(struct cgpu_info *cgpu)
  10285. {
  10286. cgpu->deven = DEV_ENABLED;
  10287. wr_lock(&devices_lock);
  10288. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10289. wr_unlock(&devices_lock);
  10290. if (!cgpu->proc_id)
  10291. cgpu->device_line_id = device_line_id_count++;
  10292. int thr_objs = cgpu->threads ?: 1;
  10293. mining_threads += thr_objs;
  10294. base_queue += thr_objs + cgpu->extra_work_queue;
  10295. #ifdef HAVE_CURSES
  10296. adj_width(mining_threads, &dev_width);
  10297. #endif
  10298. rwlock_init(&cgpu->qlock);
  10299. cgpu->queued_work = NULL;
  10300. }
  10301. struct _cgpu_devid_counter {
  10302. char name[4];
  10303. int lastid;
  10304. UT_hash_handle hh;
  10305. };
  10306. void renumber_cgpu(struct cgpu_info *cgpu)
  10307. {
  10308. static struct _cgpu_devid_counter *devids = NULL;
  10309. struct _cgpu_devid_counter *d;
  10310. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10311. if (d)
  10312. cgpu->device_id = ++d->lastid;
  10313. else {
  10314. d = malloc(sizeof(*d));
  10315. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10316. cgpu->device_id = d->lastid = 0;
  10317. HASH_ADD_STR(devids, name, d);
  10318. }
  10319. // Build repr strings
  10320. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10321. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10322. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10323. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10324. const int lpcount = cgpu->procs;
  10325. if (lpcount > 1)
  10326. {
  10327. int ns;
  10328. struct cgpu_info *slave;
  10329. int lpdigits = 1;
  10330. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10331. ++lpdigits;
  10332. if (lpdigits > max_lpdigits)
  10333. max_lpdigits = lpdigits;
  10334. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10335. cgpu->proc_repr[5 + lpdigits] = '\0';
  10336. ns = strlen(cgpu->proc_repr_ns);
  10337. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10338. slave = cgpu;
  10339. for (int i = 1; i < lpcount; ++i)
  10340. {
  10341. slave = slave->next_proc;
  10342. strcpy(slave->proc_repr, cgpu->proc_repr);
  10343. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10344. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10345. {
  10346. slave->proc_repr_ns[ns + y] =
  10347. slave->proc_repr[5 + y] += (x % 26);
  10348. }
  10349. }
  10350. }
  10351. }
  10352. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10353. {
  10354. sha256(buffer, length, digest);
  10355. return true;
  10356. }
  10357. static
  10358. int drv_algo_check(const struct device_drv * const drv)
  10359. {
  10360. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  10361. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  10362. return (algos & algomatch);
  10363. }
  10364. #ifndef HAVE_PTHREAD_CANCEL
  10365. extern void setup_pthread_cancel_workaround();
  10366. extern struct sigaction pcwm_orig_term_handler;
  10367. #endif
  10368. bool bfg_need_detect_rescan;
  10369. extern void probe_device(struct lowlevel_device_info *);
  10370. static void schedule_rescan(const struct timeval *);
  10371. static
  10372. void drv_detect_all()
  10373. {
  10374. bool rescanning = false;
  10375. rescan:
  10376. bfg_need_detect_rescan = false;
  10377. #ifdef HAVE_BFG_LOWLEVEL
  10378. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10379. LL_FOREACH_SAFE(infolist, info, infotmp)
  10380. probe_device(info);
  10381. LL_FOREACH_SAFE(infolist, info, infotmp)
  10382. pthread_join(info->probe_pth, NULL);
  10383. #endif
  10384. struct driver_registration *reg, *tmp;
  10385. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10386. {
  10387. const struct device_drv * const drv = reg->drv;
  10388. if (!(drv_algo_check(drv) && drv->drv_detect))
  10389. continue;
  10390. drv->drv_detect();
  10391. }
  10392. #ifdef HAVE_BFG_LOWLEVEL
  10393. lowlevel_scan_free();
  10394. #endif
  10395. if (bfg_need_detect_rescan)
  10396. {
  10397. if (rescanning)
  10398. {
  10399. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10400. struct timeval tv_when;
  10401. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10402. schedule_rescan(&tv_when);
  10403. }
  10404. else
  10405. {
  10406. rescanning = true;
  10407. applog(LOG_DEBUG, "Device rescan requested");
  10408. goto rescan;
  10409. }
  10410. }
  10411. }
  10412. static
  10413. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10414. {
  10415. struct thr_info *thr;
  10416. int j;
  10417. struct device_drv *api = cgpu->drv;
  10418. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10419. int threadobj = cgpu->threads;
  10420. if (!threadobj)
  10421. // Create a fake thread object to handle hashmeter etc
  10422. threadobj = 1;
  10423. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10424. cgpu->thr[threadobj] = NULL;
  10425. cgpu->status = LIFE_INIT;
  10426. if (opt_devices_enabled_list)
  10427. {
  10428. struct string_elist *enablestr_elist;
  10429. cgpu->deven = DEV_DISABLED;
  10430. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10431. {
  10432. const char * const enablestr = enablestr_elist->string;
  10433. if (cgpu_match(enablestr, cgpu))
  10434. {
  10435. cgpu->deven = DEV_ENABLED;
  10436. break;
  10437. }
  10438. }
  10439. }
  10440. cgpu->max_hashes = 0;
  10441. BFGINIT(cgpu->min_nonce_diff, 1);
  10442. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10443. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10444. // Setup thread structs before starting any of the threads, in case they try to interact
  10445. for (j = 0; j < threadobj; ++j, ++*kp) {
  10446. thr = get_thread(*kp);
  10447. thr->id = *kp;
  10448. thr->cgpu = cgpu;
  10449. thr->device_thread = j;
  10450. thr->work_restart_notifier[1] = INVSOCK;
  10451. thr->mutex_request[1] = INVSOCK;
  10452. thr->_job_transition_in_progress = true;
  10453. timerclear(&thr->tv_morework);
  10454. thr->scanhash_working = true;
  10455. thr->hashes_done = 0;
  10456. timerclear(&thr->tv_hashes_done);
  10457. cgtime(&thr->tv_lastupdate);
  10458. thr->tv_poll.tv_sec = -1;
  10459. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10460. cgpu->thr[j] = thr;
  10461. }
  10462. if (!cgpu->device->threads)
  10463. notifier_init_invalid(cgpu->thr[0]->notifier);
  10464. else
  10465. if (!cgpu->threads)
  10466. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10467. else
  10468. for (j = 0; j < cgpu->threads; ++j)
  10469. {
  10470. thr = cgpu->thr[j];
  10471. notifier_init(thr->notifier);
  10472. }
  10473. }
  10474. static
  10475. void start_cgpu(struct cgpu_info *cgpu)
  10476. {
  10477. struct thr_info *thr;
  10478. int j;
  10479. for (j = 0; j < cgpu->threads; ++j) {
  10480. thr = cgpu->thr[j];
  10481. /* Enable threads for devices set not to mine but disable
  10482. * their queue in case we wish to enable them later */
  10483. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10484. continue;
  10485. thread_reportout(thr);
  10486. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10487. quit(1, "thread %d create failed", thr->id);
  10488. notifier_wake(thr->notifier);
  10489. }
  10490. if (cgpu->deven == DEV_ENABLED)
  10491. proc_enable(cgpu);
  10492. }
  10493. static
  10494. void _scan_serial(void *p)
  10495. {
  10496. const char *s = p;
  10497. struct string_elist *iter, *tmp;
  10498. struct string_elist *orig_scan_devices = scan_devices;
  10499. if (s)
  10500. {
  10501. // Make temporary scan_devices list
  10502. scan_devices = NULL;
  10503. string_elist_add("noauto", &scan_devices);
  10504. add_serial(s);
  10505. }
  10506. drv_detect_all();
  10507. if (s)
  10508. {
  10509. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10510. {
  10511. string_elist_del(&scan_devices, iter);
  10512. }
  10513. scan_devices = orig_scan_devices;
  10514. }
  10515. }
  10516. #ifdef HAVE_BFG_LOWLEVEL
  10517. static
  10518. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10519. {
  10520. if (!(false
  10521. || (info->serial && !strcasecmp(ser, info->serial))
  10522. || (info->path && !strcasecmp(ser, info->path ))
  10523. || (info->devid && !strcasecmp(ser, info->devid ))
  10524. ))
  10525. {
  10526. char *devid = devpath_to_devid(ser);
  10527. if (!devid)
  10528. return false;
  10529. const bool different = strcmp(info->devid, devid);
  10530. free(devid);
  10531. if (different)
  10532. return false;
  10533. }
  10534. return true;
  10535. }
  10536. static
  10537. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10538. {
  10539. struct driver_registration *dreg;
  10540. char dname[dnamelen];
  10541. int i;
  10542. for (i = 0; i < dnamelen; ++i)
  10543. dname[i] = tolower(_dname[i]);
  10544. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10545. if (!dreg)
  10546. {
  10547. for (i = 0; i < dnamelen; ++i)
  10548. dname[i] = toupper(_dname[i]);
  10549. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10550. if (!dreg)
  10551. return NULL;
  10552. }
  10553. if (!drv_algo_check(dreg->drv))
  10554. return NULL;
  10555. return dreg->drv;
  10556. }
  10557. static
  10558. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10559. {
  10560. bfg_probe_result_flags = 0;
  10561. if (drv->lowl_probe(info))
  10562. {
  10563. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10564. return true;
  10565. }
  10566. else
  10567. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10568. *request_rescan_p = true;
  10569. return false;
  10570. }
  10571. bool dummy_check_never_true = false;
  10572. static
  10573. void *probe_device_thread(void *p)
  10574. {
  10575. struct lowlevel_device_info * const infolist = p;
  10576. struct lowlevel_device_info *info = infolist;
  10577. bool request_rescan = false;
  10578. {
  10579. char threadname[5 + strlen(info->devid) + 1];
  10580. sprintf(threadname, "probe_%s", info->devid);
  10581. RenameThread(threadname);
  10582. }
  10583. // If already in use, ignore
  10584. if (bfg_claim_any(NULL, NULL, info->devid))
  10585. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10586. __func__, info->product);
  10587. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10588. struct string_elist *sd_iter, *sd_tmp;
  10589. struct driver_registration *dreg, *dreg_tmp;
  10590. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10591. {
  10592. const char * const dname = sd_iter->string;
  10593. const char * const colon = strpbrk(dname, ":@");
  10594. if (!(colon && colon != dname))
  10595. continue;
  10596. const char * const ser = &colon[1];
  10597. LL_FOREACH2(infolist, info, same_devid_next)
  10598. {
  10599. if (!_probe_device_match(info, ser))
  10600. continue;
  10601. const size_t dnamelen = (colon - dname);
  10602. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10603. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10604. continue;
  10605. if (_probe_device_do_probe(drv, info, &request_rescan))
  10606. return NULL;
  10607. }
  10608. }
  10609. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10610. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10611. {
  10612. const struct device_drv * const drv = dreg->drv;
  10613. if (!drv_algo_check(drv))
  10614. continue;
  10615. // Check for "noauto" flag
  10616. // NOTE: driver-specific configuration overrides general
  10617. bool doauto = true;
  10618. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10619. {
  10620. const char * const dname = sd_iter->string;
  10621. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10622. const char *colon = strchr(dname, ':');
  10623. if (!colon)
  10624. colon = &dname[-1];
  10625. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10626. continue;
  10627. const ssize_t dnamelen = (colon - dname);
  10628. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10629. continue;
  10630. doauto = (tolower(colon[1]) == 'a');
  10631. if (dnamelen != -1)
  10632. break;
  10633. }
  10634. if (doauto && drv->lowl_match)
  10635. {
  10636. LL_FOREACH2(infolist, info, same_devid_next)
  10637. {
  10638. /*
  10639. The below call to applog is absolutely necessary
  10640. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10641. Mac OS X using Homebrew results in a binary that segfaults on startup
  10642. There are two unresolved issues:
  10643. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10644. in debug symbols being available to help troubleshoot the issue
  10645. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10646. call to applog with infolist and / or p
  10647. We would encourage revisiting this in the future to come up with a more concrete solution
  10648. Reproducing should only require commenting / removing the following line and installing
  10649. BFGMiner using "brew install bfgminer --HEAD"
  10650. */
  10651. if (dummy_check_never_true)
  10652. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10653. if (!drv->lowl_match(info))
  10654. continue;
  10655. if (_probe_device_do_probe(drv, info, &request_rescan))
  10656. return NULL;
  10657. }
  10658. }
  10659. }
  10660. // probe driver(s) with 'all' enabled
  10661. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10662. {
  10663. const char * const dname = sd_iter->string;
  10664. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10665. const char * const colon = strchr(dname, ':');
  10666. if (!colon)
  10667. {
  10668. LL_FOREACH2(infolist, info, same_devid_next)
  10669. {
  10670. if (
  10671. #ifdef NEED_BFG_LOWL_VCOM
  10672. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  10673. #endif
  10674. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  10675. {
  10676. bool dont_rescan = false;
  10677. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10678. {
  10679. const struct device_drv * const drv = dreg->drv;
  10680. if (!drv_algo_check(drv))
  10681. continue;
  10682. if (drv->lowl_probe_by_name_only)
  10683. continue;
  10684. if (!drv->lowl_probe)
  10685. continue;
  10686. if (_probe_device_do_probe(drv, info, NULL))
  10687. return NULL;
  10688. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  10689. dont_rescan = true;
  10690. }
  10691. if (opt_hotplug && !dont_rescan)
  10692. request_rescan = true;
  10693. break;
  10694. }
  10695. }
  10696. continue;
  10697. }
  10698. if (strcasecmp(&colon[1], "all"))
  10699. continue;
  10700. const size_t dnamelen = (colon - dname);
  10701. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10702. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10703. continue;
  10704. LL_FOREACH2(infolist, info, same_devid_next)
  10705. {
  10706. if (info->lowl->exclude_from_all)
  10707. continue;
  10708. if (_probe_device_do_probe(drv, info, NULL))
  10709. return NULL;
  10710. }
  10711. }
  10712. // Only actually request a rescan if we never found any cgpu
  10713. if (request_rescan)
  10714. bfg_need_detect_rescan = true;
  10715. return NULL;
  10716. }
  10717. void probe_device(struct lowlevel_device_info * const info)
  10718. {
  10719. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  10720. }
  10721. #endif
  10722. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  10723. {
  10724. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  10725. int devcount, i, mining_threads_new = 0;
  10726. unsigned int k;
  10727. struct cgpu_info *cgpu;
  10728. struct thr_info *thr;
  10729. void *p;
  10730. mutex_lock(&mutex);
  10731. devcount = total_devices;
  10732. addfunc(arg);
  10733. if (!total_devices_new)
  10734. goto out;
  10735. wr_lock(&devices_lock);
  10736. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  10737. if (unlikely(!p))
  10738. {
  10739. wr_unlock(&devices_lock);
  10740. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  10741. goto out;
  10742. }
  10743. devices = p;
  10744. wr_unlock(&devices_lock);
  10745. for (i = 0; i < total_devices_new; ++i)
  10746. {
  10747. cgpu = devices_new[i];
  10748. mining_threads_new += cgpu->threads ?: 1;
  10749. }
  10750. wr_lock(&mining_thr_lock);
  10751. mining_threads_new += mining_threads;
  10752. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  10753. if (unlikely(!p))
  10754. {
  10755. wr_unlock(&mining_thr_lock);
  10756. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  10757. goto out;
  10758. }
  10759. mining_thr = p;
  10760. wr_unlock(&mining_thr_lock);
  10761. for (i = mining_threads; i < mining_threads_new; ++i) {
  10762. mining_thr[i] = calloc(1, sizeof(*thr));
  10763. if (!mining_thr[i])
  10764. {
  10765. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  10766. for ( ; --i >= mining_threads; )
  10767. free(mining_thr[i]);
  10768. goto out;
  10769. }
  10770. }
  10771. k = mining_threads;
  10772. for (i = 0; i < total_devices_new; ++i)
  10773. {
  10774. cgpu = devices_new[i];
  10775. allocate_cgpu(cgpu, &k);
  10776. }
  10777. for (i = 0; i < total_devices_new; ++i)
  10778. {
  10779. cgpu = devices_new[i];
  10780. start_cgpu(cgpu);
  10781. register_device(cgpu);
  10782. ++total_devices;
  10783. }
  10784. #ifdef HAVE_CURSES
  10785. switch_logsize();
  10786. #endif
  10787. out:
  10788. total_devices_new = 0;
  10789. devcount = total_devices - devcount;
  10790. mutex_unlock(&mutex);
  10791. return devcount;
  10792. }
  10793. int scan_serial(const char *s)
  10794. {
  10795. return create_new_cgpus(_scan_serial, (void*)s);
  10796. }
  10797. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  10798. static bool rescan_active;
  10799. static struct timeval tv_rescan;
  10800. static notifier_t rescan_notifier;
  10801. static
  10802. void *rescan_thread(__maybe_unused void *p)
  10803. {
  10804. pthread_detach(pthread_self());
  10805. RenameThread("rescan");
  10806. struct timeval tv_timeout, tv_now;
  10807. fd_set rfds;
  10808. while (true)
  10809. {
  10810. mutex_lock(&rescan_mutex);
  10811. tv_timeout = tv_rescan;
  10812. if (!timer_isset(&tv_timeout))
  10813. {
  10814. rescan_active = false;
  10815. mutex_unlock(&rescan_mutex);
  10816. break;
  10817. }
  10818. mutex_unlock(&rescan_mutex);
  10819. FD_ZERO(&rfds);
  10820. FD_SET(rescan_notifier[0], &rfds);
  10821. const int maxfd = rescan_notifier[0];
  10822. timer_set_now(&tv_now);
  10823. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  10824. notifier_read(rescan_notifier);
  10825. mutex_lock(&rescan_mutex);
  10826. if (timer_passed(&tv_rescan, NULL))
  10827. {
  10828. timer_unset(&tv_rescan);
  10829. mutex_unlock(&rescan_mutex);
  10830. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  10831. scan_serial(NULL);
  10832. }
  10833. else
  10834. mutex_unlock(&rescan_mutex);
  10835. }
  10836. return NULL;
  10837. }
  10838. static
  10839. void _schedule_rescan(const struct timeval * const tvp_when)
  10840. {
  10841. if (rescan_active)
  10842. {
  10843. if (timercmp(tvp_when, &tv_rescan, <))
  10844. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  10845. else
  10846. {
  10847. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  10848. tv_rescan = *tvp_when;
  10849. }
  10850. return;
  10851. }
  10852. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  10853. tv_rescan = *tvp_when;
  10854. rescan_active = true;
  10855. static pthread_t pth;
  10856. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  10857. applog(LOG_ERR, "Failed to start rescan thread");
  10858. }
  10859. static
  10860. void schedule_rescan(const struct timeval * const tvp_when)
  10861. {
  10862. mutex_lock(&rescan_mutex);
  10863. _schedule_rescan(tvp_when);
  10864. mutex_unlock(&rescan_mutex);
  10865. }
  10866. #ifdef HAVE_BFG_HOTPLUG
  10867. static
  10868. void hotplug_trigger()
  10869. {
  10870. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  10871. struct timeval tv_now;
  10872. timer_set_now(&tv_now);
  10873. schedule_rescan(&tv_now);
  10874. }
  10875. #endif
  10876. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  10877. static
  10878. void *hotplug_thread(__maybe_unused void *p)
  10879. {
  10880. pthread_detach(pthread_self());
  10881. RenameThread("hotplug");
  10882. struct udev * const udev = udev_new();
  10883. if (unlikely(!udev))
  10884. applogfailr(NULL, LOG_ERR, "udev_new");
  10885. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  10886. if (unlikely(!mon))
  10887. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  10888. if (unlikely(udev_monitor_enable_receiving(mon)))
  10889. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  10890. const int epfd = epoll_create(1);
  10891. if (unlikely(epfd == -1))
  10892. applogfailr(NULL, LOG_ERR, "epoll_create");
  10893. {
  10894. const int fd = udev_monitor_get_fd(mon);
  10895. struct epoll_event ev = {
  10896. .events = EPOLLIN | EPOLLPRI,
  10897. .data.fd = fd,
  10898. };
  10899. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  10900. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  10901. }
  10902. struct epoll_event ev;
  10903. int rv;
  10904. bool pending = false;
  10905. while (true)
  10906. {
  10907. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  10908. if (rv == -1)
  10909. {
  10910. if (errno == EAGAIN || errno == EINTR)
  10911. continue;
  10912. break;
  10913. }
  10914. if (!rv)
  10915. {
  10916. hotplug_trigger();
  10917. pending = false;
  10918. continue;
  10919. }
  10920. struct udev_device * const device = udev_monitor_receive_device(mon);
  10921. if (!device)
  10922. continue;
  10923. const char * const action = udev_device_get_action(device);
  10924. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  10925. if (!strcmp(action, "add"))
  10926. pending = true;
  10927. udev_device_unref(device);
  10928. }
  10929. applogfailr(NULL, LOG_ERR, "epoll_wait");
  10930. }
  10931. #elif defined(WIN32)
  10932. static UINT_PTR _hotplug_wintimer_id;
  10933. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  10934. {
  10935. KillTimer(NULL, _hotplug_wintimer_id);
  10936. _hotplug_wintimer_id = 0;
  10937. hotplug_trigger();
  10938. }
  10939. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  10940. {
  10941. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  10942. {
  10943. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  10944. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  10945. }
  10946. return DefWindowProc(hwnd, msg, wParam, lParam);
  10947. }
  10948. static
  10949. void *hotplug_thread(__maybe_unused void *p)
  10950. {
  10951. pthread_detach(pthread_self());
  10952. WNDCLASS DummyWinCls = {
  10953. .lpszClassName = "BFGDummyWinCls",
  10954. .lpfnWndProc = hotplug_win_callback,
  10955. };
  10956. ATOM a = RegisterClass(&DummyWinCls);
  10957. if (unlikely(!a))
  10958. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  10959. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  10960. if (unlikely(!hwnd))
  10961. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  10962. MSG msg;
  10963. while (GetMessage(&msg, NULL, 0, 0))
  10964. {
  10965. TranslateMessage(&msg);
  10966. DispatchMessage(&msg);
  10967. }
  10968. quit(0, "WM_QUIT received");
  10969. return NULL;
  10970. }
  10971. #endif
  10972. #ifdef HAVE_BFG_HOTPLUG
  10973. static
  10974. void hotplug_start()
  10975. {
  10976. pthread_t pth;
  10977. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  10978. applog(LOG_ERR, "Failed to start hotplug thread");
  10979. }
  10980. #endif
  10981. static void probe_pools(void)
  10982. {
  10983. int i;
  10984. for (i = 0; i < total_pools; i++) {
  10985. struct pool *pool = pools[i];
  10986. pool->testing = true;
  10987. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10988. }
  10989. }
  10990. static void raise_fd_limits(void)
  10991. {
  10992. #ifdef HAVE_SETRLIMIT
  10993. struct rlimit fdlimit;
  10994. rlim_t old_soft_limit;
  10995. char frombuf[0x10] = "unlimited";
  10996. char hardbuf[0x10] = "unlimited";
  10997. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  10998. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  10999. old_soft_limit = fdlimit.rlim_cur;
  11000. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11001. fdlimit.rlim_cur = FD_SETSIZE;
  11002. else
  11003. fdlimit.rlim_cur = fdlimit.rlim_max;
  11004. if (fdlimit.rlim_max != RLIM_INFINITY)
  11005. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11006. if (old_soft_limit != RLIM_INFINITY)
  11007. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11008. if (fdlimit.rlim_cur == old_soft_limit)
  11009. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11010. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11011. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11012. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11013. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11014. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11015. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11016. #else
  11017. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11018. #endif
  11019. }
  11020. static
  11021. void bfg_atexit(void)
  11022. {
  11023. puts("");
  11024. }
  11025. extern void bfg_init_threadlocal();
  11026. extern void stratumsrv_start();
  11027. extern void test_aan_pll(void);
  11028. int main(int argc, char *argv[])
  11029. {
  11030. struct sigaction handler;
  11031. struct thr_info *thr;
  11032. unsigned int k;
  11033. int i;
  11034. int rearrange_pools = 0;
  11035. char *s;
  11036. #ifdef WIN32
  11037. LoadLibrary("backtrace.dll");
  11038. #endif
  11039. atexit(bfg_atexit);
  11040. b58_sha256_impl = my_blkmaker_sha256_callback;
  11041. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11042. bfg_init_threadlocal();
  11043. #ifndef HAVE_PTHREAD_CANCEL
  11044. setup_pthread_cancel_workaround();
  11045. #endif
  11046. bfg_init_checksums();
  11047. #ifdef WIN32
  11048. {
  11049. WSADATA wsa;
  11050. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11051. if (i)
  11052. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11053. }
  11054. #endif
  11055. /* This dangerous functions tramples random dynamically allocated
  11056. * variables so do it before anything at all */
  11057. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11058. quit(1, "Failed to curl_global_init");
  11059. initial_args = malloc(sizeof(char *) * (argc + 1));
  11060. for (i = 0; i < argc; i++)
  11061. initial_args[i] = strdup(argv[i]);
  11062. initial_args[argc] = NULL;
  11063. mutex_init(&hash_lock);
  11064. mutex_init(&console_lock);
  11065. cglock_init(&control_lock);
  11066. mutex_init(&stats_lock);
  11067. mutex_init(&sharelog_lock);
  11068. cglock_init(&ch_lock);
  11069. mutex_init(&sshare_lock);
  11070. rwlock_init(&blk_lock);
  11071. rwlock_init(&netacc_lock);
  11072. rwlock_init(&mining_thr_lock);
  11073. rwlock_init(&devices_lock);
  11074. mutex_init(&lp_lock);
  11075. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11076. quit(1, "Failed to pthread_cond_init lp_cond");
  11077. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11078. quit(1, "Failed to pthread_cond_init gws_cond");
  11079. notifier_init(submit_waiting_notifier);
  11080. timer_unset(&tv_rescan);
  11081. notifier_init(rescan_notifier);
  11082. /* Create a unique get work queue */
  11083. getq = tq_new();
  11084. if (!getq)
  11085. quit(1, "Failed to create getq");
  11086. /* We use the getq mutex as the staged lock */
  11087. stgd_lock = &getq->mutex;
  11088. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11089. #ifdef WANT_CPUMINE
  11090. init_max_name_len();
  11091. #endif
  11092. handler.sa_handler = &sighandler;
  11093. handler.sa_flags = 0;
  11094. sigemptyset(&handler.sa_mask);
  11095. #ifdef HAVE_PTHREAD_CANCEL
  11096. sigaction(SIGTERM, &handler, &termhandler);
  11097. #else
  11098. // Need to let pthread_cancel emulation handle SIGTERM first
  11099. termhandler = pcwm_orig_term_handler;
  11100. pcwm_orig_term_handler = handler;
  11101. #endif
  11102. sigaction(SIGINT, &handler, &inthandler);
  11103. #ifndef WIN32
  11104. signal(SIGPIPE, SIG_IGN);
  11105. #else
  11106. timeBeginPeriod(1);
  11107. #endif
  11108. opt_kernel_path = CGMINER_PREFIX;
  11109. cgminer_path = alloca(PATH_MAX);
  11110. s = strdup(argv[0]);
  11111. strcpy(cgminer_path, dirname(s));
  11112. free(s);
  11113. strcat(cgminer_path, "/");
  11114. #if defined(WANT_CPUMINE) && defined(WIN32)
  11115. {
  11116. char buf[32];
  11117. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11118. if (gev > 0 && gev < sizeof(buf))
  11119. {
  11120. setup_benchmark_pool();
  11121. double rate = bench_algo_stage3(atoi(buf));
  11122. // Write result to shared memory for parent
  11123. char unique_name[64];
  11124. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11125. {
  11126. HANDLE map_handle = CreateFileMapping(
  11127. INVALID_HANDLE_VALUE, // use paging file
  11128. NULL, // default security attributes
  11129. PAGE_READWRITE, // read/write access
  11130. 0, // size: high 32-bits
  11131. 4096, // size: low 32-bits
  11132. unique_name // name of map object
  11133. );
  11134. if (NULL != map_handle) {
  11135. void *shared_mem = MapViewOfFile(
  11136. map_handle, // object to map view of
  11137. FILE_MAP_WRITE, // read/write access
  11138. 0, // high offset: map from
  11139. 0, // low offset: beginning
  11140. 0 // default: map entire file
  11141. );
  11142. if (NULL != shared_mem)
  11143. CopyMemory(shared_mem, &rate, sizeof(rate));
  11144. (void)UnmapViewOfFile(shared_mem);
  11145. }
  11146. (void)CloseHandle(map_handle);
  11147. }
  11148. exit(0);
  11149. }
  11150. }
  11151. #endif
  11152. #ifdef HAVE_CURSES
  11153. devcursor = 8;
  11154. logstart = devcursor;
  11155. logcursor = logstart;
  11156. #endif
  11157. mutex_init(&submitting_lock);
  11158. #ifdef HAVE_OPENCL
  11159. opencl_early_init();
  11160. #endif
  11161. schedstart.tm.tm_sec = 1;
  11162. schedstop .tm.tm_sec = 1;
  11163. opt_register_table(opt_early_table, NULL);
  11164. opt_register_table(opt_config_table, NULL);
  11165. opt_register_table(opt_cmdline_table, NULL);
  11166. opt_early_parse(argc, argv, applog_and_exit);
  11167. if (!config_loaded)
  11168. {
  11169. load_default_config();
  11170. rearrange_pools = total_pools;
  11171. }
  11172. opt_free_table();
  11173. /* parse command line */
  11174. opt_register_table(opt_config_table,
  11175. "Options for both config file and command line");
  11176. opt_register_table(opt_cmdline_table,
  11177. "Options for command line only");
  11178. opt_parse(&argc, argv, applog_and_exit);
  11179. if (argc != 1)
  11180. quit(1, "Unexpected extra commandline arguments");
  11181. if (rearrange_pools && rearrange_pools < total_pools)
  11182. {
  11183. // Prioritise commandline pools before default-config pools
  11184. for (i = 0; i < rearrange_pools; ++i)
  11185. pools[i]->prio += rearrange_pools;
  11186. for ( ; i < total_pools; ++i)
  11187. pools[i]->prio -= rearrange_pools;
  11188. }
  11189. #ifndef HAVE_PTHREAD_CANCEL
  11190. // Can't do this any earlier, or config isn't loaded
  11191. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11192. #endif
  11193. #ifdef HAVE_PWD_H
  11194. struct passwd *user_info = NULL;
  11195. if (opt_setuid != NULL) {
  11196. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11197. quit(1, "Unable to find setuid user information");
  11198. }
  11199. }
  11200. #endif
  11201. #ifdef HAVE_CHROOT
  11202. if (chroot_dir != NULL) {
  11203. #ifdef HAVE_PWD_H
  11204. if (user_info == NULL && getuid() == 0) {
  11205. applog(LOG_WARNING, "Running as root inside chroot");
  11206. }
  11207. #endif
  11208. if (chroot(chroot_dir) != 0) {
  11209. quit(1, "Unable to chroot");
  11210. }
  11211. if (chdir("/"))
  11212. quit(1, "Unable to chdir to chroot");
  11213. }
  11214. #endif
  11215. #ifdef HAVE_PWD_H
  11216. if (user_info != NULL) {
  11217. if (setgid((*user_info).pw_gid) != 0)
  11218. quit(1, "Unable to setgid");
  11219. if (setuid((*user_info).pw_uid) != 0)
  11220. quit(1, "Unable to setuid");
  11221. }
  11222. #endif
  11223. raise_fd_limits();
  11224. if (opt_benchmark) {
  11225. while (total_pools)
  11226. remove_pool(pools[0]);
  11227. setup_benchmark_pool();
  11228. }
  11229. if (opt_unittest) {
  11230. test_cgpu_match();
  11231. test_intrange();
  11232. test_decimal_width();
  11233. test_domain_funcs();
  11234. #ifdef USE_SCRYPT
  11235. test_scrypt();
  11236. #endif
  11237. test_target();
  11238. test_uri_get_param();
  11239. utf8_test();
  11240. #ifdef USE_JINGTIAN
  11241. test_aan_pll();
  11242. #endif
  11243. if (unittest_failures)
  11244. quit(1, "Unit tests failed");
  11245. }
  11246. #ifdef HAVE_CURSES
  11247. if (opt_realquiet || opt_display_devs)
  11248. use_curses = false;
  11249. setlocale(LC_ALL, "C");
  11250. if (use_curses)
  11251. enable_curses();
  11252. #endif
  11253. #ifdef HAVE_LIBUSB
  11254. int err = libusb_init(NULL);
  11255. if (err)
  11256. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11257. else
  11258. have_libusb = true;
  11259. #endif
  11260. applog(LOG_WARNING, "Started %s", packagename);
  11261. {
  11262. struct bfg_loaded_configfile *configfile;
  11263. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11264. {
  11265. char * const cnfbuf = configfile->filename;
  11266. int fileconf_load = configfile->fileconf_load;
  11267. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11268. switch (fileconf_load) {
  11269. case 0:
  11270. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11271. applog(LOG_WARNING, "Configuration file could not be used.");
  11272. break;
  11273. case -1:
  11274. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11275. if (use_curses)
  11276. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11277. break;
  11278. default:
  11279. break;
  11280. }
  11281. }
  11282. }
  11283. i = strlen(opt_kernel_path) + 2;
  11284. char __kernel_path[i];
  11285. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11286. opt_kernel_path = __kernel_path;
  11287. if (want_per_device_stats)
  11288. opt_log_output = true;
  11289. #ifdef WANT_CPUMINE
  11290. #ifdef USE_SCRYPT
  11291. if (opt_scrypt)
  11292. set_scrypt_algo(&opt_algo);
  11293. #endif
  11294. #endif
  11295. bfg_devapi_init();
  11296. drv_detect_all();
  11297. total_devices = total_devices_new;
  11298. devices = devices_new;
  11299. total_devices_new = 0;
  11300. devices_new = NULL;
  11301. if (opt_display_devs) {
  11302. int devcount = 0;
  11303. applog(LOG_ERR, "Devices detected:");
  11304. for (i = 0; i < total_devices; ++i) {
  11305. struct cgpu_info *cgpu = devices[i];
  11306. char buf[0x100];
  11307. if (cgpu->device != cgpu)
  11308. continue;
  11309. if (cgpu->name)
  11310. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11311. else
  11312. if (cgpu->dev_manufacturer)
  11313. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11314. else
  11315. if (cgpu->dev_product)
  11316. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11317. else
  11318. strcpy(buf, " Device");
  11319. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11320. if (cgpu->dev_serial)
  11321. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11322. if (cgpu->device_path)
  11323. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11324. tailsprintf(buf, sizeof(buf), ")");
  11325. _applog(LOG_NOTICE, buf);
  11326. ++devcount;
  11327. }
  11328. quit(0, "%d devices listed", devcount);
  11329. }
  11330. mining_threads = 0;
  11331. for (i = 0; i < total_devices; ++i)
  11332. register_device(devices[i]);
  11333. if (!total_devices) {
  11334. applog(LOG_WARNING, "No devices detected!");
  11335. if (use_curses)
  11336. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11337. else
  11338. applog(LOG_WARNING, "Waiting for devices");
  11339. }
  11340. #ifdef HAVE_CURSES
  11341. switch_logsize();
  11342. #endif
  11343. #if BLKMAKER_VERSION > 1
  11344. if (opt_load_bitcoin_conf && !(opt_scrypt || opt_benchmark))
  11345. add_local_gbt(total_pools);
  11346. #endif
  11347. if (!total_pools) {
  11348. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11349. #ifdef HAVE_CURSES
  11350. if (!use_curses || !input_pool(false))
  11351. #endif
  11352. quit(1, "Pool setup failed");
  11353. }
  11354. for (i = 0; i < total_pools; i++) {
  11355. struct pool *pool = pools[i];
  11356. size_t siz;
  11357. if (!pool->rpc_url)
  11358. quit(1, "No URI supplied for pool %u", i);
  11359. if (!pool->rpc_userpass) {
  11360. if (!pool->rpc_user || !pool->rpc_pass)
  11361. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11362. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11363. pool->rpc_userpass = malloc(siz);
  11364. if (!pool->rpc_userpass)
  11365. quit(1, "Failed to malloc userpass");
  11366. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11367. }
  11368. }
  11369. /* Set the currentpool to pool with priority 0 */
  11370. validate_pool_priorities();
  11371. for (i = 0; i < total_pools; i++) {
  11372. struct pool *pool = pools[i];
  11373. if (!pool->prio)
  11374. currentpool = pool;
  11375. }
  11376. #ifdef HAVE_SYSLOG_H
  11377. if (use_syslog)
  11378. openlog(PACKAGE, LOG_PID, LOG_USER);
  11379. #endif
  11380. #if defined(unix) || defined(__APPLE__)
  11381. if (opt_stderr_cmd)
  11382. fork_monitor();
  11383. #endif // defined(unix)
  11384. mining_thr = calloc(mining_threads, sizeof(thr));
  11385. if (!mining_thr)
  11386. quit(1, "Failed to calloc mining_thr");
  11387. for (i = 0; i < mining_threads; i++) {
  11388. mining_thr[i] = calloc(1, sizeof(*thr));
  11389. if (!mining_thr[i])
  11390. quit(1, "Failed to calloc mining_thr[%d]", i);
  11391. }
  11392. total_control_threads = 6;
  11393. control_thr = calloc(total_control_threads, sizeof(*thr));
  11394. if (!control_thr)
  11395. quit(1, "Failed to calloc control_thr");
  11396. if (opt_benchmark)
  11397. goto begin_bench;
  11398. applog(LOG_NOTICE, "Probing for an alive pool");
  11399. do {
  11400. bool still_testing;
  11401. int i;
  11402. /* Look for at least one active pool before starting */
  11403. probe_pools();
  11404. do {
  11405. sleep(1);
  11406. if (pools_active)
  11407. break;
  11408. still_testing = false;
  11409. for (int i = 0; i < total_pools; ++i)
  11410. if (pools[i]->testing)
  11411. still_testing = true;
  11412. } while (still_testing);
  11413. if (!pools_active) {
  11414. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11415. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11416. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11417. for (i = 0; i < total_pools; i++) {
  11418. struct pool *pool;
  11419. pool = pools[i];
  11420. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11421. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11422. }
  11423. #ifdef HAVE_CURSES
  11424. if (use_curses) {
  11425. halfdelay(150);
  11426. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11427. if (getch() != ERR)
  11428. quit(0, "No servers could be used! Exiting.");
  11429. cbreak();
  11430. } else
  11431. #endif
  11432. quit(0, "No servers could be used! Exiting.");
  11433. }
  11434. } while (!pools_active);
  11435. #ifdef USE_SCRYPT
  11436. if (detect_algo == 1 && !opt_scrypt) {
  11437. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11438. opt_scrypt = true;
  11439. }
  11440. #endif
  11441. detect_algo = 0;
  11442. begin_bench:
  11443. total_mhashes_done = 0;
  11444. for (i = 0; i < total_devices; i++) {
  11445. struct cgpu_info *cgpu = devices[i];
  11446. cgpu->rolling = cgpu->total_mhashes = 0;
  11447. }
  11448. cgtime(&total_tv_start);
  11449. cgtime(&total_tv_end);
  11450. miner_started = total_tv_start;
  11451. time_t miner_start_ts = time(NULL);
  11452. if (schedstart.tm.tm_sec)
  11453. localtime_r(&miner_start_ts, &schedstart.tm);
  11454. if (schedstop.tm.tm_sec)
  11455. localtime_r(&miner_start_ts, &schedstop .tm);
  11456. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11457. // Initialise processors and threads
  11458. k = 0;
  11459. for (i = 0; i < total_devices; ++i) {
  11460. struct cgpu_info *cgpu = devices[i];
  11461. allocate_cgpu(cgpu, &k);
  11462. }
  11463. // Start threads
  11464. for (i = 0; i < total_devices; ++i) {
  11465. struct cgpu_info *cgpu = devices[i];
  11466. start_cgpu(cgpu);
  11467. }
  11468. #ifdef HAVE_OPENCL
  11469. for (i = 0; i < nDevs; i++)
  11470. pause_dynamic_threads(i);
  11471. #endif
  11472. #ifdef WANT_CPUMINE
  11473. if (opt_n_threads > 0)
  11474. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11475. opt_n_threads, algo_names[opt_algo]);
  11476. #endif
  11477. cgtime(&total_tv_start);
  11478. cgtime(&total_tv_end);
  11479. if (!opt_benchmark)
  11480. {
  11481. pthread_t submit_thread;
  11482. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11483. quit(1, "submit_work thread create failed");
  11484. }
  11485. watchpool_thr_id = 1;
  11486. thr = &control_thr[watchpool_thr_id];
  11487. /* start watchpool thread */
  11488. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11489. quit(1, "watchpool thread create failed");
  11490. pthread_detach(thr->pth);
  11491. watchdog_thr_id = 2;
  11492. thr = &control_thr[watchdog_thr_id];
  11493. /* start watchdog thread */
  11494. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11495. quit(1, "watchdog thread create failed");
  11496. pthread_detach(thr->pth);
  11497. #ifdef HAVE_OPENCL
  11498. /* Create reinit gpu thread */
  11499. gpur_thr_id = 3;
  11500. thr = &control_thr[gpur_thr_id];
  11501. thr->q = tq_new();
  11502. if (!thr->q)
  11503. quit(1, "tq_new failed for gpur_thr_id");
  11504. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11505. quit(1, "reinit_gpu thread create failed");
  11506. #endif
  11507. /* Create API socket thread */
  11508. api_thr_id = 4;
  11509. thr = &control_thr[api_thr_id];
  11510. if (thr_info_create(thr, NULL, api_thread, thr))
  11511. quit(1, "API thread create failed");
  11512. #ifdef USE_LIBMICROHTTPD
  11513. if (httpsrv_port != -1)
  11514. httpsrv_start(httpsrv_port);
  11515. #endif
  11516. #ifdef USE_LIBEVENT
  11517. if (stratumsrv_port != -1)
  11518. stratumsrv_start();
  11519. #endif
  11520. #ifdef HAVE_BFG_HOTPLUG
  11521. if (opt_hotplug)
  11522. hotplug_start();
  11523. #endif
  11524. #ifdef HAVE_CURSES
  11525. /* Create curses input thread for keyboard input. Create this last so
  11526. * that we know all threads are created since this can call kill_work
  11527. * to try and shut down ll previous threads. */
  11528. input_thr_id = 5;
  11529. thr = &control_thr[input_thr_id];
  11530. if (thr_info_create(thr, NULL, input_thread, thr))
  11531. quit(1, "input thread create failed");
  11532. pthread_detach(thr->pth);
  11533. #endif
  11534. /* Just to be sure */
  11535. if (total_control_threads != 6)
  11536. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11537. /* Once everything is set up, main() becomes the getwork scheduler */
  11538. while (42) {
  11539. int ts, max_staged = opt_queue;
  11540. struct pool *pool, *cp;
  11541. bool lagging = false;
  11542. struct curl_ent *ce;
  11543. struct work *work;
  11544. cp = current_pool();
  11545. // Generally, each processor needs a new work, and all at once during work restarts
  11546. max_staged += base_queue;
  11547. mutex_lock(stgd_lock);
  11548. ts = __total_staged();
  11549. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11550. lagging = true;
  11551. /* Wait until hash_pop tells us we need to create more work */
  11552. if (ts > max_staged) {
  11553. staged_full = true;
  11554. pthread_cond_wait(&gws_cond, stgd_lock);
  11555. ts = __total_staged();
  11556. }
  11557. mutex_unlock(stgd_lock);
  11558. if (ts > max_staged)
  11559. continue;
  11560. work = make_work();
  11561. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11562. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11563. cp->getfail_occasions++;
  11564. total_go++;
  11565. }
  11566. pool = select_pool(lagging);
  11567. retry:
  11568. if (pool->has_stratum) {
  11569. while (!pool->stratum_active || !pool->stratum_notify) {
  11570. struct pool *altpool = select_pool(true);
  11571. if (altpool == pool && pool->has_stratum)
  11572. cgsleep_ms(5000);
  11573. pool = altpool;
  11574. goto retry;
  11575. }
  11576. gen_stratum_work(pool, work);
  11577. applog(LOG_DEBUG, "Generated stratum work");
  11578. stage_work(work);
  11579. continue;
  11580. }
  11581. if (pool->last_work_copy) {
  11582. mutex_lock(&pool->last_work_lock);
  11583. struct work *last_work = pool->last_work_copy;
  11584. if (!last_work)
  11585. {}
  11586. else
  11587. if (can_roll(last_work) && should_roll(last_work)) {
  11588. struct timeval tv_now;
  11589. cgtime(&tv_now);
  11590. free_work(work);
  11591. work = make_clone(pool->last_work_copy);
  11592. mutex_unlock(&pool->last_work_lock);
  11593. roll_work(work);
  11594. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tr->tmpl, tv_now.tv_sec));
  11595. stage_work(work);
  11596. continue;
  11597. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11598. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11599. } else {
  11600. free_work(last_work);
  11601. pool->last_work_copy = NULL;
  11602. }
  11603. mutex_unlock(&pool->last_work_lock);
  11604. }
  11605. if (clone_available()) {
  11606. applog(LOG_DEBUG, "Cloned getwork work");
  11607. free_work(work);
  11608. continue;
  11609. }
  11610. if (opt_benchmark) {
  11611. get_benchmark_work(work, opt_benchmark_intense);
  11612. applog(LOG_DEBUG, "Generated benchmark work");
  11613. stage_work(work);
  11614. continue;
  11615. }
  11616. work->pool = pool;
  11617. ce = pop_curl_entry3(pool, 2);
  11618. /* obtain new work from bitcoin via JSON-RPC */
  11619. if (!get_upstream_work(work, ce->curl)) {
  11620. struct pool *next_pool;
  11621. /* Make sure the pool just hasn't stopped serving
  11622. * requests but is up as we'll keep hammering it */
  11623. push_curl_entry(ce, pool);
  11624. ++pool->seq_getfails;
  11625. pool_died(pool);
  11626. next_pool = select_pool(!opt_fail_only);
  11627. if (pool == next_pool) {
  11628. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11629. cgsleep_ms(5000);
  11630. } else {
  11631. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11632. pool = next_pool;
  11633. }
  11634. goto retry;
  11635. }
  11636. if (ts >= max_staged)
  11637. pool_tclear(pool, &pool->lagging);
  11638. if (pool_tclear(pool, &pool->idle))
  11639. pool_resus(pool);
  11640. applog(LOG_DEBUG, "Generated getwork work");
  11641. stage_work(work);
  11642. push_curl_entry(ce, pool);
  11643. }
  11644. return 0;
  11645. }