miner.c 357 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2012-2014 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 "util.h"
  76. #ifdef USE_AVALON
  77. #include "driver-avalon.h"
  78. #endif
  79. #ifdef HAVE_BFG_LOWLEVEL
  80. #include "lowlevel.h"
  81. #endif
  82. #if defined(unix) || defined(__APPLE__)
  83. #include <errno.h>
  84. #include <fcntl.h>
  85. #include <sys/wait.h>
  86. #endif
  87. #ifdef USE_SCRYPT
  88. #include "malgo/scrypt.h"
  89. #endif
  90. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  91. # define USE_FPGA
  92. #endif
  93. enum bfg_quit_summary {
  94. BQS_DEFAULT,
  95. BQS_NONE,
  96. BQS_DEVS,
  97. BQS_PROCS,
  98. BQS_DETAILED,
  99. };
  100. struct strategies strategies[] = {
  101. { "Failover" },
  102. { "Round Robin" },
  103. { "Rotate" },
  104. { "Load Balance" },
  105. { "Balance" },
  106. };
  107. #define packagename bfgminer_name_space_ver
  108. bool opt_protocol;
  109. bool opt_dev_protocol;
  110. static bool opt_benchmark, opt_benchmark_intense;
  111. static bool want_longpoll = true;
  112. static bool want_gbt = true;
  113. static bool want_getwork = true;
  114. #if BLKMAKER_VERSION > 1
  115. static bool opt_load_bitcoin_conf = true;
  116. static uint32_t coinbase_script_block_id;
  117. static uint32_t template_nonce;
  118. #endif
  119. #if BLKMAKER_VERSION > 0
  120. char *opt_coinbase_sig;
  121. #endif
  122. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  123. static bool include_serial_in_statline;
  124. char *request_target_str;
  125. float request_pdiff = 1.0;
  126. double request_bdiff;
  127. static bool want_stratum = true;
  128. int opt_skip_checks;
  129. bool want_per_device_stats;
  130. bool use_syslog;
  131. bool opt_quiet_work_updates = true;
  132. bool opt_quiet;
  133. bool opt_realquiet;
  134. int loginput_size;
  135. bool opt_compact;
  136. bool opt_show_procs;
  137. const int opt_cutofftemp = 95;
  138. int opt_hysteresis = 3;
  139. static int opt_retries = -1;
  140. int opt_fail_pause = 5;
  141. int opt_log_interval = 20;
  142. int opt_queue = 1;
  143. int opt_scantime = 60;
  144. int opt_expiry = 120;
  145. int opt_expiry_lp = 3600;
  146. unsigned long long global_hashrate;
  147. static bool opt_unittest = false;
  148. unsigned unittest_failures;
  149. unsigned long global_quota_gcd = 1;
  150. time_t last_getwork;
  151. #ifdef USE_OPENCL
  152. int opt_dynamic_interval = 7;
  153. int nDevs;
  154. int opt_g_threads = -1;
  155. #endif
  156. #ifdef USE_SCRYPT
  157. static char detect_algo = 1;
  158. #else
  159. static char detect_algo;
  160. #endif
  161. bool opt_restart = true;
  162. #ifdef USE_LIBMICROHTTPD
  163. #include "httpsrv.h"
  164. int httpsrv_port = -1;
  165. #endif
  166. #ifdef USE_LIBEVENT
  167. int stratumsrv_port = -1;
  168. #endif
  169. const
  170. int rescan_delay_ms = 1000;
  171. #ifdef HAVE_BFG_HOTPLUG
  172. bool opt_hotplug = 1;
  173. const
  174. int hotplug_delay_ms = 100;
  175. #else
  176. const bool opt_hotplug;
  177. #endif
  178. struct string_elist *scan_devices;
  179. static struct string_elist *opt_set_device_list;
  180. bool opt_force_dev_init;
  181. static struct string_elist *opt_devices_enabled_list;
  182. static bool opt_display_devs;
  183. int total_devices;
  184. struct cgpu_info **devices;
  185. int total_devices_new;
  186. struct cgpu_info **devices_new;
  187. bool have_opencl;
  188. int opt_n_threads = -1;
  189. int mining_threads;
  190. int base_queue;
  191. int num_processors;
  192. #ifdef HAVE_CURSES
  193. bool use_curses = true;
  194. #else
  195. bool use_curses;
  196. #endif
  197. int last_logstatusline_len;
  198. #ifdef HAVE_LIBUSB
  199. bool have_libusb;
  200. #endif
  201. static bool opt_submit_stale = true;
  202. static float opt_shares;
  203. static int opt_submit_threads = 0x40;
  204. bool opt_fail_only;
  205. int opt_fail_switch_delay = 300;
  206. bool opt_autofan;
  207. bool opt_autoengine;
  208. bool opt_noadl;
  209. char *opt_api_allow = NULL;
  210. char *opt_api_groups;
  211. char *opt_api_description = PACKAGE_STRING;
  212. int opt_api_port = 4028;
  213. bool opt_api_listen;
  214. bool opt_api_mcast;
  215. char *opt_api_mcast_addr = API_MCAST_ADDR;
  216. char *opt_api_mcast_code = API_MCAST_CODE;
  217. char *opt_api_mcast_des = "";
  218. int opt_api_mcast_port = 4028;
  219. bool opt_api_network;
  220. bool opt_delaynet;
  221. bool opt_disable_pool;
  222. bool opt_disable_client_reconnect = false;
  223. static bool no_work;
  224. bool opt_worktime;
  225. bool opt_weighed_stats;
  226. char *opt_kernel_path;
  227. char *cgminer_path;
  228. #if defined(USE_BITFORCE)
  229. bool opt_bfl_noncerange;
  230. #endif
  231. #define QUIET (opt_quiet || opt_realquiet)
  232. struct thr_info *control_thr;
  233. struct thr_info **mining_thr;
  234. static int watchpool_thr_id;
  235. static int watchdog_thr_id;
  236. #ifdef HAVE_CURSES
  237. static int input_thr_id;
  238. #endif
  239. int gpur_thr_id;
  240. static int api_thr_id;
  241. static int total_control_threads;
  242. pthread_mutex_t hash_lock;
  243. static pthread_mutex_t *stgd_lock;
  244. pthread_mutex_t console_lock;
  245. cglock_t ch_lock;
  246. static pthread_rwlock_t blk_lock;
  247. static pthread_mutex_t sshare_lock;
  248. pthread_rwlock_t netacc_lock;
  249. pthread_rwlock_t mining_thr_lock;
  250. pthread_rwlock_t devices_lock;
  251. static pthread_mutex_t lp_lock;
  252. static pthread_cond_t lp_cond;
  253. pthread_cond_t gws_cond;
  254. bool shutting_down;
  255. double total_rolling;
  256. double total_mhashes_done;
  257. static struct timeval total_tv_start, total_tv_end;
  258. static struct timeval miner_started;
  259. cglock_t control_lock;
  260. pthread_mutex_t stats_lock;
  261. static pthread_mutex_t submitting_lock;
  262. static int total_submitting;
  263. static struct work *submit_waiting;
  264. notifier_t submit_waiting_notifier;
  265. int hw_errors;
  266. int total_accepted, total_rejected;
  267. int total_getworks, total_stale, total_discarded;
  268. uint64_t total_bytes_rcvd, total_bytes_sent;
  269. double total_diff1, total_bad_diff1;
  270. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  271. static int staged_rollable, staged_spare;
  272. unsigned int new_blocks;
  273. unsigned int found_blocks;
  274. unsigned int local_work;
  275. unsigned int total_go, total_ro;
  276. struct pool **pools;
  277. static struct pool *currentpool = NULL;
  278. int total_pools, enabled_pools;
  279. enum pool_strategy pool_strategy = POOL_FAILOVER;
  280. int opt_rotate_period;
  281. static int total_urls, total_users, total_passes;
  282. static
  283. #ifndef HAVE_CURSES
  284. const
  285. #endif
  286. bool curses_active;
  287. #ifdef HAVE_CURSES
  288. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  289. const
  290. #endif
  291. short default_bgcolor = COLOR_BLACK;
  292. static int attr_title = A_BOLD;
  293. #endif
  294. static
  295. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  296. bool use_unicode;
  297. static
  298. bool have_unicode_degrees;
  299. static
  300. wchar_t unicode_micro = 'u';
  301. #else
  302. const bool use_unicode;
  303. static
  304. const bool have_unicode_degrees;
  305. #ifdef HAVE_CURSES
  306. static
  307. const char unicode_micro = 'u';
  308. #endif
  309. #endif
  310. #ifdef HAVE_CURSES
  311. #define U8_BAD_START "\xef\x80\x81"
  312. #define U8_BAD_END "\xef\x80\x80"
  313. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  314. /* logstart is where the log window should start */
  315. static int devcursor, logstart, logcursor;
  316. bool selecting_device;
  317. unsigned selected_device;
  318. #endif
  319. static int max_lpdigits;
  320. // current_hash was replaced with goal->current_goal_detail
  321. // current_block_id was replaced with blkchain->currentblk->block_id
  322. static char datestamp[40];
  323. static char best_share[ALLOC_H2B_SHORTV] = "0";
  324. double best_diff = 0;
  325. struct mining_algorithm *mining_algorithms;
  326. struct mining_goal_info *mining_goals;
  327. int active_goals = 1;
  328. int swork_id;
  329. /* For creating a hash database of stratum shares submitted that have not had
  330. * a response yet */
  331. struct stratum_share {
  332. UT_hash_handle hh;
  333. bool block;
  334. struct work *work;
  335. int id;
  336. };
  337. static struct stratum_share *stratum_shares = NULL;
  338. char *opt_socks_proxy = NULL;
  339. static const char def_conf[] = "bfgminer.conf";
  340. static bool config_loaded;
  341. static int include_count;
  342. #define JSON_INCLUDE_CONF "include"
  343. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  344. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  345. #define JSON_MAX_DEPTH 10
  346. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  347. #define JSON_WEB_ERROR "WEB config err"
  348. char *cmd_idle, *cmd_sick, *cmd_dead;
  349. #if defined(unix) || defined(__APPLE__)
  350. static char *opt_stderr_cmd = NULL;
  351. static int forkpid;
  352. #endif // defined(unix)
  353. #ifdef HAVE_CHROOT
  354. char *chroot_dir;
  355. #endif
  356. #ifdef HAVE_PWD_H
  357. char *opt_setuid;
  358. #endif
  359. struct sigaction termhandler, inthandler;
  360. struct thread_q *getq;
  361. static int total_work;
  362. static bool staged_full;
  363. struct work *staged_work = NULL;
  364. struct schedtime {
  365. bool enable;
  366. struct tm tm;
  367. };
  368. struct schedtime schedstart;
  369. struct schedtime schedstop;
  370. bool sched_paused;
  371. static bool time_before(struct tm *tm1, struct tm *tm2)
  372. {
  373. if (tm1->tm_hour < tm2->tm_hour)
  374. return true;
  375. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  376. return true;
  377. return false;
  378. }
  379. static bool should_run(void)
  380. {
  381. struct tm tm;
  382. time_t tt;
  383. bool within_range;
  384. if (!schedstart.enable && !schedstop.enable)
  385. return true;
  386. tt = time(NULL);
  387. localtime_r(&tt, &tm);
  388. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  389. if (time_before(&schedstop.tm, &schedstart.tm))
  390. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  391. else
  392. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  393. if (within_range && !schedstop.enable)
  394. /* This is a once off event with no stop time set */
  395. schedstart.enable = false;
  396. return within_range;
  397. }
  398. void get_datestamp(char *f, size_t fsiz, time_t tt)
  399. {
  400. struct tm _tm;
  401. struct tm *tm = &_tm;
  402. if (tt == INVALID_TIMESTAMP)
  403. tt = time(NULL);
  404. localtime_r(&tt, tm);
  405. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  406. tm->tm_year + 1900,
  407. tm->tm_mon + 1,
  408. tm->tm_mday,
  409. tm->tm_hour,
  410. tm->tm_min,
  411. tm->tm_sec);
  412. }
  413. static
  414. void get_timestamp(char *f, size_t fsiz, time_t tt)
  415. {
  416. struct tm _tm;
  417. struct tm *tm = &_tm;
  418. localtime_r(&tt, tm);
  419. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  420. tm->tm_hour,
  421. tm->tm_min,
  422. tm->tm_sec);
  423. }
  424. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  425. static char exit_buf[512];
  426. static void applog_and_exit(const char *fmt, ...)
  427. {
  428. va_list ap;
  429. va_start(ap, fmt);
  430. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  431. va_end(ap);
  432. _applog(LOG_ERR, exit_buf);
  433. exit(1);
  434. }
  435. static
  436. float drv_min_nonce_diff(const struct device_drv * const drv, struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  437. {
  438. if (drv->drv_min_nonce_diff)
  439. return drv->drv_min_nonce_diff(proc, malgo);
  440. #ifdef USE_SHA256D
  441. return (malgo->algo == POW_SHA256D) ? 1. : -1.;
  442. #else
  443. return -1.;
  444. #endif
  445. }
  446. char *devpath_to_devid(const char *devpath)
  447. {
  448. #ifndef WIN32
  449. if (devpath[0] != '/')
  450. return NULL;
  451. struct stat my_stat;
  452. if (stat(devpath, &my_stat))
  453. return NULL;
  454. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  455. memcpy(devs, "dev_t:", 6);
  456. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  457. #else
  458. if (!strncmp(devpath, "\\\\.\\", 4))
  459. devpath += 4;
  460. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  461. return NULL;
  462. devpath += 3;
  463. char *p;
  464. strtol(devpath, &p, 10);
  465. if (p[0])
  466. return NULL;
  467. const int sz = (p - devpath);
  468. char *devs = malloc(4 + sz + 1);
  469. sprintf(devs, "com:%s", devpath);
  470. #endif
  471. return devs;
  472. }
  473. static
  474. bool devpaths_match(const char * const ap, const char * const bp)
  475. {
  476. char * const a = devpath_to_devid(ap);
  477. if (!a)
  478. return false;
  479. char * const b = devpath_to_devid(bp);
  480. bool rv = false;
  481. if (b)
  482. {
  483. rv = !strcmp(a, b);
  484. free(b);
  485. }
  486. free(a);
  487. return rv;
  488. }
  489. static
  490. int proc_letter_to_number(const char *s, const char ** const rem)
  491. {
  492. int n = 0, c;
  493. for ( ; s[0]; ++s)
  494. {
  495. if (unlikely(n > INT_MAX / 26))
  496. break;
  497. c = tolower(s[0]) - 'a';
  498. if (unlikely(c < 0 || c > 25))
  499. break;
  500. if (unlikely(INT_MAX - c < n))
  501. break;
  502. n = (n * 26) + c;
  503. }
  504. *rem = s;
  505. return n;
  506. }
  507. static
  508. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  509. {
  510. // all - matches anything
  511. // d0 - matches all processors of device 0
  512. // d0-3 - matches all processors of device 0, 1, 2, or 3
  513. // d0a - matches first processor of device 0
  514. // 0 - matches processor 0
  515. // 0-4 - matches processors 0, 1, 2, 3, or 4
  516. // ___ - matches all processors on all devices using driver/name ___
  517. // ___0 - matches all processors of 0th device using driver/name ___
  518. // ___0a - matches first processor of 0th device using driver/name ___
  519. // @* - matches device with serial or path *
  520. // @*@a - matches first processor of device with serial or path *
  521. // ___@* - matches device with serial or path * using driver/name ___
  522. if (!strcasecmp(pattern, "all"))
  523. return true;
  524. const struct device_drv * const drv = cgpu->drv;
  525. const char *p = pattern, *p2;
  526. size_t L;
  527. int n, i, c = -1;
  528. int n2;
  529. int proc_first = -1, proc_last = -1;
  530. struct cgpu_info *device;
  531. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  532. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  533. // dname or name
  534. p = &pattern[L];
  535. else
  536. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  537. // d#
  538. ++p;
  539. else
  540. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  541. // # or @
  542. {}
  543. else
  544. return false;
  545. L = p - pattern;
  546. while (isspace(p[0]))
  547. ++p;
  548. if (p[0] == '@')
  549. {
  550. // Serial/path
  551. const char * const ser = &p[1];
  552. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  553. {}
  554. p2 = (p[0] == '@') ? &p[1] : p;
  555. const size_t serlen = (p - ser);
  556. p = "";
  557. n = n2 = 0;
  558. const char * const devpath = cgpu->device_path ?: "";
  559. const char * const devser = cgpu->dev_serial ?: "";
  560. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  561. {} // Match
  562. else
  563. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  564. {} // Match
  565. else
  566. {
  567. char devpath2[serlen + 1];
  568. memcpy(devpath2, ser, serlen);
  569. devpath2[serlen] = '\0';
  570. if (!devpaths_match(devpath, ser))
  571. return false;
  572. }
  573. }
  574. else
  575. {
  576. if (isdigit(p[0]))
  577. n = strtol(p, (void*)&p2, 0);
  578. else
  579. {
  580. n = 0;
  581. p2 = p;
  582. }
  583. if (p2[0] == '-')
  584. {
  585. ++p2;
  586. if (p2[0] && isdigit(p2[0]))
  587. n2 = strtol(p2, (void*)&p2, 0);
  588. else
  589. n2 = INT_MAX;
  590. }
  591. else
  592. n2 = n;
  593. if (p == pattern)
  594. {
  595. if (!p[0])
  596. return true;
  597. if (p2 && p2[0])
  598. goto invsyntax;
  599. for (i = n; i <= n2; ++i)
  600. {
  601. if (i >= total_devices)
  602. break;
  603. if (cgpu == devices[i])
  604. return true;
  605. }
  606. return false;
  607. }
  608. }
  609. if (p2[0])
  610. {
  611. proc_first = proc_letter_to_number(&p2[0], &p2);
  612. if (p2[0] == '-')
  613. {
  614. ++p2;
  615. if (p2[0])
  616. proc_last = proc_letter_to_number(p2, &p2);
  617. else
  618. proc_last = INT_MAX;
  619. }
  620. else
  621. proc_last = proc_first;
  622. if (p2[0])
  623. goto invsyntax;
  624. }
  625. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  626. {
  627. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  628. (!L) ||
  629. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  630. {} // Matched name or dname
  631. else
  632. return false;
  633. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  634. return false;
  635. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  636. return false;
  637. return true;
  638. }
  639. // d#
  640. c = -1;
  641. for (i = 0; ; ++i)
  642. {
  643. if (i == total_devices)
  644. return false;
  645. if (devices[i]->device != devices[i])
  646. continue;
  647. ++c;
  648. if (c < n)
  649. continue;
  650. if (c > n2)
  651. break;
  652. for (device = devices[i]; device; device = device->next_proc)
  653. {
  654. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  655. continue;
  656. if (device == cgpu)
  657. return true;
  658. }
  659. }
  660. return false;
  661. invsyntax:
  662. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  663. return false;
  664. }
  665. #define TEST_CGPU_MATCH(pattern) \
  666. if (!cgpu_match(pattern, &cgpu)) \
  667. { \
  668. ++unittest_failures; \
  669. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  670. } \
  671. // END TEST_CGPU_MATCH
  672. #define TEST_CGPU_NOMATCH(pattern) \
  673. if (cgpu_match(pattern, &cgpu)) \
  674. { \
  675. ++unittest_failures; \
  676. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  677. } \
  678. // END TEST_CGPU_MATCH
  679. static __maybe_unused
  680. void test_cgpu_match()
  681. {
  682. struct device_drv drv = {
  683. .dname = "test",
  684. .name = "TST",
  685. };
  686. struct cgpu_info cgpu = {
  687. .drv = &drv,
  688. .device = &cgpu,
  689. .device_id = 1,
  690. .proc_id = 1,
  691. .proc_repr = "TST 1b",
  692. }, cgpu0a = {
  693. .drv = &drv,
  694. .device = &cgpu0a,
  695. .device_id = 0,
  696. .proc_id = 0,
  697. .proc_repr = "TST 0a",
  698. }, cgpu1a = {
  699. .drv = &drv,
  700. .device = &cgpu0a,
  701. .device_id = 1,
  702. .proc_id = 0,
  703. .proc_repr = "TST 1a",
  704. };
  705. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  706. devices = devices_list;
  707. total_devices = 3;
  708. TEST_CGPU_MATCH("all")
  709. TEST_CGPU_MATCH("d1")
  710. TEST_CGPU_NOMATCH("d2")
  711. TEST_CGPU_MATCH("d0-5")
  712. TEST_CGPU_NOMATCH("d0-0")
  713. TEST_CGPU_NOMATCH("d2-5")
  714. TEST_CGPU_MATCH("d-1")
  715. TEST_CGPU_MATCH("d1-")
  716. TEST_CGPU_NOMATCH("d-0")
  717. TEST_CGPU_NOMATCH("d2-")
  718. TEST_CGPU_MATCH("2")
  719. TEST_CGPU_NOMATCH("3")
  720. TEST_CGPU_MATCH("1-2")
  721. TEST_CGPU_MATCH("2-3")
  722. TEST_CGPU_NOMATCH("1-1")
  723. TEST_CGPU_NOMATCH("3-4")
  724. TEST_CGPU_MATCH("TST")
  725. TEST_CGPU_MATCH("test")
  726. TEST_CGPU_MATCH("tst")
  727. TEST_CGPU_MATCH("TEST")
  728. TEST_CGPU_NOMATCH("TSF")
  729. TEST_CGPU_NOMATCH("TS")
  730. TEST_CGPU_NOMATCH("TSTF")
  731. TEST_CGPU_MATCH("TST1")
  732. TEST_CGPU_MATCH("test1")
  733. TEST_CGPU_MATCH("TST0-1")
  734. TEST_CGPU_MATCH("TST 1")
  735. TEST_CGPU_MATCH("TST 1-2")
  736. TEST_CGPU_MATCH("TEST 1-2")
  737. TEST_CGPU_NOMATCH("TST2")
  738. TEST_CGPU_NOMATCH("TST2-3")
  739. TEST_CGPU_NOMATCH("TST0-0")
  740. TEST_CGPU_MATCH("TST1b")
  741. TEST_CGPU_MATCH("tst1b")
  742. TEST_CGPU_NOMATCH("TST1c")
  743. TEST_CGPU_NOMATCH("TST1bb")
  744. TEST_CGPU_MATCH("TST0-1b")
  745. TEST_CGPU_NOMATCH("TST0-1c")
  746. TEST_CGPU_MATCH("TST1a-d")
  747. TEST_CGPU_NOMATCH("TST1a-a")
  748. TEST_CGPU_NOMATCH("TST1-a")
  749. TEST_CGPU_NOMATCH("TST1c-z")
  750. TEST_CGPU_NOMATCH("TST1c-")
  751. TEST_CGPU_MATCH("@")
  752. TEST_CGPU_NOMATCH("@abc")
  753. TEST_CGPU_MATCH("@@b")
  754. TEST_CGPU_NOMATCH("@@c")
  755. TEST_CGPU_MATCH("TST@")
  756. TEST_CGPU_NOMATCH("TST@abc")
  757. TEST_CGPU_MATCH("TST@@b")
  758. TEST_CGPU_NOMATCH("TST@@c")
  759. TEST_CGPU_MATCH("TST@@b-f")
  760. TEST_CGPU_NOMATCH("TST@@c-f")
  761. TEST_CGPU_NOMATCH("TST@@-a")
  762. cgpu.device_path = "/dev/test";
  763. cgpu.dev_serial = "testy";
  764. TEST_CGPU_MATCH("TST@/dev/test")
  765. TEST_CGPU_MATCH("TST@testy")
  766. TEST_CGPU_NOMATCH("TST@")
  767. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  768. TEST_CGPU_NOMATCH("TST@testy3@b")
  769. TEST_CGPU_MATCH("TST@/dev/test@b")
  770. TEST_CGPU_MATCH("TST@testy@b")
  771. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  772. TEST_CGPU_NOMATCH("TST@testy@c")
  773. cgpu.device_path = "usb:000:999";
  774. TEST_CGPU_MATCH("TST@usb:000:999")
  775. drv.dname = "test7";
  776. TEST_CGPU_MATCH("test7")
  777. TEST_CGPU_MATCH("TEST7")
  778. TEST_CGPU_NOMATCH("test&")
  779. TEST_CGPU_MATCH("test7 1-2")
  780. TEST_CGPU_MATCH("test7@testy@b")
  781. }
  782. static
  783. int cgpu_search(const char * const pattern, const int first)
  784. {
  785. int i;
  786. struct cgpu_info *cgpu;
  787. #define CHECK_CGPU_SEARCH do{ \
  788. cgpu = get_devices(i); \
  789. if (cgpu_match(pattern, cgpu)) \
  790. return i; \
  791. }while(0)
  792. for (i = first; i < total_devices; ++i)
  793. CHECK_CGPU_SEARCH;
  794. for (i = 0; i < first; ++i)
  795. CHECK_CGPU_SEARCH;
  796. #undef CHECK_CGPU_SEARCH
  797. return -1;
  798. }
  799. static pthread_mutex_t sharelog_lock;
  800. static FILE *sharelog_file = NULL;
  801. struct thr_info *get_thread(int thr_id)
  802. {
  803. struct thr_info *thr;
  804. rd_lock(&mining_thr_lock);
  805. thr = mining_thr[thr_id];
  806. rd_unlock(&mining_thr_lock);
  807. return thr;
  808. }
  809. static struct cgpu_info *get_thr_cgpu(int thr_id)
  810. {
  811. struct thr_info *thr = get_thread(thr_id);
  812. return thr->cgpu;
  813. }
  814. struct cgpu_info *get_devices(int id)
  815. {
  816. struct cgpu_info *cgpu;
  817. rd_lock(&devices_lock);
  818. cgpu = devices[id];
  819. rd_unlock(&devices_lock);
  820. return cgpu;
  821. }
  822. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  823. static FILE *noncelog_file = NULL;
  824. static
  825. void noncelog(const struct work * const work)
  826. {
  827. const int thr_id = work->thr_id;
  828. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  829. char buf[0x200], hash[65], data[161], midstate[65];
  830. int rv;
  831. size_t ret;
  832. bin2hex(hash, work->hash, 32);
  833. bin2hex(data, work->data, 80);
  834. bin2hex(midstate, work->midstate, 32);
  835. // timestamp,proc,hash,data,midstate
  836. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  837. (unsigned long)time(NULL), proc->proc_repr_ns,
  838. hash, data, midstate);
  839. if (unlikely(rv < 1))
  840. {
  841. applog(LOG_ERR, "noncelog printf error");
  842. return;
  843. }
  844. mutex_lock(&noncelog_lock);
  845. ret = fwrite(buf, rv, 1, noncelog_file);
  846. fflush(noncelog_file);
  847. mutex_unlock(&noncelog_lock);
  848. if (ret != 1)
  849. applog(LOG_ERR, "noncelog fwrite error");
  850. }
  851. static void sharelog(const char*disposition, const struct work*work)
  852. {
  853. char target[(sizeof(work->target) * 2) + 1];
  854. char hash[(sizeof(work->hash) * 2) + 1];
  855. char data[(sizeof(work->data) * 2) + 1];
  856. struct cgpu_info *cgpu;
  857. unsigned long int t;
  858. struct pool *pool;
  859. int thr_id, rv;
  860. char s[1024];
  861. size_t ret;
  862. if (!sharelog_file)
  863. return;
  864. thr_id = work->thr_id;
  865. cgpu = get_thr_cgpu(thr_id);
  866. pool = work->pool;
  867. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  868. bin2hex(target, work->target, sizeof(work->target));
  869. bin2hex(hash, work->hash, sizeof(work->hash));
  870. bin2hex(data, work->data, sizeof(work->data));
  871. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  872. 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);
  873. if (rv >= (int)(sizeof(s)))
  874. s[sizeof(s) - 1] = '\0';
  875. else if (rv < 0) {
  876. applog(LOG_ERR, "sharelog printf error");
  877. return;
  878. }
  879. mutex_lock(&sharelog_lock);
  880. ret = fwrite(s, rv, 1, sharelog_file);
  881. fflush(sharelog_file);
  882. mutex_unlock(&sharelog_lock);
  883. if (ret != 1)
  884. applog(LOG_ERR, "sharelog fwrite error");
  885. }
  886. #ifdef HAVE_CURSES
  887. static void switch_logsize(void);
  888. #endif
  889. static void hotplug_trigger();
  890. void goal_set_malgo(struct mining_goal_info * const goal, struct mining_algorithm * const malgo)
  891. {
  892. if (goal->malgo == malgo)
  893. return;
  894. if (goal->malgo)
  895. --goal->malgo->goal_refs;
  896. if (malgo->goal_refs++)
  897. // First time using a new mining algorithm may means we need to add mining hardware to support it
  898. // api_thr_id is used as an ugly hack to determine if mining has started - if not, we do NOT want to try to hotplug anything (let the initial detect handle it)
  899. if (opt_hotplug && api_thr_id)
  900. hotplug_trigger();
  901. goal->malgo = malgo;
  902. }
  903. struct mining_algorithm *mining_algorithm_by_alias(const char * const alias)
  904. {
  905. struct mining_algorithm *malgo;
  906. LL_FOREACH(mining_algorithms, malgo)
  907. {
  908. if (match_strtok(malgo->aliases, "|", alias))
  909. return malgo;
  910. }
  911. return NULL;
  912. }
  913. #ifdef USE_SCRYPT
  914. extern struct mining_algorithm malgo_scrypt;
  915. static
  916. const char *set_malgo_scrypt()
  917. {
  918. goal_set_malgo(get_mining_goal("default"), &malgo_scrypt);
  919. return NULL;
  920. }
  921. #endif
  922. static
  923. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  924. {
  925. // default always goes first
  926. if (a->is_default)
  927. return -1;
  928. if (b->is_default)
  929. return 1;
  930. return strcmp(a->name, b->name);
  931. }
  932. static
  933. void blkchain_init_block(struct blockchain_info * const blkchain)
  934. {
  935. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  936. memset(dummy_block->prevblkhash, 0, 0x20);
  937. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  938. blkchain->currentblk = dummy_block;
  939. }
  940. extern struct mining_algorithm malgo_sha256d;
  941. struct mining_goal_info *get_mining_goal(const char * const name)
  942. {
  943. static unsigned next_goal_id;
  944. struct mining_goal_info *goal;
  945. HASH_FIND_STR(mining_goals, name, goal);
  946. if (!goal)
  947. {
  948. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  949. goal = (void*)(&blkchain[1]);
  950. *blkchain = (struct blockchain_info){
  951. .currentblk = NULL,
  952. };
  953. blkchain_init_block(blkchain);
  954. *goal = (struct mining_goal_info){
  955. .id = next_goal_id++,
  956. .name = strdup(name),
  957. .is_default = !strcmp(name, "default"),
  958. .blkchain = blkchain,
  959. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  960. };
  961. #ifdef USE_SHA256D
  962. goal_set_malgo(goal, &malgo_sha256d);
  963. #else
  964. // NOTE: Basically random default
  965. goal_set_malgo(goal, mining_algorithms);
  966. #endif
  967. HASH_ADD_KEYPTR(hh, mining_goals, goal->name, strlen(goal->name), goal);
  968. HASH_SORT(mining_goals, mining_goals_name_cmp);
  969. #ifdef HAVE_CURSES
  970. devcursor = 7 + active_goals;
  971. switch_logsize();
  972. #endif
  973. }
  974. return goal;
  975. }
  976. void mining_goal_reset(struct mining_goal_info * const goal)
  977. {
  978. struct blockchain_info * const blkchain = goal->blkchain;
  979. struct block_info *blkinfo, *tmpblkinfo;
  980. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  981. {
  982. HASH_DEL(blkchain->blocks, blkinfo);
  983. free(blkinfo);
  984. }
  985. blkchain_init_block(blkchain);
  986. }
  987. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  988. /* Adjust all the pools' quota to the greatest common denominator after a pool
  989. * has been added or the quotas changed. */
  990. void adjust_quota_gcd(void)
  991. {
  992. unsigned long gcd, lowest_quota = ~0UL, quota;
  993. struct pool *pool;
  994. int i;
  995. for (i = 0; i < total_pools; i++) {
  996. pool = pools[i];
  997. quota = pool->quota;
  998. if (!quota)
  999. continue;
  1000. if (quota < lowest_quota)
  1001. lowest_quota = quota;
  1002. }
  1003. if (likely(lowest_quota < ~0UL)) {
  1004. gcd = lowest_quota;
  1005. for (i = 0; i < total_pools; i++) {
  1006. pool = pools[i];
  1007. quota = pool->quota;
  1008. if (!quota)
  1009. continue;
  1010. while (quota % gcd)
  1011. gcd--;
  1012. }
  1013. } else
  1014. gcd = 1;
  1015. for (i = 0; i < total_pools; i++) {
  1016. pool = pools[i];
  1017. pool->quota_used *= global_quota_gcd;
  1018. pool->quota_used /= gcd;
  1019. pool->quota_gcd = pool->quota / gcd;
  1020. }
  1021. global_quota_gcd = gcd;
  1022. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  1023. }
  1024. /* Return value is ignored if not called from add_pool_details */
  1025. struct pool *add_pool2(struct mining_goal_info * const goal)
  1026. {
  1027. struct pool *pool;
  1028. pool = calloc(sizeof(struct pool), 1);
  1029. if (!pool)
  1030. quit(1, "Failed to malloc pool in add_pool");
  1031. pool->pool_no = pool->prio = total_pools;
  1032. mutex_init(&pool->last_work_lock);
  1033. mutex_init(&pool->pool_lock);
  1034. mutex_init(&pool->pool_test_lock);
  1035. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  1036. quit(1, "Failed to pthread_cond_init in add_pool");
  1037. cglock_init(&pool->data_lock);
  1038. mutex_init(&pool->stratum_lock);
  1039. timer_unset(&pool->swork.tv_transparency);
  1040. pool->swork.pool = pool;
  1041. pool->goal = goal;
  1042. pool->idle = true;
  1043. /* Make sure the pool doesn't think we've been idle since time 0 */
  1044. pool->tv_idle.tv_sec = ~0UL;
  1045. cgtime(&pool->cgminer_stats.start_tv);
  1046. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1047. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1048. pool->rpc_proxy = NULL;
  1049. pool->quota = 1;
  1050. pool->sock = INVSOCK;
  1051. pool->lp_socket = CURL_SOCKET_BAD;
  1052. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1053. pools[total_pools++] = pool;
  1054. if (opt_benchmark)
  1055. {
  1056. // Immediately remove it
  1057. remove_pool(pool);
  1058. return pool;
  1059. }
  1060. adjust_quota_gcd();
  1061. if (!currentpool)
  1062. currentpool = pool;
  1063. enable_pool(pool);
  1064. return pool;
  1065. }
  1066. static
  1067. void pool_set_uri(struct pool * const pool, char * const uri)
  1068. {
  1069. pool->rpc_url = uri;
  1070. }
  1071. /* Pool variant of test and set */
  1072. static bool pool_tset(struct pool *pool, bool *var)
  1073. {
  1074. bool ret;
  1075. mutex_lock(&pool->pool_lock);
  1076. ret = *var;
  1077. *var = true;
  1078. mutex_unlock(&pool->pool_lock);
  1079. return ret;
  1080. }
  1081. bool pool_tclear(struct pool *pool, bool *var)
  1082. {
  1083. bool ret;
  1084. mutex_lock(&pool->pool_lock);
  1085. ret = *var;
  1086. *var = false;
  1087. mutex_unlock(&pool->pool_lock);
  1088. return ret;
  1089. }
  1090. struct pool *current_pool(void)
  1091. {
  1092. struct pool *pool;
  1093. cg_rlock(&control_lock);
  1094. pool = currentpool;
  1095. cg_runlock(&control_lock);
  1096. return pool;
  1097. }
  1098. #if defined(USE_CPUMINING) && !defined(USE_SHA256D)
  1099. static
  1100. char *arg_ignored(const char * const arg)
  1101. {
  1102. return NULL;
  1103. }
  1104. #endif
  1105. static
  1106. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1107. {
  1108. return opt_set_bool(b);
  1109. }
  1110. char *set_int_range(const char *arg, int *i, int min, int max)
  1111. {
  1112. char *err = opt_set_intval(arg, i);
  1113. if (err)
  1114. return err;
  1115. if (*i < min || *i > max)
  1116. return "Value out of range";
  1117. return NULL;
  1118. }
  1119. static char *set_int_0_to_9999(const char *arg, int *i)
  1120. {
  1121. return set_int_range(arg, i, 0, 9999);
  1122. }
  1123. static char *set_int_1_to_65535(const char *arg, int *i)
  1124. {
  1125. return set_int_range(arg, i, 1, 65535);
  1126. }
  1127. static char *set_int_0_to_10(const char *arg, int *i)
  1128. {
  1129. return set_int_range(arg, i, 0, 10);
  1130. }
  1131. static char *set_int_1_to_10(const char *arg, int *i)
  1132. {
  1133. return set_int_range(arg, i, 1, 10);
  1134. }
  1135. char *set_strdup(const char *arg, char **p)
  1136. {
  1137. *p = strdup((char *)arg);
  1138. return NULL;
  1139. }
  1140. #if BLKMAKER_VERSION > 1
  1141. static
  1142. char *set_b58addr(const char * const arg, bytes_t * const b)
  1143. {
  1144. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1145. if (!scriptsz)
  1146. return "Invalid address";
  1147. char *script = malloc(scriptsz);
  1148. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1149. free(script);
  1150. return "Failed to convert address to script";
  1151. }
  1152. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1153. return NULL;
  1154. }
  1155. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1156. static
  1157. char *set_generate_addr(char *arg)
  1158. {
  1159. char * const colon = strchr(arg, ':');
  1160. struct mining_goal_info *goal;
  1161. if (colon)
  1162. {
  1163. colon[0] = '\0';
  1164. goal = get_mining_goal(arg);
  1165. arg = &colon[1];
  1166. }
  1167. else
  1168. goal = get_mining_goal("default");
  1169. return set_generate_addr2(goal, arg);
  1170. }
  1171. static
  1172. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1173. {
  1174. bytes_t newscript = BYTES_INIT;
  1175. char *estr = set_b58addr(arg, &newscript);
  1176. if (estr)
  1177. {
  1178. bytes_free(&newscript);
  1179. return estr;
  1180. }
  1181. if (!goal->generation_script)
  1182. {
  1183. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1184. bytes_init(goal->generation_script);
  1185. }
  1186. bytes_assimilate(goal->generation_script, &newscript);
  1187. bytes_free(&newscript);
  1188. return NULL;
  1189. }
  1190. #endif
  1191. static
  1192. char *set_quit_summary(const char * const arg)
  1193. {
  1194. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1195. opt_quit_summary = BQS_NONE;
  1196. else
  1197. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1198. opt_quit_summary = BQS_DEVS;
  1199. else
  1200. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1201. opt_quit_summary = BQS_PROCS;
  1202. else
  1203. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1204. opt_quit_summary = BQS_DETAILED;
  1205. else
  1206. return "Quit summary must be one of none/devs/procs/detailed";
  1207. return NULL;
  1208. }
  1209. static void pdiff_target_leadzero(void *, double);
  1210. char *set_request_diff(const char *arg, float *p)
  1211. {
  1212. unsigned char target[32];
  1213. char *e = opt_set_floatval(arg, p);
  1214. if (e)
  1215. return e;
  1216. request_bdiff = (double)*p * 0.9999847412109375;
  1217. pdiff_target_leadzero(target, *p);
  1218. request_target_str = malloc(65);
  1219. bin2hex(request_target_str, target, 32);
  1220. return NULL;
  1221. }
  1222. #ifdef NEED_BFG_LOWL_VCOM
  1223. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1224. #ifdef WIN32
  1225. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1226. {
  1227. char dev[PATH_MAX];
  1228. char *devp = dev;
  1229. size_t bufLen = 0x100;
  1230. tryagain: ;
  1231. char buf[bufLen];
  1232. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1233. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1234. bufLen *= 2;
  1235. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1236. goto tryagain;
  1237. }
  1238. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1239. }
  1240. size_t tLen;
  1241. memcpy(devp, "\\\\.\\", 4);
  1242. devp = &devp[4];
  1243. for (char *t = buf; *t; t += tLen) {
  1244. tLen = strlen(t) + 1;
  1245. if (strncmp("COM", t, 3))
  1246. continue;
  1247. memcpy(devp, t, tLen);
  1248. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1249. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1250. }
  1251. }
  1252. #else
  1253. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1254. {
  1255. char dev[PATH_MAX];
  1256. char *devp = dev;
  1257. DIR *D;
  1258. struct dirent *de;
  1259. const char devdir[] = "/dev";
  1260. const size_t devdirlen = sizeof(devdir) - 1;
  1261. char *devpath = devp;
  1262. char *devfile = devpath + devdirlen + 1;
  1263. D = opendir(devdir);
  1264. if (!D)
  1265. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1266. memcpy(devpath, devdir, devdirlen);
  1267. devpath[devdirlen] = '/';
  1268. while ( (de = readdir(D)) ) {
  1269. if (!strncmp(de->d_name, "cu.", 3)
  1270. //don't probe Bluetooth devices - causes bus errors and segfaults
  1271. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1272. goto trydev;
  1273. if (strncmp(de->d_name, "tty", 3))
  1274. continue;
  1275. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1276. continue;
  1277. trydev:
  1278. strcpy(devfile, de->d_name);
  1279. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1280. }
  1281. closedir(D);
  1282. }
  1283. #endif
  1284. #endif
  1285. static char *add_serial(const char *arg)
  1286. {
  1287. string_elist_add(arg, &scan_devices);
  1288. return NULL;
  1289. }
  1290. static
  1291. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1292. {
  1293. string_elist_add(arg, elist);
  1294. return NULL;
  1295. }
  1296. bool get_intrange(const char *arg, int *val1, int *val2)
  1297. {
  1298. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1299. char *p, *p2;
  1300. *val1 = strtol(arg, &p, 0);
  1301. if (arg == p)
  1302. // Zero-length ending number, invalid
  1303. return false;
  1304. while (true)
  1305. {
  1306. if (!p[0])
  1307. {
  1308. *val2 = *val1;
  1309. return true;
  1310. }
  1311. if (p[0] == '-')
  1312. break;
  1313. if (!isspace(p[0]))
  1314. // Garbage, invalid
  1315. return false;
  1316. ++p;
  1317. }
  1318. p2 = &p[1];
  1319. *val2 = strtol(p2, &p, 0);
  1320. if (p2 == p)
  1321. // Zero-length ending number, invalid
  1322. return false;
  1323. while (true)
  1324. {
  1325. if (!p[0])
  1326. return true;
  1327. if (!isspace(p[0]))
  1328. // Garbage, invalid
  1329. return false;
  1330. ++p;
  1331. }
  1332. }
  1333. static
  1334. void _test_intrange(const char *s, const int v[2])
  1335. {
  1336. int a[2];
  1337. if (!get_intrange(s, &a[0], &a[1]))
  1338. {
  1339. ++unittest_failures;
  1340. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1341. }
  1342. for (int i = 0; i < 2; ++i)
  1343. if (unlikely(a[i] != v[i]))
  1344. {
  1345. ++unittest_failures;
  1346. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1347. }
  1348. }
  1349. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1350. static
  1351. void _test_intrange_fail(const char *s)
  1352. {
  1353. int a[2];
  1354. if (get_intrange(s, &a[0], &a[1]))
  1355. {
  1356. ++unittest_failures;
  1357. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1358. }
  1359. }
  1360. static
  1361. void test_intrange()
  1362. {
  1363. _test_intrange("-1--2", -1, -2);
  1364. _test_intrange("-1-2", -1, 2);
  1365. _test_intrange("1--2", 1, -2);
  1366. _test_intrange("1-2", 1, 2);
  1367. _test_intrange("111-222", 111, 222);
  1368. _test_intrange(" 11 - 22 ", 11, 22);
  1369. _test_intrange("+11-+22", 11, 22);
  1370. _test_intrange("-1", -1, -1);
  1371. _test_intrange_fail("all");
  1372. _test_intrange_fail("1-");
  1373. _test_intrange_fail("");
  1374. _test_intrange_fail("1-54x");
  1375. }
  1376. static char *set_devices(char *arg)
  1377. {
  1378. if (*arg) {
  1379. if (*arg == '?') {
  1380. opt_display_devs = true;
  1381. return NULL;
  1382. }
  1383. } else
  1384. return "Invalid device parameters";
  1385. string_elist_add(arg, &opt_devices_enabled_list);
  1386. return NULL;
  1387. }
  1388. static char *set_balance(enum pool_strategy *strategy)
  1389. {
  1390. *strategy = POOL_BALANCE;
  1391. return NULL;
  1392. }
  1393. static char *set_loadbalance(enum pool_strategy *strategy)
  1394. {
  1395. *strategy = POOL_LOADBALANCE;
  1396. return NULL;
  1397. }
  1398. static char *set_rotate(const char *arg, int *i)
  1399. {
  1400. pool_strategy = POOL_ROTATE;
  1401. return set_int_range(arg, i, 0, 9999);
  1402. }
  1403. static char *set_rr(enum pool_strategy *strategy)
  1404. {
  1405. *strategy = POOL_ROUNDROBIN;
  1406. return NULL;
  1407. }
  1408. static
  1409. char *set_benchmark_intense()
  1410. {
  1411. opt_benchmark = true;
  1412. opt_benchmark_intense = true;
  1413. return NULL;
  1414. }
  1415. /* Detect that url is for a stratum protocol either via the presence of
  1416. * stratum+tcp or by detecting a stratum server response */
  1417. bool detect_stratum(struct pool *pool, char *url)
  1418. {
  1419. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1420. return false;
  1421. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1422. pool_set_uri(pool, strdup(url));
  1423. pool->has_stratum = true;
  1424. pool->stratum_url = pool->sockaddr_url;
  1425. return true;
  1426. }
  1427. return false;
  1428. }
  1429. static struct pool *add_url(void)
  1430. {
  1431. total_urls++;
  1432. if (total_urls > total_pools)
  1433. add_pool();
  1434. return pools[total_urls - 1];
  1435. }
  1436. static void setup_url(struct pool *pool, char *arg)
  1437. {
  1438. if (detect_stratum(pool, arg))
  1439. return;
  1440. opt_set_charp(arg, &pool->rpc_url);
  1441. if (strncmp(arg, "http://", 7) &&
  1442. strncmp(arg, "https://", 8)) {
  1443. const size_t L = strlen(arg);
  1444. char *httpinput;
  1445. httpinput = malloc(8 + L);
  1446. if (!httpinput)
  1447. quit(1, "Failed to malloc httpinput");
  1448. sprintf(httpinput, "http://%s", arg);
  1449. pool_set_uri(pool, httpinput);
  1450. }
  1451. }
  1452. static char *set_url(char *arg)
  1453. {
  1454. struct pool *pool = add_url();
  1455. setup_url(pool, arg);
  1456. return NULL;
  1457. }
  1458. static char *set_quota(char *arg)
  1459. {
  1460. char *semicolon = strchr(arg, ';'), *url;
  1461. int len, qlen, quota;
  1462. struct pool *pool;
  1463. if (!semicolon)
  1464. return "No semicolon separated quota;URL pair found";
  1465. len = strlen(arg);
  1466. *semicolon = '\0';
  1467. qlen = strlen(arg);
  1468. if (!qlen)
  1469. return "No parameter for quota found";
  1470. len -= qlen + 1;
  1471. if (len < 1)
  1472. return "No parameter for URL found";
  1473. quota = atoi(arg);
  1474. if (quota < 0)
  1475. return "Invalid negative parameter for quota set";
  1476. url = arg + qlen + 1;
  1477. pool = add_url();
  1478. setup_url(pool, url);
  1479. pool->quota = quota;
  1480. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1481. adjust_quota_gcd();
  1482. return NULL;
  1483. }
  1484. static char *set_user(const char *arg)
  1485. {
  1486. struct pool *pool;
  1487. total_users++;
  1488. if (total_users > total_pools)
  1489. add_pool();
  1490. pool = pools[total_users - 1];
  1491. opt_set_charp(arg, &pool->rpc_user);
  1492. return NULL;
  1493. }
  1494. static char *set_pass(const char *arg)
  1495. {
  1496. struct pool *pool;
  1497. total_passes++;
  1498. if (total_passes > total_pools)
  1499. add_pool();
  1500. pool = pools[total_passes - 1];
  1501. opt_set_charp(arg, &pool->rpc_pass);
  1502. return NULL;
  1503. }
  1504. static char *set_userpass(const char *arg)
  1505. {
  1506. struct pool *pool;
  1507. char *updup;
  1508. if (total_users != total_passes)
  1509. return "User + pass options must be balanced before userpass";
  1510. ++total_users;
  1511. ++total_passes;
  1512. if (total_users > total_pools)
  1513. add_pool();
  1514. pool = pools[total_users - 1];
  1515. updup = strdup(arg);
  1516. opt_set_charp(arg, &pool->rpc_userpass);
  1517. pool->rpc_user = updup;
  1518. pool->rpc_pass = strchr(updup, ':');
  1519. if (pool->rpc_pass)
  1520. pool->rpc_pass++[0] = '\0';
  1521. else
  1522. pool->rpc_pass = &updup[strlen(updup)];
  1523. return NULL;
  1524. }
  1525. static char *set_cbcaddr(char *arg)
  1526. {
  1527. struct pool *pool;
  1528. char *p, *addr;
  1529. bytes_t target_script = BYTES_INIT;
  1530. if (!total_pools)
  1531. return "Define pool first, then the --coinbase-check-addr list";
  1532. pool = pools[total_pools - 1];
  1533. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1534. * need support it later, but now leave the code just so.
  1535. *
  1536. * Regarding details of address prefix 'x', check the below URL:
  1537. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1538. */
  1539. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1540. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1541. {
  1542. struct bytes_hashtbl *ah;
  1543. if (set_b58addr(addr, &target_script))
  1544. /* No bother to free memory since we are going to exit anyway */
  1545. return "Invalid address in --coinbase-check-address list";
  1546. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1547. if (!ah)
  1548. {
  1549. /* Note: for the below allocated memory we have good way to release its memory
  1550. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1551. * get called.
  1552. *
  1553. * We just hope the remove_pool() would not be called many many times during
  1554. * the whole running life of this program.
  1555. */
  1556. ah = malloc(sizeof(*ah));
  1557. bytes_init(&ah->b);
  1558. bytes_assimilate(&ah->b, &target_script);
  1559. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1560. }
  1561. }
  1562. bytes_free(&target_script);
  1563. return NULL;
  1564. }
  1565. static char *set_cbctotal(const char *arg)
  1566. {
  1567. struct pool *pool;
  1568. if (!total_pools)
  1569. return "Define pool first, then the --coinbase-check-total argument";
  1570. pool = pools[total_pools - 1];
  1571. pool->cb_param.total = atoll(arg);
  1572. if (pool->cb_param.total < 0)
  1573. return "The total payout amount in coinbase should be greater than 0";
  1574. return NULL;
  1575. }
  1576. static char *set_cbcperc(const char *arg)
  1577. {
  1578. struct pool *pool;
  1579. if (!total_pools)
  1580. return "Define pool first, then the --coinbase-check-percent argument";
  1581. pool = pools[total_pools - 1];
  1582. if (!pool->cb_param.scripts)
  1583. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1584. pool->cb_param.perc = atof(arg) / 100;
  1585. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1586. return "The percentage should be between 0 and 100";
  1587. return NULL;
  1588. }
  1589. static
  1590. const char *goal_set(struct mining_goal_info * const goal, const char * const optname, const char * const newvalue, bytes_t * const replybuf, enum bfg_set_device_replytype * const out_success)
  1591. {
  1592. *out_success = SDR_ERR;
  1593. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1594. {
  1595. if (!newvalue)
  1596. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1597. struct mining_algorithm * const new_malgo = mining_algorithm_by_alias(newvalue);
  1598. if (!new_malgo)
  1599. return "Unrecognised mining algorithm";
  1600. goal_set_malgo(goal, new_malgo);
  1601. goto success;
  1602. }
  1603. #if BLKMAKER_VERSION > 1
  1604. if (match_strtok("generate-to|generate-to-addr|generate-to-address|genaddress|genaddr|gen-address|gen-addr|generate-address|generate-addr|coinbase-addr|coinbase-address|coinbase-payout|cbaddress|cbaddr|cb-address|cb-addr|payout", "|", optname))
  1605. {
  1606. if (!newvalue)
  1607. return "Missing value for 'generate-to' goal option";
  1608. const char * const emsg = set_generate_addr2(goal, newvalue);
  1609. if (emsg)
  1610. return emsg;
  1611. goto success;
  1612. }
  1613. #endif
  1614. *out_success = SDR_UNKNOWN;
  1615. return "Unknown goal option";
  1616. success:
  1617. *out_success = SDR_OK;
  1618. return NULL;
  1619. }
  1620. // May leak replybuf if returning an error
  1621. static
  1622. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1623. {
  1624. bytes_t replybuf = BYTES_INIT;
  1625. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1626. {
  1627. char *val = strchr(param, '=');
  1628. if (val)
  1629. val++[0] = '\0';
  1630. enum bfg_set_device_replytype success;
  1631. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1632. if (success != SDR_OK)
  1633. return emsg ?: "Error setting goal param";
  1634. }
  1635. bytes_free(&replybuf);
  1636. return NULL;
  1637. }
  1638. static
  1639. const char *set_pool_goal(const char * const arg)
  1640. {
  1641. struct pool *pool;
  1642. if (!total_pools)
  1643. return "Usage of --pool-goal before pools are defined does not make sense";
  1644. pool = pools[total_pools - 1];
  1645. char *param = strchr(arg, ':');
  1646. if (param)
  1647. param++[0] = '\0';
  1648. pool->goal = get_mining_goal(arg);
  1649. if (param)
  1650. return set_goal_params(pool->goal, param);
  1651. return NULL;
  1652. }
  1653. static char *set_pool_priority(const char *arg)
  1654. {
  1655. struct pool *pool;
  1656. if (!total_pools)
  1657. return "Usage of --pool-priority before pools are defined does not make sense";
  1658. pool = pools[total_pools - 1];
  1659. opt_set_intval(arg, &pool->prio);
  1660. return NULL;
  1661. }
  1662. static char *set_pool_proxy(const char *arg)
  1663. {
  1664. struct pool *pool;
  1665. if (!total_pools)
  1666. return "Usage of --pool-proxy before pools are defined does not make sense";
  1667. if (!our_curl_supports_proxy_uris())
  1668. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1669. pool = pools[total_pools - 1];
  1670. opt_set_charp(arg, &pool->rpc_proxy);
  1671. return NULL;
  1672. }
  1673. static char *set_pool_force_rollntime(const char *arg)
  1674. {
  1675. struct pool *pool;
  1676. if (!total_pools)
  1677. return "Usage of --force-rollntime before pools are defined does not make sense";
  1678. pool = pools[total_pools - 1];
  1679. opt_set_intval(arg, &pool->force_rollntime);
  1680. return NULL;
  1681. }
  1682. static char *enable_debug(bool *flag)
  1683. {
  1684. *flag = true;
  1685. opt_debug_console = true;
  1686. /* Turn on verbose output, too. */
  1687. opt_log_output = true;
  1688. return NULL;
  1689. }
  1690. static char *set_schedtime(const char *arg, struct schedtime *st)
  1691. {
  1692. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1693. {
  1694. if (strcasecmp(arg, "now"))
  1695. return "Invalid time set, should be HH:MM";
  1696. } else
  1697. schedstop.tm.tm_sec = 0;
  1698. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1699. return "Invalid time set.";
  1700. st->enable = true;
  1701. return NULL;
  1702. }
  1703. static
  1704. char *set_log_file(char *arg)
  1705. {
  1706. char *r = "";
  1707. long int i = strtol(arg, &r, 10);
  1708. int fd, stderr_fd = fileno(stderr);
  1709. if ((!*r) && i >= 0 && i <= INT_MAX)
  1710. fd = i;
  1711. else
  1712. if (!strcmp(arg, "-"))
  1713. {
  1714. fd = fileno(stdout);
  1715. if (unlikely(fd == -1))
  1716. return "Standard output missing for log-file";
  1717. }
  1718. else
  1719. {
  1720. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1721. if (unlikely(fd == -1))
  1722. return "Failed to open log-file";
  1723. }
  1724. close(stderr_fd);
  1725. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1726. return "Failed to dup2 for log-file";
  1727. close(fd);
  1728. return NULL;
  1729. }
  1730. static
  1731. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1732. {
  1733. char *r = "";
  1734. long int i = strtol(arg, &r, 10);
  1735. static char *err = NULL;
  1736. const size_t errbufsz = 0x100;
  1737. free(err);
  1738. err = NULL;
  1739. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1740. *F = fdopen((int)i, mode);
  1741. if (!*F)
  1742. {
  1743. err = malloc(errbufsz);
  1744. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1745. (int)i, purpose);
  1746. return err;
  1747. }
  1748. } else if (!strcmp(arg, "-")) {
  1749. *F = (mode[0] == 'a') ? stdout : stdin;
  1750. if (!*F)
  1751. {
  1752. err = malloc(errbufsz);
  1753. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1754. (mode[0] == 'a') ? "out" : "in", purpose);
  1755. return err;
  1756. }
  1757. } else {
  1758. *F = fopen(arg, mode);
  1759. if (!*F)
  1760. {
  1761. err = malloc(errbufsz);
  1762. snprintf(err, errbufsz, "Failed to open %s for %s",
  1763. arg, purpose);
  1764. return err;
  1765. }
  1766. }
  1767. return NULL;
  1768. }
  1769. static char *set_noncelog(char *arg)
  1770. {
  1771. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1772. }
  1773. static char *set_sharelog(char *arg)
  1774. {
  1775. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1776. }
  1777. static
  1778. void _add_set_device_option(const char * const func, const char * const buf)
  1779. {
  1780. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1781. string_elist_add(buf, &opt_set_device_list);
  1782. }
  1783. #define add_set_device_option(...) do{ \
  1784. char _tmp1718[0x100]; \
  1785. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1786. _add_set_device_option(__func__, _tmp1718); \
  1787. }while(0)
  1788. char *set_temp_cutoff(char *arg)
  1789. {
  1790. if (strchr(arg, ','))
  1791. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1792. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1793. add_set_device_option("all:temp-cutoff=%s", arg);
  1794. return NULL;
  1795. }
  1796. char *set_temp_target(char *arg)
  1797. {
  1798. if (strchr(arg, ','))
  1799. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1800. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1801. add_set_device_option("all:temp-target=%s", arg);
  1802. return NULL;
  1803. }
  1804. #ifdef USE_OPENCL
  1805. static
  1806. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1807. {
  1808. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1809. add_set_device_option("OCL:binary=no");
  1810. return NULL;
  1811. }
  1812. #endif
  1813. static
  1814. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1815. {
  1816. opt_disable_client_reconnect = true;
  1817. want_stratum = false;
  1818. return NULL;
  1819. }
  1820. static char *set_api_allow(const char *arg)
  1821. {
  1822. opt_set_charp(arg, &opt_api_allow);
  1823. return NULL;
  1824. }
  1825. static char *set_api_groups(const char *arg)
  1826. {
  1827. opt_set_charp(arg, &opt_api_groups);
  1828. return NULL;
  1829. }
  1830. static char *set_api_description(const char *arg)
  1831. {
  1832. opt_set_charp(arg, &opt_api_description);
  1833. return NULL;
  1834. }
  1835. static char *set_api_mcast_des(const char *arg)
  1836. {
  1837. opt_set_charp(arg, &opt_api_mcast_des);
  1838. return NULL;
  1839. }
  1840. #ifdef USE_ICARUS
  1841. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1842. static char *set_icarus_options(const char *arg)
  1843. {
  1844. if (strchr(arg, ','))
  1845. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1846. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1847. char *opts = strdup(arg), *argdup;
  1848. argdup = opts;
  1849. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1850. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1851. char *saveptr, *opt;
  1852. for (int i = 0; i < 4; ++i, ++sdf)
  1853. {
  1854. opt = strtok_r(opts, ":", &saveptr);
  1855. opts = NULL;
  1856. if (!opt)
  1857. break;
  1858. if (!opt[0])
  1859. continue;
  1860. for (int j = 0; j < 4; ++j)
  1861. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1862. }
  1863. free(argdup);
  1864. return NULL;
  1865. }
  1866. static char *set_icarus_timing(const char *arg)
  1867. {
  1868. if (strchr(arg, ','))
  1869. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1870. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1871. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1872. for (int j = 0; j < 4; ++j)
  1873. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1874. return NULL;
  1875. }
  1876. #endif
  1877. #ifdef USE_AVALON
  1878. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1879. static char *set_avalon_options(const char *arg)
  1880. {
  1881. if (strchr(arg, ','))
  1882. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1883. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1884. char *opts = strdup(arg), *argdup;
  1885. argdup = opts;
  1886. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1887. char *saveptr, *opt;
  1888. for (int i = 0; i < 5; ++i, ++sdf)
  1889. {
  1890. opt = strtok_r(opts, ":", &saveptr);
  1891. opts = NULL;
  1892. if (!opt)
  1893. break;
  1894. if (!opt[0])
  1895. continue;
  1896. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1897. }
  1898. free(argdup);
  1899. return NULL;
  1900. }
  1901. #endif
  1902. #ifdef USE_KLONDIKE
  1903. static char *set_klondike_options(const char *arg)
  1904. {
  1905. int hashclock;
  1906. double temptarget;
  1907. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1908. {
  1909. default:
  1910. return "Unrecognised --klondike-options";
  1911. case 2:
  1912. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1913. // fallthru
  1914. case 1:
  1915. add_set_device_option("klondike:clock=%d", hashclock);
  1916. }
  1917. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1918. return NULL;
  1919. }
  1920. #endif
  1921. __maybe_unused
  1922. static char *set_null(const char __maybe_unused *arg)
  1923. {
  1924. return NULL;
  1925. }
  1926. /* These options are available from config file or commandline */
  1927. static struct opt_table opt_config_table[] = {
  1928. #ifdef USE_CPUMINING
  1929. #ifdef USE_SHA256D
  1930. OPT_WITH_ARG("--algo",
  1931. set_algo, show_algo, &opt_algo,
  1932. "Specify sha256 implementation for CPU mining:\n"
  1933. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1934. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1935. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1936. #ifdef WANT_SSE2_4WAY
  1937. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1938. #endif
  1939. #ifdef WANT_VIA_PADLOCK
  1940. "\n\tvia\t\tVIA padlock implementation"
  1941. #endif
  1942. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1943. #ifdef WANT_CRYPTOPP_ASM32
  1944. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1945. #endif
  1946. #ifdef WANT_X8632_SSE2
  1947. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1948. #endif
  1949. #ifdef WANT_X8664_SSE2
  1950. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1951. #endif
  1952. #ifdef WANT_X8664_SSE4
  1953. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1954. #endif
  1955. #ifdef WANT_ALTIVEC_4WAY
  1956. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1957. #endif
  1958. ),
  1959. OPT_WITH_ARG("-a",
  1960. set_algo, show_algo, &opt_algo,
  1961. opt_hidden),
  1962. #else
  1963. // NOTE: Silently ignoring option, since it is plausable a non-SHA256d miner was using it just to skip benchmarking
  1964. OPT_WITH_ARG("--algo|-a", arg_ignored, NULL, NULL, opt_hidden),
  1965. #endif /* USE_SHA256D */
  1966. #endif /* USE_CPUMINING */
  1967. OPT_WITH_ARG("--api-allow",
  1968. set_api_allow, NULL, NULL,
  1969. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1970. OPT_WITH_ARG("--api-description",
  1971. set_api_description, NULL, NULL,
  1972. "Description placed in the API status header, default: BFGMiner version"),
  1973. OPT_WITH_ARG("--api-groups",
  1974. set_api_groups, NULL, NULL,
  1975. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1976. OPT_WITHOUT_ARG("--api-listen",
  1977. opt_set_bool, &opt_api_listen,
  1978. "Enable API, default: disabled"),
  1979. OPT_WITHOUT_ARG("--api-mcast",
  1980. opt_set_bool, &opt_api_mcast,
  1981. "Enable API Multicast listener, default: disabled"),
  1982. OPT_WITH_ARG("--api-mcast-addr",
  1983. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1984. "API Multicast listen address"),
  1985. OPT_WITH_ARG("--api-mcast-code",
  1986. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1987. "Code expected in the API Multicast message, don't use '-'"),
  1988. OPT_WITH_ARG("--api-mcast-des",
  1989. set_api_mcast_des, NULL, NULL,
  1990. "Description appended to the API Multicast reply, default: ''"),
  1991. OPT_WITH_ARG("--api-mcast-port",
  1992. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1993. "API Multicast listen port"),
  1994. OPT_WITHOUT_ARG("--api-network",
  1995. opt_set_bool, &opt_api_network,
  1996. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1997. OPT_WITH_ARG("--api-port",
  1998. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1999. "Port number of miner API"),
  2000. #ifdef HAVE_ADL
  2001. OPT_WITHOUT_ARG("--auto-fan",
  2002. opt_set_bool, &opt_autofan,
  2003. opt_hidden),
  2004. OPT_WITHOUT_ARG("--auto-gpu",
  2005. opt_set_bool, &opt_autoengine,
  2006. opt_hidden),
  2007. #endif
  2008. OPT_WITHOUT_ARG("--balance",
  2009. set_balance, &pool_strategy,
  2010. "Change multipool strategy from failover to even share balance"),
  2011. OPT_WITHOUT_ARG("--benchmark",
  2012. opt_set_bool, &opt_benchmark,
  2013. "Run BFGMiner in benchmark mode - produces no shares"),
  2014. OPT_WITHOUT_ARG("--benchmark-intense",
  2015. set_benchmark_intense, &opt_benchmark_intense,
  2016. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2017. #if defined(USE_BITFORCE)
  2018. OPT_WITHOUT_ARG("--bfl-range",
  2019. opt_set_bool, &opt_bfl_noncerange,
  2020. "Use nonce range on bitforce devices if supported"),
  2021. #endif
  2022. #ifdef HAVE_CHROOT
  2023. OPT_WITH_ARG("--chroot-dir",
  2024. opt_set_charp, NULL, &chroot_dir,
  2025. "Chroot to a directory right after startup"),
  2026. #endif
  2027. OPT_WITH_ARG("--cmd-idle",
  2028. opt_set_charp, NULL, &cmd_idle,
  2029. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2030. OPT_WITH_ARG("--cmd-sick",
  2031. opt_set_charp, NULL, &cmd_sick,
  2032. "Execute a command when a device is declared sick"),
  2033. OPT_WITH_ARG("--cmd-dead",
  2034. opt_set_charp, NULL, &cmd_dead,
  2035. "Execute a command when a device is declared dead"),
  2036. #if BLKMAKER_VERSION > 0
  2037. OPT_WITH_ARG("--coinbase-sig",
  2038. set_strdup, NULL, &opt_coinbase_sig,
  2039. "Set coinbase signature when possible"),
  2040. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2041. set_strdup, NULL, &opt_coinbase_sig,
  2042. opt_hidden),
  2043. #endif
  2044. #ifdef HAVE_CURSES
  2045. OPT_WITHOUT_ARG("--compact",
  2046. opt_set_bool, &opt_compact,
  2047. "Use compact display without per device statistics"),
  2048. #endif
  2049. #ifdef USE_CPUMINING
  2050. OPT_WITH_ARG("--cpu-threads",
  2051. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2052. "Number of miner CPU threads"),
  2053. OPT_WITH_ARG("-t",
  2054. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2055. opt_hidden),
  2056. #endif
  2057. OPT_WITHOUT_ARG("--debug|-D",
  2058. enable_debug, &opt_debug,
  2059. "Enable debug output"),
  2060. OPT_WITHOUT_ARG("--debuglog",
  2061. opt_set_bool, &opt_debug,
  2062. "Enable debug logging"),
  2063. OPT_WITHOUT_ARG("--device-protocol-dump",
  2064. opt_set_bool, &opt_dev_protocol,
  2065. "Verbose dump of device protocol-level activities"),
  2066. OPT_WITH_ARG("--device|-d",
  2067. set_devices, NULL, NULL,
  2068. "Enable only devices matching pattern (default: all)"),
  2069. OPT_WITHOUT_ARG("--disable-rejecting",
  2070. opt_set_bool, &opt_disable_pool,
  2071. "Automatically disable pools that continually reject shares"),
  2072. #ifdef USE_LIBMICROHTTPD
  2073. OPT_WITH_ARG("--http-port",
  2074. opt_set_intval, opt_show_intval, &httpsrv_port,
  2075. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2076. #endif
  2077. OPT_WITH_ARG("--expiry",
  2078. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2079. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2080. OPT_WITH_ARG("-E",
  2081. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2082. opt_hidden),
  2083. OPT_WITH_ARG("--expiry-lp",
  2084. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2085. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2086. OPT_WITHOUT_ARG("--failover-only",
  2087. opt_set_bool, &opt_fail_only,
  2088. "Don't leak work to backup pools when primary pool is lagging"),
  2089. OPT_WITH_ARG("--failover-switch-delay",
  2090. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2091. "Delay in seconds before switching back to a failed pool"),
  2092. #ifdef USE_FPGA
  2093. OPT_WITHOUT_ARG("--force-dev-init",
  2094. opt_set_bool, &opt_force_dev_init,
  2095. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2096. #endif
  2097. #if BLKMAKER_VERSION > 1
  2098. OPT_WITH_ARG("--generate-to",
  2099. set_generate_addr, NULL, NULL,
  2100. "Set an address to generate to for solo mining"),
  2101. OPT_WITH_ARG("--generate-to-addr|--generate-to-address|--genaddress|--genaddr|--gen-address|--gen-addr|--generate-address|--generate-addr|--coinbase-addr|--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  2102. set_generate_addr, NULL, NULL,
  2103. opt_hidden),
  2104. #endif
  2105. #ifdef USE_OPENCL
  2106. OPT_WITH_ARG("--gpu-dyninterval",
  2107. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2108. opt_hidden),
  2109. OPT_WITH_ARG("--gpu-platform",
  2110. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2111. "Select OpenCL platform ID to use for GPU mining"),
  2112. OPT_WITH_ARG("--gpu-threads|-g",
  2113. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2114. opt_hidden),
  2115. #ifdef HAVE_ADL
  2116. OPT_WITH_ARG("--gpu-engine",
  2117. set_gpu_engine, NULL, NULL,
  2118. opt_hidden),
  2119. OPT_WITH_ARG("--gpu-fan",
  2120. set_gpu_fan, NULL, NULL,
  2121. opt_hidden),
  2122. OPT_WITH_ARG("--gpu-map",
  2123. set_gpu_map, NULL, NULL,
  2124. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2125. OPT_WITH_ARG("--gpu-memclock",
  2126. set_gpu_memclock, NULL, NULL,
  2127. opt_hidden),
  2128. OPT_WITH_ARG("--gpu-memdiff",
  2129. set_gpu_memdiff, NULL, NULL,
  2130. opt_hidden),
  2131. OPT_WITH_ARG("--gpu-powertune",
  2132. set_gpu_powertune, NULL, NULL,
  2133. opt_hidden),
  2134. OPT_WITHOUT_ARG("--gpu-reorder",
  2135. opt_set_bool, &opt_reorder,
  2136. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2137. OPT_WITH_ARG("--gpu-vddc",
  2138. set_gpu_vddc, NULL, NULL,
  2139. opt_hidden),
  2140. #endif
  2141. #ifdef USE_SCRYPT
  2142. OPT_WITH_ARG("--lookup-gap",
  2143. set_lookup_gap, NULL, NULL,
  2144. opt_hidden),
  2145. #endif
  2146. OPT_WITH_ARG("--intensity|-I",
  2147. set_intensity, NULL, NULL,
  2148. opt_hidden),
  2149. #endif
  2150. #if defined(USE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2151. OPT_WITH_ARG("--kernel-path",
  2152. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2153. "Specify a path to where bitstream and kernel files are"),
  2154. OPT_WITH_ARG("-K",
  2155. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2156. opt_hidden),
  2157. #endif
  2158. #ifdef USE_OPENCL
  2159. OPT_WITH_ARG("--kernel|-k",
  2160. set_kernel, NULL, NULL,
  2161. opt_hidden),
  2162. #endif
  2163. #ifdef USE_ICARUS
  2164. OPT_WITH_ARG("--icarus-options",
  2165. set_icarus_options, NULL, NULL,
  2166. opt_hidden),
  2167. OPT_WITH_ARG("--icarus-timing",
  2168. set_icarus_timing, NULL, NULL,
  2169. opt_hidden),
  2170. #endif
  2171. #ifdef USE_AVALON
  2172. OPT_WITH_ARG("--avalon-options",
  2173. set_avalon_options, NULL, NULL,
  2174. opt_hidden),
  2175. #endif
  2176. #ifdef USE_KLONDIKE
  2177. OPT_WITH_ARG("--klondike-options",
  2178. set_klondike_options, NULL, NULL,
  2179. "Set klondike options clock:temptarget"),
  2180. #endif
  2181. OPT_WITHOUT_ARG("--load-balance",
  2182. set_loadbalance, &pool_strategy,
  2183. "Change multipool strategy from failover to quota based balance"),
  2184. OPT_WITH_ARG("--log|-l",
  2185. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2186. "Interval in seconds between log output"),
  2187. OPT_WITH_ARG("--log-file|-L",
  2188. set_log_file, NULL, NULL,
  2189. "Append log file for output messages"),
  2190. OPT_WITH_ARG("--logfile",
  2191. set_log_file, NULL, NULL,
  2192. opt_hidden),
  2193. OPT_WITHOUT_ARG("--log-microseconds",
  2194. opt_set_bool, &opt_log_microseconds,
  2195. "Include microseconds in log output"),
  2196. #if defined(unix) || defined(__APPLE__)
  2197. OPT_WITH_ARG("--monitor|-m",
  2198. opt_set_charp, NULL, &opt_stderr_cmd,
  2199. "Use custom pipe cmd for output messages"),
  2200. #endif // defined(unix)
  2201. OPT_WITHOUT_ARG("--net-delay",
  2202. opt_set_bool, &opt_delaynet,
  2203. "Impose small delays in networking to avoid overloading slow routers"),
  2204. OPT_WITHOUT_ARG("--no-adl",
  2205. opt_set_bool, &opt_noadl,
  2206. #ifdef HAVE_ADL
  2207. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2208. #else
  2209. opt_hidden
  2210. #endif
  2211. ),
  2212. OPT_WITHOUT_ARG("--no-gbt",
  2213. opt_set_invbool, &want_gbt,
  2214. "Disable getblocktemplate support"),
  2215. OPT_WITHOUT_ARG("--no-getwork",
  2216. opt_set_invbool, &want_getwork,
  2217. "Disable getwork support"),
  2218. OPT_WITHOUT_ARG("--no-hotplug",
  2219. #ifdef HAVE_BFG_HOTPLUG
  2220. opt_set_invbool, &opt_hotplug,
  2221. "Disable hotplug detection"
  2222. #else
  2223. set_null, &opt_hotplug,
  2224. opt_hidden
  2225. #endif
  2226. ),
  2227. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2228. #if BLKMAKER_VERSION > 1
  2229. opt_set_invbool, &opt_load_bitcoin_conf,
  2230. "Disable adding pools for local bitcoin RPC servers"),
  2231. #else
  2232. set_null, NULL, opt_hidden),
  2233. #endif
  2234. OPT_WITHOUT_ARG("--no-longpoll",
  2235. opt_set_invbool, &want_longpoll,
  2236. "Disable X-Long-Polling support"),
  2237. OPT_WITHOUT_ARG("--no-pool-disable",
  2238. opt_set_invbool, &opt_disable_pool,
  2239. opt_hidden),
  2240. OPT_WITHOUT_ARG("--no-client-reconnect",
  2241. opt_set_invbool, &opt_disable_client_reconnect,
  2242. opt_hidden),
  2243. OPT_WITHOUT_ARG("--no-pool-redirect",
  2244. disable_pool_redirect, NULL,
  2245. "Ignore pool requests to redirect to another server"),
  2246. OPT_WITHOUT_ARG("--no-restart",
  2247. opt_set_invbool, &opt_restart,
  2248. "Do not attempt to restart devices that hang"
  2249. ),
  2250. OPT_WITHOUT_ARG("--no-show-processors",
  2251. opt_set_invbool, &opt_show_procs,
  2252. opt_hidden),
  2253. OPT_WITHOUT_ARG("--no-show-procs",
  2254. opt_set_invbool, &opt_show_procs,
  2255. opt_hidden),
  2256. OPT_WITHOUT_ARG("--no-stratum",
  2257. opt_set_invbool, &want_stratum,
  2258. "Disable Stratum detection"),
  2259. OPT_WITHOUT_ARG("--no-submit-stale",
  2260. opt_set_invbool, &opt_submit_stale,
  2261. "Don't submit shares if they are detected as stale"),
  2262. #ifdef USE_OPENCL
  2263. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2264. set_no_opencl_binaries, NULL,
  2265. opt_hidden),
  2266. #endif
  2267. OPT_WITHOUT_ARG("--no-unicode",
  2268. #ifdef USE_UNICODE
  2269. opt_set_invbool, &use_unicode,
  2270. "Don't use Unicode characters in TUI"
  2271. #else
  2272. set_null, &use_unicode,
  2273. opt_hidden
  2274. #endif
  2275. ),
  2276. OPT_WITH_ARG("--noncelog",
  2277. set_noncelog, NULL, NULL,
  2278. "Create log of all nonces found"),
  2279. OPT_WITH_ARG("--pass|-p",
  2280. set_pass, NULL, NULL,
  2281. "Password for bitcoin JSON-RPC server"),
  2282. OPT_WITHOUT_ARG("--per-device-stats",
  2283. opt_set_bool, &want_per_device_stats,
  2284. "Force verbose mode and output per-device statistics"),
  2285. OPT_WITH_ARG("--userpass|-O",
  2286. set_userpass, NULL, NULL,
  2287. "Username:Password pair for bitcoin JSON-RPC server"),
  2288. OPT_WITH_ARG("--pool-goal",
  2289. set_pool_goal, NULL, NULL,
  2290. "Named goal for the previous-defined pool"),
  2291. OPT_WITH_ARG("--pool-priority",
  2292. set_pool_priority, NULL, NULL,
  2293. "Priority for just the previous-defined pool"),
  2294. OPT_WITH_ARG("--pool-proxy|-x",
  2295. set_pool_proxy, NULL, NULL,
  2296. "Proxy URI to use for connecting to just the previous-defined pool"),
  2297. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2298. set_pool_force_rollntime, NULL, NULL,
  2299. opt_hidden),
  2300. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2301. opt_set_bool, &opt_protocol,
  2302. "Verbose dump of protocol-level activities"),
  2303. OPT_WITH_ARG("--queue|-Q",
  2304. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2305. "Minimum number of work items to have queued (0+)"),
  2306. OPT_WITHOUT_ARG("--quiet|-q",
  2307. opt_set_bool, &opt_quiet,
  2308. "Disable logging output, display status and errors"),
  2309. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2310. opt_set_bool, &opt_quiet_work_updates,
  2311. opt_hidden),
  2312. OPT_WITH_ARG("--quit-summary",
  2313. set_quit_summary, NULL, NULL,
  2314. "Summary printed when you quit: none/devs/procs/detailed"),
  2315. OPT_WITH_ARG("--quota|-U",
  2316. set_quota, NULL, NULL,
  2317. "quota;URL combination for server with load-balance strategy quotas"),
  2318. OPT_WITHOUT_ARG("--real-quiet",
  2319. opt_set_bool, &opt_realquiet,
  2320. "Disable all output"),
  2321. OPT_WITH_ARG("--request-diff",
  2322. set_request_diff, opt_show_floatval, &request_pdiff,
  2323. "Request a specific difficulty from pools"),
  2324. OPT_WITH_ARG("--retries",
  2325. opt_set_intval, opt_show_intval, &opt_retries,
  2326. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2327. OPT_WITH_ARG("--retry-pause",
  2328. set_null, NULL, NULL,
  2329. opt_hidden),
  2330. OPT_WITH_ARG("--rotate",
  2331. set_rotate, opt_show_intval, &opt_rotate_period,
  2332. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2333. OPT_WITHOUT_ARG("--round-robin",
  2334. set_rr, &pool_strategy,
  2335. "Change multipool strategy from failover to round robin on failure"),
  2336. OPT_WITH_ARG("--scan|-S",
  2337. add_serial, NULL, NULL,
  2338. "Configure how to scan for mining devices"),
  2339. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2340. add_serial, NULL, NULL,
  2341. opt_hidden),
  2342. OPT_WITH_ARG("--scan-time",
  2343. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2344. "Upper bound on time spent scanning current work, in seconds"),
  2345. OPT_WITH_ARG("-s",
  2346. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2347. opt_hidden),
  2348. OPT_WITH_ARG("--scantime",
  2349. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2350. opt_hidden),
  2351. OPT_WITH_ARG("--sched-start",
  2352. set_schedtime, NULL, &schedstart,
  2353. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2354. OPT_WITH_ARG("--sched-stop",
  2355. set_schedtime, NULL, &schedstop,
  2356. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2357. #ifdef USE_SCRYPT
  2358. OPT_WITHOUT_ARG("--scrypt",
  2359. set_malgo_scrypt, NULL,
  2360. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2361. #endif
  2362. OPT_WITH_ARG("--set-device|--set",
  2363. opt_string_elist_add, NULL, &opt_set_device_list,
  2364. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2365. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2366. OPT_WITH_ARG("--shaders",
  2367. set_shaders, NULL, NULL,
  2368. opt_hidden),
  2369. #endif
  2370. #ifdef HAVE_PWD_H
  2371. OPT_WITH_ARG("--setuid",
  2372. opt_set_charp, NULL, &opt_setuid,
  2373. "Username of an unprivileged user to run as"),
  2374. #endif
  2375. OPT_WITH_ARG("--sharelog",
  2376. set_sharelog, NULL, NULL,
  2377. "Append share log to file"),
  2378. OPT_WITH_ARG("--shares",
  2379. opt_set_floatval, NULL, &opt_shares,
  2380. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2381. OPT_WITHOUT_ARG("--show-processors",
  2382. opt_set_bool, &opt_show_procs,
  2383. "Show per processor statistics in summary"),
  2384. OPT_WITHOUT_ARG("--show-procs",
  2385. opt_set_bool, &opt_show_procs,
  2386. opt_hidden),
  2387. OPT_WITH_ARG("--skip-security-checks",
  2388. set_int_0_to_9999, NULL, &opt_skip_checks,
  2389. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2390. OPT_WITH_ARG("--socks-proxy",
  2391. opt_set_charp, NULL, &opt_socks_proxy,
  2392. "Set socks proxy (host:port)"),
  2393. #ifdef USE_LIBEVENT
  2394. OPT_WITH_ARG("--stratum-port",
  2395. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2396. "Port number to listen on for stratum miners (-1 means disabled)"),
  2397. #endif
  2398. OPT_WITHOUT_ARG("--submit-stale",
  2399. opt_set_bool, &opt_submit_stale,
  2400. opt_hidden),
  2401. OPT_WITH_ARG("--submit-threads",
  2402. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2403. "Minimum number of concurrent share submissions (default: 64)"),
  2404. #ifdef HAVE_SYSLOG_H
  2405. OPT_WITHOUT_ARG("--syslog",
  2406. opt_set_bool, &use_syslog,
  2407. "Use system log for output messages (default: standard error)"),
  2408. #endif
  2409. OPT_WITH_ARG("--temp-cutoff",
  2410. set_temp_cutoff, NULL, &opt_cutofftemp,
  2411. opt_hidden),
  2412. OPT_WITH_ARG("--temp-hysteresis",
  2413. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2414. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2415. #ifdef HAVE_ADL
  2416. OPT_WITH_ARG("--temp-overheat",
  2417. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2418. opt_hidden),
  2419. #endif
  2420. OPT_WITH_ARG("--temp-target",
  2421. set_temp_target, NULL, NULL,
  2422. opt_hidden),
  2423. OPT_WITHOUT_ARG("--text-only|-T",
  2424. opt_set_invbool, &use_curses,
  2425. #ifdef HAVE_CURSES
  2426. "Disable ncurses formatted screen output"
  2427. #else
  2428. opt_hidden
  2429. #endif
  2430. ),
  2431. #if defined(USE_SCRYPT) && defined(USE_OPENCL)
  2432. OPT_WITH_ARG("--thread-concurrency",
  2433. set_thread_concurrency, NULL, NULL,
  2434. opt_hidden),
  2435. #endif
  2436. #ifdef USE_UNICODE
  2437. OPT_WITHOUT_ARG("--unicode",
  2438. opt_set_bool, &use_unicode,
  2439. "Use Unicode characters in TUI"),
  2440. #endif
  2441. OPT_WITH_ARG("--url|-o",
  2442. set_url, NULL, NULL,
  2443. "URL for bitcoin JSON-RPC server"),
  2444. OPT_WITH_ARG("--user|-u",
  2445. set_user, NULL, NULL,
  2446. "Username for bitcoin JSON-RPC server"),
  2447. #ifdef USE_OPENCL
  2448. OPT_WITH_ARG("--vectors|-v",
  2449. set_vector, NULL, NULL,
  2450. opt_hidden),
  2451. #endif
  2452. OPT_WITHOUT_ARG("--verbose",
  2453. opt_set_bool, &opt_log_output,
  2454. "Log verbose output to stderr as well as status output"),
  2455. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2456. opt_set_invbool, &opt_quiet_work_updates,
  2457. opt_hidden),
  2458. OPT_WITHOUT_ARG("--weighed-stats",
  2459. opt_set_bool, &opt_weighed_stats,
  2460. "Display statistics weighed to difficulty 1"),
  2461. #ifdef USE_OPENCL
  2462. OPT_WITH_ARG("--worksize|-w",
  2463. set_worksize, NULL, NULL,
  2464. opt_hidden),
  2465. #endif
  2466. OPT_WITHOUT_ARG("--unittest",
  2467. opt_set_bool, &opt_unittest, opt_hidden),
  2468. OPT_WITH_ARG("--coinbase-check-addr",
  2469. set_cbcaddr, NULL, NULL,
  2470. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2471. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2472. set_cbcaddr, NULL, NULL,
  2473. opt_hidden),
  2474. OPT_WITH_ARG("--coinbase-check-total",
  2475. set_cbctotal, NULL, NULL,
  2476. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2477. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2478. set_cbctotal, NULL, NULL,
  2479. opt_hidden),
  2480. OPT_WITH_ARG("--coinbase-check-percent",
  2481. set_cbcperc, NULL, NULL,
  2482. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2483. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2484. set_cbcperc, NULL, NULL,
  2485. opt_hidden),
  2486. OPT_WITHOUT_ARG("--worktime",
  2487. opt_set_bool, &opt_worktime,
  2488. "Display extra work time debug information"),
  2489. OPT_WITH_ARG("--pools",
  2490. opt_set_bool, NULL, NULL, opt_hidden),
  2491. OPT_ENDTABLE
  2492. };
  2493. static char *load_config(const char *arg, void __maybe_unused *unused);
  2494. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2495. {
  2496. static char err_buf[200];
  2497. struct opt_table *opt;
  2498. json_t *val;
  2499. if (fileconf && !*fileconf_load_p)
  2500. *fileconf_load_p = 1;
  2501. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2502. char *p, *name, *sp;
  2503. /* We don't handle subtables. */
  2504. assert(!(opt->type & OPT_SUBTABLE));
  2505. if (!opt->names)
  2506. continue;
  2507. /* Pull apart the option name(s). */
  2508. name = strdup(opt->names);
  2509. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2510. char *err = "Invalid value";
  2511. /* Ignore short options. */
  2512. if (p[1] != '-')
  2513. continue;
  2514. val = json_object_get(config, p+2);
  2515. if (!val)
  2516. continue;
  2517. if (opt->type & OPT_HASARG) {
  2518. if (json_is_string(val)) {
  2519. err = opt->cb_arg(json_string_value(val),
  2520. opt->u.arg);
  2521. } else if (json_is_number(val)) {
  2522. char buf[256], *p, *q;
  2523. snprintf(buf, 256, "%f", json_number_value(val));
  2524. if ( (p = strchr(buf, '.')) ) {
  2525. // Trim /\.0*$/ to work properly with integer-only arguments
  2526. q = p;
  2527. while (*(++q) == '0') {}
  2528. if (*q == '\0')
  2529. *p = '\0';
  2530. }
  2531. err = opt->cb_arg(buf, opt->u.arg);
  2532. } else if (json_is_array(val)) {
  2533. int n, size = json_array_size(val);
  2534. err = NULL;
  2535. for (n = 0; n < size && !err; n++) {
  2536. if (json_is_string(json_array_get(val, n)))
  2537. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2538. else if (json_is_object(json_array_get(val, n)))
  2539. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2540. }
  2541. }
  2542. } else if (opt->type & OPT_NOARG) {
  2543. if (json_is_true(val))
  2544. err = opt->cb(opt->u.arg);
  2545. else if (json_is_boolean(val)) {
  2546. if (opt->cb == (void*)opt_set_bool)
  2547. err = opt_set_invbool(opt->u.arg);
  2548. else if (opt->cb == (void*)opt_set_invbool)
  2549. err = opt_set_bool(opt->u.arg);
  2550. }
  2551. }
  2552. if (err) {
  2553. /* Allow invalid values to be in configuration
  2554. * file, just skipping over them provided the
  2555. * JSON is still valid after that. */
  2556. if (fileconf) {
  2557. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2558. *fileconf_load_p = -1;
  2559. } else {
  2560. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2561. p, err);
  2562. free(name);
  2563. return err_buf;
  2564. }
  2565. }
  2566. }
  2567. free(name);
  2568. }
  2569. val = json_object_get(config, JSON_INCLUDE_CONF);
  2570. if (val && json_is_string(val))
  2571. return load_config(json_string_value(val), NULL);
  2572. return NULL;
  2573. }
  2574. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2575. char conf_web1[] = "http://";
  2576. char conf_web2[] = "https://";
  2577. static char *load_web_config(const char *arg)
  2578. {
  2579. json_t *val;
  2580. CURL *curl;
  2581. struct bfg_loaded_configfile *cfginfo;
  2582. curl = curl_easy_init();
  2583. if (unlikely(!curl))
  2584. quithere(1, "CURL initialisation failed");
  2585. val = json_web_config(curl, arg);
  2586. curl_easy_cleanup(curl);
  2587. if (!val || !json_is_object(val))
  2588. return JSON_WEB_ERROR;
  2589. cfginfo = malloc(sizeof(*cfginfo));
  2590. *cfginfo = (struct bfg_loaded_configfile){
  2591. .filename = strdup(arg),
  2592. };
  2593. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2594. config_loaded = true;
  2595. return parse_config(val, true, &cfginfo->fileconf_load);
  2596. }
  2597. static char *load_config(const char *arg, void __maybe_unused *unused)
  2598. {
  2599. json_error_t err;
  2600. json_t *config;
  2601. char *json_error;
  2602. size_t siz;
  2603. struct bfg_loaded_configfile *cfginfo;
  2604. if (strncasecmp(arg, conf_web1, sizeof(conf_web1)-1) == 0 ||
  2605. strncasecmp(arg, conf_web2, sizeof(conf_web2)-1) == 0)
  2606. return load_web_config(arg);
  2607. cfginfo = malloc(sizeof(*cfginfo));
  2608. *cfginfo = (struct bfg_loaded_configfile){
  2609. .filename = strdup(arg),
  2610. };
  2611. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2612. if (++include_count > JSON_MAX_DEPTH)
  2613. return JSON_MAX_DEPTH_ERR;
  2614. #if JANSSON_MAJOR_VERSION > 1
  2615. config = json_load_file(arg, 0, &err);
  2616. #else
  2617. config = json_load_file(arg, &err);
  2618. #endif
  2619. if (!json_is_object(config)) {
  2620. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2621. json_error = malloc(siz);
  2622. if (!json_error)
  2623. quit(1, "Malloc failure in json error");
  2624. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2625. return json_error;
  2626. }
  2627. config_loaded = true;
  2628. /* Parse the config now, so we can override it. That can keep pointers
  2629. * so don't free config object. */
  2630. return parse_config(config, true, &cfginfo->fileconf_load);
  2631. }
  2632. static
  2633. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2634. {
  2635. bool * const found_defcfg_p = userp;
  2636. *found_defcfg_p = true;
  2637. load_config(filepath, NULL);
  2638. // Regardless of status of loading the config file, we should continue loading other defaults
  2639. return false;
  2640. }
  2641. static void load_default_config(void)
  2642. {
  2643. bool found_defcfg = false;
  2644. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2645. if (!found_defcfg)
  2646. {
  2647. // No BFGMiner config, try Cgminer's...
  2648. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2649. }
  2650. }
  2651. extern const char *opt_argv0;
  2652. static
  2653. void bfg_versioninfo(void)
  2654. {
  2655. puts(packagename);
  2656. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2657. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2658. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2659. printf(" Options:%s\n", BFG_OPTLIST);
  2660. }
  2661. static char *opt_verusage_and_exit(const char *extra)
  2662. {
  2663. bfg_versioninfo();
  2664. printf("%s", opt_usage(opt_argv0, extra));
  2665. fflush(stdout);
  2666. exit(0);
  2667. }
  2668. static
  2669. const char *my_opt_version_and_exit(void)
  2670. {
  2671. bfg_versioninfo();
  2672. fflush(stdout);
  2673. exit(0);
  2674. }
  2675. /* These options are parsed before anything else */
  2676. static struct opt_table opt_early_table[] = {
  2677. // Default config is loaded in command line order, like a regular config
  2678. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2679. set_bool_ignore_arg, NULL, &config_loaded,
  2680. opt_hidden),
  2681. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2682. opt_set_bool, &config_loaded,
  2683. "Inhibit loading default config file"),
  2684. OPT_ENDTABLE
  2685. };
  2686. /* These options are available from commandline only */
  2687. static struct opt_table opt_cmdline_table[] = {
  2688. OPT_WITH_ARG("--config|-c",
  2689. load_config, NULL, NULL,
  2690. "Load a JSON-format configuration file\n"
  2691. "See example.conf for an example configuration."),
  2692. OPT_EARLY_WITHOUT_ARG("--no-config",
  2693. opt_set_bool, &config_loaded,
  2694. opt_hidden),
  2695. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2696. opt_set_bool, &config_loaded,
  2697. "Inhibit loading default config file"),
  2698. OPT_WITHOUT_ARG("--default-config",
  2699. load_default_config, NULL,
  2700. "Always load the default config file"),
  2701. OPT_WITHOUT_ARG("--help|-h",
  2702. opt_verusage_and_exit, NULL,
  2703. "Print this message"),
  2704. #ifdef USE_OPENCL
  2705. OPT_WITHOUT_ARG("--ndevs|-n",
  2706. print_ndevs_and_exit, &nDevs,
  2707. opt_hidden),
  2708. #endif
  2709. OPT_WITHOUT_ARG("--version|-V",
  2710. my_opt_version_and_exit, NULL,
  2711. "Display version and exit"),
  2712. OPT_ENDTABLE
  2713. };
  2714. static bool jobj_binary(const json_t *obj, const char *key,
  2715. void *buf, size_t buflen, bool required)
  2716. {
  2717. const char *hexstr;
  2718. json_t *tmp;
  2719. tmp = json_object_get(obj, key);
  2720. if (unlikely(!tmp)) {
  2721. if (unlikely(required))
  2722. applog(LOG_ERR, "JSON key '%s' not found", key);
  2723. return false;
  2724. }
  2725. hexstr = json_string_value(tmp);
  2726. if (unlikely(!hexstr)) {
  2727. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2728. return false;
  2729. }
  2730. if (!hex2bin(buf, hexstr, buflen))
  2731. return false;
  2732. return true;
  2733. }
  2734. static void calc_midstate(struct work *work)
  2735. {
  2736. union {
  2737. unsigned char c[64];
  2738. uint32_t i[16];
  2739. } data;
  2740. swap32yes(&data.i[0], work->data, 16);
  2741. sha256_ctx ctx;
  2742. sha256_init(&ctx);
  2743. sha256_update(&ctx, data.c, 64);
  2744. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2745. swap32tole(work->midstate, work->midstate, 8);
  2746. }
  2747. static
  2748. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2749. {
  2750. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2751. *tr = (struct bfg_tmpl_ref){
  2752. .tmpl = tmpl,
  2753. .refcount = 1,
  2754. };
  2755. mutex_init(&tr->mutex);
  2756. return tr;
  2757. }
  2758. static
  2759. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2760. {
  2761. mutex_lock(&tr->mutex);
  2762. ++tr->refcount;
  2763. mutex_unlock(&tr->mutex);
  2764. }
  2765. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2766. {
  2767. mutex_lock(&tr->mutex);
  2768. bool free_tmpl = !--tr->refcount;
  2769. mutex_unlock(&tr->mutex);
  2770. if (free_tmpl)
  2771. {
  2772. blktmpl_free(tr->tmpl);
  2773. mutex_destroy(&tr->mutex);
  2774. free(tr);
  2775. }
  2776. }
  2777. static struct work *make_work(void)
  2778. {
  2779. struct work *work = calloc(1, sizeof(struct work));
  2780. if (unlikely(!work))
  2781. quit(1, "Failed to calloc work in make_work");
  2782. cg_wlock(&control_lock);
  2783. work->id = total_work++;
  2784. cg_wunlock(&control_lock);
  2785. return work;
  2786. }
  2787. /* This is the central place all work that is about to be retired should be
  2788. * cleaned to remove any dynamically allocated arrays within the struct */
  2789. void clean_work(struct work *work)
  2790. {
  2791. free(work->job_id);
  2792. bytes_free(&work->nonce2);
  2793. free(work->nonce1);
  2794. if (work->device_data_free_func)
  2795. work->device_data_free_func(work);
  2796. if (work->tr)
  2797. tmpl_decref(work->tr);
  2798. memset(work, 0, sizeof(struct work));
  2799. }
  2800. /* All dynamically allocated work structs should be freed here to not leak any
  2801. * ram from arrays allocated within the work struct */
  2802. void free_work(struct work *work)
  2803. {
  2804. clean_work(work);
  2805. free(work);
  2806. }
  2807. 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";
  2808. #define workpadding_bin bfg_workpadding_bin
  2809. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2810. static
  2811. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2812. {
  2813. unsigned char hash_swap[32];
  2814. swap256(hash_swap, blkinfo->prevblkhash);
  2815. swap32tole(hash_swap, hash_swap, 32 / 4);
  2816. memset(out, '.', 3);
  2817. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2818. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2819. {
  2820. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2821. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2822. }
  2823. else
  2824. bin2hex(&out[3], &hash_swap[0x18], 8);
  2825. }
  2826. #ifdef HAVE_CURSES
  2827. static void update_block_display(void);
  2828. #endif
  2829. // Must only be called with ch_lock held!
  2830. static
  2831. void __update_block_title(struct mining_goal_info * const goal)
  2832. {
  2833. struct blockchain_info * const blkchain = goal->blkchain;
  2834. if (!goal->current_goal_detail)
  2835. goal->current_goal_detail = malloc(block_info_str_sz);
  2836. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2837. #ifdef HAVE_CURSES
  2838. update_block_display();
  2839. #endif
  2840. }
  2841. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2842. static
  2843. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2844. {
  2845. struct blockchain_info * const blkchain = goal->blkchain;
  2846. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2847. if ((!blkinfo) || blkinfo->height)
  2848. return;
  2849. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2850. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2851. cg_wlock(&ch_lock);
  2852. blkinfo->height = blkheight;
  2853. if (blkinfo == blkchain->currentblk)
  2854. {
  2855. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2856. __update_block_title(goal);
  2857. }
  2858. cg_wunlock(&ch_lock);
  2859. }
  2860. static
  2861. void pool_set_opaque(struct pool *pool, bool opaque)
  2862. {
  2863. if (pool->swork.opaque == opaque)
  2864. return;
  2865. pool->swork.opaque = opaque;
  2866. if (opaque)
  2867. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2868. pool->pool_no);
  2869. else
  2870. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2871. pool->pool_no);
  2872. }
  2873. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2874. {
  2875. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2876. return true;
  2877. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2878. }
  2879. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2880. {
  2881. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2882. {}
  2883. else
  2884. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2885. {
  2886. if (pool->enabled == POOL_ENABLED)
  2887. {
  2888. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2889. disable_pool(pool, POOL_MISBEHAVING);
  2890. }
  2891. }
  2892. else
  2893. if (pool->enabled == POOL_MISBEHAVING)
  2894. {
  2895. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2896. enable_pool(pool);
  2897. }
  2898. }
  2899. 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)
  2900. {
  2901. const int offsets = max(ntime_roll, 60);
  2902. *nrl = (struct ntime_roll_limits){
  2903. .min = ntime_base,
  2904. .max = ntime_base + ntime_roll,
  2905. .tv_ref = *tvp_ref,
  2906. .minoff = -offsets,
  2907. .maxoff = offsets,
  2908. };
  2909. }
  2910. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2911. {
  2912. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2913. }
  2914. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2915. {
  2916. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2917. const uint32_t ref_ntime = work_get_ntime(work);
  2918. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2919. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2920. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2921. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2922. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2923. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2924. if (max_ntime < min_ntime)
  2925. return -1;
  2926. if (max_ntime - min_ntime > desired_roll)
  2927. {
  2928. // Adjust min_ntime upward for accuracy, when possible
  2929. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2930. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2931. if (ideal_ntime > min_ntime)
  2932. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2933. }
  2934. work_set_ntime(work, min_ntime);
  2935. return max_ntime - min_ntime;
  2936. }
  2937. #if BLKMAKER_VERSION > 1
  2938. static
  2939. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2940. {
  2941. for (int i = 0; i < total_pools; ++i)
  2942. {
  2943. struct pool * const pool = pools[i];
  2944. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2945. return true;
  2946. }
  2947. return false;
  2948. }
  2949. static
  2950. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2951. {
  2952. struct blockchain_info * const blkchain = goal->blkchain;
  2953. if (!goal_has_at_least_one_getcbaddr(goal))
  2954. return;
  2955. char getcbaddr_req[60];
  2956. CURL *curl = NULL;
  2957. json_t *json, *j2;
  2958. const char *s, *s2;
  2959. bytes_t newscript = BYTES_INIT;
  2960. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2961. for (int i = 0; i < total_pools; ++i)
  2962. {
  2963. struct pool * const pool = pools[i];
  2964. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2965. continue;
  2966. if (pool->goal != goal)
  2967. continue;
  2968. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2969. if (!curl)
  2970. {
  2971. curl = curl_easy_init();
  2972. if (unlikely(!curl))
  2973. {
  2974. applogfail(LOG_ERR, "curl_easy_init");
  2975. break;
  2976. }
  2977. }
  2978. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2979. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2980. {
  2981. const char *estrc;
  2982. char *estr = NULL;
  2983. if (!(json && j2))
  2984. estrc = NULL;
  2985. else
  2986. {
  2987. estrc = json_string_value(j2);
  2988. if (!estrc)
  2989. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2990. }
  2991. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2992. free(estr);
  2993. continue;
  2994. }
  2995. s = bfg_json_obj_string(json, "result", NULL);
  2996. if (unlikely(!s))
  2997. {
  2998. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2999. continue;
  3000. }
  3001. s2 = set_b58addr(s, &newscript);
  3002. if (unlikely(s2))
  3003. {
  3004. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  3005. continue;
  3006. }
  3007. if (goal->generation_script)
  3008. {
  3009. if (bytes_eq(&newscript, goal->generation_script))
  3010. {
  3011. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s);
  3012. break;
  3013. }
  3014. }
  3015. else
  3016. {
  3017. goal->generation_script = malloc(sizeof(*goal->generation_script));
  3018. bytes_init(goal->generation_script);
  3019. }
  3020. bytes_assimilate(goal->generation_script, &newscript);
  3021. coinbase_script_block_id = blkchain->currentblk->block_id;
  3022. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  3023. break;
  3024. }
  3025. bytes_free(&newscript);
  3026. if (curl)
  3027. curl_easy_cleanup(curl);
  3028. }
  3029. #endif
  3030. #define GBT_XNONCESZ (sizeof(uint32_t))
  3031. #if BLKMAKER_VERSION > 4
  3032. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  3033. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  3034. #endif
  3035. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  3036. {
  3037. json_t *res_val = json_object_get(val, "result");
  3038. json_t *tmp_val;
  3039. bool ret = false;
  3040. struct timeval tv_now;
  3041. if (unlikely(detect_algo == 1)) {
  3042. json_t *tmp = json_object_get(res_val, "algorithm");
  3043. const char *v = tmp ? json_string_value(tmp) : "";
  3044. if (strncasecmp(v, "scrypt", 6))
  3045. detect_algo = 2;
  3046. }
  3047. timer_set_now(&tv_now);
  3048. if (work->tr)
  3049. {
  3050. blktemplate_t * const tmpl = work->tr->tmpl;
  3051. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3052. if (err) {
  3053. applog(LOG_ERR, "blktmpl error: %s", err);
  3054. return false;
  3055. }
  3056. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3057. #if BLKMAKER_VERSION > 1
  3058. struct mining_goal_info * const goal = pool->goal;
  3059. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3060. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3061. refresh_bitcoind_address(goal, false);
  3062. if (goal->generation_script)
  3063. {
  3064. bool newcb;
  3065. #if BLKMAKER_VERSION > 2
  3066. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3067. #else
  3068. newcb = !tmpl->cbtxn;
  3069. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3070. #endif
  3071. if (newcb)
  3072. {
  3073. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3074. if (ae < (ssize_t)sizeof(template_nonce))
  3075. 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);
  3076. ++template_nonce;
  3077. }
  3078. }
  3079. #endif
  3080. #if BLKMAKER_VERSION > 0
  3081. {
  3082. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3083. static bool appenderr = false;
  3084. if (ae <= 0) {
  3085. if (opt_coinbase_sig) {
  3086. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3087. appenderr = true;
  3088. }
  3089. } else if (ae >= 3 || opt_coinbase_sig) {
  3090. const char *cbappend = opt_coinbase_sig;
  3091. const char * const full = bfgminer_name_space_ver;
  3092. char *need_free = NULL;
  3093. if (!cbappend) {
  3094. if ((size_t)ae >= sizeof(full) - 1)
  3095. cbappend = full;
  3096. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3097. {
  3098. const char *pos = strchr(full, '-');
  3099. size_t sz = (pos - full);
  3100. if (pos && ae > sz)
  3101. {
  3102. cbappend = need_free = malloc(sz + 1);
  3103. memcpy(need_free, full, sz);
  3104. need_free[sz] = '\0';
  3105. }
  3106. else
  3107. cbappend = PACKAGE;
  3108. }
  3109. else
  3110. cbappend = "BFG";
  3111. }
  3112. size_t cbappendsz = strlen(cbappend);
  3113. static bool truncatewarning = false;
  3114. if (cbappendsz <= (size_t)ae) {
  3115. if (cbappendsz < (size_t)ae)
  3116. // If we have space, include the trailing \0
  3117. ++cbappendsz;
  3118. ae = cbappendsz;
  3119. truncatewarning = false;
  3120. } else {
  3121. char *tmp = malloc(ae + 1);
  3122. memcpy(tmp, opt_coinbase_sig, ae);
  3123. tmp[ae] = '\0';
  3124. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3125. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3126. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3127. free(tmp);
  3128. truncatewarning = true;
  3129. }
  3130. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3131. free(need_free);
  3132. if (ae <= 0) {
  3133. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3134. appenderr = true;
  3135. } else
  3136. appenderr = false;
  3137. }
  3138. }
  3139. #endif
  3140. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3141. return false;
  3142. swap32yes(work->data, work->data, 80 / 4);
  3143. memcpy(&work->data[80], workpadding_bin, 48);
  3144. work->ntime_roll_limits = (struct ntime_roll_limits){
  3145. .min = tmpl->mintime,
  3146. .max = tmpl->maxtime,
  3147. .tv_ref = tv_now,
  3148. .minoff = tmpl->mintimeoff,
  3149. .maxoff = tmpl->maxtimeoff,
  3150. };
  3151. const struct blktmpl_longpoll_req *lp;
  3152. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3153. free(pool->lp_id);
  3154. pool->lp_id = strdup(lp->id);
  3155. #if 0 /* This just doesn't work :( */
  3156. curl_socket_t sock = pool->lp_socket;
  3157. if (sock != CURL_SOCKET_BAD) {
  3158. pool->lp_socket = CURL_SOCKET_BAD;
  3159. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3160. shutdown(sock, SHUT_RDWR);
  3161. }
  3162. #endif
  3163. }
  3164. }
  3165. else
  3166. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3167. applog(LOG_ERR, "JSON inval data");
  3168. return false;
  3169. }
  3170. else
  3171. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3172. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3173. // Calculate it ourselves
  3174. applog(LOG_DEBUG, "Calculating midstate locally");
  3175. calc_midstate(work);
  3176. }
  3177. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3178. applog(LOG_ERR, "JSON inval target");
  3179. return false;
  3180. }
  3181. if (work->tr)
  3182. {
  3183. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3184. {
  3185. int p = (sizeof(work->target) - 1) - i;
  3186. unsigned char c = work->target[i];
  3187. work->target[i] = work->target[p];
  3188. work->target[p] = c;
  3189. }
  3190. }
  3191. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3192. struct mining_goal_info * const goal = pool->goal;
  3193. uint32_t blkheight = json_number_value(tmp_val);
  3194. const void * const prevblkhash = &work->data[4];
  3195. have_block_height(goal, prevblkhash, blkheight);
  3196. }
  3197. memset(work->hash, 0, sizeof(work->hash));
  3198. work->tv_staged = tv_now;
  3199. #if BLKMAKER_VERSION > 4
  3200. if (work->tr)
  3201. {
  3202. blktemplate_t * const tmpl = work->tr->tmpl;
  3203. uint8_t buf[80];
  3204. int16_t expire;
  3205. uint8_t *cbtxn;
  3206. size_t cbtxnsz;
  3207. size_t cbextranonceoffset;
  3208. int branchcount;
  3209. libblkmaker_hash_t *branches;
  3210. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3211. {
  3212. struct stratum_work * const swork = &pool->swork;
  3213. const size_t branchdatasz = branchcount * 0x20;
  3214. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3215. cg_wlock(&pool->data_lock);
  3216. swork->tr = work->tr;
  3217. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3218. swork->nonce2_offset = cbextranonceoffset;
  3219. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3220. swork->merkles = branchcount;
  3221. memcpy(swork->header1, &buf[0], 36);
  3222. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3223. swork->tv_received = tv_now;
  3224. memcpy(swork->diffbits, &buf[72], 4);
  3225. memcpy(swork->target, work->target, sizeof(swork->target));
  3226. free(swork->job_id);
  3227. swork->job_id = NULL;
  3228. swork->clean = true;
  3229. swork->work_restart_id = pool->work_restart_id;
  3230. // FIXME: Do something with expire
  3231. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3232. pool->nonce2 = 0;
  3233. cg_wunlock(&pool->data_lock);
  3234. }
  3235. else
  3236. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3237. }
  3238. #endif // BLKMAKER_VERSION > 4
  3239. pool_set_opaque(pool, !work->tr);
  3240. ret = true;
  3241. return ret;
  3242. }
  3243. /* Returns whether the pool supports local work generation or not. */
  3244. static bool pool_localgen(struct pool *pool)
  3245. {
  3246. return (pool->last_work_copy || pool->has_stratum);
  3247. }
  3248. int dev_from_id(int thr_id)
  3249. {
  3250. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3251. return cgpu->device_id;
  3252. }
  3253. /* Create an exponentially decaying average over the opt_log_interval */
  3254. void decay_time(double *f, double fadd, double fsecs)
  3255. {
  3256. double ftotal, fprop;
  3257. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3258. ftotal = 1.0 + fprop;
  3259. *f += (fadd * fprop);
  3260. *f /= ftotal;
  3261. }
  3262. static
  3263. int __total_staged(const bool include_spares)
  3264. {
  3265. int tot = HASH_COUNT(staged_work);
  3266. if (!include_spares)
  3267. tot -= staged_spare;
  3268. return tot;
  3269. }
  3270. static int total_staged(const bool include_spares)
  3271. {
  3272. int ret;
  3273. mutex_lock(stgd_lock);
  3274. ret = __total_staged(include_spares);
  3275. mutex_unlock(stgd_lock);
  3276. return ret;
  3277. }
  3278. #ifdef HAVE_CURSES
  3279. WINDOW *mainwin, *statuswin, *logwin;
  3280. #endif
  3281. double total_secs = 1.0;
  3282. #ifdef HAVE_CURSES
  3283. static char statusline[256];
  3284. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3285. static int statusy;
  3286. static int devsummaryYOffset;
  3287. static int total_lines;
  3288. #endif
  3289. #ifdef USE_OPENCL
  3290. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3291. #endif
  3292. struct cgpu_info *cpus;
  3293. bool _bfg_console_cancel_disabled;
  3294. int _bfg_console_prev_cancelstate;
  3295. #ifdef HAVE_CURSES
  3296. #define lock_curses() bfg_console_lock()
  3297. #define unlock_curses() bfg_console_unlock()
  3298. static bool curses_active_locked(void)
  3299. {
  3300. bool ret;
  3301. lock_curses();
  3302. ret = curses_active;
  3303. if (!ret)
  3304. unlock_curses();
  3305. return ret;
  3306. }
  3307. // Cancellable getch
  3308. int my_cancellable_getch(void)
  3309. {
  3310. // This only works because the macro only hits direct getch() calls
  3311. typedef int (*real_getch_t)(void);
  3312. const real_getch_t real_getch = __real_getch;
  3313. int type, rv;
  3314. bool sct;
  3315. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3316. rv = real_getch();
  3317. if (sct)
  3318. pthread_setcanceltype(type, &type);
  3319. return rv;
  3320. }
  3321. #ifdef PDCURSES
  3322. static
  3323. int bfg_wresize(WINDOW *win, int lines, int columns)
  3324. {
  3325. int rv = wresize(win, lines, columns);
  3326. int x, y;
  3327. getyx(win, y, x);
  3328. if (unlikely(y >= lines || x >= columns))
  3329. {
  3330. if (y >= lines)
  3331. y = lines - 1;
  3332. if (x >= columns)
  3333. x = columns - 1;
  3334. wmove(win, y, x);
  3335. }
  3336. return rv;
  3337. }
  3338. #else
  3339. # define bfg_wresize wresize
  3340. #endif
  3341. #endif
  3342. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3343. {
  3344. va_list ap;
  3345. size_t presz = strlen(buf);
  3346. va_start(ap, fmt);
  3347. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3348. va_end(ap);
  3349. }
  3350. double stats_elapsed(struct cgminer_stats *stats)
  3351. {
  3352. struct timeval now;
  3353. double elapsed;
  3354. if (stats->start_tv.tv_sec == 0)
  3355. elapsed = total_secs;
  3356. else {
  3357. cgtime(&now);
  3358. elapsed = tdiff(&now, &stats->start_tv);
  3359. }
  3360. if (elapsed < 1.0)
  3361. elapsed = 1.0;
  3362. return elapsed;
  3363. }
  3364. bool drv_ready(struct cgpu_info *cgpu)
  3365. {
  3366. switch (cgpu->status) {
  3367. case LIFE_INIT:
  3368. case LIFE_DEAD2:
  3369. return false;
  3370. default:
  3371. return true;
  3372. }
  3373. }
  3374. double cgpu_utility(struct cgpu_info *cgpu)
  3375. {
  3376. double dev_runtime = cgpu_runtime(cgpu);
  3377. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3378. }
  3379. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3380. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3381. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3382. }while(0)
  3383. static float
  3384. utility_to_hashrate(double utility)
  3385. {
  3386. return utility * 0x4444444;
  3387. }
  3388. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3389. static const int _unitbase = 4;
  3390. static
  3391. void pick_unit(float hashrate, unsigned char *unit)
  3392. {
  3393. unsigned char i;
  3394. if (hashrate == 0 || !isfinite(hashrate))
  3395. {
  3396. if (*unit < _unitbase)
  3397. *unit = _unitbase;
  3398. return;
  3399. }
  3400. hashrate *= 1e12;
  3401. for (i = 0; i < *unit; ++i)
  3402. hashrate /= 1e3;
  3403. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3404. while (hashrate >= 999.95)
  3405. {
  3406. hashrate /= 1e3;
  3407. if (likely(_unitchar[*unit] != '?'))
  3408. ++*unit;
  3409. }
  3410. }
  3411. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3412. enum h2bs_fmt {
  3413. H2B_NOUNIT, // "xxx.x"
  3414. H2B_SHORT, // "xxx.xMH/s"
  3415. H2B_SPACED, // "xxx.x MH/s"
  3416. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3417. };
  3418. enum bfu_floatprec {
  3419. FUP_INTEGER,
  3420. FUP_HASHES,
  3421. FUP_BTC,
  3422. FUP_DIFF,
  3423. };
  3424. static
  3425. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3426. {
  3427. char *s = buf;
  3428. unsigned char prec, i, unit;
  3429. int rv = 0;
  3430. if (unitin == -1)
  3431. {
  3432. unit = 0;
  3433. hashrate_pick_unit(hashrate, &unit);
  3434. }
  3435. else
  3436. unit = unitin;
  3437. hashrate *= 1e12;
  3438. for (i = 0; i < unit; ++i)
  3439. hashrate /= 1000;
  3440. switch (fprec)
  3441. {
  3442. case FUP_HASHES:
  3443. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3444. if (hashrate >= 99.995 || unit < 6)
  3445. prec = 1;
  3446. else
  3447. prec = 2;
  3448. _SNP("%5.*f", prec, hashrate);
  3449. break;
  3450. case FUP_INTEGER:
  3451. _SNP("%3d", (int)hashrate);
  3452. break;
  3453. case FUP_BTC:
  3454. if (hashrate >= 99.995)
  3455. prec = 0;
  3456. else
  3457. prec = 2;
  3458. _SNP("%5.*f", prec, hashrate);
  3459. break;
  3460. case FUP_DIFF:
  3461. if (unit > _unitbase)
  3462. _SNP("%.3g", hashrate);
  3463. else
  3464. _SNP("%u", (unsigned int)hashrate);
  3465. }
  3466. if (fmt != H2B_NOUNIT)
  3467. {
  3468. char uc[3] = {_unitchar[unit], '\0'};
  3469. switch (fmt) {
  3470. case H2B_SPACED:
  3471. _SNP(" ");
  3472. default:
  3473. break;
  3474. case H2B_SHORTV:
  3475. if (isspace(uc[0]))
  3476. uc[0] = '\0';
  3477. }
  3478. if (uc[0] == '\xb5')
  3479. // Convert to UTF-8
  3480. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3481. _SNP("%s%s", uc, measurement);
  3482. }
  3483. return rv;
  3484. }
  3485. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3486. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3487. static
  3488. 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)
  3489. {
  3490. unsigned char unit = 0;
  3491. bool allzero = true;
  3492. int i;
  3493. size_t delimsz = 0;
  3494. char *buf = buflist[0];
  3495. size_t bufsz = bufszlist[0];
  3496. size_t itemwidth = (floatprec ? 5 : 3);
  3497. if (!isarray)
  3498. delimsz = strlen(delim);
  3499. for (i = 0; i < count; ++i)
  3500. if (numbers[i] != 0)
  3501. {
  3502. pick_unit(numbers[i], &unit);
  3503. allzero = false;
  3504. }
  3505. if (allzero)
  3506. unit = _unitbase;
  3507. --count;
  3508. for (i = 0; i < count; ++i)
  3509. {
  3510. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3511. if (isarray)
  3512. {
  3513. buf = buflist[i + 1];
  3514. bufsz = bufszlist[i + 1];
  3515. }
  3516. else
  3517. {
  3518. buf += itemwidth;
  3519. bufsz -= itemwidth;
  3520. if (delimsz > bufsz)
  3521. delimsz = bufsz;
  3522. memcpy(buf, delim, delimsz);
  3523. buf += delimsz;
  3524. bufsz -= delimsz;
  3525. }
  3526. }
  3527. // Last entry has the unit
  3528. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3529. return buflist[0];
  3530. }
  3531. #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)
  3532. #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)
  3533. static
  3534. int percentf3(char * const buf, size_t sz, double p, const double t)
  3535. {
  3536. char *s = buf;
  3537. int rv = 0;
  3538. if (!p)
  3539. _SNP("none");
  3540. else
  3541. if (t <= p)
  3542. _SNP("100%%");
  3543. else
  3544. {
  3545. p /= t;
  3546. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3547. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3548. else
  3549. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3550. _SNP("%.1f%%", p * 100); // "9.1%"
  3551. else
  3552. _SNP("%3.0f%%", p * 100); // " 99%"
  3553. }
  3554. return rv;
  3555. }
  3556. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3557. static
  3558. void test_decimal_width()
  3559. {
  3560. // The pipe character at end of each line should perfectly line up
  3561. char printbuf[512];
  3562. char testbuf1[64];
  3563. char testbuf2[64];
  3564. char testbuf3[64];
  3565. char testbuf4[64];
  3566. double testn;
  3567. int width;
  3568. int saved;
  3569. // Hotspots around 0.1 and 0.01
  3570. saved = -1;
  3571. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3572. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3573. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3574. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3575. if (unlikely((saved != -1) && (width != saved))) {
  3576. ++unittest_failures;
  3577. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3578. applog(LOG_ERR, "%s", printbuf);
  3579. }
  3580. saved = width;
  3581. }
  3582. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3583. saved = -1;
  3584. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3585. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3586. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3587. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3588. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3589. width = utf8_strlen(printbuf);
  3590. if (unlikely((saved != -1) && (width != saved))) {
  3591. ++unittest_failures;
  3592. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3593. applog(LOG_ERR, "%s", printbuf);
  3594. }
  3595. saved = width;
  3596. }
  3597. // Hotspot around unit transition boundary in pick_unit
  3598. saved = -1;
  3599. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3600. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3601. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3602. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3603. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3604. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3605. width = utf8_strlen(printbuf);
  3606. if (unlikely((saved != -1) && (width != saved))) {
  3607. ++unittest_failures;
  3608. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3609. applog(LOG_ERR, "%s", printbuf);
  3610. }
  3611. saved = width;
  3612. }
  3613. }
  3614. #ifdef HAVE_CURSES
  3615. static void adj_width(int var, int *length);
  3616. #endif
  3617. #ifdef HAVE_CURSES
  3618. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3619. static
  3620. 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)
  3621. {
  3622. char rejpcbuf[6];
  3623. char bnbuf[6];
  3624. adj_width(accepted, &awidth);
  3625. adj_width(rejected, &rwidth);
  3626. adj_width(stale, &swidth);
  3627. adj_width(hwerrs, &hwwidth);
  3628. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3629. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3630. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3631. cHr, aHr, uHr,
  3632. awidth, accepted,
  3633. rwidth, rejected,
  3634. swidth, stale,
  3635. rejpcbuf,
  3636. hwwidth, hwerrs,
  3637. bnbuf
  3638. );
  3639. }
  3640. static
  3641. const char *pool_proto_str(const struct pool * const pool)
  3642. {
  3643. if (pool->idle)
  3644. return "Dead ";
  3645. if (pool->has_stratum)
  3646. return "Strtm";
  3647. if (pool->lp_url && pool->proto != pool->lp_proto)
  3648. return "Mixed";
  3649. switch (pool->proto)
  3650. {
  3651. case PLP_GETBLOCKTEMPLATE:
  3652. return " GBT ";
  3653. case PLP_GETWORK:
  3654. return "GWork";
  3655. default:
  3656. return "Alive";
  3657. }
  3658. }
  3659. #endif
  3660. static inline
  3661. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3662. {
  3663. if (!(use_unicode && have_unicode_degrees))
  3664. maybe_unicode = false;
  3665. if (temp && *temp > 0.)
  3666. if (maybe_unicode)
  3667. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3668. else
  3669. snprintf(buf, bufsz, "%4.1fC", *temp);
  3670. else
  3671. {
  3672. if (temp)
  3673. snprintf(buf, bufsz, " ");
  3674. if (maybe_unicode)
  3675. tailsprintf(buf, bufsz, " ");
  3676. }
  3677. tailsprintf(buf, bufsz, " | ");
  3678. }
  3679. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3680. {
  3681. #ifndef HAVE_CURSES
  3682. assert(for_curses == false);
  3683. #endif
  3684. struct device_drv *drv = cgpu->drv;
  3685. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3686. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3687. char rejpcbuf[6];
  3688. char bnbuf[6];
  3689. double dev_runtime;
  3690. if (!opt_show_procs)
  3691. cgpu = cgpu->device;
  3692. dev_runtime = cgpu_runtime(cgpu);
  3693. double rolling, mhashes;
  3694. int accepted, rejected, stale;
  3695. double waccepted;
  3696. double wnotaccepted;
  3697. int hwerrs;
  3698. double bad_diff1, good_diff1;
  3699. rolling = mhashes = waccepted = wnotaccepted = 0;
  3700. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3701. {
  3702. struct cgpu_info *slave = cgpu;
  3703. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3704. {
  3705. slave->utility = slave->accepted / dev_runtime * 60;
  3706. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3707. rolling += drv->get_proc_rolling_hashrate ? drv->get_proc_rolling_hashrate(slave) : slave->rolling;
  3708. mhashes += slave->total_mhashes;
  3709. if (opt_weighed_stats)
  3710. {
  3711. accepted += slave->diff_accepted;
  3712. rejected += slave->diff_rejected;
  3713. stale += slave->diff_stale;
  3714. }
  3715. else
  3716. {
  3717. accepted += slave->accepted;
  3718. rejected += slave->rejected;
  3719. stale += slave->stale;
  3720. }
  3721. waccepted += slave->diff_accepted;
  3722. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3723. hwerrs += slave->hw_errors;
  3724. bad_diff1 += slave->bad_diff1;
  3725. good_diff1 += slave->diff1;
  3726. if (opt_show_procs)
  3727. break;
  3728. }
  3729. }
  3730. double wtotal = (waccepted + wnotaccepted);
  3731. multi_format_unit_array2(
  3732. ((char*[]){cHr, aHr, uHr}),
  3733. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3734. true, "h/s", hashrate_style,
  3735. 3,
  3736. 1e6*rolling,
  3737. 1e6*mhashes / dev_runtime,
  3738. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3739. // Processor representation
  3740. #ifdef HAVE_CURSES
  3741. if (for_curses)
  3742. {
  3743. if (opt_show_procs)
  3744. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3745. else
  3746. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3747. }
  3748. else
  3749. #endif
  3750. {
  3751. if (opt_show_procs)
  3752. snprintf(buf, bufsz, "%*s ", -(5 + max_lpdigits), cgpu->proc_repr_ns);
  3753. else
  3754. snprintf(buf, bufsz, "%-5s ", cgpu->dev_repr_ns);
  3755. }
  3756. if (include_serial_in_statline && cgpu->dev_serial)
  3757. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3758. if (unlikely(cgpu->status == LIFE_INIT))
  3759. {
  3760. tailsprintf(buf, bufsz, "Initializing...");
  3761. return;
  3762. }
  3763. {
  3764. const size_t bufln = strlen(buf);
  3765. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3766. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3767. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3768. else
  3769. {
  3770. float temp = cgpu->temp;
  3771. if (!opt_show_procs)
  3772. {
  3773. // Find the highest temperature of all processors
  3774. struct cgpu_info *proc = cgpu;
  3775. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3776. if (proc->temp > temp)
  3777. temp = proc->temp;
  3778. }
  3779. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3780. }
  3781. }
  3782. #ifdef HAVE_CURSES
  3783. if (for_curses)
  3784. {
  3785. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3786. const char *cHrStats;
  3787. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3788. bool all_dead = true, all_off = true, all_rdrv = true;
  3789. struct cgpu_info *proc = cgpu;
  3790. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3791. {
  3792. switch (cHrStatsI) {
  3793. default:
  3794. if (proc->status == LIFE_WAIT)
  3795. cHrStatsI = 5;
  3796. case 5:
  3797. if (proc->deven == DEV_RECOVER_ERR)
  3798. cHrStatsI = 4;
  3799. case 4:
  3800. if (proc->deven == DEV_RECOVER)
  3801. cHrStatsI = 3;
  3802. case 3:
  3803. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3804. {
  3805. cHrStatsI = 1;
  3806. all_off = false;
  3807. }
  3808. else
  3809. {
  3810. if (likely(proc->deven == DEV_ENABLED))
  3811. all_off = false;
  3812. if (proc->deven != DEV_RECOVER_DRV)
  3813. all_rdrv = false;
  3814. }
  3815. case 1:
  3816. break;
  3817. }
  3818. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3819. all_dead = false;
  3820. if (opt_show_procs)
  3821. break;
  3822. }
  3823. if (unlikely(all_dead))
  3824. cHrStatsI = 0;
  3825. else
  3826. if (unlikely(all_off))
  3827. cHrStatsI = 2;
  3828. cHrStats = cHrStatsOpt[cHrStatsI];
  3829. if (cHrStatsI == 2 && all_rdrv)
  3830. cHrStats = " RST ";
  3831. format_statline(buf, bufsz,
  3832. cHrStats,
  3833. aHr, uHr,
  3834. accepted, rejected, stale,
  3835. wnotaccepted, waccepted,
  3836. hwerrs,
  3837. bad_diff1, bad_diff1 + good_diff1);
  3838. }
  3839. else
  3840. #endif
  3841. {
  3842. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3843. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3844. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3845. opt_log_interval,
  3846. cHr, aHr, uHr,
  3847. accepted,
  3848. rejected,
  3849. stale,
  3850. rejpcbuf,
  3851. hwerrs,
  3852. bnbuf
  3853. );
  3854. }
  3855. }
  3856. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3857. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3858. static void text_print_status(int thr_id)
  3859. {
  3860. struct cgpu_info *cgpu;
  3861. char logline[256];
  3862. cgpu = get_thr_cgpu(thr_id);
  3863. if (cgpu) {
  3864. get_statline(logline, sizeof(logline), cgpu);
  3865. printf("\n%s\r", logline);
  3866. fflush(stdout);
  3867. }
  3868. }
  3869. #ifdef HAVE_CURSES
  3870. static int attr_bad = A_BOLD;
  3871. #ifdef WIN32
  3872. #define swprintf snwprintf
  3873. #endif
  3874. static
  3875. void bfg_waddstr(WINDOW *win, const char *s)
  3876. {
  3877. const char *p = s;
  3878. int32_t w;
  3879. int wlen;
  3880. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3881. while (true)
  3882. {
  3883. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3884. {
  3885. // Printable ASCII
  3886. ++p;
  3887. }
  3888. if (p != s)
  3889. waddnstr(win, s, p - s);
  3890. w = utf8_decode(p, &wlen);
  3891. s = p += wlen;
  3892. switch(w)
  3893. {
  3894. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3895. case '\0':
  3896. return;
  3897. case 0xb5: // micro symbol
  3898. w = unicode_micro;
  3899. goto default_addch;
  3900. case 0xf000: // "bad" off
  3901. wattroff(win, attr_bad);
  3902. break;
  3903. case 0xf001: // "bad" on
  3904. wattron(win, attr_bad);
  3905. break;
  3906. #ifdef USE_UNICODE
  3907. case '|':
  3908. wadd_wch(win, WACS_VLINE);
  3909. break;
  3910. #endif
  3911. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3912. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3913. if (!use_unicode)
  3914. {
  3915. waddch(win, '-');
  3916. break;
  3917. }
  3918. #ifdef USE_UNICODE
  3919. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3920. break;
  3921. #endif
  3922. case 0x2022:
  3923. if (w > WCHAR_MAX || !iswprint(w))
  3924. w = '*';
  3925. default:
  3926. default_addch:
  3927. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3928. {
  3929. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3930. if (iswprint(REPLACEMENT_CHAR))
  3931. w = REPLACEMENT_CHAR;
  3932. else
  3933. #endif
  3934. w = '?';
  3935. }
  3936. {
  3937. #ifdef USE_UNICODE
  3938. wchar_t wbuf[0x10];
  3939. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3940. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3941. waddnwstr(win, wbuf, wbuflen);
  3942. #else
  3943. wprintw(win, "%lc", (wint_t)w);
  3944. #endif
  3945. }
  3946. }
  3947. }
  3948. }
  3949. static inline
  3950. void bfg_hline(WINDOW *win, int y)
  3951. {
  3952. int maxx, __maybe_unused maxy;
  3953. getmaxyx(win, maxy, maxx);
  3954. #ifdef USE_UNICODE
  3955. if (use_unicode)
  3956. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3957. else
  3958. #endif
  3959. mvwhline(win, y, 0, '-', maxx);
  3960. }
  3961. static
  3962. int bfg_win_linelen(WINDOW * const win)
  3963. {
  3964. int maxx;
  3965. int __maybe_unused y;
  3966. getmaxyx(win, y, maxx);
  3967. return maxx;
  3968. }
  3969. // Spaces until end of line, using current attributes (ie, not completely clear)
  3970. static
  3971. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3972. {
  3973. int x, maxx;
  3974. int __maybe_unused y;
  3975. getmaxyx(win, y, maxx);
  3976. getyx(win, y, x);
  3977. const int space_count = (maxx - x) - offset;
  3978. // Check for negative - terminal too narrow
  3979. if (space_count <= 0)
  3980. return;
  3981. char buf[space_count];
  3982. memset(buf, ' ', space_count);
  3983. waddnstr(win, buf, space_count);
  3984. }
  3985. static int menu_attr = A_REVERSE;
  3986. #define CURBUFSIZ 256
  3987. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3988. char tmp42[CURBUFSIZ]; \
  3989. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3990. wmove(win, y, x); \
  3991. bfg_waddstr(win, tmp42); \
  3992. } while (0)
  3993. #define cg_wprintw(win, fmt, ...) do { \
  3994. char tmp42[CURBUFSIZ]; \
  3995. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3996. bfg_waddstr(win, tmp42); \
  3997. } while (0)
  3998. static
  3999. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  4000. {
  4001. struct blockchain_info * const blkchain = goal->blkchain;
  4002. struct block_info * const blkinfo = blkchain->currentblk;
  4003. double income;
  4004. char incomestr[ALLOC_H2B_SHORT+6+1];
  4005. if (blkinfo->height)
  4006. {
  4007. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  4008. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  4009. }
  4010. else
  4011. strcpy(incomestr, "?");
  4012. int linelen = bfg_win_linelen(statuswin);
  4013. wmove(statuswin, blky, 0);
  4014. bfg_waddstr(statuswin, " Block");
  4015. if (!goal->is_default)
  4016. linelen -= strlen(goal->name) + 1;
  4017. linelen -= 6; // " Block"
  4018. if (blkinfo->height && blkinfo->height < 1000000)
  4019. {
  4020. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  4021. linelen -= 8;
  4022. }
  4023. bfg_waddstr(statuswin, ":");
  4024. if (linelen > 55)
  4025. bfg_waddstr(statuswin, " ");
  4026. if (linelen >= 65)
  4027. bfg_waddstr(statuswin, "...");
  4028. {
  4029. char hexpbh[0x11];
  4030. if (!(blkinfo->height && blkinfo->height < 1000000))
  4031. {
  4032. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  4033. bfg_waddstr(statuswin, hexpbh);
  4034. }
  4035. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  4036. bfg_waddstr(statuswin, hexpbh);
  4037. }
  4038. if (linelen >= 55)
  4039. bfg_waddstr(statuswin, " ");
  4040. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  4041. if (linelen >= 69)
  4042. bfg_waddstr(statuswin, " ");
  4043. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  4044. if (linelen >= 62)
  4045. {
  4046. if (linelen >= 69)
  4047. bfg_waddstr(statuswin, " ");
  4048. bfg_waddstr(statuswin, "Started:");
  4049. }
  4050. else
  4051. bfg_waddstr(statuswin, "S:");
  4052. if (linelen >= 69)
  4053. bfg_waddstr(statuswin, " ");
  4054. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4055. if (linelen >= 69)
  4056. bfg_waddstr(statuswin, " ");
  4057. cg_wprintw(statuswin, " I:%s", incomestr);
  4058. if (!goal->is_default)
  4059. cg_wprintw(statuswin, " %s", goal->name);
  4060. wclrtoeol(statuswin);
  4061. }
  4062. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4063. static
  4064. void update_block_display(void)
  4065. {
  4066. struct mining_goal_info *goal, *tmpgoal;
  4067. int blky = 3, i, total_found_goals = 0;
  4068. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4069. {
  4070. for (i = 0; i < total_pools; ++i)
  4071. {
  4072. struct pool * const pool = pools[i];
  4073. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4074. break;
  4075. }
  4076. if (i >= total_pools)
  4077. // no pools using this goal, so it's probably stale anyway
  4078. continue;
  4079. update_block_display_line(blky++, goal);
  4080. ++total_found_goals;
  4081. }
  4082. if (total_found_goals != active_goals)
  4083. {
  4084. active_goals = total_found_goals;
  4085. devcursor = 7 + active_goals;
  4086. switch_logsize();
  4087. }
  4088. }
  4089. static bool pool_unworkable(const struct pool *);
  4090. /* Must be called with curses mutex lock held and curses_active */
  4091. static void curses_print_status(const int ts)
  4092. {
  4093. struct pool *pool = currentpool;
  4094. struct timeval now, tv;
  4095. float efficiency;
  4096. int logdiv;
  4097. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4098. wattron(statuswin, attr_title);
  4099. const int linelen = bfg_win_linelen(statuswin);
  4100. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(bfgminer_ver) + 3 + 21 + 3 + 19;
  4101. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4102. if (titlelen + 17 < linelen)
  4103. cg_wprintw(statuswin, "version ");
  4104. cg_wprintw(statuswin, "%s - ", bfgminer_ver);
  4105. if (titlelen + 9 < linelen)
  4106. cg_wprintw(statuswin, "Started: ");
  4107. else
  4108. if (titlelen + 7 <= linelen)
  4109. cg_wprintw(statuswin, "Start: ");
  4110. cg_wprintw(statuswin, "%s", datestamp);
  4111. timer_set_now(&now);
  4112. {
  4113. unsigned int days, hours;
  4114. div_t d;
  4115. timersub(&now, &miner_started, &tv);
  4116. d = div(tv.tv_sec, 86400);
  4117. days = d.quot;
  4118. d = div(d.rem, 3600);
  4119. hours = d.quot;
  4120. d = div(d.rem, 60);
  4121. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4122. , days
  4123. , (days == 1) ? ' ' : 's'
  4124. , hours
  4125. , d.quot
  4126. , d.rem
  4127. );
  4128. }
  4129. bfg_wspctoeol(statuswin, 0);
  4130. wattroff(statuswin, attr_title);
  4131. wattron(statuswin, menu_attr);
  4132. wmove(statuswin, 1, 0);
  4133. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4134. bfg_wspctoeol(statuswin, 14);
  4135. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4136. wattroff(statuswin, menu_attr);
  4137. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4138. char poolinfo[20], poolinfo2[20];
  4139. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4140. double lowdiff = DBL_MAX, highdiff = -1;
  4141. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4142. time_t oldest_work_restart = time(NULL) + 1;
  4143. struct pool *oldest_work_restart_pool = pools[0];
  4144. for (int i = 0; i < total_pools; ++i)
  4145. {
  4146. if (pool_unworkable(pools[i]))
  4147. continue;
  4148. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4149. pool = pools[i];
  4150. ++workable_pools;
  4151. if (poolinfooff < sizeof(poolinfo))
  4152. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4153. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4154. if (pool_stats->last_diff < lowdiff)
  4155. {
  4156. lowdiff = pool_stats->last_diff;
  4157. lowdiff_pool = pool;
  4158. }
  4159. if (pool_stats->last_diff > highdiff)
  4160. {
  4161. highdiff = pool_stats->last_diff;
  4162. highdiff_pool = pool;
  4163. }
  4164. if (oldest_work_restart >= pool->work_restart_time)
  4165. {
  4166. oldest_work_restart = pool->work_restart_time;
  4167. oldest_work_restart_pool = pool;
  4168. }
  4169. }
  4170. if (unlikely(!workable_pools))
  4171. goto no_workable_pools;
  4172. if (workable_pools == 1)
  4173. goto one_workable_pool;
  4174. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4175. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4176. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4177. else
  4178. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4179. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4180. poolinfo2,
  4181. lowdiff_pool->diff,
  4182. (lowdiff == highdiff) ? "" : "-",
  4183. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4184. pool->goal->have_longpoll ? '+' : '-',
  4185. oldest_work_restart_pool->work_restart_timestamp);
  4186. }
  4187. else
  4188. if (pool_unworkable(pool))
  4189. {
  4190. no_workable_pools: ;
  4191. wattron(statuswin, attr_bad);
  4192. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4193. wattroff(statuswin, attr_bad);
  4194. }
  4195. else
  4196. {
  4197. one_workable_pool: ;
  4198. char pooladdr[19];
  4199. {
  4200. const char *rawaddr = pool->sockaddr_url;
  4201. BFGINIT(rawaddr, pool->rpc_url);
  4202. size_t pooladdrlen = strlen(rawaddr);
  4203. if (pooladdrlen > 20)
  4204. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4205. else
  4206. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4207. }
  4208. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4209. pool->pool_no, pooladdr, pool->diff,
  4210. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4211. pool->work_restart_timestamp,
  4212. pool->rpc_user);
  4213. }
  4214. wclrtoeol(statuswin);
  4215. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4216. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4217. ts,
  4218. total_go + total_ro,
  4219. new_blocks,
  4220. total_submitting,
  4221. multi_format_unit2(bwstr, sizeof(bwstr),
  4222. false, "B/s", H2B_SHORT, "/", 2,
  4223. (float)(total_bytes_rcvd / total_secs),
  4224. (float)(total_bytes_sent / total_secs)),
  4225. efficiency,
  4226. best_share);
  4227. wclrtoeol(statuswin);
  4228. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4229. bfg_waddstr(statuswin, statusline);
  4230. wclrtoeol(statuswin);
  4231. int devdiv = devcursor - 2;
  4232. logdiv = statusy - 1;
  4233. bfg_hline(statuswin, devdiv);
  4234. bfg_hline(statuswin, logdiv);
  4235. #ifdef USE_UNICODE
  4236. if (use_unicode)
  4237. {
  4238. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4239. if (opt_show_procs && !opt_compact)
  4240. offset += max_lpdigits; // proc letter(s)
  4241. if (have_unicode_degrees)
  4242. ++offset; // degrees symbol
  4243. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4244. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4245. offset += 24; // hashrates etc
  4246. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4247. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4248. }
  4249. #endif
  4250. }
  4251. static void adj_width(int var, int *length)
  4252. {
  4253. if ((int)(log10(var) + 1) > *length)
  4254. (*length)++;
  4255. }
  4256. static int dev_width;
  4257. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4258. {
  4259. char logline[256];
  4260. int ypos;
  4261. if (opt_compact)
  4262. return;
  4263. /* Check this isn't out of the window size */
  4264. if (opt_show_procs)
  4265. ypos = cgpu->cgminer_id;
  4266. else
  4267. {
  4268. if (cgpu->proc_id)
  4269. return;
  4270. ypos = cgpu->device_line_id;
  4271. }
  4272. ypos += devsummaryYOffset;
  4273. if (ypos < 0)
  4274. return;
  4275. ypos += devcursor - 1;
  4276. if (ypos >= statusy - 1)
  4277. return;
  4278. if (wmove(statuswin, ypos, 0) == ERR)
  4279. return;
  4280. get_statline2(logline, sizeof(logline), cgpu, true);
  4281. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4282. wattron(statuswin, A_REVERSE);
  4283. bfg_waddstr(statuswin, logline);
  4284. wattroff(statuswin, A_REVERSE);
  4285. wclrtoeol(statuswin);
  4286. }
  4287. static
  4288. void _refresh_devstatus(const bool already_have_lock) {
  4289. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4290. int i;
  4291. if (unlikely(!total_devices))
  4292. {
  4293. const int ypos = devcursor - 1;
  4294. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4295. {
  4296. wattron(statuswin, attr_bad);
  4297. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4298. wclrtoeol(statuswin);
  4299. wattroff(statuswin, attr_bad);
  4300. }
  4301. }
  4302. for (i = 0; i < total_devices; i++)
  4303. curses_print_devstatus(get_devices(i));
  4304. touchwin(statuswin);
  4305. wrefresh(statuswin);
  4306. if (!already_have_lock)
  4307. unlock_curses();
  4308. }
  4309. }
  4310. #define refresh_devstatus() _refresh_devstatus(false)
  4311. #endif
  4312. static void print_status(int thr_id)
  4313. {
  4314. if (!curses_active)
  4315. text_print_status(thr_id);
  4316. }
  4317. #ifdef HAVE_CURSES
  4318. static
  4319. bool set_statusy(int maxy)
  4320. {
  4321. if (loginput_size)
  4322. {
  4323. maxy -= loginput_size;
  4324. if (maxy < 0)
  4325. maxy = 0;
  4326. }
  4327. if (logstart < maxy)
  4328. maxy = logstart;
  4329. if (statusy == maxy)
  4330. return false;
  4331. statusy = maxy;
  4332. logcursor = statusy;
  4333. return true;
  4334. }
  4335. /* Check for window resize. Called with curses mutex locked */
  4336. static inline void change_logwinsize(void)
  4337. {
  4338. int x, y, logx, logy;
  4339. getmaxyx(mainwin, y, x);
  4340. if (x < 80 || y < 25)
  4341. return;
  4342. if (y > statusy + 2 && statusy < logstart) {
  4343. set_statusy(y - 2);
  4344. mvwin(logwin, logcursor, 0);
  4345. bfg_wresize(statuswin, statusy, x);
  4346. }
  4347. y -= logcursor;
  4348. getmaxyx(logwin, logy, logx);
  4349. /* Detect screen size change */
  4350. if (x != logx || y != logy)
  4351. bfg_wresize(logwin, y, x);
  4352. }
  4353. static void check_winsizes(void)
  4354. {
  4355. if (!use_curses)
  4356. return;
  4357. if (curses_active_locked()) {
  4358. int y, x;
  4359. x = getmaxx(statuswin);
  4360. if (set_statusy(LINES - 2))
  4361. {
  4362. erase();
  4363. bfg_wresize(statuswin, statusy, x);
  4364. getmaxyx(mainwin, y, x);
  4365. y -= logcursor;
  4366. bfg_wresize(logwin, y, x);
  4367. mvwin(logwin, logcursor, 0);
  4368. }
  4369. unlock_curses();
  4370. }
  4371. }
  4372. static int device_line_id_count;
  4373. static void switch_logsize(void)
  4374. {
  4375. if (curses_active_locked()) {
  4376. if (opt_compact) {
  4377. logstart = devcursor - 1;
  4378. logcursor = logstart + 1;
  4379. } else {
  4380. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4381. logstart = devcursor + total_lines;
  4382. logcursor = logstart;
  4383. }
  4384. unlock_curses();
  4385. }
  4386. check_winsizes();
  4387. update_block_display();
  4388. }
  4389. /* For mandatory printing when mutex is already locked */
  4390. void _wlog(const char *str)
  4391. {
  4392. static bool newline;
  4393. size_t end = strlen(str) - 1;
  4394. if (newline)
  4395. bfg_waddstr(logwin, "\n");
  4396. if (str[end] == '\n')
  4397. {
  4398. char *s;
  4399. newline = true;
  4400. s = alloca(end + 1);
  4401. memcpy(s, str, end);
  4402. s[end] = '\0';
  4403. str = s;
  4404. }
  4405. else
  4406. newline = false;
  4407. bfg_waddstr(logwin, str);
  4408. }
  4409. /* Mandatory printing */
  4410. void _wlogprint(const char *str)
  4411. {
  4412. if (curses_active_locked()) {
  4413. _wlog(str);
  4414. unlock_curses();
  4415. }
  4416. }
  4417. #endif
  4418. #ifdef HAVE_CURSES
  4419. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4420. {
  4421. bool high_prio;
  4422. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4423. if (curses_active)
  4424. {
  4425. if (!loginput_size || high_prio) {
  4426. wlog(" %s %s\n", datetime, str);
  4427. if (high_prio) {
  4428. touchwin(logwin);
  4429. wrefresh(logwin);
  4430. }
  4431. }
  4432. return true;
  4433. }
  4434. return false;
  4435. }
  4436. void clear_logwin(void)
  4437. {
  4438. if (curses_active_locked()) {
  4439. wclear(logwin);
  4440. unlock_curses();
  4441. }
  4442. }
  4443. void logwin_update(void)
  4444. {
  4445. if (curses_active_locked()) {
  4446. touchwin(logwin);
  4447. wrefresh(logwin);
  4448. unlock_curses();
  4449. }
  4450. }
  4451. #endif
  4452. void enable_pool(struct pool * const pool)
  4453. {
  4454. if (pool->enabled != POOL_ENABLED) {
  4455. mutex_lock(&lp_lock);
  4456. enabled_pools++;
  4457. pool->enabled = POOL_ENABLED;
  4458. pthread_cond_broadcast(&lp_cond);
  4459. mutex_unlock(&lp_lock);
  4460. if (pool->prio < current_pool()->prio)
  4461. switch_pools(pool);
  4462. }
  4463. }
  4464. void manual_enable_pool(struct pool * const pool)
  4465. {
  4466. pool->failover_only = false;
  4467. BFGINIT(pool->quota, 1);
  4468. enable_pool(pool);
  4469. }
  4470. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4471. {
  4472. if (pool->enabled == POOL_DISABLED)
  4473. /* had been manually disabled before */
  4474. return;
  4475. if (pool->enabled != POOL_ENABLED)
  4476. {
  4477. /* has been programmatically disabled already, just change to the new status directly */
  4478. pool->enabled = enable_status;
  4479. return;
  4480. }
  4481. /* Fall into the lock area */
  4482. mutex_lock(&lp_lock);
  4483. --enabled_pools;
  4484. pool->enabled = enable_status;
  4485. mutex_unlock(&lp_lock);
  4486. if (pool == current_pool())
  4487. switch_pools(NULL);
  4488. }
  4489. static
  4490. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4491. struct cgpu_info *cgpu;
  4492. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4493. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4494. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4495. const double tgtdiff = work->work_difficulty;
  4496. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4497. char where[20];
  4498. cgpu = get_thr_cgpu(work->thr_id);
  4499. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4500. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4501. if (total_pools > 1)
  4502. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4503. else
  4504. where[0] = '\0';
  4505. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4506. disp,
  4507. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4508. cgpu->proc_repr,
  4509. where,
  4510. shrdiffdisp, tgtdiffdisp,
  4511. reason,
  4512. resubmit ? "(resubmit)" : "",
  4513. worktime
  4514. );
  4515. }
  4516. static bool test_work_current(struct work *);
  4517. static void _submit_work_async(struct work *);
  4518. static
  4519. void maybe_local_submit(const struct work *work)
  4520. {
  4521. #if BLKMAKER_VERSION > 3
  4522. if (unlikely(work->block && work->tr))
  4523. {
  4524. // This is a block with a full template (GBT)
  4525. // Regardless of the result, submit to local bitcoind(s) as well
  4526. struct work *work_cp;
  4527. for (int i = 0; i < total_pools; ++i)
  4528. {
  4529. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4530. continue;
  4531. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4532. work_cp = copy_work(work);
  4533. work_cp->pool = pools[i];
  4534. work_cp->do_foreign_submit = true;
  4535. _submit_work_async(work_cp);
  4536. }
  4537. }
  4538. #endif
  4539. }
  4540. static
  4541. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4542. {
  4543. if (json_is_string(res))
  4544. return res;
  4545. if ( (res = json_object_get(val, "reject-reason")) )
  4546. return res;
  4547. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4548. return res;
  4549. return NULL;
  4550. }
  4551. static
  4552. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4553. {
  4554. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4555. return j ? json_string_value(j) : NULL;
  4556. }
  4557. static
  4558. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4559. {
  4560. if (!s)
  4561. {
  4562. if (bufsz)
  4563. buf[0] = '\0';
  4564. return 0;
  4565. }
  4566. int p = snprintf(buf, bufsz, " (%s", s);
  4567. if (p >= bufsz - 1)
  4568. p = bufsz - 2;
  4569. strcpy(&buf[p], ")");
  4570. return p + 1;
  4571. }
  4572. /* Theoretically threads could race when modifying accepted and
  4573. * rejected values but the chance of two submits completing at the
  4574. * same time is zero so there is no point adding extra locking */
  4575. static void
  4576. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4577. /*char *hashshow,*/ bool resubmit, char *worktime)
  4578. {
  4579. struct pool *pool = work->pool;
  4580. struct cgpu_info *cgpu;
  4581. cgpu = get_thr_cgpu(work->thr_id);
  4582. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4583. struct mining_goal_info * const goal = pool->goal;
  4584. mutex_lock(&stats_lock);
  4585. cgpu->accepted++;
  4586. total_accepted++;
  4587. pool->accepted++;
  4588. cgpu->diff_accepted += work->work_difficulty;
  4589. total_diff_accepted += work->work_difficulty;
  4590. pool->diff_accepted += work->work_difficulty;
  4591. goal->diff_accepted += work->work_difficulty;
  4592. mutex_unlock(&stats_lock);
  4593. pool->seq_rejects = 0;
  4594. cgpu->last_share_pool = pool->pool_no;
  4595. cgpu->last_share_pool_time = time(NULL);
  4596. cgpu->last_share_diff = work->work_difficulty;
  4597. pool->last_share_time = cgpu->last_share_pool_time;
  4598. pool->last_share_diff = work->work_difficulty;
  4599. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4600. if (!QUIET) {
  4601. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4602. }
  4603. sharelog("accept", work);
  4604. if (opt_shares && total_diff_accepted >= opt_shares) {
  4605. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4606. kill_work();
  4607. return;
  4608. }
  4609. /* Detect if a pool that has been temporarily disabled for
  4610. * continually rejecting shares has started accepting shares.
  4611. * This will only happen with the work returned from a
  4612. * longpoll */
  4613. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4614. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4615. enable_pool(pool);
  4616. }
  4617. if (unlikely(work->block)) {
  4618. // Force moving on to this new block :)
  4619. struct work fakework;
  4620. memset(&fakework, 0, sizeof(fakework));
  4621. fakework.pool = work->pool;
  4622. // Copy block version, bits, and time from share
  4623. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4624. memcpy(&fakework.data[68], &work->data[68], 8);
  4625. // Set prevblock to winning hash (swap32'd)
  4626. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4627. test_work_current(&fakework);
  4628. }
  4629. }
  4630. else
  4631. if (!hash_target_check(work->hash, work->target))
  4632. {
  4633. // This was submitted despite failing the proper target
  4634. // Quietly ignore the reject
  4635. char reason[32];
  4636. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4637. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4638. } else {
  4639. mutex_lock(&stats_lock);
  4640. cgpu->rejected++;
  4641. total_rejected++;
  4642. pool->rejected++;
  4643. cgpu->diff_rejected += work->work_difficulty;
  4644. total_diff_rejected += work->work_difficulty;
  4645. pool->diff_rejected += work->work_difficulty;
  4646. pool->seq_rejects++;
  4647. mutex_unlock(&stats_lock);
  4648. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4649. if (!QUIET) {
  4650. char disposition[36] = "reject";
  4651. char reason[32];
  4652. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4653. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4654. if (reason[0])
  4655. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4656. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4657. sharelog(disposition, work);
  4658. }
  4659. /* Once we have more than a nominal amount of sequential rejects,
  4660. * at least 10 and more than 3 mins at the current utility,
  4661. * disable the pool because some pool error is likely to have
  4662. * ensued. Do not do this if we know the share just happened to
  4663. * be stale due to networking delays.
  4664. */
  4665. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4666. double utility = total_accepted / total_secs * 60;
  4667. if (pool->seq_rejects > utility * 3) {
  4668. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4669. pool->pool_no, pool->seq_rejects);
  4670. disable_pool(pool, POOL_REJECTING);
  4671. pool->seq_rejects = 0;
  4672. }
  4673. }
  4674. }
  4675. maybe_local_submit(work);
  4676. }
  4677. static char *submit_upstream_work_request(struct work *work)
  4678. {
  4679. char *hexstr = NULL;
  4680. char *s, *sd;
  4681. struct pool *pool = work->pool;
  4682. if (work->tr)
  4683. {
  4684. blktemplate_t * const tmpl = work->tr->tmpl;
  4685. json_t *req;
  4686. unsigned char data[80];
  4687. swap32yes(data, work->data, 80 / 4);
  4688. #if BLKMAKER_VERSION > 3
  4689. if (work->do_foreign_submit)
  4690. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4691. else
  4692. #endif
  4693. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4694. s = json_dumps(req, 0);
  4695. json_decref(req);
  4696. sd = malloc(161);
  4697. bin2hex(sd, data, 80);
  4698. } else {
  4699. /* build hex string */
  4700. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4701. bin2hex(hexstr, work->data, sizeof(work->data));
  4702. /* build JSON-RPC request */
  4703. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4704. s = realloc_strcat(s, hexstr);
  4705. s = realloc_strcat(s, "\" ], \"id\":1}");
  4706. free(hexstr);
  4707. sd = s;
  4708. }
  4709. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4710. if (work->tr)
  4711. free(sd);
  4712. else
  4713. s = realloc_strcat(s, "\n");
  4714. return s;
  4715. }
  4716. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4717. json_t *res, *err;
  4718. bool rc = false;
  4719. int thr_id = work->thr_id;
  4720. struct pool *pool = work->pool;
  4721. struct timeval tv_submit_reply;
  4722. time_t ts_submit_reply;
  4723. char worktime[200] = "";
  4724. cgtime(&tv_submit_reply);
  4725. ts_submit_reply = time(NULL);
  4726. if (unlikely(!val)) {
  4727. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4728. if (!pool_tset(pool, &pool->submit_fail)) {
  4729. total_ro++;
  4730. pool->remotefail_occasions++;
  4731. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4732. }
  4733. goto out;
  4734. } else if (pool_tclear(pool, &pool->submit_fail))
  4735. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4736. res = json_object_get(val, "result");
  4737. err = json_object_get(val, "error");
  4738. if (!QUIET) {
  4739. if (opt_worktime) {
  4740. char workclone[20];
  4741. struct tm _tm;
  4742. struct tm *tm, tm_getwork, tm_submit_reply;
  4743. tm = &_tm;
  4744. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4745. (struct timeval *)&(work->tv_getwork));
  4746. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4747. (struct timeval *)&(work->tv_getwork_reply));
  4748. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4749. (struct timeval *)&(work->tv_work_start));
  4750. double work_to_submit = tdiff(ptv_submit,
  4751. (struct timeval *)&(work->tv_work_found));
  4752. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4753. int diffplaces = 3;
  4754. localtime_r(&work->ts_getwork, tm);
  4755. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4756. localtime_r(&ts_submit_reply, tm);
  4757. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4758. if (work->clone) {
  4759. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4760. tdiff((struct timeval *)&(work->tv_cloned),
  4761. (struct timeval *)&(work->tv_getwork_reply)));
  4762. }
  4763. else
  4764. strcpy(workclone, "O");
  4765. if (work->work_difficulty < 1)
  4766. diffplaces = 6;
  4767. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4768. const uint8_t * const prevblkhash = &work->data[4];
  4769. snprintf(worktime, sizeof(worktime),
  4770. " <-%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",
  4771. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4772. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4773. work->getwork_mode, diffplaces, work->work_difficulty,
  4774. tm_getwork.tm_hour, tm_getwork.tm_min,
  4775. tm_getwork.tm_sec, getwork_time, workclone,
  4776. getwork_to_work, work_time, work_to_submit, submit_time,
  4777. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4778. tm_submit_reply.tm_sec);
  4779. }
  4780. }
  4781. share_result(val, res, err, work, resubmit, worktime);
  4782. if (!opt_realquiet)
  4783. print_status(thr_id);
  4784. if (!want_per_device_stats) {
  4785. char logline[256];
  4786. struct cgpu_info *cgpu;
  4787. cgpu = get_thr_cgpu(thr_id);
  4788. get_statline(logline, sizeof(logline), cgpu);
  4789. applog(LOG_INFO, "%s", logline);
  4790. }
  4791. json_decref(val);
  4792. rc = true;
  4793. out:
  4794. return rc;
  4795. }
  4796. /* Specifies whether we can use this pool for work or not. */
  4797. static bool pool_unworkable(const struct pool * const pool)
  4798. {
  4799. if (pool->idle)
  4800. return true;
  4801. if (pool->enabled != POOL_ENABLED)
  4802. return true;
  4803. if (pool->has_stratum && !pool->stratum_active)
  4804. return true;
  4805. return false;
  4806. }
  4807. static struct pool *priority_pool(int);
  4808. static bool pool_unusable(struct pool *);
  4809. static
  4810. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4811. {
  4812. if (pool->enabled != POOL_ENABLED)
  4813. return false;
  4814. if (pool_strategy == POOL_LOADBALANCE && pool->quota)
  4815. return true;
  4816. if (pool_strategy == POOL_BALANCE && !pool->failover_only)
  4817. return true;
  4818. if (!cp)
  4819. cp = current_pool();
  4820. if (pool == cp)
  4821. return true;
  4822. // If we are the highest priority, workable pool for a given algorithm, we are needed
  4823. struct mining_algorithm * const malgo = pool->goal->malgo;
  4824. for (int i = 0; i < total_pools; ++i)
  4825. {
  4826. struct pool * const other_pool = priority_pool(i);
  4827. if (other_pool == pool)
  4828. return true;
  4829. if (pool_unusable(other_pool))
  4830. continue;
  4831. if (other_pool->goal->malgo == malgo)
  4832. break;
  4833. }
  4834. return false;
  4835. }
  4836. static
  4837. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4838. {
  4839. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4840. }
  4841. static
  4842. bool pool_supports_block_change_notification(struct pool * const pool)
  4843. {
  4844. return pool->has_stratum || pool->lp_url;
  4845. }
  4846. static
  4847. bool pool_has_active_block_change_notification(struct pool * const pool)
  4848. {
  4849. return pool->stratum_active || pool->lp_active;
  4850. }
  4851. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4852. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4853. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4854. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4855. * rolling average per 10 minutes and if pools start getting more, it biases
  4856. * away from them to distribute work evenly. The share count is reset to the
  4857. * rolling average every 10 minutes to not send all work to one pool after it
  4858. * has been disabled/out for an extended period. */
  4859. static
  4860. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4861. {
  4862. int i, lowest = cp->shares;
  4863. struct pool *ret = cp, *failover_pool = NULL;
  4864. for (i = 0; i < total_pools; i++) {
  4865. struct pool *pool = pools[i];
  4866. if (malgo && pool->goal->malgo != malgo)
  4867. continue;
  4868. if (pool_unworkable(pool))
  4869. continue;
  4870. if (pool->failover_only)
  4871. {
  4872. BFGINIT(failover_pool, pool);
  4873. continue;
  4874. }
  4875. if (pool->shares < lowest) {
  4876. lowest = pool->shares;
  4877. ret = pool;
  4878. }
  4879. }
  4880. if (malgo && ret->goal->malgo != malgo)
  4881. // Yes, we want failover_pool even if it's NULL
  4882. ret = failover_pool;
  4883. else
  4884. if (pool_unworkable(ret) && failover_pool)
  4885. ret = failover_pool;
  4886. if (ret)
  4887. ++ret->shares;
  4888. return ret;
  4889. }
  4890. static
  4891. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4892. {
  4893. static int rotating_pool = 0;
  4894. struct pool *pool;
  4895. bool avail = false;
  4896. int tested, i, rpsave;
  4897. for (i = 0; i < total_pools; i++) {
  4898. struct pool *tp = pools[i];
  4899. if (tp->quota_used < tp->quota_gcd) {
  4900. avail = true;
  4901. break;
  4902. }
  4903. }
  4904. /* There are no pools with quota, so reset them. */
  4905. if (!avail) {
  4906. for (i = 0; i < total_pools; i++)
  4907. {
  4908. struct pool * const tp = pools[i];
  4909. tp->quota_used -= tp->quota_gcd;
  4910. }
  4911. if (++rotating_pool >= total_pools)
  4912. rotating_pool = 0;
  4913. }
  4914. /* Try to find the first pool in the rotation that is usable */
  4915. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4916. struct pool *pool_lowest = NULL;
  4917. int lowest = INT_MAX;
  4918. rpsave = rotating_pool;
  4919. for (tested = 0; tested < total_pools; ++tested)
  4920. {
  4921. pool = pools[rotating_pool];
  4922. if (malgo && pool->goal->malgo != malgo)
  4923. goto continue_tested;
  4924. if (pool->quota_used < pool->quota_gcd)
  4925. {
  4926. ++pool->quota_used;
  4927. if (!pool_unworkable(pool))
  4928. goto out;
  4929. /* Failover-only flag for load-balance means distribute
  4930. * unused quota to priority pool 0. */
  4931. if (opt_fail_only)
  4932. priority_pool(0)->quota_used--;
  4933. }
  4934. if (malgo)
  4935. {
  4936. const int count = pool->quota_used / pool->quota_gcd;
  4937. if (count < lowest)
  4938. {
  4939. pool_lowest = pool;
  4940. lowest = count;
  4941. }
  4942. }
  4943. continue_tested: ;
  4944. if (++rotating_pool >= total_pools)
  4945. rotating_pool = 0;
  4946. }
  4947. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4948. // Note it isn't possible to get here if !malgo
  4949. pool = pool_lowest;
  4950. out: ;
  4951. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4952. if (malgo)
  4953. rotating_pool = rpsave;
  4954. return pool;
  4955. }
  4956. static
  4957. struct pool *select_failover(struct mining_algorithm * const malgo)
  4958. {
  4959. int i;
  4960. for (i = 0; i < total_pools; i++) {
  4961. struct pool *tp = priority_pool(i);
  4962. if (malgo && tp->goal->malgo != malgo)
  4963. continue;
  4964. if (!pool_unusable(tp)) {
  4965. return tp;
  4966. }
  4967. }
  4968. return NULL;
  4969. }
  4970. static bool pool_active(struct pool *, bool pinging);
  4971. static void pool_died(struct pool *);
  4972. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4973. * it has any quota left. */
  4974. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  4975. {
  4976. struct pool *pool = NULL, *cp;
  4977. retry:
  4978. cp = current_pool();
  4979. if (pool_strategy == POOL_BALANCE) {
  4980. pool = select_balanced(cp, malgo);
  4981. if ((!pool) || pool_unworkable(pool))
  4982. goto simple_failover;
  4983. goto out;
  4984. }
  4985. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4986. if (malgo && cp->goal->malgo != malgo)
  4987. goto simple_failover;
  4988. pool = cp;
  4989. goto out;
  4990. } else
  4991. pool = select_loadbalance(malgo);
  4992. simple_failover:
  4993. /* If there are no alive pools with quota, choose according to
  4994. * priority. */
  4995. if (!pool) {
  4996. pool = select_failover(malgo);
  4997. }
  4998. /* If still nothing is usable, use the current pool */
  4999. if (!pool)
  5000. {
  5001. if (malgo && cp->goal->malgo != malgo)
  5002. {
  5003. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm '%s'", malgo->name);
  5004. return NULL;
  5005. }
  5006. pool = cp;
  5007. }
  5008. out:
  5009. if (!pool_actively_in_use(pool, cp))
  5010. {
  5011. if (!pool_active(pool, false))
  5012. {
  5013. pool_died(pool);
  5014. goto retry;
  5015. }
  5016. pool_tclear(pool, &pool->idle);
  5017. }
  5018. applog(LOG_DEBUG, "Selecting pool %d for %s%swork", pool->pool_no, malgo ? malgo->name : "", malgo ? " " : "");
  5019. return pool;
  5020. }
  5021. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  5022. double target_diff(const unsigned char *target)
  5023. {
  5024. double targ = 0;
  5025. signed int i;
  5026. for (i = 31; i >= 0; --i)
  5027. targ = (targ * 0x100) + target[i];
  5028. return DIFFEXACTONE / (targ ?: 1);
  5029. }
  5030. /*
  5031. * Calculate the work share difficulty
  5032. */
  5033. static void calc_diff(struct work *work, int known)
  5034. {
  5035. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  5036. double difficulty;
  5037. if (!known) {
  5038. work->work_difficulty = target_diff(work->target);
  5039. } else
  5040. work->work_difficulty = known;
  5041. difficulty = work->work_difficulty;
  5042. pool_stats->last_diff = difficulty;
  5043. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  5044. if (difficulty == pool_stats->min_diff)
  5045. pool_stats->min_diff_count++;
  5046. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  5047. pool_stats->min_diff = difficulty;
  5048. pool_stats->min_diff_count = 1;
  5049. }
  5050. if (difficulty == pool_stats->max_diff)
  5051. pool_stats->max_diff_count++;
  5052. else if (difficulty > pool_stats->max_diff) {
  5053. pool_stats->max_diff = difficulty;
  5054. pool_stats->max_diff_count = 1;
  5055. }
  5056. }
  5057. static void gen_stratum_work(struct pool *, struct work *);
  5058. static void pool_update_work_restart_time(struct pool *);
  5059. static void restart_threads(void);
  5060. static uint32_t benchmark_blkhdr[20];
  5061. static const int benchmark_update_interval = 1;
  5062. static
  5063. void *benchmark_intense_work_update_thread(void *userp)
  5064. {
  5065. pthread_detach(pthread_self());
  5066. RenameThread("benchmark-intense");
  5067. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5068. struct pool * const pool = userp;
  5069. struct stratum_work * const swork = &pool->swork;
  5070. uint8_t * const blkhdr = swork->header1;
  5071. while (true)
  5072. {
  5073. sleep(benchmark_update_interval);
  5074. cg_wlock(&pool->data_lock);
  5075. for (int i = 36; --i >= 0; )
  5076. if (++blkhdr[i])
  5077. break;
  5078. cg_wunlock(&pool->data_lock);
  5079. struct work *work = make_work();
  5080. gen_stratum_work(pool, work);
  5081. pool->swork.work_restart_id = ++pool->work_restart_id;
  5082. pool_update_work_restart_time(pool);
  5083. test_work_current(work);
  5084. free_work(work);
  5085. restart_threads();
  5086. }
  5087. return NULL;
  5088. }
  5089. static
  5090. void setup_benchmark_pool()
  5091. {
  5092. struct pool *pool;
  5093. want_longpoll = false;
  5094. // Temporarily disable opt_benchmark to avoid auto-removal
  5095. opt_benchmark = false;
  5096. pool = add_pool();
  5097. opt_benchmark = true;
  5098. pool->rpc_url = malloc(255);
  5099. strcpy(pool->rpc_url, "Benchmark");
  5100. pool_set_uri(pool, pool->rpc_url);
  5101. pool->rpc_user = pool->rpc_url;
  5102. pool->rpc_pass = pool->rpc_url;
  5103. enable_pool(pool);
  5104. pool->idle = false;
  5105. successful_connect = true;
  5106. {
  5107. uint32_t * const blkhdr = benchmark_blkhdr;
  5108. blkhdr[2] = htobe32(1);
  5109. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5110. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5111. }
  5112. {
  5113. struct stratum_work * const swork = &pool->swork;
  5114. const int branchcount = 15; // 1 MB block
  5115. const size_t branchdatasz = branchcount * 0x20;
  5116. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5117. bytes_resize(&swork->coinbase, coinbase_sz);
  5118. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5119. swork->nonce2_offset = 0;
  5120. bytes_resize(&swork->merkle_bin, branchdatasz);
  5121. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5122. swork->merkles = branchcount;
  5123. swork->header1[0] = '\xff';
  5124. memset(&swork->header1[1], '\0', 34);
  5125. swork->header1[35] = '\x01';
  5126. swork->ntime = 0x7fffffff;
  5127. timer_unset(&swork->tv_received);
  5128. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5129. const struct mining_goal_info * const goal = get_mining_goal("default");
  5130. const struct mining_algorithm * const malgo = goal->malgo;
  5131. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5132. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5133. pool->nonce2 = 0;
  5134. }
  5135. if (opt_benchmark_intense)
  5136. {
  5137. pthread_t pth;
  5138. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5139. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5140. }
  5141. }
  5142. void get_benchmark_work(struct work *work, bool use_swork)
  5143. {
  5144. if (use_swork)
  5145. {
  5146. struct timeval tv_now;
  5147. timer_set_now(&tv_now);
  5148. gen_stratum_work(pools[0], work);
  5149. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5150. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5151. return;
  5152. }
  5153. struct pool * const pool = pools[0];
  5154. uint32_t * const blkhdr = benchmark_blkhdr;
  5155. for (int i = 16; i >= 0; --i)
  5156. if (++blkhdr[i])
  5157. break;
  5158. memcpy(&work->data[ 0], blkhdr, 80);
  5159. memcpy(&work->data[80], workpadding_bin, 48);
  5160. char hex[161];
  5161. bin2hex(hex, work->data, 80);
  5162. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5163. calc_midstate(work);
  5164. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5165. work->mandatory = true;
  5166. work->pool = pools[0];
  5167. cgtime(&work->tv_getwork);
  5168. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5169. copy_time(&work->tv_staged, &work->tv_getwork);
  5170. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5171. calc_diff(work, 0);
  5172. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5173. }
  5174. static void wake_gws(void);
  5175. static void update_last_work(struct work *work)
  5176. {
  5177. if (!work->tr)
  5178. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5179. return;
  5180. struct pool *pool = work->pool;
  5181. mutex_lock(&pool->last_work_lock);
  5182. if (pool->last_work_copy)
  5183. free_work(pool->last_work_copy);
  5184. pool->last_work_copy = copy_work(work);
  5185. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5186. mutex_unlock(&pool->last_work_lock);
  5187. }
  5188. static
  5189. void gbt_req_target(json_t *req)
  5190. {
  5191. json_t *j;
  5192. json_t *n;
  5193. if (!request_target_str)
  5194. return;
  5195. j = json_object_get(req, "params");
  5196. if (!j)
  5197. {
  5198. n = json_array();
  5199. if (!n)
  5200. return;
  5201. if (json_object_set_new(req, "params", n))
  5202. goto erradd;
  5203. j = n;
  5204. }
  5205. n = json_array_get(j, 0);
  5206. if (!n)
  5207. {
  5208. n = json_object();
  5209. if (!n)
  5210. return;
  5211. if (json_array_append_new(j, n))
  5212. goto erradd;
  5213. }
  5214. j = n;
  5215. n = json_string(request_target_str);
  5216. if (!n)
  5217. return;
  5218. if (json_object_set_new(j, "target", n))
  5219. goto erradd;
  5220. return;
  5221. erradd:
  5222. json_decref(n);
  5223. }
  5224. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5225. {
  5226. char *rpc_req;
  5227. clean_work(work);
  5228. switch (proto) {
  5229. case PLP_GETWORK:
  5230. work->getwork_mode = GETWORK_MODE_POOL;
  5231. return strdup(getwork_req);
  5232. case PLP_GETBLOCKTEMPLATE:
  5233. work->getwork_mode = GETWORK_MODE_GBT;
  5234. blktemplate_t * const tmpl = blktmpl_create();
  5235. if (!tmpl)
  5236. goto gbtfail2;
  5237. work->tr = tmpl_makeref(tmpl);
  5238. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5239. if (!caps)
  5240. goto gbtfail;
  5241. caps |= GBT_LONGPOLL;
  5242. #if BLKMAKER_VERSION > 1
  5243. const struct mining_goal_info * const goal = pool->goal;
  5244. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5245. caps |= GBT_CBVALUE;
  5246. #endif
  5247. json_t *req = blktmpl_request_jansson(caps, lpid);
  5248. if (!req)
  5249. goto gbtfail;
  5250. if (probe)
  5251. gbt_req_target(req);
  5252. rpc_req = json_dumps(req, 0);
  5253. if (!rpc_req)
  5254. goto gbtfail;
  5255. json_decref(req);
  5256. return rpc_req;
  5257. default:
  5258. return NULL;
  5259. }
  5260. return NULL;
  5261. gbtfail:
  5262. tmpl_decref(work->tr);
  5263. work->tr = NULL;
  5264. gbtfail2:
  5265. return NULL;
  5266. }
  5267. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5268. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5269. static const char *pool_protocol_name(enum pool_protocol proto)
  5270. {
  5271. switch (proto) {
  5272. case PLP_GETBLOCKTEMPLATE:
  5273. return "getblocktemplate";
  5274. case PLP_GETWORK:
  5275. return "getwork";
  5276. default:
  5277. return "UNKNOWN";
  5278. }
  5279. }
  5280. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5281. {
  5282. switch (proto) {
  5283. case PLP_GETBLOCKTEMPLATE:
  5284. if (want_getwork)
  5285. return PLP_GETWORK;
  5286. default:
  5287. return PLP_NONE;
  5288. }
  5289. }
  5290. static bool get_upstream_work(struct work *work, CURL *curl)
  5291. {
  5292. struct pool *pool = work->pool;
  5293. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5294. struct timeval tv_elapsed;
  5295. json_t *val = NULL;
  5296. bool rc = false;
  5297. char *url;
  5298. enum pool_protocol proto;
  5299. char *rpc_req;
  5300. if (pool->proto == PLP_NONE)
  5301. pool->proto = PLP_GETBLOCKTEMPLATE;
  5302. tryagain:
  5303. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5304. work->pool = pool;
  5305. if (!rpc_req)
  5306. return false;
  5307. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5308. url = pool->rpc_url;
  5309. cgtime(&work->tv_getwork);
  5310. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5311. false, &work->rolltime, pool, false);
  5312. pool_stats->getwork_attempts++;
  5313. free(rpc_req);
  5314. if (likely(val)) {
  5315. rc = work_decode(pool, work, val);
  5316. if (unlikely(!rc))
  5317. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5318. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5319. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5320. pool->proto = proto;
  5321. goto tryagain;
  5322. } else
  5323. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5324. cgtime(&work->tv_getwork_reply);
  5325. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5326. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5327. pool_stats->getwork_wait_rolling /= 1.63;
  5328. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5329. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5330. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5331. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5332. }
  5333. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5334. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5335. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5336. }
  5337. pool_stats->getwork_calls++;
  5338. work->pool = pool;
  5339. work->longpoll = false;
  5340. calc_diff(work, 0);
  5341. total_getworks++;
  5342. pool->getwork_requested++;
  5343. if (rc)
  5344. update_last_work(work);
  5345. if (likely(val))
  5346. json_decref(val);
  5347. return rc;
  5348. }
  5349. #ifdef HAVE_CURSES
  5350. static void disable_curses(void)
  5351. {
  5352. if (curses_active_locked()) {
  5353. use_curses = false;
  5354. curses_active = false;
  5355. leaveok(logwin, false);
  5356. leaveok(statuswin, false);
  5357. leaveok(mainwin, false);
  5358. nocbreak();
  5359. echo();
  5360. delwin(logwin);
  5361. delwin(statuswin);
  5362. delwin(mainwin);
  5363. endwin();
  5364. #ifdef WIN32
  5365. // Move the cursor to after curses output.
  5366. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5367. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5368. COORD coord;
  5369. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5370. coord.X = 0;
  5371. coord.Y = csbi.dwSize.Y - 1;
  5372. SetConsoleCursorPosition(hout, coord);
  5373. }
  5374. #endif
  5375. unlock_curses();
  5376. }
  5377. }
  5378. #endif
  5379. static void __kill_work(void)
  5380. {
  5381. struct cgpu_info *cgpu;
  5382. struct thr_info *thr;
  5383. int i;
  5384. if (!successful_connect)
  5385. return;
  5386. applog(LOG_INFO, "Received kill message");
  5387. shutting_down = true;
  5388. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5389. notifier_wake(submit_waiting_notifier);
  5390. #ifdef USE_LIBMICROHTTPD
  5391. httpsrv_stop();
  5392. #endif
  5393. applog(LOG_DEBUG, "Killing off watchpool thread");
  5394. /* Kill the watchpool thread */
  5395. thr = &control_thr[watchpool_thr_id];
  5396. thr_info_cancel(thr);
  5397. applog(LOG_DEBUG, "Killing off watchdog thread");
  5398. /* Kill the watchdog thread */
  5399. thr = &control_thr[watchdog_thr_id];
  5400. thr_info_cancel(thr);
  5401. applog(LOG_DEBUG, "Shutting down mining threads");
  5402. for (i = 0; i < mining_threads; i++) {
  5403. thr = get_thread(i);
  5404. if (!thr)
  5405. continue;
  5406. cgpu = thr->cgpu;
  5407. if (!cgpu)
  5408. continue;
  5409. if (!cgpu->threads)
  5410. continue;
  5411. cgpu->shutdown = true;
  5412. thr->work_restart = true;
  5413. notifier_wake(thr->notifier);
  5414. notifier_wake(thr->work_restart_notifier);
  5415. }
  5416. sleep(1);
  5417. applog(LOG_DEBUG, "Killing off mining threads");
  5418. /* Kill the mining threads*/
  5419. for (i = 0; i < mining_threads; i++) {
  5420. thr = get_thread(i);
  5421. if (!thr)
  5422. continue;
  5423. cgpu = thr->cgpu;
  5424. if (cgpu->threads)
  5425. {
  5426. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5427. thr_info_cancel(thr);
  5428. }
  5429. cgpu->status = LIFE_DEAD2;
  5430. }
  5431. /* Stop the others */
  5432. applog(LOG_DEBUG, "Killing off API thread");
  5433. thr = &control_thr[api_thr_id];
  5434. thr_info_cancel(thr);
  5435. }
  5436. /* This should be the common exit path */
  5437. void kill_work(void)
  5438. {
  5439. __kill_work();
  5440. quit(0, "Shutdown signal received.");
  5441. }
  5442. static
  5443. #ifdef WIN32
  5444. #ifndef _WIN64
  5445. const
  5446. #endif
  5447. #endif
  5448. char **initial_args;
  5449. void _bfg_clean_up(bool);
  5450. void app_restart(void)
  5451. {
  5452. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5453. __kill_work();
  5454. _bfg_clean_up(true);
  5455. #if defined(unix) || defined(__APPLE__)
  5456. if (forkpid > 0) {
  5457. kill(forkpid, SIGTERM);
  5458. forkpid = 0;
  5459. }
  5460. #endif
  5461. execv(initial_args[0], initial_args);
  5462. applog(LOG_WARNING, "Failed to restart application");
  5463. }
  5464. static void sighandler(int __maybe_unused sig)
  5465. {
  5466. /* Restore signal handlers so we can still quit if kill_work fails */
  5467. sigaction(SIGTERM, &termhandler, NULL);
  5468. sigaction(SIGINT, &inthandler, NULL);
  5469. kill_work();
  5470. }
  5471. static void start_longpoll(void);
  5472. static void stop_longpoll(void);
  5473. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5474. * this pool. */
  5475. static void recruit_curl(struct pool *pool)
  5476. {
  5477. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5478. if (unlikely(!ce))
  5479. quit(1, "Failed to calloc in recruit_curl");
  5480. ce->curl = curl_easy_init();
  5481. if (unlikely(!ce->curl))
  5482. quit(1, "Failed to init in recruit_curl");
  5483. LL_PREPEND(pool->curllist, ce);
  5484. pool->curls++;
  5485. }
  5486. /* Grab an available curl if there is one. If not, then recruit extra curls
  5487. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5488. * and there are already 5 curls in circulation. Limit total number to the
  5489. * number of mining threads per pool as well to prevent blasting a pool during
  5490. * network delays/outages. */
  5491. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5492. {
  5493. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5494. bool recruited = false;
  5495. struct curl_ent *ce;
  5496. mutex_lock(&pool->pool_lock);
  5497. retry:
  5498. if (!pool->curls) {
  5499. recruit_curl(pool);
  5500. recruited = true;
  5501. } else if (!pool->curllist) {
  5502. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5503. if (!blocking) {
  5504. mutex_unlock(&pool->pool_lock);
  5505. return NULL;
  5506. }
  5507. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5508. goto retry;
  5509. } else {
  5510. recruit_curl(pool);
  5511. recruited = true;
  5512. }
  5513. }
  5514. ce = pool->curllist;
  5515. LL_DELETE(pool->curllist, ce);
  5516. mutex_unlock(&pool->pool_lock);
  5517. if (recruited)
  5518. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5519. return ce;
  5520. }
  5521. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5522. {
  5523. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5524. }
  5525. __maybe_unused
  5526. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5527. {
  5528. return pop_curl_entry3(pool, 1);
  5529. }
  5530. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5531. {
  5532. mutex_lock(&pool->pool_lock);
  5533. if (!ce || !ce->curl)
  5534. quithere(1, "Attempted to add NULL");
  5535. LL_PREPEND(pool->curllist, ce);
  5536. cgtime(&ce->tv);
  5537. pthread_cond_broadcast(&pool->cr_cond);
  5538. mutex_unlock(&pool->pool_lock);
  5539. }
  5540. bool stale_work(struct work *work, bool share);
  5541. static inline bool should_roll(struct work *work)
  5542. {
  5543. struct timeval now;
  5544. time_t expiry;
  5545. if (!pool_actively_in_use(work->pool, NULL))
  5546. return false;
  5547. if (stale_work(work, false))
  5548. return false;
  5549. if (work->rolltime > opt_scantime)
  5550. expiry = work->rolltime;
  5551. else
  5552. expiry = opt_scantime;
  5553. expiry = expiry * 2 / 3;
  5554. /* We shouldn't roll if we're unlikely to get one shares' duration
  5555. * work out of doing so */
  5556. cgtime(&now);
  5557. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5558. return false;
  5559. return true;
  5560. }
  5561. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5562. * reject blocks as invalid. */
  5563. static inline bool can_roll(struct work *work)
  5564. {
  5565. if (work->stratum)
  5566. return false;
  5567. if (!(work->pool && !work->clone))
  5568. return false;
  5569. if (work->tr)
  5570. {
  5571. if (stale_work(work, false))
  5572. return false;
  5573. return blkmk_work_left(work->tr->tmpl);
  5574. }
  5575. return (work->rolltime &&
  5576. work->rolls < 7000 && !stale_work(work, false));
  5577. }
  5578. static void roll_work(struct work *work)
  5579. {
  5580. if (work->tr)
  5581. {
  5582. struct timeval tv_now;
  5583. cgtime(&tv_now);
  5584. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5585. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5586. swap32yes(work->data, work->data, 80 / 4);
  5587. calc_midstate(work);
  5588. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5589. } else {
  5590. uint32_t *work_ntime;
  5591. uint32_t ntime;
  5592. work_ntime = (uint32_t *)(work->data + 68);
  5593. ntime = be32toh(*work_ntime);
  5594. ntime++;
  5595. *work_ntime = htobe32(ntime);
  5596. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5597. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5598. }
  5599. local_work++;
  5600. work->rolls++;
  5601. work->blk.nonce = 0;
  5602. /* This is now a different work item so it needs a different ID for the
  5603. * hashtable */
  5604. work->id = total_work++;
  5605. }
  5606. /* Duplicates any dynamically allocated arrays within the work struct to
  5607. * prevent a copied work struct from freeing ram belonging to another struct */
  5608. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5609. {
  5610. int id = work->id;
  5611. clean_work(work);
  5612. memcpy(work, base_work, sizeof(struct work));
  5613. /* Keep the unique new id assigned during make_work to prevent copied
  5614. * work from having the same id. */
  5615. work->id = id;
  5616. if (base_work->job_id)
  5617. work->job_id = strdup(base_work->job_id);
  5618. if (base_work->nonce1)
  5619. work->nonce1 = strdup(base_work->nonce1);
  5620. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5621. if (base_work->tr)
  5622. tmpl_incref(base_work->tr);
  5623. if (noffset)
  5624. {
  5625. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5626. uint32_t ntime = be32toh(*work_ntime);
  5627. ntime += noffset;
  5628. *work_ntime = htobe32(ntime);
  5629. }
  5630. if (work->device_data_dup_func)
  5631. work->device_data = work->device_data_dup_func(work);
  5632. }
  5633. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5634. * for all dynamically allocated arrays within the struct. noffset is used for
  5635. * when a driver has internally rolled the ntime, noffset is a relative value.
  5636. * The macro copy_work() calls this function with an noffset of 0. */
  5637. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5638. {
  5639. struct work *work = make_work();
  5640. _copy_work(work, base_work, noffset);
  5641. return work;
  5642. }
  5643. void __copy_work(struct work *work, const struct work *base_work)
  5644. {
  5645. _copy_work(work, base_work, 0);
  5646. }
  5647. static struct work *make_clone(struct work *work)
  5648. {
  5649. struct work *work_clone = copy_work(work);
  5650. work_clone->clone = true;
  5651. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5652. work_clone->longpoll = false;
  5653. work_clone->mandatory = false;
  5654. /* Make cloned work appear slightly older to bias towards keeping the
  5655. * master work item which can be further rolled */
  5656. work_clone->tv_staged.tv_sec -= 1;
  5657. return work_clone;
  5658. }
  5659. static void stage_work(struct work *work);
  5660. static bool clone_available(void)
  5661. {
  5662. struct work *work_clone = NULL, *work, *tmp;
  5663. bool cloned = false;
  5664. mutex_lock(stgd_lock);
  5665. if (!staged_rollable)
  5666. goto out_unlock;
  5667. HASH_ITER(hh, staged_work, work, tmp) {
  5668. if (can_roll(work) && should_roll(work)) {
  5669. roll_work(work);
  5670. work_clone = make_clone(work);
  5671. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5672. roll_work(work);
  5673. cloned = true;
  5674. break;
  5675. }
  5676. }
  5677. out_unlock:
  5678. mutex_unlock(stgd_lock);
  5679. if (cloned) {
  5680. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5681. stage_work(work_clone);
  5682. }
  5683. return cloned;
  5684. }
  5685. static void pool_died(struct pool *pool)
  5686. {
  5687. mutex_lock(&lp_lock);
  5688. if (!pool_tset(pool, &pool->idle)) {
  5689. cgtime(&pool->tv_idle);
  5690. pthread_cond_broadcast(&lp_cond);
  5691. mutex_unlock(&lp_lock);
  5692. if (pool == current_pool()) {
  5693. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5694. switch_pools(NULL);
  5695. } else
  5696. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5697. }
  5698. else
  5699. mutex_unlock(&lp_lock);
  5700. }
  5701. bool stale_work(struct work *work, bool share)
  5702. {
  5703. unsigned work_expiry;
  5704. struct pool *pool;
  5705. uint32_t block_id;
  5706. unsigned getwork_delay;
  5707. block_id = ((uint32_t*)work->data)[1];
  5708. pool = work->pool;
  5709. struct mining_goal_info * const goal = pool->goal;
  5710. struct blockchain_info * const blkchain = goal->blkchain;
  5711. /* Technically the rolltime should be correct but some pools
  5712. * advertise a broken expire= that is lower than a meaningful
  5713. * scantime */
  5714. if (work->rolltime >= opt_scantime || work->tr)
  5715. work_expiry = work->rolltime;
  5716. else
  5717. work_expiry = opt_expiry;
  5718. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5719. if (work_expiry > max_expiry)
  5720. work_expiry = max_expiry;
  5721. if (share) {
  5722. /* If the share isn't on this pool's latest block, it's stale */
  5723. if (pool->block_id && pool->block_id != block_id)
  5724. {
  5725. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5726. return true;
  5727. }
  5728. /* If the pool doesn't want old shares, then any found in work before
  5729. * the most recent longpoll is stale */
  5730. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5731. {
  5732. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5733. return true;
  5734. }
  5735. } else {
  5736. /* If this work isn't for the latest Bitcoin block, it's stale */
  5737. /* But only care about the current pool if failover-only */
  5738. if (enabled_pools <= 1 || opt_fail_only) {
  5739. if (pool->block_id && block_id != pool->block_id)
  5740. {
  5741. 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);
  5742. return true;
  5743. }
  5744. } else {
  5745. if (block_id != blkchain->currentblk->block_id)
  5746. {
  5747. 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);
  5748. return true;
  5749. }
  5750. }
  5751. /* If the pool has asked us to restart since this work, it's stale */
  5752. if (work->work_restart_id != pool->work_restart_id)
  5753. {
  5754. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5755. return true;
  5756. }
  5757. if (pool->has_stratum && work->job_id) {
  5758. bool same_job;
  5759. if (!pool->stratum_active || !pool->stratum_notify) {
  5760. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5761. return true;
  5762. }
  5763. same_job = true;
  5764. cg_rlock(&pool->data_lock);
  5765. if (strcmp(work->job_id, pool->swork.job_id))
  5766. same_job = false;
  5767. cg_runlock(&pool->data_lock);
  5768. if (!same_job) {
  5769. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5770. return true;
  5771. }
  5772. }
  5773. /* Factor in the average getwork delay of this pool, rounding it up to
  5774. * the nearest second */
  5775. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5776. if (unlikely(work_expiry <= getwork_delay + 5))
  5777. work_expiry = 5;
  5778. else
  5779. work_expiry -= getwork_delay;
  5780. }
  5781. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5782. if (elapsed_since_staged > work_expiry) {
  5783. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5784. return true;
  5785. }
  5786. /* If the user only wants strict failover, any work from a pool other than
  5787. * the current one is always considered stale */
  5788. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5789. {
  5790. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5791. return true;
  5792. }
  5793. return false;
  5794. }
  5795. double share_diff(const struct work *work)
  5796. {
  5797. double ret;
  5798. bool new_best = false;
  5799. ret = target_diff(work->hash);
  5800. cg_wlock(&control_lock);
  5801. if (unlikely(ret > best_diff)) {
  5802. new_best = true;
  5803. best_diff = ret;
  5804. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5805. }
  5806. if (unlikely(ret > work->pool->best_diff))
  5807. work->pool->best_diff = ret;
  5808. cg_wunlock(&control_lock);
  5809. if (unlikely(new_best))
  5810. applog(LOG_INFO, "New best share: %s", best_share);
  5811. return ret;
  5812. }
  5813. static
  5814. void work_check_for_block(struct work * const work)
  5815. {
  5816. struct pool * const pool = work->pool;
  5817. struct mining_goal_info * const goal = pool->goal;
  5818. work->share_diff = share_diff(work);
  5819. if (unlikely(work->share_diff >= goal->current_diff)) {
  5820. work->block = true;
  5821. work->pool->solved++;
  5822. found_blocks++;
  5823. work->mandatory = true;
  5824. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5825. }
  5826. }
  5827. static void submit_discard_share2(const char *reason, struct work *work)
  5828. {
  5829. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5830. sharelog(reason, work);
  5831. mutex_lock(&stats_lock);
  5832. ++total_stale;
  5833. ++cgpu->stale;
  5834. ++(work->pool->stale_shares);
  5835. total_diff_stale += work->work_difficulty;
  5836. cgpu->diff_stale += work->work_difficulty;
  5837. work->pool->diff_stale += work->work_difficulty;
  5838. mutex_unlock(&stats_lock);
  5839. }
  5840. static void submit_discard_share(struct work *work)
  5841. {
  5842. submit_discard_share2("discard", work);
  5843. }
  5844. struct submit_work_state {
  5845. struct work *work;
  5846. bool resubmit;
  5847. struct curl_ent *ce;
  5848. int failures;
  5849. struct timeval tv_staleexpire;
  5850. char *s;
  5851. struct timeval tv_submit;
  5852. struct submit_work_state *next;
  5853. };
  5854. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5855. {
  5856. long *p_timeout_us = userp;
  5857. const long max_ms = LONG_MAX / 1000;
  5858. if (max_ms < timeout_ms)
  5859. timeout_ms = max_ms;
  5860. *p_timeout_us = timeout_ms * 1000;
  5861. return 0;
  5862. }
  5863. static void sws_has_ce(struct submit_work_state *sws)
  5864. {
  5865. struct pool *pool = sws->work->pool;
  5866. sws->s = submit_upstream_work_request(sws->work);
  5867. cgtime(&sws->tv_submit);
  5868. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5869. }
  5870. static struct submit_work_state *begin_submission(struct work *work)
  5871. {
  5872. struct pool *pool;
  5873. struct submit_work_state *sws = NULL;
  5874. pool = work->pool;
  5875. sws = malloc(sizeof(*sws));
  5876. *sws = (struct submit_work_state){
  5877. .work = work,
  5878. };
  5879. work_check_for_block(work);
  5880. if (stale_work(work, true)) {
  5881. work->stale = true;
  5882. if (opt_submit_stale)
  5883. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5884. else if (pool->submit_old)
  5885. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5886. else {
  5887. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5888. submit_discard_share(work);
  5889. goto out;
  5890. }
  5891. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5892. }
  5893. if (work->stratum) {
  5894. char *s;
  5895. s = malloc(1024);
  5896. sws->s = s;
  5897. } else {
  5898. /* submit solution to bitcoin via JSON-RPC */
  5899. sws->ce = pop_curl_entry2(pool, false);
  5900. if (sws->ce) {
  5901. sws_has_ce(sws);
  5902. } else {
  5903. sws->next = pool->sws_waiting_on_curl;
  5904. pool->sws_waiting_on_curl = sws;
  5905. if (sws->next)
  5906. applog(LOG_DEBUG, "submit_thread queuing submission");
  5907. else
  5908. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5909. }
  5910. }
  5911. return sws;
  5912. out:
  5913. free(sws);
  5914. return NULL;
  5915. }
  5916. static bool retry_submission(struct submit_work_state *sws)
  5917. {
  5918. struct work *work = sws->work;
  5919. struct pool *pool = work->pool;
  5920. sws->resubmit = true;
  5921. if ((!work->stale) && stale_work(work, true)) {
  5922. work->stale = true;
  5923. if (opt_submit_stale)
  5924. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5925. else if (pool->submit_old)
  5926. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5927. else {
  5928. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5929. submit_discard_share(work);
  5930. return false;
  5931. }
  5932. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5933. }
  5934. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5935. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5936. submit_discard_share(work);
  5937. return false;
  5938. }
  5939. else if (work->stale) {
  5940. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5941. {
  5942. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5943. submit_discard_share(work);
  5944. return false;
  5945. }
  5946. }
  5947. /* pause, then restart work-request loop */
  5948. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5949. cgtime(&sws->tv_submit);
  5950. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5951. return true;
  5952. }
  5953. static void free_sws(struct submit_work_state *sws)
  5954. {
  5955. free(sws->s);
  5956. free_work(sws->work);
  5957. free(sws);
  5958. }
  5959. static void *submit_work_thread(__maybe_unused void *userdata)
  5960. {
  5961. int wip = 0;
  5962. CURLM *curlm;
  5963. long curlm_timeout_us = -1;
  5964. struct timeval curlm_timer;
  5965. struct submit_work_state *sws, **swsp;
  5966. struct submit_work_state *write_sws = NULL;
  5967. unsigned tsreduce = 0;
  5968. pthread_detach(pthread_self());
  5969. RenameThread("submit_work");
  5970. applog(LOG_DEBUG, "Creating extra submit work thread");
  5971. curlm = curl_multi_init();
  5972. curlm_timeout_us = -1;
  5973. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5974. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5975. fd_set rfds, wfds, efds;
  5976. int maxfd;
  5977. struct timeval tv_timeout, tv_now;
  5978. int n;
  5979. CURLMsg *cm;
  5980. FD_ZERO(&rfds);
  5981. while (1) {
  5982. mutex_lock(&submitting_lock);
  5983. total_submitting -= tsreduce;
  5984. tsreduce = 0;
  5985. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5986. notifier_read(submit_waiting_notifier);
  5987. }
  5988. // Receive any new submissions
  5989. while (submit_waiting) {
  5990. struct work *work = submit_waiting;
  5991. DL_DELETE(submit_waiting, work);
  5992. if ( (sws = begin_submission(work)) ) {
  5993. if (sws->ce)
  5994. curl_multi_add_handle(curlm, sws->ce->curl);
  5995. else if (sws->s) {
  5996. sws->next = write_sws;
  5997. write_sws = sws;
  5998. }
  5999. ++wip;
  6000. }
  6001. else {
  6002. --total_submitting;
  6003. free_work(work);
  6004. }
  6005. }
  6006. if (unlikely(shutting_down && !wip))
  6007. break;
  6008. mutex_unlock(&submitting_lock);
  6009. FD_ZERO(&rfds);
  6010. FD_ZERO(&wfds);
  6011. FD_ZERO(&efds);
  6012. tv_timeout.tv_sec = -1;
  6013. // Setup cURL with select
  6014. // Need to call perform to ensure the timeout gets updated
  6015. curl_multi_perform(curlm, &n);
  6016. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  6017. if (curlm_timeout_us >= 0)
  6018. {
  6019. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  6020. reduce_timeout_to(&tv_timeout, &curlm_timer);
  6021. }
  6022. // Setup waiting stratum submissions with select
  6023. for (sws = write_sws; sws; sws = sws->next)
  6024. {
  6025. struct pool *pool = sws->work->pool;
  6026. int fd = pool->sock;
  6027. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  6028. continue;
  6029. FD_SET(fd, &wfds);
  6030. set_maxfd(&maxfd, fd);
  6031. }
  6032. // Setup "submit waiting" notifier with select
  6033. FD_SET(submit_waiting_notifier[0], &rfds);
  6034. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  6035. // Wait for something interesting to happen :)
  6036. cgtime(&tv_now);
  6037. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  6038. FD_ZERO(&rfds);
  6039. continue;
  6040. }
  6041. // Handle any stratum ready-to-write results
  6042. for (swsp = &write_sws; (sws = *swsp); ) {
  6043. struct work *work = sws->work;
  6044. struct pool *pool = work->pool;
  6045. int fd = pool->sock;
  6046. bool sessionid_match;
  6047. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  6048. next_write_sws:
  6049. // TODO: Check if stale, possibly discard etc
  6050. swsp = &sws->next;
  6051. continue;
  6052. }
  6053. cg_rlock(&pool->data_lock);
  6054. // 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
  6055. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  6056. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  6057. cg_runlock(&pool->data_lock);
  6058. if (!sessionid_match)
  6059. {
  6060. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  6061. submit_discard_share2("disconnect", work);
  6062. ++tsreduce;
  6063. next_write_sws_del:
  6064. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  6065. FD_CLR(fd, &wfds);
  6066. // Delete sws for this submission, since we're done with it
  6067. *swsp = sws->next;
  6068. free_sws(sws);
  6069. --wip;
  6070. continue;
  6071. }
  6072. char *s = sws->s;
  6073. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  6074. int sshare_id;
  6075. uint32_t nonce;
  6076. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6077. char noncehex[9];
  6078. char ntimehex[9];
  6079. sshare->work = copy_work(work);
  6080. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6081. nonce = *((uint32_t *)(work->data + 76));
  6082. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6083. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6084. mutex_lock(&sshare_lock);
  6085. /* Give the stratum share a unique id */
  6086. sshare_id =
  6087. sshare->id = swork_id++;
  6088. HASH_ADD_INT(stratum_shares, id, sshare);
  6089. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6090. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6091. mutex_unlock(&sshare_lock);
  6092. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6093. if (likely(stratum_send(pool, s, strlen(s)))) {
  6094. if (pool_tclear(pool, &pool->submit_fail))
  6095. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6096. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6097. goto next_write_sws_del;
  6098. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6099. // Undo stuff
  6100. mutex_lock(&sshare_lock);
  6101. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6102. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6103. if (sshare)
  6104. HASH_DEL(stratum_shares, sshare);
  6105. mutex_unlock(&sshare_lock);
  6106. if (sshare)
  6107. {
  6108. free_work(sshare->work);
  6109. free(sshare);
  6110. }
  6111. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6112. total_ro++;
  6113. pool->remotefail_occasions++;
  6114. if (!sshare)
  6115. goto next_write_sws_del;
  6116. goto next_write_sws;
  6117. }
  6118. }
  6119. // Handle any cURL activities
  6120. curl_multi_perform(curlm, &n);
  6121. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6122. if (cm->msg == CURLMSG_DONE)
  6123. {
  6124. bool finished;
  6125. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6126. curl_multi_remove_handle(curlm, cm->easy_handle);
  6127. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6128. if (!finished) {
  6129. if (retry_submission(sws))
  6130. curl_multi_add_handle(curlm, sws->ce->curl);
  6131. else
  6132. finished = true;
  6133. }
  6134. if (finished) {
  6135. --wip;
  6136. ++tsreduce;
  6137. struct pool *pool = sws->work->pool;
  6138. if (pool->sws_waiting_on_curl) {
  6139. pool->sws_waiting_on_curl->ce = sws->ce;
  6140. sws_has_ce(pool->sws_waiting_on_curl);
  6141. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6142. curl_multi_add_handle(curlm, sws->ce->curl);
  6143. } else {
  6144. push_curl_entry(sws->ce, sws->work->pool);
  6145. }
  6146. free_sws(sws);
  6147. }
  6148. }
  6149. }
  6150. }
  6151. assert(!write_sws);
  6152. mutex_unlock(&submitting_lock);
  6153. curl_multi_cleanup(curlm);
  6154. applog(LOG_DEBUG, "submit_work thread exiting");
  6155. return NULL;
  6156. }
  6157. /* Find the pool that currently has the highest priority */
  6158. static struct pool *priority_pool(int choice)
  6159. {
  6160. struct pool *ret = NULL;
  6161. int i;
  6162. for (i = 0; i < total_pools; i++) {
  6163. struct pool *pool = pools[i];
  6164. if (pool->prio == choice) {
  6165. ret = pool;
  6166. break;
  6167. }
  6168. }
  6169. if (unlikely(!ret)) {
  6170. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6171. return pools[choice];
  6172. }
  6173. return ret;
  6174. }
  6175. int prioritize_pools(char *param, int *pid)
  6176. {
  6177. char *ptr, *next;
  6178. int i, pr, prio = 0;
  6179. if (total_pools == 0) {
  6180. return MSG_NOPOOL;
  6181. }
  6182. if (param == NULL || *param == '\0') {
  6183. return MSG_MISPID;
  6184. }
  6185. bool pools_changed[total_pools];
  6186. int new_prio[total_pools];
  6187. for (i = 0; i < total_pools; ++i)
  6188. pools_changed[i] = false;
  6189. next = param;
  6190. while (next && *next) {
  6191. ptr = next;
  6192. next = strchr(ptr, ',');
  6193. if (next)
  6194. *(next++) = '\0';
  6195. i = atoi(ptr);
  6196. if (i < 0 || i >= total_pools) {
  6197. *pid = i;
  6198. return MSG_INVPID;
  6199. }
  6200. if (pools_changed[i]) {
  6201. *pid = i;
  6202. return MSG_DUPPID;
  6203. }
  6204. pools_changed[i] = true;
  6205. new_prio[i] = prio++;
  6206. }
  6207. // Only change them if no errors
  6208. for (i = 0; i < total_pools; i++) {
  6209. if (pools_changed[i])
  6210. pools[i]->prio = new_prio[i];
  6211. }
  6212. // In priority order, cycle through the unchanged pools and append them
  6213. for (pr = 0; pr < total_pools; pr++)
  6214. for (i = 0; i < total_pools; i++) {
  6215. if (!pools_changed[i] && pools[i]->prio == pr) {
  6216. pools[i]->prio = prio++;
  6217. pools_changed[i] = true;
  6218. break;
  6219. }
  6220. }
  6221. if (current_pool()->prio)
  6222. switch_pools(NULL);
  6223. return MSG_POOLPRIO;
  6224. }
  6225. void validate_pool_priorities(void)
  6226. {
  6227. // TODO: this should probably do some sort of logging
  6228. int i, j;
  6229. bool used[total_pools];
  6230. bool valid[total_pools];
  6231. for (i = 0; i < total_pools; i++)
  6232. used[i] = valid[i] = false;
  6233. for (i = 0; i < total_pools; i++) {
  6234. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6235. if (!used[pools[i]->prio]) {
  6236. valid[i] = true;
  6237. used[pools[i]->prio] = true;
  6238. }
  6239. }
  6240. }
  6241. for (i = 0; i < total_pools; i++) {
  6242. if (!valid[i]) {
  6243. for (j = 0; j < total_pools; j++) {
  6244. if (!used[j]) {
  6245. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6246. pools[i]->prio = j;
  6247. used[j] = true;
  6248. break;
  6249. }
  6250. }
  6251. }
  6252. }
  6253. }
  6254. static void clear_pool_work(struct pool *pool);
  6255. /* Specifies whether we can switch to this pool or not. */
  6256. static bool pool_unusable(struct pool *pool)
  6257. {
  6258. if (pool->idle)
  6259. return true;
  6260. if (pool->enabled != POOL_ENABLED)
  6261. return true;
  6262. return false;
  6263. }
  6264. void switch_pools(struct pool *selected)
  6265. {
  6266. struct pool *pool, *last_pool, *failover_pool = NULL;
  6267. int i, pool_no, next_pool;
  6268. if (selected)
  6269. enable_pool(selected);
  6270. cg_wlock(&control_lock);
  6271. last_pool = currentpool;
  6272. pool_no = currentpool->pool_no;
  6273. /* Switch selected to pool number 0 and move the rest down */
  6274. if (selected) {
  6275. if (selected->prio != 0) {
  6276. for (i = 0; i < total_pools; i++) {
  6277. pool = pools[i];
  6278. if (pool->prio < selected->prio)
  6279. pool->prio++;
  6280. }
  6281. selected->prio = 0;
  6282. }
  6283. }
  6284. switch (pool_strategy) {
  6285. /* All of these set to the master pool */
  6286. case POOL_BALANCE:
  6287. case POOL_FAILOVER:
  6288. case POOL_LOADBALANCE:
  6289. for (i = 0; i < total_pools; i++) {
  6290. pool = priority_pool(i);
  6291. if (pool_unusable(pool))
  6292. continue;
  6293. pool_no = pool->pool_no;
  6294. break;
  6295. }
  6296. break;
  6297. /* Both of these simply increment and cycle */
  6298. case POOL_ROUNDROBIN:
  6299. case POOL_ROTATE:
  6300. if (selected && !selected->idle) {
  6301. pool_no = selected->pool_no;
  6302. break;
  6303. }
  6304. next_pool = pool_no;
  6305. /* Select the next alive pool */
  6306. for (i = 1; i < total_pools; i++) {
  6307. next_pool++;
  6308. if (next_pool >= total_pools)
  6309. next_pool = 0;
  6310. pool = pools[next_pool];
  6311. if (pool_unusable(pool))
  6312. continue;
  6313. if (pool->failover_only)
  6314. {
  6315. BFGINIT(failover_pool, pool);
  6316. continue;
  6317. }
  6318. pool_no = next_pool;
  6319. break;
  6320. }
  6321. break;
  6322. default:
  6323. break;
  6324. }
  6325. pool = pools[pool_no];
  6326. if (pool_unusable(pool) && failover_pool)
  6327. pool = failover_pool;
  6328. currentpool = pool;
  6329. cg_wunlock(&control_lock);
  6330. mutex_lock(&lp_lock);
  6331. pthread_cond_broadcast(&lp_cond);
  6332. mutex_unlock(&lp_lock);
  6333. /* Set the lagging flag to avoid pool not providing work fast enough
  6334. * messages in failover only mode since we have to get all fresh work
  6335. * as in restart_threads */
  6336. if (opt_fail_only)
  6337. pool_tset(pool, &pool->lagging);
  6338. if (pool != last_pool)
  6339. {
  6340. pool->block_id = 0;
  6341. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6342. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6343. if (pool_localgen(pool) || opt_fail_only)
  6344. clear_pool_work(last_pool);
  6345. }
  6346. }
  6347. mutex_lock(&lp_lock);
  6348. pthread_cond_broadcast(&lp_cond);
  6349. mutex_unlock(&lp_lock);
  6350. #ifdef HAVE_CURSES
  6351. update_block_display();
  6352. #endif
  6353. }
  6354. static void discard_work(struct work *work)
  6355. {
  6356. if (!work->clone && !work->rolls && !work->mined) {
  6357. if (work->pool) {
  6358. work->pool->discarded_work++;
  6359. work->pool->quota_used--;
  6360. work->pool->works--;
  6361. }
  6362. total_discarded++;
  6363. applog(LOG_DEBUG, "Discarded work");
  6364. } else
  6365. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6366. free_work(work);
  6367. }
  6368. static bool work_rollable(struct work *);
  6369. static
  6370. void unstage_work(struct work * const work)
  6371. {
  6372. HASH_DEL(staged_work, work);
  6373. --work_mining_algorithm(work)->staged;
  6374. if (work_rollable(work))
  6375. --staged_rollable;
  6376. if (work->spare)
  6377. --staged_spare;
  6378. staged_full = false;
  6379. }
  6380. static void wake_gws(void)
  6381. {
  6382. mutex_lock(stgd_lock);
  6383. pthread_cond_signal(&gws_cond);
  6384. mutex_unlock(stgd_lock);
  6385. }
  6386. static void discard_stale(void)
  6387. {
  6388. struct work *work, *tmp;
  6389. int stale = 0;
  6390. mutex_lock(stgd_lock);
  6391. HASH_ITER(hh, staged_work, work, tmp) {
  6392. if (stale_work(work, false)) {
  6393. unstage_work(work);
  6394. discard_work(work);
  6395. stale++;
  6396. }
  6397. }
  6398. pthread_cond_signal(&gws_cond);
  6399. mutex_unlock(stgd_lock);
  6400. if (stale)
  6401. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6402. }
  6403. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6404. {
  6405. bool rv;
  6406. struct timeval tv, orig;
  6407. ldiv_t d;
  6408. d = ldiv(ustime, 1000000);
  6409. tv = (struct timeval){
  6410. .tv_sec = d.quot,
  6411. .tv_usec = d.rem,
  6412. };
  6413. orig = work->tv_staged;
  6414. timersub(&orig, &tv, &work->tv_staged);
  6415. rv = stale_work(work, share);
  6416. work->tv_staged = orig;
  6417. return rv;
  6418. }
  6419. static
  6420. void pool_update_work_restart_time(struct pool * const pool)
  6421. {
  6422. pool->work_restart_time = time(NULL);
  6423. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6424. }
  6425. static void restart_threads(void)
  6426. {
  6427. struct pool *cp = current_pool();
  6428. int i;
  6429. struct thr_info *thr;
  6430. /* Artificially set the lagging flag to avoid pool not providing work
  6431. * fast enough messages after every long poll */
  6432. pool_tset(cp, &cp->lagging);
  6433. /* Discard staged work that is now stale */
  6434. discard_stale();
  6435. rd_lock(&mining_thr_lock);
  6436. for (i = 0; i < mining_threads; i++)
  6437. {
  6438. thr = mining_thr[i];
  6439. thr->work_restart = true;
  6440. }
  6441. for (i = 0; i < mining_threads; i++)
  6442. {
  6443. thr = mining_thr[i];
  6444. notifier_wake(thr->work_restart_notifier);
  6445. }
  6446. rd_unlock(&mining_thr_lock);
  6447. }
  6448. void blkhashstr(char *rv, const unsigned char *hash)
  6449. {
  6450. unsigned char hash_swap[32];
  6451. swap256(hash_swap, hash);
  6452. swap32tole(hash_swap, hash_swap, 32 / 4);
  6453. bin2hex(rv, hash_swap, 32);
  6454. }
  6455. static
  6456. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6457. {
  6458. struct blockchain_info * const blkchain = goal->blkchain;
  6459. blkchain->currentblk = blkinfo;
  6460. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6461. cg_wlock(&ch_lock);
  6462. __update_block_title(goal);
  6463. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6464. cg_wunlock(&ch_lock);
  6465. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6466. }
  6467. /* Search to see if this prevblkhash has been seen before */
  6468. static
  6469. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6470. {
  6471. struct block_info *s;
  6472. rd_lock(&blk_lock);
  6473. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6474. rd_unlock(&blk_lock);
  6475. return s;
  6476. }
  6477. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6478. {
  6479. return blocka->block_seen_order - blockb->block_seen_order;
  6480. }
  6481. static
  6482. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6483. {
  6484. unsigned char target[32];
  6485. double diff;
  6486. uint64_t diff64;
  6487. real_block_target(target, work->data);
  6488. diff = target_diff(target);
  6489. diff64 = diff;
  6490. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6491. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6492. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6493. if (unlikely(goal->current_diff != diff))
  6494. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6495. goal->current_diff = diff;
  6496. }
  6497. static bool test_work_current(struct work *work)
  6498. {
  6499. bool ret = true;
  6500. if (work->mandatory)
  6501. return ret;
  6502. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6503. const uint8_t * const prevblkhash = &work->data[4];
  6504. {
  6505. /* Hack to work around dud work sneaking into test */
  6506. bool dudwork = true;
  6507. for (int i = 8; i < 26; ++i)
  6508. if (work->data[i])
  6509. {
  6510. dudwork = false;
  6511. break;
  6512. }
  6513. if (dudwork)
  6514. goto out_free;
  6515. }
  6516. struct pool * const pool = work->pool;
  6517. struct mining_goal_info * const goal = pool->goal;
  6518. struct blockchain_info * const blkchain = goal->blkchain;
  6519. /* Search to see if this block exists yet and if not, consider it a
  6520. * new block and set the current block details to this one */
  6521. if (!block_exists(blkchain, prevblkhash))
  6522. {
  6523. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6524. int deleted_block = 0;
  6525. ret = false;
  6526. if (unlikely(!s))
  6527. quit (1, "test_work_current OOM");
  6528. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6529. s->block_id = block_id;
  6530. s->block_seen_order = new_blocks++;
  6531. s->first_seen_time = time(NULL);
  6532. wr_lock(&blk_lock);
  6533. /* Only keep the last hour's worth of blocks in memory since
  6534. * work from blocks before this is virtually impossible and we
  6535. * want to prevent memory usage from continually rising */
  6536. if (HASH_COUNT(blkchain->blocks) > 6)
  6537. {
  6538. struct block_info *oldblock;
  6539. HASH_SORT(blkchain->blocks, block_sort);
  6540. oldblock = blkchain->blocks;
  6541. deleted_block = oldblock->block_seen_order;
  6542. HASH_DEL(blkchain->blocks, oldblock);
  6543. free(oldblock);
  6544. }
  6545. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6546. set_blockdiff(goal, work);
  6547. wr_unlock(&blk_lock);
  6548. pool->block_id = block_id;
  6549. pool_update_work_restart_time(pool);
  6550. if (deleted_block)
  6551. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6552. #if BLKMAKER_VERSION > 1
  6553. template_nonce = 0;
  6554. #endif
  6555. set_curblock(goal, s);
  6556. if (unlikely(new_blocks == 1))
  6557. goto out_free;
  6558. if (!work->stratum)
  6559. {
  6560. if (work->longpoll)
  6561. {
  6562. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6563. pool->pool_no);
  6564. }
  6565. else
  6566. if (goal->have_longpoll)
  6567. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6568. else
  6569. applog(LOG_NOTICE, "New block detected on network");
  6570. }
  6571. restart_threads();
  6572. }
  6573. else
  6574. {
  6575. bool restart = false;
  6576. if (unlikely(pool->block_id != block_id))
  6577. {
  6578. bool was_active = pool->block_id != 0;
  6579. pool->block_id = block_id;
  6580. pool_update_work_restart_time(pool);
  6581. if (!work->longpoll)
  6582. update_last_work(work);
  6583. if (was_active)
  6584. {
  6585. // Pool actively changed block
  6586. if (pool == current_pool())
  6587. restart = true;
  6588. if (block_id == blkchain->currentblk->block_id)
  6589. {
  6590. // Caught up, only announce if this pool is the one in use
  6591. if (restart)
  6592. applog(LOG_NOTICE, "%s %d caught up to new block",
  6593. work->longpoll ? "Longpoll from pool" : "Pool",
  6594. pool->pool_no);
  6595. }
  6596. else
  6597. {
  6598. // Switched to a block we know, but not the latest... why?
  6599. // This might detect pools trying to double-spend or 51%,
  6600. // but let's not make any accusations until it's had time
  6601. // in the real world.
  6602. char hexstr[65];
  6603. blkhashstr(hexstr, prevblkhash);
  6604. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6605. work->longpoll ? "Longpoll from pool" : "Pool",
  6606. pool->pool_no,
  6607. hexstr);
  6608. }
  6609. }
  6610. }
  6611. if (work->longpoll)
  6612. {
  6613. struct pool * const cp = current_pool();
  6614. ++pool->work_restart_id;
  6615. if (work->tr && work->tr == pool->swork.tr)
  6616. pool->swork.work_restart_id = pool->work_restart_id;
  6617. update_last_work(work);
  6618. pool_update_work_restart_time(pool);
  6619. applog(
  6620. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6621. "Longpoll from pool %d requested work update",
  6622. pool->pool_no);
  6623. if ((!restart) && pool == cp)
  6624. restart = true;
  6625. }
  6626. if (restart)
  6627. restart_threads();
  6628. }
  6629. work->longpoll = false;
  6630. out_free:
  6631. return ret;
  6632. }
  6633. static int tv_sort(struct work *worka, struct work *workb)
  6634. {
  6635. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6636. }
  6637. static bool work_rollable(struct work *work)
  6638. {
  6639. return (!work->clone && work->rolltime);
  6640. }
  6641. static bool hash_push(struct work *work)
  6642. {
  6643. bool rc = true;
  6644. mutex_lock(stgd_lock);
  6645. if (work_rollable(work))
  6646. staged_rollable++;
  6647. ++work_mining_algorithm(work)->staged;
  6648. if (work->spare)
  6649. ++staged_spare;
  6650. if (likely(!getq->frozen)) {
  6651. HASH_ADD_INT(staged_work, id, work);
  6652. HASH_SORT(staged_work, tv_sort);
  6653. } else
  6654. rc = false;
  6655. pthread_cond_broadcast(&getq->cond);
  6656. mutex_unlock(stgd_lock);
  6657. return rc;
  6658. }
  6659. static void stage_work(struct work *work)
  6660. {
  6661. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6662. work->id, work->pool->pool_no);
  6663. work->work_restart_id = work->pool->work_restart_id;
  6664. work->pool->last_work_time = time(NULL);
  6665. cgtime(&work->pool->tv_last_work_time);
  6666. test_work_current(work);
  6667. work->pool->works++;
  6668. hash_push(work);
  6669. }
  6670. #ifdef HAVE_CURSES
  6671. int curses_int(const char *query)
  6672. {
  6673. int ret;
  6674. char *cvar;
  6675. cvar = curses_input(query);
  6676. if (unlikely(!cvar))
  6677. return -1;
  6678. ret = atoi(cvar);
  6679. free(cvar);
  6680. return ret;
  6681. }
  6682. #endif
  6683. #ifdef HAVE_CURSES
  6684. static bool input_pool(bool live);
  6685. #endif
  6686. #ifdef HAVE_CURSES
  6687. static void display_pool_summary(struct pool *pool)
  6688. {
  6689. double efficiency = 0.0;
  6690. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6691. int pool_secs;
  6692. if (curses_active_locked()) {
  6693. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6694. if (pool->solved)
  6695. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6696. if (!pool->has_stratum)
  6697. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6698. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6699. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6700. wlog(" Accepted shares: %d\n", pool->accepted);
  6701. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6702. pool->rejected, pool->stale_shares,
  6703. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6704. );
  6705. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6706. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6707. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6708. wlog(" Network transfer: %s (%s)\n",
  6709. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6710. (float)pool->cgminer_pool_stats.net_bytes_received,
  6711. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6712. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6713. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6714. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6715. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6716. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6717. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6718. wlog(" Items worked on: %d\n", pool->works);
  6719. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6720. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6721. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6722. unlock_curses();
  6723. }
  6724. }
  6725. #endif
  6726. /* We can't remove the memory used for this struct pool because there may
  6727. * still be work referencing it. We just remove it from the pools list */
  6728. void remove_pool(struct pool *pool)
  6729. {
  6730. int i, last_pool = total_pools - 1;
  6731. struct pool *other;
  6732. disable_pool(pool, POOL_DISABLED);
  6733. /* Boost priority of any lower prio than this one */
  6734. for (i = 0; i < total_pools; i++) {
  6735. other = pools[i];
  6736. if (other->prio > pool->prio)
  6737. other->prio--;
  6738. }
  6739. if (pool->pool_no < last_pool) {
  6740. /* Swap the last pool for this one */
  6741. (pools[last_pool])->pool_no = pool->pool_no;
  6742. pools[pool->pool_no] = pools[last_pool];
  6743. }
  6744. /* Give it an invalid number */
  6745. pool->pool_no = total_pools;
  6746. pool->removed = true;
  6747. pool->has_stratum = false;
  6748. total_pools--;
  6749. }
  6750. /* add a mutex if this needs to be thread safe in the future */
  6751. static struct JE {
  6752. char *buf;
  6753. struct JE *next;
  6754. } *jedata = NULL;
  6755. static void json_escape_free()
  6756. {
  6757. struct JE *jeptr = jedata;
  6758. struct JE *jenext;
  6759. jedata = NULL;
  6760. while (jeptr) {
  6761. jenext = jeptr->next;
  6762. free(jeptr->buf);
  6763. free(jeptr);
  6764. jeptr = jenext;
  6765. }
  6766. }
  6767. static
  6768. char *json_escape(const char *str)
  6769. {
  6770. struct JE *jeptr;
  6771. char *buf, *ptr;
  6772. /* 2x is the max, may as well just allocate that */
  6773. ptr = buf = malloc(strlen(str) * 2 + 1);
  6774. jeptr = malloc(sizeof(*jeptr));
  6775. jeptr->buf = buf;
  6776. jeptr->next = jedata;
  6777. jedata = jeptr;
  6778. while (*str) {
  6779. if (*str == '\\' || *str == '"')
  6780. *(ptr++) = '\\';
  6781. *(ptr++) = *(str++);
  6782. }
  6783. *ptr = '\0';
  6784. return buf;
  6785. }
  6786. static
  6787. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6788. {
  6789. if (!elist)
  6790. return;
  6791. static struct string_elist *entry;
  6792. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6793. bool first = true;
  6794. DL_FOREACH(elist, entry)
  6795. {
  6796. const char * const s = entry->string;
  6797. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6798. first = false;
  6799. }
  6800. fprintf(fcfg, "\n]");
  6801. }
  6802. void write_config(FILE *fcfg)
  6803. {
  6804. int i;
  6805. /* Write pool values */
  6806. fputs("{\n\"pools\" : [", fcfg);
  6807. for(i = 0; i < total_pools; i++) {
  6808. struct pool *pool = pools[i];
  6809. if (pool->failover_only)
  6810. // Don't write failover-only (automatically added) pools to the config file for now
  6811. continue;
  6812. if (pool->quota != 1) {
  6813. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6814. pool->quota,
  6815. json_escape(pool->rpc_url));
  6816. } else {
  6817. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6818. json_escape(pool->rpc_url));
  6819. }
  6820. if (pool->rpc_proxy)
  6821. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6822. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6823. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6824. if (strcmp(pool->goal->name, "default"))
  6825. fprintf(fcfg, "\n\t\t\"pool-goal\" : \"%s\",", pool->goal->name);
  6826. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6827. if (pool->force_rollntime)
  6828. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6829. fprintf(fcfg, "\n\t}");
  6830. }
  6831. fputs("\n]\n", fcfg);
  6832. #ifdef USE_OPENCL
  6833. write_config_opencl(fcfg);
  6834. #endif
  6835. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  6836. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6837. #endif
  6838. /* Simple bool and int options */
  6839. struct opt_table *opt;
  6840. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6841. char *p, *name = strdup(opt->names);
  6842. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6843. if (p[1] != '-')
  6844. continue;
  6845. if (opt->type & OPT_NOARG &&
  6846. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6847. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6848. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6849. if (opt->type & OPT_HASARG &&
  6850. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6851. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6852. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6853. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6854. opt->desc != opt_hidden &&
  6855. 0 <= *(int *)opt->u.arg)
  6856. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6857. }
  6858. free(name);
  6859. }
  6860. /* Special case options */
  6861. if (request_target_str)
  6862. {
  6863. if (request_pdiff == (long)request_pdiff)
  6864. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6865. else
  6866. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6867. }
  6868. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6869. if (pool_strategy == POOL_BALANCE)
  6870. fputs(",\n\"balance\" : true", fcfg);
  6871. if (pool_strategy == POOL_LOADBALANCE)
  6872. fputs(",\n\"load-balance\" : true", fcfg);
  6873. if (pool_strategy == POOL_ROUNDROBIN)
  6874. fputs(",\n\"round-robin\" : true", fcfg);
  6875. if (pool_strategy == POOL_ROTATE)
  6876. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6877. #if defined(unix) || defined(__APPLE__)
  6878. if (opt_stderr_cmd && *opt_stderr_cmd)
  6879. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6880. #endif // defined(unix)
  6881. if (opt_kernel_path && *opt_kernel_path) {
  6882. char *kpath = strdup(opt_kernel_path);
  6883. if (kpath[strlen(kpath)-1] == '/')
  6884. kpath[strlen(kpath)-1] = 0;
  6885. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6886. free(kpath);
  6887. }
  6888. if (schedstart.enable)
  6889. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6890. if (schedstop.enable)
  6891. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6892. if (opt_socks_proxy && *opt_socks_proxy)
  6893. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6894. _write_config_string_elist(fcfg, "scan", scan_devices);
  6895. #ifdef USE_LIBMICROHTTPD
  6896. if (httpsrv_port != -1)
  6897. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6898. #endif
  6899. #ifdef USE_LIBEVENT
  6900. if (stratumsrv_port != -1)
  6901. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6902. #endif
  6903. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6904. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6905. if (opt_api_allow)
  6906. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6907. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6908. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6909. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6910. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6911. if (*opt_api_mcast_des)
  6912. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6913. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6914. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6915. if (opt_api_groups)
  6916. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6917. fputs("\n}\n", fcfg);
  6918. json_escape_free();
  6919. }
  6920. void zero_bestshare(void)
  6921. {
  6922. int i;
  6923. best_diff = 0;
  6924. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6925. for (i = 0; i < total_pools; i++) {
  6926. struct pool *pool = pools[i];
  6927. pool->best_diff = 0;
  6928. }
  6929. }
  6930. void zero_stats(void)
  6931. {
  6932. int i;
  6933. applog(LOG_DEBUG, "Zeroing stats");
  6934. cgtime(&total_tv_start);
  6935. miner_started = total_tv_start;
  6936. total_rolling = 0;
  6937. total_mhashes_done = 0;
  6938. total_getworks = 0;
  6939. total_accepted = 0;
  6940. total_rejected = 0;
  6941. hw_errors = 0;
  6942. total_stale = 0;
  6943. total_discarded = 0;
  6944. total_bytes_rcvd = total_bytes_sent = 0;
  6945. new_blocks = 0;
  6946. local_work = 0;
  6947. total_go = 0;
  6948. total_ro = 0;
  6949. total_secs = 1.0;
  6950. total_diff1 = 0;
  6951. total_bad_diff1 = 0;
  6952. found_blocks = 0;
  6953. total_diff_accepted = 0;
  6954. total_diff_rejected = 0;
  6955. total_diff_stale = 0;
  6956. #ifdef HAVE_CURSES
  6957. awidth = rwidth = swidth = hwwidth = 1;
  6958. #endif
  6959. struct mining_goal_info *goal, *tmpgoal;
  6960. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6961. {
  6962. goal->diff_accepted = 0;
  6963. }
  6964. for (i = 0; i < total_pools; i++) {
  6965. struct pool *pool = pools[i];
  6966. pool->getwork_requested = 0;
  6967. pool->accepted = 0;
  6968. pool->rejected = 0;
  6969. pool->solved = 0;
  6970. pool->getwork_requested = 0;
  6971. pool->stale_shares = 0;
  6972. pool->discarded_work = 0;
  6973. pool->getfail_occasions = 0;
  6974. pool->remotefail_occasions = 0;
  6975. pool->last_share_time = 0;
  6976. pool->works = 0;
  6977. pool->diff1 = 0;
  6978. pool->diff_accepted = 0;
  6979. pool->diff_rejected = 0;
  6980. pool->diff_stale = 0;
  6981. pool->last_share_diff = 0;
  6982. pool->cgminer_stats.start_tv = total_tv_start;
  6983. pool->cgminer_stats.getwork_calls = 0;
  6984. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6985. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6986. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6987. pool->cgminer_pool_stats.getwork_calls = 0;
  6988. pool->cgminer_pool_stats.getwork_attempts = 0;
  6989. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6990. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6991. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6992. pool->cgminer_pool_stats.min_diff = 0;
  6993. pool->cgminer_pool_stats.max_diff = 0;
  6994. pool->cgminer_pool_stats.min_diff_count = 0;
  6995. pool->cgminer_pool_stats.max_diff_count = 0;
  6996. pool->cgminer_pool_stats.times_sent = 0;
  6997. pool->cgminer_pool_stats.bytes_sent = 0;
  6998. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6999. pool->cgminer_pool_stats.times_received = 0;
  7000. pool->cgminer_pool_stats.bytes_received = 0;
  7001. pool->cgminer_pool_stats.net_bytes_received = 0;
  7002. }
  7003. zero_bestshare();
  7004. for (i = 0; i < total_devices; ++i) {
  7005. struct cgpu_info *cgpu = get_devices(i);
  7006. mutex_lock(&hash_lock);
  7007. cgpu->total_mhashes = 0;
  7008. cgpu->accepted = 0;
  7009. cgpu->rejected = 0;
  7010. cgpu->stale = 0;
  7011. cgpu->hw_errors = 0;
  7012. cgpu->utility = 0.0;
  7013. cgpu->utility_diff1 = 0;
  7014. cgpu->last_share_pool_time = 0;
  7015. cgpu->bad_diff1 = 0;
  7016. cgpu->diff1 = 0;
  7017. cgpu->diff_accepted = 0;
  7018. cgpu->diff_rejected = 0;
  7019. cgpu->diff_stale = 0;
  7020. cgpu->last_share_diff = 0;
  7021. cgpu->thread_fail_init_count = 0;
  7022. cgpu->thread_zero_hash_count = 0;
  7023. cgpu->thread_fail_queue_count = 0;
  7024. cgpu->dev_sick_idle_60_count = 0;
  7025. cgpu->dev_dead_idle_600_count = 0;
  7026. cgpu->dev_nostart_count = 0;
  7027. cgpu->dev_over_heat_count = 0;
  7028. cgpu->dev_thermal_cutoff_count = 0;
  7029. cgpu->dev_comms_error_count = 0;
  7030. cgpu->dev_throttle_count = 0;
  7031. cgpu->cgminer_stats.start_tv = total_tv_start;
  7032. cgpu->cgminer_stats.getwork_calls = 0;
  7033. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7034. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  7035. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  7036. mutex_unlock(&hash_lock);
  7037. if (cgpu->drv->zero_stats)
  7038. cgpu->drv->zero_stats(cgpu);
  7039. }
  7040. }
  7041. #ifdef HAVE_CURSES
  7042. static
  7043. void loginput_mode(const int size)
  7044. {
  7045. clear_logwin();
  7046. loginput_size = size;
  7047. check_winsizes();
  7048. }
  7049. static void display_pools(void)
  7050. {
  7051. struct pool *pool;
  7052. int selected, i, j;
  7053. char input;
  7054. loginput_mode(7 + total_pools);
  7055. immedok(logwin, true);
  7056. updated:
  7057. for (j = 0; j < total_pools; j++) {
  7058. for (i = 0; i < total_pools; i++) {
  7059. pool = pools[i];
  7060. if (pool->prio != j)
  7061. continue;
  7062. if (pool_actively_in_use(pool, NULL))
  7063. wattron(logwin, A_BOLD);
  7064. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  7065. wattron(logwin, A_DIM);
  7066. wlogprint("%d: ", pool->prio);
  7067. switch (pool->enabled) {
  7068. case POOL_ENABLED:
  7069. if ((pool_strategy == POOL_LOADBALANCE) ? (!pool->quota)
  7070. : ((pool_strategy != POOL_FAILOVER) ? pool->failover_only : 0))
  7071. wlogprint("Failover ");
  7072. else
  7073. wlogprint("Enabled ");
  7074. break;
  7075. case POOL_DISABLED:
  7076. wlogprint("Disabled ");
  7077. break;
  7078. case POOL_REJECTING:
  7079. wlogprint("Rejectin ");
  7080. break;
  7081. case POOL_MISBEHAVING:
  7082. wlogprint("Misbehav ");
  7083. break;
  7084. }
  7085. _wlogprint(pool_proto_str(pool));
  7086. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7087. pool->quota,
  7088. pool->pool_no,
  7089. pool->rpc_url, pool->rpc_user);
  7090. wattroff(logwin, A_BOLD | A_DIM);
  7091. break; //for (i = 0; i < total_pools; i++)
  7092. }
  7093. }
  7094. retry:
  7095. wlogprint("\nCurrent pool management strategy: %s\n",
  7096. strategies[pool_strategy].s);
  7097. if (pool_strategy == POOL_ROTATE)
  7098. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7099. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7100. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7101. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7102. wlogprint("Or press any other key to continue\n");
  7103. logwin_update();
  7104. input = getch();
  7105. if (!strncasecmp(&input, "a", 1)) {
  7106. if (opt_benchmark)
  7107. {
  7108. wlogprint("Cannot add pools in benchmark mode");
  7109. goto retry;
  7110. }
  7111. input_pool(true);
  7112. goto updated;
  7113. } else if (!strncasecmp(&input, "r", 1)) {
  7114. if (total_pools <= 1) {
  7115. wlogprint("Cannot remove last pool");
  7116. goto retry;
  7117. }
  7118. selected = curses_int("Select pool number");
  7119. if (selected < 0 || selected >= total_pools) {
  7120. wlogprint("Invalid selection\n");
  7121. goto retry;
  7122. }
  7123. pool = pools[selected];
  7124. if (pool == current_pool())
  7125. switch_pools(NULL);
  7126. if (pool == current_pool()) {
  7127. wlogprint("Unable to remove pool due to activity\n");
  7128. goto retry;
  7129. }
  7130. remove_pool(pool);
  7131. goto updated;
  7132. } else if (!strncasecmp(&input, "s", 1)) {
  7133. selected = curses_int("Select pool number");
  7134. if (selected < 0 || selected >= total_pools) {
  7135. wlogprint("Invalid selection\n");
  7136. goto retry;
  7137. }
  7138. pool = pools[selected];
  7139. manual_enable_pool(pool);
  7140. switch_pools(pool);
  7141. goto updated;
  7142. } else if (!strncasecmp(&input, "d", 1)) {
  7143. if (enabled_pools <= 1) {
  7144. wlogprint("Cannot disable last pool");
  7145. goto retry;
  7146. }
  7147. selected = curses_int("Select pool number");
  7148. if (selected < 0 || selected >= total_pools) {
  7149. wlogprint("Invalid selection\n");
  7150. goto retry;
  7151. }
  7152. pool = pools[selected];
  7153. disable_pool(pool, POOL_DISABLED);
  7154. goto updated;
  7155. } else if (!strncasecmp(&input, "e", 1)) {
  7156. selected = curses_int("Select pool number");
  7157. if (selected < 0 || selected >= total_pools) {
  7158. wlogprint("Invalid selection\n");
  7159. goto retry;
  7160. }
  7161. pool = pools[selected];
  7162. manual_enable_pool(pool);
  7163. goto updated;
  7164. } else if (!strncasecmp(&input, "c", 1)) {
  7165. for (i = 0; i <= TOP_STRATEGY; i++)
  7166. wlogprint("%d: %s\n", i, strategies[i].s);
  7167. selected = curses_int("Select strategy number type");
  7168. if (selected < 0 || selected > TOP_STRATEGY) {
  7169. wlogprint("Invalid selection\n");
  7170. goto retry;
  7171. }
  7172. if (selected == POOL_ROTATE) {
  7173. opt_rotate_period = curses_int("Select interval in minutes");
  7174. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  7175. opt_rotate_period = 0;
  7176. wlogprint("Invalid selection\n");
  7177. goto retry;
  7178. }
  7179. }
  7180. mutex_lock(&lp_lock);
  7181. pool_strategy = selected;
  7182. pthread_cond_broadcast(&lp_cond);
  7183. mutex_unlock(&lp_lock);
  7184. switch_pools(NULL);
  7185. goto updated;
  7186. } else if (!strncasecmp(&input, "i", 1)) {
  7187. selected = curses_int("Select pool number");
  7188. if (selected < 0 || selected >= total_pools) {
  7189. wlogprint("Invalid selection\n");
  7190. goto retry;
  7191. }
  7192. pool = pools[selected];
  7193. display_pool_summary(pool);
  7194. goto retry;
  7195. } else if (!strncasecmp(&input, "q", 1)) {
  7196. selected = curses_int("Select pool number");
  7197. if (selected < 0 || selected >= total_pools) {
  7198. wlogprint("Invalid selection\n");
  7199. goto retry;
  7200. }
  7201. pool = pools[selected];
  7202. selected = curses_int("Set quota");
  7203. if (selected < 0) {
  7204. wlogprint("Invalid negative quota\n");
  7205. goto retry;
  7206. }
  7207. if (selected > 0)
  7208. pool->failover_only = false;
  7209. pool->quota = selected;
  7210. adjust_quota_gcd();
  7211. goto updated;
  7212. } else if (!strncasecmp(&input, "f", 1)) {
  7213. opt_fail_only ^= true;
  7214. goto updated;
  7215. } else if (!strncasecmp(&input, "p", 1)) {
  7216. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7217. if (!prilist)
  7218. {
  7219. wlogprint("Not changing priorities\n");
  7220. goto retry;
  7221. }
  7222. int res = prioritize_pools(prilist, &i);
  7223. free(prilist);
  7224. switch (res) {
  7225. case MSG_NOPOOL:
  7226. wlogprint("No pools\n");
  7227. goto retry;
  7228. case MSG_MISPID:
  7229. wlogprint("Missing pool id parameter\n");
  7230. goto retry;
  7231. case MSG_INVPID:
  7232. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7233. goto retry;
  7234. case MSG_DUPPID:
  7235. wlogprint("Duplicate pool specified %d\n", i);
  7236. goto retry;
  7237. case MSG_POOLPRIO:
  7238. default:
  7239. goto updated;
  7240. }
  7241. }
  7242. immedok(logwin, false);
  7243. loginput_mode(0);
  7244. }
  7245. static const char *summary_detail_level_str(void)
  7246. {
  7247. if (opt_compact)
  7248. return "compact";
  7249. if (opt_show_procs)
  7250. return "processors";
  7251. return "devices";
  7252. }
  7253. static void display_options(void)
  7254. {
  7255. int selected;
  7256. char input;
  7257. immedok(logwin, true);
  7258. loginput_mode(12);
  7259. retry:
  7260. clear_logwin();
  7261. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7262. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7263. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7264. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7265. opt_debug_console ? "on" : "off",
  7266. want_per_device_stats? "on" : "off",
  7267. opt_quiet ? "on" : "off",
  7268. opt_log_output ? "on" : "off",
  7269. opt_protocol ? "on" : "off",
  7270. opt_worktime ? "on" : "off",
  7271. summary_detail_level_str(),
  7272. opt_log_interval,
  7273. opt_weighed_stats ? "weighed" : "absolute");
  7274. wlogprint("Select an option or any other key to return\n");
  7275. logwin_update();
  7276. input = getch();
  7277. if (!strncasecmp(&input, "q", 1)) {
  7278. opt_quiet ^= true;
  7279. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7280. goto retry;
  7281. } else if (!strncasecmp(&input, "v", 1)) {
  7282. opt_log_output ^= true;
  7283. if (opt_log_output)
  7284. opt_quiet = false;
  7285. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7286. goto retry;
  7287. } else if (!strncasecmp(&input, "n", 1)) {
  7288. opt_log_output = false;
  7289. opt_debug_console = false;
  7290. opt_quiet = false;
  7291. opt_protocol = false;
  7292. opt_compact = false;
  7293. opt_show_procs = false;
  7294. devsummaryYOffset = 0;
  7295. want_per_device_stats = false;
  7296. wlogprint("Output mode reset to normal\n");
  7297. switch_logsize();
  7298. goto retry;
  7299. } else if (!strncasecmp(&input, "d", 1)) {
  7300. opt_debug = true;
  7301. opt_debug_console ^= true;
  7302. opt_log_output = opt_debug_console;
  7303. if (opt_debug_console)
  7304. opt_quiet = false;
  7305. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7306. goto retry;
  7307. } else if (!strncasecmp(&input, "m", 1)) {
  7308. if (opt_compact)
  7309. opt_compact = false;
  7310. else
  7311. if (!opt_show_procs)
  7312. opt_show_procs = true;
  7313. else
  7314. {
  7315. opt_compact = true;
  7316. opt_show_procs = false;
  7317. devsummaryYOffset = 0;
  7318. }
  7319. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7320. switch_logsize();
  7321. goto retry;
  7322. } else if (!strncasecmp(&input, "p", 1)) {
  7323. want_per_device_stats ^= true;
  7324. opt_log_output = want_per_device_stats;
  7325. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7326. goto retry;
  7327. } else if (!strncasecmp(&input, "r", 1)) {
  7328. opt_protocol ^= true;
  7329. if (opt_protocol)
  7330. opt_quiet = false;
  7331. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7332. goto retry;
  7333. } else if (!strncasecmp(&input, "c", 1))
  7334. clear_logwin();
  7335. else if (!strncasecmp(&input, "l", 1)) {
  7336. selected = curses_int("Interval in seconds");
  7337. if (selected < 0 || selected > 9999) {
  7338. wlogprint("Invalid selection\n");
  7339. goto retry;
  7340. }
  7341. opt_log_interval = selected;
  7342. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7343. goto retry;
  7344. } else if (!strncasecmp(&input, "s", 1)) {
  7345. opt_realquiet = true;
  7346. } else if (!strncasecmp(&input, "w", 1)) {
  7347. opt_worktime ^= true;
  7348. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7349. goto retry;
  7350. } else if (!strncasecmp(&input, "t", 1)) {
  7351. opt_weighed_stats ^= true;
  7352. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7353. goto retry;
  7354. } else if (!strncasecmp(&input, "z", 1)) {
  7355. zero_stats();
  7356. goto retry;
  7357. }
  7358. immedok(logwin, false);
  7359. loginput_mode(0);
  7360. }
  7361. #endif
  7362. void default_save_file(char *filename)
  7363. {
  7364. #if defined(unix) || defined(__APPLE__)
  7365. if (getenv("HOME") && *getenv("HOME")) {
  7366. strcpy(filename, getenv("HOME"));
  7367. strcat(filename, "/");
  7368. }
  7369. else
  7370. strcpy(filename, "");
  7371. strcat(filename, ".bfgminer/");
  7372. mkdir(filename, 0777);
  7373. #else
  7374. strcpy(filename, "");
  7375. #endif
  7376. strcat(filename, def_conf);
  7377. }
  7378. #ifdef HAVE_CURSES
  7379. static void set_options(void)
  7380. {
  7381. int selected;
  7382. char input;
  7383. immedok(logwin, true);
  7384. loginput_mode(8);
  7385. retry:
  7386. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7387. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7388. "[W]rite config file\n[B]FGMiner restart\n",
  7389. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7390. wlogprint("Select an option or any other key to return\n");
  7391. logwin_update();
  7392. input = getch();
  7393. if (!strncasecmp(&input, "q", 1)) {
  7394. selected = curses_int("Extra work items to queue");
  7395. if (selected < 0 || selected > 9999) {
  7396. wlogprint("Invalid selection\n");
  7397. goto retry;
  7398. }
  7399. opt_queue = selected;
  7400. goto retry;
  7401. } else if (!strncasecmp(&input, "l", 1)) {
  7402. if (want_longpoll)
  7403. stop_longpoll();
  7404. else
  7405. start_longpoll();
  7406. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7407. goto retry;
  7408. } else if (!strncasecmp(&input, "s", 1)) {
  7409. selected = curses_int("Set scantime in seconds");
  7410. if (selected < 0 || selected > 9999) {
  7411. wlogprint("Invalid selection\n");
  7412. goto retry;
  7413. }
  7414. opt_scantime = selected;
  7415. goto retry;
  7416. } else if (!strncasecmp(&input, "e", 1)) {
  7417. selected = curses_int("Set expiry time in seconds");
  7418. if (selected < 0 || selected > 9999) {
  7419. wlogprint("Invalid selection\n");
  7420. goto retry;
  7421. }
  7422. opt_expiry = selected;
  7423. goto retry;
  7424. } else if (!strncasecmp(&input, "r", 1)) {
  7425. selected = curses_int("Retries before failing (-1 infinite)");
  7426. if (selected < -1 || selected > 9999) {
  7427. wlogprint("Invalid selection\n");
  7428. goto retry;
  7429. }
  7430. opt_retries = selected;
  7431. goto retry;
  7432. } else if (!strncasecmp(&input, "w", 1)) {
  7433. FILE *fcfg;
  7434. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7435. default_save_file(filename);
  7436. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7437. str = curses_input(prompt);
  7438. if (str) {
  7439. struct stat statbuf;
  7440. strcpy(filename, str);
  7441. free(str);
  7442. if (!stat(filename, &statbuf)) {
  7443. wlogprint("File exists, overwrite?\n");
  7444. input = getch();
  7445. if (strncasecmp(&input, "y", 1))
  7446. goto retry;
  7447. }
  7448. }
  7449. fcfg = fopen(filename, "w");
  7450. if (!fcfg) {
  7451. wlogprint("Cannot open or create file\n");
  7452. goto retry;
  7453. }
  7454. write_config(fcfg);
  7455. fclose(fcfg);
  7456. goto retry;
  7457. } else if (!strncasecmp(&input, "b", 1)) {
  7458. wlogprint("Are you sure?\n");
  7459. input = getch();
  7460. if (!strncasecmp(&input, "y", 1))
  7461. app_restart();
  7462. else
  7463. clear_logwin();
  7464. } else
  7465. clear_logwin();
  7466. loginput_mode(0);
  7467. immedok(logwin, false);
  7468. }
  7469. int scan_serial(const char *);
  7470. static
  7471. void _managetui_msg(const char *repr, const char **msg)
  7472. {
  7473. if (*msg)
  7474. {
  7475. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7476. wattron(logwin, A_BOLD);
  7477. wlogprint("%s", *msg);
  7478. wattroff(logwin, A_BOLD);
  7479. *msg = NULL;
  7480. }
  7481. logwin_update();
  7482. }
  7483. void manage_device(void)
  7484. {
  7485. char logline[256];
  7486. const char *msg = NULL;
  7487. struct cgpu_info *cgpu;
  7488. const struct device_drv *drv;
  7489. selecting_device = true;
  7490. immedok(logwin, true);
  7491. loginput_mode(12);
  7492. devchange:
  7493. if (unlikely(!total_devices))
  7494. {
  7495. clear_logwin();
  7496. wlogprint("(no devices)\n");
  7497. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7498. _managetui_msg("(none)", &msg);
  7499. int input = getch();
  7500. switch (input)
  7501. {
  7502. case '+': case '=': // add new device
  7503. goto addnew;
  7504. default:
  7505. goto out;
  7506. }
  7507. }
  7508. cgpu = devices[selected_device];
  7509. drv = cgpu->drv;
  7510. refresh_devstatus();
  7511. refresh:
  7512. clear_logwin();
  7513. wlogprint("Select processor to manage using up/down arrow keys\n");
  7514. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7515. wattron(logwin, A_BOLD);
  7516. wlogprint("%s", logline);
  7517. wattroff(logwin, A_BOLD);
  7518. wlogprint("\n");
  7519. if (cgpu->dev_manufacturer)
  7520. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7521. else
  7522. if (cgpu->dev_product)
  7523. wlogprint(" %s\n", cgpu->dev_product);
  7524. if (cgpu->dev_serial)
  7525. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7526. if (cgpu->kname)
  7527. wlogprint("Kernel: %s\n", cgpu->kname);
  7528. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7529. drv->proc_wlogprint_status(cgpu);
  7530. wlogprint("\n");
  7531. // TODO: Last share at TIMESTAMP on pool N
  7532. // TODO: Custom device info/commands
  7533. if (cgpu->deven != DEV_ENABLED)
  7534. wlogprint("[E]nable ");
  7535. if (cgpu->deven != DEV_DISABLED)
  7536. wlogprint("[D]isable ");
  7537. if (drv->identify_device)
  7538. wlogprint("[I]dentify ");
  7539. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7540. drv->proc_tui_wlogprint_choices(cgpu);
  7541. wlogprint("\n");
  7542. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7543. _managetui_msg(cgpu->proc_repr, &msg);
  7544. while (true)
  7545. {
  7546. int input = getch();
  7547. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7548. switch (input) {
  7549. case 'd': case 'D':
  7550. if (cgpu->deven == DEV_DISABLED)
  7551. msg = "Processor already disabled\n";
  7552. else
  7553. {
  7554. cgpu->deven = DEV_DISABLED;
  7555. msg = "Processor being disabled\n";
  7556. }
  7557. goto refresh;
  7558. case 'e': case 'E':
  7559. if (cgpu->deven == DEV_ENABLED)
  7560. msg = "Processor already enabled\n";
  7561. else
  7562. {
  7563. proc_enable(cgpu);
  7564. msg = "Processor being enabled\n";
  7565. }
  7566. goto refresh;
  7567. case 'i': case 'I':
  7568. if (drv->identify_device && drv->identify_device(cgpu))
  7569. msg = "Identify command sent\n";
  7570. else
  7571. goto key_default;
  7572. goto refresh;
  7573. case KEY_DOWN:
  7574. if (selected_device >= total_devices - 1)
  7575. break;
  7576. ++selected_device;
  7577. goto devchange;
  7578. case KEY_UP:
  7579. if (selected_device <= 0)
  7580. break;
  7581. --selected_device;
  7582. goto devchange;
  7583. case KEY_NPAGE:
  7584. {
  7585. if (selected_device >= total_devices - 1)
  7586. break;
  7587. struct cgpu_info *mdev = devices[selected_device]->device;
  7588. do {
  7589. ++selected_device;
  7590. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7591. goto devchange;
  7592. }
  7593. case KEY_PPAGE:
  7594. {
  7595. if (selected_device <= 0)
  7596. break;
  7597. struct cgpu_info *mdev = devices[selected_device]->device;
  7598. do {
  7599. --selected_device;
  7600. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7601. goto devchange;
  7602. }
  7603. case '/': case '?': // find device
  7604. {
  7605. static char *pattern = NULL;
  7606. char *newpattern = curses_input("Enter pattern");
  7607. if (newpattern)
  7608. {
  7609. free(pattern);
  7610. pattern = newpattern;
  7611. }
  7612. else
  7613. if (!pattern)
  7614. pattern = calloc(1, 1);
  7615. int match = cgpu_search(pattern, selected_device + 1);
  7616. if (match == -1)
  7617. {
  7618. msg = "Couldn't find device\n";
  7619. goto refresh;
  7620. }
  7621. selected_device = match;
  7622. goto devchange;
  7623. }
  7624. case '+': case '=': // add new device
  7625. {
  7626. addnew:
  7627. clear_logwin();
  7628. _wlogprint(
  7629. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7630. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7631. "For example: erupter:"
  7632. #ifdef WIN32
  7633. "\\\\.\\COM40"
  7634. #elif defined(__APPLE__)
  7635. "/dev/cu.SLAB_USBtoUART"
  7636. #else
  7637. "/dev/ttyUSB39"
  7638. #endif
  7639. "\n"
  7640. );
  7641. char *scanser = curses_input("Enter target");
  7642. if (scan_serial(scanser))
  7643. {
  7644. selected_device = total_devices - 1;
  7645. msg = "Device scan succeeded\n";
  7646. }
  7647. else
  7648. msg = "No new devices found\n";
  7649. goto devchange;
  7650. }
  7651. case 'Q': case 'q':
  7652. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7653. case '\x1b': // ESC
  7654. case KEY_ENTER:
  7655. case '\r': // Ctrl-M on Windows, with nonl
  7656. #ifdef PADENTER
  7657. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7658. #endif
  7659. case '\n':
  7660. goto out;
  7661. default:
  7662. ;
  7663. key_default:
  7664. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7665. {
  7666. msg = drv->proc_tui_handle_choice(cgpu, input);
  7667. if (msg)
  7668. goto refresh;
  7669. }
  7670. }
  7671. }
  7672. out:
  7673. selecting_device = false;
  7674. loginput_mode(0);
  7675. immedok(logwin, false);
  7676. }
  7677. void show_help(void)
  7678. {
  7679. loginput_mode(11);
  7680. // NOTE: wlogprint is a macro with a buffer limit
  7681. _wlogprint(
  7682. "LU: oldest explicit work update currently being used for new work\n"
  7683. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7684. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7685. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7686. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7687. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7688. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7689. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7690. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7691. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7692. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7693. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7694. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7695. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7696. "\n"
  7697. "devices/processors hashing (only for totals line), hottest temperature\n"
  7698. );
  7699. wlogprint(
  7700. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7701. , opt_log_interval);
  7702. _wlogprint(
  7703. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7704. "HW: hardware errors / % nonces invalid\n"
  7705. "\n"
  7706. "Press any key to clear"
  7707. );
  7708. logwin_update();
  7709. getch();
  7710. loginput_mode(0);
  7711. }
  7712. static void *input_thread(void __maybe_unused *userdata)
  7713. {
  7714. RenameThread("input");
  7715. if (!curses_active)
  7716. return NULL;
  7717. while (1) {
  7718. int input;
  7719. input = getch();
  7720. switch (input) {
  7721. case 'h': case 'H': case '?':
  7722. case KEY_F(1):
  7723. show_help();
  7724. break;
  7725. case 'q': case 'Q':
  7726. kill_work();
  7727. return NULL;
  7728. case 'd': case 'D':
  7729. display_options();
  7730. break;
  7731. case 'm': case 'M':
  7732. manage_device();
  7733. break;
  7734. case 'p': case 'P':
  7735. display_pools();
  7736. break;
  7737. case 's': case 'S':
  7738. set_options();
  7739. break;
  7740. #ifdef HAVE_CURSES
  7741. case KEY_DOWN:
  7742. {
  7743. const int visible_lines = logcursor - devcursor;
  7744. const int invisible_lines = total_lines - visible_lines;
  7745. if (devsummaryYOffset <= -invisible_lines)
  7746. break;
  7747. devsummaryYOffset -= 2;
  7748. }
  7749. case KEY_UP:
  7750. if (devsummaryYOffset == 0)
  7751. break;
  7752. ++devsummaryYOffset;
  7753. refresh_devstatus();
  7754. break;
  7755. case KEY_NPAGE:
  7756. {
  7757. const int visible_lines = logcursor - devcursor;
  7758. const int invisible_lines = total_lines - visible_lines;
  7759. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7760. devsummaryYOffset = -invisible_lines;
  7761. else
  7762. devsummaryYOffset -= visible_lines;
  7763. refresh_devstatus();
  7764. break;
  7765. }
  7766. case KEY_PPAGE:
  7767. {
  7768. const int visible_lines = logcursor - devcursor;
  7769. if (devsummaryYOffset + visible_lines >= 0)
  7770. devsummaryYOffset = 0;
  7771. else
  7772. devsummaryYOffset += visible_lines;
  7773. refresh_devstatus();
  7774. break;
  7775. }
  7776. #endif
  7777. }
  7778. if (opt_realquiet) {
  7779. disable_curses();
  7780. break;
  7781. }
  7782. }
  7783. return NULL;
  7784. }
  7785. #endif
  7786. static void *api_thread(void *userdata)
  7787. {
  7788. struct thr_info *mythr = userdata;
  7789. pthread_detach(pthread_self());
  7790. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7791. RenameThread("rpc");
  7792. api(api_thr_id);
  7793. mythr->has_pth = false;
  7794. return NULL;
  7795. }
  7796. void thread_reportin(struct thr_info *thr)
  7797. {
  7798. cgtime(&thr->last);
  7799. thr->cgpu->status = LIFE_WELL;
  7800. thr->getwork = 0;
  7801. thr->cgpu->device_last_well = time(NULL);
  7802. }
  7803. void thread_reportout(struct thr_info *thr)
  7804. {
  7805. thr->getwork = time(NULL);
  7806. }
  7807. static void hashmeter(int thr_id, struct timeval *diff,
  7808. uint64_t hashes_done)
  7809. {
  7810. char logstatusline[256];
  7811. struct timeval temp_tv_end, total_diff;
  7812. double secs;
  7813. double local_secs;
  7814. static double local_mhashes_done = 0;
  7815. double local_mhashes = (double)hashes_done / 1000000.0;
  7816. bool showlog = false;
  7817. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7818. char rejpcbuf[6];
  7819. char bnbuf[6];
  7820. struct thr_info *thr;
  7821. /* Update the last time this thread reported in */
  7822. if (thr_id >= 0) {
  7823. thr = get_thread(thr_id);
  7824. cgtime(&(thr->last));
  7825. thr->cgpu->device_last_well = time(NULL);
  7826. }
  7827. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7828. /* So we can call hashmeter from a non worker thread */
  7829. if (thr_id >= 0) {
  7830. struct cgpu_info *cgpu = thr->cgpu;
  7831. int threadobj = cgpu->threads ?: 1;
  7832. double thread_rolling = 0.0;
  7833. int i;
  7834. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7835. thr_id, hashes_done, hashes_done / 1000 / secs);
  7836. /* Rolling average for each thread and each device */
  7837. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7838. for (i = 0; i < threadobj; i++)
  7839. thread_rolling += cgpu->thr[i]->rolling;
  7840. mutex_lock(&hash_lock);
  7841. decay_time(&cgpu->rolling, thread_rolling, secs);
  7842. cgpu->total_mhashes += local_mhashes;
  7843. mutex_unlock(&hash_lock);
  7844. // If needed, output detailed, per-device stats
  7845. if (want_per_device_stats) {
  7846. struct timeval now;
  7847. struct timeval elapsed;
  7848. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7849. cgtime(&now);
  7850. timersub(&now, last_msg_tv, &elapsed);
  7851. if (opt_log_interval <= elapsed.tv_sec) {
  7852. struct cgpu_info *cgpu = thr->cgpu;
  7853. char logline[255];
  7854. *last_msg_tv = now;
  7855. get_statline(logline, sizeof(logline), cgpu);
  7856. if (!curses_active) {
  7857. printf("\n%s\r", logline);
  7858. fflush(stdout);
  7859. } else
  7860. applog(LOG_INFO, "%s", logline);
  7861. }
  7862. }
  7863. }
  7864. /* Totals are updated by all threads so can race without locking */
  7865. mutex_lock(&hash_lock);
  7866. cgtime(&temp_tv_end);
  7867. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7868. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7869. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7870. total_mhashes_done += local_mhashes;
  7871. local_mhashes_done += local_mhashes;
  7872. /* Only update with opt_log_interval */
  7873. if (total_diff.tv_sec < opt_log_interval)
  7874. goto out_unlock;
  7875. showlog = true;
  7876. cgtime(&total_tv_end);
  7877. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7878. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7879. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7880. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7881. multi_format_unit_array2(
  7882. ((char*[]){cHr, aHr, uHr}),
  7883. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7884. true, "h/s", H2B_SHORT,
  7885. 3,
  7886. 1e6*total_rolling,
  7887. 1e6*total_mhashes_done / total_secs,
  7888. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7889. int ui_accepted, ui_rejected, ui_stale;
  7890. if (opt_weighed_stats)
  7891. {
  7892. ui_accepted = total_diff_accepted;
  7893. ui_rejected = total_diff_rejected;
  7894. ui_stale = total_diff_stale;
  7895. }
  7896. else
  7897. {
  7898. ui_accepted = total_accepted;
  7899. ui_rejected = total_rejected;
  7900. ui_stale = total_stale;
  7901. }
  7902. #ifdef HAVE_CURSES
  7903. if (curses_active_locked()) {
  7904. float temp = 0;
  7905. struct cgpu_info *proc, *last_working_dev = NULL;
  7906. int i, working_devs = 0, working_procs = 0;
  7907. int divx;
  7908. bool bad = false;
  7909. // Find the highest temperature of all processors
  7910. for (i = 0; i < total_devices; ++i)
  7911. {
  7912. proc = get_devices(i);
  7913. if (proc->temp > temp)
  7914. temp = proc->temp;
  7915. if (unlikely(proc->deven == DEV_DISABLED))
  7916. ; // Just need to block it off from both conditions
  7917. else
  7918. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7919. {
  7920. if (proc->rolling > .1)
  7921. {
  7922. ++working_procs;
  7923. if (proc->device != last_working_dev)
  7924. {
  7925. ++working_devs;
  7926. last_working_dev = proc->device;
  7927. }
  7928. }
  7929. }
  7930. else
  7931. bad = true;
  7932. }
  7933. if (working_devs == working_procs)
  7934. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7935. else
  7936. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7937. divx = 7;
  7938. if (opt_show_procs && !opt_compact)
  7939. divx += max_lpdigits;
  7940. if (bad)
  7941. {
  7942. divx += sizeof(U8_BAD_START)-1;
  7943. strcpy(&statusline[divx], U8_BAD_END);
  7944. divx += sizeof(U8_BAD_END)-1;
  7945. }
  7946. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7947. format_statline(statusline, sizeof(statusline),
  7948. cHr, aHr,
  7949. uHr,
  7950. ui_accepted,
  7951. ui_rejected,
  7952. ui_stale,
  7953. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7954. hw_errors,
  7955. total_bad_diff1, total_bad_diff1 + total_diff1);
  7956. unlock_curses();
  7957. }
  7958. #endif
  7959. // Add a space
  7960. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7961. uHr[5] = ' ';
  7962. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7963. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7964. snprintf(logstatusline, sizeof(logstatusline),
  7965. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7966. want_per_device_stats ? "ALL " : "",
  7967. opt_log_interval,
  7968. cHr, aHr,
  7969. uHr,
  7970. ui_accepted,
  7971. ui_rejected,
  7972. ui_stale,
  7973. rejpcbuf,
  7974. hw_errors,
  7975. bnbuf
  7976. );
  7977. local_mhashes_done = 0;
  7978. out_unlock:
  7979. mutex_unlock(&hash_lock);
  7980. if (showlog) {
  7981. if (!curses_active) {
  7982. if (want_per_device_stats)
  7983. printf("\n%s\r", logstatusline);
  7984. else
  7985. {
  7986. const int logstatusline_len = strlen(logstatusline);
  7987. int padding;
  7988. if (last_logstatusline_len > logstatusline_len)
  7989. padding = (last_logstatusline_len - logstatusline_len);
  7990. else
  7991. {
  7992. padding = 0;
  7993. if (last_logstatusline_len == -1)
  7994. puts("");
  7995. }
  7996. printf("%s%*s\r", logstatusline, padding, "");
  7997. last_logstatusline_len = logstatusline_len;
  7998. }
  7999. fflush(stdout);
  8000. } else
  8001. applog(LOG_INFO, "%s", logstatusline);
  8002. }
  8003. }
  8004. void hashmeter2(struct thr_info *thr)
  8005. {
  8006. struct timeval tv_now, tv_elapsed;
  8007. timerclear(&thr->tv_hashes_done);
  8008. cgtime(&tv_now);
  8009. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  8010. /* Update the hashmeter at most 5 times per second */
  8011. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  8012. tv_elapsed.tv_sec >= opt_log_interval) {
  8013. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  8014. thr->hashes_done = 0;
  8015. thr->tv_lastupdate = tv_now;
  8016. }
  8017. }
  8018. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  8019. struct stratum_share *sshare)
  8020. {
  8021. struct work *work = sshare->work;
  8022. share_result(val, res_val, err_val, work, false, "");
  8023. }
  8024. /* Parses stratum json responses and tries to find the id that the request
  8025. * matched to and treat it accordingly. */
  8026. bool parse_stratum_response(struct pool *pool, char *s)
  8027. {
  8028. json_t *val = NULL, *err_val, *res_val, *id_val;
  8029. struct stratum_share *sshare;
  8030. json_error_t err;
  8031. bool ret = false;
  8032. int id;
  8033. val = JSON_LOADS(s, &err);
  8034. if (!val) {
  8035. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  8036. goto out;
  8037. }
  8038. res_val = json_object_get(val, "result");
  8039. err_val = json_object_get(val, "error");
  8040. id_val = json_object_get(val, "id");
  8041. if (json_is_null(id_val) || !id_val) {
  8042. char *ss;
  8043. if (err_val)
  8044. ss = json_dumps(err_val, JSON_INDENT(3));
  8045. else
  8046. ss = strdup("(unknown reason)");
  8047. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  8048. free(ss);
  8049. goto out;
  8050. }
  8051. if (!json_is_integer(id_val)) {
  8052. if (json_is_string(id_val)
  8053. && !strncmp(json_string_value(id_val), "txlist", 6))
  8054. {
  8055. const bool is_array = json_is_array(res_val);
  8056. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  8057. is_array ? "transaction list" : "no-transaction-list response",
  8058. pool->pool_no, &json_string_value(id_val)[6]);
  8059. if (!is_array)
  8060. {
  8061. // No need to wait for a timeout
  8062. timer_unset(&pool->swork.tv_transparency);
  8063. pool_set_opaque(pool, true);
  8064. goto fishy;
  8065. }
  8066. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  8067. // We only care about a transaction list for the current job id
  8068. goto fishy;
  8069. // Check that the transactions actually hash to the merkle links
  8070. {
  8071. unsigned maxtx = 1 << pool->swork.merkles;
  8072. unsigned mintx = maxtx >> 1;
  8073. --maxtx;
  8074. unsigned acttx = (unsigned)json_array_size(res_val);
  8075. if (acttx < mintx || acttx > maxtx) {
  8076. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  8077. pool->pool_no, acttx, mintx, maxtx);
  8078. goto fishy;
  8079. }
  8080. // TODO: Check hashes match actual merkle links
  8081. }
  8082. pool_set_opaque(pool, false);
  8083. timer_unset(&pool->swork.tv_transparency);
  8084. fishy:
  8085. ret = true;
  8086. }
  8087. goto out;
  8088. }
  8089. id = json_integer_value(id_val);
  8090. mutex_lock(&sshare_lock);
  8091. HASH_FIND_INT(stratum_shares, &id, sshare);
  8092. if (sshare)
  8093. HASH_DEL(stratum_shares, sshare);
  8094. mutex_unlock(&sshare_lock);
  8095. if (!sshare) {
  8096. double pool_diff;
  8097. /* Since the share is untracked, we can only guess at what the
  8098. * work difficulty is based on the current pool diff. */
  8099. cg_rlock(&pool->data_lock);
  8100. pool_diff = target_diff(pool->swork.target);
  8101. cg_runlock(&pool->data_lock);
  8102. if (json_is_true(res_val)) {
  8103. struct mining_goal_info * const goal = pool->goal;
  8104. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8105. /* We don't know what device this came from so we can't
  8106. * attribute the work to the relevant cgpu */
  8107. mutex_lock(&stats_lock);
  8108. total_accepted++;
  8109. pool->accepted++;
  8110. total_diff_accepted += pool_diff;
  8111. pool->diff_accepted += pool_diff;
  8112. goal->diff_accepted += pool_diff;
  8113. mutex_unlock(&stats_lock);
  8114. } else {
  8115. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8116. mutex_lock(&stats_lock);
  8117. total_rejected++;
  8118. pool->rejected++;
  8119. total_diff_rejected += pool_diff;
  8120. pool->diff_rejected += pool_diff;
  8121. mutex_unlock(&stats_lock);
  8122. }
  8123. goto out;
  8124. }
  8125. else {
  8126. mutex_lock(&submitting_lock);
  8127. --total_submitting;
  8128. mutex_unlock(&submitting_lock);
  8129. }
  8130. stratum_share_result(val, res_val, err_val, sshare);
  8131. free_work(sshare->work);
  8132. free(sshare);
  8133. ret = true;
  8134. out:
  8135. if (val)
  8136. json_decref(val);
  8137. return ret;
  8138. }
  8139. static void shutdown_stratum(struct pool *pool)
  8140. {
  8141. // Shut down Stratum as if we never had it
  8142. pool->stratum_active = false;
  8143. pool->stratum_init = false;
  8144. pool->has_stratum = false;
  8145. shutdown(pool->sock, SHUT_RDWR);
  8146. free(pool->stratum_url);
  8147. if (pool->sockaddr_url == pool->stratum_url)
  8148. pool->sockaddr_url = NULL;
  8149. pool->stratum_url = NULL;
  8150. }
  8151. void clear_stratum_shares(struct pool *pool)
  8152. {
  8153. int my_mining_threads = mining_threads; // Cached outside of locking
  8154. struct stratum_share *sshare, *tmpshare;
  8155. struct work *work;
  8156. struct cgpu_info *cgpu;
  8157. double diff_cleared = 0;
  8158. double thr_diff_cleared[my_mining_threads];
  8159. int cleared = 0;
  8160. int thr_cleared[my_mining_threads];
  8161. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8162. for (int i = 0; i < my_mining_threads; ++i)
  8163. {
  8164. thr_diff_cleared[i] = 0;
  8165. thr_cleared[i] = 0;
  8166. }
  8167. mutex_lock(&sshare_lock);
  8168. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8169. work = sshare->work;
  8170. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8171. HASH_DEL(stratum_shares, sshare);
  8172. sharelog("disconnect", work);
  8173. diff_cleared += sshare->work->work_difficulty;
  8174. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8175. ++thr_cleared[work->thr_id];
  8176. free_work(sshare->work);
  8177. free(sshare);
  8178. cleared++;
  8179. }
  8180. }
  8181. mutex_unlock(&sshare_lock);
  8182. if (cleared) {
  8183. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8184. mutex_lock(&stats_lock);
  8185. pool->stale_shares += cleared;
  8186. total_stale += cleared;
  8187. pool->diff_stale += diff_cleared;
  8188. total_diff_stale += diff_cleared;
  8189. for (int i = 0; i < my_mining_threads; ++i)
  8190. if (thr_cleared[i])
  8191. {
  8192. cgpu = get_thr_cgpu(i);
  8193. cgpu->diff_stale += thr_diff_cleared[i];
  8194. cgpu->stale += thr_cleared[i];
  8195. }
  8196. mutex_unlock(&stats_lock);
  8197. mutex_lock(&submitting_lock);
  8198. total_submitting -= cleared;
  8199. mutex_unlock(&submitting_lock);
  8200. }
  8201. }
  8202. static void resubmit_stratum_shares(struct pool *pool)
  8203. {
  8204. struct stratum_share *sshare, *tmpshare;
  8205. struct work *work;
  8206. unsigned resubmitted = 0;
  8207. mutex_lock(&sshare_lock);
  8208. mutex_lock(&submitting_lock);
  8209. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8210. if (sshare->work->pool != pool)
  8211. continue;
  8212. HASH_DEL(stratum_shares, sshare);
  8213. work = sshare->work;
  8214. DL_APPEND(submit_waiting, work);
  8215. free(sshare);
  8216. ++resubmitted;
  8217. }
  8218. mutex_unlock(&submitting_lock);
  8219. mutex_unlock(&sshare_lock);
  8220. if (resubmitted) {
  8221. notifier_wake(submit_waiting_notifier);
  8222. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8223. }
  8224. }
  8225. static void clear_pool_work(struct pool *pool)
  8226. {
  8227. struct work *work, *tmp;
  8228. int cleared = 0;
  8229. mutex_lock(stgd_lock);
  8230. HASH_ITER(hh, staged_work, work, tmp) {
  8231. if (work->pool == pool) {
  8232. unstage_work(work);
  8233. free_work(work);
  8234. cleared++;
  8235. }
  8236. }
  8237. mutex_unlock(stgd_lock);
  8238. }
  8239. static int cp_prio(void)
  8240. {
  8241. int prio;
  8242. cg_rlock(&control_lock);
  8243. prio = currentpool->prio;
  8244. cg_runlock(&control_lock);
  8245. return prio;
  8246. }
  8247. /* We only need to maintain a secondary pool connection when we need the
  8248. * capacity to get work from the backup pools while still on the primary */
  8249. static bool cnx_needed(struct pool *pool)
  8250. {
  8251. struct pool *cp;
  8252. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8253. if (pool->enabled == POOL_DISABLED)
  8254. return false;
  8255. /* Idle stratum pool needs something to kick it alive again */
  8256. if (pool->has_stratum && pool->idle)
  8257. return true;
  8258. /* Getwork pools without opt_fail_only need backup pools up to be able
  8259. * to leak shares */
  8260. cp = current_pool();
  8261. if (pool_actively_desired(pool, cp))
  8262. return true;
  8263. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8264. return true;
  8265. /* Keep the connection open to allow any stray shares to be submitted
  8266. * on switching pools for 2 minutes. */
  8267. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8268. return true;
  8269. /* If the pool has only just come to life and is higher priority than
  8270. * the current pool keep the connection open so we can fail back to
  8271. * it. */
  8272. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8273. return true;
  8274. if (pool_unworkable(cp))
  8275. return true;
  8276. /* We've run out of work, bring anything back to life. */
  8277. if (no_work)
  8278. return true;
  8279. // If the current pool lacks its own block change detection, see if we are needed for that
  8280. if (pool_active_lp_pool(cp) == pool)
  8281. return true;
  8282. return false;
  8283. }
  8284. static void wait_lpcurrent(struct pool *pool);
  8285. static void pool_resus(struct pool *pool);
  8286. static void stratum_resumed(struct pool *pool)
  8287. {
  8288. if (!pool->stratum_notify)
  8289. return;
  8290. if (pool_tclear(pool, &pool->idle)) {
  8291. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8292. pool_resus(pool);
  8293. }
  8294. }
  8295. static bool supports_resume(struct pool *pool)
  8296. {
  8297. bool ret;
  8298. cg_rlock(&pool->data_lock);
  8299. ret = (pool->sessionid != NULL);
  8300. cg_runlock(&pool->data_lock);
  8301. return ret;
  8302. }
  8303. static bool pools_active;
  8304. /* One stratum thread per pool that has stratum waits on the socket checking
  8305. * for new messages and for the integrity of the socket connection. We reset
  8306. * the connection based on the integrity of the receive side only as the send
  8307. * side will eventually expire data it fails to send. */
  8308. static void *stratum_thread(void *userdata)
  8309. {
  8310. struct pool *pool = (struct pool *)userdata;
  8311. pthread_detach(pthread_self());
  8312. char threadname[20];
  8313. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8314. RenameThread(threadname);
  8315. srand(time(NULL) + (intptr_t)userdata);
  8316. while (42) {
  8317. struct timeval timeout;
  8318. int sel_ret;
  8319. fd_set rd;
  8320. char *s;
  8321. int sock;
  8322. if (unlikely(!pool->has_stratum))
  8323. break;
  8324. /* Check to see whether we need to maintain this connection
  8325. * indefinitely or just bring it up when we switch to this
  8326. * pool */
  8327. while (true)
  8328. {
  8329. sock = pool->sock;
  8330. if (sock == INVSOCK)
  8331. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8332. pool->pool_no);
  8333. else
  8334. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8335. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8336. pool->pool_no);
  8337. else
  8338. break;
  8339. suspend_stratum(pool);
  8340. clear_stratum_shares(pool);
  8341. clear_pool_work(pool);
  8342. wait_lpcurrent(pool);
  8343. if (!restart_stratum(pool)) {
  8344. pool_died(pool);
  8345. while (!restart_stratum(pool)) {
  8346. if (pool->removed)
  8347. goto out;
  8348. cgsleep_ms(30000);
  8349. }
  8350. }
  8351. }
  8352. FD_ZERO(&rd);
  8353. FD_SET(sock, &rd);
  8354. timeout.tv_sec = 120;
  8355. timeout.tv_usec = 0;
  8356. /* If we fail to receive any notify messages for 2 minutes we
  8357. * assume the connection has been dropped and treat this pool
  8358. * as dead */
  8359. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8360. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8361. s = NULL;
  8362. } else
  8363. s = recv_line(pool);
  8364. if (!s) {
  8365. if (!pool->has_stratum)
  8366. break;
  8367. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8368. pool->getfail_occasions++;
  8369. total_go++;
  8370. mutex_lock(&pool->stratum_lock);
  8371. pool->stratum_active = pool->stratum_notify = false;
  8372. pool->sock = INVSOCK;
  8373. mutex_unlock(&pool->stratum_lock);
  8374. /* If the socket to our stratum pool disconnects, all
  8375. * submissions need to be discarded or resent. */
  8376. if (!supports_resume(pool))
  8377. clear_stratum_shares(pool);
  8378. else
  8379. resubmit_stratum_shares(pool);
  8380. clear_pool_work(pool);
  8381. if (pool == current_pool())
  8382. restart_threads();
  8383. if (restart_stratum(pool))
  8384. continue;
  8385. shutdown_stratum(pool);
  8386. pool_died(pool);
  8387. break;
  8388. }
  8389. /* Check this pool hasn't died while being a backup pool and
  8390. * has not had its idle flag cleared */
  8391. stratum_resumed(pool);
  8392. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8393. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8394. free(s);
  8395. if (pool->swork.clean) {
  8396. struct work *work = make_work();
  8397. /* Generate a single work item to update the current
  8398. * block database */
  8399. pool->swork.clean = false;
  8400. gen_stratum_work(pool, work);
  8401. /* Try to extract block height from coinbase scriptSig */
  8402. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8403. unsigned char cb_height_sz;
  8404. cb_height_sz = bin_height[-1];
  8405. if (cb_height_sz == 3) {
  8406. // FIXME: The block number will overflow this by AD 2173
  8407. struct mining_goal_info * const goal = pool->goal;
  8408. const void * const prevblkhash = &work->data[4];
  8409. uint32_t height = 0;
  8410. memcpy(&height, bin_height, 3);
  8411. height = le32toh(height);
  8412. have_block_height(goal, prevblkhash, height);
  8413. }
  8414. pool->swork.work_restart_id =
  8415. ++pool->work_restart_id;
  8416. pool_update_work_restart_time(pool);
  8417. if (test_work_current(work)) {
  8418. /* Only accept a work update if this stratum
  8419. * connection is from the current pool */
  8420. struct pool * const cp = current_pool();
  8421. if (pool == cp)
  8422. restart_threads();
  8423. applog(
  8424. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8425. "Stratum from pool %d requested work update", pool->pool_no);
  8426. } else
  8427. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8428. free_work(work);
  8429. }
  8430. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8431. // More than 4 timmills past since requested transactions
  8432. timer_unset(&pool->swork.tv_transparency);
  8433. pool_set_opaque(pool, true);
  8434. }
  8435. }
  8436. out:
  8437. return NULL;
  8438. }
  8439. static void init_stratum_thread(struct pool *pool)
  8440. {
  8441. struct mining_goal_info * const goal = pool->goal;
  8442. goal->have_longpoll = true;
  8443. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8444. quit(1, "Failed to create stratum thread");
  8445. }
  8446. static void *longpoll_thread(void *userdata);
  8447. static bool stratum_works(struct pool *pool)
  8448. {
  8449. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8450. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8451. return false;
  8452. if (pool->stratum_active)
  8453. return true;
  8454. if (!initiate_stratum(pool))
  8455. return false;
  8456. return true;
  8457. }
  8458. static
  8459. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8460. {
  8461. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8462. }
  8463. static bool pool_active(struct pool *pool, bool pinging)
  8464. {
  8465. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8466. bool ret = false;
  8467. json_t *val;
  8468. CURL *curl = NULL;
  8469. int rolltime;
  8470. char *rpc_req;
  8471. struct work *work;
  8472. enum pool_protocol proto;
  8473. if (pool->stratum_init)
  8474. {
  8475. if (pool->stratum_active)
  8476. return true;
  8477. }
  8478. else
  8479. if (!pool->idle)
  8480. {
  8481. timer_set_now(&tv_now);
  8482. if (pool_recently_got_work(pool, &tv_now))
  8483. return true;
  8484. }
  8485. mutex_lock(&pool->pool_test_lock);
  8486. if (pool->stratum_init)
  8487. {
  8488. ret = pool->stratum_active;
  8489. goto out;
  8490. }
  8491. timer_set_now(&tv_now);
  8492. if (pool->idle)
  8493. {
  8494. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8495. goto out;
  8496. }
  8497. else
  8498. if (pool_recently_got_work(pool, &tv_now))
  8499. {
  8500. ret = true;
  8501. goto out;
  8502. }
  8503. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8504. /* This is the central point we activate stratum when we can */
  8505. curl = curl_easy_init();
  8506. if (unlikely(!curl)) {
  8507. applog(LOG_ERR, "CURL initialisation failed");
  8508. goto out;
  8509. }
  8510. if (!(want_gbt || want_getwork))
  8511. goto nohttp;
  8512. work = make_work();
  8513. /* Probe for GBT support on first pass */
  8514. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8515. tryagain:
  8516. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8517. work->pool = pool;
  8518. if (!rpc_req)
  8519. goto out;
  8520. pool->probed = false;
  8521. cgtime(&tv_getwork);
  8522. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8523. true, false, &rolltime, pool, false);
  8524. cgtime(&tv_getwork_reply);
  8525. free(rpc_req);
  8526. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8527. * and if so, switch to that in preference to getwork if it works */
  8528. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8529. if (!pool->has_stratum) {
  8530. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8531. if (!pool->rpc_url)
  8532. pool_set_uri(pool, strdup(pool->stratum_url));
  8533. pool->has_stratum = true;
  8534. }
  8535. free_work(work);
  8536. if (val)
  8537. json_decref(val);
  8538. retry_stratum:
  8539. ;
  8540. /* We create the stratum thread for each pool just after
  8541. * successful authorisation. Once the init flag has been set
  8542. * we never unset it and the stratum thread is responsible for
  8543. * setting/unsetting the active flag */
  8544. bool init = pool_tset(pool, &pool->stratum_init);
  8545. if (!init) {
  8546. ret = initiate_stratum(pool) && auth_stratum(pool);
  8547. if (ret)
  8548. {
  8549. detect_algo = 2;
  8550. init_stratum_thread(pool);
  8551. }
  8552. else
  8553. {
  8554. pool_tclear(pool, &pool->stratum_init);
  8555. pool->tv_idle = tv_getwork_reply;
  8556. }
  8557. goto out;
  8558. }
  8559. ret = pool->stratum_active;
  8560. goto out;
  8561. }
  8562. else if (pool->has_stratum)
  8563. shutdown_stratum(pool);
  8564. if (val) {
  8565. bool rc;
  8566. json_t *res;
  8567. res = json_object_get(val, "result");
  8568. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8569. goto badwork;
  8570. work->rolltime = rolltime;
  8571. rc = work_decode(pool, work, val);
  8572. if (rc) {
  8573. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8574. pool->pool_no, pool->rpc_url);
  8575. work->pool = pool;
  8576. copy_time(&work->tv_getwork, &tv_getwork);
  8577. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8578. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8579. calc_diff(work, 0);
  8580. update_last_work(work);
  8581. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8582. stage_work(work);
  8583. total_getworks++;
  8584. pool->getwork_requested++;
  8585. ret = true;
  8586. pool->tv_idle = tv_getwork_reply;
  8587. } else {
  8588. badwork:
  8589. json_decref(val);
  8590. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8591. pool->pool_no, pool->rpc_url);
  8592. pool->proto = proto = pool_protocol_fallback(proto);
  8593. if (PLP_NONE != proto)
  8594. goto tryagain;
  8595. pool->tv_idle = tv_getwork_reply;
  8596. free_work(work);
  8597. goto out;
  8598. }
  8599. json_decref(val);
  8600. if (proto != pool->proto) {
  8601. pool->proto = proto;
  8602. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8603. }
  8604. if (pool->lp_url)
  8605. goto out;
  8606. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8607. const struct blktmpl_longpoll_req *lp;
  8608. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8609. // NOTE: work_decode takes care of lp id
  8610. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8611. if (!pool->lp_url)
  8612. {
  8613. ret = false;
  8614. goto out;
  8615. }
  8616. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8617. }
  8618. else
  8619. if (pool->hdr_path && want_getwork) {
  8620. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8621. if (!pool->lp_url)
  8622. {
  8623. ret = false;
  8624. goto out;
  8625. }
  8626. pool->lp_proto = PLP_GETWORK;
  8627. } else
  8628. pool->lp_url = NULL;
  8629. if (want_longpoll && !pool->lp_started) {
  8630. pool->lp_started = true;
  8631. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8632. quit(1, "Failed to create pool longpoll thread");
  8633. }
  8634. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8635. pool->proto = proto;
  8636. goto tryagain;
  8637. } else {
  8638. pool->tv_idle = tv_getwork_reply;
  8639. free_work(work);
  8640. nohttp:
  8641. /* If we failed to parse a getwork, this could be a stratum
  8642. * url without the prefix stratum+tcp:// so let's check it */
  8643. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8644. pool->has_stratum = true;
  8645. goto retry_stratum;
  8646. }
  8647. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8648. pool->pool_no, pool->rpc_url);
  8649. if (!pinging)
  8650. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8651. }
  8652. out:
  8653. if (curl)
  8654. curl_easy_cleanup(curl);
  8655. mutex_unlock(&pool->pool_test_lock);
  8656. return ret;
  8657. }
  8658. static void pool_resus(struct pool *pool)
  8659. {
  8660. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8661. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8662. else
  8663. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8664. }
  8665. static
  8666. void *cmd_idle_thread(void * const __maybe_unused userp)
  8667. {
  8668. pthread_detach(pthread_self());
  8669. RenameThread("cmd-idle");
  8670. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8671. sleep(opt_log_interval);
  8672. pthread_testcancel();
  8673. run_cmd(cmd_idle);
  8674. return NULL;
  8675. }
  8676. static struct work *hash_pop(struct cgpu_info * const proc)
  8677. {
  8678. int hc;
  8679. struct work *work, *work_found, *tmp;
  8680. enum {
  8681. HPWS_NONE,
  8682. HPWS_LOWDIFF,
  8683. HPWS_SPARE,
  8684. HPWS_ROLLABLE,
  8685. HPWS_PERFECT,
  8686. } work_score = HPWS_NONE;
  8687. bool did_cmd_idle = false;
  8688. pthread_t cmd_idle_thr;
  8689. retry:
  8690. mutex_lock(stgd_lock);
  8691. while (true)
  8692. {
  8693. work_found = NULL;
  8694. work_score = 0;
  8695. hc = HASH_COUNT(staged_work);
  8696. HASH_ITER(hh, staged_work, work, tmp)
  8697. {
  8698. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8699. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8700. #define FOUND_WORK(score) do{ \
  8701. if (work_score < score) \
  8702. { \
  8703. work_found = work; \
  8704. work_score = score; \
  8705. } \
  8706. continue; \
  8707. }while(0)
  8708. if (min_nonce_diff < work->work_difficulty)
  8709. {
  8710. if (min_nonce_diff < 0)
  8711. continue;
  8712. FOUND_WORK(HPWS_LOWDIFF);
  8713. }
  8714. if (work->spare)
  8715. FOUND_WORK(HPWS_SPARE);
  8716. if (work->rolltime && hc > staged_rollable)
  8717. FOUND_WORK(HPWS_ROLLABLE);
  8718. #undef FOUND_WORK
  8719. // Good match
  8720. work_found = work;
  8721. work_score = HPWS_PERFECT;
  8722. break;
  8723. }
  8724. if (work_found)
  8725. {
  8726. work = work_found;
  8727. break;
  8728. }
  8729. // Failed to get a usable work
  8730. if (unlikely(staged_full))
  8731. {
  8732. if (likely(opt_queue < 10 + mining_threads))
  8733. {
  8734. ++opt_queue;
  8735. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8736. }
  8737. else
  8738. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8739. staged_full = false; // Let it fill up before triggering an underrun again
  8740. no_work = true;
  8741. }
  8742. pthread_cond_signal(&gws_cond);
  8743. if (cmd_idle && !did_cmd_idle)
  8744. {
  8745. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8746. did_cmd_idle = true;
  8747. }
  8748. pthread_cond_wait(&getq->cond, stgd_lock);
  8749. }
  8750. if (did_cmd_idle)
  8751. pthread_cancel(cmd_idle_thr);
  8752. no_work = false;
  8753. if (can_roll(work) && should_roll(work))
  8754. {
  8755. // Instead of consuming it, force it to be cloned and grab the clone
  8756. mutex_unlock(stgd_lock);
  8757. clone_available();
  8758. goto retry;
  8759. }
  8760. unstage_work(work);
  8761. /* Signal the getwork scheduler to look for more work */
  8762. pthread_cond_signal(&gws_cond);
  8763. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8764. pthread_cond_signal(&getq->cond);
  8765. mutex_unlock(stgd_lock);
  8766. work->pool->last_work_time = time(NULL);
  8767. cgtime(&work->pool->tv_last_work_time);
  8768. return work;
  8769. }
  8770. /* Clones work by rolling it if possible, and returning a clone instead of the
  8771. * original work item which gets staged again to possibly be rolled again in
  8772. * the future */
  8773. static struct work *clone_work(struct work *work)
  8774. {
  8775. int mrs = mining_threads + opt_queue - total_staged(false);
  8776. struct work *work_clone;
  8777. bool cloned;
  8778. if (mrs < 1)
  8779. return work;
  8780. cloned = false;
  8781. work_clone = make_clone(work);
  8782. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8783. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8784. stage_work(work_clone);
  8785. roll_work(work);
  8786. work_clone = make_clone(work);
  8787. /* Roll it again to prevent duplicates should this be used
  8788. * directly later on */
  8789. roll_work(work);
  8790. cloned = true;
  8791. }
  8792. if (cloned) {
  8793. stage_work(work);
  8794. return work_clone;
  8795. }
  8796. free_work(work_clone);
  8797. return work;
  8798. }
  8799. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8800. {
  8801. unsigned char hash1[32];
  8802. sha256(data, len, hash1);
  8803. sha256(hash1, 32, hash);
  8804. }
  8805. /* PDiff 1 is a 256 bit unsigned integer of
  8806. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8807. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8808. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8809. static void pdiff_target_leadzero(void * const target_p, double diff)
  8810. {
  8811. uint8_t *target = target_p;
  8812. diff *= 0x100000000;
  8813. int skip = log2(diff) / 8;
  8814. if (skip)
  8815. {
  8816. if (skip > 0x1c)
  8817. skip = 0x1c;
  8818. diff /= pow(0x100, skip);
  8819. memset(target, 0, skip);
  8820. }
  8821. uint32_t n = 0xffffffff;
  8822. n = (double)n / diff;
  8823. n = htobe32(n);
  8824. memcpy(&target[skip], &n, sizeof(n));
  8825. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8826. }
  8827. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8828. {
  8829. unsigned char rtarget[32];
  8830. pdiff_target_leadzero(rtarget, pdiff);
  8831. swab256(dest_target, rtarget);
  8832. if (opt_debug) {
  8833. char htarget[65];
  8834. bin2hex(htarget, rtarget, 32);
  8835. applog(LOG_DEBUG, "Generated target %s", htarget);
  8836. }
  8837. }
  8838. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8839. {
  8840. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8841. }
  8842. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8843. {
  8844. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8845. int off;
  8846. void (*func)(void *, double) = funcp;
  8847. func(little_endian ? bufr : buf, diff);
  8848. if (little_endian)
  8849. swab256(buf, bufr);
  8850. swap32tobe(expect, expectp, 256/32);
  8851. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8852. for (off = 0; off < 28 && !buf[off]; ++off)
  8853. {}
  8854. if (memcmp(&buf[off], &expect[off], 4))
  8855. {
  8856. testfail: ;
  8857. ++unittest_failures;
  8858. char hexbuf[65], expectbuf[65];
  8859. bin2hex(hexbuf, buf, 32);
  8860. bin2hex(expectbuf, expect, 32);
  8861. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8862. funcname, diff, hexbuf, expectbuf);
  8863. }
  8864. if (!little_endian)
  8865. swab256(bufr, buf);
  8866. swab256(expectr, expect);
  8867. if (!hash_target_check(expectr, bufr))
  8868. goto testfail;
  8869. }
  8870. #define TEST_TARGET(func, le, expect, diff) \
  8871. _test_target(func, #func, le, expect, diff)
  8872. void test_target()
  8873. {
  8874. uint32_t expect[8] = {0};
  8875. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8876. expect[0] = 0x0000ffff;
  8877. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8878. expect[0] = 0;
  8879. expect[1] = 0xffff0000;
  8880. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8881. expect[1] >>= 1;
  8882. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8883. expect[1] >>= 3;
  8884. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8885. expect[1] >>= 4;
  8886. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8887. memset(&expect[1], '\xff', 28);
  8888. expect[0] = 0x0000ffff;
  8889. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8890. expect[0] = 0;
  8891. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8892. expect[1] >>= 1;
  8893. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8894. expect[1] >>= 3;
  8895. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8896. expect[1] >>= 4;
  8897. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8898. }
  8899. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8900. {
  8901. *dst = *src;
  8902. if (dst->tr)
  8903. tmpl_incref(dst->tr);
  8904. dst->nonce1 = maybe_strdup(src->nonce1);
  8905. dst->job_id = maybe_strdup(src->job_id);
  8906. bytes_cpy(&dst->coinbase, &src->coinbase);
  8907. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8908. }
  8909. void stratum_work_clean(struct stratum_work * const swork)
  8910. {
  8911. if (swork->tr)
  8912. tmpl_decref(swork->tr);
  8913. free(swork->nonce1);
  8914. free(swork->job_id);
  8915. bytes_free(&swork->coinbase);
  8916. bytes_free(&swork->merkle_bin);
  8917. }
  8918. bool pool_has_usable_swork(const struct pool * const pool)
  8919. {
  8920. if (opt_benchmark)
  8921. return true;
  8922. if (pool->swork.tr)
  8923. {
  8924. // GBT
  8925. struct timeval tv_now;
  8926. timer_set_now(&tv_now);
  8927. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8928. }
  8929. return pool->stratum_notify;
  8930. }
  8931. /* Generates stratum based work based on the most recent notify information
  8932. * from the pool. This will keep generating work while a pool is down so we use
  8933. * other means to detect when the pool has died in stratum_thread */
  8934. static void gen_stratum_work(struct pool *pool, struct work *work)
  8935. {
  8936. clean_work(work);
  8937. cg_wlock(&pool->data_lock);
  8938. pool->swork.data_lock_p = &pool->data_lock;
  8939. const int n2size = pool->swork.n2size;
  8940. bytes_resize(&work->nonce2, n2size);
  8941. if (pool->nonce2sz < n2size)
  8942. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8943. memcpy(bytes_buf(&work->nonce2),
  8944. #ifdef WORDS_BIGENDIAN
  8945. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8946. &((char*)&pool->nonce2)[pool->nonce2off],
  8947. #else
  8948. &pool->nonce2,
  8949. #endif
  8950. pool->nonce2sz);
  8951. pool->nonce2++;
  8952. work->pool = pool;
  8953. work->work_restart_id = pool->swork.work_restart_id;
  8954. gen_stratum_work2(work, &pool->swork);
  8955. cgtime(&work->tv_staged);
  8956. }
  8957. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8958. {
  8959. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8960. uint8_t *merkle_bin;
  8961. uint32_t *data32, *swap32;
  8962. int i;
  8963. /* Generate coinbase */
  8964. coinbase = bytes_buf(&swork->coinbase);
  8965. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8966. /* Downgrade to a read lock to read off the variables */
  8967. if (swork->data_lock_p)
  8968. cg_dwlock(swork->data_lock_p);
  8969. /* Generate merkle root */
  8970. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8971. memcpy(merkle_sha, merkle_root, 32);
  8972. merkle_bin = bytes_buf(&swork->merkle_bin);
  8973. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8974. memcpy(merkle_sha + 32, merkle_bin, 32);
  8975. gen_hash(merkle_sha, merkle_root, 64);
  8976. memcpy(merkle_sha, merkle_root, 32);
  8977. }
  8978. data32 = (uint32_t *)merkle_sha;
  8979. swap32 = (uint32_t *)merkle_root;
  8980. flip32(swap32, data32);
  8981. memcpy(&work->data[0], swork->header1, 36);
  8982. memcpy(&work->data[36], merkle_root, 32);
  8983. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8984. memcpy(&work->data[72], swork->diffbits, 4);
  8985. memset(&work->data[76], 0, 4); // nonce
  8986. memcpy(&work->data[80], workpadding_bin, 48);
  8987. work->ntime_roll_limits = swork->ntime_roll_limits;
  8988. /* Copy parameters required for share submission */
  8989. memcpy(work->target, swork->target, sizeof(work->target));
  8990. work->job_id = maybe_strdup(swork->job_id);
  8991. work->nonce1 = maybe_strdup(swork->nonce1);
  8992. if (swork->data_lock_p)
  8993. cg_runlock(swork->data_lock_p);
  8994. if (opt_debug)
  8995. {
  8996. char header[161];
  8997. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8998. bin2hex(header, work->data, 80);
  8999. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  9000. applog(LOG_DEBUG, "Generated stratum header %s", header);
  9001. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  9002. }
  9003. calc_midstate(work);
  9004. local_work++;
  9005. work->stratum = true;
  9006. work->blk.nonce = 0;
  9007. work->id = total_work++;
  9008. work->longpoll = false;
  9009. work->getwork_mode = GETWORK_MODE_STRATUM;
  9010. calc_diff(work, 0);
  9011. }
  9012. void request_work(struct thr_info *thr)
  9013. {
  9014. struct cgpu_info *cgpu = thr->cgpu;
  9015. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9016. /* Tell the watchdog thread this thread is waiting on getwork and
  9017. * should not be restarted */
  9018. thread_reportout(thr);
  9019. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  9020. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9021. {
  9022. if (proc->threads)
  9023. break;
  9024. thread_reportout(proc->thr[0]);
  9025. }
  9026. cgtime(&dev_stats->_get_start);
  9027. }
  9028. // FIXME: Make this non-blocking (and remove HACK above)
  9029. struct work *get_work(struct thr_info *thr)
  9030. {
  9031. const int thr_id = thr->id;
  9032. struct cgpu_info *cgpu = thr->cgpu;
  9033. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9034. struct cgminer_stats *pool_stats;
  9035. struct timeval tv_get;
  9036. struct work *work = NULL;
  9037. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  9038. while (!work) {
  9039. work = hash_pop(cgpu);
  9040. if (stale_work(work, false)) {
  9041. staged_full = false; // It wasn't really full, since it was stale :(
  9042. discard_work(work);
  9043. work = NULL;
  9044. wake_gws();
  9045. }
  9046. }
  9047. last_getwork = time(NULL);
  9048. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  9049. cgpu->proc_repr, work->id, thr_id);
  9050. work->thr_id = thr_id;
  9051. thread_reportin(thr);
  9052. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  9053. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9054. {
  9055. if (proc->threads)
  9056. break;
  9057. thread_reportin(proc->thr[0]);
  9058. }
  9059. work->mined = true;
  9060. work->blk.nonce = 0;
  9061. cgtime(&tv_get);
  9062. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  9063. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  9064. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  9065. dev_stats->getwork_wait_max = tv_get;
  9066. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  9067. dev_stats->getwork_wait_min = tv_get;
  9068. ++dev_stats->getwork_calls;
  9069. pool_stats = &(work->pool->cgminer_stats);
  9070. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  9071. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  9072. pool_stats->getwork_wait_max = tv_get;
  9073. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  9074. pool_stats->getwork_wait_min = tv_get;
  9075. ++pool_stats->getwork_calls;
  9076. if (work->work_difficulty < 1)
  9077. {
  9078. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  9079. if (unlikely(work->work_difficulty < min_nonce_diff))
  9080. {
  9081. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  9082. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  9083. cgpu->proc_repr);
  9084. work->nonce_diff = min_nonce_diff;
  9085. }
  9086. else
  9087. work->nonce_diff = work->work_difficulty;
  9088. }
  9089. else
  9090. work->nonce_diff = 1;
  9091. return work;
  9092. }
  9093. struct dupe_hash_elem {
  9094. uint8_t hash[0x20];
  9095. struct timeval tv_prune;
  9096. UT_hash_handle hh;
  9097. };
  9098. static
  9099. void _submit_work_async(struct work *work)
  9100. {
  9101. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9102. if (opt_benchmark)
  9103. {
  9104. json_t * const jn = json_null(), *result = NULL;
  9105. work_check_for_block(work);
  9106. {
  9107. static struct dupe_hash_elem *dupe_hashes;
  9108. struct dupe_hash_elem *dhe, *dhetmp;
  9109. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9110. if (dhe)
  9111. result = json_string("duplicate");
  9112. else
  9113. {
  9114. struct timeval tv_now;
  9115. timer_set_now(&tv_now);
  9116. // Prune old entries
  9117. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9118. {
  9119. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9120. break;
  9121. HASH_DEL(dupe_hashes, dhe);
  9122. free(dhe);
  9123. }
  9124. dhe = malloc(sizeof(*dhe));
  9125. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9126. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9127. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9128. }
  9129. }
  9130. if (result)
  9131. {}
  9132. else
  9133. if (stale_work(work, true))
  9134. {
  9135. char stalemsg[0x10];
  9136. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9137. result = json_string(stalemsg);
  9138. }
  9139. else
  9140. result = json_incref(jn);
  9141. share_result(jn, result, jn, work, false, "");
  9142. free_work(work);
  9143. json_decref(result);
  9144. json_decref(jn);
  9145. return;
  9146. }
  9147. mutex_lock(&submitting_lock);
  9148. ++total_submitting;
  9149. DL_APPEND(submit_waiting, work);
  9150. mutex_unlock(&submitting_lock);
  9151. notifier_wake(submit_waiting_notifier);
  9152. }
  9153. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9154. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9155. {
  9156. if (tv_work_found)
  9157. copy_time(&work->tv_work_found, tv_work_found);
  9158. _submit_work_async(work);
  9159. }
  9160. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9161. {
  9162. struct cgpu_info * const cgpu = thr->cgpu;
  9163. if (bad_nonce_p)
  9164. {
  9165. if (bad_nonce_p == UNKNOWN_NONCE)
  9166. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9167. cgpu->proc_repr);
  9168. else
  9169. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9170. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9171. }
  9172. mutex_lock(&stats_lock);
  9173. hw_errors++;
  9174. ++cgpu->hw_errors;
  9175. if (bad_nonce_p)
  9176. {
  9177. total_bad_diff1 += nonce_diff;
  9178. cgpu->bad_diff1 += nonce_diff;
  9179. }
  9180. mutex_unlock(&stats_lock);
  9181. if (thr->cgpu->drv->hw_error)
  9182. thr->cgpu->drv->hw_error(thr);
  9183. }
  9184. void work_hash(struct work * const work)
  9185. {
  9186. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9187. malgo->hash_data_f(work->hash, work->data);
  9188. }
  9189. static
  9190. bool test_hash(const void * const phash, const float diff)
  9191. {
  9192. const uint32_t * const hash = phash;
  9193. if (diff >= 1.)
  9194. // FIXME: > 1 should check more
  9195. return !hash[7];
  9196. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9197. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9198. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9199. (long unsigned int)Htarg,
  9200. (long unsigned int)tmp_hash7);
  9201. return (tmp_hash7 <= Htarg);
  9202. }
  9203. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9204. {
  9205. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9206. *work_nonce = htole32(nonce);
  9207. work_hash(work);
  9208. if (!test_hash(work->hash, work->nonce_diff))
  9209. return TNR_BAD;
  9210. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9211. {
  9212. bool high_hash = true;
  9213. struct pool * const pool = work->pool;
  9214. if (pool->stratum_active)
  9215. {
  9216. // 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
  9217. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9218. {
  9219. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9220. pool->pool_no);
  9221. if (hash_target_check_v(work->hash, pool->next_target))
  9222. high_hash = false;
  9223. }
  9224. }
  9225. if (high_hash)
  9226. return TNR_HIGH;
  9227. }
  9228. return TNR_GOOD;
  9229. }
  9230. /* Returns true if nonce for work was a valid share */
  9231. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9232. {
  9233. return submit_noffset_nonce(thr, work, nonce, 0);
  9234. }
  9235. /* Allows drivers to submit work items where the driver has changed the ntime
  9236. * value by noffset. Must be only used with a work protocol that does not ntime
  9237. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9238. * the original work struct, but the copy of it only. */
  9239. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9240. int noffset)
  9241. {
  9242. struct work *work = make_work();
  9243. _copy_work(work, work_in, noffset);
  9244. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9245. struct timeval tv_work_found;
  9246. enum test_nonce2_result res;
  9247. bool ret = true;
  9248. thread_reportout(thr);
  9249. cgtime(&tv_work_found);
  9250. *work_nonce = htole32(nonce);
  9251. work->thr_id = thr->id;
  9252. /* Do one last check before attempting to submit the work */
  9253. /* Side effect: sets work->data and work->hash for us */
  9254. res = test_nonce2(work, nonce);
  9255. if (unlikely(res == TNR_BAD))
  9256. {
  9257. inc_hw_errors(thr, work, nonce);
  9258. ret = false;
  9259. goto out;
  9260. }
  9261. mutex_lock(&stats_lock);
  9262. total_diff1 += work->nonce_diff;
  9263. thr ->cgpu->diff1 += work->nonce_diff;
  9264. work->pool->diff1 += work->nonce_diff;
  9265. thr->cgpu->last_device_valid_work = time(NULL);
  9266. mutex_unlock(&stats_lock);
  9267. if (noncelog_file)
  9268. noncelog(work);
  9269. if (res == TNR_HIGH)
  9270. {
  9271. // Share above target, normal
  9272. /* Check the diff of the share, even if it didn't reach the
  9273. * target, just to set the best share value if it's higher. */
  9274. share_diff(work);
  9275. goto out;
  9276. }
  9277. submit_work_async2(work, &tv_work_found);
  9278. work = NULL; // Taken by submit_work_async2
  9279. out:
  9280. if (work)
  9281. free_work(work);
  9282. thread_reportin(thr);
  9283. return ret;
  9284. }
  9285. // return true of we should stop working on this piece of work
  9286. // returning false means we will keep scanning for a nonce
  9287. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9288. // see minerloop_scanhash comments for more details & usage
  9289. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9290. {
  9291. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9292. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9293. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9294. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9295. stale_work(work, false)) // work is stale
  9296. return true;
  9297. return false;
  9298. }
  9299. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9300. {
  9301. struct cgpu_info *proc = thr->cgpu;
  9302. if (proc->threads > 1)
  9303. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9304. else
  9305. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9306. }
  9307. // Called by asynchronous minerloops, when they find their processor should be disabled
  9308. void mt_disable_start(struct thr_info *mythr)
  9309. {
  9310. struct cgpu_info *cgpu = mythr->cgpu;
  9311. struct device_drv *drv = cgpu->drv;
  9312. if (drv->thread_disable)
  9313. drv->thread_disable(mythr);
  9314. hashmeter2(mythr);
  9315. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9316. mythr->rolling = mythr->cgpu->rolling = 0;
  9317. thread_reportout(mythr);
  9318. mythr->_mt_disable_called = true;
  9319. }
  9320. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9321. * the driver tells us it's full so that it may extract the work item using
  9322. * the get_queued() function which adds it to the hashtable on
  9323. * cgpu->queued_work. */
  9324. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9325. {
  9326. thread_reportout(mythr);
  9327. do {
  9328. bool need_work;
  9329. /* Do this lockless just to know if we need more unqueued work. */
  9330. need_work = (!cgpu->unqueued_work);
  9331. /* get_work is a blocking function so do it outside of lock
  9332. * to prevent deadlocks with other locks. */
  9333. if (need_work) {
  9334. struct work *work = get_work(mythr);
  9335. wr_lock(&cgpu->qlock);
  9336. /* Check we haven't grabbed work somehow between
  9337. * checking and picking up the lock. */
  9338. if (likely(!cgpu->unqueued_work))
  9339. cgpu->unqueued_work = work;
  9340. else
  9341. need_work = false;
  9342. wr_unlock(&cgpu->qlock);
  9343. if (unlikely(!need_work))
  9344. discard_work(work);
  9345. }
  9346. /* The queue_full function should be used by the driver to
  9347. * actually place work items on the physical device if it
  9348. * does have a queue. */
  9349. } while (drv->queue_full && !drv->queue_full(cgpu));
  9350. }
  9351. /* Add a work item to a cgpu's queued hashlist */
  9352. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9353. {
  9354. cgpu->queued_count++;
  9355. HASH_ADD_INT(cgpu->queued_work, id, work);
  9356. }
  9357. /* This function is for retrieving one work item from the unqueued pointer and
  9358. * adding it to the hashtable of queued work. Code using this function must be
  9359. * able to handle NULL as a return which implies there is no work available. */
  9360. struct work *get_queued(struct cgpu_info *cgpu)
  9361. {
  9362. struct work *work = NULL;
  9363. wr_lock(&cgpu->qlock);
  9364. if (cgpu->unqueued_work) {
  9365. work = cgpu->unqueued_work;
  9366. if (unlikely(stale_work(work, false))) {
  9367. discard_work(work);
  9368. work = NULL;
  9369. wake_gws();
  9370. } else
  9371. __add_queued(cgpu, work);
  9372. cgpu->unqueued_work = NULL;
  9373. }
  9374. wr_unlock(&cgpu->qlock);
  9375. return work;
  9376. }
  9377. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9378. {
  9379. wr_lock(&cgpu->qlock);
  9380. __add_queued(cgpu, work);
  9381. wr_unlock(&cgpu->qlock);
  9382. }
  9383. /* Get fresh work and add it to cgpu's queued hashlist */
  9384. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9385. {
  9386. struct work *work = get_work(thr);
  9387. add_queued(cgpu, work);
  9388. return work;
  9389. }
  9390. /* This function is for finding an already queued work item in the
  9391. * given que hashtable. Code using this function must be able
  9392. * to handle NULL as a return which implies there is no matching work.
  9393. * The calling function must lock access to the que if it is required.
  9394. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9395. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9396. {
  9397. struct work *work, *tmp, *ret = NULL;
  9398. HASH_ITER(hh, que, work, tmp) {
  9399. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9400. memcmp(work->data + offset, data, datalen) == 0) {
  9401. ret = work;
  9402. break;
  9403. }
  9404. }
  9405. return ret;
  9406. }
  9407. /* This function is for finding an already queued work item in the
  9408. * device's queued_work hashtable. Code using this function must be able
  9409. * to handle NULL as a return which implies there is no matching work.
  9410. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9411. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9412. {
  9413. struct work *ret;
  9414. rd_lock(&cgpu->qlock);
  9415. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9416. rd_unlock(&cgpu->qlock);
  9417. return ret;
  9418. }
  9419. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9420. {
  9421. struct work *work, *ret = NULL;
  9422. rd_lock(&cgpu->qlock);
  9423. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9424. if (work)
  9425. ret = copy_work(work);
  9426. rd_unlock(&cgpu->qlock);
  9427. return ret;
  9428. }
  9429. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9430. {
  9431. cgpu->queued_count--;
  9432. HASH_DEL(cgpu->queued_work, work);
  9433. }
  9434. /* This iterates over a queued hashlist finding work started more than secs
  9435. * seconds ago and discards the work as completed. The driver must set the
  9436. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9437. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9438. {
  9439. struct work *work, *tmp;
  9440. struct timeval tv_now;
  9441. int aged = 0;
  9442. cgtime(&tv_now);
  9443. wr_lock(&cgpu->qlock);
  9444. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9445. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9446. __work_completed(cgpu, work);
  9447. aged++;
  9448. }
  9449. }
  9450. wr_unlock(&cgpu->qlock);
  9451. return aged;
  9452. }
  9453. /* This function should be used by queued device drivers when they're sure
  9454. * the work struct is no longer in use. */
  9455. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9456. {
  9457. wr_lock(&cgpu->qlock);
  9458. __work_completed(cgpu, work);
  9459. wr_unlock(&cgpu->qlock);
  9460. free_work(work);
  9461. }
  9462. /* Combines find_queued_work_bymidstate and work_completed in one function
  9463. * withOUT destroying the work so the driver must free it. */
  9464. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9465. {
  9466. struct work *work;
  9467. wr_lock(&cgpu->qlock);
  9468. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9469. if (work)
  9470. __work_completed(cgpu, work);
  9471. wr_unlock(&cgpu->qlock);
  9472. return work;
  9473. }
  9474. void flush_queue(struct cgpu_info *cgpu)
  9475. {
  9476. struct work *work = NULL;
  9477. wr_lock(&cgpu->qlock);
  9478. work = cgpu->unqueued_work;
  9479. cgpu->unqueued_work = NULL;
  9480. wr_unlock(&cgpu->qlock);
  9481. if (work) {
  9482. free_work(work);
  9483. applog(LOG_DEBUG, "Discarded queued work item");
  9484. }
  9485. }
  9486. /* This version of hash work is for devices that are fast enough to always
  9487. * perform a full nonce range and need a queue to maintain the device busy.
  9488. * Work creation and destruction is not done from within this function
  9489. * directly. */
  9490. void hash_queued_work(struct thr_info *mythr)
  9491. {
  9492. const long cycle = opt_log_interval / 5 ? : 1;
  9493. struct timeval tv_start = {0, 0}, tv_end;
  9494. struct cgpu_info *cgpu = mythr->cgpu;
  9495. struct device_drv *drv = cgpu->drv;
  9496. const int thr_id = mythr->id;
  9497. int64_t hashes_done = 0;
  9498. if (unlikely(cgpu->deven != DEV_ENABLED))
  9499. mt_disable(mythr);
  9500. while (likely(!cgpu->shutdown)) {
  9501. struct timeval diff;
  9502. int64_t hashes;
  9503. fill_queue(mythr, cgpu, drv, thr_id);
  9504. thread_reportin(mythr);
  9505. hashes = drv->scanwork(mythr);
  9506. /* Reset the bool here in case the driver looks for it
  9507. * synchronously in the scanwork loop. */
  9508. mythr->work_restart = false;
  9509. if (unlikely(hashes == -1 )) {
  9510. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9511. cgpu->deven = DEV_DISABLED;
  9512. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9513. mt_disable(mythr);
  9514. }
  9515. hashes_done += hashes;
  9516. cgtime(&tv_end);
  9517. timersub(&tv_end, &tv_start, &diff);
  9518. if (diff.tv_sec >= cycle) {
  9519. hashmeter(thr_id, &diff, hashes_done);
  9520. hashes_done = 0;
  9521. copy_time(&tv_start, &tv_end);
  9522. }
  9523. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9524. mt_disable(mythr);
  9525. if (unlikely(mythr->work_restart)) {
  9526. flush_queue(cgpu);
  9527. if (drv->flush_work)
  9528. drv->flush_work(cgpu);
  9529. }
  9530. }
  9531. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9532. }
  9533. // Called by minerloop, when it is re-enabling a processor
  9534. void mt_disable_finish(struct thr_info *mythr)
  9535. {
  9536. struct device_drv *drv = mythr->cgpu->drv;
  9537. thread_reportin(mythr);
  9538. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9539. if (drv->thread_enable)
  9540. drv->thread_enable(mythr);
  9541. mythr->_mt_disable_called = false;
  9542. }
  9543. // Called by synchronous minerloops, when they find their processor should be disabled
  9544. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9545. void mt_disable(struct thr_info *mythr)
  9546. {
  9547. const struct cgpu_info * const cgpu = mythr->cgpu;
  9548. mt_disable_start(mythr);
  9549. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9550. do {
  9551. notifier_read(mythr->notifier);
  9552. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9553. mt_disable_finish(mythr);
  9554. }
  9555. enum {
  9556. STAT_SLEEP_INTERVAL = 1,
  9557. STAT_CTR_INTERVAL = 10000000,
  9558. FAILURE_INTERVAL = 30,
  9559. };
  9560. /* Stage another work item from the work returned in a longpoll */
  9561. 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)
  9562. {
  9563. bool rc;
  9564. work->rolltime = rolltime;
  9565. rc = work_decode(pool, work, val);
  9566. if (unlikely(!rc)) {
  9567. applog(LOG_ERR, "Could not convert longpoll data to work");
  9568. free_work(work);
  9569. return;
  9570. }
  9571. total_getworks++;
  9572. pool->getwork_requested++;
  9573. work->pool = pool;
  9574. copy_time(&work->tv_getwork, tv_lp);
  9575. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9576. calc_diff(work, 0);
  9577. if (pool->enabled == POOL_REJECTING)
  9578. work->mandatory = true;
  9579. work->longpoll = true;
  9580. work->getwork_mode = GETWORK_MODE_LP;
  9581. update_last_work(work);
  9582. /* We'll be checking this work item twice, but we already know it's
  9583. * from a new block so explicitly force the new block detection now
  9584. * rather than waiting for it to hit the stage thread. This also
  9585. * allows testwork to know whether LP discovered the block or not. */
  9586. test_work_current(work);
  9587. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9588. * the longpoll work from a pool that has been rejecting shares as a
  9589. * way to detect when the pool has recovered.
  9590. */
  9591. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9592. free_work(work);
  9593. return;
  9594. }
  9595. work = clone_work(work);
  9596. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9597. stage_work(work);
  9598. applog(LOG_DEBUG, "Converted longpoll data to work");
  9599. }
  9600. /* If we want longpoll, enable it for the chosen default pool, or, if
  9601. * the pool does not support longpoll, find the first one that does
  9602. * and use its longpoll support */
  9603. static
  9604. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9605. {
  9606. int i;
  9607. if (func(cp))
  9608. return cp;
  9609. for (i = 0; i < total_pools; i++) {
  9610. struct pool *pool = pools[i];
  9611. if (cp->goal != pool->goal)
  9612. continue;
  9613. if (func(pool))
  9614. return pool;
  9615. }
  9616. return NULL;
  9617. }
  9618. /* This will make the longpoll thread wait till it's the current pool, or it
  9619. * has been flagged as rejecting, before attempting to open any connections.
  9620. */
  9621. static void wait_lpcurrent(struct pool *pool)
  9622. {
  9623. mutex_lock(&lp_lock);
  9624. while (!cnx_needed(pool))
  9625. {
  9626. pool->lp_active = false;
  9627. pthread_cond_wait(&lp_cond, &lp_lock);
  9628. }
  9629. mutex_unlock(&lp_lock);
  9630. }
  9631. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9632. struct pool *pool = vpool;
  9633. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9634. pool->lp_socket = sock;
  9635. return sock;
  9636. }
  9637. static void *longpoll_thread(void *userdata)
  9638. {
  9639. struct pool *cp = (struct pool *)userdata;
  9640. /* This *pool is the source of the actual longpoll, not the pool we've
  9641. * tied it to */
  9642. struct timeval start, reply, end;
  9643. struct pool *pool = NULL;
  9644. char threadname[20];
  9645. CURL *curl = NULL;
  9646. int failures = 0;
  9647. char *lp_url;
  9648. int rolltime;
  9649. #ifndef HAVE_PTHREAD_CANCEL
  9650. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9651. #endif
  9652. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9653. RenameThread(threadname);
  9654. curl = curl_easy_init();
  9655. if (unlikely(!curl)) {
  9656. applog(LOG_ERR, "CURL initialisation failed");
  9657. return NULL;
  9658. }
  9659. retry_pool:
  9660. pool = select_longpoll_pool(cp);
  9661. if (!pool) {
  9662. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9663. while (!pool) {
  9664. cgsleep_ms(60000);
  9665. pool = select_longpoll_pool(cp);
  9666. }
  9667. }
  9668. if (pool->has_stratum) {
  9669. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9670. cp->rpc_url, pool->rpc_url);
  9671. goto out;
  9672. }
  9673. /* Any longpoll from any pool is enough for this to be true */
  9674. pool->goal->have_longpoll = true;
  9675. wait_lpcurrent(cp);
  9676. {
  9677. lp_url = pool->lp_url;
  9678. if (cp == pool)
  9679. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9680. else
  9681. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9682. }
  9683. while (42) {
  9684. json_t *val, *soval;
  9685. struct work *work = make_work();
  9686. char *lpreq;
  9687. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9688. work->pool = pool;
  9689. if (!lpreq)
  9690. {
  9691. free_work(work);
  9692. goto lpfail;
  9693. }
  9694. wait_lpcurrent(cp);
  9695. cgtime(&start);
  9696. /* Longpoll connections can be persistent for a very long time
  9697. * and any number of issues could have come up in the meantime
  9698. * so always establish a fresh connection instead of relying on
  9699. * a persistent one. */
  9700. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9701. curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);
  9702. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9703. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9704. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9705. lpreq, false, true, &rolltime, pool, false);
  9706. pool->lp_socket = CURL_SOCKET_BAD;
  9707. cgtime(&reply);
  9708. free(lpreq);
  9709. if (likely(val)) {
  9710. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9711. if (soval)
  9712. pool->submit_old = json_is_true(soval);
  9713. else
  9714. pool->submit_old = false;
  9715. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9716. failures = 0;
  9717. json_decref(val);
  9718. } else {
  9719. /* Some pools regularly drop the longpoll request so
  9720. * only see this as longpoll failure if it happens
  9721. * immediately and just restart it the rest of the
  9722. * time. */
  9723. cgtime(&end);
  9724. free_work(work);
  9725. if (end.tv_sec - start.tv_sec <= 30)
  9726. {
  9727. if (failures == 1)
  9728. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9729. lpfail:
  9730. cgsleep_ms(30000);
  9731. }
  9732. }
  9733. if (pool != cp) {
  9734. pool = select_longpoll_pool(cp);
  9735. if (pool->has_stratum) {
  9736. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9737. cp->rpc_url, pool->rpc_url);
  9738. break;
  9739. }
  9740. if (unlikely(!pool))
  9741. goto retry_pool;
  9742. }
  9743. if (unlikely(pool->removed))
  9744. break;
  9745. }
  9746. out:
  9747. pool->lp_active = false;
  9748. curl_easy_cleanup(curl);
  9749. return NULL;
  9750. }
  9751. static void stop_longpoll(void)
  9752. {
  9753. int i;
  9754. want_longpoll = false;
  9755. for (i = 0; i < total_pools; ++i)
  9756. {
  9757. struct pool *pool = pools[i];
  9758. if (unlikely(!pool->lp_started))
  9759. continue;
  9760. pool->lp_started = false;
  9761. pthread_cancel(pool->longpoll_thread);
  9762. }
  9763. struct mining_goal_info *goal, *tmpgoal;
  9764. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9765. {
  9766. goal->have_longpoll = false;
  9767. }
  9768. }
  9769. static void start_longpoll(void)
  9770. {
  9771. int i;
  9772. want_longpoll = true;
  9773. for (i = 0; i < total_pools; ++i)
  9774. {
  9775. struct pool *pool = pools[i];
  9776. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9777. continue;
  9778. pool->lp_started = true;
  9779. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9780. quit(1, "Failed to create pool longpoll thread");
  9781. }
  9782. }
  9783. void reinit_device(struct cgpu_info *cgpu)
  9784. {
  9785. if (cgpu->drv->reinit_device)
  9786. cgpu->drv->reinit_device(cgpu);
  9787. }
  9788. static struct timeval rotate_tv;
  9789. /* We reap curls if they are unused for over a minute */
  9790. static void reap_curl(struct pool *pool)
  9791. {
  9792. struct curl_ent *ent, *iter;
  9793. struct timeval now;
  9794. int reaped = 0;
  9795. cgtime(&now);
  9796. mutex_lock(&pool->pool_lock);
  9797. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9798. if (pool->curls < 2)
  9799. break;
  9800. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9801. reaped++;
  9802. pool->curls--;
  9803. LL_DELETE(pool->curllist, ent);
  9804. curl_easy_cleanup(ent->curl);
  9805. free(ent);
  9806. }
  9807. }
  9808. mutex_unlock(&pool->pool_lock);
  9809. if (reaped)
  9810. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9811. }
  9812. static void *watchpool_thread(void __maybe_unused *userdata)
  9813. {
  9814. int intervals = 0;
  9815. #ifndef HAVE_PTHREAD_CANCEL
  9816. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9817. #endif
  9818. RenameThread("watchpool");
  9819. while (42) {
  9820. struct timeval now;
  9821. int i;
  9822. if (++intervals > 20)
  9823. intervals = 0;
  9824. cgtime(&now);
  9825. for (i = 0; i < total_pools; i++) {
  9826. struct pool *pool = pools[i];
  9827. if (!opt_benchmark)
  9828. reap_curl(pool);
  9829. /* Get a rolling utility per pool over 10 mins */
  9830. if (intervals > 19) {
  9831. int shares = pool->diff1 - pool->last_shares;
  9832. pool->last_shares = pool->diff1;
  9833. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9834. pool->shares = pool->utility;
  9835. }
  9836. if (pool->enabled == POOL_DISABLED)
  9837. continue;
  9838. /* Don't start testing any pools if the test threads
  9839. * from startup are still doing their first attempt. */
  9840. if (unlikely(pool->testing)) {
  9841. pthread_join(pool->test_thread, NULL);
  9842. }
  9843. /* Test pool is idle once every minute */
  9844. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9845. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9846. pool_resus(pool);
  9847. }
  9848. /* Only switch pools if the failback pool has been
  9849. * alive for more than 5 minutes (default) to prevent
  9850. * intermittently failing pools from being used. */
  9851. 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)
  9852. {
  9853. if (opt_fail_switch_delay % 60)
  9854. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9855. pool->pool_no, pool->rpc_url,
  9856. opt_fail_switch_delay,
  9857. (opt_fail_switch_delay == 1 ? "" : "s"));
  9858. else
  9859. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9860. pool->pool_no, pool->rpc_url,
  9861. opt_fail_switch_delay / 60,
  9862. (opt_fail_switch_delay == 60 ? "" : "s"));
  9863. switch_pools(NULL);
  9864. }
  9865. }
  9866. if (current_pool()->idle)
  9867. switch_pools(NULL);
  9868. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9869. cgtime(&rotate_tv);
  9870. switch_pools(NULL);
  9871. }
  9872. cgsleep_ms(30000);
  9873. }
  9874. return NULL;
  9875. }
  9876. void mt_enable(struct thr_info *thr)
  9877. {
  9878. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9879. notifier_wake(thr->notifier);
  9880. }
  9881. void proc_enable(struct cgpu_info *cgpu)
  9882. {
  9883. int j;
  9884. cgpu->deven = DEV_ENABLED;
  9885. for (j = cgpu->threads ?: 1; j--; )
  9886. mt_enable(cgpu->thr[j]);
  9887. }
  9888. #define device_recovered(cgpu) proc_enable(cgpu)
  9889. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9890. {
  9891. struct string_elist *setstr_elist;
  9892. const char *p, *p2;
  9893. char replybuf[0x2000];
  9894. size_t L;
  9895. DL_FOREACH(opt_set_device_list, setstr_elist)
  9896. {
  9897. const char * const setstr = setstr_elist->string;
  9898. p = strchr(setstr, ':');
  9899. if (!p)
  9900. p = setstr;
  9901. {
  9902. L = p - setstr;
  9903. char pattern[L + 1];
  9904. if (L)
  9905. memcpy(pattern, setstr, L);
  9906. pattern[L] = '\0';
  9907. if (!cgpu_match(pattern, cgpu))
  9908. continue;
  9909. }
  9910. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9911. cgpu->proc_repr, __func__, setstr);
  9912. if (p[0] == ':')
  9913. ++p;
  9914. p2 = strchr(p, '=');
  9915. if (!p2)
  9916. {
  9917. L = strlen(p);
  9918. p2 = "";
  9919. }
  9920. else
  9921. {
  9922. L = p2 - p;
  9923. ++p2;
  9924. }
  9925. char opt[L + 1];
  9926. if (L)
  9927. memcpy(opt, p, L);
  9928. opt[L] = '\0';
  9929. L = strlen(p2);
  9930. char setval[L + 1];
  9931. if (L)
  9932. memcpy(setval, p2, L);
  9933. setval[L] = '\0';
  9934. enum bfg_set_device_replytype success;
  9935. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9936. switch (success)
  9937. {
  9938. case SDR_OK:
  9939. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9940. cgpu->proc_repr, setstr,
  9941. p ? ": " : "", p ?: "");
  9942. break;
  9943. case SDR_ERR:
  9944. case SDR_HELP:
  9945. case SDR_UNKNOWN:
  9946. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9947. cgpu->proc_repr, setstr, p);
  9948. break;
  9949. case SDR_AUTO:
  9950. case SDR_NOSUPP:
  9951. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9952. cgpu->proc_repr, setstr);
  9953. }
  9954. }
  9955. cgpu->already_set_defaults = true;
  9956. }
  9957. 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)
  9958. {
  9959. struct device_drv dummy_drv = *drv;
  9960. struct cgpu_info dummy_cgpu = {
  9961. .drv = &dummy_drv,
  9962. .device = &dummy_cgpu,
  9963. .device_id = -1,
  9964. .proc_id = -1,
  9965. .device_data = userp,
  9966. .device_path = devpath,
  9967. .dev_serial = serial,
  9968. };
  9969. strcpy(dummy_cgpu.proc_repr, drv->name);
  9970. switch (mode)
  9971. {
  9972. case 0:
  9973. dummy_drv.set_device = datap;
  9974. break;
  9975. case 1:
  9976. dummy_drv.set_device = NULL;
  9977. dummy_cgpu.set_device_funcs = datap;
  9978. break;
  9979. }
  9980. cgpu_set_defaults(&dummy_cgpu);
  9981. }
  9982. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9983. * the screen at regular intervals, and restarts threads if they appear to have
  9984. * died. */
  9985. #define WATCHDOG_SICK_TIME 60
  9986. #define WATCHDOG_DEAD_TIME 600
  9987. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9988. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9989. static void *watchdog_thread(void __maybe_unused *userdata)
  9990. {
  9991. const unsigned int interval = WATCHDOG_INTERVAL;
  9992. struct timeval zero_tv;
  9993. #ifndef HAVE_PTHREAD_CANCEL
  9994. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9995. #endif
  9996. RenameThread("watchdog");
  9997. memset(&zero_tv, 0, sizeof(struct timeval));
  9998. cgtime(&rotate_tv);
  9999. while (1) {
  10000. int i;
  10001. struct timeval now;
  10002. sleep(interval);
  10003. discard_stale();
  10004. hashmeter(-1, &zero_tv, 0);
  10005. #ifdef HAVE_CURSES
  10006. const int ts = total_staged(true);
  10007. if (curses_active_locked()) {
  10008. change_logwinsize();
  10009. curses_print_status(ts);
  10010. _refresh_devstatus(true);
  10011. touchwin(logwin);
  10012. wrefresh(logwin);
  10013. unlock_curses();
  10014. }
  10015. #endif
  10016. cgtime(&now);
  10017. if (!sched_paused && !should_run()) {
  10018. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  10019. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10020. if (!schedstart.enable) {
  10021. quit(0, "Terminating execution as planned");
  10022. break;
  10023. }
  10024. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  10025. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10026. sched_paused = true;
  10027. rd_lock(&mining_thr_lock);
  10028. for (i = 0; i < mining_threads; i++)
  10029. mining_thr[i]->pause = true;
  10030. rd_unlock(&mining_thr_lock);
  10031. } else if (sched_paused && should_run()) {
  10032. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  10033. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10034. if (schedstop.enable)
  10035. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  10036. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10037. sched_paused = false;
  10038. for (i = 0; i < mining_threads; i++) {
  10039. struct thr_info *thr;
  10040. thr = get_thread(i);
  10041. thr->pause = false;
  10042. }
  10043. for (i = 0; i < total_devices; ++i)
  10044. {
  10045. struct cgpu_info *cgpu = get_devices(i);
  10046. /* Don't touch disabled devices */
  10047. if (cgpu->deven == DEV_DISABLED)
  10048. continue;
  10049. proc_enable(cgpu);
  10050. }
  10051. }
  10052. for (i = 0; i < total_devices; ++i) {
  10053. struct cgpu_info *cgpu = get_devices(i);
  10054. if (!cgpu->disable_watchdog)
  10055. bfg_watchdog(cgpu, &now);
  10056. }
  10057. }
  10058. return NULL;
  10059. }
  10060. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  10061. {
  10062. struct thr_info *thr = cgpu->thr[0];
  10063. enum dev_enable *denable;
  10064. char *dev_str = cgpu->proc_repr;
  10065. if (likely(drv_ready(cgpu)))
  10066. {
  10067. if (unlikely(!cgpu->already_set_defaults))
  10068. cgpu_set_defaults(cgpu);
  10069. if (cgpu->drv->get_stats)
  10070. cgpu->drv->get_stats(cgpu);
  10071. }
  10072. denable = &cgpu->deven;
  10073. if (cgpu->drv->watchdog)
  10074. cgpu->drv->watchdog(cgpu, tvp_now);
  10075. /* Thread is disabled */
  10076. if (*denable == DEV_DISABLED)
  10077. return;
  10078. else
  10079. if (*denable == DEV_RECOVER_ERR) {
  10080. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  10081. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  10082. dev_str);
  10083. if (cgpu->reinit_backoff < 300)
  10084. cgpu->reinit_backoff *= 2;
  10085. device_recovered(cgpu);
  10086. }
  10087. return;
  10088. }
  10089. else
  10090. if (*denable == DEV_RECOVER) {
  10091. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10092. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10093. dev_str);
  10094. device_recovered(cgpu);
  10095. }
  10096. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10097. return;
  10098. }
  10099. else
  10100. if (cgpu->temp > cgpu->cutofftemp)
  10101. {
  10102. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10103. dev_str, (int)cgpu->temp);
  10104. *denable = DEV_RECOVER;
  10105. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10106. run_cmd(cmd_idle);
  10107. }
  10108. if (thr->getwork) {
  10109. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10110. int thrid;
  10111. bool cgpu_idle = true;
  10112. thr->rolling = 0;
  10113. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10114. if (!cgpu->thr[thrid]->getwork)
  10115. cgpu_idle = false;
  10116. if (cgpu_idle) {
  10117. cgpu->rolling = 0;
  10118. cgpu->status = LIFE_WAIT;
  10119. }
  10120. }
  10121. return;
  10122. }
  10123. else if (cgpu->status == LIFE_WAIT)
  10124. cgpu->status = LIFE_WELL;
  10125. #ifdef USE_CPUMINING
  10126. if (!strcmp(cgpu->drv->dname, "cpu"))
  10127. return;
  10128. #endif
  10129. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10130. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10131. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10132. cgpu->status = LIFE_WELL;
  10133. cgpu->device_last_well = time(NULL);
  10134. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10135. thr->rolling = cgpu->rolling = 0;
  10136. cgpu->status = LIFE_SICK;
  10137. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10138. cgtime(&thr->sick);
  10139. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10140. run_cmd(cmd_sick);
  10141. if (opt_restart && cgpu->drv->reinit_device) {
  10142. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10143. reinit_device(cgpu);
  10144. }
  10145. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10146. cgpu->status = LIFE_DEAD;
  10147. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10148. cgtime(&thr->sick);
  10149. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10150. run_cmd(cmd_dead);
  10151. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10152. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10153. /* Attempt to restart a GPU that's sick or dead once every minute */
  10154. cgtime(&thr->sick);
  10155. if (opt_restart)
  10156. reinit_device(cgpu);
  10157. }
  10158. }
  10159. static void log_print_status(struct cgpu_info *cgpu)
  10160. {
  10161. char logline[255];
  10162. get_statline(logline, sizeof(logline), cgpu);
  10163. applog(LOG_WARNING, "%s", logline);
  10164. }
  10165. void print_summary(void)
  10166. {
  10167. struct timeval diff;
  10168. int hours, mins, secs, i;
  10169. double utility, efficiency = 0.0;
  10170. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10171. int pool_secs;
  10172. timersub(&total_tv_end, &total_tv_start, &diff);
  10173. hours = diff.tv_sec / 3600;
  10174. mins = (diff.tv_sec % 3600) / 60;
  10175. secs = diff.tv_sec % 60;
  10176. utility = total_accepted / total_secs * 60;
  10177. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10178. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10179. applog(LOG_WARNING, "Started at %s", datestamp);
  10180. if (total_pools == 1)
  10181. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10182. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  10183. if (opt_n_threads > 0)
  10184. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10185. #endif
  10186. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10187. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10188. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10189. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10190. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10191. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10192. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10193. total_rejected, total_stale,
  10194. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10195. );
  10196. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10197. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10198. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10199. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10200. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10201. (float)total_bytes_rcvd,
  10202. (float)total_bytes_sent),
  10203. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10204. (float)(total_bytes_rcvd / total_secs),
  10205. (float)(total_bytes_sent / total_secs)));
  10206. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10207. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10208. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10209. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10210. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10211. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10212. if (total_pools > 1) {
  10213. for (i = 0; i < total_pools; i++) {
  10214. struct pool *pool = pools[i];
  10215. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10216. if (pool->solved)
  10217. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10218. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10219. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10220. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10221. pool->rejected, pool->stale_shares,
  10222. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10223. );
  10224. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10225. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10226. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10227. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10228. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10229. (float)pool->cgminer_pool_stats.net_bytes_received,
  10230. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10231. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10232. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10233. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10234. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10235. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10236. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10237. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10238. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10239. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10240. }
  10241. }
  10242. if (opt_quit_summary != BQS_NONE)
  10243. {
  10244. if (opt_quit_summary == BQS_DEFAULT)
  10245. {
  10246. if (total_devices < 25)
  10247. opt_quit_summary = BQS_PROCS;
  10248. else
  10249. opt_quit_summary = BQS_DEVS;
  10250. }
  10251. if (opt_quit_summary == BQS_DETAILED)
  10252. include_serial_in_statline = true;
  10253. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10254. for (i = 0; i < total_devices; ++i) {
  10255. struct cgpu_info *cgpu = get_devices(i);
  10256. if (!cgpu->proc_id)
  10257. {
  10258. // Device summary line
  10259. opt_show_procs = false;
  10260. log_print_status(cgpu);
  10261. opt_show_procs = true;
  10262. }
  10263. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10264. log_print_status(cgpu);
  10265. }
  10266. }
  10267. if (opt_shares) {
  10268. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10269. if (opt_shares > total_diff_accepted)
  10270. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10271. }
  10272. applog(LOG_WARNING, " ");
  10273. fflush(stderr);
  10274. fflush(stdout);
  10275. }
  10276. void _bfg_clean_up(bool restarting)
  10277. {
  10278. #ifdef USE_OPENCL
  10279. clear_adl(nDevs);
  10280. #endif
  10281. #ifdef HAVE_LIBUSB
  10282. if (likely(have_libusb))
  10283. libusb_exit(NULL);
  10284. #endif
  10285. cgtime(&total_tv_end);
  10286. #ifdef WIN32
  10287. timeEndPeriod(1);
  10288. #endif
  10289. if (!restarting) {
  10290. /* Attempting to disable curses or print a summary during a
  10291. * restart can lead to a deadlock. */
  10292. #ifdef HAVE_CURSES
  10293. disable_curses();
  10294. #endif
  10295. if (!opt_realquiet && successful_connect)
  10296. print_summary();
  10297. }
  10298. if (opt_n_threads > 0)
  10299. free(cpus);
  10300. curl_global_cleanup();
  10301. #ifdef WIN32
  10302. WSACleanup();
  10303. #endif
  10304. }
  10305. void _quit(int status)
  10306. {
  10307. if (status) {
  10308. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10309. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10310. int *p = NULL;
  10311. // NOTE debugger can bypass with: p = &p
  10312. *p = status; // Segfault, hopefully dumping core
  10313. }
  10314. }
  10315. #if defined(unix) || defined(__APPLE__)
  10316. if (forkpid > 0) {
  10317. kill(forkpid, SIGTERM);
  10318. forkpid = 0;
  10319. }
  10320. #endif
  10321. exit(status);
  10322. }
  10323. #ifdef HAVE_CURSES
  10324. char *curses_input(const char *query)
  10325. {
  10326. char *input;
  10327. echo();
  10328. input = malloc(255);
  10329. if (!input)
  10330. quit(1, "Failed to malloc input");
  10331. leaveok(logwin, false);
  10332. wlogprint("%s:\n", query);
  10333. wgetnstr(logwin, input, 255);
  10334. if (!strlen(input))
  10335. {
  10336. free(input);
  10337. input = NULL;
  10338. }
  10339. leaveok(logwin, true);
  10340. noecho();
  10341. return input;
  10342. }
  10343. #endif
  10344. static void *test_pool_thread(void *arg)
  10345. {
  10346. struct pool *pool = (struct pool *)arg;
  10347. if (pool_active(pool, false)) {
  10348. pool_tset(pool, &pool->lagging);
  10349. pool_tclear(pool, &pool->idle);
  10350. bool first_pool = false;
  10351. cg_wlock(&control_lock);
  10352. if (!pools_active) {
  10353. currentpool = pool;
  10354. if (pool->pool_no != 0)
  10355. first_pool = true;
  10356. pools_active = true;
  10357. }
  10358. cg_wunlock(&control_lock);
  10359. if (unlikely(first_pool))
  10360. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10361. else
  10362. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10363. switch_pools(NULL);
  10364. } else
  10365. pool_died(pool);
  10366. pool->testing = false;
  10367. return NULL;
  10368. }
  10369. /* Always returns true that the pool details were added unless we are not
  10370. * live, implying this is the only pool being added, so if no pools are
  10371. * active it returns false. */
  10372. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10373. {
  10374. size_t siz;
  10375. pool_set_uri(pool, url);
  10376. pool->rpc_user = user;
  10377. pool->rpc_pass = pass;
  10378. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10379. pool->rpc_userpass = malloc(siz);
  10380. if (!pool->rpc_userpass)
  10381. quit(1, "Failed to malloc userpass");
  10382. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10383. pool->testing = true;
  10384. pool->idle = true;
  10385. enable_pool(pool);
  10386. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10387. if (!live) {
  10388. pthread_join(pool->test_thread, NULL);
  10389. return pools_active;
  10390. }
  10391. return true;
  10392. }
  10393. #ifdef HAVE_CURSES
  10394. static bool input_pool(bool live)
  10395. {
  10396. char *url = NULL, *user = NULL, *pass = NULL;
  10397. struct pool *pool;
  10398. bool ret = false;
  10399. immedok(logwin, true);
  10400. wlogprint("Input server details.\n");
  10401. url = curses_input("URL");
  10402. if (!url)
  10403. goto out;
  10404. user = curses_input("Username");
  10405. if (!user)
  10406. goto out;
  10407. pass = curses_input("Password");
  10408. if (!pass)
  10409. pass = calloc(1, 1);
  10410. pool = add_pool();
  10411. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10412. strncmp(url, "https://", 8)) {
  10413. char *httpinput;
  10414. httpinput = malloc(256);
  10415. if (!httpinput)
  10416. quit(1, "Failed to malloc httpinput");
  10417. strcpy(httpinput, "http://");
  10418. strncat(httpinput, url, 248);
  10419. free(url);
  10420. url = httpinput;
  10421. }
  10422. ret = add_pool_details(pool, live, url, user, pass);
  10423. out:
  10424. immedok(logwin, false);
  10425. if (!ret) {
  10426. if (url)
  10427. free(url);
  10428. if (user)
  10429. free(user);
  10430. if (pass)
  10431. free(pass);
  10432. }
  10433. return ret;
  10434. }
  10435. #endif
  10436. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  10437. static
  10438. bool _add_local_gbt(const char * const filepath, void *userp)
  10439. {
  10440. const bool * const live_p = userp;
  10441. struct pool *pool;
  10442. char buf[0x100];
  10443. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10444. int rpcport = 0, rpcssl = -101;
  10445. FILE * const F = fopen(filepath, "r");
  10446. if (!F)
  10447. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10448. while (fgets(buf, sizeof(buf), F))
  10449. {
  10450. if (!strncasecmp(buf, "rpcuser=", 8))
  10451. rpcuser = trimmed_strdup(&buf[8]);
  10452. else
  10453. if (!strncasecmp(buf, "rpcpassword=", 12))
  10454. rpcpass = trimmed_strdup(&buf[12]);
  10455. else
  10456. if (!strncasecmp(buf, "rpcport=", 8))
  10457. rpcport = atoi(&buf[8]);
  10458. else
  10459. if (!strncasecmp(buf, "rpcssl=", 7))
  10460. rpcssl = atoi(&buf[7]);
  10461. else
  10462. if (!strncasecmp(buf, "rpcconnect=", 11))
  10463. rpcconnect = trimmed_strdup(&buf[11]);
  10464. else
  10465. continue;
  10466. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10467. break;
  10468. }
  10469. fclose(F);
  10470. if (!rpcpass)
  10471. {
  10472. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10473. err:
  10474. free(rpcuser);
  10475. free(rpcpass);
  10476. goto out;
  10477. }
  10478. if (!rpcport)
  10479. rpcport = 8332;
  10480. if (rpcssl == -101)
  10481. rpcssl = 0;
  10482. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10483. const int uri_sz = 0x30;
  10484. char * const uri = malloc(uri_sz);
  10485. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10486. char hfuri[0x40];
  10487. if (rpcconnect)
  10488. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10489. else
  10490. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10491. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10492. for (int i = 0; i < total_pools; ++i)
  10493. {
  10494. struct pool *pool = pools[i];
  10495. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10496. {
  10497. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10498. free(uri);
  10499. goto err;
  10500. }
  10501. }
  10502. pool = add_pool();
  10503. if (!pool)
  10504. {
  10505. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10506. goto err;
  10507. }
  10508. if (!rpcuser)
  10509. rpcuser = "";
  10510. pool->quota = 0;
  10511. adjust_quota_gcd();
  10512. pool->failover_only = true;
  10513. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10514. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10515. out:
  10516. return false;
  10517. }
  10518. static
  10519. void add_local_gbt(bool live)
  10520. {
  10521. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10522. }
  10523. #endif
  10524. #if defined(unix) || defined(__APPLE__)
  10525. static void fork_monitor()
  10526. {
  10527. // Make a pipe: [readFD, writeFD]
  10528. int pfd[2];
  10529. int r = pipe(pfd);
  10530. if (r < 0) {
  10531. perror("pipe - failed to create pipe for --monitor");
  10532. exit(1);
  10533. }
  10534. // Make stderr write end of pipe
  10535. fflush(stderr);
  10536. r = dup2(pfd[1], 2);
  10537. if (r < 0) {
  10538. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10539. exit(1);
  10540. }
  10541. r = close(pfd[1]);
  10542. if (r < 0) {
  10543. perror("close - failed to close write end of pipe for --monitor");
  10544. exit(1);
  10545. }
  10546. // Don't allow a dying monitor to kill the main process
  10547. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10548. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10549. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10550. perror("signal - failed to edit signal mask for --monitor");
  10551. exit(1);
  10552. }
  10553. // Fork a child process
  10554. forkpid = fork();
  10555. if (forkpid < 0) {
  10556. perror("fork - failed to fork child process for --monitor");
  10557. exit(1);
  10558. }
  10559. // Child: launch monitor command
  10560. if (0 == forkpid) {
  10561. // Make stdin read end of pipe
  10562. r = dup2(pfd[0], 0);
  10563. if (r < 0) {
  10564. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10565. exit(1);
  10566. }
  10567. close(pfd[0]);
  10568. if (r < 0) {
  10569. perror("close - in child, failed to close read end of pipe for --monitor");
  10570. exit(1);
  10571. }
  10572. // Launch user specified command
  10573. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10574. perror("execl - in child failed to exec user specified command for --monitor");
  10575. exit(1);
  10576. }
  10577. // Parent: clean up unused fds and bail
  10578. r = close(pfd[0]);
  10579. if (r < 0) {
  10580. perror("close - failed to close read end of pipe for --monitor");
  10581. exit(1);
  10582. }
  10583. }
  10584. #endif // defined(unix)
  10585. #ifdef HAVE_CURSES
  10586. #ifdef USE_UNICODE
  10587. static
  10588. wchar_t select_unicode_char(const wchar_t *opt)
  10589. {
  10590. for ( ; *opt; ++opt)
  10591. if (iswprint(*opt))
  10592. return *opt;
  10593. return '?';
  10594. }
  10595. #endif
  10596. void enable_curses(void) {
  10597. int x;
  10598. __maybe_unused int y;
  10599. lock_curses();
  10600. if (curses_active) {
  10601. unlock_curses();
  10602. return;
  10603. }
  10604. #ifdef USE_UNICODE
  10605. if (use_unicode)
  10606. {
  10607. setlocale(LC_CTYPE, "");
  10608. if (iswprint(0xb0))
  10609. have_unicode_degrees = true;
  10610. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10611. }
  10612. #endif
  10613. mainwin = initscr();
  10614. start_color();
  10615. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10616. if (ERR != use_default_colors())
  10617. default_bgcolor = -1;
  10618. #endif
  10619. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10620. {
  10621. menu_attr = COLOR_PAIR(1);
  10622. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10623. attr_bad |= COLOR_PAIR(2);
  10624. }
  10625. keypad(mainwin, true);
  10626. getmaxyx(mainwin, y, x);
  10627. statuswin = newwin(logstart, x, 0, 0);
  10628. leaveok(statuswin, true);
  10629. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10630. // We resize the window later anyway, so just start it off at 1 :)
  10631. logwin = newwin(1, 0, logcursor, 0);
  10632. idlok(logwin, true);
  10633. scrollok(logwin, true);
  10634. leaveok(logwin, true);
  10635. cbreak();
  10636. noecho();
  10637. nonl();
  10638. curses_active = true;
  10639. statusy = logstart;
  10640. unlock_curses();
  10641. }
  10642. #endif
  10643. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10644. #ifndef USE_CPUMINING
  10645. struct device_drv cpu_drv;
  10646. struct device_drv cpu_drv = {
  10647. .name = "CPU",
  10648. };
  10649. #endif
  10650. static int cgminer_id_count = 0;
  10651. static int device_line_id_count;
  10652. void register_device(struct cgpu_info *cgpu)
  10653. {
  10654. cgpu->deven = DEV_ENABLED;
  10655. wr_lock(&devices_lock);
  10656. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10657. wr_unlock(&devices_lock);
  10658. if (!cgpu->proc_id)
  10659. cgpu->device_line_id = device_line_id_count++;
  10660. int thr_objs = cgpu->threads ?: 1;
  10661. mining_threads += thr_objs;
  10662. base_queue += thr_objs + cgpu->extra_work_queue;
  10663. {
  10664. const struct device_drv * const drv = cgpu->drv;
  10665. struct mining_algorithm *malgo;
  10666. LL_FOREACH(mining_algorithms, malgo)
  10667. {
  10668. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10669. continue;
  10670. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10671. }
  10672. }
  10673. #ifdef HAVE_CURSES
  10674. adj_width(mining_threads, &dev_width);
  10675. #endif
  10676. rwlock_init(&cgpu->qlock);
  10677. cgpu->queued_work = NULL;
  10678. }
  10679. struct _cgpu_devid_counter {
  10680. char name[4];
  10681. int lastid;
  10682. UT_hash_handle hh;
  10683. };
  10684. void renumber_cgpu(struct cgpu_info *cgpu)
  10685. {
  10686. static struct _cgpu_devid_counter *devids = NULL;
  10687. struct _cgpu_devid_counter *d;
  10688. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10689. if (d)
  10690. cgpu->device_id = ++d->lastid;
  10691. else {
  10692. d = malloc(sizeof(*d));
  10693. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10694. cgpu->device_id = d->lastid = 0;
  10695. HASH_ADD_STR(devids, name, d);
  10696. }
  10697. // Build repr strings
  10698. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10699. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10700. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10701. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10702. const int lpcount = cgpu->procs;
  10703. if (lpcount > 1)
  10704. {
  10705. int ns;
  10706. struct cgpu_info *slave;
  10707. int lpdigits = 1;
  10708. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10709. ++lpdigits;
  10710. if (lpdigits > max_lpdigits)
  10711. max_lpdigits = lpdigits;
  10712. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10713. cgpu->proc_repr[5 + lpdigits] = '\0';
  10714. ns = strlen(cgpu->proc_repr_ns);
  10715. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10716. slave = cgpu;
  10717. for (int i = 1; i < lpcount; ++i)
  10718. {
  10719. slave = slave->next_proc;
  10720. strcpy(slave->proc_repr, cgpu->proc_repr);
  10721. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10722. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10723. {
  10724. slave->proc_repr_ns[ns + y] =
  10725. slave->proc_repr[5 + y] += (x % 26);
  10726. }
  10727. }
  10728. }
  10729. }
  10730. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10731. {
  10732. sha256(buffer, length, digest);
  10733. return true;
  10734. }
  10735. static
  10736. bool drv_algo_check(const struct device_drv * const drv)
  10737. {
  10738. struct mining_goal_info *goal, *tmpgoal;
  10739. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10740. {
  10741. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10742. return true;
  10743. }
  10744. return false;
  10745. }
  10746. #ifndef HAVE_PTHREAD_CANCEL
  10747. extern void setup_pthread_cancel_workaround();
  10748. extern struct sigaction pcwm_orig_term_handler;
  10749. #endif
  10750. bool bfg_need_detect_rescan;
  10751. extern void probe_device(struct lowlevel_device_info *);
  10752. static void schedule_rescan(const struct timeval *);
  10753. static
  10754. void drv_detect_all()
  10755. {
  10756. bool rescanning = false;
  10757. rescan:
  10758. bfg_need_detect_rescan = false;
  10759. #ifdef HAVE_BFG_LOWLEVEL
  10760. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10761. LL_FOREACH_SAFE(infolist, info, infotmp)
  10762. probe_device(info);
  10763. LL_FOREACH_SAFE(infolist, info, infotmp)
  10764. pthread_join(info->probe_pth, NULL);
  10765. #endif
  10766. struct driver_registration *reg, *tmp;
  10767. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10768. {
  10769. const struct device_drv * const drv = reg->drv;
  10770. if (!(drv_algo_check(drv) && drv->drv_detect))
  10771. continue;
  10772. drv->drv_detect();
  10773. }
  10774. #ifdef HAVE_BFG_LOWLEVEL
  10775. lowlevel_scan_free();
  10776. #endif
  10777. if (bfg_need_detect_rescan)
  10778. {
  10779. if (rescanning)
  10780. {
  10781. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10782. struct timeval tv_when;
  10783. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10784. schedule_rescan(&tv_when);
  10785. }
  10786. else
  10787. {
  10788. rescanning = true;
  10789. applog(LOG_DEBUG, "Device rescan requested");
  10790. goto rescan;
  10791. }
  10792. }
  10793. }
  10794. static
  10795. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10796. {
  10797. struct thr_info *thr;
  10798. int j;
  10799. struct device_drv *api = cgpu->drv;
  10800. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10801. int threadobj = cgpu->threads;
  10802. if (!threadobj)
  10803. // Create a fake thread object to handle hashmeter etc
  10804. threadobj = 1;
  10805. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10806. cgpu->thr[threadobj] = NULL;
  10807. cgpu->status = LIFE_INIT;
  10808. if (opt_devices_enabled_list)
  10809. {
  10810. struct string_elist *enablestr_elist;
  10811. cgpu->deven = DEV_DISABLED;
  10812. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10813. {
  10814. const char * const enablestr = enablestr_elist->string;
  10815. if (cgpu_match(enablestr, cgpu))
  10816. {
  10817. cgpu->deven = DEV_ENABLED;
  10818. break;
  10819. }
  10820. }
  10821. }
  10822. cgpu->max_hashes = 0;
  10823. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10824. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10825. // Setup thread structs before starting any of the threads, in case they try to interact
  10826. for (j = 0; j < threadobj; ++j, ++*kp) {
  10827. thr = get_thread(*kp);
  10828. thr->id = *kp;
  10829. thr->cgpu = cgpu;
  10830. thr->device_thread = j;
  10831. thr->work_restart_notifier[1] = INVSOCK;
  10832. thr->mutex_request[1] = INVSOCK;
  10833. thr->_job_transition_in_progress = true;
  10834. timerclear(&thr->tv_morework);
  10835. thr->scanhash_working = true;
  10836. thr->hashes_done = 0;
  10837. timerclear(&thr->tv_hashes_done);
  10838. cgtime(&thr->tv_lastupdate);
  10839. thr->tv_poll.tv_sec = -1;
  10840. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10841. cgpu->thr[j] = thr;
  10842. }
  10843. if (!cgpu->device->threads)
  10844. notifier_init_invalid(cgpu->thr[0]->notifier);
  10845. else
  10846. if (!cgpu->threads)
  10847. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10848. else
  10849. for (j = 0; j < cgpu->threads; ++j)
  10850. {
  10851. thr = cgpu->thr[j];
  10852. notifier_init(thr->notifier);
  10853. }
  10854. }
  10855. static
  10856. void start_cgpu(struct cgpu_info *cgpu)
  10857. {
  10858. struct thr_info *thr;
  10859. int j;
  10860. for (j = 0; j < cgpu->threads; ++j) {
  10861. thr = cgpu->thr[j];
  10862. /* Enable threads for devices set not to mine but disable
  10863. * their queue in case we wish to enable them later */
  10864. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10865. continue;
  10866. thread_reportout(thr);
  10867. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10868. quit(1, "thread %d create failed", thr->id);
  10869. notifier_wake(thr->notifier);
  10870. }
  10871. if (cgpu->deven == DEV_ENABLED)
  10872. proc_enable(cgpu);
  10873. }
  10874. static
  10875. void _scan_serial(void *p)
  10876. {
  10877. const char *s = p;
  10878. struct string_elist *iter, *tmp;
  10879. struct string_elist *orig_scan_devices = scan_devices;
  10880. if (s)
  10881. {
  10882. // Make temporary scan_devices list
  10883. scan_devices = NULL;
  10884. string_elist_add("noauto", &scan_devices);
  10885. add_serial(s);
  10886. }
  10887. drv_detect_all();
  10888. if (s)
  10889. {
  10890. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10891. {
  10892. string_elist_del(&scan_devices, iter);
  10893. }
  10894. scan_devices = orig_scan_devices;
  10895. }
  10896. }
  10897. #ifdef HAVE_BFG_LOWLEVEL
  10898. static
  10899. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10900. {
  10901. if (!(false
  10902. || (info->serial && !strcasecmp(ser, info->serial))
  10903. || (info->path && !strcasecmp(ser, info->path ))
  10904. || (info->devid && !strcasecmp(ser, info->devid ))
  10905. ))
  10906. {
  10907. char *devid = devpath_to_devid(ser);
  10908. if (!devid)
  10909. return false;
  10910. const bool different = strcmp(info->devid, devid);
  10911. free(devid);
  10912. if (different)
  10913. return false;
  10914. }
  10915. return true;
  10916. }
  10917. static
  10918. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10919. {
  10920. struct driver_registration *dreg;
  10921. char dname[dnamelen];
  10922. int i;
  10923. for (i = 0; i < dnamelen; ++i)
  10924. dname[i] = tolower(_dname[i]);
  10925. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10926. if (!dreg)
  10927. {
  10928. for (i = 0; i < dnamelen; ++i)
  10929. dname[i] = toupper(_dname[i]);
  10930. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10931. if (!dreg)
  10932. return NULL;
  10933. }
  10934. if (!drv_algo_check(dreg->drv))
  10935. return NULL;
  10936. return dreg->drv;
  10937. }
  10938. static
  10939. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10940. {
  10941. bfg_probe_result_flags = 0;
  10942. if (drv->lowl_probe(info))
  10943. {
  10944. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10945. return true;
  10946. }
  10947. else
  10948. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10949. *request_rescan_p = true;
  10950. return false;
  10951. }
  10952. bool dummy_check_never_true = false;
  10953. static
  10954. void *probe_device_thread(void *p)
  10955. {
  10956. struct lowlevel_device_info * const infolist = p;
  10957. struct lowlevel_device_info *info = infolist;
  10958. bool request_rescan = false;
  10959. {
  10960. char threadname[5 + strlen(info->devid) + 1];
  10961. sprintf(threadname, "probe_%s", info->devid);
  10962. RenameThread(threadname);
  10963. }
  10964. // If already in use, ignore
  10965. if (bfg_claim_any(NULL, NULL, info->devid))
  10966. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10967. __func__, info->product);
  10968. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10969. struct string_elist *sd_iter, *sd_tmp;
  10970. struct driver_registration *dreg, *dreg_tmp;
  10971. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10972. {
  10973. const char * const dname = sd_iter->string;
  10974. const char * const colon = strpbrk(dname, ":@");
  10975. if (!(colon && colon != dname))
  10976. continue;
  10977. const char * const ser = &colon[1];
  10978. LL_FOREACH2(infolist, info, same_devid_next)
  10979. {
  10980. if (!_probe_device_match(info, ser))
  10981. continue;
  10982. const size_t dnamelen = (colon - dname);
  10983. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10984. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10985. continue;
  10986. if (_probe_device_do_probe(drv, info, &request_rescan))
  10987. return NULL;
  10988. }
  10989. }
  10990. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10991. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10992. {
  10993. const struct device_drv * const drv = dreg->drv;
  10994. if (!drv_algo_check(drv))
  10995. continue;
  10996. // Check for "noauto" flag
  10997. // NOTE: driver-specific configuration overrides general
  10998. bool doauto = true;
  10999. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11000. {
  11001. const char * const dname = sd_iter->string;
  11002. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11003. const char *colon = strchr(dname, ':');
  11004. if (!colon)
  11005. colon = &dname[-1];
  11006. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  11007. continue;
  11008. const ssize_t dnamelen = (colon - dname);
  11009. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  11010. continue;
  11011. doauto = (tolower(colon[1]) == 'a');
  11012. if (dnamelen != -1)
  11013. break;
  11014. }
  11015. if (doauto && drv->lowl_match)
  11016. {
  11017. LL_FOREACH2(infolist, info, same_devid_next)
  11018. {
  11019. /*
  11020. The below call to applog is absolutely necessary
  11021. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  11022. Mac OS X using Homebrew results in a binary that segfaults on startup
  11023. There are two unresolved issues:
  11024. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  11025. in debug symbols being available to help troubleshoot the issue
  11026. 2) The issue disappears when unrelated code changes are made, such as adding the following
  11027. call to applog with infolist and / or p
  11028. We would encourage revisiting this in the future to come up with a more concrete solution
  11029. Reproducing should only require commenting / removing the following line and installing
  11030. BFGMiner using "brew install bfgminer --HEAD"
  11031. */
  11032. if (dummy_check_never_true)
  11033. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  11034. if (!drv->lowl_match(info))
  11035. continue;
  11036. if (_probe_device_do_probe(drv, info, &request_rescan))
  11037. return NULL;
  11038. }
  11039. }
  11040. }
  11041. // probe driver(s) with 'all' enabled
  11042. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11043. {
  11044. const char * const dname = sd_iter->string;
  11045. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11046. const char * const colon = strchr(dname, ':');
  11047. if (!colon)
  11048. {
  11049. LL_FOREACH2(infolist, info, same_devid_next)
  11050. {
  11051. if (
  11052. #ifdef NEED_BFG_LOWL_VCOM
  11053. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  11054. #endif
  11055. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  11056. {
  11057. bool dont_rescan = false;
  11058. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  11059. {
  11060. const struct device_drv * const drv = dreg->drv;
  11061. if (!drv_algo_check(drv))
  11062. continue;
  11063. if (drv->lowl_probe_by_name_only)
  11064. continue;
  11065. if (!drv->lowl_probe)
  11066. continue;
  11067. if (_probe_device_do_probe(drv, info, NULL))
  11068. return NULL;
  11069. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  11070. dont_rescan = true;
  11071. }
  11072. if (opt_hotplug && !dont_rescan)
  11073. request_rescan = true;
  11074. break;
  11075. }
  11076. }
  11077. continue;
  11078. }
  11079. if (strcasecmp(&colon[1], "all"))
  11080. continue;
  11081. const size_t dnamelen = (colon - dname);
  11082. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  11083. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11084. continue;
  11085. LL_FOREACH2(infolist, info, same_devid_next)
  11086. {
  11087. if (info->lowl->exclude_from_all)
  11088. continue;
  11089. if (_probe_device_do_probe(drv, info, NULL))
  11090. return NULL;
  11091. }
  11092. }
  11093. // Only actually request a rescan if we never found any cgpu
  11094. if (request_rescan)
  11095. bfg_need_detect_rescan = true;
  11096. return NULL;
  11097. }
  11098. void probe_device(struct lowlevel_device_info * const info)
  11099. {
  11100. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11101. }
  11102. #endif
  11103. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11104. {
  11105. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11106. int devcount, i, mining_threads_new = 0;
  11107. unsigned int k;
  11108. struct cgpu_info *cgpu;
  11109. struct thr_info *thr;
  11110. void *p;
  11111. mutex_lock(&mutex);
  11112. devcount = total_devices;
  11113. addfunc(arg);
  11114. if (!total_devices_new)
  11115. goto out;
  11116. wr_lock(&devices_lock);
  11117. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11118. if (unlikely(!p))
  11119. {
  11120. wr_unlock(&devices_lock);
  11121. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11122. goto out;
  11123. }
  11124. devices = p;
  11125. wr_unlock(&devices_lock);
  11126. for (i = 0; i < total_devices_new; ++i)
  11127. {
  11128. cgpu = devices_new[i];
  11129. mining_threads_new += cgpu->threads ?: 1;
  11130. }
  11131. wr_lock(&mining_thr_lock);
  11132. mining_threads_new += mining_threads;
  11133. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11134. if (unlikely(!p))
  11135. {
  11136. wr_unlock(&mining_thr_lock);
  11137. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11138. goto out;
  11139. }
  11140. mining_thr = p;
  11141. wr_unlock(&mining_thr_lock);
  11142. for (i = mining_threads; i < mining_threads_new; ++i) {
  11143. mining_thr[i] = calloc(1, sizeof(*thr));
  11144. if (!mining_thr[i])
  11145. {
  11146. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11147. for ( ; --i >= mining_threads; )
  11148. free(mining_thr[i]);
  11149. goto out;
  11150. }
  11151. }
  11152. k = mining_threads;
  11153. for (i = 0; i < total_devices_new; ++i)
  11154. {
  11155. cgpu = devices_new[i];
  11156. allocate_cgpu(cgpu, &k);
  11157. }
  11158. for (i = 0; i < total_devices_new; ++i)
  11159. {
  11160. cgpu = devices_new[i];
  11161. start_cgpu(cgpu);
  11162. register_device(cgpu);
  11163. ++total_devices;
  11164. }
  11165. #ifdef HAVE_CURSES
  11166. switch_logsize();
  11167. #endif
  11168. out:
  11169. total_devices_new = 0;
  11170. devcount = total_devices - devcount;
  11171. mutex_unlock(&mutex);
  11172. return devcount;
  11173. }
  11174. int scan_serial(const char *s)
  11175. {
  11176. return create_new_cgpus(_scan_serial, (void*)s);
  11177. }
  11178. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11179. static bool rescan_active;
  11180. static struct timeval tv_rescan;
  11181. static notifier_t rescan_notifier;
  11182. static
  11183. void *rescan_thread(__maybe_unused void *p)
  11184. {
  11185. pthread_detach(pthread_self());
  11186. RenameThread("rescan");
  11187. struct timeval tv_timeout, tv_now;
  11188. fd_set rfds;
  11189. while (true)
  11190. {
  11191. mutex_lock(&rescan_mutex);
  11192. tv_timeout = tv_rescan;
  11193. if (!timer_isset(&tv_timeout))
  11194. {
  11195. rescan_active = false;
  11196. mutex_unlock(&rescan_mutex);
  11197. break;
  11198. }
  11199. mutex_unlock(&rescan_mutex);
  11200. FD_ZERO(&rfds);
  11201. FD_SET(rescan_notifier[0], &rfds);
  11202. const int maxfd = rescan_notifier[0];
  11203. timer_set_now(&tv_now);
  11204. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11205. notifier_read(rescan_notifier);
  11206. mutex_lock(&rescan_mutex);
  11207. if (timer_passed(&tv_rescan, NULL))
  11208. {
  11209. timer_unset(&tv_rescan);
  11210. mutex_unlock(&rescan_mutex);
  11211. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11212. scan_serial(NULL);
  11213. }
  11214. else
  11215. mutex_unlock(&rescan_mutex);
  11216. }
  11217. return NULL;
  11218. }
  11219. static
  11220. void _schedule_rescan(const struct timeval * const tvp_when)
  11221. {
  11222. if (rescan_active)
  11223. {
  11224. if (timercmp(tvp_when, &tv_rescan, <))
  11225. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11226. else
  11227. {
  11228. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11229. tv_rescan = *tvp_when;
  11230. }
  11231. return;
  11232. }
  11233. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11234. tv_rescan = *tvp_when;
  11235. rescan_active = true;
  11236. static pthread_t pth;
  11237. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11238. applog(LOG_ERR, "Failed to start rescan thread");
  11239. }
  11240. static
  11241. void schedule_rescan(const struct timeval * const tvp_when)
  11242. {
  11243. mutex_lock(&rescan_mutex);
  11244. _schedule_rescan(tvp_when);
  11245. mutex_unlock(&rescan_mutex);
  11246. }
  11247. static
  11248. void hotplug_trigger()
  11249. {
  11250. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11251. struct timeval tv_now;
  11252. timer_set_now(&tv_now);
  11253. schedule_rescan(&tv_now);
  11254. }
  11255. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11256. static
  11257. void *hotplug_thread(__maybe_unused void *p)
  11258. {
  11259. pthread_detach(pthread_self());
  11260. RenameThread("hotplug");
  11261. struct udev * const udev = udev_new();
  11262. if (unlikely(!udev))
  11263. applogfailr(NULL, LOG_ERR, "udev_new");
  11264. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11265. if (unlikely(!mon))
  11266. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11267. if (unlikely(udev_monitor_enable_receiving(mon)))
  11268. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11269. const int epfd = epoll_create(1);
  11270. if (unlikely(epfd == -1))
  11271. applogfailr(NULL, LOG_ERR, "epoll_create");
  11272. {
  11273. const int fd = udev_monitor_get_fd(mon);
  11274. struct epoll_event ev = {
  11275. .events = EPOLLIN | EPOLLPRI,
  11276. .data.fd = fd,
  11277. };
  11278. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11279. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11280. }
  11281. struct epoll_event ev;
  11282. int rv;
  11283. bool pending = false;
  11284. while (true)
  11285. {
  11286. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11287. if (rv == -1)
  11288. {
  11289. if (errno == EAGAIN || errno == EINTR)
  11290. continue;
  11291. break;
  11292. }
  11293. if (!rv)
  11294. {
  11295. hotplug_trigger();
  11296. pending = false;
  11297. continue;
  11298. }
  11299. struct udev_device * const device = udev_monitor_receive_device(mon);
  11300. if (!device)
  11301. continue;
  11302. const char * const action = udev_device_get_action(device);
  11303. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11304. if (!strcmp(action, "add"))
  11305. pending = true;
  11306. udev_device_unref(device);
  11307. }
  11308. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11309. }
  11310. #elif defined(WIN32)
  11311. static UINT_PTR _hotplug_wintimer_id;
  11312. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11313. {
  11314. KillTimer(NULL, _hotplug_wintimer_id);
  11315. _hotplug_wintimer_id = 0;
  11316. hotplug_trigger();
  11317. }
  11318. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11319. {
  11320. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11321. {
  11322. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11323. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11324. }
  11325. return DefWindowProc(hwnd, msg, wParam, lParam);
  11326. }
  11327. static
  11328. void *hotplug_thread(__maybe_unused void *p)
  11329. {
  11330. pthread_detach(pthread_self());
  11331. WNDCLASS DummyWinCls = {
  11332. .lpszClassName = "BFGDummyWinCls",
  11333. .lpfnWndProc = hotplug_win_callback,
  11334. };
  11335. ATOM a = RegisterClass(&DummyWinCls);
  11336. if (unlikely(!a))
  11337. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11338. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11339. if (unlikely(!hwnd))
  11340. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11341. MSG msg;
  11342. while (GetMessage(&msg, NULL, 0, 0))
  11343. {
  11344. TranslateMessage(&msg);
  11345. DispatchMessage(&msg);
  11346. }
  11347. quit(0, "WM_QUIT received");
  11348. return NULL;
  11349. }
  11350. #endif
  11351. #ifdef HAVE_BFG_HOTPLUG
  11352. static
  11353. void hotplug_start()
  11354. {
  11355. pthread_t pth;
  11356. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11357. applog(LOG_ERR, "Failed to start hotplug thread");
  11358. }
  11359. #endif
  11360. static void probe_pools(void)
  11361. {
  11362. int i;
  11363. for (i = 0; i < total_pools; i++) {
  11364. struct pool *pool = pools[i];
  11365. pool->testing = true;
  11366. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11367. }
  11368. }
  11369. static void raise_fd_limits(void)
  11370. {
  11371. #ifdef HAVE_SETRLIMIT
  11372. struct rlimit fdlimit;
  11373. rlim_t old_soft_limit;
  11374. char frombuf[0x10] = "unlimited";
  11375. char hardbuf[0x10] = "unlimited";
  11376. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11377. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11378. old_soft_limit = fdlimit.rlim_cur;
  11379. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11380. fdlimit.rlim_cur = FD_SETSIZE;
  11381. else
  11382. fdlimit.rlim_cur = fdlimit.rlim_max;
  11383. if (fdlimit.rlim_max != RLIM_INFINITY)
  11384. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11385. if (old_soft_limit != RLIM_INFINITY)
  11386. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11387. if (fdlimit.rlim_cur == old_soft_limit)
  11388. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11389. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11390. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11391. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11392. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11393. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11394. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11395. #else
  11396. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11397. #endif
  11398. }
  11399. static
  11400. void bfg_atexit(void)
  11401. {
  11402. puts("");
  11403. }
  11404. extern void bfg_init_threadlocal();
  11405. extern void stratumsrv_start();
  11406. extern void test_aan_pll(void);
  11407. int main(int argc, char *argv[])
  11408. {
  11409. struct sigaction handler;
  11410. struct thr_info *thr;
  11411. unsigned int k;
  11412. int i;
  11413. int rearrange_pools = 0;
  11414. char *s;
  11415. #ifdef WIN32
  11416. LoadLibrary("backtrace.dll");
  11417. #endif
  11418. atexit(bfg_atexit);
  11419. b58_sha256_impl = my_blkmaker_sha256_callback;
  11420. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11421. bfg_init_threadlocal();
  11422. #ifndef HAVE_PTHREAD_CANCEL
  11423. setup_pthread_cancel_workaround();
  11424. #endif
  11425. bfg_init_checksums();
  11426. #ifdef WIN32
  11427. {
  11428. WSADATA wsa;
  11429. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11430. if (i)
  11431. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11432. }
  11433. #endif
  11434. /* This dangerous functions tramples random dynamically allocated
  11435. * variables so do it before anything at all */
  11436. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11437. quit(1, "Failed to curl_global_init");
  11438. initial_args = malloc(sizeof(char *) * (argc + 1));
  11439. for (i = 0; i < argc; i++)
  11440. initial_args[i] = strdup(argv[i]);
  11441. initial_args[argc] = NULL;
  11442. mutex_init(&hash_lock);
  11443. mutex_init(&console_lock);
  11444. cglock_init(&control_lock);
  11445. mutex_init(&stats_lock);
  11446. mutex_init(&sharelog_lock);
  11447. cglock_init(&ch_lock);
  11448. mutex_init(&sshare_lock);
  11449. rwlock_init(&blk_lock);
  11450. rwlock_init(&netacc_lock);
  11451. rwlock_init(&mining_thr_lock);
  11452. rwlock_init(&devices_lock);
  11453. mutex_init(&lp_lock);
  11454. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11455. quit(1, "Failed to pthread_cond_init lp_cond");
  11456. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11457. quit(1, "Failed to pthread_cond_init gws_cond");
  11458. notifier_init(submit_waiting_notifier);
  11459. timer_unset(&tv_rescan);
  11460. notifier_init(rescan_notifier);
  11461. /* Create a unique get work queue */
  11462. getq = tq_new();
  11463. if (!getq)
  11464. quit(1, "Failed to create getq");
  11465. /* We use the getq mutex as the staged lock */
  11466. stgd_lock = &getq->mutex;
  11467. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11468. init_max_name_len();
  11469. #endif
  11470. handler.sa_handler = &sighandler;
  11471. handler.sa_flags = 0;
  11472. sigemptyset(&handler.sa_mask);
  11473. #ifdef HAVE_PTHREAD_CANCEL
  11474. sigaction(SIGTERM, &handler, &termhandler);
  11475. #else
  11476. // Need to let pthread_cancel emulation handle SIGTERM first
  11477. termhandler = pcwm_orig_term_handler;
  11478. pcwm_orig_term_handler = handler;
  11479. #endif
  11480. sigaction(SIGINT, &handler, &inthandler);
  11481. #ifndef WIN32
  11482. signal(SIGPIPE, SIG_IGN);
  11483. #else
  11484. timeBeginPeriod(1);
  11485. #endif
  11486. opt_kernel_path = CGMINER_PREFIX;
  11487. cgminer_path = alloca(PATH_MAX);
  11488. s = strdup(argv[0]);
  11489. strcpy(cgminer_path, dirname(s));
  11490. free(s);
  11491. strcat(cgminer_path, "/");
  11492. #if defined(USE_CPUMINING) && defined(WIN32)
  11493. {
  11494. char buf[32];
  11495. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11496. if (gev > 0 && gev < sizeof(buf))
  11497. {
  11498. setup_benchmark_pool();
  11499. double rate = bench_algo_stage3(atoi(buf));
  11500. // Write result to shared memory for parent
  11501. char unique_name[64];
  11502. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11503. {
  11504. HANDLE map_handle = CreateFileMapping(
  11505. INVALID_HANDLE_VALUE, // use paging file
  11506. NULL, // default security attributes
  11507. PAGE_READWRITE, // read/write access
  11508. 0, // size: high 32-bits
  11509. 4096, // size: low 32-bits
  11510. unique_name // name of map object
  11511. );
  11512. if (NULL != map_handle) {
  11513. void *shared_mem = MapViewOfFile(
  11514. map_handle, // object to map view of
  11515. FILE_MAP_WRITE, // read/write access
  11516. 0, // high offset: map from
  11517. 0, // low offset: beginning
  11518. 0 // default: map entire file
  11519. );
  11520. if (NULL != shared_mem)
  11521. CopyMemory(shared_mem, &rate, sizeof(rate));
  11522. (void)UnmapViewOfFile(shared_mem);
  11523. }
  11524. (void)CloseHandle(map_handle);
  11525. }
  11526. exit(0);
  11527. }
  11528. }
  11529. #endif
  11530. #ifdef HAVE_CURSES
  11531. devcursor = 8;
  11532. logstart = devcursor;
  11533. logcursor = logstart;
  11534. #endif
  11535. mutex_init(&submitting_lock);
  11536. // Ensure at least the default goal is created
  11537. get_mining_goal("default");
  11538. #ifdef USE_OPENCL
  11539. opencl_early_init();
  11540. #endif
  11541. schedstart.tm.tm_sec = 1;
  11542. schedstop .tm.tm_sec = 1;
  11543. opt_register_table(opt_early_table, NULL);
  11544. opt_register_table(opt_config_table, NULL);
  11545. opt_register_table(opt_cmdline_table, NULL);
  11546. opt_early_parse(argc, argv, applog_and_exit);
  11547. if (!config_loaded)
  11548. {
  11549. load_default_config();
  11550. rearrange_pools = total_pools;
  11551. }
  11552. opt_free_table();
  11553. /* parse command line */
  11554. opt_register_table(opt_config_table,
  11555. "Options for both config file and command line");
  11556. opt_register_table(opt_cmdline_table,
  11557. "Options for command line only");
  11558. opt_parse(&argc, argv, applog_and_exit);
  11559. if (argc != 1)
  11560. quit(1, "Unexpected extra commandline arguments");
  11561. if (rearrange_pools && rearrange_pools < total_pools)
  11562. {
  11563. // Prioritise commandline pools before default-config pools
  11564. for (i = 0; i < rearrange_pools; ++i)
  11565. pools[i]->prio += rearrange_pools;
  11566. for ( ; i < total_pools; ++i)
  11567. pools[i]->prio -= rearrange_pools;
  11568. }
  11569. #ifndef HAVE_PTHREAD_CANCEL
  11570. // Can't do this any earlier, or config isn't loaded
  11571. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11572. #endif
  11573. #ifdef HAVE_PWD_H
  11574. struct passwd *user_info = NULL;
  11575. if (opt_setuid != NULL) {
  11576. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11577. quit(1, "Unable to find setuid user information");
  11578. }
  11579. }
  11580. #endif
  11581. #ifdef HAVE_CHROOT
  11582. if (chroot_dir != NULL) {
  11583. #ifdef HAVE_PWD_H
  11584. if (user_info == NULL && getuid() == 0) {
  11585. applog(LOG_WARNING, "Running as root inside chroot");
  11586. }
  11587. #endif
  11588. if (chroot(chroot_dir) != 0) {
  11589. quit(1, "Unable to chroot");
  11590. }
  11591. if (chdir("/"))
  11592. quit(1, "Unable to chdir to chroot");
  11593. }
  11594. #endif
  11595. #ifdef HAVE_PWD_H
  11596. if (user_info != NULL) {
  11597. if (setgid((*user_info).pw_gid) != 0)
  11598. quit(1, "Unable to setgid");
  11599. if (setuid((*user_info).pw_uid) != 0)
  11600. quit(1, "Unable to setuid");
  11601. }
  11602. #endif
  11603. raise_fd_limits();
  11604. if (opt_benchmark) {
  11605. while (total_pools)
  11606. remove_pool(pools[0]);
  11607. setup_benchmark_pool();
  11608. }
  11609. if (opt_unittest) {
  11610. test_cgpu_match();
  11611. test_intrange();
  11612. test_decimal_width();
  11613. test_domain_funcs();
  11614. #ifdef USE_SCRYPT
  11615. test_scrypt();
  11616. #endif
  11617. test_target();
  11618. test_uri_get_param();
  11619. utf8_test();
  11620. #ifdef USE_JINGTIAN
  11621. test_aan_pll();
  11622. #endif
  11623. if (unittest_failures)
  11624. quit(1, "Unit tests failed");
  11625. }
  11626. #ifdef HAVE_CURSES
  11627. if (opt_realquiet || opt_display_devs)
  11628. use_curses = false;
  11629. setlocale(LC_ALL, "C");
  11630. if (use_curses)
  11631. enable_curses();
  11632. #endif
  11633. #ifdef HAVE_LIBUSB
  11634. int err = libusb_init(NULL);
  11635. if (err)
  11636. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11637. else
  11638. have_libusb = true;
  11639. #endif
  11640. applog(LOG_WARNING, "Started %s", packagename);
  11641. {
  11642. struct bfg_loaded_configfile *configfile;
  11643. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11644. {
  11645. char * const cnfbuf = configfile->filename;
  11646. int fileconf_load = configfile->fileconf_load;
  11647. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11648. switch (fileconf_load) {
  11649. case 0:
  11650. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11651. applog(LOG_WARNING, "Configuration file could not be used.");
  11652. break;
  11653. case -1:
  11654. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11655. if (use_curses)
  11656. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11657. break;
  11658. default:
  11659. break;
  11660. }
  11661. }
  11662. }
  11663. i = strlen(opt_kernel_path) + 2;
  11664. char __kernel_path[i];
  11665. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11666. opt_kernel_path = __kernel_path;
  11667. if (want_per_device_stats)
  11668. opt_log_output = true;
  11669. bfg_devapi_init();
  11670. drv_detect_all();
  11671. total_devices = total_devices_new;
  11672. devices = devices_new;
  11673. total_devices_new = 0;
  11674. devices_new = NULL;
  11675. if (opt_display_devs) {
  11676. int devcount = 0;
  11677. applog(LOG_ERR, "Devices detected:");
  11678. for (i = 0; i < total_devices; ++i) {
  11679. struct cgpu_info *cgpu = devices[i];
  11680. char buf[0x100];
  11681. if (cgpu->device != cgpu)
  11682. continue;
  11683. if (cgpu->name)
  11684. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11685. else
  11686. if (cgpu->dev_manufacturer)
  11687. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11688. else
  11689. if (cgpu->dev_product)
  11690. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11691. else
  11692. strcpy(buf, " Device");
  11693. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11694. if (cgpu->dev_serial)
  11695. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11696. if (cgpu->device_path)
  11697. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11698. tailsprintf(buf, sizeof(buf), ")");
  11699. _applog(LOG_NOTICE, buf);
  11700. ++devcount;
  11701. }
  11702. quit(0, "%d devices listed", devcount);
  11703. }
  11704. mining_threads = 0;
  11705. for (i = 0; i < total_devices; ++i)
  11706. register_device(devices[i]);
  11707. if (!total_devices) {
  11708. applog(LOG_WARNING, "No devices detected!");
  11709. if (use_curses)
  11710. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11711. else
  11712. applog(LOG_WARNING, "Waiting for devices");
  11713. }
  11714. #ifdef HAVE_CURSES
  11715. switch_logsize();
  11716. #endif
  11717. #if BLKMAKER_VERSION > 1 && defined(USE_SHA256D)
  11718. if (opt_load_bitcoin_conf && !(get_mining_goal("default")->malgo->algo != POW_SHA256D || opt_benchmark))
  11719. add_local_gbt(total_pools);
  11720. #endif
  11721. if (!total_pools) {
  11722. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11723. #ifdef HAVE_CURSES
  11724. if (!use_curses || !input_pool(false))
  11725. #endif
  11726. quit(1, "Pool setup failed");
  11727. }
  11728. for (i = 0; i < total_pools; i++) {
  11729. struct pool *pool = pools[i];
  11730. size_t siz;
  11731. if (!pool->rpc_url)
  11732. quit(1, "No URI supplied for pool %u", i);
  11733. if (!pool->rpc_userpass) {
  11734. if (!pool->rpc_user || !pool->rpc_pass)
  11735. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11736. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11737. pool->rpc_userpass = malloc(siz);
  11738. if (!pool->rpc_userpass)
  11739. quit(1, "Failed to malloc userpass");
  11740. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11741. }
  11742. }
  11743. /* Set the currentpool to pool with priority 0 */
  11744. validate_pool_priorities();
  11745. for (i = 0; i < total_pools; i++) {
  11746. struct pool *pool = pools[i];
  11747. if (!pool->prio)
  11748. currentpool = pool;
  11749. }
  11750. #ifdef HAVE_SYSLOG_H
  11751. if (use_syslog)
  11752. openlog(PACKAGE, LOG_PID, LOG_USER);
  11753. #endif
  11754. #if defined(unix) || defined(__APPLE__)
  11755. if (opt_stderr_cmd)
  11756. fork_monitor();
  11757. #endif // defined(unix)
  11758. mining_thr = calloc(mining_threads, sizeof(thr));
  11759. if (!mining_thr)
  11760. quit(1, "Failed to calloc mining_thr");
  11761. for (i = 0; i < mining_threads; i++) {
  11762. mining_thr[i] = calloc(1, sizeof(*thr));
  11763. if (!mining_thr[i])
  11764. quit(1, "Failed to calloc mining_thr[%d]", i);
  11765. }
  11766. total_control_threads = 6;
  11767. control_thr = calloc(total_control_threads, sizeof(*thr));
  11768. if (!control_thr)
  11769. quit(1, "Failed to calloc control_thr");
  11770. if (opt_benchmark)
  11771. goto begin_bench;
  11772. applog(LOG_NOTICE, "Probing for an alive pool");
  11773. do {
  11774. bool still_testing;
  11775. int i;
  11776. /* Look for at least one active pool before starting */
  11777. probe_pools();
  11778. do {
  11779. sleep(1);
  11780. if (pools_active)
  11781. break;
  11782. still_testing = false;
  11783. for (int i = 0; i < total_pools; ++i)
  11784. if (pools[i]->testing)
  11785. still_testing = true;
  11786. } while (still_testing);
  11787. if (!pools_active) {
  11788. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11789. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11790. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11791. for (i = 0; i < total_pools; i++) {
  11792. struct pool *pool;
  11793. pool = pools[i];
  11794. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11795. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11796. }
  11797. #ifdef HAVE_CURSES
  11798. if (use_curses) {
  11799. halfdelay(150);
  11800. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11801. if (getch() != ERR)
  11802. quit(0, "No servers could be used! Exiting.");
  11803. cbreak();
  11804. } else
  11805. #endif
  11806. quit(0, "No servers could be used! Exiting.");
  11807. }
  11808. } while (!pools_active);
  11809. #ifdef USE_SCRYPT
  11810. if (detect_algo == 1 && get_mining_goal("default")->malgo->algo != POW_SCRYPT) {
  11811. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11812. set_malgo_scrypt();
  11813. }
  11814. #endif
  11815. detect_algo = 0;
  11816. begin_bench:
  11817. total_mhashes_done = 0;
  11818. for (i = 0; i < total_devices; i++) {
  11819. struct cgpu_info *cgpu = devices[i];
  11820. cgpu->rolling = cgpu->total_mhashes = 0;
  11821. }
  11822. cgtime(&total_tv_start);
  11823. cgtime(&total_tv_end);
  11824. miner_started = total_tv_start;
  11825. time_t miner_start_ts = time(NULL);
  11826. if (schedstart.tm.tm_sec)
  11827. localtime_r(&miner_start_ts, &schedstart.tm);
  11828. if (schedstop.tm.tm_sec)
  11829. localtime_r(&miner_start_ts, &schedstop .tm);
  11830. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11831. // Initialise processors and threads
  11832. k = 0;
  11833. for (i = 0; i < total_devices; ++i) {
  11834. struct cgpu_info *cgpu = devices[i];
  11835. allocate_cgpu(cgpu, &k);
  11836. }
  11837. // Start threads
  11838. for (i = 0; i < total_devices; ++i) {
  11839. struct cgpu_info *cgpu = devices[i];
  11840. start_cgpu(cgpu);
  11841. }
  11842. #ifdef USE_OPENCL
  11843. for (i = 0; i < nDevs; i++)
  11844. pause_dynamic_threads(i);
  11845. #endif
  11846. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  11847. if (opt_n_threads > 0)
  11848. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11849. opt_n_threads, algo_names[opt_algo]);
  11850. #endif
  11851. cgtime(&total_tv_start);
  11852. cgtime(&total_tv_end);
  11853. if (!opt_benchmark)
  11854. {
  11855. pthread_t submit_thread;
  11856. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11857. quit(1, "submit_work thread create failed");
  11858. }
  11859. watchpool_thr_id = 1;
  11860. thr = &control_thr[watchpool_thr_id];
  11861. /* start watchpool thread */
  11862. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11863. quit(1, "watchpool thread create failed");
  11864. pthread_detach(thr->pth);
  11865. watchdog_thr_id = 2;
  11866. thr = &control_thr[watchdog_thr_id];
  11867. /* start watchdog thread */
  11868. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11869. quit(1, "watchdog thread create failed");
  11870. pthread_detach(thr->pth);
  11871. #ifdef USE_OPENCL
  11872. /* Create reinit gpu thread */
  11873. gpur_thr_id = 3;
  11874. thr = &control_thr[gpur_thr_id];
  11875. thr->q = tq_new();
  11876. if (!thr->q)
  11877. quit(1, "tq_new failed for gpur_thr_id");
  11878. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11879. quit(1, "reinit_gpu thread create failed");
  11880. #endif
  11881. /* Create API socket thread */
  11882. api_thr_id = 4;
  11883. thr = &control_thr[api_thr_id];
  11884. if (thr_info_create(thr, NULL, api_thread, thr))
  11885. quit(1, "API thread create failed");
  11886. #ifdef USE_LIBMICROHTTPD
  11887. if (httpsrv_port != -1)
  11888. httpsrv_start(httpsrv_port);
  11889. #endif
  11890. #ifdef USE_LIBEVENT
  11891. if (stratumsrv_port != -1)
  11892. stratumsrv_start();
  11893. #endif
  11894. #ifdef HAVE_BFG_HOTPLUG
  11895. if (opt_hotplug)
  11896. hotplug_start();
  11897. #endif
  11898. #ifdef HAVE_CURSES
  11899. /* Create curses input thread for keyboard input. Create this last so
  11900. * that we know all threads are created since this can call kill_work
  11901. * to try and shut down ll previous threads. */
  11902. input_thr_id = 5;
  11903. thr = &control_thr[input_thr_id];
  11904. if (thr_info_create(thr, NULL, input_thread, thr))
  11905. quit(1, "input thread create failed");
  11906. pthread_detach(thr->pth);
  11907. #endif
  11908. /* Just to be sure */
  11909. if (total_control_threads != 6)
  11910. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11911. /* Once everything is set up, main() becomes the getwork scheduler */
  11912. while (42) {
  11913. int ts, max_staged = opt_queue;
  11914. struct pool *pool, *cp;
  11915. bool lagging = false;
  11916. struct curl_ent *ce;
  11917. struct work *work;
  11918. struct mining_algorithm *malgo = NULL;
  11919. cp = current_pool();
  11920. // Generally, each processor needs a new work, and all at once during work restarts
  11921. max_staged += base_queue;
  11922. mutex_lock(stgd_lock);
  11923. ts = __total_staged(false);
  11924. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11925. lagging = true;
  11926. /* Wait until hash_pop tells us we need to create more work */
  11927. if (ts > max_staged) {
  11928. {
  11929. LL_FOREACH(mining_algorithms, malgo)
  11930. {
  11931. if (!malgo->goal_refs)
  11932. continue;
  11933. if (!malgo->base_queue)
  11934. continue;
  11935. if (malgo->staged < malgo->base_queue + opt_queue)
  11936. {
  11937. mutex_unlock(stgd_lock);
  11938. pool = select_pool(lagging, malgo);
  11939. if (pool)
  11940. {
  11941. work = make_work();
  11942. work->spare = true;
  11943. goto retry;
  11944. }
  11945. mutex_lock(stgd_lock);
  11946. }
  11947. }
  11948. malgo = NULL;
  11949. }
  11950. staged_full = true;
  11951. pthread_cond_wait(&gws_cond, stgd_lock);
  11952. ts = __total_staged(false);
  11953. }
  11954. mutex_unlock(stgd_lock);
  11955. if (ts > max_staged)
  11956. continue;
  11957. work = make_work();
  11958. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11959. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11960. cp->getfail_occasions++;
  11961. total_go++;
  11962. }
  11963. pool = select_pool(lagging, malgo);
  11964. retry:
  11965. if (pool->has_stratum) {
  11966. while (!pool->stratum_active || !pool->stratum_notify) {
  11967. struct pool *altpool = select_pool(true, malgo);
  11968. if (altpool == pool && pool->has_stratum)
  11969. cgsleep_ms(5000);
  11970. pool = altpool;
  11971. goto retry;
  11972. }
  11973. gen_stratum_work(pool, work);
  11974. applog(LOG_DEBUG, "Generated stratum work");
  11975. stage_work(work);
  11976. continue;
  11977. }
  11978. if (pool->last_work_copy) {
  11979. mutex_lock(&pool->last_work_lock);
  11980. struct work *last_work = pool->last_work_copy;
  11981. if (!last_work)
  11982. {}
  11983. else
  11984. if (can_roll(last_work) && should_roll(last_work)) {
  11985. struct timeval tv_now;
  11986. cgtime(&tv_now);
  11987. free_work(work);
  11988. work = make_clone(pool->last_work_copy);
  11989. mutex_unlock(&pool->last_work_lock);
  11990. roll_work(work);
  11991. 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));
  11992. stage_work(work);
  11993. continue;
  11994. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11995. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11996. } else {
  11997. free_work(last_work);
  11998. pool->last_work_copy = NULL;
  11999. }
  12000. mutex_unlock(&pool->last_work_lock);
  12001. }
  12002. if (clone_available()) {
  12003. applog(LOG_DEBUG, "Cloned getwork work");
  12004. free_work(work);
  12005. continue;
  12006. }
  12007. if (opt_benchmark) {
  12008. get_benchmark_work(work, opt_benchmark_intense);
  12009. applog(LOG_DEBUG, "Generated benchmark work");
  12010. stage_work(work);
  12011. continue;
  12012. }
  12013. work->pool = pool;
  12014. ce = pop_curl_entry3(pool, 2);
  12015. /* obtain new work from bitcoin via JSON-RPC */
  12016. if (!get_upstream_work(work, ce->curl)) {
  12017. struct pool *next_pool;
  12018. /* Make sure the pool just hasn't stopped serving
  12019. * requests but is up as we'll keep hammering it */
  12020. push_curl_entry(ce, pool);
  12021. ++pool->seq_getfails;
  12022. pool_died(pool);
  12023. next_pool = select_pool(!opt_fail_only, malgo);
  12024. if (pool == next_pool) {
  12025. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  12026. cgsleep_ms(5000);
  12027. } else {
  12028. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  12029. pool = next_pool;
  12030. }
  12031. goto retry;
  12032. }
  12033. if (ts >= max_staged)
  12034. pool_tclear(pool, &pool->lagging);
  12035. if (pool_tclear(pool, &pool->idle))
  12036. pool_resus(pool);
  12037. applog(LOG_DEBUG, "Generated getwork work");
  12038. stage_work(work);
  12039. push_curl_entry(ce, pool);
  12040. }
  12041. return 0;
  12042. }