miner.c 346 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413
  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. int opt_skip_checks;
  133. bool want_per_device_stats;
  134. bool use_syslog;
  135. bool opt_quiet_work_updates = true;
  136. bool opt_quiet;
  137. bool opt_realquiet;
  138. int loginput_size;
  139. bool opt_compact;
  140. bool opt_show_procs;
  141. const int opt_cutofftemp = 95;
  142. int opt_hysteresis = 3;
  143. static int opt_retries = -1;
  144. int opt_fail_pause = 5;
  145. int opt_log_interval = 20;
  146. int opt_queue = 1;
  147. int opt_scantime = 60;
  148. int opt_expiry = 120;
  149. int opt_expiry_lp = 3600;
  150. unsigned long long global_hashrate;
  151. static bool opt_unittest = false;
  152. unsigned unittest_failures;
  153. unsigned long global_quota_gcd = 1;
  154. time_t last_getwork;
  155. #ifdef HAVE_OPENCL
  156. int opt_dynamic_interval = 7;
  157. int nDevs;
  158. int opt_g_threads = -1;
  159. #endif
  160. #ifdef USE_SCRYPT
  161. static char detect_algo = 1;
  162. bool opt_scrypt;
  163. #else
  164. static char detect_algo;
  165. #endif
  166. bool opt_restart = true;
  167. #ifdef USE_LIBMICROHTTPD
  168. #include "httpsrv.h"
  169. int httpsrv_port = -1;
  170. #endif
  171. #ifdef USE_LIBEVENT
  172. int stratumsrv_port = -1;
  173. #endif
  174. const
  175. int rescan_delay_ms = 1000;
  176. #ifdef HAVE_BFG_HOTPLUG
  177. bool opt_hotplug = 1;
  178. const
  179. int hotplug_delay_ms = 100;
  180. #else
  181. const bool opt_hotplug;
  182. #endif
  183. struct string_elist *scan_devices;
  184. static struct string_elist *opt_set_device_list;
  185. bool opt_force_dev_init;
  186. static struct string_elist *opt_devices_enabled_list;
  187. static bool opt_display_devs;
  188. int total_devices;
  189. struct cgpu_info **devices;
  190. int total_devices_new;
  191. struct cgpu_info **devices_new;
  192. bool have_opencl;
  193. int opt_n_threads = -1;
  194. int mining_threads;
  195. int base_queue;
  196. int num_processors;
  197. #ifdef HAVE_CURSES
  198. bool use_curses = true;
  199. #else
  200. bool use_curses;
  201. #endif
  202. int last_logstatusline_len;
  203. #ifdef HAVE_LIBUSB
  204. bool have_libusb;
  205. #endif
  206. static bool opt_submit_stale = true;
  207. static float opt_shares;
  208. static int opt_submit_threads = 0x40;
  209. bool opt_fail_only;
  210. int opt_fail_switch_delay = 300;
  211. bool opt_autofan;
  212. bool opt_autoengine;
  213. bool opt_noadl;
  214. char *opt_api_allow = NULL;
  215. char *opt_api_groups;
  216. char *opt_api_description = PACKAGE_STRING;
  217. int opt_api_port = 4028;
  218. bool opt_api_listen;
  219. bool opt_api_mcast;
  220. char *opt_api_mcast_addr = API_MCAST_ADDR;
  221. char *opt_api_mcast_code = API_MCAST_CODE;
  222. char *opt_api_mcast_des = "";
  223. int opt_api_mcast_port = 4028;
  224. bool opt_api_network;
  225. bool opt_delaynet;
  226. bool opt_disable_pool;
  227. bool opt_disable_client_reconnect = false;
  228. static bool no_work;
  229. bool opt_worktime;
  230. bool opt_weighed_stats;
  231. char *opt_kernel_path;
  232. char *cgminer_path;
  233. #if defined(USE_BITFORCE)
  234. bool opt_bfl_noncerange;
  235. #endif
  236. #define QUIET (opt_quiet || opt_realquiet)
  237. struct thr_info *control_thr;
  238. struct thr_info **mining_thr;
  239. static int watchpool_thr_id;
  240. static int watchdog_thr_id;
  241. #ifdef HAVE_CURSES
  242. static int input_thr_id;
  243. #endif
  244. int gpur_thr_id;
  245. static int api_thr_id;
  246. static int total_control_threads;
  247. pthread_mutex_t hash_lock;
  248. static pthread_mutex_t *stgd_lock;
  249. pthread_mutex_t console_lock;
  250. cglock_t ch_lock;
  251. static pthread_rwlock_t blk_lock;
  252. static pthread_mutex_t sshare_lock;
  253. pthread_rwlock_t netacc_lock;
  254. pthread_rwlock_t mining_thr_lock;
  255. pthread_rwlock_t devices_lock;
  256. static pthread_mutex_t lp_lock;
  257. static pthread_cond_t lp_cond;
  258. pthread_cond_t gws_cond;
  259. bool shutting_down;
  260. double total_rolling;
  261. double total_mhashes_done;
  262. static struct timeval total_tv_start, total_tv_end;
  263. static struct timeval miner_started;
  264. cglock_t control_lock;
  265. pthread_mutex_t stats_lock;
  266. static pthread_mutex_t submitting_lock;
  267. static int total_submitting;
  268. static struct work *submit_waiting;
  269. notifier_t submit_waiting_notifier;
  270. int hw_errors;
  271. int total_accepted, total_rejected;
  272. int total_getworks, total_stale, total_discarded;
  273. uint64_t total_bytes_rcvd, total_bytes_sent;
  274. double total_diff1, total_bad_diff1;
  275. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  276. static int staged_rollable;
  277. unsigned int new_blocks;
  278. unsigned int found_blocks;
  279. unsigned int local_work;
  280. unsigned int total_go, total_ro;
  281. struct pool **pools;
  282. static struct pool *currentpool = NULL;
  283. int total_pools, enabled_pools;
  284. enum pool_strategy pool_strategy = POOL_FAILOVER;
  285. int opt_rotate_period;
  286. static int total_urls, total_users, total_passes;
  287. static
  288. #ifndef HAVE_CURSES
  289. const
  290. #endif
  291. bool curses_active;
  292. #ifdef HAVE_CURSES
  293. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  294. const
  295. #endif
  296. short default_bgcolor = COLOR_BLACK;
  297. static int attr_title = A_BOLD;
  298. #endif
  299. static
  300. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  301. bool use_unicode;
  302. static
  303. bool have_unicode_degrees;
  304. static
  305. wchar_t unicode_micro = 'u';
  306. #else
  307. const bool use_unicode;
  308. static
  309. const bool have_unicode_degrees;
  310. #ifdef HAVE_CURSES
  311. static
  312. const char unicode_micro = 'u';
  313. #endif
  314. #endif
  315. #ifdef HAVE_CURSES
  316. #define U8_BAD_START "\xef\x80\x81"
  317. #define U8_BAD_END "\xef\x80\x80"
  318. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  319. /* logstart is where the log window should start */
  320. static int devcursor, logstart, logcursor;
  321. bool selecting_device;
  322. unsigned selected_device;
  323. #endif
  324. static int max_lpdigits;
  325. // current_hash was replaced with goal->current_goal_detail
  326. // current_block_id was replaced with blkchain->currentblk->block_id
  327. static char datestamp[40];
  328. static char best_share[ALLOC_H2B_SHORTV] = "0";
  329. double best_diff = 0;
  330. struct mining_goal_info *mining_goals;
  331. int active_goals = 1;
  332. int swork_id;
  333. /* For creating a hash database of stratum shares submitted that have not had
  334. * a response yet */
  335. struct stratum_share {
  336. UT_hash_handle hh;
  337. bool block;
  338. struct work *work;
  339. int id;
  340. };
  341. static struct stratum_share *stratum_shares = NULL;
  342. char *opt_socks_proxy = NULL;
  343. static const char def_conf[] = "bfgminer.conf";
  344. static bool config_loaded;
  345. static int include_count;
  346. #define JSON_INCLUDE_CONF "include"
  347. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  348. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  349. #define JSON_MAX_DEPTH 10
  350. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  351. char *cmd_idle, *cmd_sick, *cmd_dead;
  352. #if defined(unix) || defined(__APPLE__)
  353. static char *opt_stderr_cmd = NULL;
  354. static int forkpid;
  355. #endif // defined(unix)
  356. #ifdef HAVE_CHROOT
  357. char *chroot_dir;
  358. #endif
  359. #ifdef HAVE_PWD_H
  360. char *opt_setuid;
  361. #endif
  362. struct sigaction termhandler, inthandler;
  363. struct thread_q *getq;
  364. static int total_work;
  365. static bool staged_full;
  366. struct work *staged_work = NULL;
  367. struct schedtime {
  368. bool enable;
  369. struct tm tm;
  370. };
  371. struct schedtime schedstart;
  372. struct schedtime schedstop;
  373. bool sched_paused;
  374. static bool time_before(struct tm *tm1, struct tm *tm2)
  375. {
  376. if (tm1->tm_hour < tm2->tm_hour)
  377. return true;
  378. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  379. return true;
  380. return false;
  381. }
  382. static bool should_run(void)
  383. {
  384. struct tm tm;
  385. time_t tt;
  386. bool within_range;
  387. if (!schedstart.enable && !schedstop.enable)
  388. return true;
  389. tt = time(NULL);
  390. localtime_r(&tt, &tm);
  391. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  392. if (time_before(&schedstop.tm, &schedstart.tm))
  393. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  394. else
  395. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  396. if (within_range && !schedstop.enable)
  397. /* This is a once off event with no stop time set */
  398. schedstart.enable = false;
  399. return within_range;
  400. }
  401. void get_datestamp(char *f, size_t fsiz, time_t tt)
  402. {
  403. struct tm _tm;
  404. struct tm *tm = &_tm;
  405. if (tt == INVALID_TIMESTAMP)
  406. tt = time(NULL);
  407. localtime_r(&tt, tm);
  408. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  409. tm->tm_year + 1900,
  410. tm->tm_mon + 1,
  411. tm->tm_mday,
  412. tm->tm_hour,
  413. tm->tm_min,
  414. tm->tm_sec);
  415. }
  416. static
  417. void get_timestamp(char *f, size_t fsiz, time_t tt)
  418. {
  419. struct tm _tm;
  420. struct tm *tm = &_tm;
  421. localtime_r(&tt, tm);
  422. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  423. tm->tm_hour,
  424. tm->tm_min,
  425. tm->tm_sec);
  426. }
  427. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  428. static char exit_buf[512];
  429. static void applog_and_exit(const char *fmt, ...)
  430. {
  431. va_list ap;
  432. va_start(ap, fmt);
  433. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  434. va_end(ap);
  435. _applog(LOG_ERR, exit_buf);
  436. exit(1);
  437. }
  438. char *devpath_to_devid(const char *devpath)
  439. {
  440. #ifndef WIN32
  441. if (devpath[0] != '/')
  442. return NULL;
  443. struct stat my_stat;
  444. if (stat(devpath, &my_stat))
  445. return NULL;
  446. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  447. memcpy(devs, "dev_t:", 6);
  448. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  449. #else
  450. if (!strncmp(devpath, "\\\\.\\", 4))
  451. devpath += 4;
  452. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  453. return NULL;
  454. devpath += 3;
  455. char *p;
  456. strtol(devpath, &p, 10);
  457. if (p[0])
  458. return NULL;
  459. const int sz = (p - devpath);
  460. char *devs = malloc(4 + sz + 1);
  461. sprintf(devs, "com:%s", devpath);
  462. #endif
  463. return devs;
  464. }
  465. static
  466. bool devpaths_match(const char * const ap, const char * const bp)
  467. {
  468. char * const a = devpath_to_devid(ap);
  469. if (!a)
  470. return false;
  471. char * const b = devpath_to_devid(bp);
  472. bool rv = false;
  473. if (b)
  474. {
  475. rv = !strcmp(a, b);
  476. free(b);
  477. }
  478. free(a);
  479. return rv;
  480. }
  481. static
  482. int proc_letter_to_number(const char *s, const char ** const rem)
  483. {
  484. int n = 0, c;
  485. for ( ; s[0]; ++s)
  486. {
  487. if (unlikely(n > INT_MAX / 26))
  488. break;
  489. c = tolower(s[0]) - 'a';
  490. if (unlikely(c < 0 || c > 25))
  491. break;
  492. if (unlikely(INT_MAX - c < n))
  493. break;
  494. n = (n * 26) + c;
  495. }
  496. *rem = s;
  497. return n;
  498. }
  499. static
  500. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  501. {
  502. // all - matches anything
  503. // d0 - matches all processors of device 0
  504. // d0-3 - matches all processors of device 0, 1, 2, or 3
  505. // d0a - matches first processor of device 0
  506. // 0 - matches processor 0
  507. // 0-4 - matches processors 0, 1, 2, 3, or 4
  508. // ___ - matches all processors on all devices using driver/name ___
  509. // ___0 - matches all processors of 0th device using driver/name ___
  510. // ___0a - matches first processor of 0th device using driver/name ___
  511. // @* - matches device with serial or path *
  512. // @*@a - matches first processor of device with serial or path *
  513. // ___@* - matches device with serial or path * using driver/name ___
  514. if (!strcasecmp(pattern, "all"))
  515. return true;
  516. const struct device_drv * const drv = cgpu->drv;
  517. const char *p = pattern, *p2;
  518. size_t L;
  519. int n, i, c = -1;
  520. int n2;
  521. int proc_first = -1, proc_last = -1;
  522. struct cgpu_info *device;
  523. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  524. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  525. // dname or name
  526. p = &pattern[L];
  527. else
  528. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  529. // d#
  530. ++p;
  531. else
  532. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  533. // # or @
  534. {}
  535. else
  536. return false;
  537. L = p - pattern;
  538. while (isspace(p[0]))
  539. ++p;
  540. if (p[0] == '@')
  541. {
  542. // Serial/path
  543. const char * const ser = &p[1];
  544. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  545. {}
  546. p2 = (p[0] == '@') ? &p[1] : p;
  547. const size_t serlen = (p - ser);
  548. p = "";
  549. n = n2 = 0;
  550. const char * const devpath = cgpu->device_path ?: "";
  551. const char * const devser = cgpu->dev_serial ?: "";
  552. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  553. {} // Match
  554. else
  555. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  556. {} // Match
  557. else
  558. {
  559. char devpath2[serlen + 1];
  560. memcpy(devpath2, ser, serlen);
  561. devpath2[serlen] = '\0';
  562. if (!devpaths_match(devpath, ser))
  563. return false;
  564. }
  565. }
  566. else
  567. {
  568. if (isdigit(p[0]))
  569. n = strtol(p, (void*)&p2, 0);
  570. else
  571. {
  572. n = 0;
  573. p2 = p;
  574. }
  575. if (p2[0] == '-')
  576. {
  577. ++p2;
  578. if (p2[0] && isdigit(p2[0]))
  579. n2 = strtol(p2, (void*)&p2, 0);
  580. else
  581. n2 = INT_MAX;
  582. }
  583. else
  584. n2 = n;
  585. if (p == pattern)
  586. {
  587. if (!p[0])
  588. return true;
  589. if (p2 && p2[0])
  590. goto invsyntax;
  591. for (i = n; i <= n2; ++i)
  592. {
  593. if (i >= total_devices)
  594. break;
  595. if (cgpu == devices[i])
  596. return true;
  597. }
  598. return false;
  599. }
  600. }
  601. if (p2[0])
  602. {
  603. proc_first = proc_letter_to_number(&p2[0], &p2);
  604. if (p2[0] == '-')
  605. {
  606. ++p2;
  607. if (p2[0])
  608. proc_last = proc_letter_to_number(p2, &p2);
  609. else
  610. proc_last = INT_MAX;
  611. }
  612. else
  613. proc_last = proc_first;
  614. if (p2[0])
  615. goto invsyntax;
  616. }
  617. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  618. {
  619. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  620. (!L) ||
  621. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  622. {} // Matched name or dname
  623. else
  624. return false;
  625. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  626. return false;
  627. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  628. return false;
  629. return true;
  630. }
  631. // d#
  632. c = -1;
  633. for (i = 0; ; ++i)
  634. {
  635. if (i == total_devices)
  636. return false;
  637. if (devices[i]->device != devices[i])
  638. continue;
  639. ++c;
  640. if (c < n)
  641. continue;
  642. if (c > n2)
  643. break;
  644. for (device = devices[i]; device; device = device->next_proc)
  645. {
  646. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  647. continue;
  648. if (device == cgpu)
  649. return true;
  650. }
  651. }
  652. return false;
  653. invsyntax:
  654. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  655. return false;
  656. }
  657. #define TEST_CGPU_MATCH(pattern) \
  658. if (!cgpu_match(pattern, &cgpu)) \
  659. { \
  660. ++unittest_failures; \
  661. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  662. } \
  663. // END TEST_CGPU_MATCH
  664. #define TEST_CGPU_NOMATCH(pattern) \
  665. if (cgpu_match(pattern, &cgpu)) \
  666. { \
  667. ++unittest_failures; \
  668. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  669. } \
  670. // END TEST_CGPU_MATCH
  671. static __maybe_unused
  672. void test_cgpu_match()
  673. {
  674. struct device_drv drv = {
  675. .dname = "test",
  676. .name = "TST",
  677. };
  678. struct cgpu_info cgpu = {
  679. .drv = &drv,
  680. .device = &cgpu,
  681. .device_id = 1,
  682. .proc_id = 1,
  683. .proc_repr = "TST 1b",
  684. }, cgpu0a = {
  685. .drv = &drv,
  686. .device = &cgpu0a,
  687. .device_id = 0,
  688. .proc_id = 0,
  689. .proc_repr = "TST 0a",
  690. }, cgpu1a = {
  691. .drv = &drv,
  692. .device = &cgpu0a,
  693. .device_id = 1,
  694. .proc_id = 0,
  695. .proc_repr = "TST 1a",
  696. };
  697. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  698. devices = devices_list;
  699. total_devices = 3;
  700. TEST_CGPU_MATCH("all")
  701. TEST_CGPU_MATCH("d1")
  702. TEST_CGPU_NOMATCH("d2")
  703. TEST_CGPU_MATCH("d0-5")
  704. TEST_CGPU_NOMATCH("d0-0")
  705. TEST_CGPU_NOMATCH("d2-5")
  706. TEST_CGPU_MATCH("d-1")
  707. TEST_CGPU_MATCH("d1-")
  708. TEST_CGPU_NOMATCH("d-0")
  709. TEST_CGPU_NOMATCH("d2-")
  710. TEST_CGPU_MATCH("2")
  711. TEST_CGPU_NOMATCH("3")
  712. TEST_CGPU_MATCH("1-2")
  713. TEST_CGPU_MATCH("2-3")
  714. TEST_CGPU_NOMATCH("1-1")
  715. TEST_CGPU_NOMATCH("3-4")
  716. TEST_CGPU_MATCH("TST")
  717. TEST_CGPU_MATCH("test")
  718. TEST_CGPU_MATCH("tst")
  719. TEST_CGPU_MATCH("TEST")
  720. TEST_CGPU_NOMATCH("TSF")
  721. TEST_CGPU_NOMATCH("TS")
  722. TEST_CGPU_NOMATCH("TSTF")
  723. TEST_CGPU_MATCH("TST1")
  724. TEST_CGPU_MATCH("test1")
  725. TEST_CGPU_MATCH("TST0-1")
  726. TEST_CGPU_MATCH("TST 1")
  727. TEST_CGPU_MATCH("TST 1-2")
  728. TEST_CGPU_MATCH("TEST 1-2")
  729. TEST_CGPU_NOMATCH("TST2")
  730. TEST_CGPU_NOMATCH("TST2-3")
  731. TEST_CGPU_NOMATCH("TST0-0")
  732. TEST_CGPU_MATCH("TST1b")
  733. TEST_CGPU_MATCH("tst1b")
  734. TEST_CGPU_NOMATCH("TST1c")
  735. TEST_CGPU_NOMATCH("TST1bb")
  736. TEST_CGPU_MATCH("TST0-1b")
  737. TEST_CGPU_NOMATCH("TST0-1c")
  738. TEST_CGPU_MATCH("TST1a-d")
  739. TEST_CGPU_NOMATCH("TST1a-a")
  740. TEST_CGPU_NOMATCH("TST1-a")
  741. TEST_CGPU_NOMATCH("TST1c-z")
  742. TEST_CGPU_NOMATCH("TST1c-")
  743. TEST_CGPU_MATCH("@")
  744. TEST_CGPU_NOMATCH("@abc")
  745. TEST_CGPU_MATCH("@@b")
  746. TEST_CGPU_NOMATCH("@@c")
  747. TEST_CGPU_MATCH("TST@")
  748. TEST_CGPU_NOMATCH("TST@abc")
  749. TEST_CGPU_MATCH("TST@@b")
  750. TEST_CGPU_NOMATCH("TST@@c")
  751. TEST_CGPU_MATCH("TST@@b-f")
  752. TEST_CGPU_NOMATCH("TST@@c-f")
  753. TEST_CGPU_NOMATCH("TST@@-a")
  754. cgpu.device_path = "/dev/test";
  755. cgpu.dev_serial = "testy";
  756. TEST_CGPU_MATCH("TST@/dev/test")
  757. TEST_CGPU_MATCH("TST@testy")
  758. TEST_CGPU_NOMATCH("TST@")
  759. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  760. TEST_CGPU_NOMATCH("TST@testy3@b")
  761. TEST_CGPU_MATCH("TST@/dev/test@b")
  762. TEST_CGPU_MATCH("TST@testy@b")
  763. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  764. TEST_CGPU_NOMATCH("TST@testy@c")
  765. cgpu.device_path = "usb:000:999";
  766. TEST_CGPU_MATCH("TST@usb:000:999")
  767. drv.dname = "test7";
  768. TEST_CGPU_MATCH("test7")
  769. TEST_CGPU_MATCH("TEST7")
  770. TEST_CGPU_NOMATCH("test&")
  771. TEST_CGPU_MATCH("test7 1-2")
  772. TEST_CGPU_MATCH("test7@testy@b")
  773. }
  774. static
  775. int cgpu_search(const char * const pattern, const int first)
  776. {
  777. int i;
  778. struct cgpu_info *cgpu;
  779. #define CHECK_CGPU_SEARCH do{ \
  780. cgpu = get_devices(i); \
  781. if (cgpu_match(pattern, cgpu)) \
  782. return i; \
  783. }while(0)
  784. for (i = first; i < total_devices; ++i)
  785. CHECK_CGPU_SEARCH;
  786. for (i = 0; i < first; ++i)
  787. CHECK_CGPU_SEARCH;
  788. #undef CHECK_CGPU_SEARCH
  789. return -1;
  790. }
  791. static pthread_mutex_t sharelog_lock;
  792. static FILE *sharelog_file = NULL;
  793. struct thr_info *get_thread(int thr_id)
  794. {
  795. struct thr_info *thr;
  796. rd_lock(&mining_thr_lock);
  797. thr = mining_thr[thr_id];
  798. rd_unlock(&mining_thr_lock);
  799. return thr;
  800. }
  801. static struct cgpu_info *get_thr_cgpu(int thr_id)
  802. {
  803. struct thr_info *thr = get_thread(thr_id);
  804. return thr->cgpu;
  805. }
  806. struct cgpu_info *get_devices(int id)
  807. {
  808. struct cgpu_info *cgpu;
  809. rd_lock(&devices_lock);
  810. cgpu = devices[id];
  811. rd_unlock(&devices_lock);
  812. return cgpu;
  813. }
  814. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  815. static FILE *noncelog_file = NULL;
  816. static
  817. void noncelog(const struct work * const work)
  818. {
  819. const int thr_id = work->thr_id;
  820. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  821. char buf[0x200], hash[65], data[161], midstate[65];
  822. int rv;
  823. size_t ret;
  824. bin2hex(hash, work->hash, 32);
  825. bin2hex(data, work->data, 80);
  826. bin2hex(midstate, work->midstate, 32);
  827. // timestamp,proc,hash,data,midstate
  828. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  829. (unsigned long)time(NULL), proc->proc_repr_ns,
  830. hash, data, midstate);
  831. if (unlikely(rv < 1))
  832. {
  833. applog(LOG_ERR, "noncelog printf error");
  834. return;
  835. }
  836. mutex_lock(&noncelog_lock);
  837. ret = fwrite(buf, rv, 1, noncelog_file);
  838. fflush(noncelog_file);
  839. mutex_unlock(&noncelog_lock);
  840. if (ret != 1)
  841. applog(LOG_ERR, "noncelog fwrite error");
  842. }
  843. static void sharelog(const char*disposition, const struct work*work)
  844. {
  845. char target[(sizeof(work->target) * 2) + 1];
  846. char hash[(sizeof(work->hash) * 2) + 1];
  847. char data[(sizeof(work->data) * 2) + 1];
  848. struct cgpu_info *cgpu;
  849. unsigned long int t;
  850. struct pool *pool;
  851. int thr_id, rv;
  852. char s[1024];
  853. size_t ret;
  854. if (!sharelog_file)
  855. return;
  856. thr_id = work->thr_id;
  857. cgpu = get_thr_cgpu(thr_id);
  858. pool = work->pool;
  859. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  860. bin2hex(target, work->target, sizeof(work->target));
  861. bin2hex(hash, work->hash, sizeof(work->hash));
  862. bin2hex(data, work->data, sizeof(work->data));
  863. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  864. 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);
  865. if (rv >= (int)(sizeof(s)))
  866. s[sizeof(s) - 1] = '\0';
  867. else if (rv < 0) {
  868. applog(LOG_ERR, "sharelog printf error");
  869. return;
  870. }
  871. mutex_lock(&sharelog_lock);
  872. ret = fwrite(s, rv, 1, sharelog_file);
  873. fflush(sharelog_file);
  874. mutex_unlock(&sharelog_lock);
  875. if (ret != 1)
  876. applog(LOG_ERR, "sharelog fwrite error");
  877. }
  878. #ifdef HAVE_CURSES
  879. static void switch_logsize(void);
  880. #endif
  881. static
  882. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  883. {
  884. // default always goes first
  885. if (a->is_default)
  886. return -1;
  887. if (b->is_default)
  888. return 1;
  889. return strcmp(a->name, b->name);
  890. }
  891. static
  892. void blkchain_init_block(struct blockchain_info * const blkchain)
  893. {
  894. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  895. memset(dummy_block->prevblkhash, 0, 0x20);
  896. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  897. blkchain->currentblk = dummy_block;
  898. }
  899. struct mining_goal_info *get_mining_goal(const char * const name)
  900. {
  901. static unsigned next_goal_id;
  902. struct mining_goal_info *goal;
  903. HASH_FIND_STR(mining_goals, name, goal);
  904. if (!goal)
  905. {
  906. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  907. goal = (void*)(&blkchain[1]);
  908. *blkchain = (struct blockchain_info){
  909. .currentblk = NULL,
  910. };
  911. blkchain_init_block(blkchain);
  912. *goal = (struct mining_goal_info){
  913. .id = next_goal_id++,
  914. .name = strdup(name),
  915. .is_default = !strcmp(name, "default"),
  916. .blkchain = blkchain,
  917. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  918. };
  919. HASH_ADD_STR(mining_goals, name, goal);
  920. HASH_SORT(mining_goals, mining_goals_name_cmp);
  921. #ifdef HAVE_CURSES
  922. devcursor = 7 + active_goals;
  923. switch_logsize();
  924. #endif
  925. }
  926. return goal;
  927. }
  928. void mining_goal_reset(struct mining_goal_info * const goal)
  929. {
  930. struct blockchain_info * const blkchain = goal->blkchain;
  931. struct block_info *blkinfo, *tmpblkinfo;
  932. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  933. {
  934. HASH_DEL(blkchain->blocks, blkinfo);
  935. free(blkinfo);
  936. }
  937. blkchain_init_block(blkchain);
  938. }
  939. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  940. /* Adjust all the pools' quota to the greatest common denominator after a pool
  941. * has been added or the quotas changed. */
  942. void adjust_quota_gcd(void)
  943. {
  944. unsigned long gcd, lowest_quota = ~0UL, quota;
  945. struct pool *pool;
  946. int i;
  947. for (i = 0; i < total_pools; i++) {
  948. pool = pools[i];
  949. quota = pool->quota;
  950. if (!quota)
  951. continue;
  952. if (quota < lowest_quota)
  953. lowest_quota = quota;
  954. }
  955. if (likely(lowest_quota < ~0UL)) {
  956. gcd = lowest_quota;
  957. for (i = 0; i < total_pools; i++) {
  958. pool = pools[i];
  959. quota = pool->quota;
  960. if (!quota)
  961. continue;
  962. while (quota % gcd)
  963. gcd--;
  964. }
  965. } else
  966. gcd = 1;
  967. for (i = 0; i < total_pools; i++) {
  968. pool = pools[i];
  969. pool->quota_used *= global_quota_gcd;
  970. pool->quota_used /= gcd;
  971. pool->quota_gcd = pool->quota / gcd;
  972. }
  973. global_quota_gcd = gcd;
  974. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  975. }
  976. /* Return value is ignored if not called from add_pool_details */
  977. struct pool *add_pool(void)
  978. {
  979. struct pool *pool;
  980. pool = calloc(sizeof(struct pool), 1);
  981. if (!pool)
  982. quit(1, "Failed to malloc pool in add_pool");
  983. pool->pool_no = pool->prio = total_pools;
  984. mutex_init(&pool->last_work_lock);
  985. mutex_init(&pool->pool_lock);
  986. mutex_init(&pool->pool_test_lock);
  987. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  988. quit(1, "Failed to pthread_cond_init in add_pool");
  989. cglock_init(&pool->data_lock);
  990. mutex_init(&pool->stratum_lock);
  991. timer_unset(&pool->swork.tv_transparency);
  992. pool->swork.pool = pool;
  993. pool->goal = get_mining_goal("default");
  994. pool->idle = true;
  995. /* Make sure the pool doesn't think we've been idle since time 0 */
  996. pool->tv_idle.tv_sec = ~0UL;
  997. cgtime(&pool->cgminer_stats.start_tv);
  998. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  999. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1000. pool->rpc_proxy = NULL;
  1001. pool->quota = 1;
  1002. pool->sock = INVSOCK;
  1003. pool->lp_socket = CURL_SOCKET_BAD;
  1004. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1005. pools[total_pools++] = pool;
  1006. if (opt_benchmark)
  1007. {
  1008. // Immediately remove it
  1009. remove_pool(pool);
  1010. return pool;
  1011. }
  1012. adjust_quota_gcd();
  1013. if (!currentpool)
  1014. currentpool = pool;
  1015. enable_pool(pool);
  1016. return pool;
  1017. }
  1018. static
  1019. void pool_set_uri(struct pool * const pool, char * const uri)
  1020. {
  1021. pool->rpc_url = uri;
  1022. #if BLKMAKER_VERSION > 1
  1023. if (uri_get_param_bool(uri, "getcbaddr", false))
  1024. have_at_least_one_getcbaddr = true;
  1025. #endif
  1026. }
  1027. /* Pool variant of test and set */
  1028. static bool pool_tset(struct pool *pool, bool *var)
  1029. {
  1030. bool ret;
  1031. mutex_lock(&pool->pool_lock);
  1032. ret = *var;
  1033. *var = true;
  1034. mutex_unlock(&pool->pool_lock);
  1035. return ret;
  1036. }
  1037. bool pool_tclear(struct pool *pool, bool *var)
  1038. {
  1039. bool ret;
  1040. mutex_lock(&pool->pool_lock);
  1041. ret = *var;
  1042. *var = false;
  1043. mutex_unlock(&pool->pool_lock);
  1044. return ret;
  1045. }
  1046. struct pool *current_pool(void)
  1047. {
  1048. struct pool *pool;
  1049. cg_rlock(&control_lock);
  1050. pool = currentpool;
  1051. cg_runlock(&control_lock);
  1052. return pool;
  1053. }
  1054. static
  1055. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1056. {
  1057. return opt_set_bool(b);
  1058. }
  1059. char *set_int_range(const char *arg, int *i, int min, int max)
  1060. {
  1061. char *err = opt_set_intval(arg, i);
  1062. if (err)
  1063. return err;
  1064. if (*i < min || *i > max)
  1065. return "Value out of range";
  1066. return NULL;
  1067. }
  1068. static char *set_int_0_to_9999(const char *arg, int *i)
  1069. {
  1070. return set_int_range(arg, i, 0, 9999);
  1071. }
  1072. static char *set_int_1_to_65535(const char *arg, int *i)
  1073. {
  1074. return set_int_range(arg, i, 1, 65535);
  1075. }
  1076. static char *set_int_0_to_10(const char *arg, int *i)
  1077. {
  1078. return set_int_range(arg, i, 0, 10);
  1079. }
  1080. static char *set_int_1_to_10(const char *arg, int *i)
  1081. {
  1082. return set_int_range(arg, i, 1, 10);
  1083. }
  1084. char *set_strdup(const char *arg, char **p)
  1085. {
  1086. *p = strdup((char *)arg);
  1087. return NULL;
  1088. }
  1089. #if BLKMAKER_VERSION > 1
  1090. static
  1091. char *set_b58addr(const char * const arg, bytes_t * const b)
  1092. {
  1093. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1094. if (!scriptsz)
  1095. return "Invalid address";
  1096. char *script = malloc(scriptsz);
  1097. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1098. free(script);
  1099. return "Failed to convert address to script";
  1100. }
  1101. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1102. return NULL;
  1103. }
  1104. #endif
  1105. static
  1106. char *set_quit_summary(const char * const arg)
  1107. {
  1108. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1109. opt_quit_summary = BQS_NONE;
  1110. else
  1111. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1112. opt_quit_summary = BQS_DEVS;
  1113. else
  1114. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1115. opt_quit_summary = BQS_PROCS;
  1116. else
  1117. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1118. opt_quit_summary = BQS_DETAILED;
  1119. else
  1120. return "Quit summary must be one of none/devs/procs/detailed";
  1121. return NULL;
  1122. }
  1123. static void pdiff_target_leadzero(void *, double);
  1124. char *set_request_diff(const char *arg, float *p)
  1125. {
  1126. unsigned char target[32];
  1127. char *e = opt_set_floatval(arg, p);
  1128. if (e)
  1129. return e;
  1130. request_bdiff = (double)*p * 0.9999847412109375;
  1131. pdiff_target_leadzero(target, *p);
  1132. request_target_str = malloc(65);
  1133. bin2hex(request_target_str, target, 32);
  1134. return NULL;
  1135. }
  1136. #ifdef NEED_BFG_LOWL_VCOM
  1137. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1138. #ifdef WIN32
  1139. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1140. {
  1141. char dev[PATH_MAX];
  1142. char *devp = dev;
  1143. size_t bufLen = 0x100;
  1144. tryagain: ;
  1145. char buf[bufLen];
  1146. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1147. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1148. bufLen *= 2;
  1149. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1150. goto tryagain;
  1151. }
  1152. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1153. }
  1154. size_t tLen;
  1155. memcpy(devp, "\\\\.\\", 4);
  1156. devp = &devp[4];
  1157. for (char *t = buf; *t; t += tLen) {
  1158. tLen = strlen(t) + 1;
  1159. if (strncmp("COM", t, 3))
  1160. continue;
  1161. memcpy(devp, t, tLen);
  1162. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1163. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1164. }
  1165. }
  1166. #else
  1167. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1168. {
  1169. char dev[PATH_MAX];
  1170. char *devp = dev;
  1171. DIR *D;
  1172. struct dirent *de;
  1173. const char devdir[] = "/dev";
  1174. const size_t devdirlen = sizeof(devdir) - 1;
  1175. char *devpath = devp;
  1176. char *devfile = devpath + devdirlen + 1;
  1177. D = opendir(devdir);
  1178. if (!D)
  1179. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1180. memcpy(devpath, devdir, devdirlen);
  1181. devpath[devdirlen] = '/';
  1182. while ( (de = readdir(D)) ) {
  1183. if (!strncmp(de->d_name, "cu.", 3)
  1184. //don't probe Bluetooth devices - causes bus errors and segfaults
  1185. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1186. goto trydev;
  1187. if (strncmp(de->d_name, "tty", 3))
  1188. continue;
  1189. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1190. continue;
  1191. trydev:
  1192. strcpy(devfile, de->d_name);
  1193. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1194. }
  1195. closedir(D);
  1196. }
  1197. #endif
  1198. #endif
  1199. static char *add_serial(const char *arg)
  1200. {
  1201. string_elist_add(arg, &scan_devices);
  1202. return NULL;
  1203. }
  1204. static
  1205. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1206. {
  1207. string_elist_add(arg, elist);
  1208. return NULL;
  1209. }
  1210. bool get_intrange(const char *arg, int *val1, int *val2)
  1211. {
  1212. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1213. char *p, *p2;
  1214. *val1 = strtol(arg, &p, 0);
  1215. if (arg == p)
  1216. // Zero-length ending number, invalid
  1217. return false;
  1218. while (true)
  1219. {
  1220. if (!p[0])
  1221. {
  1222. *val2 = *val1;
  1223. return true;
  1224. }
  1225. if (p[0] == '-')
  1226. break;
  1227. if (!isspace(p[0]))
  1228. // Garbage, invalid
  1229. return false;
  1230. ++p;
  1231. }
  1232. p2 = &p[1];
  1233. *val2 = strtol(p2, &p, 0);
  1234. if (p2 == p)
  1235. // Zero-length ending number, invalid
  1236. return false;
  1237. while (true)
  1238. {
  1239. if (!p[0])
  1240. return true;
  1241. if (!isspace(p[0]))
  1242. // Garbage, invalid
  1243. return false;
  1244. ++p;
  1245. }
  1246. }
  1247. static
  1248. void _test_intrange(const char *s, const int v[2])
  1249. {
  1250. int a[2];
  1251. if (!get_intrange(s, &a[0], &a[1]))
  1252. {
  1253. ++unittest_failures;
  1254. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1255. }
  1256. for (int i = 0; i < 2; ++i)
  1257. if (unlikely(a[i] != v[i]))
  1258. {
  1259. ++unittest_failures;
  1260. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1261. }
  1262. }
  1263. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1264. static
  1265. void _test_intrange_fail(const char *s)
  1266. {
  1267. int a[2];
  1268. if (get_intrange(s, &a[0], &a[1]))
  1269. {
  1270. ++unittest_failures;
  1271. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1272. }
  1273. }
  1274. static
  1275. void test_intrange()
  1276. {
  1277. _test_intrange("-1--2", -1, -2);
  1278. _test_intrange("-1-2", -1, 2);
  1279. _test_intrange("1--2", 1, -2);
  1280. _test_intrange("1-2", 1, 2);
  1281. _test_intrange("111-222", 111, 222);
  1282. _test_intrange(" 11 - 22 ", 11, 22);
  1283. _test_intrange("+11-+22", 11, 22);
  1284. _test_intrange("-1", -1, -1);
  1285. _test_intrange_fail("all");
  1286. _test_intrange_fail("1-");
  1287. _test_intrange_fail("");
  1288. _test_intrange_fail("1-54x");
  1289. }
  1290. static char *set_devices(char *arg)
  1291. {
  1292. if (*arg) {
  1293. if (*arg == '?') {
  1294. opt_display_devs = true;
  1295. return NULL;
  1296. }
  1297. } else
  1298. return "Invalid device parameters";
  1299. string_elist_add(arg, &opt_devices_enabled_list);
  1300. return NULL;
  1301. }
  1302. static char *set_balance(enum pool_strategy *strategy)
  1303. {
  1304. *strategy = POOL_BALANCE;
  1305. return NULL;
  1306. }
  1307. static char *set_loadbalance(enum pool_strategy *strategy)
  1308. {
  1309. *strategy = POOL_LOADBALANCE;
  1310. return NULL;
  1311. }
  1312. static char *set_rotate(const char *arg, int *i)
  1313. {
  1314. pool_strategy = POOL_ROTATE;
  1315. return set_int_range(arg, i, 0, 9999);
  1316. }
  1317. static char *set_rr(enum pool_strategy *strategy)
  1318. {
  1319. *strategy = POOL_ROUNDROBIN;
  1320. return NULL;
  1321. }
  1322. static
  1323. char *set_benchmark_intense()
  1324. {
  1325. opt_benchmark = true;
  1326. opt_benchmark_intense = true;
  1327. return NULL;
  1328. }
  1329. /* Detect that url is for a stratum protocol either via the presence of
  1330. * stratum+tcp or by detecting a stratum server response */
  1331. bool detect_stratum(struct pool *pool, char *url)
  1332. {
  1333. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1334. return false;
  1335. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1336. pool_set_uri(pool, strdup(url));
  1337. pool->has_stratum = true;
  1338. pool->stratum_url = pool->sockaddr_url;
  1339. return true;
  1340. }
  1341. return false;
  1342. }
  1343. static struct pool *add_url(void)
  1344. {
  1345. total_urls++;
  1346. if (total_urls > total_pools)
  1347. add_pool();
  1348. return pools[total_urls - 1];
  1349. }
  1350. static void setup_url(struct pool *pool, char *arg)
  1351. {
  1352. if (detect_stratum(pool, arg))
  1353. return;
  1354. opt_set_charp(arg, &pool->rpc_url);
  1355. if (strncmp(arg, "http://", 7) &&
  1356. strncmp(arg, "https://", 8)) {
  1357. const size_t L = strlen(arg);
  1358. char *httpinput;
  1359. httpinput = malloc(8 + L);
  1360. if (!httpinput)
  1361. quit(1, "Failed to malloc httpinput");
  1362. sprintf(httpinput, "http://%s", arg);
  1363. pool_set_uri(pool, httpinput);
  1364. }
  1365. }
  1366. static char *set_url(char *arg)
  1367. {
  1368. struct pool *pool = add_url();
  1369. setup_url(pool, arg);
  1370. return NULL;
  1371. }
  1372. static char *set_quota(char *arg)
  1373. {
  1374. char *semicolon = strchr(arg, ';'), *url;
  1375. int len, qlen, quota;
  1376. struct pool *pool;
  1377. if (!semicolon)
  1378. return "No semicolon separated quota;URL pair found";
  1379. len = strlen(arg);
  1380. *semicolon = '\0';
  1381. qlen = strlen(arg);
  1382. if (!qlen)
  1383. return "No parameter for quota found";
  1384. len -= qlen + 1;
  1385. if (len < 1)
  1386. return "No parameter for URL found";
  1387. quota = atoi(arg);
  1388. if (quota < 0)
  1389. return "Invalid negative parameter for quota set";
  1390. url = arg + qlen + 1;
  1391. pool = add_url();
  1392. setup_url(pool, url);
  1393. pool->quota = quota;
  1394. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1395. adjust_quota_gcd();
  1396. return NULL;
  1397. }
  1398. static char *set_user(const char *arg)
  1399. {
  1400. struct pool *pool;
  1401. total_users++;
  1402. if (total_users > total_pools)
  1403. add_pool();
  1404. pool = pools[total_users - 1];
  1405. opt_set_charp(arg, &pool->rpc_user);
  1406. return NULL;
  1407. }
  1408. static char *set_pass(const char *arg)
  1409. {
  1410. struct pool *pool;
  1411. total_passes++;
  1412. if (total_passes > total_pools)
  1413. add_pool();
  1414. pool = pools[total_passes - 1];
  1415. opt_set_charp(arg, &pool->rpc_pass);
  1416. return NULL;
  1417. }
  1418. static char *set_userpass(const char *arg)
  1419. {
  1420. struct pool *pool;
  1421. char *updup;
  1422. if (total_users != total_passes)
  1423. return "User + pass options must be balanced before userpass";
  1424. ++total_users;
  1425. ++total_passes;
  1426. if (total_users > total_pools)
  1427. add_pool();
  1428. pool = pools[total_users - 1];
  1429. updup = strdup(arg);
  1430. opt_set_charp(arg, &pool->rpc_userpass);
  1431. pool->rpc_user = updup;
  1432. pool->rpc_pass = strchr(updup, ':');
  1433. if (pool->rpc_pass)
  1434. pool->rpc_pass++[0] = '\0';
  1435. else
  1436. pool->rpc_pass = &updup[strlen(updup)];
  1437. return NULL;
  1438. }
  1439. static char *set_cbcaddr(char *arg)
  1440. {
  1441. struct pool *pool;
  1442. char *p, *addr;
  1443. bytes_t target_script = BYTES_INIT;
  1444. if (!total_pools)
  1445. return "Define pool first, then the --coinbase-check-addr list";
  1446. pool = pools[total_pools - 1];
  1447. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1448. * need support it later, but now leave the code just so.
  1449. *
  1450. * Regarding details of address prefix 'x', check the below URL:
  1451. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1452. */
  1453. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1454. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1455. {
  1456. struct bytes_hashtbl *ah;
  1457. if (set_b58addr(addr, &target_script))
  1458. /* No bother to free memory since we are going to exit anyway */
  1459. return "Invalid address in --coinbase-check-address list";
  1460. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1461. if (!ah)
  1462. {
  1463. /* Note: for the below allocated memory we have good way to release its memory
  1464. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1465. * get called.
  1466. *
  1467. * We just hope the remove_pool() would not be called many many times during
  1468. * the whole running life of this program.
  1469. */
  1470. ah = malloc(sizeof(*ah));
  1471. bytes_init(&ah->b);
  1472. bytes_assimilate(&ah->b, &target_script);
  1473. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1474. }
  1475. }
  1476. bytes_free(&target_script);
  1477. return NULL;
  1478. }
  1479. static char *set_cbctotal(const char *arg)
  1480. {
  1481. struct pool *pool;
  1482. if (!total_pools)
  1483. return "Define pool first, then the --coinbase-check-total argument";
  1484. pool = pools[total_pools - 1];
  1485. pool->cb_param.total = atoll(arg);
  1486. if (pool->cb_param.total < 0)
  1487. return "The total payout amount in coinbase should be greater than 0";
  1488. return NULL;
  1489. }
  1490. static char *set_cbcperc(const char *arg)
  1491. {
  1492. struct pool *pool;
  1493. if (!total_pools)
  1494. return "Define pool first, then the --coinbase-check-percent argument";
  1495. pool = pools[total_pools - 1];
  1496. if (!pool->cb_param.scripts)
  1497. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1498. pool->cb_param.perc = atof(arg) / 100;
  1499. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1500. return "The percentage should be between 0 and 100";
  1501. return NULL;
  1502. }
  1503. static
  1504. char *set_pool_goal(const char * const arg)
  1505. {
  1506. struct pool *pool;
  1507. if (!total_pools)
  1508. return "Usage of --pool-goal before pools are defined does not make sense";
  1509. pool = pools[total_pools - 1];
  1510. pool->goal = get_mining_goal(arg);
  1511. return NULL;
  1512. }
  1513. static char *set_pool_priority(const char *arg)
  1514. {
  1515. struct pool *pool;
  1516. if (!total_pools)
  1517. return "Usage of --pool-priority before pools are defined does not make sense";
  1518. pool = pools[total_pools - 1];
  1519. opt_set_intval(arg, &pool->prio);
  1520. return NULL;
  1521. }
  1522. static char *set_pool_proxy(const char *arg)
  1523. {
  1524. struct pool *pool;
  1525. if (!total_pools)
  1526. return "Usage of --pool-proxy before pools are defined does not make sense";
  1527. if (!our_curl_supports_proxy_uris())
  1528. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1529. pool = pools[total_pools - 1];
  1530. opt_set_charp(arg, &pool->rpc_proxy);
  1531. return NULL;
  1532. }
  1533. static char *set_pool_force_rollntime(const char *arg)
  1534. {
  1535. struct pool *pool;
  1536. if (!total_pools)
  1537. return "Usage of --force-rollntime before pools are defined does not make sense";
  1538. pool = pools[total_pools - 1];
  1539. opt_set_intval(arg, &pool->force_rollntime);
  1540. return NULL;
  1541. }
  1542. static char *enable_debug(bool *flag)
  1543. {
  1544. *flag = true;
  1545. opt_debug_console = true;
  1546. /* Turn on verbose output, too. */
  1547. opt_log_output = true;
  1548. return NULL;
  1549. }
  1550. static char *set_schedtime(const char *arg, struct schedtime *st)
  1551. {
  1552. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1553. {
  1554. if (strcasecmp(arg, "now"))
  1555. return "Invalid time set, should be HH:MM";
  1556. } else
  1557. schedstop.tm.tm_sec = 0;
  1558. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1559. return "Invalid time set.";
  1560. st->enable = true;
  1561. return NULL;
  1562. }
  1563. static
  1564. char *set_log_file(char *arg)
  1565. {
  1566. char *r = "";
  1567. long int i = strtol(arg, &r, 10);
  1568. int fd, stderr_fd = fileno(stderr);
  1569. if ((!*r) && i >= 0 && i <= INT_MAX)
  1570. fd = i;
  1571. else
  1572. if (!strcmp(arg, "-"))
  1573. {
  1574. fd = fileno(stdout);
  1575. if (unlikely(fd == -1))
  1576. return "Standard output missing for log-file";
  1577. }
  1578. else
  1579. {
  1580. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1581. if (unlikely(fd == -1))
  1582. return "Failed to open log-file";
  1583. }
  1584. close(stderr_fd);
  1585. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1586. return "Failed to dup2 for log-file";
  1587. close(fd);
  1588. return NULL;
  1589. }
  1590. static
  1591. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1592. {
  1593. char *r = "";
  1594. long int i = strtol(arg, &r, 10);
  1595. static char *err = NULL;
  1596. const size_t errbufsz = 0x100;
  1597. free(err);
  1598. err = NULL;
  1599. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1600. *F = fdopen((int)i, mode);
  1601. if (!*F)
  1602. {
  1603. err = malloc(errbufsz);
  1604. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1605. (int)i, purpose);
  1606. return err;
  1607. }
  1608. } else if (!strcmp(arg, "-")) {
  1609. *F = (mode[0] == 'a') ? stdout : stdin;
  1610. if (!*F)
  1611. {
  1612. err = malloc(errbufsz);
  1613. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1614. (mode[0] == 'a') ? "out" : "in", purpose);
  1615. return err;
  1616. }
  1617. } else {
  1618. *F = fopen(arg, mode);
  1619. if (!*F)
  1620. {
  1621. err = malloc(errbufsz);
  1622. snprintf(err, errbufsz, "Failed to open %s for %s",
  1623. arg, purpose);
  1624. return err;
  1625. }
  1626. }
  1627. return NULL;
  1628. }
  1629. static char *set_noncelog(char *arg)
  1630. {
  1631. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1632. }
  1633. static char *set_sharelog(char *arg)
  1634. {
  1635. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1636. }
  1637. static
  1638. void _add_set_device_option(const char * const func, const char * const buf)
  1639. {
  1640. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1641. string_elist_add(buf, &opt_set_device_list);
  1642. }
  1643. #define add_set_device_option(...) do{ \
  1644. char _tmp1718[0x100]; \
  1645. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1646. _add_set_device_option(__func__, _tmp1718); \
  1647. }while(0)
  1648. char *set_temp_cutoff(char *arg)
  1649. {
  1650. if (strchr(arg, ','))
  1651. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1652. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1653. add_set_device_option("all:temp-cutoff=%s", arg);
  1654. return NULL;
  1655. }
  1656. char *set_temp_target(char *arg)
  1657. {
  1658. if (strchr(arg, ','))
  1659. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1660. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1661. add_set_device_option("all:temp-target=%s", arg);
  1662. return NULL;
  1663. }
  1664. #ifdef HAVE_OPENCL
  1665. static
  1666. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1667. {
  1668. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1669. add_set_device_option("OCL:binary=no");
  1670. return NULL;
  1671. }
  1672. #endif
  1673. static
  1674. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1675. {
  1676. opt_disable_client_reconnect = true;
  1677. want_stratum = false;
  1678. return NULL;
  1679. }
  1680. static char *set_api_allow(const char *arg)
  1681. {
  1682. opt_set_charp(arg, &opt_api_allow);
  1683. return NULL;
  1684. }
  1685. static char *set_api_groups(const char *arg)
  1686. {
  1687. opt_set_charp(arg, &opt_api_groups);
  1688. return NULL;
  1689. }
  1690. static char *set_api_description(const char *arg)
  1691. {
  1692. opt_set_charp(arg, &opt_api_description);
  1693. return NULL;
  1694. }
  1695. static char *set_api_mcast_des(const char *arg)
  1696. {
  1697. opt_set_charp(arg, &opt_api_mcast_des);
  1698. return NULL;
  1699. }
  1700. #ifdef USE_ICARUS
  1701. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1702. static char *set_icarus_options(const char *arg)
  1703. {
  1704. if (strchr(arg, ','))
  1705. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1706. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1707. char *opts = strdup(arg), *argdup;
  1708. argdup = opts;
  1709. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1710. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1711. char *saveptr, *opt;
  1712. for (int i = 0; i < 4; ++i, ++sdf)
  1713. {
  1714. opt = strtok_r(opts, ":", &saveptr);
  1715. opts = NULL;
  1716. if (!opt)
  1717. break;
  1718. if (!opt[0])
  1719. continue;
  1720. for (int j = 0; j < 4; ++j)
  1721. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1722. }
  1723. free(argdup);
  1724. return NULL;
  1725. }
  1726. static char *set_icarus_timing(const char *arg)
  1727. {
  1728. if (strchr(arg, ','))
  1729. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1730. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1731. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1732. for (int j = 0; j < 4; ++j)
  1733. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1734. return NULL;
  1735. }
  1736. #endif
  1737. #ifdef USE_AVALON
  1738. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1739. static char *set_avalon_options(const char *arg)
  1740. {
  1741. if (strchr(arg, ','))
  1742. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1743. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1744. char *opts = strdup(arg), *argdup;
  1745. argdup = opts;
  1746. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1747. char *saveptr, *opt;
  1748. for (int i = 0; i < 5; ++i, ++sdf)
  1749. {
  1750. opt = strtok_r(opts, ":", &saveptr);
  1751. opts = NULL;
  1752. if (!opt)
  1753. break;
  1754. if (!opt[0])
  1755. continue;
  1756. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1757. }
  1758. free(argdup);
  1759. return NULL;
  1760. }
  1761. #endif
  1762. #ifdef USE_KLONDIKE
  1763. static char *set_klondike_options(const char *arg)
  1764. {
  1765. int hashclock;
  1766. double temptarget;
  1767. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1768. {
  1769. default:
  1770. return "Unrecognised --klondike-options";
  1771. case 2:
  1772. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1773. // fallthru
  1774. case 1:
  1775. add_set_device_option("klondike:clock=%d", hashclock);
  1776. }
  1777. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1778. return NULL;
  1779. }
  1780. #endif
  1781. __maybe_unused
  1782. static char *set_null(const char __maybe_unused *arg)
  1783. {
  1784. return NULL;
  1785. }
  1786. /* These options are available from config file or commandline */
  1787. static struct opt_table opt_config_table[] = {
  1788. #ifdef WANT_CPUMINE
  1789. OPT_WITH_ARG("--algo",
  1790. set_algo, show_algo, &opt_algo,
  1791. "Specify sha256 implementation for CPU mining:\n"
  1792. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1793. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1794. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1795. #ifdef WANT_SSE2_4WAY
  1796. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1797. #endif
  1798. #ifdef WANT_VIA_PADLOCK
  1799. "\n\tvia\t\tVIA padlock implementation"
  1800. #endif
  1801. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1802. #ifdef WANT_CRYPTOPP_ASM32
  1803. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1804. #endif
  1805. #ifdef WANT_X8632_SSE2
  1806. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1807. #endif
  1808. #ifdef WANT_X8664_SSE2
  1809. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1810. #endif
  1811. #ifdef WANT_X8664_SSE4
  1812. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1813. #endif
  1814. #ifdef WANT_ALTIVEC_4WAY
  1815. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1816. #endif
  1817. ),
  1818. OPT_WITH_ARG("-a",
  1819. set_algo, show_algo, &opt_algo,
  1820. opt_hidden),
  1821. #endif
  1822. OPT_WITH_ARG("--api-allow",
  1823. set_api_allow, NULL, NULL,
  1824. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1825. OPT_WITH_ARG("--api-description",
  1826. set_api_description, NULL, NULL,
  1827. "Description placed in the API status header, default: BFGMiner version"),
  1828. OPT_WITH_ARG("--api-groups",
  1829. set_api_groups, NULL, NULL,
  1830. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1831. OPT_WITHOUT_ARG("--api-listen",
  1832. opt_set_bool, &opt_api_listen,
  1833. "Enable API, default: disabled"),
  1834. OPT_WITHOUT_ARG("--api-mcast",
  1835. opt_set_bool, &opt_api_mcast,
  1836. "Enable API Multicast listener, default: disabled"),
  1837. OPT_WITH_ARG("--api-mcast-addr",
  1838. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1839. "API Multicast listen address"),
  1840. OPT_WITH_ARG("--api-mcast-code",
  1841. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1842. "Code expected in the API Multicast message, don't use '-'"),
  1843. OPT_WITH_ARG("--api-mcast-des",
  1844. set_api_mcast_des, NULL, NULL,
  1845. "Description appended to the API Multicast reply, default: ''"),
  1846. OPT_WITH_ARG("--api-mcast-port",
  1847. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1848. "API Multicast listen port"),
  1849. OPT_WITHOUT_ARG("--api-network",
  1850. opt_set_bool, &opt_api_network,
  1851. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1852. OPT_WITH_ARG("--api-port",
  1853. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1854. "Port number of miner API"),
  1855. #ifdef HAVE_ADL
  1856. OPT_WITHOUT_ARG("--auto-fan",
  1857. opt_set_bool, &opt_autofan,
  1858. opt_hidden),
  1859. OPT_WITHOUT_ARG("--auto-gpu",
  1860. opt_set_bool, &opt_autoengine,
  1861. opt_hidden),
  1862. #endif
  1863. OPT_WITHOUT_ARG("--balance",
  1864. set_balance, &pool_strategy,
  1865. "Change multipool strategy from failover to even share balance"),
  1866. OPT_WITHOUT_ARG("--benchmark",
  1867. opt_set_bool, &opt_benchmark,
  1868. "Run BFGMiner in benchmark mode - produces no shares"),
  1869. OPT_WITHOUT_ARG("--benchmark-intense",
  1870. set_benchmark_intense, &opt_benchmark_intense,
  1871. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  1872. #if defined(USE_BITFORCE)
  1873. OPT_WITHOUT_ARG("--bfl-range",
  1874. opt_set_bool, &opt_bfl_noncerange,
  1875. "Use nonce range on bitforce devices if supported"),
  1876. #endif
  1877. #ifdef HAVE_CHROOT
  1878. OPT_WITH_ARG("--chroot-dir",
  1879. opt_set_charp, NULL, &chroot_dir,
  1880. "Chroot to a directory right after startup"),
  1881. #endif
  1882. OPT_WITH_ARG("--cmd-idle",
  1883. opt_set_charp, NULL, &cmd_idle,
  1884. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1885. OPT_WITH_ARG("--cmd-sick",
  1886. opt_set_charp, NULL, &cmd_sick,
  1887. "Execute a command when a device is declared sick"),
  1888. OPT_WITH_ARG("--cmd-dead",
  1889. opt_set_charp, NULL, &cmd_dead,
  1890. "Execute a command when a device is declared dead"),
  1891. #if BLKMAKER_VERSION > 1
  1892. OPT_WITH_ARG("--coinbase-addr",
  1893. set_b58addr, NULL, &opt_coinbase_script,
  1894. "Set coinbase payout address for solo mining"),
  1895. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1896. set_b58addr, NULL, &opt_coinbase_script,
  1897. opt_hidden),
  1898. #endif
  1899. #if BLKMAKER_VERSION > 0
  1900. OPT_WITH_ARG("--coinbase-sig",
  1901. set_strdup, NULL, &opt_coinbase_sig,
  1902. "Set coinbase signature when possible"),
  1903. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1904. set_strdup, NULL, &opt_coinbase_sig,
  1905. opt_hidden),
  1906. #endif
  1907. #ifdef HAVE_CURSES
  1908. OPT_WITHOUT_ARG("--compact",
  1909. opt_set_bool, &opt_compact,
  1910. "Use compact display without per device statistics"),
  1911. #endif
  1912. #ifdef WANT_CPUMINE
  1913. OPT_WITH_ARG("--cpu-threads",
  1914. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1915. "Number of miner CPU threads"),
  1916. OPT_WITH_ARG("-t",
  1917. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1918. opt_hidden),
  1919. #endif
  1920. OPT_WITHOUT_ARG("--debug|-D",
  1921. enable_debug, &opt_debug,
  1922. "Enable debug output"),
  1923. OPT_WITHOUT_ARG("--debuglog",
  1924. opt_set_bool, &opt_debug,
  1925. "Enable debug logging"),
  1926. OPT_WITHOUT_ARG("--device-protocol-dump",
  1927. opt_set_bool, &opt_dev_protocol,
  1928. "Verbose dump of device protocol-level activities"),
  1929. OPT_WITH_ARG("--device|-d",
  1930. set_devices, NULL, NULL,
  1931. "Enable only devices matching pattern (default: all)"),
  1932. OPT_WITHOUT_ARG("--disable-rejecting",
  1933. opt_set_bool, &opt_disable_pool,
  1934. "Automatically disable pools that continually reject shares"),
  1935. #ifdef USE_LIBMICROHTTPD
  1936. OPT_WITH_ARG("--http-port",
  1937. opt_set_intval, opt_show_intval, &httpsrv_port,
  1938. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1939. #endif
  1940. OPT_WITH_ARG("--expiry",
  1941. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1942. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1943. OPT_WITH_ARG("-E",
  1944. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1945. opt_hidden),
  1946. OPT_WITH_ARG("--expiry-lp",
  1947. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1948. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1949. OPT_WITHOUT_ARG("--failover-only",
  1950. opt_set_bool, &opt_fail_only,
  1951. "Don't leak work to backup pools when primary pool is lagging"),
  1952. OPT_WITH_ARG("--failover-switch-delay",
  1953. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  1954. "Delay in seconds before switching back to a failed pool"),
  1955. #ifdef USE_FPGA
  1956. OPT_WITHOUT_ARG("--force-dev-init",
  1957. opt_set_bool, &opt_force_dev_init,
  1958. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1959. #endif
  1960. #ifdef HAVE_OPENCL
  1961. OPT_WITH_ARG("--gpu-dyninterval",
  1962. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1963. opt_hidden),
  1964. OPT_WITH_ARG("--gpu-platform",
  1965. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1966. "Select OpenCL platform ID to use for GPU mining"),
  1967. OPT_WITH_ARG("--gpu-threads|-g",
  1968. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1969. opt_hidden),
  1970. #ifdef HAVE_ADL
  1971. OPT_WITH_ARG("--gpu-engine",
  1972. set_gpu_engine, NULL, NULL,
  1973. opt_hidden),
  1974. OPT_WITH_ARG("--gpu-fan",
  1975. set_gpu_fan, NULL, NULL,
  1976. opt_hidden),
  1977. OPT_WITH_ARG("--gpu-map",
  1978. set_gpu_map, NULL, NULL,
  1979. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1980. OPT_WITH_ARG("--gpu-memclock",
  1981. set_gpu_memclock, NULL, NULL,
  1982. opt_hidden),
  1983. OPT_WITH_ARG("--gpu-memdiff",
  1984. set_gpu_memdiff, NULL, NULL,
  1985. opt_hidden),
  1986. OPT_WITH_ARG("--gpu-powertune",
  1987. set_gpu_powertune, NULL, NULL,
  1988. opt_hidden),
  1989. OPT_WITHOUT_ARG("--gpu-reorder",
  1990. opt_set_bool, &opt_reorder,
  1991. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1992. OPT_WITH_ARG("--gpu-vddc",
  1993. set_gpu_vddc, NULL, NULL,
  1994. opt_hidden),
  1995. #endif
  1996. #ifdef USE_SCRYPT
  1997. OPT_WITH_ARG("--lookup-gap",
  1998. set_lookup_gap, NULL, NULL,
  1999. opt_hidden),
  2000. #endif
  2001. OPT_WITH_ARG("--intensity|-I",
  2002. set_intensity, NULL, NULL,
  2003. opt_hidden),
  2004. #endif
  2005. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2006. OPT_WITH_ARG("--kernel-path",
  2007. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2008. "Specify a path to where bitstream and kernel files are"),
  2009. OPT_WITH_ARG("-K",
  2010. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2011. opt_hidden),
  2012. #endif
  2013. #ifdef HAVE_OPENCL
  2014. OPT_WITH_ARG("--kernel|-k",
  2015. set_kernel, NULL, NULL,
  2016. opt_hidden),
  2017. #endif
  2018. #ifdef USE_ICARUS
  2019. OPT_WITH_ARG("--icarus-options",
  2020. set_icarus_options, NULL, NULL,
  2021. opt_hidden),
  2022. OPT_WITH_ARG("--icarus-timing",
  2023. set_icarus_timing, NULL, NULL,
  2024. opt_hidden),
  2025. #endif
  2026. #ifdef USE_AVALON
  2027. OPT_WITH_ARG("--avalon-options",
  2028. set_avalon_options, NULL, NULL,
  2029. opt_hidden),
  2030. #endif
  2031. #ifdef USE_KLONDIKE
  2032. OPT_WITH_ARG("--klondike-options",
  2033. set_klondike_options, NULL, NULL,
  2034. "Set klondike options clock:temptarget"),
  2035. #endif
  2036. OPT_WITHOUT_ARG("--load-balance",
  2037. set_loadbalance, &pool_strategy,
  2038. "Change multipool strategy from failover to quota based balance"),
  2039. OPT_WITH_ARG("--log|-l",
  2040. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2041. "Interval in seconds between log output"),
  2042. OPT_WITH_ARG("--log-file|-L",
  2043. set_log_file, NULL, NULL,
  2044. "Append log file for output messages"),
  2045. OPT_WITH_ARG("--logfile",
  2046. set_log_file, NULL, NULL,
  2047. opt_hidden),
  2048. OPT_WITHOUT_ARG("--log-microseconds",
  2049. opt_set_bool, &opt_log_microseconds,
  2050. "Include microseconds in log output"),
  2051. #if defined(unix) || defined(__APPLE__)
  2052. OPT_WITH_ARG("--monitor|-m",
  2053. opt_set_charp, NULL, &opt_stderr_cmd,
  2054. "Use custom pipe cmd for output messages"),
  2055. #endif // defined(unix)
  2056. OPT_WITHOUT_ARG("--net-delay",
  2057. opt_set_bool, &opt_delaynet,
  2058. "Impose small delays in networking to avoid overloading slow routers"),
  2059. OPT_WITHOUT_ARG("--no-adl",
  2060. opt_set_bool, &opt_noadl,
  2061. #ifdef HAVE_ADL
  2062. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2063. #else
  2064. opt_hidden
  2065. #endif
  2066. ),
  2067. OPT_WITHOUT_ARG("--no-gbt",
  2068. opt_set_invbool, &want_gbt,
  2069. "Disable getblocktemplate support"),
  2070. OPT_WITHOUT_ARG("--no-getwork",
  2071. opt_set_invbool, &want_getwork,
  2072. "Disable getwork support"),
  2073. OPT_WITHOUT_ARG("--no-hotplug",
  2074. #ifdef HAVE_BFG_HOTPLUG
  2075. opt_set_invbool, &opt_hotplug,
  2076. "Disable hotplug detection"
  2077. #else
  2078. set_null, &opt_hotplug,
  2079. opt_hidden
  2080. #endif
  2081. ),
  2082. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2083. #if BLKMAKER_VERSION > 1
  2084. opt_set_invbool, &opt_load_bitcoin_conf,
  2085. "Disable adding pools for local bitcoin RPC servers"),
  2086. #else
  2087. set_null, NULL, opt_hidden),
  2088. #endif
  2089. OPT_WITHOUT_ARG("--no-longpoll",
  2090. opt_set_invbool, &want_longpoll,
  2091. "Disable X-Long-Polling support"),
  2092. OPT_WITHOUT_ARG("--no-pool-disable",
  2093. opt_set_invbool, &opt_disable_pool,
  2094. opt_hidden),
  2095. OPT_WITHOUT_ARG("--no-client-reconnect",
  2096. opt_set_invbool, &opt_disable_client_reconnect,
  2097. opt_hidden),
  2098. OPT_WITHOUT_ARG("--no-pool-redirect",
  2099. disable_pool_redirect, NULL,
  2100. "Ignore pool requests to redirect to another server"),
  2101. OPT_WITHOUT_ARG("--no-restart",
  2102. opt_set_invbool, &opt_restart,
  2103. "Do not attempt to restart devices that hang"
  2104. ),
  2105. OPT_WITHOUT_ARG("--no-show-processors",
  2106. opt_set_invbool, &opt_show_procs,
  2107. opt_hidden),
  2108. OPT_WITHOUT_ARG("--no-show-procs",
  2109. opt_set_invbool, &opt_show_procs,
  2110. opt_hidden),
  2111. OPT_WITHOUT_ARG("--no-stratum",
  2112. opt_set_invbool, &want_stratum,
  2113. "Disable Stratum detection"),
  2114. OPT_WITHOUT_ARG("--no-submit-stale",
  2115. opt_set_invbool, &opt_submit_stale,
  2116. "Don't submit shares if they are detected as stale"),
  2117. #ifdef HAVE_OPENCL
  2118. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2119. set_no_opencl_binaries, NULL,
  2120. opt_hidden),
  2121. #endif
  2122. OPT_WITHOUT_ARG("--no-unicode",
  2123. #ifdef USE_UNICODE
  2124. opt_set_invbool, &use_unicode,
  2125. "Don't use Unicode characters in TUI"
  2126. #else
  2127. set_null, &use_unicode,
  2128. opt_hidden
  2129. #endif
  2130. ),
  2131. OPT_WITH_ARG("--noncelog",
  2132. set_noncelog, NULL, NULL,
  2133. "Create log of all nonces found"),
  2134. OPT_WITH_ARG("--pass|-p",
  2135. set_pass, NULL, NULL,
  2136. "Password for bitcoin JSON-RPC server"),
  2137. OPT_WITHOUT_ARG("--per-device-stats",
  2138. opt_set_bool, &want_per_device_stats,
  2139. "Force verbose mode and output per-device statistics"),
  2140. OPT_WITH_ARG("--userpass|-O",
  2141. set_userpass, NULL, NULL,
  2142. "Username:Password pair for bitcoin JSON-RPC server"),
  2143. OPT_WITH_ARG("--pool-goal",
  2144. set_pool_goal, NULL, NULL,
  2145. "Named goal for the previous-defined pool"),
  2146. OPT_WITH_ARG("--pool-priority",
  2147. set_pool_priority, NULL, NULL,
  2148. "Priority for just the previous-defined pool"),
  2149. OPT_WITH_ARG("--pool-proxy|-x",
  2150. set_pool_proxy, NULL, NULL,
  2151. "Proxy URI to use for connecting to just the previous-defined pool"),
  2152. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2153. set_pool_force_rollntime, NULL, NULL,
  2154. opt_hidden),
  2155. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2156. opt_set_bool, &opt_protocol,
  2157. "Verbose dump of protocol-level activities"),
  2158. OPT_WITH_ARG("--queue|-Q",
  2159. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2160. "Minimum number of work items to have queued (0+)"),
  2161. OPT_WITHOUT_ARG("--quiet|-q",
  2162. opt_set_bool, &opt_quiet,
  2163. "Disable logging output, display status and errors"),
  2164. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2165. opt_set_bool, &opt_quiet_work_updates,
  2166. opt_hidden),
  2167. OPT_WITH_ARG("--quit-summary",
  2168. set_quit_summary, NULL, NULL,
  2169. "Summary printed when you quit: none/devs/procs/detailed"),
  2170. OPT_WITH_ARG("--quota|-U",
  2171. set_quota, NULL, NULL,
  2172. "quota;URL combination for server with load-balance strategy quotas"),
  2173. OPT_WITHOUT_ARG("--real-quiet",
  2174. opt_set_bool, &opt_realquiet,
  2175. "Disable all output"),
  2176. OPT_WITH_ARG("--request-diff",
  2177. set_request_diff, opt_show_floatval, &request_pdiff,
  2178. "Request a specific difficulty from pools"),
  2179. OPT_WITH_ARG("--retries",
  2180. opt_set_intval, opt_show_intval, &opt_retries,
  2181. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2182. OPT_WITH_ARG("--retry-pause",
  2183. set_null, NULL, NULL,
  2184. opt_hidden),
  2185. OPT_WITH_ARG("--rotate",
  2186. set_rotate, opt_show_intval, &opt_rotate_period,
  2187. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2188. OPT_WITHOUT_ARG("--round-robin",
  2189. set_rr, &pool_strategy,
  2190. "Change multipool strategy from failover to round robin on failure"),
  2191. OPT_WITH_ARG("--scan|-S",
  2192. add_serial, NULL, NULL,
  2193. "Configure how to scan for mining devices"),
  2194. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2195. add_serial, NULL, NULL,
  2196. opt_hidden),
  2197. OPT_WITH_ARG("--scan-time",
  2198. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2199. "Upper bound on time spent scanning current work, in seconds"),
  2200. OPT_WITH_ARG("-s",
  2201. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2202. opt_hidden),
  2203. OPT_WITH_ARG("--scantime",
  2204. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2205. opt_hidden),
  2206. OPT_WITH_ARG("--sched-start",
  2207. set_schedtime, NULL, &schedstart,
  2208. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2209. OPT_WITH_ARG("--sched-stop",
  2210. set_schedtime, NULL, &schedstop,
  2211. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2212. #ifdef USE_SCRYPT
  2213. OPT_WITHOUT_ARG("--scrypt",
  2214. opt_set_bool, &opt_scrypt,
  2215. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2216. #endif
  2217. OPT_WITH_ARG("--set-device|--set",
  2218. opt_string_elist_add, NULL, &opt_set_device_list,
  2219. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2220. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2221. OPT_WITH_ARG("--shaders",
  2222. set_shaders, NULL, NULL,
  2223. opt_hidden),
  2224. #endif
  2225. #ifdef HAVE_PWD_H
  2226. OPT_WITH_ARG("--setuid",
  2227. opt_set_charp, NULL, &opt_setuid,
  2228. "Username of an unprivileged user to run as"),
  2229. #endif
  2230. OPT_WITH_ARG("--sharelog",
  2231. set_sharelog, NULL, NULL,
  2232. "Append share log to file"),
  2233. OPT_WITH_ARG("--shares",
  2234. opt_set_floatval, NULL, &opt_shares,
  2235. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2236. OPT_WITHOUT_ARG("--show-processors",
  2237. opt_set_bool, &opt_show_procs,
  2238. "Show per processor statistics in summary"),
  2239. OPT_WITHOUT_ARG("--show-procs",
  2240. opt_set_bool, &opt_show_procs,
  2241. opt_hidden),
  2242. OPT_WITH_ARG("--skip-security-checks",
  2243. set_int_0_to_9999, NULL, &opt_skip_checks,
  2244. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2245. OPT_WITH_ARG("--socks-proxy",
  2246. opt_set_charp, NULL, &opt_socks_proxy,
  2247. "Set socks proxy (host:port)"),
  2248. #ifdef USE_LIBEVENT
  2249. OPT_WITH_ARG("--stratum-port",
  2250. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2251. "Port number to listen on for stratum miners (-1 means disabled)"),
  2252. #endif
  2253. OPT_WITHOUT_ARG("--submit-stale",
  2254. opt_set_bool, &opt_submit_stale,
  2255. opt_hidden),
  2256. OPT_WITH_ARG("--submit-threads",
  2257. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2258. "Minimum number of concurrent share submissions (default: 64)"),
  2259. #ifdef HAVE_SYSLOG_H
  2260. OPT_WITHOUT_ARG("--syslog",
  2261. opt_set_bool, &use_syslog,
  2262. "Use system log for output messages (default: standard error)"),
  2263. #endif
  2264. OPT_WITH_ARG("--temp-cutoff",
  2265. set_temp_cutoff, NULL, &opt_cutofftemp,
  2266. opt_hidden),
  2267. OPT_WITH_ARG("--temp-hysteresis",
  2268. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2269. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2270. #ifdef HAVE_ADL
  2271. OPT_WITH_ARG("--temp-overheat",
  2272. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2273. opt_hidden),
  2274. #endif
  2275. OPT_WITH_ARG("--temp-target",
  2276. set_temp_target, NULL, NULL,
  2277. opt_hidden),
  2278. OPT_WITHOUT_ARG("--text-only|-T",
  2279. opt_set_invbool, &use_curses,
  2280. #ifdef HAVE_CURSES
  2281. "Disable ncurses formatted screen output"
  2282. #else
  2283. opt_hidden
  2284. #endif
  2285. ),
  2286. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2287. OPT_WITH_ARG("--thread-concurrency",
  2288. set_thread_concurrency, NULL, NULL,
  2289. opt_hidden),
  2290. #endif
  2291. #ifdef USE_UNICODE
  2292. OPT_WITHOUT_ARG("--unicode",
  2293. opt_set_bool, &use_unicode,
  2294. "Use Unicode characters in TUI"),
  2295. #endif
  2296. OPT_WITH_ARG("--url|-o",
  2297. set_url, NULL, NULL,
  2298. "URL for bitcoin JSON-RPC server"),
  2299. OPT_WITH_ARG("--user|-u",
  2300. set_user, NULL, NULL,
  2301. "Username for bitcoin JSON-RPC server"),
  2302. #ifdef HAVE_OPENCL
  2303. OPT_WITH_ARG("--vectors|-v",
  2304. set_vector, NULL, NULL,
  2305. opt_hidden),
  2306. #endif
  2307. OPT_WITHOUT_ARG("--verbose",
  2308. opt_set_bool, &opt_log_output,
  2309. "Log verbose output to stderr as well as status output"),
  2310. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2311. opt_set_invbool, &opt_quiet_work_updates,
  2312. opt_hidden),
  2313. OPT_WITHOUT_ARG("--weighed-stats",
  2314. opt_set_bool, &opt_weighed_stats,
  2315. "Display statistics weighed to difficulty 1"),
  2316. #ifdef HAVE_OPENCL
  2317. OPT_WITH_ARG("--worksize|-w",
  2318. set_worksize, NULL, NULL,
  2319. opt_hidden),
  2320. #endif
  2321. OPT_WITHOUT_ARG("--unittest",
  2322. opt_set_bool, &opt_unittest, opt_hidden),
  2323. OPT_WITH_ARG("--coinbase-check-addr",
  2324. set_cbcaddr, NULL, NULL,
  2325. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2326. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2327. set_cbcaddr, NULL, NULL,
  2328. opt_hidden),
  2329. OPT_WITH_ARG("--coinbase-check-total",
  2330. set_cbctotal, NULL, NULL,
  2331. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2332. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2333. set_cbctotal, NULL, NULL,
  2334. opt_hidden),
  2335. OPT_WITH_ARG("--coinbase-check-percent",
  2336. set_cbcperc, NULL, NULL,
  2337. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2338. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2339. set_cbcperc, NULL, NULL,
  2340. opt_hidden),
  2341. OPT_WITHOUT_ARG("--worktime",
  2342. opt_set_bool, &opt_worktime,
  2343. "Display extra work time debug information"),
  2344. OPT_WITH_ARG("--pools",
  2345. opt_set_bool, NULL, NULL, opt_hidden),
  2346. OPT_ENDTABLE
  2347. };
  2348. static char *load_config(const char *arg, void __maybe_unused *unused);
  2349. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2350. {
  2351. static char err_buf[200];
  2352. struct opt_table *opt;
  2353. json_t *val;
  2354. if (fileconf && !*fileconf_load_p)
  2355. *fileconf_load_p = 1;
  2356. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2357. char *p, *name, *sp;
  2358. /* We don't handle subtables. */
  2359. assert(!(opt->type & OPT_SUBTABLE));
  2360. if (!opt->names)
  2361. continue;
  2362. /* Pull apart the option name(s). */
  2363. name = strdup(opt->names);
  2364. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2365. char *err = "Invalid value";
  2366. /* Ignore short options. */
  2367. if (p[1] != '-')
  2368. continue;
  2369. val = json_object_get(config, p+2);
  2370. if (!val)
  2371. continue;
  2372. if (opt->type & OPT_HASARG) {
  2373. if (json_is_string(val)) {
  2374. err = opt->cb_arg(json_string_value(val),
  2375. opt->u.arg);
  2376. } else if (json_is_number(val)) {
  2377. char buf[256], *p, *q;
  2378. snprintf(buf, 256, "%f", json_number_value(val));
  2379. if ( (p = strchr(buf, '.')) ) {
  2380. // Trim /\.0*$/ to work properly with integer-only arguments
  2381. q = p;
  2382. while (*(++q) == '0') {}
  2383. if (*q == '\0')
  2384. *p = '\0';
  2385. }
  2386. err = opt->cb_arg(buf, opt->u.arg);
  2387. } else if (json_is_array(val)) {
  2388. int n, size = json_array_size(val);
  2389. err = NULL;
  2390. for (n = 0; n < size && !err; n++) {
  2391. if (json_is_string(json_array_get(val, n)))
  2392. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2393. else if (json_is_object(json_array_get(val, n)))
  2394. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2395. }
  2396. }
  2397. } else if (opt->type & OPT_NOARG) {
  2398. if (json_is_true(val))
  2399. err = opt->cb(opt->u.arg);
  2400. else if (json_is_boolean(val)) {
  2401. if (opt->cb == (void*)opt_set_bool)
  2402. err = opt_set_invbool(opt->u.arg);
  2403. else if (opt->cb == (void*)opt_set_invbool)
  2404. err = opt_set_bool(opt->u.arg);
  2405. }
  2406. }
  2407. if (err) {
  2408. /* Allow invalid values to be in configuration
  2409. * file, just skipping over them provided the
  2410. * JSON is still valid after that. */
  2411. if (fileconf) {
  2412. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2413. *fileconf_load_p = -1;
  2414. } else {
  2415. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2416. p, err);
  2417. return err_buf;
  2418. }
  2419. }
  2420. }
  2421. free(name);
  2422. }
  2423. val = json_object_get(config, JSON_INCLUDE_CONF);
  2424. if (val && json_is_string(val))
  2425. return load_config(json_string_value(val), NULL);
  2426. return NULL;
  2427. }
  2428. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2429. static char *load_config(const char *arg, void __maybe_unused *unused)
  2430. {
  2431. json_error_t err;
  2432. json_t *config;
  2433. char *json_error;
  2434. size_t siz;
  2435. struct bfg_loaded_configfile *cfginfo;
  2436. cfginfo = malloc(sizeof(*cfginfo));
  2437. *cfginfo = (struct bfg_loaded_configfile){
  2438. .filename = strdup(arg),
  2439. };
  2440. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2441. if (++include_count > JSON_MAX_DEPTH)
  2442. return JSON_MAX_DEPTH_ERR;
  2443. #if JANSSON_MAJOR_VERSION > 1
  2444. config = json_load_file(arg, 0, &err);
  2445. #else
  2446. config = json_load_file(arg, &err);
  2447. #endif
  2448. if (!json_is_object(config)) {
  2449. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2450. json_error = malloc(siz);
  2451. if (!json_error)
  2452. quit(1, "Malloc failure in json error");
  2453. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2454. return json_error;
  2455. }
  2456. config_loaded = true;
  2457. /* Parse the config now, so we can override it. That can keep pointers
  2458. * so don't free config object. */
  2459. return parse_config(config, true, &cfginfo->fileconf_load);
  2460. }
  2461. static
  2462. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2463. {
  2464. bool * const found_defcfg_p = userp;
  2465. *found_defcfg_p = true;
  2466. load_config(filepath, NULL);
  2467. // Regardless of status of loading the config file, we should continue loading other defaults
  2468. return false;
  2469. }
  2470. static void load_default_config(void)
  2471. {
  2472. bool found_defcfg = false;
  2473. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2474. if (!found_defcfg)
  2475. {
  2476. // No BFGMiner config, try Cgminer's...
  2477. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2478. }
  2479. }
  2480. extern const char *opt_argv0;
  2481. static char *opt_verusage_and_exit(const char *extra)
  2482. {
  2483. puts(packagename);
  2484. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2485. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2486. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2487. printf(" Options:%s\n", BFG_OPTLIST);
  2488. printf("%s", opt_usage(opt_argv0, extra));
  2489. fflush(stdout);
  2490. exit(0);
  2491. }
  2492. /* These options are parsed before anything else */
  2493. static struct opt_table opt_early_table[] = {
  2494. // Default config is loaded in command line order, like a regular config
  2495. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2496. set_bool_ignore_arg, NULL, &config_loaded,
  2497. opt_hidden),
  2498. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2499. opt_set_bool, &config_loaded,
  2500. "Inhibit loading default config file"),
  2501. OPT_ENDTABLE
  2502. };
  2503. /* These options are available from commandline only */
  2504. static struct opt_table opt_cmdline_table[] = {
  2505. OPT_WITH_ARG("--config|-c",
  2506. load_config, NULL, NULL,
  2507. "Load a JSON-format configuration file\n"
  2508. "See example.conf for an example configuration."),
  2509. OPT_EARLY_WITHOUT_ARG("--no-config",
  2510. opt_set_bool, &config_loaded,
  2511. opt_hidden),
  2512. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2513. opt_set_bool, &config_loaded,
  2514. "Inhibit loading default config file"),
  2515. OPT_WITHOUT_ARG("--default-config",
  2516. load_default_config, NULL,
  2517. "Always load the default config file"),
  2518. OPT_WITHOUT_ARG("--help|-h",
  2519. opt_verusage_and_exit, NULL,
  2520. "Print this message"),
  2521. #ifdef HAVE_OPENCL
  2522. OPT_WITHOUT_ARG("--ndevs|-n",
  2523. print_ndevs_and_exit, &nDevs,
  2524. opt_hidden),
  2525. #endif
  2526. OPT_WITHOUT_ARG("--version|-V",
  2527. opt_version_and_exit, packagename,
  2528. "Display version and exit"),
  2529. OPT_ENDTABLE
  2530. };
  2531. static bool jobj_binary(const json_t *obj, const char *key,
  2532. void *buf, size_t buflen, bool required)
  2533. {
  2534. const char *hexstr;
  2535. json_t *tmp;
  2536. tmp = json_object_get(obj, key);
  2537. if (unlikely(!tmp)) {
  2538. if (unlikely(required))
  2539. applog(LOG_ERR, "JSON key '%s' not found", key);
  2540. return false;
  2541. }
  2542. hexstr = json_string_value(tmp);
  2543. if (unlikely(!hexstr)) {
  2544. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2545. return false;
  2546. }
  2547. if (!hex2bin(buf, hexstr, buflen))
  2548. return false;
  2549. return true;
  2550. }
  2551. static void calc_midstate(struct work *work)
  2552. {
  2553. union {
  2554. unsigned char c[64];
  2555. uint32_t i[16];
  2556. } data;
  2557. swap32yes(&data.i[0], work->data, 16);
  2558. sha256_ctx ctx;
  2559. sha256_init(&ctx);
  2560. sha256_update(&ctx, data.c, 64);
  2561. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2562. swap32tole(work->midstate, work->midstate, 8);
  2563. }
  2564. static
  2565. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2566. {
  2567. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2568. *tr = (struct bfg_tmpl_ref){
  2569. .tmpl = tmpl,
  2570. .refcount = 1,
  2571. };
  2572. mutex_init(&tr->mutex);
  2573. return tr;
  2574. }
  2575. static
  2576. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2577. {
  2578. mutex_lock(&tr->mutex);
  2579. ++tr->refcount;
  2580. mutex_unlock(&tr->mutex);
  2581. }
  2582. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2583. {
  2584. mutex_lock(&tr->mutex);
  2585. bool free_tmpl = !--tr->refcount;
  2586. mutex_unlock(&tr->mutex);
  2587. if (free_tmpl)
  2588. {
  2589. blktmpl_free(tr->tmpl);
  2590. mutex_destroy(&tr->mutex);
  2591. free(tr);
  2592. }
  2593. }
  2594. static struct work *make_work(void)
  2595. {
  2596. struct work *work = calloc(1, sizeof(struct work));
  2597. if (unlikely(!work))
  2598. quit(1, "Failed to calloc work in make_work");
  2599. cg_wlock(&control_lock);
  2600. work->id = total_work++;
  2601. cg_wunlock(&control_lock);
  2602. return work;
  2603. }
  2604. /* This is the central place all work that is about to be retired should be
  2605. * cleaned to remove any dynamically allocated arrays within the struct */
  2606. void clean_work(struct work *work)
  2607. {
  2608. free(work->job_id);
  2609. bytes_free(&work->nonce2);
  2610. free(work->nonce1);
  2611. if (work->device_data_free_func)
  2612. work->device_data_free_func(work);
  2613. if (work->tr)
  2614. tmpl_decref(work->tr);
  2615. memset(work, 0, sizeof(struct work));
  2616. }
  2617. /* All dynamically allocated work structs should be freed here to not leak any
  2618. * ram from arrays allocated within the work struct */
  2619. void free_work(struct work *work)
  2620. {
  2621. clean_work(work);
  2622. free(work);
  2623. }
  2624. 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";
  2625. #define workpadding_bin bfg_workpadding_bin
  2626. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2627. static
  2628. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2629. {
  2630. unsigned char hash_swap[32];
  2631. swap256(hash_swap, blkinfo->prevblkhash);
  2632. swap32tole(hash_swap, hash_swap, 32 / 4);
  2633. memset(out, '.', 3);
  2634. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2635. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2636. {
  2637. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2638. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2639. }
  2640. else
  2641. bin2hex(&out[3], &hash_swap[0x18], 8);
  2642. }
  2643. #ifdef HAVE_CURSES
  2644. static void update_block_display(void);
  2645. #endif
  2646. // Must only be called with ch_lock held!
  2647. static
  2648. void __update_block_title(struct mining_goal_info * const goal)
  2649. {
  2650. struct blockchain_info * const blkchain = goal->blkchain;
  2651. if (!goal->current_goal_detail)
  2652. goal->current_goal_detail = malloc(block_info_str_sz);
  2653. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2654. #ifdef HAVE_CURSES
  2655. update_block_display();
  2656. #endif
  2657. }
  2658. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2659. static
  2660. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2661. {
  2662. struct blockchain_info * const blkchain = goal->blkchain;
  2663. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2664. if ((!blkinfo) || blkinfo->height)
  2665. return;
  2666. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2667. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2668. cg_wlock(&ch_lock);
  2669. blkinfo->height = blkheight;
  2670. if (blkinfo == blkchain->currentblk)
  2671. {
  2672. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2673. __update_block_title(goal);
  2674. }
  2675. cg_wunlock(&ch_lock);
  2676. }
  2677. static
  2678. void pool_set_opaque(struct pool *pool, bool opaque)
  2679. {
  2680. if (pool->swork.opaque == opaque)
  2681. return;
  2682. pool->swork.opaque = opaque;
  2683. if (opaque)
  2684. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2685. pool->pool_no);
  2686. else
  2687. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2688. pool->pool_no);
  2689. }
  2690. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2691. {
  2692. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2693. return true;
  2694. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2695. }
  2696. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2697. {
  2698. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2699. {}
  2700. else
  2701. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2702. {
  2703. if (pool->enabled == POOL_ENABLED)
  2704. {
  2705. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2706. disable_pool(pool, POOL_MISBEHAVING);
  2707. }
  2708. }
  2709. else
  2710. if (pool->enabled == POOL_MISBEHAVING)
  2711. {
  2712. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2713. enable_pool(pool);
  2714. }
  2715. }
  2716. 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)
  2717. {
  2718. const int offsets = max(ntime_roll, 60);
  2719. *nrl = (struct ntime_roll_limits){
  2720. .min = ntime_base,
  2721. .max = ntime_base + ntime_roll,
  2722. .tv_ref = *tvp_ref,
  2723. .minoff = -offsets,
  2724. .maxoff = offsets,
  2725. };
  2726. }
  2727. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2728. {
  2729. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2730. }
  2731. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2732. {
  2733. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2734. const uint32_t ref_ntime = work_get_ntime(work);
  2735. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2736. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2737. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2738. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2739. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2740. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2741. if (max_ntime < min_ntime)
  2742. return -1;
  2743. if (max_ntime - min_ntime > desired_roll)
  2744. {
  2745. // Adjust min_ntime upward for accuracy, when possible
  2746. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2747. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2748. if (ideal_ntime > min_ntime)
  2749. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2750. }
  2751. work_set_ntime(work, min_ntime);
  2752. return max_ntime - min_ntime;
  2753. }
  2754. #if BLKMAKER_VERSION > 1
  2755. static
  2756. void refresh_bitcoind_address(const bool fresh)
  2757. {
  2758. struct mining_goal_info * const goal = get_mining_goal("default");
  2759. struct blockchain_info * const blkchain = goal->blkchain;
  2760. if (!have_at_least_one_getcbaddr)
  2761. return;
  2762. char getcbaddr_req[60];
  2763. CURL *curl = NULL;
  2764. json_t *json, *j2;
  2765. const char *s, *s2;
  2766. bytes_t newscript = BYTES_INIT;
  2767. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2768. for (int i = 0; i < total_pools; ++i)
  2769. {
  2770. struct pool * const pool = pools[i];
  2771. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2772. continue;
  2773. if (pool->goal != goal)
  2774. // TODO: Multi-blockchain support
  2775. continue;
  2776. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2777. if (!curl)
  2778. {
  2779. curl = curl_easy_init();
  2780. if (unlikely(!curl))
  2781. {
  2782. applogfail(LOG_ERR, "curl_easy_init");
  2783. break;
  2784. }
  2785. }
  2786. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2787. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2788. {
  2789. const char *estrc;
  2790. char *estr = NULL;
  2791. if (!(json && j2))
  2792. estrc = NULL;
  2793. else
  2794. {
  2795. estrc = json_string_value(j2);
  2796. if (!estrc)
  2797. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2798. }
  2799. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2800. free(estr);
  2801. continue;
  2802. }
  2803. s = bfg_json_obj_string(json, "result", NULL);
  2804. if (unlikely(!s))
  2805. {
  2806. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2807. continue;
  2808. }
  2809. s2 = set_b58addr(s, &newscript);
  2810. if (unlikely(s2))
  2811. {
  2812. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2813. continue;
  2814. }
  2815. if (bytes_eq(&newscript, &opt_coinbase_script))
  2816. {
  2817. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2818. break;
  2819. }
  2820. bytes_assimilate(&opt_coinbase_script, &newscript);
  2821. coinbase_script_block_id = blkchain->currentblk->block_id;
  2822. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2823. break;
  2824. }
  2825. bytes_free(&newscript);
  2826. if (curl)
  2827. curl_easy_cleanup(curl);
  2828. }
  2829. #endif
  2830. #define GBT_XNONCESZ (sizeof(uint32_t))
  2831. #if BLKMAKER_VERSION > 4
  2832. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2833. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2834. #endif
  2835. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2836. {
  2837. json_t *res_val = json_object_get(val, "result");
  2838. json_t *tmp_val;
  2839. bool ret = false;
  2840. struct timeval tv_now;
  2841. if (unlikely(detect_algo == 1)) {
  2842. json_t *tmp = json_object_get(res_val, "algorithm");
  2843. const char *v = tmp ? json_string_value(tmp) : "";
  2844. if (strncasecmp(v, "scrypt", 6))
  2845. detect_algo = 2;
  2846. }
  2847. timer_set_now(&tv_now);
  2848. if (work->tr)
  2849. {
  2850. blktemplate_t * const tmpl = work->tr->tmpl;
  2851. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  2852. if (err) {
  2853. applog(LOG_ERR, "blktmpl error: %s", err);
  2854. return false;
  2855. }
  2856. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  2857. #if BLKMAKER_VERSION > 1
  2858. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  2859. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  2860. refresh_bitcoind_address(false);
  2861. if (bytes_len(&opt_coinbase_script) && get_mining_goal("default") == pool->goal)
  2862. {
  2863. bool newcb;
  2864. #if BLKMAKER_VERSION > 2
  2865. blkmk_init_generation2(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script), &newcb);
  2866. #else
  2867. newcb = !tmpl->cbtxn;
  2868. blkmk_init_generation(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script));
  2869. #endif
  2870. if (newcb)
  2871. {
  2872. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  2873. if (ae < (ssize_t)sizeof(template_nonce))
  2874. 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);
  2875. ++template_nonce;
  2876. }
  2877. }
  2878. #endif
  2879. #if BLKMAKER_VERSION > 0
  2880. {
  2881. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  2882. static bool appenderr = false;
  2883. if (ae <= 0) {
  2884. if (opt_coinbase_sig) {
  2885. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2886. appenderr = true;
  2887. }
  2888. } else if (ae >= 3 || opt_coinbase_sig) {
  2889. const char *cbappend = opt_coinbase_sig;
  2890. const char full[] = PACKAGE " " VERSION;
  2891. char *need_free = NULL;
  2892. if (!cbappend) {
  2893. if ((size_t)ae >= sizeof(full) - 1)
  2894. cbappend = full;
  2895. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2896. {
  2897. const char *pos = strchr(full, '-');
  2898. size_t sz = (pos - full);
  2899. if (pos && ae > sz)
  2900. {
  2901. cbappend = need_free = malloc(sz + 1);
  2902. memcpy(need_free, full, sz);
  2903. need_free[sz] = '\0';
  2904. }
  2905. else
  2906. cbappend = PACKAGE;
  2907. }
  2908. else
  2909. cbappend = "BFG";
  2910. }
  2911. size_t cbappendsz = strlen(cbappend);
  2912. static bool truncatewarning = false;
  2913. if (cbappendsz <= (size_t)ae) {
  2914. if (cbappendsz < (size_t)ae)
  2915. // If we have space, include the trailing \0
  2916. ++cbappendsz;
  2917. ae = cbappendsz;
  2918. truncatewarning = false;
  2919. } else {
  2920. char *tmp = malloc(ae + 1);
  2921. memcpy(tmp, opt_coinbase_sig, ae);
  2922. tmp[ae] = '\0';
  2923. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2924. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2925. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2926. free(tmp);
  2927. truncatewarning = true;
  2928. }
  2929. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  2930. free(need_free);
  2931. if (ae <= 0) {
  2932. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2933. appenderr = true;
  2934. } else
  2935. appenderr = false;
  2936. }
  2937. }
  2938. #endif
  2939. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2940. return false;
  2941. swap32yes(work->data, work->data, 80 / 4);
  2942. memcpy(&work->data[80], workpadding_bin, 48);
  2943. work->ntime_roll_limits = (struct ntime_roll_limits){
  2944. .min = tmpl->mintime,
  2945. .max = tmpl->maxtime,
  2946. .tv_ref = tv_now,
  2947. .minoff = tmpl->mintimeoff,
  2948. .maxoff = tmpl->maxtimeoff,
  2949. };
  2950. const struct blktmpl_longpoll_req *lp;
  2951. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2952. free(pool->lp_id);
  2953. pool->lp_id = strdup(lp->id);
  2954. #if 0 /* This just doesn't work :( */
  2955. curl_socket_t sock = pool->lp_socket;
  2956. if (sock != CURL_SOCKET_BAD) {
  2957. pool->lp_socket = CURL_SOCKET_BAD;
  2958. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2959. shutdown(sock, SHUT_RDWR);
  2960. }
  2961. #endif
  2962. }
  2963. }
  2964. else
  2965. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2966. applog(LOG_ERR, "JSON inval data");
  2967. return false;
  2968. }
  2969. else
  2970. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  2971. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2972. // Calculate it ourselves
  2973. applog(LOG_DEBUG, "Calculating midstate locally");
  2974. calc_midstate(work);
  2975. }
  2976. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2977. applog(LOG_ERR, "JSON inval target");
  2978. return false;
  2979. }
  2980. if (work->tr)
  2981. {
  2982. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2983. {
  2984. int p = (sizeof(work->target) - 1) - i;
  2985. unsigned char c = work->target[i];
  2986. work->target[i] = work->target[p];
  2987. work->target[p] = c;
  2988. }
  2989. }
  2990. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2991. struct mining_goal_info * const goal = pool->goal;
  2992. uint32_t blkheight = json_number_value(tmp_val);
  2993. const void * const prevblkhash = &work->data[4];
  2994. have_block_height(goal, prevblkhash, blkheight);
  2995. }
  2996. memset(work->hash, 0, sizeof(work->hash));
  2997. work->tv_staged = tv_now;
  2998. #if BLKMAKER_VERSION > 4
  2999. if (work->tr)
  3000. {
  3001. blktemplate_t * const tmpl = work->tr->tmpl;
  3002. uint8_t buf[80];
  3003. int16_t expire;
  3004. uint8_t *cbtxn;
  3005. size_t cbtxnsz;
  3006. size_t cbextranonceoffset;
  3007. int branchcount;
  3008. libblkmaker_hash_t *branches;
  3009. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3010. {
  3011. struct stratum_work * const swork = &pool->swork;
  3012. const size_t branchdatasz = branchcount * 0x20;
  3013. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3014. cg_wlock(&pool->data_lock);
  3015. swork->tr = work->tr;
  3016. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3017. swork->nonce2_offset = cbextranonceoffset;
  3018. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3019. swork->merkles = branchcount;
  3020. memcpy(swork->header1, &buf[0], 36);
  3021. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3022. swork->tv_received = tv_now;
  3023. memcpy(swork->diffbits, &buf[72], 4);
  3024. memcpy(swork->target, work->target, sizeof(swork->target));
  3025. free(swork->job_id);
  3026. swork->job_id = NULL;
  3027. swork->clean = true;
  3028. swork->work_restart_id = pool->work_restart_id;
  3029. // FIXME: Do something with expire
  3030. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3031. pool->nonce2 = 0;
  3032. cg_wunlock(&pool->data_lock);
  3033. }
  3034. else
  3035. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3036. }
  3037. #endif // BLKMAKER_VERSION > 4
  3038. pool_set_opaque(pool, !work->tr);
  3039. ret = true;
  3040. return ret;
  3041. }
  3042. /* Returns whether the pool supports local work generation or not. */
  3043. static bool pool_localgen(struct pool *pool)
  3044. {
  3045. return (pool->last_work_copy || pool->has_stratum);
  3046. }
  3047. int dev_from_id(int thr_id)
  3048. {
  3049. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3050. return cgpu->device_id;
  3051. }
  3052. /* Create an exponentially decaying average over the opt_log_interval */
  3053. void decay_time(double *f, double fadd, double fsecs)
  3054. {
  3055. double ftotal, fprop;
  3056. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3057. ftotal = 1.0 + fprop;
  3058. *f += (fadd * fprop);
  3059. *f /= ftotal;
  3060. }
  3061. static int __total_staged(void)
  3062. {
  3063. return HASH_COUNT(staged_work);
  3064. }
  3065. static int total_staged(void)
  3066. {
  3067. int ret;
  3068. mutex_lock(stgd_lock);
  3069. ret = __total_staged();
  3070. mutex_unlock(stgd_lock);
  3071. return ret;
  3072. }
  3073. #ifdef HAVE_CURSES
  3074. WINDOW *mainwin, *statuswin, *logwin;
  3075. #endif
  3076. double total_secs = 1.0;
  3077. #ifdef HAVE_CURSES
  3078. static char statusline[256];
  3079. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3080. static int statusy;
  3081. static int devsummaryYOffset;
  3082. static int total_lines;
  3083. #endif
  3084. #ifdef HAVE_OPENCL
  3085. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3086. #endif
  3087. struct cgpu_info *cpus;
  3088. bool _bfg_console_cancel_disabled;
  3089. int _bfg_console_prev_cancelstate;
  3090. #ifdef HAVE_CURSES
  3091. #define lock_curses() bfg_console_lock()
  3092. #define unlock_curses() bfg_console_unlock()
  3093. static bool curses_active_locked(void)
  3094. {
  3095. bool ret;
  3096. lock_curses();
  3097. ret = curses_active;
  3098. if (!ret)
  3099. unlock_curses();
  3100. return ret;
  3101. }
  3102. // Cancellable getch
  3103. int my_cancellable_getch(void)
  3104. {
  3105. // This only works because the macro only hits direct getch() calls
  3106. typedef int (*real_getch_t)(void);
  3107. const real_getch_t real_getch = __real_getch;
  3108. int type, rv;
  3109. bool sct;
  3110. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3111. rv = real_getch();
  3112. if (sct)
  3113. pthread_setcanceltype(type, &type);
  3114. return rv;
  3115. }
  3116. #ifdef PDCURSES
  3117. static
  3118. int bfg_wresize(WINDOW *win, int lines, int columns)
  3119. {
  3120. int rv = wresize(win, lines, columns);
  3121. int x, y;
  3122. getyx(win, y, x);
  3123. if (unlikely(y >= lines || x >= columns))
  3124. {
  3125. if (y >= lines)
  3126. y = lines - 1;
  3127. if (x >= columns)
  3128. x = columns - 1;
  3129. wmove(win, y, x);
  3130. }
  3131. return rv;
  3132. }
  3133. #else
  3134. # define bfg_wresize wresize
  3135. #endif
  3136. #endif
  3137. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3138. {
  3139. va_list ap;
  3140. size_t presz = strlen(buf);
  3141. va_start(ap, fmt);
  3142. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3143. va_end(ap);
  3144. }
  3145. double stats_elapsed(struct cgminer_stats *stats)
  3146. {
  3147. struct timeval now;
  3148. double elapsed;
  3149. if (stats->start_tv.tv_sec == 0)
  3150. elapsed = total_secs;
  3151. else {
  3152. cgtime(&now);
  3153. elapsed = tdiff(&now, &stats->start_tv);
  3154. }
  3155. if (elapsed < 1.0)
  3156. elapsed = 1.0;
  3157. return elapsed;
  3158. }
  3159. bool drv_ready(struct cgpu_info *cgpu)
  3160. {
  3161. switch (cgpu->status) {
  3162. case LIFE_INIT:
  3163. case LIFE_DEAD2:
  3164. return false;
  3165. default:
  3166. return true;
  3167. }
  3168. }
  3169. double cgpu_utility(struct cgpu_info *cgpu)
  3170. {
  3171. double dev_runtime = cgpu_runtime(cgpu);
  3172. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3173. }
  3174. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3175. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3176. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3177. }while(0)
  3178. static float
  3179. utility_to_hashrate(double utility)
  3180. {
  3181. return utility * 0x4444444;
  3182. }
  3183. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3184. static const int _unitbase = 4;
  3185. static
  3186. void pick_unit(float hashrate, unsigned char *unit)
  3187. {
  3188. unsigned char i;
  3189. if (hashrate == 0 || !isfinite(hashrate))
  3190. {
  3191. if (*unit < _unitbase)
  3192. *unit = _unitbase;
  3193. return;
  3194. }
  3195. hashrate *= 1e12;
  3196. for (i = 0; i < *unit; ++i)
  3197. hashrate /= 1e3;
  3198. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3199. while (hashrate >= 999.95)
  3200. {
  3201. hashrate /= 1e3;
  3202. if (likely(_unitchar[*unit] != '?'))
  3203. ++*unit;
  3204. }
  3205. }
  3206. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3207. enum h2bs_fmt {
  3208. H2B_NOUNIT, // "xxx.x"
  3209. H2B_SHORT, // "xxx.xMH/s"
  3210. H2B_SPACED, // "xxx.x MH/s"
  3211. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3212. };
  3213. enum bfu_floatprec {
  3214. FUP_INTEGER,
  3215. FUP_HASHES,
  3216. FUP_BTC,
  3217. FUP_DIFF,
  3218. };
  3219. static
  3220. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3221. {
  3222. char *s = buf;
  3223. unsigned char prec, i, unit;
  3224. int rv = 0;
  3225. if (unitin == -1)
  3226. {
  3227. unit = 0;
  3228. hashrate_pick_unit(hashrate, &unit);
  3229. }
  3230. else
  3231. unit = unitin;
  3232. hashrate *= 1e12;
  3233. for (i = 0; i < unit; ++i)
  3234. hashrate /= 1000;
  3235. switch (fprec)
  3236. {
  3237. case FUP_HASHES:
  3238. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3239. if (hashrate >= 99.995 || unit < 6)
  3240. prec = 1;
  3241. else
  3242. prec = 2;
  3243. _SNP("%5.*f", prec, hashrate);
  3244. break;
  3245. case FUP_INTEGER:
  3246. _SNP("%3d", (int)hashrate);
  3247. break;
  3248. case FUP_BTC:
  3249. if (hashrate >= 99.995)
  3250. prec = 0;
  3251. else
  3252. prec = 2;
  3253. _SNP("%5.*f", prec, hashrate);
  3254. break;
  3255. case FUP_DIFF:
  3256. if (unit > _unitbase)
  3257. _SNP("%.3g", hashrate);
  3258. else
  3259. _SNP("%u", (unsigned int)hashrate);
  3260. }
  3261. if (fmt != H2B_NOUNIT)
  3262. {
  3263. char uc[3] = {_unitchar[unit], '\0'};
  3264. switch (fmt) {
  3265. case H2B_SPACED:
  3266. _SNP(" ");
  3267. default:
  3268. break;
  3269. case H2B_SHORTV:
  3270. if (isspace(uc[0]))
  3271. uc[0] = '\0';
  3272. }
  3273. if (uc[0] == '\xb5')
  3274. // Convert to UTF-8
  3275. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3276. _SNP("%s%s", uc, measurement);
  3277. }
  3278. return rv;
  3279. }
  3280. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3281. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3282. static
  3283. 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)
  3284. {
  3285. unsigned char unit = 0;
  3286. bool allzero = true;
  3287. int i;
  3288. size_t delimsz = 0;
  3289. char *buf = buflist[0];
  3290. size_t bufsz = bufszlist[0];
  3291. size_t itemwidth = (floatprec ? 5 : 3);
  3292. if (!isarray)
  3293. delimsz = strlen(delim);
  3294. for (i = 0; i < count; ++i)
  3295. if (numbers[i] != 0)
  3296. {
  3297. pick_unit(numbers[i], &unit);
  3298. allzero = false;
  3299. }
  3300. if (allzero)
  3301. unit = _unitbase;
  3302. --count;
  3303. for (i = 0; i < count; ++i)
  3304. {
  3305. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3306. if (isarray)
  3307. {
  3308. buf = buflist[i + 1];
  3309. bufsz = bufszlist[i + 1];
  3310. }
  3311. else
  3312. {
  3313. buf += itemwidth;
  3314. bufsz -= itemwidth;
  3315. if (delimsz > bufsz)
  3316. delimsz = bufsz;
  3317. memcpy(buf, delim, delimsz);
  3318. buf += delimsz;
  3319. bufsz -= delimsz;
  3320. }
  3321. }
  3322. // Last entry has the unit
  3323. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3324. return buflist[0];
  3325. }
  3326. #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)
  3327. #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)
  3328. static
  3329. int percentf3(char * const buf, size_t sz, double p, const double t)
  3330. {
  3331. char *s = buf;
  3332. int rv = 0;
  3333. if (!p)
  3334. _SNP("none");
  3335. else
  3336. if (t <= p)
  3337. _SNP("100%%");
  3338. else
  3339. {
  3340. p /= t;
  3341. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3342. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3343. else
  3344. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3345. _SNP("%.1f%%", p * 100); // "9.1%"
  3346. else
  3347. _SNP("%3.0f%%", p * 100); // " 99%"
  3348. }
  3349. return rv;
  3350. }
  3351. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3352. static
  3353. void test_decimal_width()
  3354. {
  3355. // The pipe character at end of each line should perfectly line up
  3356. char printbuf[512];
  3357. char testbuf1[64];
  3358. char testbuf2[64];
  3359. char testbuf3[64];
  3360. char testbuf4[64];
  3361. double testn;
  3362. int width;
  3363. int saved;
  3364. // Hotspots around 0.1 and 0.01
  3365. saved = -1;
  3366. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3367. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3368. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3369. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3370. if (unlikely((saved != -1) && (width != saved))) {
  3371. ++unittest_failures;
  3372. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3373. applog(LOG_ERR, "%s", printbuf);
  3374. }
  3375. saved = width;
  3376. }
  3377. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3378. saved = -1;
  3379. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3380. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3381. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3382. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3383. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3384. width = utf8_strlen(printbuf);
  3385. if (unlikely((saved != -1) && (width != saved))) {
  3386. ++unittest_failures;
  3387. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3388. applog(LOG_ERR, "%s", printbuf);
  3389. }
  3390. saved = width;
  3391. }
  3392. // Hotspot around unit transition boundary in pick_unit
  3393. saved = -1;
  3394. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3395. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3396. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3397. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3398. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3399. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3400. width = utf8_strlen(printbuf);
  3401. if (unlikely((saved != -1) && (width != saved))) {
  3402. ++unittest_failures;
  3403. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3404. applog(LOG_ERR, "%s", printbuf);
  3405. }
  3406. saved = width;
  3407. }
  3408. }
  3409. #ifdef HAVE_CURSES
  3410. static void adj_width(int var, int *length);
  3411. #endif
  3412. #ifdef HAVE_CURSES
  3413. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3414. static
  3415. 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)
  3416. {
  3417. char rejpcbuf[6];
  3418. char bnbuf[6];
  3419. adj_width(accepted, &awidth);
  3420. adj_width(rejected, &rwidth);
  3421. adj_width(stale, &swidth);
  3422. adj_width(hwerrs, &hwwidth);
  3423. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3424. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3425. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3426. cHr, aHr, uHr,
  3427. awidth, accepted,
  3428. rwidth, rejected,
  3429. swidth, stale,
  3430. rejpcbuf,
  3431. hwwidth, hwerrs,
  3432. bnbuf
  3433. );
  3434. }
  3435. static
  3436. const char *pool_proto_str(const struct pool * const pool)
  3437. {
  3438. if (pool->idle)
  3439. return "Dead ";
  3440. if (pool->has_stratum)
  3441. return "Strtm";
  3442. if (pool->lp_url && pool->proto != pool->lp_proto)
  3443. return "Mixed";
  3444. switch (pool->proto)
  3445. {
  3446. case PLP_GETBLOCKTEMPLATE:
  3447. return " GBT ";
  3448. case PLP_GETWORK:
  3449. return "GWork";
  3450. default:
  3451. return "Alive";
  3452. }
  3453. }
  3454. #endif
  3455. static inline
  3456. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3457. {
  3458. if (!(use_unicode && have_unicode_degrees))
  3459. maybe_unicode = false;
  3460. if (temp && *temp > 0.)
  3461. if (maybe_unicode)
  3462. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3463. else
  3464. snprintf(buf, bufsz, "%4.1fC", *temp);
  3465. else
  3466. {
  3467. if (temp)
  3468. snprintf(buf, bufsz, " ");
  3469. if (maybe_unicode)
  3470. tailsprintf(buf, bufsz, " ");
  3471. }
  3472. tailsprintf(buf, bufsz, " | ");
  3473. }
  3474. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3475. {
  3476. #ifndef HAVE_CURSES
  3477. assert(for_curses == false);
  3478. #endif
  3479. struct device_drv *drv = cgpu->drv;
  3480. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3481. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3482. char rejpcbuf[6];
  3483. char bnbuf[6];
  3484. double dev_runtime;
  3485. if (!opt_show_procs)
  3486. cgpu = cgpu->device;
  3487. dev_runtime = cgpu_runtime(cgpu);
  3488. double rolling, mhashes;
  3489. int accepted, rejected, stale;
  3490. double waccepted;
  3491. double wnotaccepted;
  3492. int hwerrs;
  3493. double bad_diff1, good_diff1;
  3494. rolling = mhashes = waccepted = wnotaccepted = 0;
  3495. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3496. {
  3497. struct cgpu_info *slave = cgpu;
  3498. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3499. {
  3500. slave->utility = slave->accepted / dev_runtime * 60;
  3501. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3502. rolling += slave->rolling;
  3503. mhashes += slave->total_mhashes;
  3504. if (opt_weighed_stats)
  3505. {
  3506. accepted += slave->diff_accepted;
  3507. rejected += slave->diff_rejected;
  3508. stale += slave->diff_stale;
  3509. }
  3510. else
  3511. {
  3512. accepted += slave->accepted;
  3513. rejected += slave->rejected;
  3514. stale += slave->stale;
  3515. }
  3516. waccepted += slave->diff_accepted;
  3517. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3518. hwerrs += slave->hw_errors;
  3519. bad_diff1 += slave->bad_diff1;
  3520. good_diff1 += slave->diff1;
  3521. if (opt_show_procs)
  3522. break;
  3523. }
  3524. }
  3525. double wtotal = (waccepted + wnotaccepted);
  3526. multi_format_unit_array2(
  3527. ((char*[]){cHr, aHr, uHr}),
  3528. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3529. true, "h/s", hashrate_style,
  3530. 3,
  3531. 1e6*rolling,
  3532. 1e6*mhashes / dev_runtime,
  3533. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3534. // Processor representation
  3535. #ifdef HAVE_CURSES
  3536. if (for_curses)
  3537. {
  3538. if (opt_show_procs)
  3539. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3540. else
  3541. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3542. }
  3543. else
  3544. #endif
  3545. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3546. if (include_serial_in_statline && cgpu->dev_serial)
  3547. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3548. if (unlikely(cgpu->status == LIFE_INIT))
  3549. {
  3550. tailsprintf(buf, bufsz, "Initializing...");
  3551. return;
  3552. }
  3553. {
  3554. const size_t bufln = strlen(buf);
  3555. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3556. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3557. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3558. else
  3559. {
  3560. float temp = cgpu->temp;
  3561. if (!opt_show_procs)
  3562. {
  3563. // Find the highest temperature of all processors
  3564. struct cgpu_info *proc = cgpu;
  3565. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3566. if (proc->temp > temp)
  3567. temp = proc->temp;
  3568. }
  3569. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3570. }
  3571. }
  3572. #ifdef HAVE_CURSES
  3573. if (for_curses)
  3574. {
  3575. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3576. const char *cHrStats;
  3577. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3578. bool all_dead = true, all_off = true, all_rdrv = true;
  3579. struct cgpu_info *proc = cgpu;
  3580. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3581. {
  3582. switch (cHrStatsI) {
  3583. default:
  3584. if (proc->status == LIFE_WAIT)
  3585. cHrStatsI = 5;
  3586. case 5:
  3587. if (proc->deven == DEV_RECOVER_ERR)
  3588. cHrStatsI = 4;
  3589. case 4:
  3590. if (proc->deven == DEV_RECOVER)
  3591. cHrStatsI = 3;
  3592. case 3:
  3593. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3594. {
  3595. cHrStatsI = 1;
  3596. all_off = false;
  3597. }
  3598. else
  3599. {
  3600. if (likely(proc->deven == DEV_ENABLED))
  3601. all_off = false;
  3602. if (proc->deven != DEV_RECOVER_DRV)
  3603. all_rdrv = false;
  3604. }
  3605. case 1:
  3606. break;
  3607. }
  3608. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3609. all_dead = false;
  3610. if (opt_show_procs)
  3611. break;
  3612. }
  3613. if (unlikely(all_dead))
  3614. cHrStatsI = 0;
  3615. else
  3616. if (unlikely(all_off))
  3617. cHrStatsI = 2;
  3618. cHrStats = cHrStatsOpt[cHrStatsI];
  3619. if (cHrStatsI == 2 && all_rdrv)
  3620. cHrStats = " RST ";
  3621. format_statline(buf, bufsz,
  3622. cHrStats,
  3623. aHr, uHr,
  3624. accepted, rejected, stale,
  3625. wnotaccepted, waccepted,
  3626. hwerrs,
  3627. bad_diff1, bad_diff1 + good_diff1);
  3628. }
  3629. else
  3630. #endif
  3631. {
  3632. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3633. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3634. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3635. opt_log_interval,
  3636. cHr, aHr, uHr,
  3637. accepted,
  3638. rejected,
  3639. stale,
  3640. rejpcbuf,
  3641. hwerrs,
  3642. bnbuf
  3643. );
  3644. }
  3645. }
  3646. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3647. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3648. static void text_print_status(int thr_id)
  3649. {
  3650. struct cgpu_info *cgpu;
  3651. char logline[256];
  3652. cgpu = get_thr_cgpu(thr_id);
  3653. if (cgpu) {
  3654. get_statline(logline, sizeof(logline), cgpu);
  3655. printf("\n%s\r", logline);
  3656. fflush(stdout);
  3657. }
  3658. }
  3659. #ifdef HAVE_CURSES
  3660. static int attr_bad = A_BOLD;
  3661. #ifdef WIN32
  3662. #define swprintf snwprintf
  3663. #endif
  3664. static
  3665. void bfg_waddstr(WINDOW *win, const char *s)
  3666. {
  3667. const char *p = s;
  3668. int32_t w;
  3669. int wlen;
  3670. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3671. while (true)
  3672. {
  3673. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3674. {
  3675. // Printable ASCII
  3676. ++p;
  3677. }
  3678. if (p != s)
  3679. waddnstr(win, s, p - s);
  3680. w = utf8_decode(p, &wlen);
  3681. s = p += wlen;
  3682. switch(w)
  3683. {
  3684. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3685. case '\0':
  3686. return;
  3687. case 0xb5: // micro symbol
  3688. w = unicode_micro;
  3689. goto default_addch;
  3690. case 0xf000: // "bad" off
  3691. wattroff(win, attr_bad);
  3692. break;
  3693. case 0xf001: // "bad" on
  3694. wattron(win, attr_bad);
  3695. break;
  3696. #ifdef USE_UNICODE
  3697. case '|':
  3698. wadd_wch(win, WACS_VLINE);
  3699. break;
  3700. #endif
  3701. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3702. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3703. if (!use_unicode)
  3704. {
  3705. waddch(win, '-');
  3706. break;
  3707. }
  3708. #ifdef USE_UNICODE
  3709. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3710. break;
  3711. #endif
  3712. case 0x2022:
  3713. if (w > WCHAR_MAX || !iswprint(w))
  3714. w = '*';
  3715. default:
  3716. default_addch:
  3717. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3718. {
  3719. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3720. if (iswprint(REPLACEMENT_CHAR))
  3721. w = REPLACEMENT_CHAR;
  3722. else
  3723. #endif
  3724. w = '?';
  3725. }
  3726. {
  3727. #ifdef USE_UNICODE
  3728. wchar_t wbuf[0x10];
  3729. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3730. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3731. waddnwstr(win, wbuf, wbuflen);
  3732. #else
  3733. wprintw(win, "%lc", (wint_t)w);
  3734. #endif
  3735. }
  3736. }
  3737. }
  3738. }
  3739. static inline
  3740. void bfg_hline(WINDOW *win, int y)
  3741. {
  3742. int maxx, __maybe_unused maxy;
  3743. getmaxyx(win, maxy, maxx);
  3744. #ifdef USE_UNICODE
  3745. if (use_unicode)
  3746. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3747. else
  3748. #endif
  3749. mvwhline(win, y, 0, '-', maxx);
  3750. }
  3751. static
  3752. int bfg_win_linelen(WINDOW * const win)
  3753. {
  3754. int maxx;
  3755. int __maybe_unused y;
  3756. getmaxyx(win, y, maxx);
  3757. return maxx;
  3758. }
  3759. // Spaces until end of line, using current attributes (ie, not completely clear)
  3760. static
  3761. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3762. {
  3763. int x, maxx;
  3764. int __maybe_unused y;
  3765. getmaxyx(win, y, maxx);
  3766. getyx(win, y, x);
  3767. const int space_count = (maxx - x) - offset;
  3768. // Check for negative - terminal too narrow
  3769. if (space_count <= 0)
  3770. return;
  3771. char buf[space_count];
  3772. memset(buf, ' ', space_count);
  3773. waddnstr(win, buf, space_count);
  3774. }
  3775. static int menu_attr = A_REVERSE;
  3776. #define CURBUFSIZ 256
  3777. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3778. char tmp42[CURBUFSIZ]; \
  3779. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3780. wmove(win, y, x); \
  3781. bfg_waddstr(win, tmp42); \
  3782. } while (0)
  3783. #define cg_wprintw(win, fmt, ...) do { \
  3784. char tmp42[CURBUFSIZ]; \
  3785. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3786. bfg_waddstr(win, tmp42); \
  3787. } while (0)
  3788. static
  3789. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3790. {
  3791. struct blockchain_info * const blkchain = goal->blkchain;
  3792. struct block_info * const blkinfo = blkchain->currentblk;
  3793. double income;
  3794. char incomestr[ALLOC_H2B_SHORT+6+1];
  3795. if (blkinfo->height)
  3796. {
  3797. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  3798. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3799. }
  3800. else
  3801. strcpy(incomestr, "?");
  3802. int linelen = bfg_win_linelen(statuswin);
  3803. wmove(statuswin, blky, 0);
  3804. bfg_waddstr(statuswin, " Block");
  3805. if (!goal->is_default)
  3806. linelen -= strlen(goal->name) + 1;
  3807. linelen -= 6; // " Block"
  3808. if (blkinfo->height && blkinfo->height < 1000000)
  3809. {
  3810. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  3811. linelen -= 8;
  3812. }
  3813. bfg_waddstr(statuswin, ":");
  3814. if (linelen > 55)
  3815. bfg_waddstr(statuswin, " ");
  3816. if (linelen >= 65)
  3817. bfg_waddstr(statuswin, "...");
  3818. {
  3819. char hexpbh[0x11];
  3820. if (!(blkinfo->height && blkinfo->height < 1000000))
  3821. {
  3822. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  3823. bfg_waddstr(statuswin, hexpbh);
  3824. }
  3825. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  3826. bfg_waddstr(statuswin, hexpbh);
  3827. }
  3828. if (linelen >= 55)
  3829. bfg_waddstr(statuswin, " ");
  3830. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  3831. if (linelen >= 69)
  3832. bfg_waddstr(statuswin, " ");
  3833. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  3834. if (linelen >= 62)
  3835. {
  3836. if (linelen >= 69)
  3837. bfg_waddstr(statuswin, " ");
  3838. bfg_waddstr(statuswin, "Started:");
  3839. }
  3840. else
  3841. bfg_waddstr(statuswin, "S:");
  3842. if (linelen >= 69)
  3843. bfg_waddstr(statuswin, " ");
  3844. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  3845. if (linelen >= 69)
  3846. bfg_waddstr(statuswin, " ");
  3847. cg_wprintw(statuswin, " I:%s", incomestr);
  3848. if (!goal->is_default)
  3849. cg_wprintw(statuswin, " %s", goal->name);
  3850. wclrtoeol(statuswin);
  3851. }
  3852. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  3853. static
  3854. void update_block_display(void)
  3855. {
  3856. struct mining_goal_info *goal, *tmpgoal;
  3857. int blky = 3, i, total_found_goals = 0;
  3858. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  3859. {
  3860. for (i = 0; i < total_pools; ++i)
  3861. {
  3862. struct pool * const pool = pools[i];
  3863. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  3864. break;
  3865. }
  3866. if (i >= total_pools)
  3867. // no pools using this goal, so it's probably stale anyway
  3868. continue;
  3869. update_block_display_line(blky++, goal);
  3870. ++total_found_goals;
  3871. }
  3872. if (total_found_goals != active_goals)
  3873. {
  3874. active_goals = total_found_goals;
  3875. devcursor = 7 + active_goals;
  3876. switch_logsize();
  3877. }
  3878. }
  3879. static bool pool_unworkable(const struct pool *);
  3880. /* Must be called with curses mutex lock held and curses_active */
  3881. static void curses_print_status(const int ts)
  3882. {
  3883. struct pool *pool = currentpool;
  3884. struct timeval now, tv;
  3885. float efficiency;
  3886. int logdiv;
  3887. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3888. wattron(statuswin, attr_title);
  3889. const int linelen = bfg_win_linelen(statuswin);
  3890. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  3891. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  3892. if (titlelen + 17 < linelen)
  3893. cg_wprintw(statuswin, "version ");
  3894. cg_wprintw(statuswin, VERSION " - ");
  3895. if (titlelen + 9 < linelen)
  3896. cg_wprintw(statuswin, "Started: ");
  3897. else
  3898. if (titlelen + 7 <= linelen)
  3899. cg_wprintw(statuswin, "Start: ");
  3900. cg_wprintw(statuswin, "%s", datestamp);
  3901. timer_set_now(&now);
  3902. {
  3903. unsigned int days, hours;
  3904. div_t d;
  3905. timersub(&now, &miner_started, &tv);
  3906. d = div(tv.tv_sec, 86400);
  3907. days = d.quot;
  3908. d = div(d.rem, 3600);
  3909. hours = d.quot;
  3910. d = div(d.rem, 60);
  3911. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3912. , days
  3913. , (days == 1) ? ' ' : 's'
  3914. , hours
  3915. , d.quot
  3916. , d.rem
  3917. );
  3918. }
  3919. bfg_wspctoeol(statuswin, 0);
  3920. wattroff(statuswin, attr_title);
  3921. wattron(statuswin, menu_attr);
  3922. wmove(statuswin, 1, 0);
  3923. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3924. bfg_wspctoeol(statuswin, 14);
  3925. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3926. wattroff(statuswin, menu_attr);
  3927. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  3928. char poolinfo[20], poolinfo2[20];
  3929. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  3930. double lowdiff = DBL_MAX, highdiff = -1;
  3931. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  3932. time_t oldest_work_restart = time(NULL) + 1;
  3933. struct pool *oldest_work_restart_pool = pools[0];
  3934. for (int i = 0; i < total_pools; ++i)
  3935. {
  3936. if (pool_unworkable(pools[i]))
  3937. continue;
  3938. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  3939. pool = pools[i];
  3940. ++workable_pools;
  3941. if (poolinfooff < sizeof(poolinfo))
  3942. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  3943. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  3944. if (pool_stats->last_diff < lowdiff)
  3945. {
  3946. lowdiff = pool_stats->last_diff;
  3947. lowdiff_pool = pool;
  3948. }
  3949. if (pool_stats->last_diff > highdiff)
  3950. {
  3951. highdiff = pool_stats->last_diff;
  3952. highdiff_pool = pool;
  3953. }
  3954. if (oldest_work_restart >= pool->work_restart_time)
  3955. {
  3956. oldest_work_restart = pool->work_restart_time;
  3957. oldest_work_restart_pool = pool;
  3958. }
  3959. }
  3960. if (unlikely(!workable_pools))
  3961. goto no_workable_pools;
  3962. if (workable_pools == 1)
  3963. goto one_workable_pool;
  3964. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  3965. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  3966. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  3967. else
  3968. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  3969. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  3970. poolinfo2,
  3971. lowdiff_pool->diff,
  3972. (lowdiff == highdiff) ? "" : "-",
  3973. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  3974. pool->goal->have_longpoll ? '+' : '-',
  3975. oldest_work_restart_pool->work_restart_timestamp);
  3976. }
  3977. else
  3978. if (pool_unworkable(pool))
  3979. {
  3980. no_workable_pools: ;
  3981. wattron(statuswin, attr_bad);
  3982. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  3983. wattroff(statuswin, attr_bad);
  3984. }
  3985. else
  3986. {
  3987. one_workable_pool: ;
  3988. char pooladdr[19];
  3989. {
  3990. const char *rawaddr = pool->sockaddr_url;
  3991. BFGINIT(rawaddr, pool->rpc_url);
  3992. size_t pooladdrlen = strlen(rawaddr);
  3993. if (pooladdrlen > 20)
  3994. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  3995. else
  3996. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  3997. }
  3998. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  3999. pool->pool_no, pooladdr, pool->diff,
  4000. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4001. pool->work_restart_timestamp,
  4002. pool->rpc_user);
  4003. }
  4004. wclrtoeol(statuswin);
  4005. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4006. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4007. ts,
  4008. total_go + total_ro,
  4009. new_blocks,
  4010. total_submitting,
  4011. multi_format_unit2(bwstr, sizeof(bwstr),
  4012. false, "B/s", H2B_SHORT, "/", 2,
  4013. (float)(total_bytes_rcvd / total_secs),
  4014. (float)(total_bytes_sent / total_secs)),
  4015. efficiency,
  4016. best_share);
  4017. wclrtoeol(statuswin);
  4018. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4019. bfg_waddstr(statuswin, statusline);
  4020. wclrtoeol(statuswin);
  4021. int devdiv = devcursor - 2;
  4022. logdiv = statusy - 1;
  4023. bfg_hline(statuswin, devdiv);
  4024. bfg_hline(statuswin, logdiv);
  4025. #ifdef USE_UNICODE
  4026. if (use_unicode)
  4027. {
  4028. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4029. if (opt_show_procs && !opt_compact)
  4030. offset += max_lpdigits; // proc letter(s)
  4031. if (have_unicode_degrees)
  4032. ++offset; // degrees symbol
  4033. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4034. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4035. offset += 24; // hashrates etc
  4036. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4037. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4038. }
  4039. #endif
  4040. }
  4041. static void adj_width(int var, int *length)
  4042. {
  4043. if ((int)(log10(var) + 1) > *length)
  4044. (*length)++;
  4045. }
  4046. static int dev_width;
  4047. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4048. {
  4049. char logline[256];
  4050. int ypos;
  4051. if (opt_compact)
  4052. return;
  4053. /* Check this isn't out of the window size */
  4054. if (opt_show_procs)
  4055. ypos = cgpu->cgminer_id;
  4056. else
  4057. {
  4058. if (cgpu->proc_id)
  4059. return;
  4060. ypos = cgpu->device_line_id;
  4061. }
  4062. ypos += devsummaryYOffset;
  4063. if (ypos < 0)
  4064. return;
  4065. ypos += devcursor - 1;
  4066. if (ypos >= statusy - 1)
  4067. return;
  4068. if (wmove(statuswin, ypos, 0) == ERR)
  4069. return;
  4070. get_statline2(logline, sizeof(logline), cgpu, true);
  4071. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4072. wattron(statuswin, A_REVERSE);
  4073. bfg_waddstr(statuswin, logline);
  4074. wattroff(statuswin, A_REVERSE);
  4075. wclrtoeol(statuswin);
  4076. }
  4077. static
  4078. void _refresh_devstatus(const bool already_have_lock) {
  4079. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4080. int i;
  4081. if (unlikely(!total_devices))
  4082. {
  4083. const int ypos = devcursor - 1;
  4084. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4085. {
  4086. wattron(statuswin, attr_bad);
  4087. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4088. wclrtoeol(statuswin);
  4089. wattroff(statuswin, attr_bad);
  4090. }
  4091. }
  4092. for (i = 0; i < total_devices; i++)
  4093. curses_print_devstatus(get_devices(i));
  4094. touchwin(statuswin);
  4095. wrefresh(statuswin);
  4096. if (!already_have_lock)
  4097. unlock_curses();
  4098. }
  4099. }
  4100. #define refresh_devstatus() _refresh_devstatus(false)
  4101. #endif
  4102. static void print_status(int thr_id)
  4103. {
  4104. if (!curses_active)
  4105. text_print_status(thr_id);
  4106. }
  4107. #ifdef HAVE_CURSES
  4108. static
  4109. bool set_statusy(int maxy)
  4110. {
  4111. if (loginput_size)
  4112. {
  4113. maxy -= loginput_size;
  4114. if (maxy < 0)
  4115. maxy = 0;
  4116. }
  4117. if (logstart < maxy)
  4118. maxy = logstart;
  4119. if (statusy == maxy)
  4120. return false;
  4121. statusy = maxy;
  4122. logcursor = statusy;
  4123. return true;
  4124. }
  4125. /* Check for window resize. Called with curses mutex locked */
  4126. static inline void change_logwinsize(void)
  4127. {
  4128. int x, y, logx, logy;
  4129. getmaxyx(mainwin, y, x);
  4130. if (x < 80 || y < 25)
  4131. return;
  4132. if (y > statusy + 2 && statusy < logstart) {
  4133. set_statusy(y - 2);
  4134. mvwin(logwin, logcursor, 0);
  4135. bfg_wresize(statuswin, statusy, x);
  4136. }
  4137. y -= logcursor;
  4138. getmaxyx(logwin, logy, logx);
  4139. /* Detect screen size change */
  4140. if (x != logx || y != logy)
  4141. bfg_wresize(logwin, y, x);
  4142. }
  4143. static void check_winsizes(void)
  4144. {
  4145. if (!use_curses)
  4146. return;
  4147. if (curses_active_locked()) {
  4148. int y, x;
  4149. x = getmaxx(statuswin);
  4150. if (set_statusy(LINES - 2))
  4151. {
  4152. erase();
  4153. bfg_wresize(statuswin, statusy, x);
  4154. getmaxyx(mainwin, y, x);
  4155. y -= logcursor;
  4156. bfg_wresize(logwin, y, x);
  4157. mvwin(logwin, logcursor, 0);
  4158. }
  4159. unlock_curses();
  4160. }
  4161. }
  4162. static int device_line_id_count;
  4163. static void switch_logsize(void)
  4164. {
  4165. if (curses_active_locked()) {
  4166. if (opt_compact) {
  4167. logstart = devcursor - 1;
  4168. logcursor = logstart + 1;
  4169. } else {
  4170. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4171. logstart = devcursor + total_lines;
  4172. logcursor = logstart;
  4173. }
  4174. unlock_curses();
  4175. }
  4176. check_winsizes();
  4177. update_block_display();
  4178. }
  4179. /* For mandatory printing when mutex is already locked */
  4180. void _wlog(const char *str)
  4181. {
  4182. static bool newline;
  4183. size_t end = strlen(str) - 1;
  4184. if (newline)
  4185. bfg_waddstr(logwin, "\n");
  4186. if (str[end] == '\n')
  4187. {
  4188. char *s;
  4189. newline = true;
  4190. s = alloca(end + 1);
  4191. memcpy(s, str, end);
  4192. s[end] = '\0';
  4193. str = s;
  4194. }
  4195. else
  4196. newline = false;
  4197. bfg_waddstr(logwin, str);
  4198. }
  4199. /* Mandatory printing */
  4200. void _wlogprint(const char *str)
  4201. {
  4202. if (curses_active_locked()) {
  4203. _wlog(str);
  4204. unlock_curses();
  4205. }
  4206. }
  4207. #endif
  4208. #ifdef HAVE_CURSES
  4209. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4210. {
  4211. bool high_prio;
  4212. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4213. if (curses_active)
  4214. {
  4215. if (!loginput_size || high_prio) {
  4216. wlog(" %s %s\n", datetime, str);
  4217. if (high_prio) {
  4218. touchwin(logwin);
  4219. wrefresh(logwin);
  4220. }
  4221. }
  4222. return true;
  4223. }
  4224. return false;
  4225. }
  4226. void clear_logwin(void)
  4227. {
  4228. if (curses_active_locked()) {
  4229. wclear(logwin);
  4230. unlock_curses();
  4231. }
  4232. }
  4233. void logwin_update(void)
  4234. {
  4235. if (curses_active_locked()) {
  4236. touchwin(logwin);
  4237. wrefresh(logwin);
  4238. unlock_curses();
  4239. }
  4240. }
  4241. #endif
  4242. void enable_pool(struct pool * const pool)
  4243. {
  4244. if (pool->enabled != POOL_ENABLED) {
  4245. mutex_lock(&lp_lock);
  4246. enabled_pools++;
  4247. pool->enabled = POOL_ENABLED;
  4248. pthread_cond_broadcast(&lp_cond);
  4249. mutex_unlock(&lp_lock);
  4250. if (pool->prio < current_pool()->prio)
  4251. switch_pools(pool);
  4252. }
  4253. }
  4254. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4255. {
  4256. if (pool->enabled == POOL_DISABLED)
  4257. /* had been manually disabled before */
  4258. return;
  4259. if (pool->enabled != POOL_ENABLED)
  4260. {
  4261. /* has been programmatically disabled already, just change to the new status directly */
  4262. pool->enabled = enable_status;
  4263. return;
  4264. }
  4265. /* Fall into the lock area */
  4266. mutex_lock(&lp_lock);
  4267. --enabled_pools;
  4268. pool->enabled = enable_status;
  4269. mutex_unlock(&lp_lock);
  4270. if (pool == current_pool())
  4271. switch_pools(NULL);
  4272. }
  4273. static
  4274. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4275. struct cgpu_info *cgpu;
  4276. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  4277. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4278. const double tgtdiff = work->work_difficulty;
  4279. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4280. char where[20];
  4281. cgpu = get_thr_cgpu(work->thr_id);
  4282. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4283. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4284. if (total_pools > 1)
  4285. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4286. else
  4287. where[0] = '\0';
  4288. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4289. disp,
  4290. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4291. cgpu->proc_repr,
  4292. where,
  4293. shrdiffdisp, tgtdiffdisp,
  4294. reason,
  4295. resubmit ? "(resubmit)" : "",
  4296. worktime
  4297. );
  4298. }
  4299. static bool test_work_current(struct work *);
  4300. static void _submit_work_async(struct work *);
  4301. static
  4302. void maybe_local_submit(const struct work *work)
  4303. {
  4304. #if BLKMAKER_VERSION > 3
  4305. if (unlikely(work->block && work->tr))
  4306. {
  4307. // This is a block with a full template (GBT)
  4308. // Regardless of the result, submit to local bitcoind(s) as well
  4309. struct work *work_cp;
  4310. for (int i = 0; i < total_pools; ++i)
  4311. {
  4312. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4313. continue;
  4314. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4315. work_cp = copy_work(work);
  4316. work_cp->pool = pools[i];
  4317. work_cp->do_foreign_submit = true;
  4318. _submit_work_async(work_cp);
  4319. }
  4320. }
  4321. #endif
  4322. }
  4323. static
  4324. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4325. {
  4326. if (json_is_string(res))
  4327. return res;
  4328. if ( (res = json_object_get(val, "reject-reason")) )
  4329. return res;
  4330. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4331. return res;
  4332. return NULL;
  4333. }
  4334. static
  4335. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4336. {
  4337. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4338. return j ? json_string_value(j) : NULL;
  4339. }
  4340. static
  4341. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4342. {
  4343. if (!s)
  4344. {
  4345. if (bufsz)
  4346. buf[0] = '\0';
  4347. return 0;
  4348. }
  4349. int p = snprintf(buf, bufsz, " (%s", s);
  4350. if (p >= bufsz - 1)
  4351. p = bufsz - 2;
  4352. strcpy(&buf[p], ")");
  4353. return p + 1;
  4354. }
  4355. /* Theoretically threads could race when modifying accepted and
  4356. * rejected values but the chance of two submits completing at the
  4357. * same time is zero so there is no point adding extra locking */
  4358. static void
  4359. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4360. /*char *hashshow,*/ bool resubmit, char *worktime)
  4361. {
  4362. struct pool *pool = work->pool;
  4363. struct cgpu_info *cgpu;
  4364. cgpu = get_thr_cgpu(work->thr_id);
  4365. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4366. struct mining_goal_info * const goal = pool->goal;
  4367. mutex_lock(&stats_lock);
  4368. cgpu->accepted++;
  4369. total_accepted++;
  4370. pool->accepted++;
  4371. cgpu->diff_accepted += work->work_difficulty;
  4372. total_diff_accepted += work->work_difficulty;
  4373. pool->diff_accepted += work->work_difficulty;
  4374. goal->diff_accepted += work->work_difficulty;
  4375. mutex_unlock(&stats_lock);
  4376. pool->seq_rejects = 0;
  4377. cgpu->last_share_pool = pool->pool_no;
  4378. cgpu->last_share_pool_time = time(NULL);
  4379. cgpu->last_share_diff = work->work_difficulty;
  4380. pool->last_share_time = cgpu->last_share_pool_time;
  4381. pool->last_share_diff = work->work_difficulty;
  4382. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4383. if (!QUIET) {
  4384. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4385. }
  4386. sharelog("accept", work);
  4387. if (opt_shares && total_diff_accepted >= opt_shares) {
  4388. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4389. kill_work();
  4390. return;
  4391. }
  4392. /* Detect if a pool that has been temporarily disabled for
  4393. * continually rejecting shares has started accepting shares.
  4394. * This will only happen with the work returned from a
  4395. * longpoll */
  4396. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4397. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4398. enable_pool(pool);
  4399. }
  4400. if (unlikely(work->block)) {
  4401. // Force moving on to this new block :)
  4402. struct work fakework;
  4403. memset(&fakework, 0, sizeof(fakework));
  4404. fakework.pool = work->pool;
  4405. // Copy block version, bits, and time from share
  4406. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4407. memcpy(&fakework.data[68], &work->data[68], 8);
  4408. // Set prevblock to winning hash (swap32'd)
  4409. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4410. test_work_current(&fakework);
  4411. }
  4412. }
  4413. else
  4414. if (!hash_target_check(work->hash, work->target))
  4415. {
  4416. // This was submitted despite failing the proper target
  4417. // Quietly ignore the reject
  4418. char reason[32];
  4419. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4420. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4421. } else {
  4422. mutex_lock(&stats_lock);
  4423. cgpu->rejected++;
  4424. total_rejected++;
  4425. pool->rejected++;
  4426. cgpu->diff_rejected += work->work_difficulty;
  4427. total_diff_rejected += work->work_difficulty;
  4428. pool->diff_rejected += work->work_difficulty;
  4429. pool->seq_rejects++;
  4430. mutex_unlock(&stats_lock);
  4431. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4432. if (!QUIET) {
  4433. char disposition[36] = "reject";
  4434. char reason[32];
  4435. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4436. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4437. if (reason[0])
  4438. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4439. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4440. sharelog(disposition, work);
  4441. }
  4442. /* Once we have more than a nominal amount of sequential rejects,
  4443. * at least 10 and more than 3 mins at the current utility,
  4444. * disable the pool because some pool error is likely to have
  4445. * ensued. Do not do this if we know the share just happened to
  4446. * be stale due to networking delays.
  4447. */
  4448. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4449. double utility = total_accepted / total_secs * 60;
  4450. if (pool->seq_rejects > utility * 3) {
  4451. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4452. pool->pool_no, pool->seq_rejects);
  4453. disable_pool(pool, POOL_REJECTING);
  4454. pool->seq_rejects = 0;
  4455. }
  4456. }
  4457. }
  4458. maybe_local_submit(work);
  4459. }
  4460. static char *submit_upstream_work_request(struct work *work)
  4461. {
  4462. char *hexstr = NULL;
  4463. char *s, *sd;
  4464. struct pool *pool = work->pool;
  4465. if (work->tr)
  4466. {
  4467. blktemplate_t * const tmpl = work->tr->tmpl;
  4468. json_t *req;
  4469. unsigned char data[80];
  4470. swap32yes(data, work->data, 80 / 4);
  4471. #if BLKMAKER_VERSION > 3
  4472. if (work->do_foreign_submit)
  4473. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4474. else
  4475. #endif
  4476. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4477. s = json_dumps(req, 0);
  4478. json_decref(req);
  4479. sd = malloc(161);
  4480. bin2hex(sd, data, 80);
  4481. } else {
  4482. /* build hex string */
  4483. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4484. bin2hex(hexstr, work->data, sizeof(work->data));
  4485. /* build JSON-RPC request */
  4486. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4487. s = realloc_strcat(s, hexstr);
  4488. s = realloc_strcat(s, "\" ], \"id\":1}");
  4489. free(hexstr);
  4490. sd = s;
  4491. }
  4492. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4493. if (work->tr)
  4494. free(sd);
  4495. else
  4496. s = realloc_strcat(s, "\n");
  4497. return s;
  4498. }
  4499. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4500. json_t *res, *err;
  4501. bool rc = false;
  4502. int thr_id = work->thr_id;
  4503. struct pool *pool = work->pool;
  4504. struct timeval tv_submit_reply;
  4505. time_t ts_submit_reply;
  4506. char worktime[200] = "";
  4507. cgtime(&tv_submit_reply);
  4508. ts_submit_reply = time(NULL);
  4509. if (unlikely(!val)) {
  4510. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4511. if (!pool_tset(pool, &pool->submit_fail)) {
  4512. total_ro++;
  4513. pool->remotefail_occasions++;
  4514. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4515. }
  4516. goto out;
  4517. } else if (pool_tclear(pool, &pool->submit_fail))
  4518. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4519. res = json_object_get(val, "result");
  4520. err = json_object_get(val, "error");
  4521. if (!QUIET) {
  4522. if (opt_worktime) {
  4523. char workclone[20];
  4524. struct tm _tm;
  4525. struct tm *tm, tm_getwork, tm_submit_reply;
  4526. tm = &_tm;
  4527. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4528. (struct timeval *)&(work->tv_getwork));
  4529. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4530. (struct timeval *)&(work->tv_getwork_reply));
  4531. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4532. (struct timeval *)&(work->tv_work_start));
  4533. double work_to_submit = tdiff(ptv_submit,
  4534. (struct timeval *)&(work->tv_work_found));
  4535. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4536. int diffplaces = 3;
  4537. localtime_r(&work->ts_getwork, tm);
  4538. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4539. localtime_r(&ts_submit_reply, tm);
  4540. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4541. if (work->clone) {
  4542. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4543. tdiff((struct timeval *)&(work->tv_cloned),
  4544. (struct timeval *)&(work->tv_getwork_reply)));
  4545. }
  4546. else
  4547. strcpy(workclone, "O");
  4548. if (work->work_difficulty < 1)
  4549. diffplaces = 6;
  4550. snprintf(worktime, sizeof(worktime),
  4551. " <-%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",
  4552. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  4553. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  4554. work->getwork_mode, diffplaces, work->work_difficulty,
  4555. tm_getwork.tm_hour, tm_getwork.tm_min,
  4556. tm_getwork.tm_sec, getwork_time, workclone,
  4557. getwork_to_work, work_time, work_to_submit, submit_time,
  4558. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4559. tm_submit_reply.tm_sec);
  4560. }
  4561. }
  4562. share_result(val, res, err, work, resubmit, worktime);
  4563. if (!opt_realquiet)
  4564. print_status(thr_id);
  4565. if (!want_per_device_stats) {
  4566. char logline[256];
  4567. struct cgpu_info *cgpu;
  4568. cgpu = get_thr_cgpu(thr_id);
  4569. get_statline(logline, sizeof(logline), cgpu);
  4570. applog(LOG_INFO, "%s", logline);
  4571. }
  4572. json_decref(val);
  4573. rc = true;
  4574. out:
  4575. return rc;
  4576. }
  4577. /* Specifies whether we can use this pool for work or not. */
  4578. static bool pool_unworkable(const struct pool * const pool)
  4579. {
  4580. if (pool->idle)
  4581. return true;
  4582. if (pool->enabled != POOL_ENABLED)
  4583. return true;
  4584. if (pool->has_stratum && !pool->stratum_active)
  4585. return true;
  4586. return false;
  4587. }
  4588. static
  4589. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4590. {
  4591. if (pool->enabled != POOL_ENABLED)
  4592. return false;
  4593. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4594. return true;
  4595. if (!cp)
  4596. cp = current_pool();
  4597. return (pool == cp);
  4598. }
  4599. static
  4600. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4601. {
  4602. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4603. }
  4604. static
  4605. bool pool_supports_block_change_notification(struct pool * const pool)
  4606. {
  4607. return pool->has_stratum || pool->lp_url;
  4608. }
  4609. static
  4610. bool pool_has_active_block_change_notification(struct pool * const pool)
  4611. {
  4612. return pool->stratum_active || pool->lp_active;
  4613. }
  4614. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4615. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4616. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4617. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4618. * rolling average per 10 minutes and if pools start getting more, it biases
  4619. * away from them to distribute work evenly. The share count is reset to the
  4620. * rolling average every 10 minutes to not send all work to one pool after it
  4621. * has been disabled/out for an extended period. */
  4622. static struct pool *select_balanced(struct pool *cp)
  4623. {
  4624. int i, lowest = cp->shares;
  4625. struct pool *ret = cp, *failover_pool = NULL;
  4626. for (i = 0; i < total_pools; i++) {
  4627. struct pool *pool = pools[i];
  4628. if (pool_unworkable(pool))
  4629. continue;
  4630. if (pool->failover_only)
  4631. {
  4632. BFGINIT(failover_pool, pool);
  4633. continue;
  4634. }
  4635. if (pool->shares < lowest) {
  4636. lowest = pool->shares;
  4637. ret = pool;
  4638. }
  4639. }
  4640. if (pool_unworkable(ret) && failover_pool)
  4641. ret = failover_pool;
  4642. ret->shares++;
  4643. return ret;
  4644. }
  4645. static bool pool_active(struct pool *, bool pinging);
  4646. static void pool_died(struct pool *);
  4647. static struct pool *priority_pool(int choice);
  4648. static bool pool_unusable(struct pool *pool);
  4649. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4650. * it has any quota left. */
  4651. static inline struct pool *select_pool(bool lagging)
  4652. {
  4653. static int rotating_pool = 0;
  4654. struct pool *pool, *cp;
  4655. bool avail = false;
  4656. int tested, i;
  4657. retry:
  4658. cp = current_pool();
  4659. if (pool_strategy == POOL_BALANCE) {
  4660. pool = select_balanced(cp);
  4661. if (pool_unworkable(pool))
  4662. goto simple_failover;
  4663. goto out;
  4664. }
  4665. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4666. pool = cp;
  4667. goto out;
  4668. } else
  4669. pool = NULL;
  4670. for (i = 0; i < total_pools; i++) {
  4671. struct pool *tp = pools[i];
  4672. if (tp->quota_used < tp->quota_gcd) {
  4673. avail = true;
  4674. break;
  4675. }
  4676. }
  4677. /* There are no pools with quota, so reset them. */
  4678. if (!avail) {
  4679. for (i = 0; i < total_pools; i++)
  4680. pools[i]->quota_used = 0;
  4681. if (++rotating_pool >= total_pools)
  4682. rotating_pool = 0;
  4683. }
  4684. /* Try to find the first pool in the rotation that is usable */
  4685. tested = 0;
  4686. while (!pool && tested++ < total_pools) {
  4687. pool = pools[rotating_pool];
  4688. if (pool->quota_used++ < pool->quota_gcd) {
  4689. if (!pool_unworkable(pool))
  4690. break;
  4691. /* Failover-only flag for load-balance means distribute
  4692. * unused quota to priority pool 0. */
  4693. if (opt_fail_only)
  4694. priority_pool(0)->quota_used--;
  4695. }
  4696. pool = NULL;
  4697. if (++rotating_pool >= total_pools)
  4698. rotating_pool = 0;
  4699. }
  4700. simple_failover:
  4701. /* If there are no alive pools with quota, choose according to
  4702. * priority. */
  4703. if (!pool) {
  4704. for (i = 0; i < total_pools; i++) {
  4705. struct pool *tp = priority_pool(i);
  4706. if (!pool_unusable(tp)) {
  4707. pool = tp;
  4708. break;
  4709. }
  4710. }
  4711. }
  4712. /* If still nothing is usable, use the current pool */
  4713. if (!pool)
  4714. pool = cp;
  4715. out:
  4716. if (!pool_actively_in_use(pool, cp))
  4717. {
  4718. if (!pool_active(pool, false))
  4719. {
  4720. pool_died(pool);
  4721. goto retry;
  4722. }
  4723. pool_tclear(pool, &pool->idle);
  4724. }
  4725. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4726. return pool;
  4727. }
  4728. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4729. double target_diff(const unsigned char *target)
  4730. {
  4731. double targ = 0;
  4732. signed int i;
  4733. for (i = 31; i >= 0; --i)
  4734. targ = (targ * 0x100) + target[i];
  4735. return DIFFEXACTONE / (targ ?: 1);
  4736. }
  4737. /*
  4738. * Calculate the work share difficulty
  4739. */
  4740. static void calc_diff(struct work *work, int known)
  4741. {
  4742. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4743. double difficulty;
  4744. if (!known) {
  4745. work->work_difficulty = target_diff(work->target);
  4746. } else
  4747. work->work_difficulty = known;
  4748. difficulty = work->work_difficulty;
  4749. pool_stats->last_diff = difficulty;
  4750. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4751. if (difficulty == pool_stats->min_diff)
  4752. pool_stats->min_diff_count++;
  4753. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4754. pool_stats->min_diff = difficulty;
  4755. pool_stats->min_diff_count = 1;
  4756. }
  4757. if (difficulty == pool_stats->max_diff)
  4758. pool_stats->max_diff_count++;
  4759. else if (difficulty > pool_stats->max_diff) {
  4760. pool_stats->max_diff = difficulty;
  4761. pool_stats->max_diff_count = 1;
  4762. }
  4763. }
  4764. static void gen_stratum_work(struct pool *, struct work *);
  4765. static void pool_update_work_restart_time(struct pool *);
  4766. static void restart_threads(void);
  4767. static uint32_t benchmark_blkhdr[20];
  4768. static const int benchmark_update_interval = 1;
  4769. static
  4770. void *benchmark_intense_work_update_thread(void *userp)
  4771. {
  4772. pthread_detach(pthread_self());
  4773. RenameThread("benchmark-intense");
  4774. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4775. struct pool * const pool = userp;
  4776. struct stratum_work * const swork = &pool->swork;
  4777. uint8_t * const blkhdr = swork->header1;
  4778. while (true)
  4779. {
  4780. sleep(benchmark_update_interval);
  4781. cg_wlock(&pool->data_lock);
  4782. for (int i = 36; --i >= 0; )
  4783. if (++blkhdr[i])
  4784. break;
  4785. cg_wunlock(&pool->data_lock);
  4786. struct work *work = make_work();
  4787. gen_stratum_work(pool, work);
  4788. pool->swork.work_restart_id = ++pool->work_restart_id;
  4789. pool_update_work_restart_time(pool);
  4790. test_work_current(work);
  4791. free_work(work);
  4792. restart_threads();
  4793. }
  4794. return NULL;
  4795. }
  4796. static
  4797. void setup_benchmark_pool()
  4798. {
  4799. struct pool *pool;
  4800. want_longpoll = false;
  4801. // Temporarily disable opt_benchmark to avoid auto-removal
  4802. opt_benchmark = false;
  4803. pool = add_pool();
  4804. opt_benchmark = true;
  4805. pool->rpc_url = malloc(255);
  4806. strcpy(pool->rpc_url, "Benchmark");
  4807. pool_set_uri(pool, pool->rpc_url);
  4808. pool->rpc_user = pool->rpc_url;
  4809. pool->rpc_pass = pool->rpc_url;
  4810. enable_pool(pool);
  4811. pool->idle = false;
  4812. successful_connect = true;
  4813. {
  4814. uint32_t * const blkhdr = benchmark_blkhdr;
  4815. blkhdr[2] = htobe32(1);
  4816. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  4817. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  4818. }
  4819. {
  4820. struct stratum_work * const swork = &pool->swork;
  4821. const int branchcount = 15; // 1 MB block
  4822. const size_t branchdatasz = branchcount * 0x20;
  4823. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  4824. bytes_resize(&swork->coinbase, coinbase_sz);
  4825. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  4826. swork->nonce2_offset = 0;
  4827. bytes_resize(&swork->merkle_bin, branchdatasz);
  4828. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  4829. swork->merkles = branchcount;
  4830. swork->header1[0] = '\xff';
  4831. memset(&swork->header1[1], '\0', 34);
  4832. swork->header1[35] = '\x01';
  4833. swork->ntime = 0x7fffffff;
  4834. timer_unset(&swork->tv_received);
  4835. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  4836. set_target_to_pdiff(swork->target, opt_scrypt ? (1./0x10000) : 1.);
  4837. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  4838. pool->nonce2 = 0;
  4839. }
  4840. if (opt_benchmark_intense)
  4841. {
  4842. pthread_t pth;
  4843. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  4844. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  4845. }
  4846. }
  4847. void get_benchmark_work(struct work *work, bool use_swork)
  4848. {
  4849. if (use_swork)
  4850. {
  4851. struct timeval tv_now;
  4852. timer_set_now(&tv_now);
  4853. gen_stratum_work(pools[0], work);
  4854. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4855. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  4856. return;
  4857. }
  4858. struct pool * const pool = pools[0];
  4859. uint32_t * const blkhdr = benchmark_blkhdr;
  4860. for (int i = 16; i >= 0; --i)
  4861. if (++blkhdr[i])
  4862. break;
  4863. memcpy(&work->data[ 0], blkhdr, 80);
  4864. memcpy(&work->data[80], workpadding_bin, 48);
  4865. char hex[161];
  4866. bin2hex(hex, work->data, 80);
  4867. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  4868. calc_midstate(work);
  4869. memcpy(work->target, pool->swork.target, sizeof(work->target));
  4870. work->mandatory = true;
  4871. work->pool = pools[0];
  4872. cgtime(&work->tv_getwork);
  4873. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4874. copy_time(&work->tv_staged, &work->tv_getwork);
  4875. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4876. calc_diff(work, 0);
  4877. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  4878. }
  4879. static void wake_gws(void);
  4880. static void update_last_work(struct work *work)
  4881. {
  4882. if (!work->tr)
  4883. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4884. return;
  4885. struct pool *pool = work->pool;
  4886. mutex_lock(&pool->last_work_lock);
  4887. if (pool->last_work_copy)
  4888. free_work(pool->last_work_copy);
  4889. pool->last_work_copy = copy_work(work);
  4890. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4891. mutex_unlock(&pool->last_work_lock);
  4892. }
  4893. static
  4894. void gbt_req_target(json_t *req)
  4895. {
  4896. json_t *j;
  4897. json_t *n;
  4898. if (!request_target_str)
  4899. return;
  4900. j = json_object_get(req, "params");
  4901. if (!j)
  4902. {
  4903. n = json_array();
  4904. if (!n)
  4905. return;
  4906. if (json_object_set_new(req, "params", n))
  4907. goto erradd;
  4908. j = n;
  4909. }
  4910. n = json_array_get(j, 0);
  4911. if (!n)
  4912. {
  4913. n = json_object();
  4914. if (!n)
  4915. return;
  4916. if (json_array_append_new(j, n))
  4917. goto erradd;
  4918. }
  4919. j = n;
  4920. n = json_string(request_target_str);
  4921. if (!n)
  4922. return;
  4923. if (json_object_set_new(j, "target", n))
  4924. goto erradd;
  4925. return;
  4926. erradd:
  4927. json_decref(n);
  4928. }
  4929. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  4930. {
  4931. char *rpc_req;
  4932. clean_work(work);
  4933. switch (proto) {
  4934. case PLP_GETWORK:
  4935. work->getwork_mode = GETWORK_MODE_POOL;
  4936. return strdup(getwork_req);
  4937. case PLP_GETBLOCKTEMPLATE:
  4938. work->getwork_mode = GETWORK_MODE_GBT;
  4939. blktemplate_t * const tmpl = blktmpl_create();
  4940. if (!tmpl)
  4941. goto gbtfail2;
  4942. work->tr = tmpl_makeref(tmpl);
  4943. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  4944. if (!caps)
  4945. goto gbtfail;
  4946. caps |= GBT_LONGPOLL;
  4947. #if BLKMAKER_VERSION > 1
  4948. if ((bytes_len(&opt_coinbase_script) || have_at_least_one_getcbaddr) && get_mining_goal("default") == pool->goal)
  4949. caps |= GBT_CBVALUE;
  4950. #endif
  4951. json_t *req = blktmpl_request_jansson(caps, lpid);
  4952. if (!req)
  4953. goto gbtfail;
  4954. if (probe)
  4955. gbt_req_target(req);
  4956. rpc_req = json_dumps(req, 0);
  4957. if (!rpc_req)
  4958. goto gbtfail;
  4959. json_decref(req);
  4960. return rpc_req;
  4961. default:
  4962. return NULL;
  4963. }
  4964. return NULL;
  4965. gbtfail:
  4966. tmpl_decref(work->tr);
  4967. work->tr = NULL;
  4968. gbtfail2:
  4969. return NULL;
  4970. }
  4971. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  4972. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  4973. static const char *pool_protocol_name(enum pool_protocol proto)
  4974. {
  4975. switch (proto) {
  4976. case PLP_GETBLOCKTEMPLATE:
  4977. return "getblocktemplate";
  4978. case PLP_GETWORK:
  4979. return "getwork";
  4980. default:
  4981. return "UNKNOWN";
  4982. }
  4983. }
  4984. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4985. {
  4986. switch (proto) {
  4987. case PLP_GETBLOCKTEMPLATE:
  4988. if (want_getwork)
  4989. return PLP_GETWORK;
  4990. default:
  4991. return PLP_NONE;
  4992. }
  4993. }
  4994. static bool get_upstream_work(struct work *work, CURL *curl)
  4995. {
  4996. struct pool *pool = work->pool;
  4997. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4998. struct timeval tv_elapsed;
  4999. json_t *val = NULL;
  5000. bool rc = false;
  5001. char *url;
  5002. enum pool_protocol proto;
  5003. char *rpc_req;
  5004. if (pool->proto == PLP_NONE)
  5005. pool->proto = PLP_GETBLOCKTEMPLATE;
  5006. tryagain:
  5007. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5008. work->pool = pool;
  5009. if (!rpc_req)
  5010. return false;
  5011. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5012. url = pool->rpc_url;
  5013. cgtime(&work->tv_getwork);
  5014. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5015. false, &work->rolltime, pool, false);
  5016. pool_stats->getwork_attempts++;
  5017. free(rpc_req);
  5018. if (likely(val)) {
  5019. rc = work_decode(pool, work, val);
  5020. if (unlikely(!rc))
  5021. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5022. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5023. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5024. pool->proto = proto;
  5025. goto tryagain;
  5026. } else
  5027. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5028. cgtime(&work->tv_getwork_reply);
  5029. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5030. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5031. pool_stats->getwork_wait_rolling /= 1.63;
  5032. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5033. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5034. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5035. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5036. }
  5037. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5038. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5039. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5040. }
  5041. pool_stats->getwork_calls++;
  5042. work->pool = pool;
  5043. work->longpoll = false;
  5044. calc_diff(work, 0);
  5045. total_getworks++;
  5046. pool->getwork_requested++;
  5047. if (rc)
  5048. update_last_work(work);
  5049. if (likely(val))
  5050. json_decref(val);
  5051. return rc;
  5052. }
  5053. #ifdef HAVE_CURSES
  5054. static void disable_curses(void)
  5055. {
  5056. if (curses_active_locked()) {
  5057. use_curses = false;
  5058. curses_active = false;
  5059. leaveok(logwin, false);
  5060. leaveok(statuswin, false);
  5061. leaveok(mainwin, false);
  5062. nocbreak();
  5063. echo();
  5064. delwin(logwin);
  5065. delwin(statuswin);
  5066. delwin(mainwin);
  5067. endwin();
  5068. #ifdef WIN32
  5069. // Move the cursor to after curses output.
  5070. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5071. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5072. COORD coord;
  5073. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5074. coord.X = 0;
  5075. coord.Y = csbi.dwSize.Y - 1;
  5076. SetConsoleCursorPosition(hout, coord);
  5077. }
  5078. #endif
  5079. unlock_curses();
  5080. }
  5081. }
  5082. #endif
  5083. static void __kill_work(void)
  5084. {
  5085. struct cgpu_info *cgpu;
  5086. struct thr_info *thr;
  5087. int i;
  5088. if (!successful_connect)
  5089. return;
  5090. applog(LOG_INFO, "Received kill message");
  5091. shutting_down = true;
  5092. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5093. notifier_wake(submit_waiting_notifier);
  5094. #ifdef USE_LIBMICROHTTPD
  5095. httpsrv_stop();
  5096. #endif
  5097. applog(LOG_DEBUG, "Killing off watchpool thread");
  5098. /* Kill the watchpool thread */
  5099. thr = &control_thr[watchpool_thr_id];
  5100. thr_info_cancel(thr);
  5101. applog(LOG_DEBUG, "Killing off watchdog thread");
  5102. /* Kill the watchdog thread */
  5103. thr = &control_thr[watchdog_thr_id];
  5104. thr_info_cancel(thr);
  5105. applog(LOG_DEBUG, "Shutting down mining threads");
  5106. for (i = 0; i < mining_threads; i++) {
  5107. thr = get_thread(i);
  5108. if (!thr)
  5109. continue;
  5110. cgpu = thr->cgpu;
  5111. if (!cgpu)
  5112. continue;
  5113. if (!cgpu->threads)
  5114. continue;
  5115. cgpu->shutdown = true;
  5116. thr->work_restart = true;
  5117. notifier_wake(thr->notifier);
  5118. notifier_wake(thr->work_restart_notifier);
  5119. }
  5120. sleep(1);
  5121. applog(LOG_DEBUG, "Killing off mining threads");
  5122. /* Kill the mining threads*/
  5123. for (i = 0; i < mining_threads; i++) {
  5124. thr = get_thread(i);
  5125. if (!thr)
  5126. continue;
  5127. cgpu = thr->cgpu;
  5128. if (cgpu->threads)
  5129. {
  5130. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5131. thr_info_cancel(thr);
  5132. }
  5133. cgpu->status = LIFE_DEAD2;
  5134. }
  5135. /* Stop the others */
  5136. applog(LOG_DEBUG, "Killing off API thread");
  5137. thr = &control_thr[api_thr_id];
  5138. thr_info_cancel(thr);
  5139. }
  5140. /* This should be the common exit path */
  5141. void kill_work(void)
  5142. {
  5143. __kill_work();
  5144. quit(0, "Shutdown signal received.");
  5145. }
  5146. static
  5147. #ifdef WIN32
  5148. #ifndef _WIN64
  5149. const
  5150. #endif
  5151. #endif
  5152. char **initial_args;
  5153. void _bfg_clean_up(bool);
  5154. void app_restart(void)
  5155. {
  5156. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5157. __kill_work();
  5158. _bfg_clean_up(true);
  5159. #if defined(unix) || defined(__APPLE__)
  5160. if (forkpid > 0) {
  5161. kill(forkpid, SIGTERM);
  5162. forkpid = 0;
  5163. }
  5164. #endif
  5165. execv(initial_args[0], initial_args);
  5166. applog(LOG_WARNING, "Failed to restart application");
  5167. }
  5168. static void sighandler(int __maybe_unused sig)
  5169. {
  5170. /* Restore signal handlers so we can still quit if kill_work fails */
  5171. sigaction(SIGTERM, &termhandler, NULL);
  5172. sigaction(SIGINT, &inthandler, NULL);
  5173. kill_work();
  5174. }
  5175. static void start_longpoll(void);
  5176. static void stop_longpoll(void);
  5177. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5178. * this pool. */
  5179. static void recruit_curl(struct pool *pool)
  5180. {
  5181. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5182. if (unlikely(!ce))
  5183. quit(1, "Failed to calloc in recruit_curl");
  5184. ce->curl = curl_easy_init();
  5185. if (unlikely(!ce->curl))
  5186. quit(1, "Failed to init in recruit_curl");
  5187. LL_PREPEND(pool->curllist, ce);
  5188. pool->curls++;
  5189. }
  5190. /* Grab an available curl if there is one. If not, then recruit extra curls
  5191. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5192. * and there are already 5 curls in circulation. Limit total number to the
  5193. * number of mining threads per pool as well to prevent blasting a pool during
  5194. * network delays/outages. */
  5195. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5196. {
  5197. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5198. bool recruited = false;
  5199. struct curl_ent *ce;
  5200. mutex_lock(&pool->pool_lock);
  5201. retry:
  5202. if (!pool->curls) {
  5203. recruit_curl(pool);
  5204. recruited = true;
  5205. } else if (!pool->curllist) {
  5206. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5207. if (!blocking) {
  5208. mutex_unlock(&pool->pool_lock);
  5209. return NULL;
  5210. }
  5211. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5212. goto retry;
  5213. } else {
  5214. recruit_curl(pool);
  5215. recruited = true;
  5216. }
  5217. }
  5218. ce = pool->curllist;
  5219. LL_DELETE(pool->curllist, ce);
  5220. mutex_unlock(&pool->pool_lock);
  5221. if (recruited)
  5222. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5223. return ce;
  5224. }
  5225. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5226. {
  5227. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5228. }
  5229. __maybe_unused
  5230. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5231. {
  5232. return pop_curl_entry3(pool, 1);
  5233. }
  5234. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5235. {
  5236. mutex_lock(&pool->pool_lock);
  5237. if (!ce || !ce->curl)
  5238. quithere(1, "Attempted to add NULL");
  5239. LL_PREPEND(pool->curllist, ce);
  5240. cgtime(&ce->tv);
  5241. pthread_cond_broadcast(&pool->cr_cond);
  5242. mutex_unlock(&pool->pool_lock);
  5243. }
  5244. bool stale_work(struct work *work, bool share);
  5245. static inline bool should_roll(struct work *work)
  5246. {
  5247. struct timeval now;
  5248. time_t expiry;
  5249. if (!pool_actively_in_use(work->pool, NULL))
  5250. return false;
  5251. if (stale_work(work, false))
  5252. return false;
  5253. if (work->rolltime > opt_scantime)
  5254. expiry = work->rolltime;
  5255. else
  5256. expiry = opt_scantime;
  5257. expiry = expiry * 2 / 3;
  5258. /* We shouldn't roll if we're unlikely to get one shares' duration
  5259. * work out of doing so */
  5260. cgtime(&now);
  5261. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5262. return false;
  5263. return true;
  5264. }
  5265. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5266. * reject blocks as invalid. */
  5267. static inline bool can_roll(struct work *work)
  5268. {
  5269. if (work->stratum)
  5270. return false;
  5271. if (!(work->pool && !work->clone))
  5272. return false;
  5273. if (work->tr)
  5274. {
  5275. if (stale_work(work, false))
  5276. return false;
  5277. return blkmk_work_left(work->tr->tmpl);
  5278. }
  5279. return (work->rolltime &&
  5280. work->rolls < 7000 && !stale_work(work, false));
  5281. }
  5282. static void roll_work(struct work *work)
  5283. {
  5284. if (work->tr)
  5285. {
  5286. struct timeval tv_now;
  5287. cgtime(&tv_now);
  5288. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5289. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5290. swap32yes(work->data, work->data, 80 / 4);
  5291. calc_midstate(work);
  5292. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5293. } else {
  5294. uint32_t *work_ntime;
  5295. uint32_t ntime;
  5296. work_ntime = (uint32_t *)(work->data + 68);
  5297. ntime = be32toh(*work_ntime);
  5298. ntime++;
  5299. *work_ntime = htobe32(ntime);
  5300. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5301. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5302. }
  5303. local_work++;
  5304. work->rolls++;
  5305. work->blk.nonce = 0;
  5306. /* This is now a different work item so it needs a different ID for the
  5307. * hashtable */
  5308. work->id = total_work++;
  5309. }
  5310. /* Duplicates any dynamically allocated arrays within the work struct to
  5311. * prevent a copied work struct from freeing ram belonging to another struct */
  5312. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5313. {
  5314. int id = work->id;
  5315. clean_work(work);
  5316. memcpy(work, base_work, sizeof(struct work));
  5317. /* Keep the unique new id assigned during make_work to prevent copied
  5318. * work from having the same id. */
  5319. work->id = id;
  5320. if (base_work->job_id)
  5321. work->job_id = strdup(base_work->job_id);
  5322. if (base_work->nonce1)
  5323. work->nonce1 = strdup(base_work->nonce1);
  5324. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5325. if (base_work->tr)
  5326. tmpl_incref(base_work->tr);
  5327. if (noffset)
  5328. {
  5329. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5330. uint32_t ntime = be32toh(*work_ntime);
  5331. ntime += noffset;
  5332. *work_ntime = htobe32(ntime);
  5333. }
  5334. if (work->device_data_dup_func)
  5335. work->device_data = work->device_data_dup_func(work);
  5336. }
  5337. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5338. * for all dynamically allocated arrays within the struct. noffset is used for
  5339. * when a driver has internally rolled the ntime, noffset is a relative value.
  5340. * The macro copy_work() calls this function with an noffset of 0. */
  5341. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5342. {
  5343. struct work *work = make_work();
  5344. _copy_work(work, base_work, noffset);
  5345. return work;
  5346. }
  5347. void __copy_work(struct work *work, const struct work *base_work)
  5348. {
  5349. _copy_work(work, base_work, 0);
  5350. }
  5351. static struct work *make_clone(struct work *work)
  5352. {
  5353. struct work *work_clone = copy_work(work);
  5354. work_clone->clone = true;
  5355. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5356. work_clone->longpoll = false;
  5357. work_clone->mandatory = false;
  5358. /* Make cloned work appear slightly older to bias towards keeping the
  5359. * master work item which can be further rolled */
  5360. work_clone->tv_staged.tv_sec -= 1;
  5361. return work_clone;
  5362. }
  5363. static void stage_work(struct work *work);
  5364. static bool clone_available(void)
  5365. {
  5366. struct work *work_clone = NULL, *work, *tmp;
  5367. bool cloned = false;
  5368. mutex_lock(stgd_lock);
  5369. if (!staged_rollable)
  5370. goto out_unlock;
  5371. HASH_ITER(hh, staged_work, work, tmp) {
  5372. if (can_roll(work) && should_roll(work)) {
  5373. roll_work(work);
  5374. work_clone = make_clone(work);
  5375. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5376. roll_work(work);
  5377. cloned = true;
  5378. break;
  5379. }
  5380. }
  5381. out_unlock:
  5382. mutex_unlock(stgd_lock);
  5383. if (cloned) {
  5384. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5385. stage_work(work_clone);
  5386. }
  5387. return cloned;
  5388. }
  5389. static void pool_died(struct pool *pool)
  5390. {
  5391. mutex_lock(&lp_lock);
  5392. if (!pool_tset(pool, &pool->idle)) {
  5393. cgtime(&pool->tv_idle);
  5394. pthread_cond_broadcast(&lp_cond);
  5395. mutex_unlock(&lp_lock);
  5396. if (pool == current_pool()) {
  5397. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5398. switch_pools(NULL);
  5399. } else
  5400. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5401. }
  5402. else
  5403. mutex_unlock(&lp_lock);
  5404. }
  5405. bool stale_work(struct work *work, bool share)
  5406. {
  5407. unsigned work_expiry;
  5408. struct pool *pool;
  5409. uint32_t block_id;
  5410. unsigned getwork_delay;
  5411. block_id = ((uint32_t*)work->data)[1];
  5412. pool = work->pool;
  5413. struct mining_goal_info * const goal = pool->goal;
  5414. struct blockchain_info * const blkchain = goal->blkchain;
  5415. /* Technically the rolltime should be correct but some pools
  5416. * advertise a broken expire= that is lower than a meaningful
  5417. * scantime */
  5418. if (work->rolltime >= opt_scantime || work->tr)
  5419. work_expiry = work->rolltime;
  5420. else
  5421. work_expiry = opt_expiry;
  5422. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5423. if (work_expiry > max_expiry)
  5424. work_expiry = max_expiry;
  5425. if (share) {
  5426. /* If the share isn't on this pool's latest block, it's stale */
  5427. if (pool->block_id && pool->block_id != block_id)
  5428. {
  5429. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5430. return true;
  5431. }
  5432. /* If the pool doesn't want old shares, then any found in work before
  5433. * the most recent longpoll is stale */
  5434. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5435. {
  5436. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5437. return true;
  5438. }
  5439. } else {
  5440. /* If this work isn't for the latest Bitcoin block, it's stale */
  5441. /* But only care about the current pool if failover-only */
  5442. if (enabled_pools <= 1 || opt_fail_only) {
  5443. if (pool->block_id && block_id != pool->block_id)
  5444. {
  5445. 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);
  5446. return true;
  5447. }
  5448. } else {
  5449. if (block_id != blkchain->currentblk->block_id)
  5450. {
  5451. 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);
  5452. return true;
  5453. }
  5454. }
  5455. /* If the pool has asked us to restart since this work, it's stale */
  5456. if (work->work_restart_id != pool->work_restart_id)
  5457. {
  5458. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5459. return true;
  5460. }
  5461. if (pool->has_stratum && work->job_id) {
  5462. bool same_job;
  5463. if (!pool->stratum_active || !pool->stratum_notify) {
  5464. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5465. return true;
  5466. }
  5467. same_job = true;
  5468. cg_rlock(&pool->data_lock);
  5469. if (strcmp(work->job_id, pool->swork.job_id))
  5470. same_job = false;
  5471. cg_runlock(&pool->data_lock);
  5472. if (!same_job) {
  5473. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5474. return true;
  5475. }
  5476. }
  5477. /* Factor in the average getwork delay of this pool, rounding it up to
  5478. * the nearest second */
  5479. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5480. if (unlikely(work_expiry <= getwork_delay + 5))
  5481. work_expiry = 5;
  5482. else
  5483. work_expiry -= getwork_delay;
  5484. }
  5485. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5486. if (elapsed_since_staged > work_expiry) {
  5487. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5488. return true;
  5489. }
  5490. /* If the user only wants strict failover, any work from a pool other than
  5491. * the current one is always considered stale */
  5492. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5493. {
  5494. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5495. return true;
  5496. }
  5497. return false;
  5498. }
  5499. double share_diff(const struct work *work)
  5500. {
  5501. double ret;
  5502. bool new_best = false;
  5503. ret = target_diff(work->hash);
  5504. cg_wlock(&control_lock);
  5505. if (unlikely(ret > best_diff)) {
  5506. new_best = true;
  5507. best_diff = ret;
  5508. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5509. }
  5510. if (unlikely(ret > work->pool->best_diff))
  5511. work->pool->best_diff = ret;
  5512. cg_wunlock(&control_lock);
  5513. if (unlikely(new_best))
  5514. applog(LOG_INFO, "New best share: %s", best_share);
  5515. return ret;
  5516. }
  5517. static
  5518. void work_check_for_block(struct work * const work)
  5519. {
  5520. struct pool * const pool = work->pool;
  5521. struct mining_goal_info * const goal = pool->goal;
  5522. work->share_diff = share_diff(work);
  5523. if (unlikely(work->share_diff >= goal->current_diff)) {
  5524. work->block = true;
  5525. work->pool->solved++;
  5526. found_blocks++;
  5527. work->mandatory = true;
  5528. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5529. }
  5530. }
  5531. static void submit_discard_share2(const char *reason, struct work *work)
  5532. {
  5533. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5534. sharelog(reason, work);
  5535. mutex_lock(&stats_lock);
  5536. ++total_stale;
  5537. ++cgpu->stale;
  5538. ++(work->pool->stale_shares);
  5539. total_diff_stale += work->work_difficulty;
  5540. cgpu->diff_stale += work->work_difficulty;
  5541. work->pool->diff_stale += work->work_difficulty;
  5542. mutex_unlock(&stats_lock);
  5543. }
  5544. static void submit_discard_share(struct work *work)
  5545. {
  5546. submit_discard_share2("discard", work);
  5547. }
  5548. struct submit_work_state {
  5549. struct work *work;
  5550. bool resubmit;
  5551. struct curl_ent *ce;
  5552. int failures;
  5553. struct timeval tv_staleexpire;
  5554. char *s;
  5555. struct timeval tv_submit;
  5556. struct submit_work_state *next;
  5557. };
  5558. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5559. {
  5560. long *p_timeout_us = userp;
  5561. const long max_ms = LONG_MAX / 1000;
  5562. if (max_ms < timeout_ms)
  5563. timeout_ms = max_ms;
  5564. *p_timeout_us = timeout_ms * 1000;
  5565. return 0;
  5566. }
  5567. static void sws_has_ce(struct submit_work_state *sws)
  5568. {
  5569. struct pool *pool = sws->work->pool;
  5570. sws->s = submit_upstream_work_request(sws->work);
  5571. cgtime(&sws->tv_submit);
  5572. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5573. }
  5574. static struct submit_work_state *begin_submission(struct work *work)
  5575. {
  5576. struct pool *pool;
  5577. struct submit_work_state *sws = NULL;
  5578. pool = work->pool;
  5579. sws = malloc(sizeof(*sws));
  5580. *sws = (struct submit_work_state){
  5581. .work = work,
  5582. };
  5583. work_check_for_block(work);
  5584. if (stale_work(work, true)) {
  5585. work->stale = true;
  5586. if (opt_submit_stale)
  5587. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5588. else if (pool->submit_old)
  5589. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5590. else {
  5591. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5592. submit_discard_share(work);
  5593. goto out;
  5594. }
  5595. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5596. }
  5597. if (work->stratum) {
  5598. char *s;
  5599. s = malloc(1024);
  5600. sws->s = s;
  5601. } else {
  5602. /* submit solution to bitcoin via JSON-RPC */
  5603. sws->ce = pop_curl_entry2(pool, false);
  5604. if (sws->ce) {
  5605. sws_has_ce(sws);
  5606. } else {
  5607. sws->next = pool->sws_waiting_on_curl;
  5608. pool->sws_waiting_on_curl = sws;
  5609. if (sws->next)
  5610. applog(LOG_DEBUG, "submit_thread queuing submission");
  5611. else
  5612. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5613. }
  5614. }
  5615. return sws;
  5616. out:
  5617. free(sws);
  5618. return NULL;
  5619. }
  5620. static bool retry_submission(struct submit_work_state *sws)
  5621. {
  5622. struct work *work = sws->work;
  5623. struct pool *pool = work->pool;
  5624. sws->resubmit = true;
  5625. if ((!work->stale) && stale_work(work, true)) {
  5626. work->stale = true;
  5627. if (opt_submit_stale)
  5628. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5629. else if (pool->submit_old)
  5630. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5631. else {
  5632. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5633. submit_discard_share(work);
  5634. return false;
  5635. }
  5636. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5637. }
  5638. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5639. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5640. submit_discard_share(work);
  5641. return false;
  5642. }
  5643. else if (work->stale) {
  5644. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5645. {
  5646. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5647. submit_discard_share(work);
  5648. return false;
  5649. }
  5650. }
  5651. /* pause, then restart work-request loop */
  5652. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5653. cgtime(&sws->tv_submit);
  5654. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5655. return true;
  5656. }
  5657. static void free_sws(struct submit_work_state *sws)
  5658. {
  5659. free(sws->s);
  5660. free_work(sws->work);
  5661. free(sws);
  5662. }
  5663. static void *submit_work_thread(__maybe_unused void *userdata)
  5664. {
  5665. int wip = 0;
  5666. CURLM *curlm;
  5667. long curlm_timeout_us = -1;
  5668. struct timeval curlm_timer;
  5669. struct submit_work_state *sws, **swsp;
  5670. struct submit_work_state *write_sws = NULL;
  5671. unsigned tsreduce = 0;
  5672. pthread_detach(pthread_self());
  5673. RenameThread("submit_work");
  5674. applog(LOG_DEBUG, "Creating extra submit work thread");
  5675. curlm = curl_multi_init();
  5676. curlm_timeout_us = -1;
  5677. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5678. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5679. fd_set rfds, wfds, efds;
  5680. int maxfd;
  5681. struct timeval tv_timeout, tv_now;
  5682. int n;
  5683. CURLMsg *cm;
  5684. FD_ZERO(&rfds);
  5685. while (1) {
  5686. mutex_lock(&submitting_lock);
  5687. total_submitting -= tsreduce;
  5688. tsreduce = 0;
  5689. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5690. notifier_read(submit_waiting_notifier);
  5691. }
  5692. // Receive any new submissions
  5693. while (submit_waiting) {
  5694. struct work *work = submit_waiting;
  5695. DL_DELETE(submit_waiting, work);
  5696. if ( (sws = begin_submission(work)) ) {
  5697. if (sws->ce)
  5698. curl_multi_add_handle(curlm, sws->ce->curl);
  5699. else if (sws->s) {
  5700. sws->next = write_sws;
  5701. write_sws = sws;
  5702. }
  5703. ++wip;
  5704. }
  5705. else {
  5706. --total_submitting;
  5707. free_work(work);
  5708. }
  5709. }
  5710. if (unlikely(shutting_down && !wip))
  5711. break;
  5712. mutex_unlock(&submitting_lock);
  5713. FD_ZERO(&rfds);
  5714. FD_ZERO(&wfds);
  5715. FD_ZERO(&efds);
  5716. tv_timeout.tv_sec = -1;
  5717. // Setup cURL with select
  5718. // Need to call perform to ensure the timeout gets updated
  5719. curl_multi_perform(curlm, &n);
  5720. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5721. if (curlm_timeout_us >= 0)
  5722. {
  5723. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5724. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5725. }
  5726. // Setup waiting stratum submissions with select
  5727. for (sws = write_sws; sws; sws = sws->next)
  5728. {
  5729. struct pool *pool = sws->work->pool;
  5730. int fd = pool->sock;
  5731. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5732. continue;
  5733. FD_SET(fd, &wfds);
  5734. set_maxfd(&maxfd, fd);
  5735. }
  5736. // Setup "submit waiting" notifier with select
  5737. FD_SET(submit_waiting_notifier[0], &rfds);
  5738. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5739. // Wait for something interesting to happen :)
  5740. cgtime(&tv_now);
  5741. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5742. FD_ZERO(&rfds);
  5743. continue;
  5744. }
  5745. // Handle any stratum ready-to-write results
  5746. for (swsp = &write_sws; (sws = *swsp); ) {
  5747. struct work *work = sws->work;
  5748. struct pool *pool = work->pool;
  5749. int fd = pool->sock;
  5750. bool sessionid_match;
  5751. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5752. next_write_sws:
  5753. // TODO: Check if stale, possibly discard etc
  5754. swsp = &sws->next;
  5755. continue;
  5756. }
  5757. cg_rlock(&pool->data_lock);
  5758. // 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
  5759. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5760. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  5761. cg_runlock(&pool->data_lock);
  5762. if (!sessionid_match)
  5763. {
  5764. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5765. submit_discard_share2("disconnect", work);
  5766. ++tsreduce;
  5767. next_write_sws_del:
  5768. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5769. FD_CLR(fd, &wfds);
  5770. // Delete sws for this submission, since we're done with it
  5771. *swsp = sws->next;
  5772. free_sws(sws);
  5773. --wip;
  5774. continue;
  5775. }
  5776. char *s = sws->s;
  5777. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5778. int sshare_id;
  5779. uint32_t nonce;
  5780. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  5781. char noncehex[9];
  5782. char ntimehex[9];
  5783. sshare->work = copy_work(work);
  5784. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5785. nonce = *((uint32_t *)(work->data + 76));
  5786. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5787. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5788. mutex_lock(&sshare_lock);
  5789. /* Give the stratum share a unique id */
  5790. sshare_id =
  5791. sshare->id = swork_id++;
  5792. HASH_ADD_INT(stratum_shares, id, sshare);
  5793. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5794. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5795. mutex_unlock(&sshare_lock);
  5796. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5797. if (likely(stratum_send(pool, s, strlen(s)))) {
  5798. if (pool_tclear(pool, &pool->submit_fail))
  5799. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5800. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5801. goto next_write_sws_del;
  5802. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5803. // Undo stuff
  5804. mutex_lock(&sshare_lock);
  5805. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5806. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5807. if (sshare)
  5808. HASH_DEL(stratum_shares, sshare);
  5809. mutex_unlock(&sshare_lock);
  5810. if (sshare)
  5811. {
  5812. free_work(sshare->work);
  5813. free(sshare);
  5814. }
  5815. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5816. total_ro++;
  5817. pool->remotefail_occasions++;
  5818. if (!sshare)
  5819. goto next_write_sws_del;
  5820. goto next_write_sws;
  5821. }
  5822. }
  5823. // Handle any cURL activities
  5824. curl_multi_perform(curlm, &n);
  5825. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5826. if (cm->msg == CURLMSG_DONE)
  5827. {
  5828. bool finished;
  5829. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5830. curl_multi_remove_handle(curlm, cm->easy_handle);
  5831. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5832. if (!finished) {
  5833. if (retry_submission(sws))
  5834. curl_multi_add_handle(curlm, sws->ce->curl);
  5835. else
  5836. finished = true;
  5837. }
  5838. if (finished) {
  5839. --wip;
  5840. ++tsreduce;
  5841. struct pool *pool = sws->work->pool;
  5842. if (pool->sws_waiting_on_curl) {
  5843. pool->sws_waiting_on_curl->ce = sws->ce;
  5844. sws_has_ce(pool->sws_waiting_on_curl);
  5845. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5846. curl_multi_add_handle(curlm, sws->ce->curl);
  5847. } else {
  5848. push_curl_entry(sws->ce, sws->work->pool);
  5849. }
  5850. free_sws(sws);
  5851. }
  5852. }
  5853. }
  5854. }
  5855. assert(!write_sws);
  5856. mutex_unlock(&submitting_lock);
  5857. curl_multi_cleanup(curlm);
  5858. applog(LOG_DEBUG, "submit_work thread exiting");
  5859. return NULL;
  5860. }
  5861. /* Find the pool that currently has the highest priority */
  5862. static struct pool *priority_pool(int choice)
  5863. {
  5864. struct pool *ret = NULL;
  5865. int i;
  5866. for (i = 0; i < total_pools; i++) {
  5867. struct pool *pool = pools[i];
  5868. if (pool->prio == choice) {
  5869. ret = pool;
  5870. break;
  5871. }
  5872. }
  5873. if (unlikely(!ret)) {
  5874. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5875. return pools[choice];
  5876. }
  5877. return ret;
  5878. }
  5879. int prioritize_pools(char *param, int *pid)
  5880. {
  5881. char *ptr, *next;
  5882. int i, pr, prio = 0;
  5883. if (total_pools == 0) {
  5884. return MSG_NOPOOL;
  5885. }
  5886. if (param == NULL || *param == '\0') {
  5887. return MSG_MISPID;
  5888. }
  5889. bool pools_changed[total_pools];
  5890. int new_prio[total_pools];
  5891. for (i = 0; i < total_pools; ++i)
  5892. pools_changed[i] = false;
  5893. next = param;
  5894. while (next && *next) {
  5895. ptr = next;
  5896. next = strchr(ptr, ',');
  5897. if (next)
  5898. *(next++) = '\0';
  5899. i = atoi(ptr);
  5900. if (i < 0 || i >= total_pools) {
  5901. *pid = i;
  5902. return MSG_INVPID;
  5903. }
  5904. if (pools_changed[i]) {
  5905. *pid = i;
  5906. return MSG_DUPPID;
  5907. }
  5908. pools_changed[i] = true;
  5909. new_prio[i] = prio++;
  5910. }
  5911. // Only change them if no errors
  5912. for (i = 0; i < total_pools; i++) {
  5913. if (pools_changed[i])
  5914. pools[i]->prio = new_prio[i];
  5915. }
  5916. // In priority order, cycle through the unchanged pools and append them
  5917. for (pr = 0; pr < total_pools; pr++)
  5918. for (i = 0; i < total_pools; i++) {
  5919. if (!pools_changed[i] && pools[i]->prio == pr) {
  5920. pools[i]->prio = prio++;
  5921. pools_changed[i] = true;
  5922. break;
  5923. }
  5924. }
  5925. if (current_pool()->prio)
  5926. switch_pools(NULL);
  5927. return MSG_POOLPRIO;
  5928. }
  5929. void validate_pool_priorities(void)
  5930. {
  5931. // TODO: this should probably do some sort of logging
  5932. int i, j;
  5933. bool used[total_pools];
  5934. bool valid[total_pools];
  5935. for (i = 0; i < total_pools; i++)
  5936. used[i] = valid[i] = false;
  5937. for (i = 0; i < total_pools; i++) {
  5938. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5939. if (!used[pools[i]->prio]) {
  5940. valid[i] = true;
  5941. used[pools[i]->prio] = true;
  5942. }
  5943. }
  5944. }
  5945. for (i = 0; i < total_pools; i++) {
  5946. if (!valid[i]) {
  5947. for (j = 0; j < total_pools; j++) {
  5948. if (!used[j]) {
  5949. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5950. pools[i]->prio = j;
  5951. used[j] = true;
  5952. break;
  5953. }
  5954. }
  5955. }
  5956. }
  5957. }
  5958. static void clear_pool_work(struct pool *pool);
  5959. /* Specifies whether we can switch to this pool or not. */
  5960. static bool pool_unusable(struct pool *pool)
  5961. {
  5962. if (pool->idle)
  5963. return true;
  5964. if (pool->enabled != POOL_ENABLED)
  5965. return true;
  5966. return false;
  5967. }
  5968. void switch_pools(struct pool *selected)
  5969. {
  5970. struct pool *pool, *last_pool, *failover_pool = NULL;
  5971. int i, pool_no, next_pool;
  5972. if (selected)
  5973. enable_pool(selected);
  5974. cg_wlock(&control_lock);
  5975. last_pool = currentpool;
  5976. pool_no = currentpool->pool_no;
  5977. /* Switch selected to pool number 0 and move the rest down */
  5978. if (selected) {
  5979. if (selected->prio != 0) {
  5980. for (i = 0; i < total_pools; i++) {
  5981. pool = pools[i];
  5982. if (pool->prio < selected->prio)
  5983. pool->prio++;
  5984. }
  5985. selected->prio = 0;
  5986. }
  5987. }
  5988. switch (pool_strategy) {
  5989. /* All of these set to the master pool */
  5990. case POOL_BALANCE:
  5991. case POOL_FAILOVER:
  5992. case POOL_LOADBALANCE:
  5993. for (i = 0; i < total_pools; i++) {
  5994. pool = priority_pool(i);
  5995. if (pool_unusable(pool))
  5996. continue;
  5997. pool_no = pool->pool_no;
  5998. break;
  5999. }
  6000. break;
  6001. /* Both of these simply increment and cycle */
  6002. case POOL_ROUNDROBIN:
  6003. case POOL_ROTATE:
  6004. if (selected && !selected->idle) {
  6005. pool_no = selected->pool_no;
  6006. break;
  6007. }
  6008. next_pool = pool_no;
  6009. /* Select the next alive pool */
  6010. for (i = 1; i < total_pools; i++) {
  6011. next_pool++;
  6012. if (next_pool >= total_pools)
  6013. next_pool = 0;
  6014. pool = pools[next_pool];
  6015. if (pool_unusable(pool))
  6016. continue;
  6017. if (pool->failover_only)
  6018. {
  6019. BFGINIT(failover_pool, pool);
  6020. continue;
  6021. }
  6022. pool_no = next_pool;
  6023. break;
  6024. }
  6025. break;
  6026. default:
  6027. break;
  6028. }
  6029. pool = pools[pool_no];
  6030. if (pool_unusable(pool) && failover_pool)
  6031. pool = failover_pool;
  6032. currentpool = pool;
  6033. cg_wunlock(&control_lock);
  6034. mutex_lock(&lp_lock);
  6035. pthread_cond_broadcast(&lp_cond);
  6036. mutex_unlock(&lp_lock);
  6037. /* Set the lagging flag to avoid pool not providing work fast enough
  6038. * messages in failover only mode since we have to get all fresh work
  6039. * as in restart_threads */
  6040. if (opt_fail_only)
  6041. pool_tset(pool, &pool->lagging);
  6042. if (pool != last_pool)
  6043. {
  6044. pool->block_id = 0;
  6045. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6046. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6047. if (pool_localgen(pool) || opt_fail_only)
  6048. clear_pool_work(last_pool);
  6049. }
  6050. }
  6051. mutex_lock(&lp_lock);
  6052. pthread_cond_broadcast(&lp_cond);
  6053. mutex_unlock(&lp_lock);
  6054. #ifdef HAVE_CURSES
  6055. update_block_display();
  6056. #endif
  6057. }
  6058. static void discard_work(struct work *work)
  6059. {
  6060. if (!work->clone && !work->rolls && !work->mined) {
  6061. if (work->pool) {
  6062. work->pool->discarded_work++;
  6063. work->pool->quota_used--;
  6064. work->pool->works--;
  6065. }
  6066. total_discarded++;
  6067. applog(LOG_DEBUG, "Discarded work");
  6068. } else
  6069. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6070. free_work(work);
  6071. }
  6072. static void wake_gws(void)
  6073. {
  6074. mutex_lock(stgd_lock);
  6075. pthread_cond_signal(&gws_cond);
  6076. mutex_unlock(stgd_lock);
  6077. }
  6078. static void discard_stale(void)
  6079. {
  6080. struct work *work, *tmp;
  6081. int stale = 0;
  6082. mutex_lock(stgd_lock);
  6083. HASH_ITER(hh, staged_work, work, tmp) {
  6084. if (stale_work(work, false)) {
  6085. HASH_DEL(staged_work, work);
  6086. discard_work(work);
  6087. stale++;
  6088. staged_full = false;
  6089. }
  6090. }
  6091. pthread_cond_signal(&gws_cond);
  6092. mutex_unlock(stgd_lock);
  6093. if (stale)
  6094. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6095. }
  6096. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6097. {
  6098. bool rv;
  6099. struct timeval tv, orig;
  6100. ldiv_t d;
  6101. d = ldiv(ustime, 1000000);
  6102. tv = (struct timeval){
  6103. .tv_sec = d.quot,
  6104. .tv_usec = d.rem,
  6105. };
  6106. orig = work->tv_staged;
  6107. timersub(&orig, &tv, &work->tv_staged);
  6108. rv = stale_work(work, share);
  6109. work->tv_staged = orig;
  6110. return rv;
  6111. }
  6112. static
  6113. void pool_update_work_restart_time(struct pool * const pool)
  6114. {
  6115. pool->work_restart_time = time(NULL);
  6116. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6117. }
  6118. static void restart_threads(void)
  6119. {
  6120. struct pool *cp = current_pool();
  6121. int i;
  6122. struct thr_info *thr;
  6123. /* Artificially set the lagging flag to avoid pool not providing work
  6124. * fast enough messages after every long poll */
  6125. pool_tset(cp, &cp->lagging);
  6126. /* Discard staged work that is now stale */
  6127. discard_stale();
  6128. rd_lock(&mining_thr_lock);
  6129. for (i = 0; i < mining_threads; i++)
  6130. {
  6131. thr = mining_thr[i];
  6132. thr->work_restart = true;
  6133. }
  6134. for (i = 0; i < mining_threads; i++)
  6135. {
  6136. thr = mining_thr[i];
  6137. notifier_wake(thr->work_restart_notifier);
  6138. }
  6139. rd_unlock(&mining_thr_lock);
  6140. }
  6141. void blkhashstr(char *rv, const unsigned char *hash)
  6142. {
  6143. unsigned char hash_swap[32];
  6144. swap256(hash_swap, hash);
  6145. swap32tole(hash_swap, hash_swap, 32 / 4);
  6146. bin2hex(rv, hash_swap, 32);
  6147. }
  6148. static
  6149. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6150. {
  6151. struct blockchain_info * const blkchain = goal->blkchain;
  6152. blkchain->currentblk = blkinfo;
  6153. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6154. cg_wlock(&ch_lock);
  6155. __update_block_title(goal);
  6156. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6157. cg_wunlock(&ch_lock);
  6158. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6159. }
  6160. /* Search to see if this prevblkhash has been seen before */
  6161. static
  6162. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6163. {
  6164. struct block_info *s;
  6165. rd_lock(&blk_lock);
  6166. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6167. rd_unlock(&blk_lock);
  6168. return s;
  6169. }
  6170. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6171. {
  6172. return blocka->block_seen_order - blockb->block_seen_order;
  6173. }
  6174. static
  6175. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6176. {
  6177. unsigned char target[32];
  6178. double diff;
  6179. uint64_t diff64;
  6180. real_block_target(target, work->data);
  6181. diff = target_diff(target);
  6182. diff64 = diff;
  6183. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6184. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6185. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6186. if (unlikely(goal->current_diff != diff))
  6187. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6188. goal->current_diff = diff;
  6189. }
  6190. static bool test_work_current(struct work *work)
  6191. {
  6192. bool ret = true;
  6193. if (work->mandatory)
  6194. return ret;
  6195. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6196. const uint8_t * const prevblkhash = &work->data[4];
  6197. {
  6198. /* Hack to work around dud work sneaking into test */
  6199. bool dudwork = true;
  6200. for (int i = 8; i < 26; ++i)
  6201. if (work->data[i])
  6202. {
  6203. dudwork = false;
  6204. break;
  6205. }
  6206. if (dudwork)
  6207. goto out_free;
  6208. }
  6209. struct pool * const pool = work->pool;
  6210. struct mining_goal_info * const goal = pool->goal;
  6211. struct blockchain_info * const blkchain = goal->blkchain;
  6212. /* Search to see if this block exists yet and if not, consider it a
  6213. * new block and set the current block details to this one */
  6214. if (!block_exists(blkchain, prevblkhash))
  6215. {
  6216. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6217. int deleted_block = 0;
  6218. ret = false;
  6219. if (unlikely(!s))
  6220. quit (1, "test_work_current OOM");
  6221. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6222. s->block_id = block_id;
  6223. s->block_seen_order = new_blocks++;
  6224. s->first_seen_time = time(NULL);
  6225. wr_lock(&blk_lock);
  6226. /* Only keep the last hour's worth of blocks in memory since
  6227. * work from blocks before this is virtually impossible and we
  6228. * want to prevent memory usage from continually rising */
  6229. if (HASH_COUNT(blkchain->blocks) > 6)
  6230. {
  6231. struct block_info *oldblock;
  6232. HASH_SORT(blkchain->blocks, block_sort);
  6233. oldblock = blkchain->blocks;
  6234. deleted_block = oldblock->block_seen_order;
  6235. HASH_DEL(blkchain->blocks, oldblock);
  6236. free(oldblock);
  6237. }
  6238. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6239. set_blockdiff(goal, work);
  6240. wr_unlock(&blk_lock);
  6241. pool->block_id = block_id;
  6242. pool_update_work_restart_time(pool);
  6243. if (deleted_block)
  6244. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6245. #if BLKMAKER_VERSION > 1
  6246. template_nonce = 0;
  6247. #endif
  6248. set_curblock(goal, s);
  6249. if (unlikely(new_blocks == 1))
  6250. goto out_free;
  6251. if (!work->stratum)
  6252. {
  6253. if (work->longpoll)
  6254. {
  6255. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6256. pool->pool_no);
  6257. }
  6258. else
  6259. if (goal->have_longpoll)
  6260. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6261. else
  6262. applog(LOG_NOTICE, "New block detected on network");
  6263. }
  6264. restart_threads();
  6265. }
  6266. else
  6267. {
  6268. bool restart = false;
  6269. if (unlikely(pool->block_id != block_id))
  6270. {
  6271. bool was_active = pool->block_id != 0;
  6272. pool->block_id = block_id;
  6273. pool_update_work_restart_time(pool);
  6274. if (!work->longpoll)
  6275. update_last_work(work);
  6276. if (was_active)
  6277. {
  6278. // Pool actively changed block
  6279. if (pool == current_pool())
  6280. restart = true;
  6281. if (block_id == blkchain->currentblk->block_id)
  6282. {
  6283. // Caught up, only announce if this pool is the one in use
  6284. if (restart)
  6285. applog(LOG_NOTICE, "%s %d caught up to new block",
  6286. work->longpoll ? "Longpoll from pool" : "Pool",
  6287. pool->pool_no);
  6288. }
  6289. else
  6290. {
  6291. // Switched to a block we know, but not the latest... why?
  6292. // This might detect pools trying to double-spend or 51%,
  6293. // but let's not make any accusations until it's had time
  6294. // in the real world.
  6295. char hexstr[65];
  6296. blkhashstr(hexstr, prevblkhash);
  6297. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6298. work->longpoll ? "Longpoll from pool" : "Pool",
  6299. pool->pool_no,
  6300. hexstr);
  6301. }
  6302. }
  6303. }
  6304. if (work->longpoll)
  6305. {
  6306. struct pool * const cp = current_pool();
  6307. ++pool->work_restart_id;
  6308. if (work->tr && work->tr == pool->swork.tr)
  6309. pool->swork.work_restart_id = pool->work_restart_id;
  6310. update_last_work(work);
  6311. pool_update_work_restart_time(pool);
  6312. applog(
  6313. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6314. "Longpoll from pool %d requested work update",
  6315. pool->pool_no);
  6316. if ((!restart) && pool == cp)
  6317. restart = true;
  6318. }
  6319. if (restart)
  6320. restart_threads();
  6321. }
  6322. work->longpoll = false;
  6323. out_free:
  6324. return ret;
  6325. }
  6326. static int tv_sort(struct work *worka, struct work *workb)
  6327. {
  6328. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6329. }
  6330. static bool work_rollable(struct work *work)
  6331. {
  6332. return (!work->clone && work->rolltime);
  6333. }
  6334. static bool hash_push(struct work *work)
  6335. {
  6336. bool rc = true;
  6337. mutex_lock(stgd_lock);
  6338. if (work_rollable(work))
  6339. staged_rollable++;
  6340. if (likely(!getq->frozen)) {
  6341. HASH_ADD_INT(staged_work, id, work);
  6342. HASH_SORT(staged_work, tv_sort);
  6343. } else
  6344. rc = false;
  6345. pthread_cond_broadcast(&getq->cond);
  6346. mutex_unlock(stgd_lock);
  6347. return rc;
  6348. }
  6349. static void stage_work(struct work *work)
  6350. {
  6351. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6352. work->id, work->pool->pool_no);
  6353. work->work_restart_id = work->pool->work_restart_id;
  6354. work->pool->last_work_time = time(NULL);
  6355. cgtime(&work->pool->tv_last_work_time);
  6356. test_work_current(work);
  6357. work->pool->works++;
  6358. hash_push(work);
  6359. }
  6360. #ifdef HAVE_CURSES
  6361. int curses_int(const char *query)
  6362. {
  6363. int ret;
  6364. char *cvar;
  6365. cvar = curses_input(query);
  6366. if (unlikely(!cvar))
  6367. return -1;
  6368. ret = atoi(cvar);
  6369. free(cvar);
  6370. return ret;
  6371. }
  6372. #endif
  6373. #ifdef HAVE_CURSES
  6374. static bool input_pool(bool live);
  6375. #endif
  6376. #ifdef HAVE_CURSES
  6377. static void display_pool_summary(struct pool *pool)
  6378. {
  6379. double efficiency = 0.0;
  6380. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6381. int pool_secs;
  6382. if (curses_active_locked()) {
  6383. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6384. if (pool->solved)
  6385. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6386. if (!pool->has_stratum)
  6387. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6388. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6389. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6390. wlog(" Accepted shares: %d\n", pool->accepted);
  6391. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6392. pool->rejected, pool->stale_shares,
  6393. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6394. );
  6395. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6396. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6397. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6398. wlog(" Network transfer: %s (%s)\n",
  6399. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6400. (float)pool->cgminer_pool_stats.net_bytes_received,
  6401. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6402. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6403. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6404. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6405. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6406. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6407. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6408. wlog(" Items worked on: %d\n", pool->works);
  6409. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6410. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6411. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6412. unlock_curses();
  6413. }
  6414. }
  6415. #endif
  6416. /* We can't remove the memory used for this struct pool because there may
  6417. * still be work referencing it. We just remove it from the pools list */
  6418. void remove_pool(struct pool *pool)
  6419. {
  6420. int i, last_pool = total_pools - 1;
  6421. struct pool *other;
  6422. disable_pool(pool, POOL_DISABLED);
  6423. /* Boost priority of any lower prio than this one */
  6424. for (i = 0; i < total_pools; i++) {
  6425. other = pools[i];
  6426. if (other->prio > pool->prio)
  6427. other->prio--;
  6428. }
  6429. if (pool->pool_no < last_pool) {
  6430. /* Swap the last pool for this one */
  6431. (pools[last_pool])->pool_no = pool->pool_no;
  6432. pools[pool->pool_no] = pools[last_pool];
  6433. }
  6434. /* Give it an invalid number */
  6435. pool->pool_no = total_pools;
  6436. pool->removed = true;
  6437. pool->has_stratum = false;
  6438. total_pools--;
  6439. }
  6440. /* add a mutex if this needs to be thread safe in the future */
  6441. static struct JE {
  6442. char *buf;
  6443. struct JE *next;
  6444. } *jedata = NULL;
  6445. static void json_escape_free()
  6446. {
  6447. struct JE *jeptr = jedata;
  6448. struct JE *jenext;
  6449. jedata = NULL;
  6450. while (jeptr) {
  6451. jenext = jeptr->next;
  6452. free(jeptr->buf);
  6453. free(jeptr);
  6454. jeptr = jenext;
  6455. }
  6456. }
  6457. static
  6458. char *json_escape(const char *str)
  6459. {
  6460. struct JE *jeptr;
  6461. char *buf, *ptr;
  6462. /* 2x is the max, may as well just allocate that */
  6463. ptr = buf = malloc(strlen(str) * 2 + 1);
  6464. jeptr = malloc(sizeof(*jeptr));
  6465. jeptr->buf = buf;
  6466. jeptr->next = jedata;
  6467. jedata = jeptr;
  6468. while (*str) {
  6469. if (*str == '\\' || *str == '"')
  6470. *(ptr++) = '\\';
  6471. *(ptr++) = *(str++);
  6472. }
  6473. *ptr = '\0';
  6474. return buf;
  6475. }
  6476. static
  6477. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6478. {
  6479. if (!elist)
  6480. return;
  6481. static struct string_elist *entry;
  6482. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6483. bool first = true;
  6484. DL_FOREACH(elist, entry)
  6485. {
  6486. const char * const s = entry->string;
  6487. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6488. first = false;
  6489. }
  6490. fprintf(fcfg, "\n]");
  6491. }
  6492. void write_config(FILE *fcfg)
  6493. {
  6494. int i;
  6495. /* Write pool values */
  6496. fputs("{\n\"pools\" : [", fcfg);
  6497. for(i = 0; i < total_pools; i++) {
  6498. struct pool *pool = pools[i];
  6499. if (pool->failover_only)
  6500. // Don't write failover-only (automatically added) pools to the config file for now
  6501. continue;
  6502. if (pool->quota != 1) {
  6503. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6504. pool->quota,
  6505. json_escape(pool->rpc_url));
  6506. } else {
  6507. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6508. json_escape(pool->rpc_url));
  6509. }
  6510. if (pool->rpc_proxy)
  6511. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6512. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6513. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6514. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6515. if (pool->force_rollntime)
  6516. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6517. fprintf(fcfg, "\n\t}");
  6518. }
  6519. fputs("\n]\n", fcfg);
  6520. #ifdef HAVE_OPENCL
  6521. write_config_opencl(fcfg);
  6522. #endif
  6523. #ifdef WANT_CPUMINE
  6524. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6525. #endif
  6526. /* Simple bool and int options */
  6527. struct opt_table *opt;
  6528. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6529. char *p, *name = strdup(opt->names);
  6530. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6531. if (p[1] != '-')
  6532. continue;
  6533. if (opt->type & OPT_NOARG &&
  6534. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6535. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6536. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6537. if (opt->type & OPT_HASARG &&
  6538. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6539. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6540. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6541. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6542. opt->desc != opt_hidden &&
  6543. 0 <= *(int *)opt->u.arg)
  6544. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6545. }
  6546. }
  6547. /* Special case options */
  6548. if (request_target_str)
  6549. {
  6550. if (request_pdiff == (long)request_pdiff)
  6551. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6552. else
  6553. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6554. }
  6555. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6556. if (pool_strategy == POOL_BALANCE)
  6557. fputs(",\n\"balance\" : true", fcfg);
  6558. if (pool_strategy == POOL_LOADBALANCE)
  6559. fputs(",\n\"load-balance\" : true", fcfg);
  6560. if (pool_strategy == POOL_ROUNDROBIN)
  6561. fputs(",\n\"round-robin\" : true", fcfg);
  6562. if (pool_strategy == POOL_ROTATE)
  6563. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6564. #if defined(unix) || defined(__APPLE__)
  6565. if (opt_stderr_cmd && *opt_stderr_cmd)
  6566. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6567. #endif // defined(unix)
  6568. if (opt_kernel_path && *opt_kernel_path) {
  6569. char *kpath = strdup(opt_kernel_path);
  6570. if (kpath[strlen(kpath)-1] == '/')
  6571. kpath[strlen(kpath)-1] = 0;
  6572. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6573. free(kpath);
  6574. }
  6575. if (schedstart.enable)
  6576. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6577. if (schedstop.enable)
  6578. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6579. if (opt_socks_proxy && *opt_socks_proxy)
  6580. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6581. _write_config_string_elist(fcfg, "scan", scan_devices);
  6582. #ifdef USE_LIBMICROHTTPD
  6583. if (httpsrv_port != -1)
  6584. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6585. #endif
  6586. #ifdef USE_LIBEVENT
  6587. if (stratumsrv_port != -1)
  6588. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6589. #endif
  6590. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6591. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6592. if (opt_api_allow)
  6593. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6594. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6595. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6596. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6597. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6598. if (*opt_api_mcast_des)
  6599. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6600. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6601. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6602. if (opt_api_groups)
  6603. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6604. fputs("\n}\n", fcfg);
  6605. json_escape_free();
  6606. }
  6607. void zero_bestshare(void)
  6608. {
  6609. int i;
  6610. best_diff = 0;
  6611. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6612. for (i = 0; i < total_pools; i++) {
  6613. struct pool *pool = pools[i];
  6614. pool->best_diff = 0;
  6615. }
  6616. }
  6617. void zero_stats(void)
  6618. {
  6619. int i;
  6620. applog(LOG_DEBUG, "Zeroing stats");
  6621. cgtime(&total_tv_start);
  6622. miner_started = total_tv_start;
  6623. total_rolling = 0;
  6624. total_mhashes_done = 0;
  6625. total_getworks = 0;
  6626. total_accepted = 0;
  6627. total_rejected = 0;
  6628. hw_errors = 0;
  6629. total_stale = 0;
  6630. total_discarded = 0;
  6631. total_bytes_rcvd = total_bytes_sent = 0;
  6632. new_blocks = 0;
  6633. local_work = 0;
  6634. total_go = 0;
  6635. total_ro = 0;
  6636. total_secs = 1.0;
  6637. total_diff1 = 0;
  6638. total_bad_diff1 = 0;
  6639. found_blocks = 0;
  6640. total_diff_accepted = 0;
  6641. total_diff_rejected = 0;
  6642. total_diff_stale = 0;
  6643. #ifdef HAVE_CURSES
  6644. awidth = rwidth = swidth = hwwidth = 1;
  6645. #endif
  6646. struct mining_goal_info *goal, *tmpgoal;
  6647. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6648. {
  6649. goal->diff_accepted = 0;
  6650. }
  6651. for (i = 0; i < total_pools; i++) {
  6652. struct pool *pool = pools[i];
  6653. pool->getwork_requested = 0;
  6654. pool->accepted = 0;
  6655. pool->rejected = 0;
  6656. pool->solved = 0;
  6657. pool->getwork_requested = 0;
  6658. pool->stale_shares = 0;
  6659. pool->discarded_work = 0;
  6660. pool->getfail_occasions = 0;
  6661. pool->remotefail_occasions = 0;
  6662. pool->last_share_time = 0;
  6663. pool->works = 0;
  6664. pool->diff1 = 0;
  6665. pool->diff_accepted = 0;
  6666. pool->diff_rejected = 0;
  6667. pool->diff_stale = 0;
  6668. pool->last_share_diff = 0;
  6669. pool->cgminer_stats.start_tv = total_tv_start;
  6670. pool->cgminer_stats.getwork_calls = 0;
  6671. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6672. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6673. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6674. pool->cgminer_pool_stats.getwork_calls = 0;
  6675. pool->cgminer_pool_stats.getwork_attempts = 0;
  6676. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6677. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6678. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6679. pool->cgminer_pool_stats.min_diff = 0;
  6680. pool->cgminer_pool_stats.max_diff = 0;
  6681. pool->cgminer_pool_stats.min_diff_count = 0;
  6682. pool->cgminer_pool_stats.max_diff_count = 0;
  6683. pool->cgminer_pool_stats.times_sent = 0;
  6684. pool->cgminer_pool_stats.bytes_sent = 0;
  6685. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6686. pool->cgminer_pool_stats.times_received = 0;
  6687. pool->cgminer_pool_stats.bytes_received = 0;
  6688. pool->cgminer_pool_stats.net_bytes_received = 0;
  6689. }
  6690. zero_bestshare();
  6691. for (i = 0; i < total_devices; ++i) {
  6692. struct cgpu_info *cgpu = get_devices(i);
  6693. mutex_lock(&hash_lock);
  6694. cgpu->total_mhashes = 0;
  6695. cgpu->accepted = 0;
  6696. cgpu->rejected = 0;
  6697. cgpu->stale = 0;
  6698. cgpu->hw_errors = 0;
  6699. cgpu->utility = 0.0;
  6700. cgpu->utility_diff1 = 0;
  6701. cgpu->last_share_pool_time = 0;
  6702. cgpu->bad_diff1 = 0;
  6703. cgpu->diff1 = 0;
  6704. cgpu->diff_accepted = 0;
  6705. cgpu->diff_rejected = 0;
  6706. cgpu->diff_stale = 0;
  6707. cgpu->last_share_diff = 0;
  6708. cgpu->thread_fail_init_count = 0;
  6709. cgpu->thread_zero_hash_count = 0;
  6710. cgpu->thread_fail_queue_count = 0;
  6711. cgpu->dev_sick_idle_60_count = 0;
  6712. cgpu->dev_dead_idle_600_count = 0;
  6713. cgpu->dev_nostart_count = 0;
  6714. cgpu->dev_over_heat_count = 0;
  6715. cgpu->dev_thermal_cutoff_count = 0;
  6716. cgpu->dev_comms_error_count = 0;
  6717. cgpu->dev_throttle_count = 0;
  6718. cgpu->cgminer_stats.start_tv = total_tv_start;
  6719. cgpu->cgminer_stats.getwork_calls = 0;
  6720. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6721. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6722. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6723. mutex_unlock(&hash_lock);
  6724. if (cgpu->drv->zero_stats)
  6725. cgpu->drv->zero_stats(cgpu);
  6726. }
  6727. }
  6728. #ifdef HAVE_CURSES
  6729. static
  6730. void loginput_mode(const int size)
  6731. {
  6732. clear_logwin();
  6733. loginput_size = size;
  6734. check_winsizes();
  6735. }
  6736. static void display_pools(void)
  6737. {
  6738. struct pool *pool;
  6739. int selected, i, j;
  6740. char input;
  6741. loginput_mode(7 + total_pools);
  6742. immedok(logwin, true);
  6743. updated:
  6744. for (j = 0; j < total_pools; j++) {
  6745. for (i = 0; i < total_pools; i++) {
  6746. pool = pools[i];
  6747. if (pool->prio != j)
  6748. continue;
  6749. if (pool == current_pool())
  6750. wattron(logwin, A_BOLD);
  6751. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  6752. wattron(logwin, A_DIM);
  6753. wlogprint("%d: ", pool->prio);
  6754. switch (pool->enabled) {
  6755. case POOL_ENABLED:
  6756. if (pool->failover_only)
  6757. wlogprint("Failover ");
  6758. else
  6759. wlogprint("Enabled ");
  6760. break;
  6761. case POOL_DISABLED:
  6762. wlogprint("Disabled ");
  6763. break;
  6764. case POOL_REJECTING:
  6765. wlogprint("Rejectin ");
  6766. break;
  6767. case POOL_MISBEHAVING:
  6768. wlogprint("Misbehav ");
  6769. break;
  6770. }
  6771. _wlogprint(pool_proto_str(pool));
  6772. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  6773. pool->quota,
  6774. pool->pool_no,
  6775. pool->rpc_url, pool->rpc_user);
  6776. wattroff(logwin, A_BOLD | A_DIM);
  6777. break; //for (i = 0; i < total_pools; i++)
  6778. }
  6779. }
  6780. retry:
  6781. wlogprint("\nCurrent pool management strategy: %s\n",
  6782. strategies[pool_strategy].s);
  6783. if (pool_strategy == POOL_ROTATE)
  6784. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6785. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6786. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6787. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6788. wlogprint("Or press any other key to continue\n");
  6789. logwin_update();
  6790. input = getch();
  6791. if (!strncasecmp(&input, "a", 1)) {
  6792. if (opt_benchmark)
  6793. {
  6794. wlogprint("Cannot add pools in benchmark mode");
  6795. goto retry;
  6796. }
  6797. input_pool(true);
  6798. goto updated;
  6799. } else if (!strncasecmp(&input, "r", 1)) {
  6800. if (total_pools <= 1) {
  6801. wlogprint("Cannot remove last pool");
  6802. goto retry;
  6803. }
  6804. selected = curses_int("Select pool number");
  6805. if (selected < 0 || selected >= total_pools) {
  6806. wlogprint("Invalid selection\n");
  6807. goto retry;
  6808. }
  6809. pool = pools[selected];
  6810. if (pool == current_pool())
  6811. switch_pools(NULL);
  6812. if (pool == current_pool()) {
  6813. wlogprint("Unable to remove pool due to activity\n");
  6814. goto retry;
  6815. }
  6816. remove_pool(pool);
  6817. goto updated;
  6818. } else if (!strncasecmp(&input, "s", 1)) {
  6819. selected = curses_int("Select pool number");
  6820. if (selected < 0 || selected >= total_pools) {
  6821. wlogprint("Invalid selection\n");
  6822. goto retry;
  6823. }
  6824. pool = pools[selected];
  6825. pool->failover_only = false;
  6826. switch_pools(pool);
  6827. goto updated;
  6828. } else if (!strncasecmp(&input, "d", 1)) {
  6829. if (enabled_pools <= 1) {
  6830. wlogprint("Cannot disable last pool");
  6831. goto retry;
  6832. }
  6833. selected = curses_int("Select pool number");
  6834. if (selected < 0 || selected >= total_pools) {
  6835. wlogprint("Invalid selection\n");
  6836. goto retry;
  6837. }
  6838. pool = pools[selected];
  6839. disable_pool(pool, POOL_DISABLED);
  6840. goto updated;
  6841. } else if (!strncasecmp(&input, "e", 1)) {
  6842. selected = curses_int("Select pool number");
  6843. if (selected < 0 || selected >= total_pools) {
  6844. wlogprint("Invalid selection\n");
  6845. goto retry;
  6846. }
  6847. pool = pools[selected];
  6848. pool->failover_only = false;
  6849. enable_pool(pool);
  6850. goto updated;
  6851. } else if (!strncasecmp(&input, "c", 1)) {
  6852. for (i = 0; i <= TOP_STRATEGY; i++)
  6853. wlogprint("%d: %s\n", i, strategies[i].s);
  6854. selected = curses_int("Select strategy number type");
  6855. if (selected < 0 || selected > TOP_STRATEGY) {
  6856. wlogprint("Invalid selection\n");
  6857. goto retry;
  6858. }
  6859. if (selected == POOL_ROTATE) {
  6860. opt_rotate_period = curses_int("Select interval in minutes");
  6861. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6862. opt_rotate_period = 0;
  6863. wlogprint("Invalid selection\n");
  6864. goto retry;
  6865. }
  6866. }
  6867. mutex_lock(&lp_lock);
  6868. pool_strategy = selected;
  6869. pthread_cond_broadcast(&lp_cond);
  6870. mutex_unlock(&lp_lock);
  6871. switch_pools(NULL);
  6872. goto updated;
  6873. } else if (!strncasecmp(&input, "i", 1)) {
  6874. selected = curses_int("Select pool number");
  6875. if (selected < 0 || selected >= total_pools) {
  6876. wlogprint("Invalid selection\n");
  6877. goto retry;
  6878. }
  6879. pool = pools[selected];
  6880. display_pool_summary(pool);
  6881. goto retry;
  6882. } else if (!strncasecmp(&input, "q", 1)) {
  6883. selected = curses_int("Select pool number");
  6884. if (selected < 0 || selected >= total_pools) {
  6885. wlogprint("Invalid selection\n");
  6886. goto retry;
  6887. }
  6888. pool = pools[selected];
  6889. selected = curses_int("Set quota");
  6890. if (selected < 0) {
  6891. wlogprint("Invalid negative quota\n");
  6892. goto retry;
  6893. }
  6894. pool->quota = selected;
  6895. adjust_quota_gcd();
  6896. goto updated;
  6897. } else if (!strncasecmp(&input, "f", 1)) {
  6898. opt_fail_only ^= true;
  6899. goto updated;
  6900. } else if (!strncasecmp(&input, "p", 1)) {
  6901. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6902. if (!prilist)
  6903. {
  6904. wlogprint("Not changing priorities\n");
  6905. goto retry;
  6906. }
  6907. int res = prioritize_pools(prilist, &i);
  6908. free(prilist);
  6909. switch (res) {
  6910. case MSG_NOPOOL:
  6911. wlogprint("No pools\n");
  6912. goto retry;
  6913. case MSG_MISPID:
  6914. wlogprint("Missing pool id parameter\n");
  6915. goto retry;
  6916. case MSG_INVPID:
  6917. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6918. goto retry;
  6919. case MSG_DUPPID:
  6920. wlogprint("Duplicate pool specified %d\n", i);
  6921. goto retry;
  6922. case MSG_POOLPRIO:
  6923. default:
  6924. goto updated;
  6925. }
  6926. }
  6927. immedok(logwin, false);
  6928. loginput_mode(0);
  6929. }
  6930. static const char *summary_detail_level_str(void)
  6931. {
  6932. if (opt_compact)
  6933. return "compact";
  6934. if (opt_show_procs)
  6935. return "processors";
  6936. return "devices";
  6937. }
  6938. static void display_options(void)
  6939. {
  6940. int selected;
  6941. char input;
  6942. immedok(logwin, true);
  6943. loginput_mode(12);
  6944. retry:
  6945. clear_logwin();
  6946. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6947. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6948. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6949. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6950. opt_debug_console ? "on" : "off",
  6951. want_per_device_stats? "on" : "off",
  6952. opt_quiet ? "on" : "off",
  6953. opt_log_output ? "on" : "off",
  6954. opt_protocol ? "on" : "off",
  6955. opt_worktime ? "on" : "off",
  6956. summary_detail_level_str(),
  6957. opt_log_interval,
  6958. opt_weighed_stats ? "weighed" : "absolute");
  6959. wlogprint("Select an option or any other key to return\n");
  6960. logwin_update();
  6961. input = getch();
  6962. if (!strncasecmp(&input, "q", 1)) {
  6963. opt_quiet ^= true;
  6964. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6965. goto retry;
  6966. } else if (!strncasecmp(&input, "v", 1)) {
  6967. opt_log_output ^= true;
  6968. if (opt_log_output)
  6969. opt_quiet = false;
  6970. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6971. goto retry;
  6972. } else if (!strncasecmp(&input, "n", 1)) {
  6973. opt_log_output = false;
  6974. opt_debug_console = false;
  6975. opt_quiet = false;
  6976. opt_protocol = false;
  6977. opt_compact = false;
  6978. opt_show_procs = false;
  6979. devsummaryYOffset = 0;
  6980. want_per_device_stats = false;
  6981. wlogprint("Output mode reset to normal\n");
  6982. switch_logsize();
  6983. goto retry;
  6984. } else if (!strncasecmp(&input, "d", 1)) {
  6985. opt_debug = true;
  6986. opt_debug_console ^= true;
  6987. opt_log_output = opt_debug_console;
  6988. if (opt_debug_console)
  6989. opt_quiet = false;
  6990. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6991. goto retry;
  6992. } else if (!strncasecmp(&input, "m", 1)) {
  6993. if (opt_compact)
  6994. opt_compact = false;
  6995. else
  6996. if (!opt_show_procs)
  6997. opt_show_procs = true;
  6998. else
  6999. {
  7000. opt_compact = true;
  7001. opt_show_procs = false;
  7002. devsummaryYOffset = 0;
  7003. }
  7004. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7005. switch_logsize();
  7006. goto retry;
  7007. } else if (!strncasecmp(&input, "p", 1)) {
  7008. want_per_device_stats ^= true;
  7009. opt_log_output = want_per_device_stats;
  7010. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7011. goto retry;
  7012. } else if (!strncasecmp(&input, "r", 1)) {
  7013. opt_protocol ^= true;
  7014. if (opt_protocol)
  7015. opt_quiet = false;
  7016. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7017. goto retry;
  7018. } else if (!strncasecmp(&input, "c", 1))
  7019. clear_logwin();
  7020. else if (!strncasecmp(&input, "l", 1)) {
  7021. selected = curses_int("Interval in seconds");
  7022. if (selected < 0 || selected > 9999) {
  7023. wlogprint("Invalid selection\n");
  7024. goto retry;
  7025. }
  7026. opt_log_interval = selected;
  7027. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7028. goto retry;
  7029. } else if (!strncasecmp(&input, "s", 1)) {
  7030. opt_realquiet = true;
  7031. } else if (!strncasecmp(&input, "w", 1)) {
  7032. opt_worktime ^= true;
  7033. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7034. goto retry;
  7035. } else if (!strncasecmp(&input, "t", 1)) {
  7036. opt_weighed_stats ^= true;
  7037. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7038. goto retry;
  7039. } else if (!strncasecmp(&input, "z", 1)) {
  7040. zero_stats();
  7041. goto retry;
  7042. }
  7043. immedok(logwin, false);
  7044. loginput_mode(0);
  7045. }
  7046. #endif
  7047. void default_save_file(char *filename)
  7048. {
  7049. #if defined(unix) || defined(__APPLE__)
  7050. if (getenv("HOME") && *getenv("HOME")) {
  7051. strcpy(filename, getenv("HOME"));
  7052. strcat(filename, "/");
  7053. }
  7054. else
  7055. strcpy(filename, "");
  7056. strcat(filename, ".bfgminer/");
  7057. mkdir(filename, 0777);
  7058. #else
  7059. strcpy(filename, "");
  7060. #endif
  7061. strcat(filename, def_conf);
  7062. }
  7063. #ifdef HAVE_CURSES
  7064. static void set_options(void)
  7065. {
  7066. int selected;
  7067. char input;
  7068. immedok(logwin, true);
  7069. loginput_mode(8);
  7070. retry:
  7071. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7072. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7073. "[W]rite config file\n[B]FGMiner restart\n",
  7074. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7075. wlogprint("Select an option or any other key to return\n");
  7076. logwin_update();
  7077. input = getch();
  7078. if (!strncasecmp(&input, "q", 1)) {
  7079. selected = curses_int("Extra work items to queue");
  7080. if (selected < 0 || selected > 9999) {
  7081. wlogprint("Invalid selection\n");
  7082. goto retry;
  7083. }
  7084. opt_queue = selected;
  7085. goto retry;
  7086. } else if (!strncasecmp(&input, "l", 1)) {
  7087. if (want_longpoll)
  7088. stop_longpoll();
  7089. else
  7090. start_longpoll();
  7091. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7092. goto retry;
  7093. } else if (!strncasecmp(&input, "s", 1)) {
  7094. selected = curses_int("Set scantime in seconds");
  7095. if (selected < 0 || selected > 9999) {
  7096. wlogprint("Invalid selection\n");
  7097. goto retry;
  7098. }
  7099. opt_scantime = selected;
  7100. goto retry;
  7101. } else if (!strncasecmp(&input, "e", 1)) {
  7102. selected = curses_int("Set expiry time in seconds");
  7103. if (selected < 0 || selected > 9999) {
  7104. wlogprint("Invalid selection\n");
  7105. goto retry;
  7106. }
  7107. opt_expiry = selected;
  7108. goto retry;
  7109. } else if (!strncasecmp(&input, "r", 1)) {
  7110. selected = curses_int("Retries before failing (-1 infinite)");
  7111. if (selected < -1 || selected > 9999) {
  7112. wlogprint("Invalid selection\n");
  7113. goto retry;
  7114. }
  7115. opt_retries = selected;
  7116. goto retry;
  7117. } else if (!strncasecmp(&input, "w", 1)) {
  7118. FILE *fcfg;
  7119. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7120. default_save_file(filename);
  7121. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7122. str = curses_input(prompt);
  7123. if (str) {
  7124. struct stat statbuf;
  7125. strcpy(filename, str);
  7126. free(str);
  7127. if (!stat(filename, &statbuf)) {
  7128. wlogprint("File exists, overwrite?\n");
  7129. input = getch();
  7130. if (strncasecmp(&input, "y", 1))
  7131. goto retry;
  7132. }
  7133. }
  7134. fcfg = fopen(filename, "w");
  7135. if (!fcfg) {
  7136. wlogprint("Cannot open or create file\n");
  7137. goto retry;
  7138. }
  7139. write_config(fcfg);
  7140. fclose(fcfg);
  7141. goto retry;
  7142. } else if (!strncasecmp(&input, "b", 1)) {
  7143. wlogprint("Are you sure?\n");
  7144. input = getch();
  7145. if (!strncasecmp(&input, "y", 1))
  7146. app_restart();
  7147. else
  7148. clear_logwin();
  7149. } else
  7150. clear_logwin();
  7151. loginput_mode(0);
  7152. immedok(logwin, false);
  7153. }
  7154. int scan_serial(const char *);
  7155. static
  7156. void _managetui_msg(const char *repr, const char **msg)
  7157. {
  7158. if (*msg)
  7159. {
  7160. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7161. wattron(logwin, A_BOLD);
  7162. wlogprint("%s", *msg);
  7163. wattroff(logwin, A_BOLD);
  7164. *msg = NULL;
  7165. }
  7166. logwin_update();
  7167. }
  7168. void manage_device(void)
  7169. {
  7170. char logline[256];
  7171. const char *msg = NULL;
  7172. struct cgpu_info *cgpu;
  7173. const struct device_drv *drv;
  7174. selecting_device = true;
  7175. immedok(logwin, true);
  7176. loginput_mode(12);
  7177. devchange:
  7178. if (unlikely(!total_devices))
  7179. {
  7180. clear_logwin();
  7181. wlogprint("(no devices)\n");
  7182. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7183. _managetui_msg("(none)", &msg);
  7184. int input = getch();
  7185. switch (input)
  7186. {
  7187. case '+': case '=': // add new device
  7188. goto addnew;
  7189. default:
  7190. goto out;
  7191. }
  7192. }
  7193. cgpu = devices[selected_device];
  7194. drv = cgpu->drv;
  7195. refresh_devstatus();
  7196. refresh:
  7197. clear_logwin();
  7198. wlogprint("Select processor to manage using up/down arrow keys\n");
  7199. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7200. wattron(logwin, A_BOLD);
  7201. wlogprint("%s", logline);
  7202. wattroff(logwin, A_BOLD);
  7203. wlogprint("\n");
  7204. if (cgpu->dev_manufacturer)
  7205. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7206. else
  7207. if (cgpu->dev_product)
  7208. wlogprint(" %s\n", cgpu->dev_product);
  7209. if (cgpu->dev_serial)
  7210. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7211. if (cgpu->kname)
  7212. wlogprint("Kernel: %s\n", cgpu->kname);
  7213. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7214. drv->proc_wlogprint_status(cgpu);
  7215. wlogprint("\n");
  7216. // TODO: Last share at TIMESTAMP on pool N
  7217. // TODO: Custom device info/commands
  7218. if (cgpu->deven != DEV_ENABLED)
  7219. wlogprint("[E]nable ");
  7220. if (cgpu->deven != DEV_DISABLED)
  7221. wlogprint("[D]isable ");
  7222. if (drv->identify_device)
  7223. wlogprint("[I]dentify ");
  7224. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7225. drv->proc_tui_wlogprint_choices(cgpu);
  7226. wlogprint("\n");
  7227. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7228. _managetui_msg(cgpu->proc_repr, &msg);
  7229. while (true)
  7230. {
  7231. int input = getch();
  7232. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7233. switch (input) {
  7234. case 'd': case 'D':
  7235. if (cgpu->deven == DEV_DISABLED)
  7236. msg = "Processor already disabled\n";
  7237. else
  7238. {
  7239. cgpu->deven = DEV_DISABLED;
  7240. msg = "Processor being disabled\n";
  7241. }
  7242. goto refresh;
  7243. case 'e': case 'E':
  7244. if (cgpu->deven == DEV_ENABLED)
  7245. msg = "Processor already enabled\n";
  7246. else
  7247. {
  7248. proc_enable(cgpu);
  7249. msg = "Processor being enabled\n";
  7250. }
  7251. goto refresh;
  7252. case 'i': case 'I':
  7253. if (drv->identify_device && drv->identify_device(cgpu))
  7254. msg = "Identify command sent\n";
  7255. else
  7256. goto key_default;
  7257. goto refresh;
  7258. case KEY_DOWN:
  7259. if (selected_device >= total_devices - 1)
  7260. break;
  7261. ++selected_device;
  7262. goto devchange;
  7263. case KEY_UP:
  7264. if (selected_device <= 0)
  7265. break;
  7266. --selected_device;
  7267. goto devchange;
  7268. case KEY_NPAGE:
  7269. {
  7270. if (selected_device >= total_devices - 1)
  7271. break;
  7272. struct cgpu_info *mdev = devices[selected_device]->device;
  7273. do {
  7274. ++selected_device;
  7275. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7276. goto devchange;
  7277. }
  7278. case KEY_PPAGE:
  7279. {
  7280. if (selected_device <= 0)
  7281. break;
  7282. struct cgpu_info *mdev = devices[selected_device]->device;
  7283. do {
  7284. --selected_device;
  7285. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7286. goto devchange;
  7287. }
  7288. case '/': case '?': // find device
  7289. {
  7290. static char *pattern = NULL;
  7291. char *newpattern = curses_input("Enter pattern");
  7292. if (newpattern)
  7293. {
  7294. free(pattern);
  7295. pattern = newpattern;
  7296. }
  7297. else
  7298. if (!pattern)
  7299. pattern = calloc(1, 1);
  7300. int match = cgpu_search(pattern, selected_device + 1);
  7301. if (match == -1)
  7302. {
  7303. msg = "Couldn't find device\n";
  7304. goto refresh;
  7305. }
  7306. selected_device = match;
  7307. goto devchange;
  7308. }
  7309. case '+': case '=': // add new device
  7310. {
  7311. addnew:
  7312. clear_logwin();
  7313. _wlogprint(
  7314. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7315. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7316. "For example: erupter:"
  7317. #ifdef WIN32
  7318. "\\\\.\\COM40"
  7319. #elif defined(__APPLE__)
  7320. "/dev/cu.SLAB_USBtoUART"
  7321. #else
  7322. "/dev/ttyUSB39"
  7323. #endif
  7324. "\n"
  7325. );
  7326. char *scanser = curses_input("Enter target");
  7327. if (scan_serial(scanser))
  7328. {
  7329. selected_device = total_devices - 1;
  7330. msg = "Device scan succeeded\n";
  7331. }
  7332. else
  7333. msg = "No new devices found\n";
  7334. goto devchange;
  7335. }
  7336. case 'Q': case 'q':
  7337. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7338. case '\x1b': // ESC
  7339. case KEY_ENTER:
  7340. case '\r': // Ctrl-M on Windows, with nonl
  7341. #ifdef PADENTER
  7342. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7343. #endif
  7344. case '\n':
  7345. goto out;
  7346. default:
  7347. ;
  7348. key_default:
  7349. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7350. {
  7351. msg = drv->proc_tui_handle_choice(cgpu, input);
  7352. if (msg)
  7353. goto refresh;
  7354. }
  7355. }
  7356. }
  7357. out:
  7358. selecting_device = false;
  7359. loginput_mode(0);
  7360. immedok(logwin, false);
  7361. }
  7362. void show_help(void)
  7363. {
  7364. loginput_mode(11);
  7365. // NOTE: wlogprint is a macro with a buffer limit
  7366. _wlogprint(
  7367. "LU: oldest explicit work update currently being used for new work\n"
  7368. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7369. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7370. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7371. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7372. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7373. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7374. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7375. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7376. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7377. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7378. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7379. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7380. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7381. "\n"
  7382. "devices/processors hashing (only for totals line), hottest temperature\n"
  7383. );
  7384. wlogprint(
  7385. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7386. , opt_log_interval);
  7387. _wlogprint(
  7388. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7389. "HW: hardware errors / % nonces invalid\n"
  7390. "\n"
  7391. "Press any key to clear"
  7392. );
  7393. logwin_update();
  7394. getch();
  7395. loginput_mode(0);
  7396. }
  7397. static void *input_thread(void __maybe_unused *userdata)
  7398. {
  7399. RenameThread("input");
  7400. if (!curses_active)
  7401. return NULL;
  7402. while (1) {
  7403. int input;
  7404. input = getch();
  7405. switch (input) {
  7406. case 'h': case 'H': case '?':
  7407. case KEY_F(1):
  7408. show_help();
  7409. break;
  7410. case 'q': case 'Q':
  7411. kill_work();
  7412. return NULL;
  7413. case 'd': case 'D':
  7414. display_options();
  7415. break;
  7416. case 'm': case 'M':
  7417. manage_device();
  7418. break;
  7419. case 'p': case 'P':
  7420. display_pools();
  7421. break;
  7422. case 's': case 'S':
  7423. set_options();
  7424. break;
  7425. #ifdef HAVE_CURSES
  7426. case KEY_DOWN:
  7427. {
  7428. const int visible_lines = logcursor - devcursor;
  7429. const int invisible_lines = total_lines - visible_lines;
  7430. if (devsummaryYOffset <= -invisible_lines)
  7431. break;
  7432. devsummaryYOffset -= 2;
  7433. }
  7434. case KEY_UP:
  7435. if (devsummaryYOffset == 0)
  7436. break;
  7437. ++devsummaryYOffset;
  7438. refresh_devstatus();
  7439. break;
  7440. case KEY_NPAGE:
  7441. {
  7442. const int visible_lines = logcursor - devcursor;
  7443. const int invisible_lines = total_lines - visible_lines;
  7444. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7445. devsummaryYOffset = -invisible_lines;
  7446. else
  7447. devsummaryYOffset -= visible_lines;
  7448. refresh_devstatus();
  7449. break;
  7450. }
  7451. case KEY_PPAGE:
  7452. {
  7453. const int visible_lines = logcursor - devcursor;
  7454. if (devsummaryYOffset + visible_lines >= 0)
  7455. devsummaryYOffset = 0;
  7456. else
  7457. devsummaryYOffset += visible_lines;
  7458. refresh_devstatus();
  7459. break;
  7460. }
  7461. #endif
  7462. }
  7463. if (opt_realquiet) {
  7464. disable_curses();
  7465. break;
  7466. }
  7467. }
  7468. return NULL;
  7469. }
  7470. #endif
  7471. static void *api_thread(void *userdata)
  7472. {
  7473. struct thr_info *mythr = userdata;
  7474. pthread_detach(pthread_self());
  7475. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7476. RenameThread("rpc");
  7477. api(api_thr_id);
  7478. mythr->has_pth = false;
  7479. return NULL;
  7480. }
  7481. void thread_reportin(struct thr_info *thr)
  7482. {
  7483. cgtime(&thr->last);
  7484. thr->cgpu->status = LIFE_WELL;
  7485. thr->getwork = 0;
  7486. thr->cgpu->device_last_well = time(NULL);
  7487. }
  7488. void thread_reportout(struct thr_info *thr)
  7489. {
  7490. thr->getwork = time(NULL);
  7491. }
  7492. static void hashmeter(int thr_id, struct timeval *diff,
  7493. uint64_t hashes_done)
  7494. {
  7495. char logstatusline[256];
  7496. struct timeval temp_tv_end, total_diff;
  7497. double secs;
  7498. double local_secs;
  7499. static double local_mhashes_done = 0;
  7500. double local_mhashes = (double)hashes_done / 1000000.0;
  7501. bool showlog = false;
  7502. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7503. char rejpcbuf[6];
  7504. char bnbuf[6];
  7505. struct thr_info *thr;
  7506. /* Update the last time this thread reported in */
  7507. if (thr_id >= 0) {
  7508. thr = get_thread(thr_id);
  7509. cgtime(&(thr->last));
  7510. thr->cgpu->device_last_well = time(NULL);
  7511. }
  7512. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7513. /* So we can call hashmeter from a non worker thread */
  7514. if (thr_id >= 0) {
  7515. struct cgpu_info *cgpu = thr->cgpu;
  7516. int threadobj = cgpu->threads ?: 1;
  7517. double thread_rolling = 0.0;
  7518. int i;
  7519. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7520. thr_id, hashes_done, hashes_done / 1000 / secs);
  7521. /* Rolling average for each thread and each device */
  7522. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7523. for (i = 0; i < threadobj; i++)
  7524. thread_rolling += cgpu->thr[i]->rolling;
  7525. mutex_lock(&hash_lock);
  7526. decay_time(&cgpu->rolling, thread_rolling, secs);
  7527. cgpu->total_mhashes += local_mhashes;
  7528. mutex_unlock(&hash_lock);
  7529. // If needed, output detailed, per-device stats
  7530. if (want_per_device_stats) {
  7531. struct timeval now;
  7532. struct timeval elapsed;
  7533. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7534. cgtime(&now);
  7535. timersub(&now, last_msg_tv, &elapsed);
  7536. if (opt_log_interval <= elapsed.tv_sec) {
  7537. struct cgpu_info *cgpu = thr->cgpu;
  7538. char logline[255];
  7539. *last_msg_tv = now;
  7540. get_statline(logline, sizeof(logline), cgpu);
  7541. if (!curses_active) {
  7542. printf("\n%s\r", logline);
  7543. fflush(stdout);
  7544. } else
  7545. applog(LOG_INFO, "%s", logline);
  7546. }
  7547. }
  7548. }
  7549. /* Totals are updated by all threads so can race without locking */
  7550. mutex_lock(&hash_lock);
  7551. cgtime(&temp_tv_end);
  7552. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7553. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7554. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7555. total_mhashes_done += local_mhashes;
  7556. local_mhashes_done += local_mhashes;
  7557. /* Only update with opt_log_interval */
  7558. if (total_diff.tv_sec < opt_log_interval)
  7559. goto out_unlock;
  7560. showlog = true;
  7561. cgtime(&total_tv_end);
  7562. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7563. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7564. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7565. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7566. multi_format_unit_array2(
  7567. ((char*[]){cHr, aHr, uHr}),
  7568. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7569. true, "h/s", H2B_SHORT,
  7570. 3,
  7571. 1e6*total_rolling,
  7572. 1e6*total_mhashes_done / total_secs,
  7573. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7574. int ui_accepted, ui_rejected, ui_stale;
  7575. if (opt_weighed_stats)
  7576. {
  7577. ui_accepted = total_diff_accepted;
  7578. ui_rejected = total_diff_rejected;
  7579. ui_stale = total_diff_stale;
  7580. }
  7581. else
  7582. {
  7583. ui_accepted = total_accepted;
  7584. ui_rejected = total_rejected;
  7585. ui_stale = total_stale;
  7586. }
  7587. #ifdef HAVE_CURSES
  7588. if (curses_active_locked()) {
  7589. float temp = 0;
  7590. struct cgpu_info *proc, *last_working_dev = NULL;
  7591. int i, working_devs = 0, working_procs = 0;
  7592. int divx;
  7593. bool bad = false;
  7594. // Find the highest temperature of all processors
  7595. for (i = 0; i < total_devices; ++i)
  7596. {
  7597. proc = get_devices(i);
  7598. if (proc->temp > temp)
  7599. temp = proc->temp;
  7600. if (unlikely(proc->deven == DEV_DISABLED))
  7601. ; // Just need to block it off from both conditions
  7602. else
  7603. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7604. {
  7605. if (proc->rolling > .1)
  7606. {
  7607. ++working_procs;
  7608. if (proc->device != last_working_dev)
  7609. {
  7610. ++working_devs;
  7611. last_working_dev = proc->device;
  7612. }
  7613. }
  7614. }
  7615. else
  7616. bad = true;
  7617. }
  7618. if (working_devs == working_procs)
  7619. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7620. else
  7621. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7622. divx = 7;
  7623. if (opt_show_procs && !opt_compact)
  7624. divx += max_lpdigits;
  7625. if (bad)
  7626. {
  7627. divx += sizeof(U8_BAD_START)-1;
  7628. strcpy(&statusline[divx], U8_BAD_END);
  7629. divx += sizeof(U8_BAD_END)-1;
  7630. }
  7631. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7632. format_statline(statusline, sizeof(statusline),
  7633. cHr, aHr,
  7634. uHr,
  7635. ui_accepted,
  7636. ui_rejected,
  7637. ui_stale,
  7638. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7639. hw_errors,
  7640. total_bad_diff1, total_bad_diff1 + total_diff1);
  7641. unlock_curses();
  7642. }
  7643. #endif
  7644. // Add a space
  7645. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7646. uHr[5] = ' ';
  7647. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7648. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7649. snprintf(logstatusline, sizeof(logstatusline),
  7650. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7651. want_per_device_stats ? "ALL " : "",
  7652. opt_log_interval,
  7653. cHr, aHr,
  7654. uHr,
  7655. ui_accepted,
  7656. ui_rejected,
  7657. ui_stale,
  7658. rejpcbuf,
  7659. hw_errors,
  7660. bnbuf
  7661. );
  7662. local_mhashes_done = 0;
  7663. out_unlock:
  7664. mutex_unlock(&hash_lock);
  7665. if (showlog) {
  7666. if (!curses_active) {
  7667. if (want_per_device_stats)
  7668. printf("\n%s\r", logstatusline);
  7669. else
  7670. {
  7671. const int logstatusline_len = strlen(logstatusline);
  7672. int padding;
  7673. if (last_logstatusline_len > logstatusline_len)
  7674. padding = (last_logstatusline_len - logstatusline_len);
  7675. else
  7676. {
  7677. padding = 0;
  7678. if (last_logstatusline_len == -1)
  7679. puts("");
  7680. }
  7681. printf("%s%*s\r", logstatusline, padding, "");
  7682. last_logstatusline_len = logstatusline_len;
  7683. }
  7684. fflush(stdout);
  7685. } else
  7686. applog(LOG_INFO, "%s", logstatusline);
  7687. }
  7688. }
  7689. void hashmeter2(struct thr_info *thr)
  7690. {
  7691. struct timeval tv_now, tv_elapsed;
  7692. timerclear(&thr->tv_hashes_done);
  7693. cgtime(&tv_now);
  7694. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7695. /* Update the hashmeter at most 5 times per second */
  7696. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7697. tv_elapsed.tv_sec >= opt_log_interval) {
  7698. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7699. thr->hashes_done = 0;
  7700. thr->tv_lastupdate = tv_now;
  7701. }
  7702. }
  7703. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7704. struct stratum_share *sshare)
  7705. {
  7706. struct work *work = sshare->work;
  7707. share_result(val, res_val, err_val, work, false, "");
  7708. }
  7709. /* Parses stratum json responses and tries to find the id that the request
  7710. * matched to and treat it accordingly. */
  7711. bool parse_stratum_response(struct pool *pool, char *s)
  7712. {
  7713. json_t *val = NULL, *err_val, *res_val, *id_val;
  7714. struct stratum_share *sshare;
  7715. json_error_t err;
  7716. bool ret = false;
  7717. int id;
  7718. val = JSON_LOADS(s, &err);
  7719. if (!val) {
  7720. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7721. goto out;
  7722. }
  7723. res_val = json_object_get(val, "result");
  7724. err_val = json_object_get(val, "error");
  7725. id_val = json_object_get(val, "id");
  7726. if (json_is_null(id_val) || !id_val) {
  7727. char *ss;
  7728. if (err_val)
  7729. ss = json_dumps(err_val, JSON_INDENT(3));
  7730. else
  7731. ss = strdup("(unknown reason)");
  7732. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7733. free(ss);
  7734. goto out;
  7735. }
  7736. if (!json_is_integer(id_val)) {
  7737. if (json_is_string(id_val)
  7738. && !strncmp(json_string_value(id_val), "txlist", 6))
  7739. {
  7740. const bool is_array = json_is_array(res_val);
  7741. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7742. is_array ? "transaction list" : "no-transaction-list response",
  7743. pool->pool_no, &json_string_value(id_val)[6]);
  7744. if (!is_array)
  7745. {
  7746. // No need to wait for a timeout
  7747. timer_unset(&pool->swork.tv_transparency);
  7748. pool_set_opaque(pool, true);
  7749. goto fishy;
  7750. }
  7751. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7752. // We only care about a transaction list for the current job id
  7753. goto fishy;
  7754. // Check that the transactions actually hash to the merkle links
  7755. {
  7756. unsigned maxtx = 1 << pool->swork.merkles;
  7757. unsigned mintx = maxtx >> 1;
  7758. --maxtx;
  7759. unsigned acttx = (unsigned)json_array_size(res_val);
  7760. if (acttx < mintx || acttx > maxtx) {
  7761. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7762. pool->pool_no, acttx, mintx, maxtx);
  7763. goto fishy;
  7764. }
  7765. // TODO: Check hashes match actual merkle links
  7766. }
  7767. pool_set_opaque(pool, false);
  7768. timer_unset(&pool->swork.tv_transparency);
  7769. fishy:
  7770. ret = true;
  7771. }
  7772. goto out;
  7773. }
  7774. id = json_integer_value(id_val);
  7775. mutex_lock(&sshare_lock);
  7776. HASH_FIND_INT(stratum_shares, &id, sshare);
  7777. if (sshare)
  7778. HASH_DEL(stratum_shares, sshare);
  7779. mutex_unlock(&sshare_lock);
  7780. if (!sshare) {
  7781. double pool_diff;
  7782. /* Since the share is untracked, we can only guess at what the
  7783. * work difficulty is based on the current pool diff. */
  7784. cg_rlock(&pool->data_lock);
  7785. pool_diff = target_diff(pool->swork.target);
  7786. cg_runlock(&pool->data_lock);
  7787. if (json_is_true(res_val)) {
  7788. struct mining_goal_info * const goal = pool->goal;
  7789. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  7790. /* We don't know what device this came from so we can't
  7791. * attribute the work to the relevant cgpu */
  7792. mutex_lock(&stats_lock);
  7793. total_accepted++;
  7794. pool->accepted++;
  7795. total_diff_accepted += pool_diff;
  7796. pool->diff_accepted += pool_diff;
  7797. goal->diff_accepted += pool_diff;
  7798. mutex_unlock(&stats_lock);
  7799. } else {
  7800. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  7801. mutex_lock(&stats_lock);
  7802. total_rejected++;
  7803. pool->rejected++;
  7804. total_diff_rejected += pool_diff;
  7805. pool->diff_rejected += pool_diff;
  7806. mutex_unlock(&stats_lock);
  7807. }
  7808. goto out;
  7809. }
  7810. else {
  7811. mutex_lock(&submitting_lock);
  7812. --total_submitting;
  7813. mutex_unlock(&submitting_lock);
  7814. }
  7815. stratum_share_result(val, res_val, err_val, sshare);
  7816. free_work(sshare->work);
  7817. free(sshare);
  7818. ret = true;
  7819. out:
  7820. if (val)
  7821. json_decref(val);
  7822. return ret;
  7823. }
  7824. static void shutdown_stratum(struct pool *pool)
  7825. {
  7826. // Shut down Stratum as if we never had it
  7827. pool->stratum_active = false;
  7828. pool->stratum_init = false;
  7829. pool->has_stratum = false;
  7830. shutdown(pool->sock, SHUT_RDWR);
  7831. free(pool->stratum_url);
  7832. if (pool->sockaddr_url == pool->stratum_url)
  7833. pool->sockaddr_url = NULL;
  7834. pool->stratum_url = NULL;
  7835. }
  7836. void clear_stratum_shares(struct pool *pool)
  7837. {
  7838. int my_mining_threads = mining_threads; // Cached outside of locking
  7839. struct stratum_share *sshare, *tmpshare;
  7840. struct work *work;
  7841. struct cgpu_info *cgpu;
  7842. double diff_cleared = 0;
  7843. double thr_diff_cleared[my_mining_threads];
  7844. int cleared = 0;
  7845. int thr_cleared[my_mining_threads];
  7846. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7847. for (int i = 0; i < my_mining_threads; ++i)
  7848. {
  7849. thr_diff_cleared[i] = 0;
  7850. thr_cleared[i] = 0;
  7851. }
  7852. mutex_lock(&sshare_lock);
  7853. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7854. work = sshare->work;
  7855. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7856. HASH_DEL(stratum_shares, sshare);
  7857. sharelog("disconnect", work);
  7858. diff_cleared += sshare->work->work_difficulty;
  7859. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7860. ++thr_cleared[work->thr_id];
  7861. free_work(sshare->work);
  7862. free(sshare);
  7863. cleared++;
  7864. }
  7865. }
  7866. mutex_unlock(&sshare_lock);
  7867. if (cleared) {
  7868. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7869. mutex_lock(&stats_lock);
  7870. pool->stale_shares += cleared;
  7871. total_stale += cleared;
  7872. pool->diff_stale += diff_cleared;
  7873. total_diff_stale += diff_cleared;
  7874. for (int i = 0; i < my_mining_threads; ++i)
  7875. if (thr_cleared[i])
  7876. {
  7877. cgpu = get_thr_cgpu(i);
  7878. cgpu->diff_stale += thr_diff_cleared[i];
  7879. cgpu->stale += thr_cleared[i];
  7880. }
  7881. mutex_unlock(&stats_lock);
  7882. mutex_lock(&submitting_lock);
  7883. total_submitting -= cleared;
  7884. mutex_unlock(&submitting_lock);
  7885. }
  7886. }
  7887. static void resubmit_stratum_shares(struct pool *pool)
  7888. {
  7889. struct stratum_share *sshare, *tmpshare;
  7890. struct work *work;
  7891. unsigned resubmitted = 0;
  7892. mutex_lock(&sshare_lock);
  7893. mutex_lock(&submitting_lock);
  7894. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7895. if (sshare->work->pool != pool)
  7896. continue;
  7897. HASH_DEL(stratum_shares, sshare);
  7898. work = sshare->work;
  7899. DL_APPEND(submit_waiting, work);
  7900. free(sshare);
  7901. ++resubmitted;
  7902. }
  7903. mutex_unlock(&submitting_lock);
  7904. mutex_unlock(&sshare_lock);
  7905. if (resubmitted) {
  7906. notifier_wake(submit_waiting_notifier);
  7907. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7908. }
  7909. }
  7910. static void clear_pool_work(struct pool *pool)
  7911. {
  7912. struct work *work, *tmp;
  7913. int cleared = 0;
  7914. mutex_lock(stgd_lock);
  7915. HASH_ITER(hh, staged_work, work, tmp) {
  7916. if (work->pool == pool) {
  7917. HASH_DEL(staged_work, work);
  7918. free_work(work);
  7919. cleared++;
  7920. staged_full = false;
  7921. }
  7922. }
  7923. mutex_unlock(stgd_lock);
  7924. }
  7925. static int cp_prio(void)
  7926. {
  7927. int prio;
  7928. cg_rlock(&control_lock);
  7929. prio = currentpool->prio;
  7930. cg_runlock(&control_lock);
  7931. return prio;
  7932. }
  7933. /* We only need to maintain a secondary pool connection when we need the
  7934. * capacity to get work from the backup pools while still on the primary */
  7935. static bool cnx_needed(struct pool *pool)
  7936. {
  7937. struct pool *cp;
  7938. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  7939. if (pool->enabled == POOL_DISABLED)
  7940. return false;
  7941. /* Idle stratum pool needs something to kick it alive again */
  7942. if (pool->has_stratum && pool->idle)
  7943. return true;
  7944. /* Getwork pools without opt_fail_only need backup pools up to be able
  7945. * to leak shares */
  7946. cp = current_pool();
  7947. if (pool_actively_desired(pool, cp))
  7948. return true;
  7949. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7950. return true;
  7951. /* Keep the connection open to allow any stray shares to be submitted
  7952. * on switching pools for 2 minutes. */
  7953. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  7954. return true;
  7955. /* If the pool has only just come to life and is higher priority than
  7956. * the current pool keep the connection open so we can fail back to
  7957. * it. */
  7958. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7959. return true;
  7960. if (pool_unworkable(cp))
  7961. return true;
  7962. /* We've run out of work, bring anything back to life. */
  7963. if (no_work)
  7964. return true;
  7965. // If the current pool lacks its own block change detection, see if we are needed for that
  7966. if (pool_active_lp_pool(cp) == pool)
  7967. return true;
  7968. return false;
  7969. }
  7970. static void wait_lpcurrent(struct pool *pool);
  7971. static void pool_resus(struct pool *pool);
  7972. static void stratum_resumed(struct pool *pool)
  7973. {
  7974. if (!pool->stratum_notify)
  7975. return;
  7976. if (pool_tclear(pool, &pool->idle)) {
  7977. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7978. pool_resus(pool);
  7979. }
  7980. }
  7981. static bool supports_resume(struct pool *pool)
  7982. {
  7983. bool ret;
  7984. cg_rlock(&pool->data_lock);
  7985. ret = (pool->sessionid != NULL);
  7986. cg_runlock(&pool->data_lock);
  7987. return ret;
  7988. }
  7989. static bool pools_active;
  7990. /* One stratum thread per pool that has stratum waits on the socket checking
  7991. * for new messages and for the integrity of the socket connection. We reset
  7992. * the connection based on the integrity of the receive side only as the send
  7993. * side will eventually expire data it fails to send. */
  7994. static void *stratum_thread(void *userdata)
  7995. {
  7996. struct pool *pool = (struct pool *)userdata;
  7997. pthread_detach(pthread_self());
  7998. char threadname[20];
  7999. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8000. RenameThread(threadname);
  8001. srand(time(NULL) + (intptr_t)userdata);
  8002. while (42) {
  8003. struct timeval timeout;
  8004. int sel_ret;
  8005. fd_set rd;
  8006. char *s;
  8007. int sock;
  8008. if (unlikely(!pool->has_stratum))
  8009. break;
  8010. /* Check to see whether we need to maintain this connection
  8011. * indefinitely or just bring it up when we switch to this
  8012. * pool */
  8013. while (true)
  8014. {
  8015. sock = pool->sock;
  8016. if (sock == INVSOCK)
  8017. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8018. pool->pool_no);
  8019. else
  8020. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8021. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8022. pool->pool_no);
  8023. else
  8024. break;
  8025. suspend_stratum(pool);
  8026. clear_stratum_shares(pool);
  8027. clear_pool_work(pool);
  8028. wait_lpcurrent(pool);
  8029. if (!restart_stratum(pool)) {
  8030. pool_died(pool);
  8031. while (!restart_stratum(pool)) {
  8032. if (pool->removed)
  8033. goto out;
  8034. cgsleep_ms(30000);
  8035. }
  8036. }
  8037. }
  8038. FD_ZERO(&rd);
  8039. FD_SET(sock, &rd);
  8040. timeout.tv_sec = 120;
  8041. timeout.tv_usec = 0;
  8042. /* If we fail to receive any notify messages for 2 minutes we
  8043. * assume the connection has been dropped and treat this pool
  8044. * as dead */
  8045. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8046. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8047. s = NULL;
  8048. } else
  8049. s = recv_line(pool);
  8050. if (!s) {
  8051. if (!pool->has_stratum)
  8052. break;
  8053. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8054. pool->getfail_occasions++;
  8055. total_go++;
  8056. mutex_lock(&pool->stratum_lock);
  8057. pool->stratum_active = pool->stratum_notify = false;
  8058. pool->sock = INVSOCK;
  8059. mutex_unlock(&pool->stratum_lock);
  8060. /* If the socket to our stratum pool disconnects, all
  8061. * submissions need to be discarded or resent. */
  8062. if (!supports_resume(pool))
  8063. clear_stratum_shares(pool);
  8064. else
  8065. resubmit_stratum_shares(pool);
  8066. clear_pool_work(pool);
  8067. if (pool == current_pool())
  8068. restart_threads();
  8069. if (restart_stratum(pool))
  8070. continue;
  8071. shutdown_stratum(pool);
  8072. pool_died(pool);
  8073. break;
  8074. }
  8075. /* Check this pool hasn't died while being a backup pool and
  8076. * has not had its idle flag cleared */
  8077. stratum_resumed(pool);
  8078. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8079. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8080. free(s);
  8081. if (pool->swork.clean) {
  8082. struct work *work = make_work();
  8083. /* Generate a single work item to update the current
  8084. * block database */
  8085. pool->swork.clean = false;
  8086. gen_stratum_work(pool, work);
  8087. /* Try to extract block height from coinbase scriptSig */
  8088. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8089. unsigned char cb_height_sz;
  8090. cb_height_sz = bin_height[-1];
  8091. if (cb_height_sz == 3) {
  8092. // FIXME: The block number will overflow this by AD 2173
  8093. struct mining_goal_info * const goal = pool->goal;
  8094. const void * const prevblkhash = &work->data[4];
  8095. uint32_t height = 0;
  8096. memcpy(&height, bin_height, 3);
  8097. height = le32toh(height);
  8098. have_block_height(goal, prevblkhash, height);
  8099. }
  8100. pool->swork.work_restart_id =
  8101. ++pool->work_restart_id;
  8102. pool_update_work_restart_time(pool);
  8103. if (test_work_current(work)) {
  8104. /* Only accept a work update if this stratum
  8105. * connection is from the current pool */
  8106. struct pool * const cp = current_pool();
  8107. if (pool == cp)
  8108. restart_threads();
  8109. applog(
  8110. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8111. "Stratum from pool %d requested work update", pool->pool_no);
  8112. } else
  8113. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8114. free_work(work);
  8115. }
  8116. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8117. // More than 4 timmills past since requested transactions
  8118. timer_unset(&pool->swork.tv_transparency);
  8119. pool_set_opaque(pool, true);
  8120. }
  8121. }
  8122. out:
  8123. return NULL;
  8124. }
  8125. static void init_stratum_thread(struct pool *pool)
  8126. {
  8127. struct mining_goal_info * const goal = pool->goal;
  8128. goal->have_longpoll = true;
  8129. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8130. quit(1, "Failed to create stratum thread");
  8131. }
  8132. static void *longpoll_thread(void *userdata);
  8133. static bool stratum_works(struct pool *pool)
  8134. {
  8135. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8136. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8137. return false;
  8138. if (pool->stratum_active)
  8139. return true;
  8140. if (!initiate_stratum(pool))
  8141. return false;
  8142. return true;
  8143. }
  8144. static
  8145. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8146. {
  8147. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8148. }
  8149. static bool pool_active(struct pool *pool, bool pinging)
  8150. {
  8151. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8152. bool ret = false;
  8153. json_t *val;
  8154. CURL *curl = NULL;
  8155. int rolltime;
  8156. char *rpc_req;
  8157. struct work *work;
  8158. enum pool_protocol proto;
  8159. if (pool->stratum_init)
  8160. {
  8161. if (pool->stratum_active)
  8162. return true;
  8163. }
  8164. else
  8165. if (!pool->idle)
  8166. {
  8167. timer_set_now(&tv_now);
  8168. if (pool_recently_got_work(pool, &tv_now))
  8169. return true;
  8170. }
  8171. mutex_lock(&pool->pool_test_lock);
  8172. if (pool->stratum_init)
  8173. {
  8174. ret = pool->stratum_active;
  8175. goto out;
  8176. }
  8177. timer_set_now(&tv_now);
  8178. if (pool->idle)
  8179. {
  8180. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8181. goto out;
  8182. }
  8183. else
  8184. if (pool_recently_got_work(pool, &tv_now))
  8185. {
  8186. ret = true;
  8187. goto out;
  8188. }
  8189. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8190. /* This is the central point we activate stratum when we can */
  8191. curl = curl_easy_init();
  8192. if (unlikely(!curl)) {
  8193. applog(LOG_ERR, "CURL initialisation failed");
  8194. goto out;
  8195. }
  8196. if (!(want_gbt || want_getwork))
  8197. goto nohttp;
  8198. work = make_work();
  8199. /* Probe for GBT support on first pass */
  8200. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8201. tryagain:
  8202. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8203. work->pool = pool;
  8204. if (!rpc_req)
  8205. goto out;
  8206. pool->probed = false;
  8207. cgtime(&tv_getwork);
  8208. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8209. true, false, &rolltime, pool, false);
  8210. cgtime(&tv_getwork_reply);
  8211. free(rpc_req);
  8212. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8213. * and if so, switch to that in preference to getwork if it works */
  8214. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8215. if (!pool->has_stratum) {
  8216. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8217. if (!pool->rpc_url)
  8218. pool_set_uri(pool, strdup(pool->stratum_url));
  8219. pool->has_stratum = true;
  8220. }
  8221. free_work(work);
  8222. if (val)
  8223. json_decref(val);
  8224. retry_stratum:
  8225. ;
  8226. /* We create the stratum thread for each pool just after
  8227. * successful authorisation. Once the init flag has been set
  8228. * we never unset it and the stratum thread is responsible for
  8229. * setting/unsetting the active flag */
  8230. bool init = pool_tset(pool, &pool->stratum_init);
  8231. if (!init) {
  8232. ret = initiate_stratum(pool) && auth_stratum(pool);
  8233. if (ret)
  8234. {
  8235. detect_algo = 2;
  8236. init_stratum_thread(pool);
  8237. }
  8238. else
  8239. {
  8240. pool_tclear(pool, &pool->stratum_init);
  8241. pool->tv_idle = tv_getwork_reply;
  8242. }
  8243. goto out;
  8244. }
  8245. ret = pool->stratum_active;
  8246. goto out;
  8247. }
  8248. else if (pool->has_stratum)
  8249. shutdown_stratum(pool);
  8250. if (val) {
  8251. bool rc;
  8252. json_t *res;
  8253. res = json_object_get(val, "result");
  8254. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8255. goto badwork;
  8256. work->rolltime = rolltime;
  8257. rc = work_decode(pool, work, val);
  8258. if (rc) {
  8259. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8260. pool->pool_no, pool->rpc_url);
  8261. work->pool = pool;
  8262. copy_time(&work->tv_getwork, &tv_getwork);
  8263. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8264. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8265. calc_diff(work, 0);
  8266. update_last_work(work);
  8267. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8268. stage_work(work);
  8269. total_getworks++;
  8270. pool->getwork_requested++;
  8271. ret = true;
  8272. pool->tv_idle = tv_getwork_reply;
  8273. } else {
  8274. badwork:
  8275. json_decref(val);
  8276. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8277. pool->pool_no, pool->rpc_url);
  8278. pool->proto = proto = pool_protocol_fallback(proto);
  8279. if (PLP_NONE != proto)
  8280. goto tryagain;
  8281. pool->tv_idle = tv_getwork_reply;
  8282. free_work(work);
  8283. goto out;
  8284. }
  8285. json_decref(val);
  8286. if (proto != pool->proto) {
  8287. pool->proto = proto;
  8288. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8289. }
  8290. if (pool->lp_url)
  8291. goto out;
  8292. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8293. const struct blktmpl_longpoll_req *lp;
  8294. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8295. // NOTE: work_decode takes care of lp id
  8296. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8297. if (!pool->lp_url)
  8298. {
  8299. ret = false;
  8300. goto out;
  8301. }
  8302. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8303. }
  8304. else
  8305. if (pool->hdr_path && want_getwork) {
  8306. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8307. if (!pool->lp_url)
  8308. {
  8309. ret = false;
  8310. goto out;
  8311. }
  8312. pool->lp_proto = PLP_GETWORK;
  8313. } else
  8314. pool->lp_url = NULL;
  8315. if (want_longpoll && !pool->lp_started) {
  8316. pool->lp_started = true;
  8317. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8318. quit(1, "Failed to create pool longpoll thread");
  8319. }
  8320. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8321. pool->proto = proto;
  8322. goto tryagain;
  8323. } else {
  8324. pool->tv_idle = tv_getwork_reply;
  8325. free_work(work);
  8326. nohttp:
  8327. /* If we failed to parse a getwork, this could be a stratum
  8328. * url without the prefix stratum+tcp:// so let's check it */
  8329. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8330. pool->has_stratum = true;
  8331. goto retry_stratum;
  8332. }
  8333. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8334. pool->pool_no, pool->rpc_url);
  8335. if (!pinging)
  8336. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8337. }
  8338. out:
  8339. if (curl)
  8340. curl_easy_cleanup(curl);
  8341. mutex_unlock(&pool->pool_test_lock);
  8342. return ret;
  8343. }
  8344. static void pool_resus(struct pool *pool)
  8345. {
  8346. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8347. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8348. else
  8349. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8350. }
  8351. static
  8352. void *cmd_idle_thread(void * const __maybe_unused userp)
  8353. {
  8354. pthread_detach(pthread_self());
  8355. RenameThread("cmd-idle");
  8356. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8357. sleep(opt_log_interval);
  8358. pthread_testcancel();
  8359. run_cmd(cmd_idle);
  8360. return NULL;
  8361. }
  8362. static struct work *hash_pop(void)
  8363. {
  8364. struct work *work = NULL, *tmp;
  8365. int hc;
  8366. bool did_cmd_idle = false;
  8367. pthread_t cmd_idle_thr;
  8368. retry:
  8369. mutex_lock(stgd_lock);
  8370. while (!HASH_COUNT(staged_work))
  8371. {
  8372. if (unlikely(staged_full))
  8373. {
  8374. if (likely(opt_queue < 10 + mining_threads))
  8375. {
  8376. ++opt_queue;
  8377. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8378. }
  8379. else
  8380. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8381. staged_full = false; // Let it fill up before triggering an underrun again
  8382. no_work = true;
  8383. }
  8384. pthread_cond_signal(&gws_cond);
  8385. if (cmd_idle && !did_cmd_idle)
  8386. {
  8387. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8388. did_cmd_idle = true;
  8389. }
  8390. pthread_cond_wait(&getq->cond, stgd_lock);
  8391. }
  8392. if (did_cmd_idle)
  8393. pthread_cancel(cmd_idle_thr);
  8394. no_work = false;
  8395. hc = HASH_COUNT(staged_work);
  8396. /* Find clone work if possible, to allow masters to be reused */
  8397. if (hc > staged_rollable) {
  8398. HASH_ITER(hh, staged_work, work, tmp) {
  8399. if (!work_rollable(work))
  8400. break;
  8401. }
  8402. } else
  8403. work = staged_work;
  8404. if (can_roll(work) && should_roll(work))
  8405. {
  8406. // Instead of consuming it, force it to be cloned and grab the clone
  8407. mutex_unlock(stgd_lock);
  8408. clone_available();
  8409. goto retry;
  8410. }
  8411. HASH_DEL(staged_work, work);
  8412. if (work_rollable(work))
  8413. staged_rollable--;
  8414. /* Signal the getwork scheduler to look for more work */
  8415. pthread_cond_signal(&gws_cond);
  8416. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8417. pthread_cond_signal(&getq->cond);
  8418. mutex_unlock(stgd_lock);
  8419. work->pool->last_work_time = time(NULL);
  8420. cgtime(&work->pool->tv_last_work_time);
  8421. return work;
  8422. }
  8423. /* Clones work by rolling it if possible, and returning a clone instead of the
  8424. * original work item which gets staged again to possibly be rolled again in
  8425. * the future */
  8426. static struct work *clone_work(struct work *work)
  8427. {
  8428. int mrs = mining_threads + opt_queue - total_staged();
  8429. struct work *work_clone;
  8430. bool cloned;
  8431. if (mrs < 1)
  8432. return work;
  8433. cloned = false;
  8434. work_clone = make_clone(work);
  8435. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8436. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8437. stage_work(work_clone);
  8438. roll_work(work);
  8439. work_clone = make_clone(work);
  8440. /* Roll it again to prevent duplicates should this be used
  8441. * directly later on */
  8442. roll_work(work);
  8443. cloned = true;
  8444. }
  8445. if (cloned) {
  8446. stage_work(work);
  8447. return work_clone;
  8448. }
  8449. free_work(work_clone);
  8450. return work;
  8451. }
  8452. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8453. {
  8454. unsigned char hash1[32];
  8455. sha256(data, len, hash1);
  8456. sha256(hash1, 32, hash);
  8457. }
  8458. /* PDiff 1 is a 256 bit unsigned integer of
  8459. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8460. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8461. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8462. static void pdiff_target_leadzero(void * const target_p, double diff)
  8463. {
  8464. uint8_t *target = target_p;
  8465. diff *= 0x100000000;
  8466. int skip = log2(diff) / 8;
  8467. if (skip)
  8468. {
  8469. if (skip > 0x1c)
  8470. skip = 0x1c;
  8471. diff /= pow(0x100, skip);
  8472. memset(target, 0, skip);
  8473. }
  8474. uint32_t n = 0xffffffff;
  8475. n = (double)n / diff;
  8476. n = htobe32(n);
  8477. memcpy(&target[skip], &n, sizeof(n));
  8478. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8479. }
  8480. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8481. {
  8482. unsigned char rtarget[32];
  8483. pdiff_target_leadzero(rtarget, pdiff);
  8484. swab256(dest_target, rtarget);
  8485. if (opt_debug) {
  8486. char htarget[65];
  8487. bin2hex(htarget, rtarget, 32);
  8488. applog(LOG_DEBUG, "Generated target %s", htarget);
  8489. }
  8490. }
  8491. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8492. {
  8493. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8494. }
  8495. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8496. {
  8497. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8498. int off;
  8499. void (*func)(void *, double) = funcp;
  8500. func(little_endian ? bufr : buf, diff);
  8501. if (little_endian)
  8502. swab256(buf, bufr);
  8503. swap32tobe(expect, expectp, 256/32);
  8504. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8505. for (off = 0; off < 28 && !buf[off]; ++off)
  8506. {}
  8507. if (memcmp(&buf[off], &expect[off], 4))
  8508. {
  8509. testfail: ;
  8510. ++unittest_failures;
  8511. char hexbuf[65], expectbuf[65];
  8512. bin2hex(hexbuf, buf, 32);
  8513. bin2hex(expectbuf, expect, 32);
  8514. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8515. funcname, diff, hexbuf, expectbuf);
  8516. }
  8517. if (!little_endian)
  8518. swab256(bufr, buf);
  8519. swab256(expectr, expect);
  8520. if (!hash_target_check(expectr, bufr))
  8521. goto testfail;
  8522. }
  8523. #define TEST_TARGET(func, le, expect, diff) \
  8524. _test_target(func, #func, le, expect, diff)
  8525. void test_target()
  8526. {
  8527. uint32_t expect[8] = {0};
  8528. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8529. expect[0] = 0x0000ffff;
  8530. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8531. expect[0] = 0;
  8532. expect[1] = 0xffff0000;
  8533. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8534. expect[1] >>= 1;
  8535. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8536. expect[1] >>= 3;
  8537. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8538. expect[1] >>= 4;
  8539. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8540. memset(&expect[1], '\xff', 28);
  8541. expect[0] = 0x0000ffff;
  8542. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8543. expect[0] = 0;
  8544. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8545. expect[1] >>= 1;
  8546. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8547. expect[1] >>= 3;
  8548. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8549. expect[1] >>= 4;
  8550. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8551. }
  8552. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8553. {
  8554. *dst = *src;
  8555. if (dst->tr)
  8556. tmpl_incref(dst->tr);
  8557. dst->nonce1 = maybe_strdup(src->nonce1);
  8558. dst->job_id = maybe_strdup(src->job_id);
  8559. bytes_cpy(&dst->coinbase, &src->coinbase);
  8560. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8561. }
  8562. void stratum_work_clean(struct stratum_work * const swork)
  8563. {
  8564. if (swork->tr)
  8565. tmpl_decref(swork->tr);
  8566. free(swork->nonce1);
  8567. free(swork->job_id);
  8568. bytes_free(&swork->coinbase);
  8569. bytes_free(&swork->merkle_bin);
  8570. }
  8571. bool pool_has_usable_swork(const struct pool * const pool)
  8572. {
  8573. if (opt_benchmark)
  8574. return true;
  8575. if (pool->swork.tr)
  8576. {
  8577. // GBT
  8578. struct timeval tv_now;
  8579. timer_set_now(&tv_now);
  8580. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8581. }
  8582. return pool->stratum_notify;
  8583. }
  8584. /* Generates stratum based work based on the most recent notify information
  8585. * from the pool. This will keep generating work while a pool is down so we use
  8586. * other means to detect when the pool has died in stratum_thread */
  8587. static void gen_stratum_work(struct pool *pool, struct work *work)
  8588. {
  8589. clean_work(work);
  8590. cg_wlock(&pool->data_lock);
  8591. pool->swork.data_lock_p = &pool->data_lock;
  8592. const int n2size = pool->swork.n2size;
  8593. bytes_resize(&work->nonce2, n2size);
  8594. if (pool->nonce2sz < n2size)
  8595. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8596. memcpy(bytes_buf(&work->nonce2),
  8597. #ifdef WORDS_BIGENDIAN
  8598. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8599. &((char*)&pool->nonce2)[pool->nonce2off],
  8600. #else
  8601. &pool->nonce2,
  8602. #endif
  8603. pool->nonce2sz);
  8604. pool->nonce2++;
  8605. work->pool = pool;
  8606. work->work_restart_id = pool->swork.work_restart_id;
  8607. gen_stratum_work2(work, &pool->swork);
  8608. cgtime(&work->tv_staged);
  8609. }
  8610. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8611. {
  8612. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8613. uint8_t *merkle_bin;
  8614. uint32_t *data32, *swap32;
  8615. int i;
  8616. /* Generate coinbase */
  8617. coinbase = bytes_buf(&swork->coinbase);
  8618. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8619. /* Downgrade to a read lock to read off the variables */
  8620. if (swork->data_lock_p)
  8621. cg_dwlock(swork->data_lock_p);
  8622. /* Generate merkle root */
  8623. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8624. memcpy(merkle_sha, merkle_root, 32);
  8625. merkle_bin = bytes_buf(&swork->merkle_bin);
  8626. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8627. memcpy(merkle_sha + 32, merkle_bin, 32);
  8628. gen_hash(merkle_sha, merkle_root, 64);
  8629. memcpy(merkle_sha, merkle_root, 32);
  8630. }
  8631. data32 = (uint32_t *)merkle_sha;
  8632. swap32 = (uint32_t *)merkle_root;
  8633. flip32(swap32, data32);
  8634. memcpy(&work->data[0], swork->header1, 36);
  8635. memcpy(&work->data[36], merkle_root, 32);
  8636. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8637. memcpy(&work->data[72], swork->diffbits, 4);
  8638. memset(&work->data[76], 0, 4); // nonce
  8639. memcpy(&work->data[80], workpadding_bin, 48);
  8640. work->ntime_roll_limits = swork->ntime_roll_limits;
  8641. /* Copy parameters required for share submission */
  8642. memcpy(work->target, swork->target, sizeof(work->target));
  8643. work->job_id = maybe_strdup(swork->job_id);
  8644. work->nonce1 = maybe_strdup(swork->nonce1);
  8645. if (swork->data_lock_p)
  8646. cg_runlock(swork->data_lock_p);
  8647. if (opt_debug)
  8648. {
  8649. char header[161];
  8650. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8651. bin2hex(header, work->data, 80);
  8652. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8653. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8654. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8655. }
  8656. calc_midstate(work);
  8657. local_work++;
  8658. work->stratum = true;
  8659. work->blk.nonce = 0;
  8660. work->id = total_work++;
  8661. work->longpoll = false;
  8662. work->getwork_mode = GETWORK_MODE_STRATUM;
  8663. calc_diff(work, 0);
  8664. }
  8665. void request_work(struct thr_info *thr)
  8666. {
  8667. struct cgpu_info *cgpu = thr->cgpu;
  8668. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8669. /* Tell the watchdog thread this thread is waiting on getwork and
  8670. * should not be restarted */
  8671. thread_reportout(thr);
  8672. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8673. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8674. {
  8675. if (proc->threads)
  8676. break;
  8677. thread_reportout(proc->thr[0]);
  8678. }
  8679. cgtime(&dev_stats->_get_start);
  8680. }
  8681. // FIXME: Make this non-blocking (and remove HACK above)
  8682. struct work *get_work(struct thr_info *thr)
  8683. {
  8684. const int thr_id = thr->id;
  8685. struct cgpu_info *cgpu = thr->cgpu;
  8686. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8687. struct cgminer_stats *pool_stats;
  8688. struct timeval tv_get;
  8689. struct work *work = NULL;
  8690. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8691. while (!work) {
  8692. work = hash_pop();
  8693. if (stale_work(work, false)) {
  8694. staged_full = false; // It wasn't really full, since it was stale :(
  8695. discard_work(work);
  8696. work = NULL;
  8697. wake_gws();
  8698. }
  8699. }
  8700. last_getwork = time(NULL);
  8701. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8702. cgpu->proc_repr, work->id, thr_id);
  8703. work->thr_id = thr_id;
  8704. thread_reportin(thr);
  8705. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8706. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8707. {
  8708. if (proc->threads)
  8709. break;
  8710. thread_reportin(proc->thr[0]);
  8711. }
  8712. work->mined = true;
  8713. work->blk.nonce = 0;
  8714. cgtime(&tv_get);
  8715. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8716. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8717. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8718. dev_stats->getwork_wait_max = tv_get;
  8719. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8720. dev_stats->getwork_wait_min = tv_get;
  8721. ++dev_stats->getwork_calls;
  8722. pool_stats = &(work->pool->cgminer_stats);
  8723. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8724. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8725. pool_stats->getwork_wait_max = tv_get;
  8726. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8727. pool_stats->getwork_wait_min = tv_get;
  8728. ++pool_stats->getwork_calls;
  8729. if (work->work_difficulty < 1)
  8730. {
  8731. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  8732. {
  8733. if (cgpu->min_nonce_diff - work->work_difficulty > 1./0x10000000)
  8734. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  8735. cgpu->proc_repr);
  8736. work->nonce_diff = cgpu->min_nonce_diff;
  8737. }
  8738. else
  8739. work->nonce_diff = work->work_difficulty;
  8740. }
  8741. else
  8742. work->nonce_diff = 1;
  8743. return work;
  8744. }
  8745. struct dupe_hash_elem {
  8746. uint8_t hash[0x20];
  8747. struct timeval tv_prune;
  8748. UT_hash_handle hh;
  8749. };
  8750. static
  8751. void _submit_work_async(struct work *work)
  8752. {
  8753. applog(LOG_DEBUG, "Pushing submit work to work thread");
  8754. if (opt_benchmark)
  8755. {
  8756. json_t * const jn = json_null(), *result = NULL;
  8757. work_check_for_block(work);
  8758. {
  8759. static struct dupe_hash_elem *dupe_hashes;
  8760. struct dupe_hash_elem *dhe, *dhetmp;
  8761. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  8762. if (dhe)
  8763. result = json_string("duplicate");
  8764. else
  8765. {
  8766. struct timeval tv_now;
  8767. timer_set_now(&tv_now);
  8768. // Prune old entries
  8769. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  8770. {
  8771. if (!timer_passed(&dhe->tv_prune, &tv_now))
  8772. break;
  8773. HASH_DEL(dupe_hashes, dhe);
  8774. free(dhe);
  8775. }
  8776. dhe = malloc(sizeof(*dhe));
  8777. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  8778. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  8779. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  8780. }
  8781. }
  8782. if (result)
  8783. {}
  8784. else
  8785. if (stale_work(work, true))
  8786. {
  8787. char stalemsg[0x10];
  8788. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  8789. result = json_string(stalemsg);
  8790. }
  8791. else
  8792. result = json_incref(jn);
  8793. share_result(jn, result, jn, work, false, "");
  8794. free_work(work);
  8795. json_decref(result);
  8796. json_decref(jn);
  8797. return;
  8798. }
  8799. mutex_lock(&submitting_lock);
  8800. ++total_submitting;
  8801. DL_APPEND(submit_waiting, work);
  8802. mutex_unlock(&submitting_lock);
  8803. notifier_wake(submit_waiting_notifier);
  8804. }
  8805. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  8806. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  8807. {
  8808. if (tv_work_found)
  8809. copy_time(&work->tv_work_found, tv_work_found);
  8810. _submit_work_async(work);
  8811. }
  8812. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  8813. {
  8814. struct cgpu_info * const cgpu = thr->cgpu;
  8815. if (bad_nonce_p)
  8816. {
  8817. if (bad_nonce_p == UNKNOWN_NONCE)
  8818. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  8819. cgpu->proc_repr);
  8820. else
  8821. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  8822. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  8823. }
  8824. mutex_lock(&stats_lock);
  8825. hw_errors++;
  8826. ++cgpu->hw_errors;
  8827. if (bad_nonce_p)
  8828. {
  8829. total_bad_diff1 += nonce_diff;
  8830. cgpu->bad_diff1 += nonce_diff;
  8831. }
  8832. mutex_unlock(&stats_lock);
  8833. if (thr->cgpu->drv->hw_error)
  8834. thr->cgpu->drv->hw_error(thr);
  8835. }
  8836. void work_hash(struct work * const work)
  8837. {
  8838. #ifdef USE_SCRYPT
  8839. if (opt_scrypt)
  8840. scrypt_hash_data(work->hash, work->data);
  8841. else
  8842. #endif
  8843. hash_data(work->hash, work->data);
  8844. }
  8845. static
  8846. bool test_hash(const void * const phash, const float diff)
  8847. {
  8848. const uint32_t * const hash = phash;
  8849. if (diff >= 1.)
  8850. // FIXME: > 1 should check more
  8851. return !hash[7];
  8852. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  8853. const uint32_t tmp_hash7 = le32toh(hash[7]);
  8854. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  8855. (long unsigned int)Htarg,
  8856. (long unsigned int)tmp_hash7);
  8857. return (tmp_hash7 <= Htarg);
  8858. }
  8859. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  8860. {
  8861. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8862. *work_nonce = htole32(nonce);
  8863. work_hash(work);
  8864. if (!test_hash(work->hash, work->nonce_diff))
  8865. return TNR_BAD;
  8866. if (checktarget && !hash_target_check_v(work->hash, work->target))
  8867. {
  8868. bool high_hash = true;
  8869. struct pool * const pool = work->pool;
  8870. if (pool->stratum_active)
  8871. {
  8872. // 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
  8873. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  8874. {
  8875. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  8876. pool->pool_no);
  8877. if (hash_target_check_v(work->hash, pool->next_target))
  8878. high_hash = false;
  8879. }
  8880. }
  8881. if (high_hash)
  8882. return TNR_HIGH;
  8883. }
  8884. return TNR_GOOD;
  8885. }
  8886. /* Returns true if nonce for work was a valid share */
  8887. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  8888. {
  8889. return submit_noffset_nonce(thr, work, nonce, 0);
  8890. }
  8891. /* Allows drivers to submit work items where the driver has changed the ntime
  8892. * value by noffset. Must be only used with a work protocol that does not ntime
  8893. * roll itself intrinsically to generate work (eg stratum). We do not touch
  8894. * the original work struct, but the copy of it only. */
  8895. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  8896. int noffset)
  8897. {
  8898. struct work *work = make_work();
  8899. _copy_work(work, work_in, noffset);
  8900. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8901. struct timeval tv_work_found;
  8902. enum test_nonce2_result res;
  8903. bool ret = true;
  8904. thread_reportout(thr);
  8905. cgtime(&tv_work_found);
  8906. *work_nonce = htole32(nonce);
  8907. work->thr_id = thr->id;
  8908. /* Do one last check before attempting to submit the work */
  8909. /* Side effect: sets work->data and work->hash for us */
  8910. res = test_nonce2(work, nonce);
  8911. if (unlikely(res == TNR_BAD))
  8912. {
  8913. inc_hw_errors(thr, work, nonce);
  8914. ret = false;
  8915. goto out;
  8916. }
  8917. mutex_lock(&stats_lock);
  8918. total_diff1 += work->nonce_diff;
  8919. thr ->cgpu->diff1 += work->nonce_diff;
  8920. work->pool->diff1 += work->nonce_diff;
  8921. thr->cgpu->last_device_valid_work = time(NULL);
  8922. mutex_unlock(&stats_lock);
  8923. if (noncelog_file)
  8924. noncelog(work);
  8925. if (res == TNR_HIGH)
  8926. {
  8927. // Share above target, normal
  8928. /* Check the diff of the share, even if it didn't reach the
  8929. * target, just to set the best share value if it's higher. */
  8930. share_diff(work);
  8931. goto out;
  8932. }
  8933. submit_work_async2(work, &tv_work_found);
  8934. work = NULL; // Taken by submit_work_async2
  8935. out:
  8936. if (work)
  8937. free_work(work);
  8938. thread_reportin(thr);
  8939. return ret;
  8940. }
  8941. // return true of we should stop working on this piece of work
  8942. // returning false means we will keep scanning for a nonce
  8943. // assumptions: work->blk.nonce is the number of nonces completed in the work
  8944. // see minerloop_scanhash comments for more details & usage
  8945. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  8946. {
  8947. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  8948. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  8949. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  8950. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  8951. stale_work(work, false)) // work is stale
  8952. return true;
  8953. return false;
  8954. }
  8955. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  8956. {
  8957. struct cgpu_info *proc = thr->cgpu;
  8958. if (proc->threads > 1)
  8959. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  8960. else
  8961. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  8962. }
  8963. // Called by asynchronous minerloops, when they find their processor should be disabled
  8964. void mt_disable_start(struct thr_info *mythr)
  8965. {
  8966. struct cgpu_info *cgpu = mythr->cgpu;
  8967. struct device_drv *drv = cgpu->drv;
  8968. if (drv->thread_disable)
  8969. drv->thread_disable(mythr);
  8970. hashmeter2(mythr);
  8971. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  8972. mythr->rolling = mythr->cgpu->rolling = 0;
  8973. thread_reportout(mythr);
  8974. mythr->_mt_disable_called = true;
  8975. }
  8976. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  8977. * the driver tells us it's full so that it may extract the work item using
  8978. * the get_queued() function which adds it to the hashtable on
  8979. * cgpu->queued_work. */
  8980. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  8981. {
  8982. thread_reportout(mythr);
  8983. do {
  8984. bool need_work;
  8985. /* Do this lockless just to know if we need more unqueued work. */
  8986. need_work = (!cgpu->unqueued_work);
  8987. /* get_work is a blocking function so do it outside of lock
  8988. * to prevent deadlocks with other locks. */
  8989. if (need_work) {
  8990. struct work *work = get_work(mythr);
  8991. wr_lock(&cgpu->qlock);
  8992. /* Check we haven't grabbed work somehow between
  8993. * checking and picking up the lock. */
  8994. if (likely(!cgpu->unqueued_work))
  8995. cgpu->unqueued_work = work;
  8996. else
  8997. need_work = false;
  8998. wr_unlock(&cgpu->qlock);
  8999. if (unlikely(!need_work))
  9000. discard_work(work);
  9001. }
  9002. /* The queue_full function should be used by the driver to
  9003. * actually place work items on the physical device if it
  9004. * does have a queue. */
  9005. } while (drv->queue_full && !drv->queue_full(cgpu));
  9006. }
  9007. /* Add a work item to a cgpu's queued hashlist */
  9008. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9009. {
  9010. cgpu->queued_count++;
  9011. HASH_ADD_INT(cgpu->queued_work, id, work);
  9012. }
  9013. /* This function is for retrieving one work item from the unqueued pointer and
  9014. * adding it to the hashtable of queued work. Code using this function must be
  9015. * able to handle NULL as a return which implies there is no work available. */
  9016. struct work *get_queued(struct cgpu_info *cgpu)
  9017. {
  9018. struct work *work = NULL;
  9019. wr_lock(&cgpu->qlock);
  9020. if (cgpu->unqueued_work) {
  9021. work = cgpu->unqueued_work;
  9022. if (unlikely(stale_work(work, false))) {
  9023. discard_work(work);
  9024. work = NULL;
  9025. wake_gws();
  9026. } else
  9027. __add_queued(cgpu, work);
  9028. cgpu->unqueued_work = NULL;
  9029. }
  9030. wr_unlock(&cgpu->qlock);
  9031. return work;
  9032. }
  9033. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9034. {
  9035. wr_lock(&cgpu->qlock);
  9036. __add_queued(cgpu, work);
  9037. wr_unlock(&cgpu->qlock);
  9038. }
  9039. /* Get fresh work and add it to cgpu's queued hashlist */
  9040. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9041. {
  9042. struct work *work = get_work(thr);
  9043. add_queued(cgpu, work);
  9044. return work;
  9045. }
  9046. /* This function is for finding an already queued work item in the
  9047. * given que hashtable. Code using this function must be able
  9048. * to handle NULL as a return which implies there is no matching work.
  9049. * The calling function must lock access to the que if it is required.
  9050. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9051. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9052. {
  9053. struct work *work, *tmp, *ret = NULL;
  9054. HASH_ITER(hh, que, work, tmp) {
  9055. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9056. memcmp(work->data + offset, data, datalen) == 0) {
  9057. ret = work;
  9058. break;
  9059. }
  9060. }
  9061. return ret;
  9062. }
  9063. /* This function is for finding an already queued work item in the
  9064. * device's queued_work hashtable. Code using this function must be able
  9065. * to handle NULL as a return which implies there is no matching work.
  9066. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9067. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9068. {
  9069. struct work *ret;
  9070. rd_lock(&cgpu->qlock);
  9071. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9072. rd_unlock(&cgpu->qlock);
  9073. return ret;
  9074. }
  9075. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9076. {
  9077. struct work *work, *ret = NULL;
  9078. rd_lock(&cgpu->qlock);
  9079. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9080. if (work)
  9081. ret = copy_work(work);
  9082. rd_unlock(&cgpu->qlock);
  9083. return ret;
  9084. }
  9085. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9086. {
  9087. cgpu->queued_count--;
  9088. HASH_DEL(cgpu->queued_work, work);
  9089. }
  9090. /* This iterates over a queued hashlist finding work started more than secs
  9091. * seconds ago and discards the work as completed. The driver must set the
  9092. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9093. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9094. {
  9095. struct work *work, *tmp;
  9096. struct timeval tv_now;
  9097. int aged = 0;
  9098. cgtime(&tv_now);
  9099. wr_lock(&cgpu->qlock);
  9100. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9101. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9102. __work_completed(cgpu, work);
  9103. aged++;
  9104. }
  9105. }
  9106. wr_unlock(&cgpu->qlock);
  9107. return aged;
  9108. }
  9109. /* This function should be used by queued device drivers when they're sure
  9110. * the work struct is no longer in use. */
  9111. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9112. {
  9113. wr_lock(&cgpu->qlock);
  9114. __work_completed(cgpu, work);
  9115. wr_unlock(&cgpu->qlock);
  9116. free_work(work);
  9117. }
  9118. /* Combines find_queued_work_bymidstate and work_completed in one function
  9119. * withOUT destroying the work so the driver must free it. */
  9120. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9121. {
  9122. struct work *work;
  9123. wr_lock(&cgpu->qlock);
  9124. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9125. if (work)
  9126. __work_completed(cgpu, work);
  9127. wr_unlock(&cgpu->qlock);
  9128. return work;
  9129. }
  9130. void flush_queue(struct cgpu_info *cgpu)
  9131. {
  9132. struct work *work = NULL;
  9133. wr_lock(&cgpu->qlock);
  9134. work = cgpu->unqueued_work;
  9135. cgpu->unqueued_work = NULL;
  9136. wr_unlock(&cgpu->qlock);
  9137. if (work) {
  9138. free_work(work);
  9139. applog(LOG_DEBUG, "Discarded queued work item");
  9140. }
  9141. }
  9142. /* This version of hash work is for devices that are fast enough to always
  9143. * perform a full nonce range and need a queue to maintain the device busy.
  9144. * Work creation and destruction is not done from within this function
  9145. * directly. */
  9146. void hash_queued_work(struct thr_info *mythr)
  9147. {
  9148. const long cycle = opt_log_interval / 5 ? : 1;
  9149. struct timeval tv_start = {0, 0}, tv_end;
  9150. struct cgpu_info *cgpu = mythr->cgpu;
  9151. struct device_drv *drv = cgpu->drv;
  9152. const int thr_id = mythr->id;
  9153. int64_t hashes_done = 0;
  9154. if (unlikely(cgpu->deven != DEV_ENABLED))
  9155. mt_disable(mythr);
  9156. while (likely(!cgpu->shutdown)) {
  9157. struct timeval diff;
  9158. int64_t hashes;
  9159. fill_queue(mythr, cgpu, drv, thr_id);
  9160. thread_reportin(mythr);
  9161. hashes = drv->scanwork(mythr);
  9162. /* Reset the bool here in case the driver looks for it
  9163. * synchronously in the scanwork loop. */
  9164. mythr->work_restart = false;
  9165. if (unlikely(hashes == -1 )) {
  9166. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9167. cgpu->deven = DEV_DISABLED;
  9168. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9169. mt_disable(mythr);
  9170. }
  9171. hashes_done += hashes;
  9172. cgtime(&tv_end);
  9173. timersub(&tv_end, &tv_start, &diff);
  9174. if (diff.tv_sec >= cycle) {
  9175. hashmeter(thr_id, &diff, hashes_done);
  9176. hashes_done = 0;
  9177. copy_time(&tv_start, &tv_end);
  9178. }
  9179. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9180. mt_disable(mythr);
  9181. if (unlikely(mythr->work_restart)) {
  9182. flush_queue(cgpu);
  9183. if (drv->flush_work)
  9184. drv->flush_work(cgpu);
  9185. }
  9186. }
  9187. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9188. }
  9189. // Called by minerloop, when it is re-enabling a processor
  9190. void mt_disable_finish(struct thr_info *mythr)
  9191. {
  9192. struct device_drv *drv = mythr->cgpu->drv;
  9193. thread_reportin(mythr);
  9194. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9195. if (drv->thread_enable)
  9196. drv->thread_enable(mythr);
  9197. mythr->_mt_disable_called = false;
  9198. }
  9199. // Called by synchronous minerloops, when they find their processor should be disabled
  9200. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9201. void mt_disable(struct thr_info *mythr)
  9202. {
  9203. const struct cgpu_info * const cgpu = mythr->cgpu;
  9204. mt_disable_start(mythr);
  9205. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9206. do {
  9207. notifier_read(mythr->notifier);
  9208. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9209. mt_disable_finish(mythr);
  9210. }
  9211. enum {
  9212. STAT_SLEEP_INTERVAL = 1,
  9213. STAT_CTR_INTERVAL = 10000000,
  9214. FAILURE_INTERVAL = 30,
  9215. };
  9216. /* Stage another work item from the work returned in a longpoll */
  9217. 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)
  9218. {
  9219. bool rc;
  9220. work->rolltime = rolltime;
  9221. rc = work_decode(pool, work, val);
  9222. if (unlikely(!rc)) {
  9223. applog(LOG_ERR, "Could not convert longpoll data to work");
  9224. free_work(work);
  9225. return;
  9226. }
  9227. total_getworks++;
  9228. pool->getwork_requested++;
  9229. work->pool = pool;
  9230. copy_time(&work->tv_getwork, tv_lp);
  9231. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9232. calc_diff(work, 0);
  9233. if (pool->enabled == POOL_REJECTING)
  9234. work->mandatory = true;
  9235. work->longpoll = true;
  9236. work->getwork_mode = GETWORK_MODE_LP;
  9237. update_last_work(work);
  9238. /* We'll be checking this work item twice, but we already know it's
  9239. * from a new block so explicitly force the new block detection now
  9240. * rather than waiting for it to hit the stage thread. This also
  9241. * allows testwork to know whether LP discovered the block or not. */
  9242. test_work_current(work);
  9243. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9244. * the longpoll work from a pool that has been rejecting shares as a
  9245. * way to detect when the pool has recovered.
  9246. */
  9247. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9248. free_work(work);
  9249. return;
  9250. }
  9251. work = clone_work(work);
  9252. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9253. stage_work(work);
  9254. applog(LOG_DEBUG, "Converted longpoll data to work");
  9255. }
  9256. /* If we want longpoll, enable it for the chosen default pool, or, if
  9257. * the pool does not support longpoll, find the first one that does
  9258. * and use its longpoll support */
  9259. static
  9260. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9261. {
  9262. int i;
  9263. if (func(cp))
  9264. return cp;
  9265. for (i = 0; i < total_pools; i++) {
  9266. struct pool *pool = pools[i];
  9267. if (cp->goal != pool->goal)
  9268. continue;
  9269. if (func(pool))
  9270. return pool;
  9271. }
  9272. return NULL;
  9273. }
  9274. /* This will make the longpoll thread wait till it's the current pool, or it
  9275. * has been flagged as rejecting, before attempting to open any connections.
  9276. */
  9277. static void wait_lpcurrent(struct pool *pool)
  9278. {
  9279. mutex_lock(&lp_lock);
  9280. while (!cnx_needed(pool))
  9281. {
  9282. pool->lp_active = false;
  9283. pthread_cond_wait(&lp_cond, &lp_lock);
  9284. }
  9285. mutex_unlock(&lp_lock);
  9286. }
  9287. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9288. struct pool *pool = vpool;
  9289. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9290. pool->lp_socket = sock;
  9291. return sock;
  9292. }
  9293. static void *longpoll_thread(void *userdata)
  9294. {
  9295. struct pool *cp = (struct pool *)userdata;
  9296. /* This *pool is the source of the actual longpoll, not the pool we've
  9297. * tied it to */
  9298. struct timeval start, reply, end;
  9299. struct pool *pool = NULL;
  9300. char threadname[20];
  9301. CURL *curl = NULL;
  9302. int failures = 0;
  9303. char *lp_url;
  9304. int rolltime;
  9305. #ifndef HAVE_PTHREAD_CANCEL
  9306. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9307. #endif
  9308. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9309. RenameThread(threadname);
  9310. curl = curl_easy_init();
  9311. if (unlikely(!curl)) {
  9312. applog(LOG_ERR, "CURL initialisation failed");
  9313. return NULL;
  9314. }
  9315. retry_pool:
  9316. pool = select_longpoll_pool(cp);
  9317. if (!pool) {
  9318. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9319. while (!pool) {
  9320. cgsleep_ms(60000);
  9321. pool = select_longpoll_pool(cp);
  9322. }
  9323. }
  9324. if (pool->has_stratum) {
  9325. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9326. cp->rpc_url, pool->rpc_url);
  9327. goto out;
  9328. }
  9329. /* Any longpoll from any pool is enough for this to be true */
  9330. pool->goal->have_longpoll = true;
  9331. wait_lpcurrent(cp);
  9332. {
  9333. lp_url = pool->lp_url;
  9334. if (cp == pool)
  9335. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9336. else
  9337. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9338. }
  9339. while (42) {
  9340. json_t *val, *soval;
  9341. struct work *work = make_work();
  9342. char *lpreq;
  9343. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9344. work->pool = pool;
  9345. if (!lpreq)
  9346. {
  9347. free_work(work);
  9348. goto lpfail;
  9349. }
  9350. wait_lpcurrent(cp);
  9351. cgtime(&start);
  9352. /* Longpoll connections can be persistent for a very long time
  9353. * and any number of issues could have come up in the meantime
  9354. * so always establish a fresh connection instead of relying on
  9355. * a persistent one. */
  9356. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9357. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9358. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9359. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9360. lpreq, false, true, &rolltime, pool, false);
  9361. pool->lp_socket = CURL_SOCKET_BAD;
  9362. cgtime(&reply);
  9363. free(lpreq);
  9364. if (likely(val)) {
  9365. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9366. if (soval)
  9367. pool->submit_old = json_is_true(soval);
  9368. else
  9369. pool->submit_old = false;
  9370. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9371. failures = 0;
  9372. json_decref(val);
  9373. } else {
  9374. /* Some pools regularly drop the longpoll request so
  9375. * only see this as longpoll failure if it happens
  9376. * immediately and just restart it the rest of the
  9377. * time. */
  9378. cgtime(&end);
  9379. free_work(work);
  9380. if (end.tv_sec - start.tv_sec <= 30)
  9381. {
  9382. if (failures == 1)
  9383. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9384. lpfail:
  9385. cgsleep_ms(30000);
  9386. }
  9387. }
  9388. if (pool != cp) {
  9389. pool = select_longpoll_pool(cp);
  9390. if (pool->has_stratum) {
  9391. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9392. cp->rpc_url, pool->rpc_url);
  9393. break;
  9394. }
  9395. if (unlikely(!pool))
  9396. goto retry_pool;
  9397. }
  9398. if (unlikely(pool->removed))
  9399. break;
  9400. }
  9401. out:
  9402. pool->lp_active = false;
  9403. curl_easy_cleanup(curl);
  9404. return NULL;
  9405. }
  9406. static void stop_longpoll(void)
  9407. {
  9408. int i;
  9409. want_longpoll = false;
  9410. for (i = 0; i < total_pools; ++i)
  9411. {
  9412. struct pool *pool = pools[i];
  9413. if (unlikely(!pool->lp_started))
  9414. continue;
  9415. pool->lp_started = false;
  9416. pthread_cancel(pool->longpoll_thread);
  9417. }
  9418. struct mining_goal_info *goal, *tmpgoal;
  9419. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9420. {
  9421. goal->have_longpoll = false;
  9422. }
  9423. }
  9424. static void start_longpoll(void)
  9425. {
  9426. int i;
  9427. want_longpoll = true;
  9428. for (i = 0; i < total_pools; ++i)
  9429. {
  9430. struct pool *pool = pools[i];
  9431. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9432. continue;
  9433. pool->lp_started = true;
  9434. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9435. quit(1, "Failed to create pool longpoll thread");
  9436. }
  9437. }
  9438. void reinit_device(struct cgpu_info *cgpu)
  9439. {
  9440. if (cgpu->drv->reinit_device)
  9441. cgpu->drv->reinit_device(cgpu);
  9442. }
  9443. static struct timeval rotate_tv;
  9444. /* We reap curls if they are unused for over a minute */
  9445. static void reap_curl(struct pool *pool)
  9446. {
  9447. struct curl_ent *ent, *iter;
  9448. struct timeval now;
  9449. int reaped = 0;
  9450. cgtime(&now);
  9451. mutex_lock(&pool->pool_lock);
  9452. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9453. if (pool->curls < 2)
  9454. break;
  9455. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9456. reaped++;
  9457. pool->curls--;
  9458. LL_DELETE(pool->curllist, ent);
  9459. curl_easy_cleanup(ent->curl);
  9460. free(ent);
  9461. }
  9462. }
  9463. mutex_unlock(&pool->pool_lock);
  9464. if (reaped)
  9465. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9466. }
  9467. static void *watchpool_thread(void __maybe_unused *userdata)
  9468. {
  9469. int intervals = 0;
  9470. #ifndef HAVE_PTHREAD_CANCEL
  9471. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9472. #endif
  9473. RenameThread("watchpool");
  9474. while (42) {
  9475. struct timeval now;
  9476. int i;
  9477. if (++intervals > 20)
  9478. intervals = 0;
  9479. cgtime(&now);
  9480. for (i = 0; i < total_pools; i++) {
  9481. struct pool *pool = pools[i];
  9482. if (!opt_benchmark)
  9483. reap_curl(pool);
  9484. /* Get a rolling utility per pool over 10 mins */
  9485. if (intervals > 19) {
  9486. int shares = pool->diff1 - pool->last_shares;
  9487. pool->last_shares = pool->diff1;
  9488. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9489. pool->shares = pool->utility;
  9490. }
  9491. if (pool->enabled == POOL_DISABLED)
  9492. continue;
  9493. /* Don't start testing any pools if the test threads
  9494. * from startup are still doing their first attempt. */
  9495. if (unlikely(pool->testing)) {
  9496. pthread_join(pool->test_thread, NULL);
  9497. }
  9498. /* Test pool is idle once every minute */
  9499. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9500. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9501. pool_resus(pool);
  9502. }
  9503. /* Only switch pools if the failback pool has been
  9504. * alive for more than 5 minutes (default) to prevent
  9505. * intermittently failing pools from being used. */
  9506. 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)
  9507. {
  9508. if (opt_fail_switch_delay % 60)
  9509. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9510. pool->pool_no, pool->rpc_url,
  9511. opt_fail_switch_delay,
  9512. (opt_fail_switch_delay == 1 ? "" : "s"));
  9513. else
  9514. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9515. pool->pool_no, pool->rpc_url,
  9516. opt_fail_switch_delay / 60,
  9517. (opt_fail_switch_delay == 60 ? "" : "s"));
  9518. switch_pools(NULL);
  9519. }
  9520. }
  9521. if (current_pool()->idle)
  9522. switch_pools(NULL);
  9523. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9524. cgtime(&rotate_tv);
  9525. switch_pools(NULL);
  9526. }
  9527. cgsleep_ms(30000);
  9528. }
  9529. return NULL;
  9530. }
  9531. void mt_enable(struct thr_info *thr)
  9532. {
  9533. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9534. notifier_wake(thr->notifier);
  9535. }
  9536. void proc_enable(struct cgpu_info *cgpu)
  9537. {
  9538. int j;
  9539. cgpu->deven = DEV_ENABLED;
  9540. for (j = cgpu->threads ?: 1; j--; )
  9541. mt_enable(cgpu->thr[j]);
  9542. }
  9543. #define device_recovered(cgpu) proc_enable(cgpu)
  9544. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9545. {
  9546. struct string_elist *setstr_elist;
  9547. const char *p, *p2;
  9548. char replybuf[0x2000];
  9549. size_t L;
  9550. DL_FOREACH(opt_set_device_list, setstr_elist)
  9551. {
  9552. const char * const setstr = setstr_elist->string;
  9553. p = strchr(setstr, ':');
  9554. if (!p)
  9555. p = setstr;
  9556. {
  9557. L = p - setstr;
  9558. char pattern[L + 1];
  9559. if (L)
  9560. memcpy(pattern, setstr, L);
  9561. pattern[L] = '\0';
  9562. if (!cgpu_match(pattern, cgpu))
  9563. continue;
  9564. }
  9565. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9566. cgpu->proc_repr, __func__, setstr);
  9567. if (p[0] == ':')
  9568. ++p;
  9569. p2 = strchr(p, '=');
  9570. if (!p2)
  9571. {
  9572. L = strlen(p);
  9573. p2 = "";
  9574. }
  9575. else
  9576. {
  9577. L = p2 - p;
  9578. ++p2;
  9579. }
  9580. char opt[L + 1];
  9581. if (L)
  9582. memcpy(opt, p, L);
  9583. opt[L] = '\0';
  9584. L = strlen(p2);
  9585. char setval[L + 1];
  9586. if (L)
  9587. memcpy(setval, p2, L);
  9588. setval[L] = '\0';
  9589. enum bfg_set_device_replytype success;
  9590. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9591. switch (success)
  9592. {
  9593. case SDR_OK:
  9594. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9595. cgpu->proc_repr, setstr,
  9596. p ? ": " : "", p ?: "");
  9597. break;
  9598. case SDR_ERR:
  9599. case SDR_HELP:
  9600. case SDR_UNKNOWN:
  9601. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9602. cgpu->proc_repr, setstr, p);
  9603. break;
  9604. case SDR_AUTO:
  9605. case SDR_NOSUPP:
  9606. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9607. cgpu->proc_repr, setstr);
  9608. }
  9609. }
  9610. cgpu->already_set_defaults = true;
  9611. }
  9612. 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)
  9613. {
  9614. struct device_drv dummy_drv = *drv;
  9615. struct cgpu_info dummy_cgpu = {
  9616. .drv = &dummy_drv,
  9617. .device = &dummy_cgpu,
  9618. .device_id = -1,
  9619. .proc_id = -1,
  9620. .device_data = userp,
  9621. .device_path = devpath,
  9622. .dev_serial = serial,
  9623. };
  9624. strcpy(dummy_cgpu.proc_repr, drv->name);
  9625. switch (mode)
  9626. {
  9627. case 0:
  9628. dummy_drv.set_device = datap;
  9629. break;
  9630. case 1:
  9631. dummy_drv.set_device = NULL;
  9632. dummy_cgpu.set_device_funcs = datap;
  9633. break;
  9634. }
  9635. cgpu_set_defaults(&dummy_cgpu);
  9636. }
  9637. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9638. * the screen at regular intervals, and restarts threads if they appear to have
  9639. * died. */
  9640. #define WATCHDOG_SICK_TIME 60
  9641. #define WATCHDOG_DEAD_TIME 600
  9642. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9643. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9644. static void *watchdog_thread(void __maybe_unused *userdata)
  9645. {
  9646. const unsigned int interval = WATCHDOG_INTERVAL;
  9647. struct timeval zero_tv;
  9648. #ifndef HAVE_PTHREAD_CANCEL
  9649. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9650. #endif
  9651. RenameThread("watchdog");
  9652. memset(&zero_tv, 0, sizeof(struct timeval));
  9653. cgtime(&rotate_tv);
  9654. while (1) {
  9655. int i;
  9656. struct timeval now;
  9657. sleep(interval);
  9658. discard_stale();
  9659. hashmeter(-1, &zero_tv, 0);
  9660. #ifdef HAVE_CURSES
  9661. const int ts = total_staged();
  9662. if (curses_active_locked()) {
  9663. change_logwinsize();
  9664. curses_print_status(ts);
  9665. _refresh_devstatus(true);
  9666. touchwin(logwin);
  9667. wrefresh(logwin);
  9668. unlock_curses();
  9669. }
  9670. #endif
  9671. cgtime(&now);
  9672. if (!sched_paused && !should_run()) {
  9673. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9674. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9675. if (!schedstart.enable) {
  9676. quit(0, "Terminating execution as planned");
  9677. break;
  9678. }
  9679. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9680. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9681. sched_paused = true;
  9682. rd_lock(&mining_thr_lock);
  9683. for (i = 0; i < mining_threads; i++)
  9684. mining_thr[i]->pause = true;
  9685. rd_unlock(&mining_thr_lock);
  9686. } else if (sched_paused && should_run()) {
  9687. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9688. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9689. if (schedstop.enable)
  9690. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9691. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9692. sched_paused = false;
  9693. for (i = 0; i < mining_threads; i++) {
  9694. struct thr_info *thr;
  9695. thr = get_thread(i);
  9696. thr->pause = false;
  9697. }
  9698. for (i = 0; i < total_devices; ++i)
  9699. {
  9700. struct cgpu_info *cgpu = get_devices(i);
  9701. /* Don't touch disabled devices */
  9702. if (cgpu->deven == DEV_DISABLED)
  9703. continue;
  9704. proc_enable(cgpu);
  9705. }
  9706. }
  9707. for (i = 0; i < total_devices; ++i) {
  9708. struct cgpu_info *cgpu = get_devices(i);
  9709. if (!cgpu->disable_watchdog)
  9710. bfg_watchdog(cgpu, &now);
  9711. }
  9712. }
  9713. return NULL;
  9714. }
  9715. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  9716. {
  9717. struct thr_info *thr = cgpu->thr[0];
  9718. enum dev_enable *denable;
  9719. char *dev_str = cgpu->proc_repr;
  9720. if (likely(drv_ready(cgpu)))
  9721. {
  9722. if (unlikely(!cgpu->already_set_defaults))
  9723. cgpu_set_defaults(cgpu);
  9724. if (cgpu->drv->get_stats)
  9725. cgpu->drv->get_stats(cgpu);
  9726. }
  9727. denable = &cgpu->deven;
  9728. if (cgpu->drv->watchdog)
  9729. cgpu->drv->watchdog(cgpu, tvp_now);
  9730. /* Thread is disabled */
  9731. if (*denable == DEV_DISABLED)
  9732. return;
  9733. else
  9734. if (*denable == DEV_RECOVER_ERR) {
  9735. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  9736. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  9737. dev_str);
  9738. if (cgpu->reinit_backoff < 300)
  9739. cgpu->reinit_backoff *= 2;
  9740. device_recovered(cgpu);
  9741. }
  9742. return;
  9743. }
  9744. else
  9745. if (*denable == DEV_RECOVER) {
  9746. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  9747. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  9748. dev_str);
  9749. device_recovered(cgpu);
  9750. }
  9751. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9752. return;
  9753. }
  9754. else
  9755. if (cgpu->temp > cgpu->cutofftemp)
  9756. {
  9757. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  9758. dev_str, (int)cgpu->temp);
  9759. *denable = DEV_RECOVER;
  9760. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9761. run_cmd(cmd_idle);
  9762. }
  9763. if (thr->getwork) {
  9764. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  9765. int thrid;
  9766. bool cgpu_idle = true;
  9767. thr->rolling = 0;
  9768. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  9769. if (!cgpu->thr[thrid]->getwork)
  9770. cgpu_idle = false;
  9771. if (cgpu_idle) {
  9772. cgpu->rolling = 0;
  9773. cgpu->status = LIFE_WAIT;
  9774. }
  9775. }
  9776. return;
  9777. }
  9778. else if (cgpu->status == LIFE_WAIT)
  9779. cgpu->status = LIFE_WELL;
  9780. #ifdef WANT_CPUMINE
  9781. if (!strcmp(cgpu->drv->dname, "cpu"))
  9782. return;
  9783. #endif
  9784. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  9785. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  9786. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  9787. cgpu->status = LIFE_WELL;
  9788. cgpu->device_last_well = time(NULL);
  9789. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  9790. thr->rolling = cgpu->rolling = 0;
  9791. cgpu->status = LIFE_SICK;
  9792. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  9793. cgtime(&thr->sick);
  9794. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  9795. run_cmd(cmd_sick);
  9796. if (opt_restart && cgpu->drv->reinit_device) {
  9797. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  9798. reinit_device(cgpu);
  9799. }
  9800. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  9801. cgpu->status = LIFE_DEAD;
  9802. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  9803. cgtime(&thr->sick);
  9804. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  9805. run_cmd(cmd_dead);
  9806. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  9807. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  9808. /* Attempt to restart a GPU that's sick or dead once every minute */
  9809. cgtime(&thr->sick);
  9810. if (opt_restart)
  9811. reinit_device(cgpu);
  9812. }
  9813. }
  9814. static void log_print_status(struct cgpu_info *cgpu)
  9815. {
  9816. char logline[255];
  9817. get_statline(logline, sizeof(logline), cgpu);
  9818. applog(LOG_WARNING, "%s", logline);
  9819. }
  9820. void print_summary(void)
  9821. {
  9822. struct timeval diff;
  9823. int hours, mins, secs, i;
  9824. double utility, efficiency = 0.0;
  9825. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  9826. int pool_secs;
  9827. timersub(&total_tv_end, &total_tv_start, &diff);
  9828. hours = diff.tv_sec / 3600;
  9829. mins = (diff.tv_sec % 3600) / 60;
  9830. secs = diff.tv_sec % 60;
  9831. utility = total_accepted / total_secs * 60;
  9832. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  9833. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  9834. applog(LOG_WARNING, "Started at %s", datestamp);
  9835. if (total_pools == 1)
  9836. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  9837. #ifdef WANT_CPUMINE
  9838. if (opt_n_threads > 0)
  9839. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  9840. #endif
  9841. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  9842. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  9843. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  9844. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  9845. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  9846. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  9847. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  9848. total_rejected, total_stale,
  9849. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  9850. );
  9851. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  9852. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  9853. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  9854. applog(LOG_WARNING, "Network transfer: %s (%s)",
  9855. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9856. (float)total_bytes_rcvd,
  9857. (float)total_bytes_sent),
  9858. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9859. (float)(total_bytes_rcvd / total_secs),
  9860. (float)(total_bytes_sent / total_secs)));
  9861. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  9862. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  9863. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  9864. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  9865. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  9866. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  9867. if (total_pools > 1) {
  9868. for (i = 0; i < total_pools; i++) {
  9869. struct pool *pool = pools[i];
  9870. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  9871. if (pool->solved)
  9872. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  9873. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  9874. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  9875. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  9876. pool->rejected, pool->stale_shares,
  9877. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  9878. );
  9879. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  9880. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  9881. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  9882. applog(LOG_WARNING, " Network transfer: %s (%s)",
  9883. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9884. (float)pool->cgminer_pool_stats.net_bytes_received,
  9885. (float)pool->cgminer_pool_stats.net_bytes_sent),
  9886. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9887. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  9888. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  9889. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  9890. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  9891. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  9892. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  9893. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  9894. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  9895. }
  9896. }
  9897. if (opt_quit_summary != BQS_NONE)
  9898. {
  9899. if (opt_quit_summary == BQS_DEFAULT)
  9900. {
  9901. if (total_devices < 25)
  9902. opt_quit_summary = BQS_PROCS;
  9903. else
  9904. opt_quit_summary = BQS_DEVS;
  9905. }
  9906. if (opt_quit_summary == BQS_DETAILED)
  9907. include_serial_in_statline = true;
  9908. applog(LOG_WARNING, "Summary of per device statistics:\n");
  9909. for (i = 0; i < total_devices; ++i) {
  9910. struct cgpu_info *cgpu = get_devices(i);
  9911. if (!cgpu->proc_id)
  9912. {
  9913. // Device summary line
  9914. opt_show_procs = false;
  9915. log_print_status(cgpu);
  9916. opt_show_procs = true;
  9917. }
  9918. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  9919. log_print_status(cgpu);
  9920. }
  9921. }
  9922. if (opt_shares) {
  9923. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  9924. if (opt_shares > total_diff_accepted)
  9925. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  9926. }
  9927. applog(LOG_WARNING, " ");
  9928. fflush(stderr);
  9929. fflush(stdout);
  9930. }
  9931. void _bfg_clean_up(bool restarting)
  9932. {
  9933. #ifdef HAVE_OPENCL
  9934. clear_adl(nDevs);
  9935. #endif
  9936. #ifdef HAVE_LIBUSB
  9937. if (likely(have_libusb))
  9938. libusb_exit(NULL);
  9939. #endif
  9940. cgtime(&total_tv_end);
  9941. #ifdef WIN32
  9942. timeEndPeriod(1);
  9943. #endif
  9944. if (!restarting) {
  9945. /* Attempting to disable curses or print a summary during a
  9946. * restart can lead to a deadlock. */
  9947. #ifdef HAVE_CURSES
  9948. disable_curses();
  9949. #endif
  9950. if (!opt_realquiet && successful_connect)
  9951. print_summary();
  9952. }
  9953. if (opt_n_threads > 0)
  9954. free(cpus);
  9955. curl_global_cleanup();
  9956. #ifdef WIN32
  9957. WSACleanup();
  9958. #endif
  9959. }
  9960. void _quit(int status)
  9961. {
  9962. if (status) {
  9963. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  9964. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  9965. int *p = NULL;
  9966. // NOTE debugger can bypass with: p = &p
  9967. *p = status; // Segfault, hopefully dumping core
  9968. }
  9969. }
  9970. #if defined(unix) || defined(__APPLE__)
  9971. if (forkpid > 0) {
  9972. kill(forkpid, SIGTERM);
  9973. forkpid = 0;
  9974. }
  9975. #endif
  9976. exit(status);
  9977. }
  9978. #ifdef HAVE_CURSES
  9979. char *curses_input(const char *query)
  9980. {
  9981. char *input;
  9982. echo();
  9983. input = malloc(255);
  9984. if (!input)
  9985. quit(1, "Failed to malloc input");
  9986. leaveok(logwin, false);
  9987. wlogprint("%s:\n", query);
  9988. wgetnstr(logwin, input, 255);
  9989. if (!strlen(input))
  9990. {
  9991. free(input);
  9992. input = NULL;
  9993. }
  9994. leaveok(logwin, true);
  9995. noecho();
  9996. return input;
  9997. }
  9998. #endif
  9999. static void *test_pool_thread(void *arg)
  10000. {
  10001. struct pool *pool = (struct pool *)arg;
  10002. if (pool_active(pool, false)) {
  10003. pool_tset(pool, &pool->lagging);
  10004. pool_tclear(pool, &pool->idle);
  10005. bool first_pool = false;
  10006. cg_wlock(&control_lock);
  10007. if (!pools_active) {
  10008. currentpool = pool;
  10009. if (pool->pool_no != 0)
  10010. first_pool = true;
  10011. pools_active = true;
  10012. }
  10013. cg_wunlock(&control_lock);
  10014. if (unlikely(first_pool))
  10015. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10016. else
  10017. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10018. switch_pools(NULL);
  10019. } else
  10020. pool_died(pool);
  10021. pool->testing = false;
  10022. return NULL;
  10023. }
  10024. /* Always returns true that the pool details were added unless we are not
  10025. * live, implying this is the only pool being added, so if no pools are
  10026. * active it returns false. */
  10027. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10028. {
  10029. size_t siz;
  10030. pool_set_uri(pool, url);
  10031. pool->rpc_user = user;
  10032. pool->rpc_pass = pass;
  10033. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10034. pool->rpc_userpass = malloc(siz);
  10035. if (!pool->rpc_userpass)
  10036. quit(1, "Failed to malloc userpass");
  10037. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10038. pool->testing = true;
  10039. pool->idle = true;
  10040. enable_pool(pool);
  10041. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10042. if (!live) {
  10043. pthread_join(pool->test_thread, NULL);
  10044. return pools_active;
  10045. }
  10046. return true;
  10047. }
  10048. #ifdef HAVE_CURSES
  10049. static bool input_pool(bool live)
  10050. {
  10051. char *url = NULL, *user = NULL, *pass = NULL;
  10052. struct pool *pool;
  10053. bool ret = false;
  10054. immedok(logwin, true);
  10055. wlogprint("Input server details.\n");
  10056. url = curses_input("URL");
  10057. if (!url)
  10058. goto out;
  10059. user = curses_input("Username");
  10060. if (!user)
  10061. goto out;
  10062. pass = curses_input("Password");
  10063. if (!pass)
  10064. pass = calloc(1, 1);
  10065. pool = add_pool();
  10066. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10067. strncmp(url, "https://", 8)) {
  10068. char *httpinput;
  10069. httpinput = malloc(256);
  10070. if (!httpinput)
  10071. quit(1, "Failed to malloc httpinput");
  10072. strcpy(httpinput, "http://");
  10073. strncat(httpinput, url, 248);
  10074. free(url);
  10075. url = httpinput;
  10076. }
  10077. ret = add_pool_details(pool, live, url, user, pass);
  10078. out:
  10079. immedok(logwin, false);
  10080. if (!ret) {
  10081. if (url)
  10082. free(url);
  10083. if (user)
  10084. free(user);
  10085. if (pass)
  10086. free(pass);
  10087. }
  10088. return ret;
  10089. }
  10090. #endif
  10091. #if BLKMAKER_VERSION > 1
  10092. static
  10093. bool _add_local_gbt(const char * const filepath, void *userp)
  10094. {
  10095. const bool * const live_p = userp;
  10096. struct pool *pool;
  10097. char buf[0x100];
  10098. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10099. int rpcport = 0, rpcssl = -101;
  10100. FILE * const F = fopen(filepath, "r");
  10101. if (!F)
  10102. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10103. while (fgets(buf, sizeof(buf), F))
  10104. {
  10105. if (!strncasecmp(buf, "rpcuser=", 8))
  10106. rpcuser = trimmed_strdup(&buf[8]);
  10107. else
  10108. if (!strncasecmp(buf, "rpcpassword=", 12))
  10109. rpcpass = trimmed_strdup(&buf[12]);
  10110. else
  10111. if (!strncasecmp(buf, "rpcport=", 8))
  10112. rpcport = atoi(&buf[8]);
  10113. else
  10114. if (!strncasecmp(buf, "rpcssl=", 7))
  10115. rpcssl = atoi(&buf[7]);
  10116. else
  10117. if (!strncasecmp(buf, "rpcconnect=", 11))
  10118. rpcconnect = trimmed_strdup(&buf[11]);
  10119. else
  10120. continue;
  10121. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10122. break;
  10123. }
  10124. fclose(F);
  10125. if (!rpcpass)
  10126. {
  10127. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10128. err:
  10129. free(rpcuser);
  10130. free(rpcpass);
  10131. goto out;
  10132. }
  10133. if (!rpcport)
  10134. rpcport = 8332;
  10135. if (rpcssl == -101)
  10136. rpcssl = 0;
  10137. const bool have_cbaddr = bytes_len(&opt_coinbase_script);
  10138. const int uri_sz = 0x30;
  10139. char * const uri = malloc(uri_sz);
  10140. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10141. char hfuri[0x40];
  10142. if (rpcconnect)
  10143. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10144. else
  10145. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10146. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10147. for (int i = 0; i < total_pools; ++i)
  10148. {
  10149. struct pool *pool = pools[i];
  10150. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10151. {
  10152. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10153. free(uri);
  10154. goto err;
  10155. }
  10156. }
  10157. pool = add_pool();
  10158. if (!pool)
  10159. {
  10160. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10161. goto err;
  10162. }
  10163. if (!rpcuser)
  10164. rpcuser = "";
  10165. pool->quota = 0;
  10166. adjust_quota_gcd();
  10167. pool->failover_only = true;
  10168. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10169. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10170. out:
  10171. return false;
  10172. }
  10173. static
  10174. void add_local_gbt(bool live)
  10175. {
  10176. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10177. }
  10178. #endif
  10179. #if defined(unix) || defined(__APPLE__)
  10180. static void fork_monitor()
  10181. {
  10182. // Make a pipe: [readFD, writeFD]
  10183. int pfd[2];
  10184. int r = pipe(pfd);
  10185. if (r < 0) {
  10186. perror("pipe - failed to create pipe for --monitor");
  10187. exit(1);
  10188. }
  10189. // Make stderr write end of pipe
  10190. fflush(stderr);
  10191. r = dup2(pfd[1], 2);
  10192. if (r < 0) {
  10193. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10194. exit(1);
  10195. }
  10196. r = close(pfd[1]);
  10197. if (r < 0) {
  10198. perror("close - failed to close write end of pipe for --monitor");
  10199. exit(1);
  10200. }
  10201. // Don't allow a dying monitor to kill the main process
  10202. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10203. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10204. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10205. perror("signal - failed to edit signal mask for --monitor");
  10206. exit(1);
  10207. }
  10208. // Fork a child process
  10209. forkpid = fork();
  10210. if (forkpid < 0) {
  10211. perror("fork - failed to fork child process for --monitor");
  10212. exit(1);
  10213. }
  10214. // Child: launch monitor command
  10215. if (0 == forkpid) {
  10216. // Make stdin read end of pipe
  10217. r = dup2(pfd[0], 0);
  10218. if (r < 0) {
  10219. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10220. exit(1);
  10221. }
  10222. close(pfd[0]);
  10223. if (r < 0) {
  10224. perror("close - in child, failed to close read end of pipe for --monitor");
  10225. exit(1);
  10226. }
  10227. // Launch user specified command
  10228. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10229. perror("execl - in child failed to exec user specified command for --monitor");
  10230. exit(1);
  10231. }
  10232. // Parent: clean up unused fds and bail
  10233. r = close(pfd[0]);
  10234. if (r < 0) {
  10235. perror("close - failed to close read end of pipe for --monitor");
  10236. exit(1);
  10237. }
  10238. }
  10239. #endif // defined(unix)
  10240. #ifdef HAVE_CURSES
  10241. #ifdef USE_UNICODE
  10242. static
  10243. wchar_t select_unicode_char(const wchar_t *opt)
  10244. {
  10245. for ( ; *opt; ++opt)
  10246. if (iswprint(*opt))
  10247. return *opt;
  10248. return '?';
  10249. }
  10250. #endif
  10251. void enable_curses(void) {
  10252. int x;
  10253. __maybe_unused int y;
  10254. lock_curses();
  10255. if (curses_active) {
  10256. unlock_curses();
  10257. return;
  10258. }
  10259. #ifdef USE_UNICODE
  10260. if (use_unicode)
  10261. {
  10262. setlocale(LC_CTYPE, "");
  10263. if (iswprint(0xb0))
  10264. have_unicode_degrees = true;
  10265. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10266. }
  10267. #endif
  10268. mainwin = initscr();
  10269. start_color();
  10270. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10271. if (ERR != use_default_colors())
  10272. default_bgcolor = -1;
  10273. #endif
  10274. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10275. {
  10276. menu_attr = COLOR_PAIR(1);
  10277. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10278. attr_bad |= COLOR_PAIR(2);
  10279. }
  10280. keypad(mainwin, true);
  10281. getmaxyx(mainwin, y, x);
  10282. statuswin = newwin(logstart, x, 0, 0);
  10283. leaveok(statuswin, true);
  10284. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10285. // We resize the window later anyway, so just start it off at 1 :)
  10286. logwin = newwin(1, 0, logcursor, 0);
  10287. idlok(logwin, true);
  10288. scrollok(logwin, true);
  10289. leaveok(logwin, true);
  10290. cbreak();
  10291. noecho();
  10292. nonl();
  10293. curses_active = true;
  10294. statusy = logstart;
  10295. unlock_curses();
  10296. }
  10297. #endif
  10298. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10299. #ifndef WANT_CPUMINE
  10300. struct device_drv cpu_drv;
  10301. struct device_drv cpu_drv = {
  10302. .name = "CPU",
  10303. };
  10304. #endif
  10305. static int cgminer_id_count = 0;
  10306. static int device_line_id_count;
  10307. void register_device(struct cgpu_info *cgpu)
  10308. {
  10309. cgpu->deven = DEV_ENABLED;
  10310. wr_lock(&devices_lock);
  10311. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10312. wr_unlock(&devices_lock);
  10313. if (!cgpu->proc_id)
  10314. cgpu->device_line_id = device_line_id_count++;
  10315. int thr_objs = cgpu->threads ?: 1;
  10316. mining_threads += thr_objs;
  10317. base_queue += thr_objs + cgpu->extra_work_queue;
  10318. #ifdef HAVE_CURSES
  10319. adj_width(mining_threads, &dev_width);
  10320. #endif
  10321. rwlock_init(&cgpu->qlock);
  10322. cgpu->queued_work = NULL;
  10323. }
  10324. struct _cgpu_devid_counter {
  10325. char name[4];
  10326. int lastid;
  10327. UT_hash_handle hh;
  10328. };
  10329. void renumber_cgpu(struct cgpu_info *cgpu)
  10330. {
  10331. static struct _cgpu_devid_counter *devids = NULL;
  10332. struct _cgpu_devid_counter *d;
  10333. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10334. if (d)
  10335. cgpu->device_id = ++d->lastid;
  10336. else {
  10337. d = malloc(sizeof(*d));
  10338. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10339. cgpu->device_id = d->lastid = 0;
  10340. HASH_ADD_STR(devids, name, d);
  10341. }
  10342. // Build repr strings
  10343. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10344. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10345. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10346. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10347. const int lpcount = cgpu->procs;
  10348. if (lpcount > 1)
  10349. {
  10350. int ns;
  10351. struct cgpu_info *slave;
  10352. int lpdigits = 1;
  10353. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10354. ++lpdigits;
  10355. if (lpdigits > max_lpdigits)
  10356. max_lpdigits = lpdigits;
  10357. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10358. cgpu->proc_repr[5 + lpdigits] = '\0';
  10359. ns = strlen(cgpu->proc_repr_ns);
  10360. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10361. slave = cgpu;
  10362. for (int i = 1; i < lpcount; ++i)
  10363. {
  10364. slave = slave->next_proc;
  10365. strcpy(slave->proc_repr, cgpu->proc_repr);
  10366. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10367. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10368. {
  10369. slave->proc_repr_ns[ns + y] =
  10370. slave->proc_repr[5 + y] += (x % 26);
  10371. }
  10372. }
  10373. }
  10374. }
  10375. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10376. {
  10377. sha256(buffer, length, digest);
  10378. return true;
  10379. }
  10380. static
  10381. int drv_algo_check(const struct device_drv * const drv)
  10382. {
  10383. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  10384. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  10385. return (algos & algomatch);
  10386. }
  10387. #ifndef HAVE_PTHREAD_CANCEL
  10388. extern void setup_pthread_cancel_workaround();
  10389. extern struct sigaction pcwm_orig_term_handler;
  10390. #endif
  10391. bool bfg_need_detect_rescan;
  10392. extern void probe_device(struct lowlevel_device_info *);
  10393. static void schedule_rescan(const struct timeval *);
  10394. static
  10395. void drv_detect_all()
  10396. {
  10397. bool rescanning = false;
  10398. rescan:
  10399. bfg_need_detect_rescan = false;
  10400. #ifdef HAVE_BFG_LOWLEVEL
  10401. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10402. LL_FOREACH_SAFE(infolist, info, infotmp)
  10403. probe_device(info);
  10404. LL_FOREACH_SAFE(infolist, info, infotmp)
  10405. pthread_join(info->probe_pth, NULL);
  10406. #endif
  10407. struct driver_registration *reg, *tmp;
  10408. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10409. {
  10410. const struct device_drv * const drv = reg->drv;
  10411. if (!(drv_algo_check(drv) && drv->drv_detect))
  10412. continue;
  10413. drv->drv_detect();
  10414. }
  10415. #ifdef HAVE_BFG_LOWLEVEL
  10416. lowlevel_scan_free();
  10417. #endif
  10418. if (bfg_need_detect_rescan)
  10419. {
  10420. if (rescanning)
  10421. {
  10422. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10423. struct timeval tv_when;
  10424. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10425. schedule_rescan(&tv_when);
  10426. }
  10427. else
  10428. {
  10429. rescanning = true;
  10430. applog(LOG_DEBUG, "Device rescan requested");
  10431. goto rescan;
  10432. }
  10433. }
  10434. }
  10435. static
  10436. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10437. {
  10438. struct thr_info *thr;
  10439. int j;
  10440. struct device_drv *api = cgpu->drv;
  10441. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10442. int threadobj = cgpu->threads;
  10443. if (!threadobj)
  10444. // Create a fake thread object to handle hashmeter etc
  10445. threadobj = 1;
  10446. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10447. cgpu->thr[threadobj] = NULL;
  10448. cgpu->status = LIFE_INIT;
  10449. if (opt_devices_enabled_list)
  10450. {
  10451. struct string_elist *enablestr_elist;
  10452. cgpu->deven = DEV_DISABLED;
  10453. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10454. {
  10455. const char * const enablestr = enablestr_elist->string;
  10456. if (cgpu_match(enablestr, cgpu))
  10457. {
  10458. cgpu->deven = DEV_ENABLED;
  10459. break;
  10460. }
  10461. }
  10462. }
  10463. cgpu->max_hashes = 0;
  10464. BFGINIT(cgpu->min_nonce_diff, 1);
  10465. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10466. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10467. // Setup thread structs before starting any of the threads, in case they try to interact
  10468. for (j = 0; j < threadobj; ++j, ++*kp) {
  10469. thr = get_thread(*kp);
  10470. thr->id = *kp;
  10471. thr->cgpu = cgpu;
  10472. thr->device_thread = j;
  10473. thr->work_restart_notifier[1] = INVSOCK;
  10474. thr->mutex_request[1] = INVSOCK;
  10475. thr->_job_transition_in_progress = true;
  10476. timerclear(&thr->tv_morework);
  10477. thr->scanhash_working = true;
  10478. thr->hashes_done = 0;
  10479. timerclear(&thr->tv_hashes_done);
  10480. cgtime(&thr->tv_lastupdate);
  10481. thr->tv_poll.tv_sec = -1;
  10482. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10483. cgpu->thr[j] = thr;
  10484. }
  10485. if (!cgpu->device->threads)
  10486. notifier_init_invalid(cgpu->thr[0]->notifier);
  10487. else
  10488. if (!cgpu->threads)
  10489. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10490. else
  10491. for (j = 0; j < cgpu->threads; ++j)
  10492. {
  10493. thr = cgpu->thr[j];
  10494. notifier_init(thr->notifier);
  10495. }
  10496. }
  10497. static
  10498. void start_cgpu(struct cgpu_info *cgpu)
  10499. {
  10500. struct thr_info *thr;
  10501. int j;
  10502. for (j = 0; j < cgpu->threads; ++j) {
  10503. thr = cgpu->thr[j];
  10504. /* Enable threads for devices set not to mine but disable
  10505. * their queue in case we wish to enable them later */
  10506. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10507. continue;
  10508. thread_reportout(thr);
  10509. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10510. quit(1, "thread %d create failed", thr->id);
  10511. notifier_wake(thr->notifier);
  10512. }
  10513. if (cgpu->deven == DEV_ENABLED)
  10514. proc_enable(cgpu);
  10515. }
  10516. static
  10517. void _scan_serial(void *p)
  10518. {
  10519. const char *s = p;
  10520. struct string_elist *iter, *tmp;
  10521. struct string_elist *orig_scan_devices = scan_devices;
  10522. if (s)
  10523. {
  10524. // Make temporary scan_devices list
  10525. scan_devices = NULL;
  10526. string_elist_add("noauto", &scan_devices);
  10527. add_serial(s);
  10528. }
  10529. drv_detect_all();
  10530. if (s)
  10531. {
  10532. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10533. {
  10534. string_elist_del(&scan_devices, iter);
  10535. }
  10536. scan_devices = orig_scan_devices;
  10537. }
  10538. }
  10539. #ifdef HAVE_BFG_LOWLEVEL
  10540. static
  10541. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10542. {
  10543. if (!(false
  10544. || (info->serial && !strcasecmp(ser, info->serial))
  10545. || (info->path && !strcasecmp(ser, info->path ))
  10546. || (info->devid && !strcasecmp(ser, info->devid ))
  10547. ))
  10548. {
  10549. char *devid = devpath_to_devid(ser);
  10550. if (!devid)
  10551. return false;
  10552. const bool different = strcmp(info->devid, devid);
  10553. free(devid);
  10554. if (different)
  10555. return false;
  10556. }
  10557. return true;
  10558. }
  10559. static
  10560. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10561. {
  10562. struct driver_registration *dreg;
  10563. char dname[dnamelen];
  10564. int i;
  10565. for (i = 0; i < dnamelen; ++i)
  10566. dname[i] = tolower(_dname[i]);
  10567. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10568. if (!dreg)
  10569. {
  10570. for (i = 0; i < dnamelen; ++i)
  10571. dname[i] = toupper(_dname[i]);
  10572. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10573. if (!dreg)
  10574. return NULL;
  10575. }
  10576. if (!drv_algo_check(dreg->drv))
  10577. return NULL;
  10578. return dreg->drv;
  10579. }
  10580. static
  10581. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10582. {
  10583. bfg_probe_result_flags = 0;
  10584. if (drv->lowl_probe(info))
  10585. {
  10586. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10587. return true;
  10588. }
  10589. else
  10590. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10591. *request_rescan_p = true;
  10592. return false;
  10593. }
  10594. bool dummy_check_never_true = false;
  10595. static
  10596. void *probe_device_thread(void *p)
  10597. {
  10598. struct lowlevel_device_info * const infolist = p;
  10599. struct lowlevel_device_info *info = infolist;
  10600. bool request_rescan = false;
  10601. {
  10602. char threadname[5 + strlen(info->devid) + 1];
  10603. sprintf(threadname, "probe_%s", info->devid);
  10604. RenameThread(threadname);
  10605. }
  10606. // If already in use, ignore
  10607. if (bfg_claim_any(NULL, NULL, info->devid))
  10608. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10609. __func__, info->product);
  10610. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10611. struct string_elist *sd_iter, *sd_tmp;
  10612. struct driver_registration *dreg, *dreg_tmp;
  10613. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10614. {
  10615. const char * const dname = sd_iter->string;
  10616. const char * const colon = strpbrk(dname, ":@");
  10617. if (!(colon && colon != dname))
  10618. continue;
  10619. const char * const ser = &colon[1];
  10620. LL_FOREACH2(infolist, info, same_devid_next)
  10621. {
  10622. if (!_probe_device_match(info, ser))
  10623. continue;
  10624. const size_t dnamelen = (colon - dname);
  10625. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10626. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10627. continue;
  10628. if (_probe_device_do_probe(drv, info, &request_rescan))
  10629. return NULL;
  10630. }
  10631. }
  10632. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10633. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10634. {
  10635. const struct device_drv * const drv = dreg->drv;
  10636. if (!drv_algo_check(drv))
  10637. continue;
  10638. // Check for "noauto" flag
  10639. // NOTE: driver-specific configuration overrides general
  10640. bool doauto = true;
  10641. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10642. {
  10643. const char * const dname = sd_iter->string;
  10644. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10645. const char *colon = strchr(dname, ':');
  10646. if (!colon)
  10647. colon = &dname[-1];
  10648. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10649. continue;
  10650. const ssize_t dnamelen = (colon - dname);
  10651. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10652. continue;
  10653. doauto = (tolower(colon[1]) == 'a');
  10654. if (dnamelen != -1)
  10655. break;
  10656. }
  10657. if (doauto && drv->lowl_match)
  10658. {
  10659. LL_FOREACH2(infolist, info, same_devid_next)
  10660. {
  10661. /*
  10662. The below call to applog is absolutely necessary
  10663. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10664. Mac OS X using Homebrew results in a binary that segfaults on startup
  10665. There are two unresolved issues:
  10666. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10667. in debug symbols being available to help troubleshoot the issue
  10668. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10669. call to applog with infolist and / or p
  10670. We would encourage revisiting this in the future to come up with a more concrete solution
  10671. Reproducing should only require commenting / removing the following line and installing
  10672. BFGMiner using "brew install bfgminer --HEAD"
  10673. */
  10674. if (dummy_check_never_true)
  10675. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10676. if (!drv->lowl_match(info))
  10677. continue;
  10678. if (_probe_device_do_probe(drv, info, &request_rescan))
  10679. return NULL;
  10680. }
  10681. }
  10682. }
  10683. // probe driver(s) with 'all' enabled
  10684. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10685. {
  10686. const char * const dname = sd_iter->string;
  10687. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10688. const char * const colon = strchr(dname, ':');
  10689. if (!colon)
  10690. {
  10691. LL_FOREACH2(infolist, info, same_devid_next)
  10692. {
  10693. if (
  10694. #ifdef NEED_BFG_LOWL_VCOM
  10695. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  10696. #endif
  10697. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  10698. {
  10699. bool dont_rescan = false;
  10700. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10701. {
  10702. const struct device_drv * const drv = dreg->drv;
  10703. if (!drv_algo_check(drv))
  10704. continue;
  10705. if (drv->lowl_probe_by_name_only)
  10706. continue;
  10707. if (!drv->lowl_probe)
  10708. continue;
  10709. if (_probe_device_do_probe(drv, info, NULL))
  10710. return NULL;
  10711. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  10712. dont_rescan = true;
  10713. }
  10714. if (opt_hotplug && !dont_rescan)
  10715. request_rescan = true;
  10716. break;
  10717. }
  10718. }
  10719. continue;
  10720. }
  10721. if (strcasecmp(&colon[1], "all"))
  10722. continue;
  10723. const size_t dnamelen = (colon - dname);
  10724. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10725. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10726. continue;
  10727. LL_FOREACH2(infolist, info, same_devid_next)
  10728. {
  10729. if (info->lowl->exclude_from_all)
  10730. continue;
  10731. if (_probe_device_do_probe(drv, info, NULL))
  10732. return NULL;
  10733. }
  10734. }
  10735. // Only actually request a rescan if we never found any cgpu
  10736. if (request_rescan)
  10737. bfg_need_detect_rescan = true;
  10738. return NULL;
  10739. }
  10740. void probe_device(struct lowlevel_device_info * const info)
  10741. {
  10742. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  10743. }
  10744. #endif
  10745. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  10746. {
  10747. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  10748. int devcount, i, mining_threads_new = 0;
  10749. unsigned int k;
  10750. struct cgpu_info *cgpu;
  10751. struct thr_info *thr;
  10752. void *p;
  10753. mutex_lock(&mutex);
  10754. devcount = total_devices;
  10755. addfunc(arg);
  10756. if (!total_devices_new)
  10757. goto out;
  10758. wr_lock(&devices_lock);
  10759. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  10760. if (unlikely(!p))
  10761. {
  10762. wr_unlock(&devices_lock);
  10763. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  10764. goto out;
  10765. }
  10766. devices = p;
  10767. wr_unlock(&devices_lock);
  10768. for (i = 0; i < total_devices_new; ++i)
  10769. {
  10770. cgpu = devices_new[i];
  10771. mining_threads_new += cgpu->threads ?: 1;
  10772. }
  10773. wr_lock(&mining_thr_lock);
  10774. mining_threads_new += mining_threads;
  10775. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  10776. if (unlikely(!p))
  10777. {
  10778. wr_unlock(&mining_thr_lock);
  10779. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  10780. goto out;
  10781. }
  10782. mining_thr = p;
  10783. wr_unlock(&mining_thr_lock);
  10784. for (i = mining_threads; i < mining_threads_new; ++i) {
  10785. mining_thr[i] = calloc(1, sizeof(*thr));
  10786. if (!mining_thr[i])
  10787. {
  10788. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  10789. for ( ; --i >= mining_threads; )
  10790. free(mining_thr[i]);
  10791. goto out;
  10792. }
  10793. }
  10794. k = mining_threads;
  10795. for (i = 0; i < total_devices_new; ++i)
  10796. {
  10797. cgpu = devices_new[i];
  10798. allocate_cgpu(cgpu, &k);
  10799. }
  10800. for (i = 0; i < total_devices_new; ++i)
  10801. {
  10802. cgpu = devices_new[i];
  10803. start_cgpu(cgpu);
  10804. register_device(cgpu);
  10805. ++total_devices;
  10806. }
  10807. #ifdef HAVE_CURSES
  10808. switch_logsize();
  10809. #endif
  10810. out:
  10811. total_devices_new = 0;
  10812. devcount = total_devices - devcount;
  10813. mutex_unlock(&mutex);
  10814. return devcount;
  10815. }
  10816. int scan_serial(const char *s)
  10817. {
  10818. return create_new_cgpus(_scan_serial, (void*)s);
  10819. }
  10820. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  10821. static bool rescan_active;
  10822. static struct timeval tv_rescan;
  10823. static notifier_t rescan_notifier;
  10824. static
  10825. void *rescan_thread(__maybe_unused void *p)
  10826. {
  10827. pthread_detach(pthread_self());
  10828. RenameThread("rescan");
  10829. struct timeval tv_timeout, tv_now;
  10830. fd_set rfds;
  10831. while (true)
  10832. {
  10833. mutex_lock(&rescan_mutex);
  10834. tv_timeout = tv_rescan;
  10835. if (!timer_isset(&tv_timeout))
  10836. {
  10837. rescan_active = false;
  10838. mutex_unlock(&rescan_mutex);
  10839. break;
  10840. }
  10841. mutex_unlock(&rescan_mutex);
  10842. FD_ZERO(&rfds);
  10843. FD_SET(rescan_notifier[0], &rfds);
  10844. const int maxfd = rescan_notifier[0];
  10845. timer_set_now(&tv_now);
  10846. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  10847. notifier_read(rescan_notifier);
  10848. mutex_lock(&rescan_mutex);
  10849. if (timer_passed(&tv_rescan, NULL))
  10850. {
  10851. timer_unset(&tv_rescan);
  10852. mutex_unlock(&rescan_mutex);
  10853. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  10854. scan_serial(NULL);
  10855. }
  10856. else
  10857. mutex_unlock(&rescan_mutex);
  10858. }
  10859. return NULL;
  10860. }
  10861. static
  10862. void _schedule_rescan(const struct timeval * const tvp_when)
  10863. {
  10864. if (rescan_active)
  10865. {
  10866. if (timercmp(tvp_when, &tv_rescan, <))
  10867. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  10868. else
  10869. {
  10870. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  10871. tv_rescan = *tvp_when;
  10872. }
  10873. return;
  10874. }
  10875. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  10876. tv_rescan = *tvp_when;
  10877. rescan_active = true;
  10878. static pthread_t pth;
  10879. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  10880. applog(LOG_ERR, "Failed to start rescan thread");
  10881. }
  10882. static
  10883. void schedule_rescan(const struct timeval * const tvp_when)
  10884. {
  10885. mutex_lock(&rescan_mutex);
  10886. _schedule_rescan(tvp_when);
  10887. mutex_unlock(&rescan_mutex);
  10888. }
  10889. #ifdef HAVE_BFG_HOTPLUG
  10890. static
  10891. void hotplug_trigger()
  10892. {
  10893. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  10894. struct timeval tv_now;
  10895. timer_set_now(&tv_now);
  10896. schedule_rescan(&tv_now);
  10897. }
  10898. #endif
  10899. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  10900. static
  10901. void *hotplug_thread(__maybe_unused void *p)
  10902. {
  10903. pthread_detach(pthread_self());
  10904. RenameThread("hotplug");
  10905. struct udev * const udev = udev_new();
  10906. if (unlikely(!udev))
  10907. applogfailr(NULL, LOG_ERR, "udev_new");
  10908. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  10909. if (unlikely(!mon))
  10910. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  10911. if (unlikely(udev_monitor_enable_receiving(mon)))
  10912. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  10913. const int epfd = epoll_create(1);
  10914. if (unlikely(epfd == -1))
  10915. applogfailr(NULL, LOG_ERR, "epoll_create");
  10916. {
  10917. const int fd = udev_monitor_get_fd(mon);
  10918. struct epoll_event ev = {
  10919. .events = EPOLLIN | EPOLLPRI,
  10920. .data.fd = fd,
  10921. };
  10922. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  10923. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  10924. }
  10925. struct epoll_event ev;
  10926. int rv;
  10927. bool pending = false;
  10928. while (true)
  10929. {
  10930. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  10931. if (rv == -1)
  10932. {
  10933. if (errno == EAGAIN || errno == EINTR)
  10934. continue;
  10935. break;
  10936. }
  10937. if (!rv)
  10938. {
  10939. hotplug_trigger();
  10940. pending = false;
  10941. continue;
  10942. }
  10943. struct udev_device * const device = udev_monitor_receive_device(mon);
  10944. if (!device)
  10945. continue;
  10946. const char * const action = udev_device_get_action(device);
  10947. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  10948. if (!strcmp(action, "add"))
  10949. pending = true;
  10950. udev_device_unref(device);
  10951. }
  10952. applogfailr(NULL, LOG_ERR, "epoll_wait");
  10953. }
  10954. #elif defined(WIN32)
  10955. static UINT_PTR _hotplug_wintimer_id;
  10956. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  10957. {
  10958. KillTimer(NULL, _hotplug_wintimer_id);
  10959. _hotplug_wintimer_id = 0;
  10960. hotplug_trigger();
  10961. }
  10962. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  10963. {
  10964. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  10965. {
  10966. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  10967. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  10968. }
  10969. return DefWindowProc(hwnd, msg, wParam, lParam);
  10970. }
  10971. static
  10972. void *hotplug_thread(__maybe_unused void *p)
  10973. {
  10974. pthread_detach(pthread_self());
  10975. WNDCLASS DummyWinCls = {
  10976. .lpszClassName = "BFGDummyWinCls",
  10977. .lpfnWndProc = hotplug_win_callback,
  10978. };
  10979. ATOM a = RegisterClass(&DummyWinCls);
  10980. if (unlikely(!a))
  10981. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  10982. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  10983. if (unlikely(!hwnd))
  10984. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  10985. MSG msg;
  10986. while (GetMessage(&msg, NULL, 0, 0))
  10987. {
  10988. TranslateMessage(&msg);
  10989. DispatchMessage(&msg);
  10990. }
  10991. quit(0, "WM_QUIT received");
  10992. return NULL;
  10993. }
  10994. #endif
  10995. #ifdef HAVE_BFG_HOTPLUG
  10996. static
  10997. void hotplug_start()
  10998. {
  10999. pthread_t pth;
  11000. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11001. applog(LOG_ERR, "Failed to start hotplug thread");
  11002. }
  11003. #endif
  11004. static void probe_pools(void)
  11005. {
  11006. int i;
  11007. for (i = 0; i < total_pools; i++) {
  11008. struct pool *pool = pools[i];
  11009. pool->testing = true;
  11010. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11011. }
  11012. }
  11013. static void raise_fd_limits(void)
  11014. {
  11015. #ifdef HAVE_SETRLIMIT
  11016. struct rlimit fdlimit;
  11017. rlim_t old_soft_limit;
  11018. char frombuf[0x10] = "unlimited";
  11019. char hardbuf[0x10] = "unlimited";
  11020. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11021. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11022. old_soft_limit = fdlimit.rlim_cur;
  11023. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11024. fdlimit.rlim_cur = FD_SETSIZE;
  11025. else
  11026. fdlimit.rlim_cur = fdlimit.rlim_max;
  11027. if (fdlimit.rlim_max != RLIM_INFINITY)
  11028. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11029. if (old_soft_limit != RLIM_INFINITY)
  11030. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11031. if (fdlimit.rlim_cur == old_soft_limit)
  11032. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11033. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11034. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11035. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11036. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11037. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11038. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11039. #else
  11040. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11041. #endif
  11042. }
  11043. static
  11044. void bfg_atexit(void)
  11045. {
  11046. puts("");
  11047. }
  11048. extern void bfg_init_threadlocal();
  11049. extern void stratumsrv_start();
  11050. extern void test_aan_pll(void);
  11051. int main(int argc, char *argv[])
  11052. {
  11053. struct sigaction handler;
  11054. struct thr_info *thr;
  11055. unsigned int k;
  11056. int i;
  11057. int rearrange_pools = 0;
  11058. char *s;
  11059. #ifdef WIN32
  11060. LoadLibrary("backtrace.dll");
  11061. #endif
  11062. atexit(bfg_atexit);
  11063. b58_sha256_impl = my_blkmaker_sha256_callback;
  11064. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11065. bfg_init_threadlocal();
  11066. #ifndef HAVE_PTHREAD_CANCEL
  11067. setup_pthread_cancel_workaround();
  11068. #endif
  11069. bfg_init_checksums();
  11070. #ifdef WIN32
  11071. {
  11072. WSADATA wsa;
  11073. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11074. if (i)
  11075. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11076. }
  11077. #endif
  11078. /* This dangerous functions tramples random dynamically allocated
  11079. * variables so do it before anything at all */
  11080. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11081. quit(1, "Failed to curl_global_init");
  11082. initial_args = malloc(sizeof(char *) * (argc + 1));
  11083. for (i = 0; i < argc; i++)
  11084. initial_args[i] = strdup(argv[i]);
  11085. initial_args[argc] = NULL;
  11086. mutex_init(&hash_lock);
  11087. mutex_init(&console_lock);
  11088. cglock_init(&control_lock);
  11089. mutex_init(&stats_lock);
  11090. mutex_init(&sharelog_lock);
  11091. cglock_init(&ch_lock);
  11092. mutex_init(&sshare_lock);
  11093. rwlock_init(&blk_lock);
  11094. rwlock_init(&netacc_lock);
  11095. rwlock_init(&mining_thr_lock);
  11096. rwlock_init(&devices_lock);
  11097. mutex_init(&lp_lock);
  11098. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11099. quit(1, "Failed to pthread_cond_init lp_cond");
  11100. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11101. quit(1, "Failed to pthread_cond_init gws_cond");
  11102. notifier_init(submit_waiting_notifier);
  11103. timer_unset(&tv_rescan);
  11104. notifier_init(rescan_notifier);
  11105. /* Create a unique get work queue */
  11106. getq = tq_new();
  11107. if (!getq)
  11108. quit(1, "Failed to create getq");
  11109. /* We use the getq mutex as the staged lock */
  11110. stgd_lock = &getq->mutex;
  11111. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11112. #ifdef WANT_CPUMINE
  11113. init_max_name_len();
  11114. #endif
  11115. handler.sa_handler = &sighandler;
  11116. handler.sa_flags = 0;
  11117. sigemptyset(&handler.sa_mask);
  11118. #ifdef HAVE_PTHREAD_CANCEL
  11119. sigaction(SIGTERM, &handler, &termhandler);
  11120. #else
  11121. // Need to let pthread_cancel emulation handle SIGTERM first
  11122. termhandler = pcwm_orig_term_handler;
  11123. pcwm_orig_term_handler = handler;
  11124. #endif
  11125. sigaction(SIGINT, &handler, &inthandler);
  11126. #ifndef WIN32
  11127. signal(SIGPIPE, SIG_IGN);
  11128. #else
  11129. timeBeginPeriod(1);
  11130. #endif
  11131. opt_kernel_path = CGMINER_PREFIX;
  11132. cgminer_path = alloca(PATH_MAX);
  11133. s = strdup(argv[0]);
  11134. strcpy(cgminer_path, dirname(s));
  11135. free(s);
  11136. strcat(cgminer_path, "/");
  11137. #if defined(WANT_CPUMINE) && defined(WIN32)
  11138. {
  11139. char buf[32];
  11140. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11141. if (gev > 0 && gev < sizeof(buf))
  11142. {
  11143. setup_benchmark_pool();
  11144. double rate = bench_algo_stage3(atoi(buf));
  11145. // Write result to shared memory for parent
  11146. char unique_name[64];
  11147. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11148. {
  11149. HANDLE map_handle = CreateFileMapping(
  11150. INVALID_HANDLE_VALUE, // use paging file
  11151. NULL, // default security attributes
  11152. PAGE_READWRITE, // read/write access
  11153. 0, // size: high 32-bits
  11154. 4096, // size: low 32-bits
  11155. unique_name // name of map object
  11156. );
  11157. if (NULL != map_handle) {
  11158. void *shared_mem = MapViewOfFile(
  11159. map_handle, // object to map view of
  11160. FILE_MAP_WRITE, // read/write access
  11161. 0, // high offset: map from
  11162. 0, // low offset: beginning
  11163. 0 // default: map entire file
  11164. );
  11165. if (NULL != shared_mem)
  11166. CopyMemory(shared_mem, &rate, sizeof(rate));
  11167. (void)UnmapViewOfFile(shared_mem);
  11168. }
  11169. (void)CloseHandle(map_handle);
  11170. }
  11171. exit(0);
  11172. }
  11173. }
  11174. #endif
  11175. #ifdef HAVE_CURSES
  11176. devcursor = 8;
  11177. logstart = devcursor;
  11178. logcursor = logstart;
  11179. #endif
  11180. mutex_init(&submitting_lock);
  11181. #ifdef HAVE_OPENCL
  11182. opencl_early_init();
  11183. #endif
  11184. schedstart.tm.tm_sec = 1;
  11185. schedstop .tm.tm_sec = 1;
  11186. opt_register_table(opt_early_table, NULL);
  11187. opt_register_table(opt_config_table, NULL);
  11188. opt_register_table(opt_cmdline_table, NULL);
  11189. opt_early_parse(argc, argv, applog_and_exit);
  11190. if (!config_loaded)
  11191. {
  11192. load_default_config();
  11193. rearrange_pools = total_pools;
  11194. }
  11195. opt_free_table();
  11196. /* parse command line */
  11197. opt_register_table(opt_config_table,
  11198. "Options for both config file and command line");
  11199. opt_register_table(opt_cmdline_table,
  11200. "Options for command line only");
  11201. opt_parse(&argc, argv, applog_and_exit);
  11202. if (argc != 1)
  11203. quit(1, "Unexpected extra commandline arguments");
  11204. if (rearrange_pools && rearrange_pools < total_pools)
  11205. {
  11206. // Prioritise commandline pools before default-config pools
  11207. for (i = 0; i < rearrange_pools; ++i)
  11208. pools[i]->prio += rearrange_pools;
  11209. for ( ; i < total_pools; ++i)
  11210. pools[i]->prio -= rearrange_pools;
  11211. }
  11212. #ifndef HAVE_PTHREAD_CANCEL
  11213. // Can't do this any earlier, or config isn't loaded
  11214. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11215. #endif
  11216. #ifdef HAVE_PWD_H
  11217. struct passwd *user_info = NULL;
  11218. if (opt_setuid != NULL) {
  11219. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11220. quit(1, "Unable to find setuid user information");
  11221. }
  11222. }
  11223. #endif
  11224. #ifdef HAVE_CHROOT
  11225. if (chroot_dir != NULL) {
  11226. #ifdef HAVE_PWD_H
  11227. if (user_info == NULL && getuid() == 0) {
  11228. applog(LOG_WARNING, "Running as root inside chroot");
  11229. }
  11230. #endif
  11231. if (chroot(chroot_dir) != 0) {
  11232. quit(1, "Unable to chroot");
  11233. }
  11234. if (chdir("/"))
  11235. quit(1, "Unable to chdir to chroot");
  11236. }
  11237. #endif
  11238. #ifdef HAVE_PWD_H
  11239. if (user_info != NULL) {
  11240. if (setgid((*user_info).pw_gid) != 0)
  11241. quit(1, "Unable to setgid");
  11242. if (setuid((*user_info).pw_uid) != 0)
  11243. quit(1, "Unable to setuid");
  11244. }
  11245. #endif
  11246. raise_fd_limits();
  11247. if (opt_benchmark) {
  11248. while (total_pools)
  11249. remove_pool(pools[0]);
  11250. setup_benchmark_pool();
  11251. }
  11252. if (opt_unittest) {
  11253. test_cgpu_match();
  11254. test_intrange();
  11255. test_decimal_width();
  11256. test_domain_funcs();
  11257. #ifdef USE_SCRYPT
  11258. test_scrypt();
  11259. #endif
  11260. test_target();
  11261. test_uri_get_param();
  11262. utf8_test();
  11263. #ifdef USE_JINGTIAN
  11264. test_aan_pll();
  11265. #endif
  11266. if (unittest_failures)
  11267. quit(1, "Unit tests failed");
  11268. }
  11269. #ifdef HAVE_CURSES
  11270. if (opt_realquiet || opt_display_devs)
  11271. use_curses = false;
  11272. setlocale(LC_ALL, "C");
  11273. if (use_curses)
  11274. enable_curses();
  11275. #endif
  11276. #ifdef HAVE_LIBUSB
  11277. int err = libusb_init(NULL);
  11278. if (err)
  11279. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11280. else
  11281. have_libusb = true;
  11282. #endif
  11283. applog(LOG_WARNING, "Started %s", packagename);
  11284. {
  11285. struct bfg_loaded_configfile *configfile;
  11286. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11287. {
  11288. char * const cnfbuf = configfile->filename;
  11289. int fileconf_load = configfile->fileconf_load;
  11290. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11291. switch (fileconf_load) {
  11292. case 0:
  11293. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11294. applog(LOG_WARNING, "Configuration file could not be used.");
  11295. break;
  11296. case -1:
  11297. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11298. if (use_curses)
  11299. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11300. break;
  11301. default:
  11302. break;
  11303. }
  11304. }
  11305. }
  11306. i = strlen(opt_kernel_path) + 2;
  11307. char __kernel_path[i];
  11308. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11309. opt_kernel_path = __kernel_path;
  11310. if (want_per_device_stats)
  11311. opt_log_output = true;
  11312. #ifdef WANT_CPUMINE
  11313. #ifdef USE_SCRYPT
  11314. if (opt_scrypt)
  11315. set_scrypt_algo(&opt_algo);
  11316. #endif
  11317. #endif
  11318. bfg_devapi_init();
  11319. drv_detect_all();
  11320. total_devices = total_devices_new;
  11321. devices = devices_new;
  11322. total_devices_new = 0;
  11323. devices_new = NULL;
  11324. if (opt_display_devs) {
  11325. int devcount = 0;
  11326. applog(LOG_ERR, "Devices detected:");
  11327. for (i = 0; i < total_devices; ++i) {
  11328. struct cgpu_info *cgpu = devices[i];
  11329. char buf[0x100];
  11330. if (cgpu->device != cgpu)
  11331. continue;
  11332. if (cgpu->name)
  11333. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11334. else
  11335. if (cgpu->dev_manufacturer)
  11336. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11337. else
  11338. if (cgpu->dev_product)
  11339. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11340. else
  11341. strcpy(buf, " Device");
  11342. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11343. if (cgpu->dev_serial)
  11344. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11345. if (cgpu->device_path)
  11346. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11347. tailsprintf(buf, sizeof(buf), ")");
  11348. _applog(LOG_NOTICE, buf);
  11349. ++devcount;
  11350. }
  11351. quit(0, "%d devices listed", devcount);
  11352. }
  11353. mining_threads = 0;
  11354. for (i = 0; i < total_devices; ++i)
  11355. register_device(devices[i]);
  11356. if (!total_devices) {
  11357. applog(LOG_WARNING, "No devices detected!");
  11358. if (use_curses)
  11359. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11360. else
  11361. applog(LOG_WARNING, "Waiting for devices");
  11362. }
  11363. #ifdef HAVE_CURSES
  11364. switch_logsize();
  11365. #endif
  11366. #if BLKMAKER_VERSION > 1
  11367. if (opt_load_bitcoin_conf && !(opt_scrypt || opt_benchmark))
  11368. add_local_gbt(total_pools);
  11369. #endif
  11370. if (!total_pools) {
  11371. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11372. #ifdef HAVE_CURSES
  11373. if (!use_curses || !input_pool(false))
  11374. #endif
  11375. quit(1, "Pool setup failed");
  11376. }
  11377. for (i = 0; i < total_pools; i++) {
  11378. struct pool *pool = pools[i];
  11379. size_t siz;
  11380. if (!pool->rpc_url)
  11381. quit(1, "No URI supplied for pool %u", i);
  11382. if (!pool->rpc_userpass) {
  11383. if (!pool->rpc_user || !pool->rpc_pass)
  11384. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11385. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11386. pool->rpc_userpass = malloc(siz);
  11387. if (!pool->rpc_userpass)
  11388. quit(1, "Failed to malloc userpass");
  11389. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11390. }
  11391. }
  11392. /* Set the currentpool to pool with priority 0 */
  11393. validate_pool_priorities();
  11394. for (i = 0; i < total_pools; i++) {
  11395. struct pool *pool = pools[i];
  11396. if (!pool->prio)
  11397. currentpool = pool;
  11398. }
  11399. #ifdef HAVE_SYSLOG_H
  11400. if (use_syslog)
  11401. openlog(PACKAGE, LOG_PID, LOG_USER);
  11402. #endif
  11403. #if defined(unix) || defined(__APPLE__)
  11404. if (opt_stderr_cmd)
  11405. fork_monitor();
  11406. #endif // defined(unix)
  11407. mining_thr = calloc(mining_threads, sizeof(thr));
  11408. if (!mining_thr)
  11409. quit(1, "Failed to calloc mining_thr");
  11410. for (i = 0; i < mining_threads; i++) {
  11411. mining_thr[i] = calloc(1, sizeof(*thr));
  11412. if (!mining_thr[i])
  11413. quit(1, "Failed to calloc mining_thr[%d]", i);
  11414. }
  11415. total_control_threads = 6;
  11416. control_thr = calloc(total_control_threads, sizeof(*thr));
  11417. if (!control_thr)
  11418. quit(1, "Failed to calloc control_thr");
  11419. if (opt_benchmark)
  11420. goto begin_bench;
  11421. applog(LOG_NOTICE, "Probing for an alive pool");
  11422. do {
  11423. bool still_testing;
  11424. int i;
  11425. /* Look for at least one active pool before starting */
  11426. probe_pools();
  11427. do {
  11428. sleep(1);
  11429. if (pools_active)
  11430. break;
  11431. still_testing = false;
  11432. for (int i = 0; i < total_pools; ++i)
  11433. if (pools[i]->testing)
  11434. still_testing = true;
  11435. } while (still_testing);
  11436. if (!pools_active) {
  11437. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11438. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11439. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11440. for (i = 0; i < total_pools; i++) {
  11441. struct pool *pool;
  11442. pool = pools[i];
  11443. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11444. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11445. }
  11446. #ifdef HAVE_CURSES
  11447. if (use_curses) {
  11448. halfdelay(150);
  11449. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11450. if (getch() != ERR)
  11451. quit(0, "No servers could be used! Exiting.");
  11452. cbreak();
  11453. } else
  11454. #endif
  11455. quit(0, "No servers could be used! Exiting.");
  11456. }
  11457. } while (!pools_active);
  11458. #ifdef USE_SCRYPT
  11459. if (detect_algo == 1 && !opt_scrypt) {
  11460. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11461. opt_scrypt = true;
  11462. }
  11463. #endif
  11464. detect_algo = 0;
  11465. begin_bench:
  11466. total_mhashes_done = 0;
  11467. for (i = 0; i < total_devices; i++) {
  11468. struct cgpu_info *cgpu = devices[i];
  11469. cgpu->rolling = cgpu->total_mhashes = 0;
  11470. }
  11471. cgtime(&total_tv_start);
  11472. cgtime(&total_tv_end);
  11473. miner_started = total_tv_start;
  11474. time_t miner_start_ts = time(NULL);
  11475. if (schedstart.tm.tm_sec)
  11476. localtime_r(&miner_start_ts, &schedstart.tm);
  11477. if (schedstop.tm.tm_sec)
  11478. localtime_r(&miner_start_ts, &schedstop .tm);
  11479. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11480. // Initialise processors and threads
  11481. k = 0;
  11482. for (i = 0; i < total_devices; ++i) {
  11483. struct cgpu_info *cgpu = devices[i];
  11484. allocate_cgpu(cgpu, &k);
  11485. }
  11486. // Start threads
  11487. for (i = 0; i < total_devices; ++i) {
  11488. struct cgpu_info *cgpu = devices[i];
  11489. start_cgpu(cgpu);
  11490. }
  11491. #ifdef HAVE_OPENCL
  11492. for (i = 0; i < nDevs; i++)
  11493. pause_dynamic_threads(i);
  11494. #endif
  11495. #ifdef WANT_CPUMINE
  11496. if (opt_n_threads > 0)
  11497. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11498. opt_n_threads, algo_names[opt_algo]);
  11499. #endif
  11500. cgtime(&total_tv_start);
  11501. cgtime(&total_tv_end);
  11502. if (!opt_benchmark)
  11503. {
  11504. pthread_t submit_thread;
  11505. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11506. quit(1, "submit_work thread create failed");
  11507. }
  11508. watchpool_thr_id = 1;
  11509. thr = &control_thr[watchpool_thr_id];
  11510. /* start watchpool thread */
  11511. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11512. quit(1, "watchpool thread create failed");
  11513. pthread_detach(thr->pth);
  11514. watchdog_thr_id = 2;
  11515. thr = &control_thr[watchdog_thr_id];
  11516. /* start watchdog thread */
  11517. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11518. quit(1, "watchdog thread create failed");
  11519. pthread_detach(thr->pth);
  11520. #ifdef HAVE_OPENCL
  11521. /* Create reinit gpu thread */
  11522. gpur_thr_id = 3;
  11523. thr = &control_thr[gpur_thr_id];
  11524. thr->q = tq_new();
  11525. if (!thr->q)
  11526. quit(1, "tq_new failed for gpur_thr_id");
  11527. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11528. quit(1, "reinit_gpu thread create failed");
  11529. #endif
  11530. /* Create API socket thread */
  11531. api_thr_id = 4;
  11532. thr = &control_thr[api_thr_id];
  11533. if (thr_info_create(thr, NULL, api_thread, thr))
  11534. quit(1, "API thread create failed");
  11535. #ifdef USE_LIBMICROHTTPD
  11536. if (httpsrv_port != -1)
  11537. httpsrv_start(httpsrv_port);
  11538. #endif
  11539. #ifdef USE_LIBEVENT
  11540. if (stratumsrv_port != -1)
  11541. stratumsrv_start();
  11542. #endif
  11543. #ifdef HAVE_BFG_HOTPLUG
  11544. if (opt_hotplug)
  11545. hotplug_start();
  11546. #endif
  11547. #ifdef HAVE_CURSES
  11548. /* Create curses input thread for keyboard input. Create this last so
  11549. * that we know all threads are created since this can call kill_work
  11550. * to try and shut down ll previous threads. */
  11551. input_thr_id = 5;
  11552. thr = &control_thr[input_thr_id];
  11553. if (thr_info_create(thr, NULL, input_thread, thr))
  11554. quit(1, "input thread create failed");
  11555. pthread_detach(thr->pth);
  11556. #endif
  11557. /* Just to be sure */
  11558. if (total_control_threads != 6)
  11559. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11560. /* Once everything is set up, main() becomes the getwork scheduler */
  11561. while (42) {
  11562. int ts, max_staged = opt_queue;
  11563. struct pool *pool, *cp;
  11564. bool lagging = false;
  11565. struct curl_ent *ce;
  11566. struct work *work;
  11567. cp = current_pool();
  11568. // Generally, each processor needs a new work, and all at once during work restarts
  11569. max_staged += base_queue;
  11570. mutex_lock(stgd_lock);
  11571. ts = __total_staged();
  11572. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11573. lagging = true;
  11574. /* Wait until hash_pop tells us we need to create more work */
  11575. if (ts > max_staged) {
  11576. staged_full = true;
  11577. pthread_cond_wait(&gws_cond, stgd_lock);
  11578. ts = __total_staged();
  11579. }
  11580. mutex_unlock(stgd_lock);
  11581. if (ts > max_staged)
  11582. continue;
  11583. work = make_work();
  11584. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11585. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11586. cp->getfail_occasions++;
  11587. total_go++;
  11588. }
  11589. pool = select_pool(lagging);
  11590. retry:
  11591. if (pool->has_stratum) {
  11592. while (!pool->stratum_active || !pool->stratum_notify) {
  11593. struct pool *altpool = select_pool(true);
  11594. if (altpool == pool && pool->has_stratum)
  11595. cgsleep_ms(5000);
  11596. pool = altpool;
  11597. goto retry;
  11598. }
  11599. gen_stratum_work(pool, work);
  11600. applog(LOG_DEBUG, "Generated stratum work");
  11601. stage_work(work);
  11602. continue;
  11603. }
  11604. if (pool->last_work_copy) {
  11605. mutex_lock(&pool->last_work_lock);
  11606. struct work *last_work = pool->last_work_copy;
  11607. if (!last_work)
  11608. {}
  11609. else
  11610. if (can_roll(last_work) && should_roll(last_work)) {
  11611. struct timeval tv_now;
  11612. cgtime(&tv_now);
  11613. free_work(work);
  11614. work = make_clone(pool->last_work_copy);
  11615. mutex_unlock(&pool->last_work_lock);
  11616. roll_work(work);
  11617. 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));
  11618. stage_work(work);
  11619. continue;
  11620. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11621. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11622. } else {
  11623. free_work(last_work);
  11624. pool->last_work_copy = NULL;
  11625. }
  11626. mutex_unlock(&pool->last_work_lock);
  11627. }
  11628. if (clone_available()) {
  11629. applog(LOG_DEBUG, "Cloned getwork work");
  11630. free_work(work);
  11631. continue;
  11632. }
  11633. if (opt_benchmark) {
  11634. get_benchmark_work(work, opt_benchmark_intense);
  11635. applog(LOG_DEBUG, "Generated benchmark work");
  11636. stage_work(work);
  11637. continue;
  11638. }
  11639. work->pool = pool;
  11640. ce = pop_curl_entry3(pool, 2);
  11641. /* obtain new work from bitcoin via JSON-RPC */
  11642. if (!get_upstream_work(work, ce->curl)) {
  11643. struct pool *next_pool;
  11644. /* Make sure the pool just hasn't stopped serving
  11645. * requests but is up as we'll keep hammering it */
  11646. push_curl_entry(ce, pool);
  11647. ++pool->seq_getfails;
  11648. pool_died(pool);
  11649. next_pool = select_pool(!opt_fail_only);
  11650. if (pool == next_pool) {
  11651. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11652. cgsleep_ms(5000);
  11653. } else {
  11654. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11655. pool = next_pool;
  11656. }
  11657. goto retry;
  11658. }
  11659. if (ts >= max_staged)
  11660. pool_tclear(pool, &pool->lagging);
  11661. if (pool_tclear(pool, &pool->idle))
  11662. pool_resus(pool);
  11663. applog(LOG_DEBUG, "Generated getwork work");
  11664. stage_work(work);
  11665. push_curl_entry(ce, pool);
  11666. }
  11667. return 0;
  11668. }