miner.c 356 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2014 Luke Dashjr
  4. * Copyright 2014 Nate Woolls
  5. * Copyright 2012-2013 Andrew Smith
  6. * Copyright 2010 Jeff Garzik
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #ifdef HAVE_CURSES
  15. #ifdef USE_UNICODE
  16. #define PDC_WIDE
  17. #endif
  18. // Must be before stdbool, since pdcurses typedefs bool :/
  19. #include <curses.h>
  20. #endif
  21. #include <ctype.h>
  22. #include <float.h>
  23. #include <limits.h>
  24. #include <locale.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <stdbool.h>
  29. #include <stdint.h>
  30. #include <unistd.h>
  31. #include <sys/time.h>
  32. #include <time.h>
  33. #include <math.h>
  34. #include <stdarg.h>
  35. #include <assert.h>
  36. #include <signal.h>
  37. #include <wctype.h>
  38. #include <sys/stat.h>
  39. #include <sys/types.h>
  40. #include <dirent.h>
  41. #ifdef HAVE_PWD_H
  42. #include <pwd.h>
  43. #endif
  44. #ifndef WIN32
  45. #include <sys/resource.h>
  46. #include <sys/socket.h>
  47. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  48. #include <libudev.h>
  49. #include <sys/epoll.h>
  50. #define HAVE_BFG_HOTPLUG
  51. #endif
  52. #else
  53. #include <winsock2.h>
  54. #include <windows.h>
  55. #include <dbt.h>
  56. #define HAVE_BFG_HOTPLUG
  57. #endif
  58. #include <ccan/opt/opt.h>
  59. #include <jansson.h>
  60. #include <curl/curl.h>
  61. #include <libgen.h>
  62. #include <sha2.h>
  63. #include <utlist.h>
  64. #include <blkmaker.h>
  65. #include <blkmaker_jansson.h>
  66. #include <blktemplate.h>
  67. #include <libbase58.h>
  68. #include "compat.h"
  69. #include "deviceapi.h"
  70. #include "logging.h"
  71. #include "miner.h"
  72. #include "adl.h"
  73. #include "driver-cpu.h"
  74. #include "driver-opencl.h"
  75. #include "scrypt.h"
  76. #include "util.h"
  77. #ifdef USE_AVALON
  78. #include "driver-avalon.h"
  79. #endif
  80. #ifdef HAVE_BFG_LOWLEVEL
  81. #include "lowlevel.h"
  82. #endif
  83. #if defined(unix) || defined(__APPLE__)
  84. #include <errno.h>
  85. #include <fcntl.h>
  86. #include <sys/wait.h>
  87. #endif
  88. #ifdef USE_SCRYPT
  89. #include "scrypt.h"
  90. #endif
  91. #include "version.h"
  92. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  93. # define USE_FPGA
  94. #endif
  95. enum bfg_quit_summary {
  96. BQS_DEFAULT,
  97. BQS_NONE,
  98. BQS_DEVS,
  99. BQS_PROCS,
  100. BQS_DETAILED,
  101. };
  102. struct strategies strategies[] = {
  103. { "Failover" },
  104. { "Round Robin" },
  105. { "Rotate" },
  106. { "Load Balance" },
  107. { "Balance" },
  108. };
  109. static char packagename[256];
  110. bool opt_protocol;
  111. bool opt_dev_protocol;
  112. static bool opt_benchmark, opt_benchmark_intense;
  113. static bool want_longpoll = true;
  114. static bool want_gbt = true;
  115. static bool want_getwork = true;
  116. #if BLKMAKER_VERSION > 1
  117. static bool opt_load_bitcoin_conf = true;
  118. static uint32_t coinbase_script_block_id;
  119. static uint32_t template_nonce;
  120. #endif
  121. #if BLKMAKER_VERSION > 0
  122. char *opt_coinbase_sig;
  123. #endif
  124. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  125. static bool include_serial_in_statline;
  126. char *request_target_str;
  127. float request_pdiff = 1.0;
  128. double request_bdiff;
  129. static bool want_stratum = true;
  130. int opt_skip_checks;
  131. bool want_per_device_stats;
  132. bool use_syslog;
  133. bool opt_quiet_work_updates = true;
  134. bool opt_quiet;
  135. bool opt_realquiet;
  136. int loginput_size;
  137. bool opt_compact;
  138. bool opt_show_procs;
  139. const int opt_cutofftemp = 95;
  140. int opt_hysteresis = 3;
  141. static int opt_retries = -1;
  142. int opt_fail_pause = 5;
  143. int opt_log_interval = 20;
  144. int opt_queue = 1;
  145. int opt_scantime = 60;
  146. int opt_expiry = 120;
  147. int opt_expiry_lp = 3600;
  148. unsigned long long global_hashrate;
  149. static bool opt_unittest = false;
  150. unsigned unittest_failures;
  151. unsigned long global_quota_gcd = 1;
  152. time_t last_getwork;
  153. #ifdef HAVE_OPENCL
  154. int opt_dynamic_interval = 7;
  155. int nDevs;
  156. int opt_g_threads = -1;
  157. #endif
  158. #ifdef USE_SCRYPT
  159. static char detect_algo = 1;
  160. #else
  161. static char detect_algo;
  162. #endif
  163. bool opt_restart = true;
  164. #ifdef USE_LIBMICROHTTPD
  165. #include "httpsrv.h"
  166. int httpsrv_port = -1;
  167. #endif
  168. #ifdef USE_LIBEVENT
  169. int stratumsrv_port = -1;
  170. #endif
  171. const
  172. int rescan_delay_ms = 1000;
  173. #ifdef HAVE_BFG_HOTPLUG
  174. bool opt_hotplug = 1;
  175. const
  176. int hotplug_delay_ms = 100;
  177. #else
  178. const bool opt_hotplug;
  179. #endif
  180. struct string_elist *scan_devices;
  181. static struct string_elist *opt_set_device_list;
  182. bool opt_force_dev_init;
  183. static struct string_elist *opt_devices_enabled_list;
  184. static bool opt_display_devs;
  185. int total_devices;
  186. struct cgpu_info **devices;
  187. int total_devices_new;
  188. struct cgpu_info **devices_new;
  189. bool have_opencl;
  190. int opt_n_threads = -1;
  191. int mining_threads;
  192. int base_queue;
  193. int num_processors;
  194. #ifdef HAVE_CURSES
  195. bool use_curses = true;
  196. #else
  197. bool use_curses;
  198. #endif
  199. int last_logstatusline_len;
  200. #ifdef HAVE_LIBUSB
  201. bool have_libusb;
  202. #endif
  203. static bool opt_submit_stale = true;
  204. static float opt_shares;
  205. static int opt_submit_threads = 0x40;
  206. bool opt_fail_only;
  207. int opt_fail_switch_delay = 300;
  208. bool opt_autofan;
  209. bool opt_autoengine;
  210. bool opt_noadl;
  211. char *opt_api_allow = NULL;
  212. char *opt_api_groups;
  213. char *opt_api_description = PACKAGE_STRING;
  214. int opt_api_port = 4028;
  215. bool opt_api_listen;
  216. bool opt_api_mcast;
  217. char *opt_api_mcast_addr = API_MCAST_ADDR;
  218. char *opt_api_mcast_code = API_MCAST_CODE;
  219. char *opt_api_mcast_des = "";
  220. int opt_api_mcast_port = 4028;
  221. bool opt_api_network;
  222. bool opt_delaynet;
  223. bool opt_disable_pool;
  224. bool opt_disable_client_reconnect = false;
  225. static bool no_work;
  226. bool opt_worktime;
  227. bool opt_weighed_stats;
  228. char *opt_kernel_path;
  229. char *cgminer_path;
  230. #if defined(USE_BITFORCE)
  231. bool opt_bfl_noncerange;
  232. #endif
  233. #define QUIET (opt_quiet || opt_realquiet)
  234. struct thr_info *control_thr;
  235. struct thr_info **mining_thr;
  236. static int watchpool_thr_id;
  237. static int watchdog_thr_id;
  238. #ifdef HAVE_CURSES
  239. static int input_thr_id;
  240. #endif
  241. int gpur_thr_id;
  242. static int api_thr_id;
  243. static int total_control_threads;
  244. pthread_mutex_t hash_lock;
  245. static pthread_mutex_t *stgd_lock;
  246. pthread_mutex_t console_lock;
  247. cglock_t ch_lock;
  248. static pthread_rwlock_t blk_lock;
  249. static pthread_mutex_t sshare_lock;
  250. pthread_rwlock_t netacc_lock;
  251. pthread_rwlock_t mining_thr_lock;
  252. pthread_rwlock_t devices_lock;
  253. static pthread_mutex_t lp_lock;
  254. static pthread_cond_t lp_cond;
  255. pthread_cond_t gws_cond;
  256. bool shutting_down;
  257. double total_rolling;
  258. double total_mhashes_done;
  259. static struct timeval total_tv_start, total_tv_end;
  260. static struct timeval miner_started;
  261. cglock_t control_lock;
  262. pthread_mutex_t stats_lock;
  263. static pthread_mutex_t submitting_lock;
  264. static int total_submitting;
  265. static struct work *submit_waiting;
  266. notifier_t submit_waiting_notifier;
  267. int hw_errors;
  268. int total_accepted, total_rejected;
  269. int total_getworks, total_stale, total_discarded;
  270. uint64_t total_bytes_rcvd, total_bytes_sent;
  271. double total_diff1, total_bad_diff1;
  272. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  273. static int staged_rollable;
  274. unsigned int new_blocks;
  275. unsigned int found_blocks;
  276. unsigned int local_work;
  277. unsigned int total_go, total_ro;
  278. struct pool **pools;
  279. static struct pool *currentpool = NULL;
  280. int total_pools, enabled_pools;
  281. enum pool_strategy pool_strategy = POOL_FAILOVER;
  282. int opt_rotate_period;
  283. static int total_urls, total_users, total_passes;
  284. static
  285. #ifndef HAVE_CURSES
  286. const
  287. #endif
  288. bool curses_active;
  289. #ifdef HAVE_CURSES
  290. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  291. const
  292. #endif
  293. short default_bgcolor = COLOR_BLACK;
  294. static int attr_title = A_BOLD;
  295. #endif
  296. static
  297. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  298. bool use_unicode;
  299. static
  300. bool have_unicode_degrees;
  301. static
  302. wchar_t unicode_micro = 'u';
  303. #else
  304. const bool use_unicode;
  305. static
  306. const bool have_unicode_degrees;
  307. #ifdef HAVE_CURSES
  308. static
  309. const char unicode_micro = 'u';
  310. #endif
  311. #endif
  312. #ifdef HAVE_CURSES
  313. #define U8_BAD_START "\xef\x80\x81"
  314. #define U8_BAD_END "\xef\x80\x80"
  315. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  316. /* logstart is where the log window should start */
  317. static int devcursor, logstart, logcursor;
  318. bool selecting_device;
  319. unsigned selected_device;
  320. #endif
  321. static int max_lpdigits;
  322. // current_hash was replaced with goal->current_goal_detail
  323. // current_block_id was replaced with blkchain->currentblk->block_id
  324. static char datestamp[40];
  325. static char best_share[ALLOC_H2B_SHORTV] = "0";
  326. double best_diff = 0;
  327. struct mining_algorithm *mining_algorithms;
  328. struct mining_goal_info *mining_goals;
  329. int active_goals = 1;
  330. int swork_id;
  331. /* For creating a hash database of stratum shares submitted that have not had
  332. * a response yet */
  333. struct stratum_share {
  334. UT_hash_handle hh;
  335. bool block;
  336. struct work *work;
  337. int id;
  338. };
  339. static struct stratum_share *stratum_shares = NULL;
  340. char *opt_socks_proxy = NULL;
  341. static const char def_conf[] = "bfgminer.conf";
  342. static bool config_loaded;
  343. static int include_count;
  344. #define JSON_INCLUDE_CONF "include"
  345. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  346. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  347. #define JSON_MAX_DEPTH 10
  348. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  349. char *cmd_idle, *cmd_sick, *cmd_dead;
  350. #if defined(unix) || defined(__APPLE__)
  351. static char *opt_stderr_cmd = NULL;
  352. static int forkpid;
  353. #endif // defined(unix)
  354. #ifdef HAVE_CHROOT
  355. char *chroot_dir;
  356. #endif
  357. #ifdef HAVE_PWD_H
  358. char *opt_setuid;
  359. #endif
  360. struct sigaction termhandler, inthandler;
  361. struct thread_q *getq;
  362. static int total_work;
  363. static bool staged_full;
  364. struct work *staged_work = NULL;
  365. struct schedtime {
  366. bool enable;
  367. struct tm tm;
  368. };
  369. struct schedtime schedstart;
  370. struct schedtime schedstop;
  371. bool sched_paused;
  372. static bool time_before(struct tm *tm1, struct tm *tm2)
  373. {
  374. if (tm1->tm_hour < tm2->tm_hour)
  375. return true;
  376. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  377. return true;
  378. return false;
  379. }
  380. static bool should_run(void)
  381. {
  382. struct tm tm;
  383. time_t tt;
  384. bool within_range;
  385. if (!schedstart.enable && !schedstop.enable)
  386. return true;
  387. tt = time(NULL);
  388. localtime_r(&tt, &tm);
  389. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  390. if (time_before(&schedstop.tm, &schedstart.tm))
  391. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  392. else
  393. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  394. if (within_range && !schedstop.enable)
  395. /* This is a once off event with no stop time set */
  396. schedstart.enable = false;
  397. return within_range;
  398. }
  399. void get_datestamp(char *f, size_t fsiz, time_t tt)
  400. {
  401. struct tm _tm;
  402. struct tm *tm = &_tm;
  403. if (tt == INVALID_TIMESTAMP)
  404. tt = time(NULL);
  405. localtime_r(&tt, tm);
  406. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  407. tm->tm_year + 1900,
  408. tm->tm_mon + 1,
  409. tm->tm_mday,
  410. tm->tm_hour,
  411. tm->tm_min,
  412. tm->tm_sec);
  413. }
  414. static
  415. void get_timestamp(char *f, size_t fsiz, time_t tt)
  416. {
  417. struct tm _tm;
  418. struct tm *tm = &_tm;
  419. localtime_r(&tt, tm);
  420. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  421. tm->tm_hour,
  422. tm->tm_min,
  423. tm->tm_sec);
  424. }
  425. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  426. static char exit_buf[512];
  427. static void applog_and_exit(const char *fmt, ...)
  428. {
  429. va_list ap;
  430. va_start(ap, fmt);
  431. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  432. va_end(ap);
  433. _applog(LOG_ERR, exit_buf);
  434. exit(1);
  435. }
  436. static
  437. float drv_min_nonce_diff(const struct device_drv * const drv, struct cgpu_info * const proc, const struct mining_algorithm * const malgo)
  438. {
  439. if (drv->drv_min_nonce_diff)
  440. return drv->drv_min_nonce_diff(proc, malgo);
  441. return (malgo->algo == POW_SHA256D) ? 1. : -1.;
  442. }
  443. char *devpath_to_devid(const char *devpath)
  444. {
  445. #ifndef WIN32
  446. if (devpath[0] != '/')
  447. return NULL;
  448. struct stat my_stat;
  449. if (stat(devpath, &my_stat))
  450. return NULL;
  451. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  452. memcpy(devs, "dev_t:", 6);
  453. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  454. #else
  455. if (!strncmp(devpath, "\\\\.\\", 4))
  456. devpath += 4;
  457. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  458. return NULL;
  459. devpath += 3;
  460. char *p;
  461. strtol(devpath, &p, 10);
  462. if (p[0])
  463. return NULL;
  464. const int sz = (p - devpath);
  465. char *devs = malloc(4 + sz + 1);
  466. sprintf(devs, "com:%s", devpath);
  467. #endif
  468. return devs;
  469. }
  470. static
  471. bool devpaths_match(const char * const ap, const char * const bp)
  472. {
  473. char * const a = devpath_to_devid(ap);
  474. if (!a)
  475. return false;
  476. char * const b = devpath_to_devid(bp);
  477. bool rv = false;
  478. if (b)
  479. {
  480. rv = !strcmp(a, b);
  481. free(b);
  482. }
  483. free(a);
  484. return rv;
  485. }
  486. static
  487. int proc_letter_to_number(const char *s, const char ** const rem)
  488. {
  489. int n = 0, c;
  490. for ( ; s[0]; ++s)
  491. {
  492. if (unlikely(n > INT_MAX / 26))
  493. break;
  494. c = tolower(s[0]) - 'a';
  495. if (unlikely(c < 0 || c > 25))
  496. break;
  497. if (unlikely(INT_MAX - c < n))
  498. break;
  499. n = (n * 26) + c;
  500. }
  501. *rem = s;
  502. return n;
  503. }
  504. static
  505. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  506. {
  507. // all - matches anything
  508. // d0 - matches all processors of device 0
  509. // d0-3 - matches all processors of device 0, 1, 2, or 3
  510. // d0a - matches first processor of device 0
  511. // 0 - matches processor 0
  512. // 0-4 - matches processors 0, 1, 2, 3, or 4
  513. // ___ - matches all processors on all devices using driver/name ___
  514. // ___0 - matches all processors of 0th device using driver/name ___
  515. // ___0a - matches first processor of 0th device using driver/name ___
  516. // @* - matches device with serial or path *
  517. // @*@a - matches first processor of device with serial or path *
  518. // ___@* - matches device with serial or path * using driver/name ___
  519. if (!strcasecmp(pattern, "all"))
  520. return true;
  521. const struct device_drv * const drv = cgpu->drv;
  522. const char *p = pattern, *p2;
  523. size_t L;
  524. int n, i, c = -1;
  525. int n2;
  526. int proc_first = -1, proc_last = -1;
  527. struct cgpu_info *device;
  528. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  529. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  530. // dname or name
  531. p = &pattern[L];
  532. else
  533. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  534. // d#
  535. ++p;
  536. else
  537. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  538. // # or @
  539. {}
  540. else
  541. return false;
  542. L = p - pattern;
  543. while (isspace(p[0]))
  544. ++p;
  545. if (p[0] == '@')
  546. {
  547. // Serial/path
  548. const char * const ser = &p[1];
  549. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  550. {}
  551. p2 = (p[0] == '@') ? &p[1] : p;
  552. const size_t serlen = (p - ser);
  553. p = "";
  554. n = n2 = 0;
  555. const char * const devpath = cgpu->device_path ?: "";
  556. const char * const devser = cgpu->dev_serial ?: "";
  557. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  558. {} // Match
  559. else
  560. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  561. {} // Match
  562. else
  563. {
  564. char devpath2[serlen + 1];
  565. memcpy(devpath2, ser, serlen);
  566. devpath2[serlen] = '\0';
  567. if (!devpaths_match(devpath, ser))
  568. return false;
  569. }
  570. }
  571. else
  572. {
  573. if (isdigit(p[0]))
  574. n = strtol(p, (void*)&p2, 0);
  575. else
  576. {
  577. n = 0;
  578. p2 = p;
  579. }
  580. if (p2[0] == '-')
  581. {
  582. ++p2;
  583. if (p2[0] && isdigit(p2[0]))
  584. n2 = strtol(p2, (void*)&p2, 0);
  585. else
  586. n2 = INT_MAX;
  587. }
  588. else
  589. n2 = n;
  590. if (p == pattern)
  591. {
  592. if (!p[0])
  593. return true;
  594. if (p2 && p2[0])
  595. goto invsyntax;
  596. for (i = n; i <= n2; ++i)
  597. {
  598. if (i >= total_devices)
  599. break;
  600. if (cgpu == devices[i])
  601. return true;
  602. }
  603. return false;
  604. }
  605. }
  606. if (p2[0])
  607. {
  608. proc_first = proc_letter_to_number(&p2[0], &p2);
  609. if (p2[0] == '-')
  610. {
  611. ++p2;
  612. if (p2[0])
  613. proc_last = proc_letter_to_number(p2, &p2);
  614. else
  615. proc_last = INT_MAX;
  616. }
  617. else
  618. proc_last = proc_first;
  619. if (p2[0])
  620. goto invsyntax;
  621. }
  622. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  623. {
  624. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  625. (!L) ||
  626. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  627. {} // Matched name or dname
  628. else
  629. return false;
  630. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  631. return false;
  632. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  633. return false;
  634. return true;
  635. }
  636. // d#
  637. c = -1;
  638. for (i = 0; ; ++i)
  639. {
  640. if (i == total_devices)
  641. return false;
  642. if (devices[i]->device != devices[i])
  643. continue;
  644. ++c;
  645. if (c < n)
  646. continue;
  647. if (c > n2)
  648. break;
  649. for (device = devices[i]; device; device = device->next_proc)
  650. {
  651. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  652. continue;
  653. if (device == cgpu)
  654. return true;
  655. }
  656. }
  657. return false;
  658. invsyntax:
  659. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  660. return false;
  661. }
  662. #define TEST_CGPU_MATCH(pattern) \
  663. if (!cgpu_match(pattern, &cgpu)) \
  664. { \
  665. ++unittest_failures; \
  666. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  667. } \
  668. // END TEST_CGPU_MATCH
  669. #define TEST_CGPU_NOMATCH(pattern) \
  670. if (cgpu_match(pattern, &cgpu)) \
  671. { \
  672. ++unittest_failures; \
  673. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  674. } \
  675. // END TEST_CGPU_MATCH
  676. static __maybe_unused
  677. void test_cgpu_match()
  678. {
  679. struct device_drv drv = {
  680. .dname = "test",
  681. .name = "TST",
  682. };
  683. struct cgpu_info cgpu = {
  684. .drv = &drv,
  685. .device = &cgpu,
  686. .device_id = 1,
  687. .proc_id = 1,
  688. .proc_repr = "TST 1b",
  689. }, cgpu0a = {
  690. .drv = &drv,
  691. .device = &cgpu0a,
  692. .device_id = 0,
  693. .proc_id = 0,
  694. .proc_repr = "TST 0a",
  695. }, cgpu1a = {
  696. .drv = &drv,
  697. .device = &cgpu0a,
  698. .device_id = 1,
  699. .proc_id = 0,
  700. .proc_repr = "TST 1a",
  701. };
  702. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  703. devices = devices_list;
  704. total_devices = 3;
  705. TEST_CGPU_MATCH("all")
  706. TEST_CGPU_MATCH("d1")
  707. TEST_CGPU_NOMATCH("d2")
  708. TEST_CGPU_MATCH("d0-5")
  709. TEST_CGPU_NOMATCH("d0-0")
  710. TEST_CGPU_NOMATCH("d2-5")
  711. TEST_CGPU_MATCH("d-1")
  712. TEST_CGPU_MATCH("d1-")
  713. TEST_CGPU_NOMATCH("d-0")
  714. TEST_CGPU_NOMATCH("d2-")
  715. TEST_CGPU_MATCH("2")
  716. TEST_CGPU_NOMATCH("3")
  717. TEST_CGPU_MATCH("1-2")
  718. TEST_CGPU_MATCH("2-3")
  719. TEST_CGPU_NOMATCH("1-1")
  720. TEST_CGPU_NOMATCH("3-4")
  721. TEST_CGPU_MATCH("TST")
  722. TEST_CGPU_MATCH("test")
  723. TEST_CGPU_MATCH("tst")
  724. TEST_CGPU_MATCH("TEST")
  725. TEST_CGPU_NOMATCH("TSF")
  726. TEST_CGPU_NOMATCH("TS")
  727. TEST_CGPU_NOMATCH("TSTF")
  728. TEST_CGPU_MATCH("TST1")
  729. TEST_CGPU_MATCH("test1")
  730. TEST_CGPU_MATCH("TST0-1")
  731. TEST_CGPU_MATCH("TST 1")
  732. TEST_CGPU_MATCH("TST 1-2")
  733. TEST_CGPU_MATCH("TEST 1-2")
  734. TEST_CGPU_NOMATCH("TST2")
  735. TEST_CGPU_NOMATCH("TST2-3")
  736. TEST_CGPU_NOMATCH("TST0-0")
  737. TEST_CGPU_MATCH("TST1b")
  738. TEST_CGPU_MATCH("tst1b")
  739. TEST_CGPU_NOMATCH("TST1c")
  740. TEST_CGPU_NOMATCH("TST1bb")
  741. TEST_CGPU_MATCH("TST0-1b")
  742. TEST_CGPU_NOMATCH("TST0-1c")
  743. TEST_CGPU_MATCH("TST1a-d")
  744. TEST_CGPU_NOMATCH("TST1a-a")
  745. TEST_CGPU_NOMATCH("TST1-a")
  746. TEST_CGPU_NOMATCH("TST1c-z")
  747. TEST_CGPU_NOMATCH("TST1c-")
  748. TEST_CGPU_MATCH("@")
  749. TEST_CGPU_NOMATCH("@abc")
  750. TEST_CGPU_MATCH("@@b")
  751. TEST_CGPU_NOMATCH("@@c")
  752. TEST_CGPU_MATCH("TST@")
  753. TEST_CGPU_NOMATCH("TST@abc")
  754. TEST_CGPU_MATCH("TST@@b")
  755. TEST_CGPU_NOMATCH("TST@@c")
  756. TEST_CGPU_MATCH("TST@@b-f")
  757. TEST_CGPU_NOMATCH("TST@@c-f")
  758. TEST_CGPU_NOMATCH("TST@@-a")
  759. cgpu.device_path = "/dev/test";
  760. cgpu.dev_serial = "testy";
  761. TEST_CGPU_MATCH("TST@/dev/test")
  762. TEST_CGPU_MATCH("TST@testy")
  763. TEST_CGPU_NOMATCH("TST@")
  764. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  765. TEST_CGPU_NOMATCH("TST@testy3@b")
  766. TEST_CGPU_MATCH("TST@/dev/test@b")
  767. TEST_CGPU_MATCH("TST@testy@b")
  768. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  769. TEST_CGPU_NOMATCH("TST@testy@c")
  770. cgpu.device_path = "usb:000:999";
  771. TEST_CGPU_MATCH("TST@usb:000:999")
  772. drv.dname = "test7";
  773. TEST_CGPU_MATCH("test7")
  774. TEST_CGPU_MATCH("TEST7")
  775. TEST_CGPU_NOMATCH("test&")
  776. TEST_CGPU_MATCH("test7 1-2")
  777. TEST_CGPU_MATCH("test7@testy@b")
  778. }
  779. static
  780. int cgpu_search(const char * const pattern, const int first)
  781. {
  782. int i;
  783. struct cgpu_info *cgpu;
  784. #define CHECK_CGPU_SEARCH do{ \
  785. cgpu = get_devices(i); \
  786. if (cgpu_match(pattern, cgpu)) \
  787. return i; \
  788. }while(0)
  789. for (i = first; i < total_devices; ++i)
  790. CHECK_CGPU_SEARCH;
  791. for (i = 0; i < first; ++i)
  792. CHECK_CGPU_SEARCH;
  793. #undef CHECK_CGPU_SEARCH
  794. return -1;
  795. }
  796. static pthread_mutex_t sharelog_lock;
  797. static FILE *sharelog_file = NULL;
  798. struct thr_info *get_thread(int thr_id)
  799. {
  800. struct thr_info *thr;
  801. rd_lock(&mining_thr_lock);
  802. thr = mining_thr[thr_id];
  803. rd_unlock(&mining_thr_lock);
  804. return thr;
  805. }
  806. static struct cgpu_info *get_thr_cgpu(int thr_id)
  807. {
  808. struct thr_info *thr = get_thread(thr_id);
  809. return thr->cgpu;
  810. }
  811. struct cgpu_info *get_devices(int id)
  812. {
  813. struct cgpu_info *cgpu;
  814. rd_lock(&devices_lock);
  815. cgpu = devices[id];
  816. rd_unlock(&devices_lock);
  817. return cgpu;
  818. }
  819. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  820. static FILE *noncelog_file = NULL;
  821. static
  822. void noncelog(const struct work * const work)
  823. {
  824. const int thr_id = work->thr_id;
  825. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  826. char buf[0x200], hash[65], data[161], midstate[65];
  827. int rv;
  828. size_t ret;
  829. bin2hex(hash, work->hash, 32);
  830. bin2hex(data, work->data, 80);
  831. bin2hex(midstate, work->midstate, 32);
  832. // timestamp,proc,hash,data,midstate
  833. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  834. (unsigned long)time(NULL), proc->proc_repr_ns,
  835. hash, data, midstate);
  836. if (unlikely(rv < 1))
  837. {
  838. applog(LOG_ERR, "noncelog printf error");
  839. return;
  840. }
  841. mutex_lock(&noncelog_lock);
  842. ret = fwrite(buf, rv, 1, noncelog_file);
  843. fflush(noncelog_file);
  844. mutex_unlock(&noncelog_lock);
  845. if (ret != 1)
  846. applog(LOG_ERR, "noncelog fwrite error");
  847. }
  848. static void sharelog(const char*disposition, const struct work*work)
  849. {
  850. char target[(sizeof(work->target) * 2) + 1];
  851. char hash[(sizeof(work->hash) * 2) + 1];
  852. char data[(sizeof(work->data) * 2) + 1];
  853. struct cgpu_info *cgpu;
  854. unsigned long int t;
  855. struct pool *pool;
  856. int thr_id, rv;
  857. char s[1024];
  858. size_t ret;
  859. if (!sharelog_file)
  860. return;
  861. thr_id = work->thr_id;
  862. cgpu = get_thr_cgpu(thr_id);
  863. pool = work->pool;
  864. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  865. bin2hex(target, work->target, sizeof(work->target));
  866. bin2hex(hash, work->hash, sizeof(work->hash));
  867. bin2hex(data, work->data, sizeof(work->data));
  868. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  869. 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);
  870. if (rv >= (int)(sizeof(s)))
  871. s[sizeof(s) - 1] = '\0';
  872. else if (rv < 0) {
  873. applog(LOG_ERR, "sharelog printf error");
  874. return;
  875. }
  876. mutex_lock(&sharelog_lock);
  877. ret = fwrite(s, rv, 1, sharelog_file);
  878. fflush(sharelog_file);
  879. mutex_unlock(&sharelog_lock);
  880. if (ret != 1)
  881. applog(LOG_ERR, "sharelog fwrite error");
  882. }
  883. #ifdef HAVE_CURSES
  884. static void switch_logsize(void);
  885. #endif
  886. static void hotplug_trigger();
  887. static
  888. void goal_set_malgo(struct mining_goal_info * const goal, struct mining_algorithm * const malgo)
  889. {
  890. if (goal->malgo == malgo)
  891. return;
  892. if (goal->malgo)
  893. --goal->malgo->goal_refs;
  894. if (malgo->goal_refs++)
  895. // First time using a new mining algorithm may means we need to add mining hardware to support it
  896. // 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)
  897. if (opt_hotplug && api_thr_id)
  898. hotplug_trigger();
  899. goal->malgo = malgo;
  900. }
  901. static
  902. struct mining_algorithm *mining_algorithm_by_alias(const char * const alias)
  903. {
  904. struct mining_algorithm *malgo;
  905. LL_FOREACH(mining_algorithms, malgo)
  906. {
  907. if (match_strtok(malgo->aliases, "|", alias))
  908. return malgo;
  909. }
  910. return NULL;
  911. }
  912. #ifdef HAVE_OPENCL
  913. static
  914. float opencl_oclthreads_to_intensity_sha256d(const unsigned long oclthreads)
  915. {
  916. return log2f(oclthreads) - 15.;
  917. }
  918. static
  919. unsigned long opencl_intensity_to_oclthreads_sha256d(float intensity)
  920. {
  921. return powf(2, intensity + 15);
  922. }
  923. #endif
  924. static struct mining_algorithm malgo_sha256d = {
  925. .name = "SHA256d",
  926. .aliases = "SHA256d|SHA256|SHA2",
  927. .algo = POW_SHA256D,
  928. .ui_skip_hash_bytes = 4,
  929. .worktime_skip_prevblk_u32 = 1,
  930. .reasonable_low_nonce_diff = 1.,
  931. .hash_data_f = hash_data,
  932. #ifdef HAVE_OPENCL
  933. .opencl_nodefault = true,
  934. .opencl_oclthreads_to_intensity = opencl_oclthreads_to_intensity_sha256d,
  935. .opencl_intensity_to_oclthreads = opencl_intensity_to_oclthreads_sha256d,
  936. .opencl_min_oclthreads = 0x20, // intensity -10
  937. .opencl_max_oclthreads = 0x20000000, // intensity 14
  938. #endif
  939. };
  940. #ifdef USE_SCRYPT
  941. #ifdef HAVE_OPENCL
  942. static
  943. float opencl_oclthreads_to_intensity_scrypt(const unsigned long oclthreads)
  944. {
  945. return log2(oclthreads);
  946. }
  947. static
  948. unsigned long opencl_intensity_to_oclthreads_scrypt(float intensity)
  949. {
  950. return pow(2, intensity);
  951. }
  952. #endif
  953. static struct mining_algorithm malgo_scrypt = {
  954. .name = "scrypt",
  955. .aliases = "scrypt",
  956. .algo = POW_SCRYPT,
  957. .ui_skip_hash_bytes = 2,
  958. .reasonable_low_nonce_diff = 1./0x10000,
  959. .hash_data_f = scrypt_hash_data,
  960. #ifdef HAVE_OPENCL
  961. .opencl_oclthreads_to_intensity = opencl_oclthreads_to_intensity_scrypt,
  962. .opencl_intensity_to_oclthreads = opencl_intensity_to_oclthreads_scrypt,
  963. .opencl_min_oclthreads = 0x100, // intensity 8
  964. .opencl_max_oclthreads = 0x20000000, // intensity 31
  965. #endif
  966. };
  967. static
  968. const char *set_malgo_scrypt()
  969. {
  970. goal_set_malgo(get_mining_goal("default"), &malgo_scrypt);
  971. return NULL;
  972. }
  973. #endif
  974. static
  975. __attribute__((constructor))
  976. void init_mining_goals(struct mining_goal_info * const goal, const struct mining_algorithm * const malgo)
  977. {
  978. LL_APPEND(mining_algorithms, (&malgo_sha256d));
  979. #ifdef USE_SCRYPT
  980. LL_APPEND(mining_algorithms, (&malgo_scrypt));
  981. #endif
  982. }
  983. static
  984. int mining_goals_name_cmp(const struct mining_goal_info * const a, const struct mining_goal_info * const b)
  985. {
  986. // default always goes first
  987. if (a->is_default)
  988. return -1;
  989. if (b->is_default)
  990. return 1;
  991. return strcmp(a->name, b->name);
  992. }
  993. static
  994. void blkchain_init_block(struct blockchain_info * const blkchain)
  995. {
  996. struct block_info * const dummy_block = calloc(sizeof(*dummy_block), 1);
  997. memset(dummy_block->prevblkhash, 0, 0x20);
  998. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(dummy_block->prevblkhash), dummy_block);
  999. blkchain->currentblk = dummy_block;
  1000. }
  1001. struct mining_goal_info *get_mining_goal(const char * const name)
  1002. {
  1003. static unsigned next_goal_id;
  1004. struct mining_goal_info *goal;
  1005. HASH_FIND_STR(mining_goals, name, goal);
  1006. if (!goal)
  1007. {
  1008. struct blockchain_info * const blkchain = malloc(sizeof(*blkchain) + sizeof(*goal));
  1009. goal = (void*)(&blkchain[1]);
  1010. *blkchain = (struct blockchain_info){
  1011. .currentblk = NULL,
  1012. };
  1013. blkchain_init_block(blkchain);
  1014. *goal = (struct mining_goal_info){
  1015. .id = next_goal_id++,
  1016. .name = strdup(name),
  1017. .is_default = !strcmp(name, "default"),
  1018. .blkchain = blkchain,
  1019. .current_diff = 0xFFFFFFFFFFFFFFFFULL,
  1020. };
  1021. goal_set_malgo(goal, &malgo_sha256d);
  1022. HASH_ADD_STR(mining_goals, name, goal);
  1023. HASH_SORT(mining_goals, mining_goals_name_cmp);
  1024. #ifdef HAVE_CURSES
  1025. devcursor = 7 + active_goals;
  1026. switch_logsize();
  1027. #endif
  1028. }
  1029. return goal;
  1030. }
  1031. void mining_goal_reset(struct mining_goal_info * const goal)
  1032. {
  1033. struct blockchain_info * const blkchain = goal->blkchain;
  1034. struct block_info *blkinfo, *tmpblkinfo;
  1035. HASH_ITER(hh, blkchain->blocks, blkinfo, tmpblkinfo)
  1036. {
  1037. HASH_DEL(blkchain->blocks, blkinfo);
  1038. free(blkinfo);
  1039. }
  1040. blkchain_init_block(blkchain);
  1041. }
  1042. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  1043. /* Adjust all the pools' quota to the greatest common denominator after a pool
  1044. * has been added or the quotas changed. */
  1045. void adjust_quota_gcd(void)
  1046. {
  1047. unsigned long gcd, lowest_quota = ~0UL, quota;
  1048. struct pool *pool;
  1049. int i;
  1050. for (i = 0; i < total_pools; i++) {
  1051. pool = pools[i];
  1052. quota = pool->quota;
  1053. if (!quota)
  1054. continue;
  1055. if (quota < lowest_quota)
  1056. lowest_quota = quota;
  1057. }
  1058. if (likely(lowest_quota < ~0UL)) {
  1059. gcd = lowest_quota;
  1060. for (i = 0; i < total_pools; i++) {
  1061. pool = pools[i];
  1062. quota = pool->quota;
  1063. if (!quota)
  1064. continue;
  1065. while (quota % gcd)
  1066. gcd--;
  1067. }
  1068. } else
  1069. gcd = 1;
  1070. for (i = 0; i < total_pools; i++) {
  1071. pool = pools[i];
  1072. pool->quota_used *= global_quota_gcd;
  1073. pool->quota_used /= gcd;
  1074. pool->quota_gcd = pool->quota / gcd;
  1075. }
  1076. global_quota_gcd = gcd;
  1077. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  1078. }
  1079. /* Return value is ignored if not called from add_pool_details */
  1080. struct pool *add_pool2(struct mining_goal_info * const goal)
  1081. {
  1082. struct pool *pool;
  1083. pool = calloc(sizeof(struct pool), 1);
  1084. if (!pool)
  1085. quit(1, "Failed to malloc pool in add_pool");
  1086. pool->pool_no = pool->prio = total_pools;
  1087. mutex_init(&pool->last_work_lock);
  1088. mutex_init(&pool->pool_lock);
  1089. mutex_init(&pool->pool_test_lock);
  1090. if (unlikely(pthread_cond_init(&pool->cr_cond, bfg_condattr)))
  1091. quit(1, "Failed to pthread_cond_init in add_pool");
  1092. cglock_init(&pool->data_lock);
  1093. mutex_init(&pool->stratum_lock);
  1094. timer_unset(&pool->swork.tv_transparency);
  1095. pool->swork.pool = pool;
  1096. pool->goal = goal;
  1097. pool->idle = true;
  1098. /* Make sure the pool doesn't think we've been idle since time 0 */
  1099. pool->tv_idle.tv_sec = ~0UL;
  1100. cgtime(&pool->cgminer_stats.start_tv);
  1101. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1102. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  1103. pool->rpc_proxy = NULL;
  1104. pool->quota = 1;
  1105. pool->sock = INVSOCK;
  1106. pool->lp_socket = CURL_SOCKET_BAD;
  1107. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  1108. pools[total_pools++] = pool;
  1109. if (opt_benchmark)
  1110. {
  1111. // Immediately remove it
  1112. remove_pool(pool);
  1113. return pool;
  1114. }
  1115. adjust_quota_gcd();
  1116. if (!currentpool)
  1117. currentpool = pool;
  1118. enable_pool(pool);
  1119. return pool;
  1120. }
  1121. static
  1122. void pool_set_uri(struct pool * const pool, char * const uri)
  1123. {
  1124. pool->rpc_url = uri;
  1125. }
  1126. /* Pool variant of test and set */
  1127. static bool pool_tset(struct pool *pool, bool *var)
  1128. {
  1129. bool ret;
  1130. mutex_lock(&pool->pool_lock);
  1131. ret = *var;
  1132. *var = true;
  1133. mutex_unlock(&pool->pool_lock);
  1134. return ret;
  1135. }
  1136. bool pool_tclear(struct pool *pool, bool *var)
  1137. {
  1138. bool ret;
  1139. mutex_lock(&pool->pool_lock);
  1140. ret = *var;
  1141. *var = false;
  1142. mutex_unlock(&pool->pool_lock);
  1143. return ret;
  1144. }
  1145. struct pool *current_pool(void)
  1146. {
  1147. struct pool *pool;
  1148. cg_rlock(&control_lock);
  1149. pool = currentpool;
  1150. cg_runlock(&control_lock);
  1151. return pool;
  1152. }
  1153. static
  1154. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1155. {
  1156. return opt_set_bool(b);
  1157. }
  1158. char *set_int_range(const char *arg, int *i, int min, int max)
  1159. {
  1160. char *err = opt_set_intval(arg, i);
  1161. if (err)
  1162. return err;
  1163. if (*i < min || *i > max)
  1164. return "Value out of range";
  1165. return NULL;
  1166. }
  1167. static char *set_int_0_to_9999(const char *arg, int *i)
  1168. {
  1169. return set_int_range(arg, i, 0, 9999);
  1170. }
  1171. static char *set_int_1_to_65535(const char *arg, int *i)
  1172. {
  1173. return set_int_range(arg, i, 1, 65535);
  1174. }
  1175. static char *set_int_0_to_10(const char *arg, int *i)
  1176. {
  1177. return set_int_range(arg, i, 0, 10);
  1178. }
  1179. static char *set_int_1_to_10(const char *arg, int *i)
  1180. {
  1181. return set_int_range(arg, i, 1, 10);
  1182. }
  1183. char *set_strdup(const char *arg, char **p)
  1184. {
  1185. *p = strdup((char *)arg);
  1186. return NULL;
  1187. }
  1188. #if BLKMAKER_VERSION > 1
  1189. static
  1190. char *set_b58addr(const char * const arg, bytes_t * const b)
  1191. {
  1192. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1193. if (!scriptsz)
  1194. return "Invalid address";
  1195. char *script = malloc(scriptsz);
  1196. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1197. free(script);
  1198. return "Failed to convert address to script";
  1199. }
  1200. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1201. return NULL;
  1202. }
  1203. static char *set_generate_addr2(struct mining_goal_info *, const char *);
  1204. static
  1205. char *set_generate_addr(char *arg)
  1206. {
  1207. char * const colon = strchr(arg, ':');
  1208. struct mining_goal_info *goal;
  1209. if (colon)
  1210. {
  1211. colon[0] = '\0';
  1212. goal = get_mining_goal(arg);
  1213. arg = &colon[1];
  1214. }
  1215. else
  1216. goal = get_mining_goal("default");
  1217. return set_generate_addr2(goal, arg);
  1218. }
  1219. static
  1220. char *set_generate_addr2(struct mining_goal_info * const goal, const char * const arg)
  1221. {
  1222. bytes_t newscript = BYTES_INIT;
  1223. char *estr = set_b58addr(arg, &newscript);
  1224. if (estr)
  1225. {
  1226. bytes_free(&newscript);
  1227. return estr;
  1228. }
  1229. if (!goal->generation_script)
  1230. {
  1231. goal->generation_script = malloc(sizeof(*goal->generation_script));
  1232. bytes_init(goal->generation_script);
  1233. }
  1234. bytes_assimilate(goal->generation_script, &newscript);
  1235. bytes_free(&newscript);
  1236. return NULL;
  1237. }
  1238. #endif
  1239. static
  1240. char *set_quit_summary(const char * const arg)
  1241. {
  1242. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1243. opt_quit_summary = BQS_NONE;
  1244. else
  1245. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1246. opt_quit_summary = BQS_DEVS;
  1247. else
  1248. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1249. opt_quit_summary = BQS_PROCS;
  1250. else
  1251. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1252. opt_quit_summary = BQS_DETAILED;
  1253. else
  1254. return "Quit summary must be one of none/devs/procs/detailed";
  1255. return NULL;
  1256. }
  1257. static void pdiff_target_leadzero(void *, double);
  1258. char *set_request_diff(const char *arg, float *p)
  1259. {
  1260. unsigned char target[32];
  1261. char *e = opt_set_floatval(arg, p);
  1262. if (e)
  1263. return e;
  1264. request_bdiff = (double)*p * 0.9999847412109375;
  1265. pdiff_target_leadzero(target, *p);
  1266. request_target_str = malloc(65);
  1267. bin2hex(request_target_str, target, 32);
  1268. return NULL;
  1269. }
  1270. #ifdef NEED_BFG_LOWL_VCOM
  1271. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1272. #ifdef WIN32
  1273. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1274. {
  1275. char dev[PATH_MAX];
  1276. char *devp = dev;
  1277. size_t bufLen = 0x100;
  1278. tryagain: ;
  1279. char buf[bufLen];
  1280. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1281. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1282. bufLen *= 2;
  1283. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1284. goto tryagain;
  1285. }
  1286. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1287. }
  1288. size_t tLen;
  1289. memcpy(devp, "\\\\.\\", 4);
  1290. devp = &devp[4];
  1291. for (char *t = buf; *t; t += tLen) {
  1292. tLen = strlen(t) + 1;
  1293. if (strncmp("COM", t, 3))
  1294. continue;
  1295. memcpy(devp, t, tLen);
  1296. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1297. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1298. }
  1299. }
  1300. #else
  1301. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1302. {
  1303. char dev[PATH_MAX];
  1304. char *devp = dev;
  1305. DIR *D;
  1306. struct dirent *de;
  1307. const char devdir[] = "/dev";
  1308. const size_t devdirlen = sizeof(devdir) - 1;
  1309. char *devpath = devp;
  1310. char *devfile = devpath + devdirlen + 1;
  1311. D = opendir(devdir);
  1312. if (!D)
  1313. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1314. memcpy(devpath, devdir, devdirlen);
  1315. devpath[devdirlen] = '/';
  1316. while ( (de = readdir(D)) ) {
  1317. if (!strncmp(de->d_name, "cu.", 3)
  1318. //don't probe Bluetooth devices - causes bus errors and segfaults
  1319. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1320. goto trydev;
  1321. if (strncmp(de->d_name, "tty", 3))
  1322. continue;
  1323. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1324. continue;
  1325. trydev:
  1326. strcpy(devfile, de->d_name);
  1327. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1328. }
  1329. closedir(D);
  1330. }
  1331. #endif
  1332. #endif
  1333. static char *add_serial(const char *arg)
  1334. {
  1335. string_elist_add(arg, &scan_devices);
  1336. return NULL;
  1337. }
  1338. static
  1339. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1340. {
  1341. string_elist_add(arg, elist);
  1342. return NULL;
  1343. }
  1344. bool get_intrange(const char *arg, int *val1, int *val2)
  1345. {
  1346. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1347. char *p, *p2;
  1348. *val1 = strtol(arg, &p, 0);
  1349. if (arg == p)
  1350. // Zero-length ending number, invalid
  1351. return false;
  1352. while (true)
  1353. {
  1354. if (!p[0])
  1355. {
  1356. *val2 = *val1;
  1357. return true;
  1358. }
  1359. if (p[0] == '-')
  1360. break;
  1361. if (!isspace(p[0]))
  1362. // Garbage, invalid
  1363. return false;
  1364. ++p;
  1365. }
  1366. p2 = &p[1];
  1367. *val2 = strtol(p2, &p, 0);
  1368. if (p2 == p)
  1369. // Zero-length ending number, invalid
  1370. return false;
  1371. while (true)
  1372. {
  1373. if (!p[0])
  1374. return true;
  1375. if (!isspace(p[0]))
  1376. // Garbage, invalid
  1377. return false;
  1378. ++p;
  1379. }
  1380. }
  1381. static
  1382. void _test_intrange(const char *s, const int v[2])
  1383. {
  1384. int a[2];
  1385. if (!get_intrange(s, &a[0], &a[1]))
  1386. {
  1387. ++unittest_failures;
  1388. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1389. }
  1390. for (int i = 0; i < 2; ++i)
  1391. if (unlikely(a[i] != v[i]))
  1392. {
  1393. ++unittest_failures;
  1394. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1395. }
  1396. }
  1397. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1398. static
  1399. void _test_intrange_fail(const char *s)
  1400. {
  1401. int a[2];
  1402. if (get_intrange(s, &a[0], &a[1]))
  1403. {
  1404. ++unittest_failures;
  1405. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1406. }
  1407. }
  1408. static
  1409. void test_intrange()
  1410. {
  1411. _test_intrange("-1--2", -1, -2);
  1412. _test_intrange("-1-2", -1, 2);
  1413. _test_intrange("1--2", 1, -2);
  1414. _test_intrange("1-2", 1, 2);
  1415. _test_intrange("111-222", 111, 222);
  1416. _test_intrange(" 11 - 22 ", 11, 22);
  1417. _test_intrange("+11-+22", 11, 22);
  1418. _test_intrange("-1", -1, -1);
  1419. _test_intrange_fail("all");
  1420. _test_intrange_fail("1-");
  1421. _test_intrange_fail("");
  1422. _test_intrange_fail("1-54x");
  1423. }
  1424. static char *set_devices(char *arg)
  1425. {
  1426. if (*arg) {
  1427. if (*arg == '?') {
  1428. opt_display_devs = true;
  1429. return NULL;
  1430. }
  1431. } else
  1432. return "Invalid device parameters";
  1433. string_elist_add(arg, &opt_devices_enabled_list);
  1434. return NULL;
  1435. }
  1436. static char *set_balance(enum pool_strategy *strategy)
  1437. {
  1438. *strategy = POOL_BALANCE;
  1439. return NULL;
  1440. }
  1441. static char *set_loadbalance(enum pool_strategy *strategy)
  1442. {
  1443. *strategy = POOL_LOADBALANCE;
  1444. return NULL;
  1445. }
  1446. static char *set_rotate(const char *arg, int *i)
  1447. {
  1448. pool_strategy = POOL_ROTATE;
  1449. return set_int_range(arg, i, 0, 9999);
  1450. }
  1451. static char *set_rr(enum pool_strategy *strategy)
  1452. {
  1453. *strategy = POOL_ROUNDROBIN;
  1454. return NULL;
  1455. }
  1456. static
  1457. char *set_benchmark_intense()
  1458. {
  1459. opt_benchmark = true;
  1460. opt_benchmark_intense = true;
  1461. return NULL;
  1462. }
  1463. /* Detect that url is for a stratum protocol either via the presence of
  1464. * stratum+tcp or by detecting a stratum server response */
  1465. bool detect_stratum(struct pool *pool, char *url)
  1466. {
  1467. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1468. return false;
  1469. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1470. pool_set_uri(pool, strdup(url));
  1471. pool->has_stratum = true;
  1472. pool->stratum_url = pool->sockaddr_url;
  1473. return true;
  1474. }
  1475. return false;
  1476. }
  1477. static struct pool *add_url(void)
  1478. {
  1479. total_urls++;
  1480. if (total_urls > total_pools)
  1481. add_pool();
  1482. return pools[total_urls - 1];
  1483. }
  1484. static void setup_url(struct pool *pool, char *arg)
  1485. {
  1486. if (detect_stratum(pool, arg))
  1487. return;
  1488. opt_set_charp(arg, &pool->rpc_url);
  1489. if (strncmp(arg, "http://", 7) &&
  1490. strncmp(arg, "https://", 8)) {
  1491. const size_t L = strlen(arg);
  1492. char *httpinput;
  1493. httpinput = malloc(8 + L);
  1494. if (!httpinput)
  1495. quit(1, "Failed to malloc httpinput");
  1496. sprintf(httpinput, "http://%s", arg);
  1497. pool_set_uri(pool, httpinput);
  1498. }
  1499. }
  1500. static char *set_url(char *arg)
  1501. {
  1502. struct pool *pool = add_url();
  1503. setup_url(pool, arg);
  1504. return NULL;
  1505. }
  1506. static char *set_quota(char *arg)
  1507. {
  1508. char *semicolon = strchr(arg, ';'), *url;
  1509. int len, qlen, quota;
  1510. struct pool *pool;
  1511. if (!semicolon)
  1512. return "No semicolon separated quota;URL pair found";
  1513. len = strlen(arg);
  1514. *semicolon = '\0';
  1515. qlen = strlen(arg);
  1516. if (!qlen)
  1517. return "No parameter for quota found";
  1518. len -= qlen + 1;
  1519. if (len < 1)
  1520. return "No parameter for URL found";
  1521. quota = atoi(arg);
  1522. if (quota < 0)
  1523. return "Invalid negative parameter for quota set";
  1524. url = arg + qlen + 1;
  1525. pool = add_url();
  1526. setup_url(pool, url);
  1527. pool->quota = quota;
  1528. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1529. adjust_quota_gcd();
  1530. return NULL;
  1531. }
  1532. static char *set_user(const char *arg)
  1533. {
  1534. struct pool *pool;
  1535. total_users++;
  1536. if (total_users > total_pools)
  1537. add_pool();
  1538. pool = pools[total_users - 1];
  1539. opt_set_charp(arg, &pool->rpc_user);
  1540. return NULL;
  1541. }
  1542. static char *set_pass(const char *arg)
  1543. {
  1544. struct pool *pool;
  1545. total_passes++;
  1546. if (total_passes > total_pools)
  1547. add_pool();
  1548. pool = pools[total_passes - 1];
  1549. opt_set_charp(arg, &pool->rpc_pass);
  1550. return NULL;
  1551. }
  1552. static char *set_userpass(const char *arg)
  1553. {
  1554. struct pool *pool;
  1555. char *updup;
  1556. if (total_users != total_passes)
  1557. return "User + pass options must be balanced before userpass";
  1558. ++total_users;
  1559. ++total_passes;
  1560. if (total_users > total_pools)
  1561. add_pool();
  1562. pool = pools[total_users - 1];
  1563. updup = strdup(arg);
  1564. opt_set_charp(arg, &pool->rpc_userpass);
  1565. pool->rpc_user = updup;
  1566. pool->rpc_pass = strchr(updup, ':');
  1567. if (pool->rpc_pass)
  1568. pool->rpc_pass++[0] = '\0';
  1569. else
  1570. pool->rpc_pass = &updup[strlen(updup)];
  1571. return NULL;
  1572. }
  1573. static char *set_cbcaddr(char *arg)
  1574. {
  1575. struct pool *pool;
  1576. char *p, *addr;
  1577. bytes_t target_script = BYTES_INIT;
  1578. if (!total_pools)
  1579. return "Define pool first, then the --coinbase-check-addr list";
  1580. pool = pools[total_pools - 1];
  1581. /* NOTE: 'x' is a new prefix which leads both mainnet and testnet address, we would
  1582. * need support it later, but now leave the code just so.
  1583. *
  1584. * Regarding details of address prefix 'x', check the below URL:
  1585. * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
  1586. */
  1587. pool->cb_param.testnet = (arg[0] != '1' && arg[0] != '3' && arg[0] != 'x');
  1588. for (; (addr = strtok_r(arg, ",", &p)); arg = NULL)
  1589. {
  1590. struct bytes_hashtbl *ah;
  1591. if (set_b58addr(addr, &target_script))
  1592. /* No bother to free memory since we are going to exit anyway */
  1593. return "Invalid address in --coinbase-check-address list";
  1594. HASH_FIND(hh, pool->cb_param.scripts, bytes_buf(&target_script), bytes_len(&target_script), ah);
  1595. if (!ah)
  1596. {
  1597. /* Note: for the below allocated memory we have good way to release its memory
  1598. * since we can't be sure there are no reference to the pool struct when remove_pool()
  1599. * get called.
  1600. *
  1601. * We just hope the remove_pool() would not be called many many times during
  1602. * the whole running life of this program.
  1603. */
  1604. ah = malloc(sizeof(*ah));
  1605. bytes_init(&ah->b);
  1606. bytes_assimilate(&ah->b, &target_script);
  1607. HASH_ADD(hh, pool->cb_param.scripts, b.buf, bytes_len(&ah->b), ah);
  1608. }
  1609. }
  1610. bytes_free(&target_script);
  1611. return NULL;
  1612. }
  1613. static char *set_cbctotal(const char *arg)
  1614. {
  1615. struct pool *pool;
  1616. if (!total_pools)
  1617. return "Define pool first, then the --coinbase-check-total argument";
  1618. pool = pools[total_pools - 1];
  1619. pool->cb_param.total = atoll(arg);
  1620. if (pool->cb_param.total < 0)
  1621. return "The total payout amount in coinbase should be greater than 0";
  1622. return NULL;
  1623. }
  1624. static char *set_cbcperc(const char *arg)
  1625. {
  1626. struct pool *pool;
  1627. if (!total_pools)
  1628. return "Define pool first, then the --coinbase-check-percent argument";
  1629. pool = pools[total_pools - 1];
  1630. if (!pool->cb_param.scripts)
  1631. return "Define --coinbase-check-addr list first, then the --coinbase-check-total argument";
  1632. pool->cb_param.perc = atof(arg) / 100;
  1633. if (pool->cb_param.perc < 0.0 || pool->cb_param.perc > 1.0)
  1634. return "The percentage should be between 0 and 100";
  1635. return NULL;
  1636. }
  1637. static
  1638. 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)
  1639. {
  1640. *out_success = SDR_ERR;
  1641. if (!(strcasecmp(optname, "malgo") && strcasecmp(optname, "algo")))
  1642. {
  1643. if (!newvalue)
  1644. return "Goal option 'malgo' requires a value (eg, SHA256d)";
  1645. struct mining_algorithm * const new_malgo = mining_algorithm_by_alias(newvalue);
  1646. if (!new_malgo)
  1647. return "Unrecognised mining algorithm";
  1648. goal_set_malgo(goal, new_malgo);
  1649. goto success;
  1650. }
  1651. #if BLKMAKER_VERSION > 1
  1652. 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))
  1653. {
  1654. if (!newvalue)
  1655. return "Missing value for 'generate-to' goal option";
  1656. const char * const emsg = set_generate_addr2(goal, newvalue);
  1657. if (emsg)
  1658. return emsg;
  1659. goto success;
  1660. }
  1661. #endif
  1662. *out_success = SDR_UNKNOWN;
  1663. return "Unknown goal option";
  1664. success:
  1665. *out_success = SDR_OK;
  1666. return NULL;
  1667. }
  1668. // May leak replybuf if returning an error
  1669. static
  1670. const char *set_goal_params(struct mining_goal_info * const goal, char *arg)
  1671. {
  1672. bytes_t replybuf = BYTES_INIT;
  1673. for (char *param, *nextptr; (param = strtok_r(arg, ",", &nextptr)); arg = NULL)
  1674. {
  1675. char *val = strchr(param, '=');
  1676. if (val)
  1677. val++[0] = '\0';
  1678. enum bfg_set_device_replytype success;
  1679. const char * const emsg = goal_set(goal, param, val, &replybuf, &success);
  1680. if (success != SDR_OK)
  1681. return emsg ?: "Error setting goal param";
  1682. }
  1683. bytes_free(&replybuf);
  1684. return NULL;
  1685. }
  1686. static
  1687. const char *set_pool_goal(const char * const arg)
  1688. {
  1689. struct pool *pool;
  1690. if (!total_pools)
  1691. return "Usage of --pool-goal before pools are defined does not make sense";
  1692. pool = pools[total_pools - 1];
  1693. char *param = strchr(arg, ':');
  1694. if (param)
  1695. param++[0] = '\0';
  1696. pool->goal = get_mining_goal(arg);
  1697. if (param)
  1698. return set_goal_params(pool->goal, param);
  1699. return NULL;
  1700. }
  1701. static char *set_pool_priority(const char *arg)
  1702. {
  1703. struct pool *pool;
  1704. if (!total_pools)
  1705. return "Usage of --pool-priority before pools are defined does not make sense";
  1706. pool = pools[total_pools - 1];
  1707. opt_set_intval(arg, &pool->prio);
  1708. return NULL;
  1709. }
  1710. static char *set_pool_proxy(const char *arg)
  1711. {
  1712. struct pool *pool;
  1713. if (!total_pools)
  1714. return "Usage of --pool-proxy before pools are defined does not make sense";
  1715. if (!our_curl_supports_proxy_uris())
  1716. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1717. pool = pools[total_pools - 1];
  1718. opt_set_charp(arg, &pool->rpc_proxy);
  1719. return NULL;
  1720. }
  1721. static char *set_pool_force_rollntime(const char *arg)
  1722. {
  1723. struct pool *pool;
  1724. if (!total_pools)
  1725. return "Usage of --force-rollntime before pools are defined does not make sense";
  1726. pool = pools[total_pools - 1];
  1727. opt_set_intval(arg, &pool->force_rollntime);
  1728. return NULL;
  1729. }
  1730. static char *enable_debug(bool *flag)
  1731. {
  1732. *flag = true;
  1733. opt_debug_console = true;
  1734. /* Turn on verbose output, too. */
  1735. opt_log_output = true;
  1736. return NULL;
  1737. }
  1738. static char *set_schedtime(const char *arg, struct schedtime *st)
  1739. {
  1740. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1741. {
  1742. if (strcasecmp(arg, "now"))
  1743. return "Invalid time set, should be HH:MM";
  1744. } else
  1745. schedstop.tm.tm_sec = 0;
  1746. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1747. return "Invalid time set.";
  1748. st->enable = true;
  1749. return NULL;
  1750. }
  1751. static
  1752. char *set_log_file(char *arg)
  1753. {
  1754. char *r = "";
  1755. long int i = strtol(arg, &r, 10);
  1756. int fd, stderr_fd = fileno(stderr);
  1757. if ((!*r) && i >= 0 && i <= INT_MAX)
  1758. fd = i;
  1759. else
  1760. if (!strcmp(arg, "-"))
  1761. {
  1762. fd = fileno(stdout);
  1763. if (unlikely(fd == -1))
  1764. return "Standard output missing for log-file";
  1765. }
  1766. else
  1767. {
  1768. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1769. if (unlikely(fd == -1))
  1770. return "Failed to open log-file";
  1771. }
  1772. close(stderr_fd);
  1773. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1774. return "Failed to dup2 for log-file";
  1775. close(fd);
  1776. return NULL;
  1777. }
  1778. static
  1779. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1780. {
  1781. char *r = "";
  1782. long int i = strtol(arg, &r, 10);
  1783. static char *err = NULL;
  1784. const size_t errbufsz = 0x100;
  1785. free(err);
  1786. err = NULL;
  1787. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1788. *F = fdopen((int)i, mode);
  1789. if (!*F)
  1790. {
  1791. err = malloc(errbufsz);
  1792. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1793. (int)i, purpose);
  1794. return err;
  1795. }
  1796. } else if (!strcmp(arg, "-")) {
  1797. *F = (mode[0] == 'a') ? stdout : stdin;
  1798. if (!*F)
  1799. {
  1800. err = malloc(errbufsz);
  1801. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1802. (mode[0] == 'a') ? "out" : "in", purpose);
  1803. return err;
  1804. }
  1805. } else {
  1806. *F = fopen(arg, mode);
  1807. if (!*F)
  1808. {
  1809. err = malloc(errbufsz);
  1810. snprintf(err, errbufsz, "Failed to open %s for %s",
  1811. arg, purpose);
  1812. return err;
  1813. }
  1814. }
  1815. return NULL;
  1816. }
  1817. static char *set_noncelog(char *arg)
  1818. {
  1819. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1820. }
  1821. static char *set_sharelog(char *arg)
  1822. {
  1823. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1824. }
  1825. static
  1826. void _add_set_device_option(const char * const func, const char * const buf)
  1827. {
  1828. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1829. string_elist_add(buf, &opt_set_device_list);
  1830. }
  1831. #define add_set_device_option(...) do{ \
  1832. char _tmp1718[0x100]; \
  1833. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1834. _add_set_device_option(__func__, _tmp1718); \
  1835. }while(0)
  1836. char *set_temp_cutoff(char *arg)
  1837. {
  1838. if (strchr(arg, ','))
  1839. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1840. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1841. add_set_device_option("all:temp-cutoff=%s", arg);
  1842. return NULL;
  1843. }
  1844. char *set_temp_target(char *arg)
  1845. {
  1846. if (strchr(arg, ','))
  1847. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1848. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1849. add_set_device_option("all:temp-target=%s", arg);
  1850. return NULL;
  1851. }
  1852. #ifdef HAVE_OPENCL
  1853. static
  1854. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1855. {
  1856. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1857. add_set_device_option("OCL:binary=no");
  1858. return NULL;
  1859. }
  1860. #endif
  1861. static
  1862. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1863. {
  1864. opt_disable_client_reconnect = true;
  1865. want_stratum = false;
  1866. return NULL;
  1867. }
  1868. static char *set_api_allow(const char *arg)
  1869. {
  1870. opt_set_charp(arg, &opt_api_allow);
  1871. return NULL;
  1872. }
  1873. static char *set_api_groups(const char *arg)
  1874. {
  1875. opt_set_charp(arg, &opt_api_groups);
  1876. return NULL;
  1877. }
  1878. static char *set_api_description(const char *arg)
  1879. {
  1880. opt_set_charp(arg, &opt_api_description);
  1881. return NULL;
  1882. }
  1883. static char *set_api_mcast_des(const char *arg)
  1884. {
  1885. opt_set_charp(arg, &opt_api_mcast_des);
  1886. return NULL;
  1887. }
  1888. #ifdef USE_ICARUS
  1889. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1890. static char *set_icarus_options(const char *arg)
  1891. {
  1892. if (strchr(arg, ','))
  1893. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1894. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1895. char *opts = strdup(arg), *argdup;
  1896. argdup = opts;
  1897. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1898. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1899. char *saveptr, *opt;
  1900. for (int i = 0; i < 4; ++i, ++sdf)
  1901. {
  1902. opt = strtok_r(opts, ":", &saveptr);
  1903. opts = NULL;
  1904. if (!opt)
  1905. break;
  1906. if (!opt[0])
  1907. continue;
  1908. for (int j = 0; j < 4; ++j)
  1909. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1910. }
  1911. free(argdup);
  1912. return NULL;
  1913. }
  1914. static char *set_icarus_timing(const char *arg)
  1915. {
  1916. if (strchr(arg, ','))
  1917. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1918. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1919. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1920. for (int j = 0; j < 4; ++j)
  1921. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1922. return NULL;
  1923. }
  1924. #endif
  1925. #ifdef USE_AVALON
  1926. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1927. static char *set_avalon_options(const char *arg)
  1928. {
  1929. if (strchr(arg, ','))
  1930. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1931. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1932. char *opts = strdup(arg), *argdup;
  1933. argdup = opts;
  1934. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1935. char *saveptr, *opt;
  1936. for (int i = 0; i < 5; ++i, ++sdf)
  1937. {
  1938. opt = strtok_r(opts, ":", &saveptr);
  1939. opts = NULL;
  1940. if (!opt)
  1941. break;
  1942. if (!opt[0])
  1943. continue;
  1944. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1945. }
  1946. free(argdup);
  1947. return NULL;
  1948. }
  1949. #endif
  1950. #ifdef USE_KLONDIKE
  1951. static char *set_klondike_options(const char *arg)
  1952. {
  1953. int hashclock;
  1954. double temptarget;
  1955. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1956. {
  1957. default:
  1958. return "Unrecognised --klondike-options";
  1959. case 2:
  1960. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1961. // fallthru
  1962. case 1:
  1963. add_set_device_option("klondike:clock=%d", hashclock);
  1964. }
  1965. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1966. return NULL;
  1967. }
  1968. #endif
  1969. __maybe_unused
  1970. static char *set_null(const char __maybe_unused *arg)
  1971. {
  1972. return NULL;
  1973. }
  1974. /* These options are available from config file or commandline */
  1975. static struct opt_table opt_config_table[] = {
  1976. #ifdef WANT_CPUMINE
  1977. OPT_WITH_ARG("--algo",
  1978. set_algo, show_algo, &opt_algo,
  1979. "Specify sha256 implementation for CPU mining:\n"
  1980. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1981. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1982. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1983. #ifdef WANT_SSE2_4WAY
  1984. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1985. #endif
  1986. #ifdef WANT_VIA_PADLOCK
  1987. "\n\tvia\t\tVIA padlock implementation"
  1988. #endif
  1989. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1990. #ifdef WANT_CRYPTOPP_ASM32
  1991. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1992. #endif
  1993. #ifdef WANT_X8632_SSE2
  1994. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1995. #endif
  1996. #ifdef WANT_X8664_SSE2
  1997. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1998. #endif
  1999. #ifdef WANT_X8664_SSE4
  2000. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  2001. #endif
  2002. #ifdef WANT_ALTIVEC_4WAY
  2003. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  2004. #endif
  2005. ),
  2006. OPT_WITH_ARG("-a",
  2007. set_algo, show_algo, &opt_algo,
  2008. opt_hidden),
  2009. #endif
  2010. OPT_WITH_ARG("--api-allow",
  2011. set_api_allow, NULL, NULL,
  2012. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  2013. OPT_WITH_ARG("--api-description",
  2014. set_api_description, NULL, NULL,
  2015. "Description placed in the API status header, default: BFGMiner version"),
  2016. OPT_WITH_ARG("--api-groups",
  2017. set_api_groups, NULL, NULL,
  2018. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  2019. OPT_WITHOUT_ARG("--api-listen",
  2020. opt_set_bool, &opt_api_listen,
  2021. "Enable API, default: disabled"),
  2022. OPT_WITHOUT_ARG("--api-mcast",
  2023. opt_set_bool, &opt_api_mcast,
  2024. "Enable API Multicast listener, default: disabled"),
  2025. OPT_WITH_ARG("--api-mcast-addr",
  2026. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  2027. "API Multicast listen address"),
  2028. OPT_WITH_ARG("--api-mcast-code",
  2029. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  2030. "Code expected in the API Multicast message, don't use '-'"),
  2031. OPT_WITH_ARG("--api-mcast-des",
  2032. set_api_mcast_des, NULL, NULL,
  2033. "Description appended to the API Multicast reply, default: ''"),
  2034. OPT_WITH_ARG("--api-mcast-port",
  2035. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  2036. "API Multicast listen port"),
  2037. OPT_WITHOUT_ARG("--api-network",
  2038. opt_set_bool, &opt_api_network,
  2039. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  2040. OPT_WITH_ARG("--api-port",
  2041. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  2042. "Port number of miner API"),
  2043. #ifdef HAVE_ADL
  2044. OPT_WITHOUT_ARG("--auto-fan",
  2045. opt_set_bool, &opt_autofan,
  2046. opt_hidden),
  2047. OPT_WITHOUT_ARG("--auto-gpu",
  2048. opt_set_bool, &opt_autoengine,
  2049. opt_hidden),
  2050. #endif
  2051. OPT_WITHOUT_ARG("--balance",
  2052. set_balance, &pool_strategy,
  2053. "Change multipool strategy from failover to even share balance"),
  2054. OPT_WITHOUT_ARG("--benchmark",
  2055. opt_set_bool, &opt_benchmark,
  2056. "Run BFGMiner in benchmark mode - produces no shares"),
  2057. OPT_WITHOUT_ARG("--benchmark-intense",
  2058. set_benchmark_intense, &opt_benchmark_intense,
  2059. "Run BFGMiner in intensive benchmark mode - produces no shares"),
  2060. #if defined(USE_BITFORCE)
  2061. OPT_WITHOUT_ARG("--bfl-range",
  2062. opt_set_bool, &opt_bfl_noncerange,
  2063. "Use nonce range on bitforce devices if supported"),
  2064. #endif
  2065. #ifdef HAVE_CHROOT
  2066. OPT_WITH_ARG("--chroot-dir",
  2067. opt_set_charp, NULL, &chroot_dir,
  2068. "Chroot to a directory right after startup"),
  2069. #endif
  2070. OPT_WITH_ARG("--cmd-idle",
  2071. opt_set_charp, NULL, &cmd_idle,
  2072. "Execute a command when a device is allowed to be idle (rest or wait)"),
  2073. OPT_WITH_ARG("--cmd-sick",
  2074. opt_set_charp, NULL, &cmd_sick,
  2075. "Execute a command when a device is declared sick"),
  2076. OPT_WITH_ARG("--cmd-dead",
  2077. opt_set_charp, NULL, &cmd_dead,
  2078. "Execute a command when a device is declared dead"),
  2079. #if BLKMAKER_VERSION > 0
  2080. OPT_WITH_ARG("--coinbase-sig",
  2081. set_strdup, NULL, &opt_coinbase_sig,
  2082. "Set coinbase signature when possible"),
  2083. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  2084. set_strdup, NULL, &opt_coinbase_sig,
  2085. opt_hidden),
  2086. #endif
  2087. #ifdef HAVE_CURSES
  2088. OPT_WITHOUT_ARG("--compact",
  2089. opt_set_bool, &opt_compact,
  2090. "Use compact display without per device statistics"),
  2091. #endif
  2092. #ifdef WANT_CPUMINE
  2093. OPT_WITH_ARG("--cpu-threads",
  2094. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2095. "Number of miner CPU threads"),
  2096. OPT_WITH_ARG("-t",
  2097. force_nthreads_int, opt_show_intval, &opt_n_threads,
  2098. opt_hidden),
  2099. #endif
  2100. OPT_WITHOUT_ARG("--debug|-D",
  2101. enable_debug, &opt_debug,
  2102. "Enable debug output"),
  2103. OPT_WITHOUT_ARG("--debuglog",
  2104. opt_set_bool, &opt_debug,
  2105. "Enable debug logging"),
  2106. OPT_WITHOUT_ARG("--device-protocol-dump",
  2107. opt_set_bool, &opt_dev_protocol,
  2108. "Verbose dump of device protocol-level activities"),
  2109. OPT_WITH_ARG("--device|-d",
  2110. set_devices, NULL, NULL,
  2111. "Enable only devices matching pattern (default: all)"),
  2112. OPT_WITHOUT_ARG("--disable-rejecting",
  2113. opt_set_bool, &opt_disable_pool,
  2114. "Automatically disable pools that continually reject shares"),
  2115. #ifdef USE_LIBMICROHTTPD
  2116. OPT_WITH_ARG("--http-port",
  2117. opt_set_intval, opt_show_intval, &httpsrv_port,
  2118. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  2119. #endif
  2120. OPT_WITH_ARG("--expiry",
  2121. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2122. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  2123. OPT_WITH_ARG("-E",
  2124. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  2125. opt_hidden),
  2126. OPT_WITH_ARG("--expiry-lp",
  2127. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  2128. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  2129. OPT_WITHOUT_ARG("--failover-only",
  2130. opt_set_bool, &opt_fail_only,
  2131. "Don't leak work to backup pools when primary pool is lagging"),
  2132. OPT_WITH_ARG("--failover-switch-delay",
  2133. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  2134. "Delay in seconds before switching back to a failed pool"),
  2135. #ifdef USE_FPGA
  2136. OPT_WITHOUT_ARG("--force-dev-init",
  2137. opt_set_bool, &opt_force_dev_init,
  2138. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  2139. #endif
  2140. #if BLKMAKER_VERSION > 1
  2141. OPT_WITH_ARG("--generate-to",
  2142. set_generate_addr, NULL, NULL,
  2143. "Set an address to generate to for solo mining"),
  2144. 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",
  2145. set_generate_addr, NULL, NULL,
  2146. opt_hidden),
  2147. #endif
  2148. #ifdef HAVE_OPENCL
  2149. OPT_WITH_ARG("--gpu-dyninterval",
  2150. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  2151. opt_hidden),
  2152. OPT_WITH_ARG("--gpu-platform",
  2153. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  2154. "Select OpenCL platform ID to use for GPU mining"),
  2155. OPT_WITH_ARG("--gpu-threads|-g",
  2156. set_gpu_threads, opt_show_intval, &opt_g_threads,
  2157. opt_hidden),
  2158. #ifdef HAVE_ADL
  2159. OPT_WITH_ARG("--gpu-engine",
  2160. set_gpu_engine, NULL, NULL,
  2161. opt_hidden),
  2162. OPT_WITH_ARG("--gpu-fan",
  2163. set_gpu_fan, NULL, NULL,
  2164. opt_hidden),
  2165. OPT_WITH_ARG("--gpu-map",
  2166. set_gpu_map, NULL, NULL,
  2167. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  2168. OPT_WITH_ARG("--gpu-memclock",
  2169. set_gpu_memclock, NULL, NULL,
  2170. opt_hidden),
  2171. OPT_WITH_ARG("--gpu-memdiff",
  2172. set_gpu_memdiff, NULL, NULL,
  2173. opt_hidden),
  2174. OPT_WITH_ARG("--gpu-powertune",
  2175. set_gpu_powertune, NULL, NULL,
  2176. opt_hidden),
  2177. OPT_WITHOUT_ARG("--gpu-reorder",
  2178. opt_set_bool, &opt_reorder,
  2179. "Attempt to reorder GPU devices according to PCI Bus ID"),
  2180. OPT_WITH_ARG("--gpu-vddc",
  2181. set_gpu_vddc, NULL, NULL,
  2182. opt_hidden),
  2183. #endif
  2184. #ifdef USE_SCRYPT
  2185. OPT_WITH_ARG("--lookup-gap",
  2186. set_lookup_gap, NULL, NULL,
  2187. opt_hidden),
  2188. #endif
  2189. OPT_WITH_ARG("--intensity|-I",
  2190. set_intensity, NULL, NULL,
  2191. opt_hidden),
  2192. #endif
  2193. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  2194. OPT_WITH_ARG("--kernel-path",
  2195. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2196. "Specify a path to where bitstream and kernel files are"),
  2197. OPT_WITH_ARG("-K",
  2198. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2199. opt_hidden),
  2200. #endif
  2201. #ifdef HAVE_OPENCL
  2202. OPT_WITH_ARG("--kernel|-k",
  2203. set_kernel, NULL, NULL,
  2204. opt_hidden),
  2205. #endif
  2206. #ifdef USE_ICARUS
  2207. OPT_WITH_ARG("--icarus-options",
  2208. set_icarus_options, NULL, NULL,
  2209. opt_hidden),
  2210. OPT_WITH_ARG("--icarus-timing",
  2211. set_icarus_timing, NULL, NULL,
  2212. opt_hidden),
  2213. #endif
  2214. #ifdef USE_AVALON
  2215. OPT_WITH_ARG("--avalon-options",
  2216. set_avalon_options, NULL, NULL,
  2217. opt_hidden),
  2218. #endif
  2219. #ifdef USE_KLONDIKE
  2220. OPT_WITH_ARG("--klondike-options",
  2221. set_klondike_options, NULL, NULL,
  2222. "Set klondike options clock:temptarget"),
  2223. #endif
  2224. OPT_WITHOUT_ARG("--load-balance",
  2225. set_loadbalance, &pool_strategy,
  2226. "Change multipool strategy from failover to quota based balance"),
  2227. OPT_WITH_ARG("--log|-l",
  2228. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2229. "Interval in seconds between log output"),
  2230. OPT_WITH_ARG("--log-file|-L",
  2231. set_log_file, NULL, NULL,
  2232. "Append log file for output messages"),
  2233. OPT_WITH_ARG("--logfile",
  2234. set_log_file, NULL, NULL,
  2235. opt_hidden),
  2236. OPT_WITHOUT_ARG("--log-microseconds",
  2237. opt_set_bool, &opt_log_microseconds,
  2238. "Include microseconds in log output"),
  2239. #if defined(unix) || defined(__APPLE__)
  2240. OPT_WITH_ARG("--monitor|-m",
  2241. opt_set_charp, NULL, &opt_stderr_cmd,
  2242. "Use custom pipe cmd for output messages"),
  2243. #endif // defined(unix)
  2244. OPT_WITHOUT_ARG("--net-delay",
  2245. opt_set_bool, &opt_delaynet,
  2246. "Impose small delays in networking to avoid overloading slow routers"),
  2247. OPT_WITHOUT_ARG("--no-adl",
  2248. opt_set_bool, &opt_noadl,
  2249. #ifdef HAVE_ADL
  2250. "Disable the ATI display library used for monitoring and setting GPU parameters"
  2251. #else
  2252. opt_hidden
  2253. #endif
  2254. ),
  2255. OPT_WITHOUT_ARG("--no-gbt",
  2256. opt_set_invbool, &want_gbt,
  2257. "Disable getblocktemplate support"),
  2258. OPT_WITHOUT_ARG("--no-getwork",
  2259. opt_set_invbool, &want_getwork,
  2260. "Disable getwork support"),
  2261. OPT_WITHOUT_ARG("--no-hotplug",
  2262. #ifdef HAVE_BFG_HOTPLUG
  2263. opt_set_invbool, &opt_hotplug,
  2264. "Disable hotplug detection"
  2265. #else
  2266. set_null, &opt_hotplug,
  2267. opt_hidden
  2268. #endif
  2269. ),
  2270. OPT_WITHOUT_ARG("--no-local-bitcoin",
  2271. #if BLKMAKER_VERSION > 1
  2272. opt_set_invbool, &opt_load_bitcoin_conf,
  2273. "Disable adding pools for local bitcoin RPC servers"),
  2274. #else
  2275. set_null, NULL, opt_hidden),
  2276. #endif
  2277. OPT_WITHOUT_ARG("--no-longpoll",
  2278. opt_set_invbool, &want_longpoll,
  2279. "Disable X-Long-Polling support"),
  2280. OPT_WITHOUT_ARG("--no-pool-disable",
  2281. opt_set_invbool, &opt_disable_pool,
  2282. opt_hidden),
  2283. OPT_WITHOUT_ARG("--no-client-reconnect",
  2284. opt_set_invbool, &opt_disable_client_reconnect,
  2285. opt_hidden),
  2286. OPT_WITHOUT_ARG("--no-pool-redirect",
  2287. disable_pool_redirect, NULL,
  2288. "Ignore pool requests to redirect to another server"),
  2289. OPT_WITHOUT_ARG("--no-restart",
  2290. opt_set_invbool, &opt_restart,
  2291. "Do not attempt to restart devices that hang"
  2292. ),
  2293. OPT_WITHOUT_ARG("--no-show-processors",
  2294. opt_set_invbool, &opt_show_procs,
  2295. opt_hidden),
  2296. OPT_WITHOUT_ARG("--no-show-procs",
  2297. opt_set_invbool, &opt_show_procs,
  2298. opt_hidden),
  2299. OPT_WITHOUT_ARG("--no-stratum",
  2300. opt_set_invbool, &want_stratum,
  2301. "Disable Stratum detection"),
  2302. OPT_WITHOUT_ARG("--no-submit-stale",
  2303. opt_set_invbool, &opt_submit_stale,
  2304. "Don't submit shares if they are detected as stale"),
  2305. #ifdef HAVE_OPENCL
  2306. OPT_WITHOUT_ARG("--no-opencl-binaries",
  2307. set_no_opencl_binaries, NULL,
  2308. opt_hidden),
  2309. #endif
  2310. OPT_WITHOUT_ARG("--no-unicode",
  2311. #ifdef USE_UNICODE
  2312. opt_set_invbool, &use_unicode,
  2313. "Don't use Unicode characters in TUI"
  2314. #else
  2315. set_null, &use_unicode,
  2316. opt_hidden
  2317. #endif
  2318. ),
  2319. OPT_WITH_ARG("--noncelog",
  2320. set_noncelog, NULL, NULL,
  2321. "Create log of all nonces found"),
  2322. OPT_WITH_ARG("--pass|-p",
  2323. set_pass, NULL, NULL,
  2324. "Password for bitcoin JSON-RPC server"),
  2325. OPT_WITHOUT_ARG("--per-device-stats",
  2326. opt_set_bool, &want_per_device_stats,
  2327. "Force verbose mode and output per-device statistics"),
  2328. OPT_WITH_ARG("--userpass|-O",
  2329. set_userpass, NULL, NULL,
  2330. "Username:Password pair for bitcoin JSON-RPC server"),
  2331. OPT_WITH_ARG("--pool-goal",
  2332. set_pool_goal, NULL, NULL,
  2333. "Named goal for the previous-defined pool"),
  2334. OPT_WITH_ARG("--pool-priority",
  2335. set_pool_priority, NULL, NULL,
  2336. "Priority for just the previous-defined pool"),
  2337. OPT_WITH_ARG("--pool-proxy|-x",
  2338. set_pool_proxy, NULL, NULL,
  2339. "Proxy URI to use for connecting to just the previous-defined pool"),
  2340. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2341. set_pool_force_rollntime, NULL, NULL,
  2342. opt_hidden),
  2343. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2344. opt_set_bool, &opt_protocol,
  2345. "Verbose dump of protocol-level activities"),
  2346. OPT_WITH_ARG("--queue|-Q",
  2347. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2348. "Minimum number of work items to have queued (0+)"),
  2349. OPT_WITHOUT_ARG("--quiet|-q",
  2350. opt_set_bool, &opt_quiet,
  2351. "Disable logging output, display status and errors"),
  2352. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2353. opt_set_bool, &opt_quiet_work_updates,
  2354. opt_hidden),
  2355. OPT_WITH_ARG("--quit-summary",
  2356. set_quit_summary, NULL, NULL,
  2357. "Summary printed when you quit: none/devs/procs/detailed"),
  2358. OPT_WITH_ARG("--quota|-U",
  2359. set_quota, NULL, NULL,
  2360. "quota;URL combination for server with load-balance strategy quotas"),
  2361. OPT_WITHOUT_ARG("--real-quiet",
  2362. opt_set_bool, &opt_realquiet,
  2363. "Disable all output"),
  2364. OPT_WITH_ARG("--request-diff",
  2365. set_request_diff, opt_show_floatval, &request_pdiff,
  2366. "Request a specific difficulty from pools"),
  2367. OPT_WITH_ARG("--retries",
  2368. opt_set_intval, opt_show_intval, &opt_retries,
  2369. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2370. OPT_WITH_ARG("--retry-pause",
  2371. set_null, NULL, NULL,
  2372. opt_hidden),
  2373. OPT_WITH_ARG("--rotate",
  2374. set_rotate, opt_show_intval, &opt_rotate_period,
  2375. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2376. OPT_WITHOUT_ARG("--round-robin",
  2377. set_rr, &pool_strategy,
  2378. "Change multipool strategy from failover to round robin on failure"),
  2379. OPT_WITH_ARG("--scan|-S",
  2380. add_serial, NULL, NULL,
  2381. "Configure how to scan for mining devices"),
  2382. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2383. add_serial, NULL, NULL,
  2384. opt_hidden),
  2385. OPT_WITH_ARG("--scan-time",
  2386. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2387. "Upper bound on time spent scanning current work, in seconds"),
  2388. OPT_WITH_ARG("-s",
  2389. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2390. opt_hidden),
  2391. OPT_WITH_ARG("--scantime",
  2392. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2393. opt_hidden),
  2394. OPT_WITH_ARG("--sched-start",
  2395. set_schedtime, NULL, &schedstart,
  2396. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2397. OPT_WITH_ARG("--sched-stop",
  2398. set_schedtime, NULL, &schedstop,
  2399. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2400. #ifdef USE_SCRYPT
  2401. OPT_WITHOUT_ARG("--scrypt",
  2402. set_malgo_scrypt, NULL,
  2403. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2404. #endif
  2405. OPT_WITH_ARG("--set-device|--set",
  2406. opt_string_elist_add, NULL, &opt_set_device_list,
  2407. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2408. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2409. OPT_WITH_ARG("--shaders",
  2410. set_shaders, NULL, NULL,
  2411. opt_hidden),
  2412. #endif
  2413. #ifdef HAVE_PWD_H
  2414. OPT_WITH_ARG("--setuid",
  2415. opt_set_charp, NULL, &opt_setuid,
  2416. "Username of an unprivileged user to run as"),
  2417. #endif
  2418. OPT_WITH_ARG("--sharelog",
  2419. set_sharelog, NULL, NULL,
  2420. "Append share log to file"),
  2421. OPT_WITH_ARG("--shares",
  2422. opt_set_floatval, NULL, &opt_shares,
  2423. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2424. OPT_WITHOUT_ARG("--show-processors",
  2425. opt_set_bool, &opt_show_procs,
  2426. "Show per processor statistics in summary"),
  2427. OPT_WITHOUT_ARG("--show-procs",
  2428. opt_set_bool, &opt_show_procs,
  2429. opt_hidden),
  2430. OPT_WITH_ARG("--skip-security-checks",
  2431. set_int_0_to_9999, NULL, &opt_skip_checks,
  2432. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2433. OPT_WITH_ARG("--socks-proxy",
  2434. opt_set_charp, NULL, &opt_socks_proxy,
  2435. "Set socks proxy (host:port)"),
  2436. #ifdef USE_LIBEVENT
  2437. OPT_WITH_ARG("--stratum-port",
  2438. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2439. "Port number to listen on for stratum miners (-1 means disabled)"),
  2440. #endif
  2441. OPT_WITHOUT_ARG("--submit-stale",
  2442. opt_set_bool, &opt_submit_stale,
  2443. opt_hidden),
  2444. OPT_WITH_ARG("--submit-threads",
  2445. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2446. "Minimum number of concurrent share submissions (default: 64)"),
  2447. #ifdef HAVE_SYSLOG_H
  2448. OPT_WITHOUT_ARG("--syslog",
  2449. opt_set_bool, &use_syslog,
  2450. "Use system log for output messages (default: standard error)"),
  2451. #endif
  2452. OPT_WITH_ARG("--temp-cutoff",
  2453. set_temp_cutoff, NULL, &opt_cutofftemp,
  2454. opt_hidden),
  2455. OPT_WITH_ARG("--temp-hysteresis",
  2456. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2457. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2458. #ifdef HAVE_ADL
  2459. OPT_WITH_ARG("--temp-overheat",
  2460. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2461. opt_hidden),
  2462. #endif
  2463. OPT_WITH_ARG("--temp-target",
  2464. set_temp_target, NULL, NULL,
  2465. opt_hidden),
  2466. OPT_WITHOUT_ARG("--text-only|-T",
  2467. opt_set_invbool, &use_curses,
  2468. #ifdef HAVE_CURSES
  2469. "Disable ncurses formatted screen output"
  2470. #else
  2471. opt_hidden
  2472. #endif
  2473. ),
  2474. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2475. OPT_WITH_ARG("--thread-concurrency",
  2476. set_thread_concurrency, NULL, NULL,
  2477. opt_hidden),
  2478. #endif
  2479. #ifdef USE_UNICODE
  2480. OPT_WITHOUT_ARG("--unicode",
  2481. opt_set_bool, &use_unicode,
  2482. "Use Unicode characters in TUI"),
  2483. #endif
  2484. OPT_WITH_ARG("--url|-o",
  2485. set_url, NULL, NULL,
  2486. "URL for bitcoin JSON-RPC server"),
  2487. OPT_WITH_ARG("--user|-u",
  2488. set_user, NULL, NULL,
  2489. "Username for bitcoin JSON-RPC server"),
  2490. #ifdef HAVE_OPENCL
  2491. OPT_WITH_ARG("--vectors|-v",
  2492. set_vector, NULL, NULL,
  2493. opt_hidden),
  2494. #endif
  2495. OPT_WITHOUT_ARG("--verbose",
  2496. opt_set_bool, &opt_log_output,
  2497. "Log verbose output to stderr as well as status output"),
  2498. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2499. opt_set_invbool, &opt_quiet_work_updates,
  2500. opt_hidden),
  2501. OPT_WITHOUT_ARG("--weighed-stats",
  2502. opt_set_bool, &opt_weighed_stats,
  2503. "Display statistics weighed to difficulty 1"),
  2504. #ifdef HAVE_OPENCL
  2505. OPT_WITH_ARG("--worksize|-w",
  2506. set_worksize, NULL, NULL,
  2507. opt_hidden),
  2508. #endif
  2509. OPT_WITHOUT_ARG("--unittest",
  2510. opt_set_bool, &opt_unittest, opt_hidden),
  2511. OPT_WITH_ARG("--coinbase-check-addr",
  2512. set_cbcaddr, NULL, NULL,
  2513. "A list of address to check against in coinbase payout list received from the previous-defined pool, separated by ','"),
  2514. OPT_WITH_ARG("--cbcheck-addr|--cbc-addr|--cbcaddr",
  2515. set_cbcaddr, NULL, NULL,
  2516. opt_hidden),
  2517. OPT_WITH_ARG("--coinbase-check-total",
  2518. set_cbctotal, NULL, NULL,
  2519. "The least total payout amount expected in coinbase received from the previous-defined pool"),
  2520. OPT_WITH_ARG("--cbcheck-total|--cbc-total|--cbctotal",
  2521. set_cbctotal, NULL, NULL,
  2522. opt_hidden),
  2523. OPT_WITH_ARG("--coinbase-check-percent",
  2524. set_cbcperc, NULL, NULL,
  2525. "The least benefit percentage expected for the sum of addr(s) listed in --cbaddr argument for previous-defined pool"),
  2526. OPT_WITH_ARG("--cbcheck-percent|--cbc-percent|--cbcpercent|--cbcperc",
  2527. set_cbcperc, NULL, NULL,
  2528. opt_hidden),
  2529. OPT_WITHOUT_ARG("--worktime",
  2530. opt_set_bool, &opt_worktime,
  2531. "Display extra work time debug information"),
  2532. OPT_WITH_ARG("--pools",
  2533. opt_set_bool, NULL, NULL, opt_hidden),
  2534. OPT_ENDTABLE
  2535. };
  2536. static char *load_config(const char *arg, void __maybe_unused *unused);
  2537. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2538. {
  2539. static char err_buf[200];
  2540. struct opt_table *opt;
  2541. json_t *val;
  2542. if (fileconf && !*fileconf_load_p)
  2543. *fileconf_load_p = 1;
  2544. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2545. char *p, *name, *sp;
  2546. /* We don't handle subtables. */
  2547. assert(!(opt->type & OPT_SUBTABLE));
  2548. if (!opt->names)
  2549. continue;
  2550. /* Pull apart the option name(s). */
  2551. name = strdup(opt->names);
  2552. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2553. char *err = "Invalid value";
  2554. /* Ignore short options. */
  2555. if (p[1] != '-')
  2556. continue;
  2557. val = json_object_get(config, p+2);
  2558. if (!val)
  2559. continue;
  2560. if (opt->type & OPT_HASARG) {
  2561. if (json_is_string(val)) {
  2562. err = opt->cb_arg(json_string_value(val),
  2563. opt->u.arg);
  2564. } else if (json_is_number(val)) {
  2565. char buf[256], *p, *q;
  2566. snprintf(buf, 256, "%f", json_number_value(val));
  2567. if ( (p = strchr(buf, '.')) ) {
  2568. // Trim /\.0*$/ to work properly with integer-only arguments
  2569. q = p;
  2570. while (*(++q) == '0') {}
  2571. if (*q == '\0')
  2572. *p = '\0';
  2573. }
  2574. err = opt->cb_arg(buf, opt->u.arg);
  2575. } else if (json_is_array(val)) {
  2576. int n, size = json_array_size(val);
  2577. err = NULL;
  2578. for (n = 0; n < size && !err; n++) {
  2579. if (json_is_string(json_array_get(val, n)))
  2580. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2581. else if (json_is_object(json_array_get(val, n)))
  2582. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2583. }
  2584. }
  2585. } else if (opt->type & OPT_NOARG) {
  2586. if (json_is_true(val))
  2587. err = opt->cb(opt->u.arg);
  2588. else if (json_is_boolean(val)) {
  2589. if (opt->cb == (void*)opt_set_bool)
  2590. err = opt_set_invbool(opt->u.arg);
  2591. else if (opt->cb == (void*)opt_set_invbool)
  2592. err = opt_set_bool(opt->u.arg);
  2593. }
  2594. }
  2595. if (err) {
  2596. /* Allow invalid values to be in configuration
  2597. * file, just skipping over them provided the
  2598. * JSON is still valid after that. */
  2599. if (fileconf) {
  2600. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2601. *fileconf_load_p = -1;
  2602. } else {
  2603. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2604. p, err);
  2605. return err_buf;
  2606. }
  2607. }
  2608. }
  2609. free(name);
  2610. }
  2611. val = json_object_get(config, JSON_INCLUDE_CONF);
  2612. if (val && json_is_string(val))
  2613. return load_config(json_string_value(val), NULL);
  2614. return NULL;
  2615. }
  2616. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2617. static char *load_config(const char *arg, void __maybe_unused *unused)
  2618. {
  2619. json_error_t err;
  2620. json_t *config;
  2621. char *json_error;
  2622. size_t siz;
  2623. struct bfg_loaded_configfile *cfginfo;
  2624. cfginfo = malloc(sizeof(*cfginfo));
  2625. *cfginfo = (struct bfg_loaded_configfile){
  2626. .filename = strdup(arg),
  2627. };
  2628. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2629. if (++include_count > JSON_MAX_DEPTH)
  2630. return JSON_MAX_DEPTH_ERR;
  2631. #if JANSSON_MAJOR_VERSION > 1
  2632. config = json_load_file(arg, 0, &err);
  2633. #else
  2634. config = json_load_file(arg, &err);
  2635. #endif
  2636. if (!json_is_object(config)) {
  2637. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2638. json_error = malloc(siz);
  2639. if (!json_error)
  2640. quit(1, "Malloc failure in json error");
  2641. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2642. return json_error;
  2643. }
  2644. config_loaded = true;
  2645. /* Parse the config now, so we can override it. That can keep pointers
  2646. * so don't free config object. */
  2647. return parse_config(config, true, &cfginfo->fileconf_load);
  2648. }
  2649. static
  2650. bool _load_default_configs(const char * const filepath, void * __maybe_unused userp)
  2651. {
  2652. bool * const found_defcfg_p = userp;
  2653. *found_defcfg_p = true;
  2654. load_config(filepath, NULL);
  2655. // Regardless of status of loading the config file, we should continue loading other defaults
  2656. return false;
  2657. }
  2658. static void load_default_config(void)
  2659. {
  2660. bool found_defcfg = false;
  2661. appdata_file_call("BFGMiner", def_conf, _load_default_configs, &found_defcfg);
  2662. if (!found_defcfg)
  2663. {
  2664. // No BFGMiner config, try Cgminer's...
  2665. appdata_file_call("cgminer", "cgminer.conf", _load_default_configs, &found_defcfg);
  2666. }
  2667. }
  2668. extern const char *opt_argv0;
  2669. static char *opt_verusage_and_exit(const char *extra)
  2670. {
  2671. puts(packagename);
  2672. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2673. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2674. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2675. printf(" Options:%s\n", BFG_OPTLIST);
  2676. printf("%s", opt_usage(opt_argv0, extra));
  2677. fflush(stdout);
  2678. exit(0);
  2679. }
  2680. /* These options are parsed before anything else */
  2681. static struct opt_table opt_early_table[] = {
  2682. // Default config is loaded in command line order, like a regular config
  2683. OPT_EARLY_WITH_ARG("--config|-c|--default-config",
  2684. set_bool_ignore_arg, NULL, &config_loaded,
  2685. opt_hidden),
  2686. OPT_EARLY_WITHOUT_ARG("--no-config|--no-default-config",
  2687. opt_set_bool, &config_loaded,
  2688. "Inhibit loading default config file"),
  2689. OPT_ENDTABLE
  2690. };
  2691. /* These options are available from commandline only */
  2692. static struct opt_table opt_cmdline_table[] = {
  2693. OPT_WITH_ARG("--config|-c",
  2694. load_config, NULL, NULL,
  2695. "Load a JSON-format configuration file\n"
  2696. "See example.conf for an example configuration."),
  2697. OPT_EARLY_WITHOUT_ARG("--no-config",
  2698. opt_set_bool, &config_loaded,
  2699. opt_hidden),
  2700. OPT_EARLY_WITHOUT_ARG("--no-default-config",
  2701. opt_set_bool, &config_loaded,
  2702. "Inhibit loading default config file"),
  2703. OPT_WITHOUT_ARG("--default-config",
  2704. load_default_config, NULL,
  2705. "Always load the default config file"),
  2706. OPT_WITHOUT_ARG("--help|-h",
  2707. opt_verusage_and_exit, NULL,
  2708. "Print this message"),
  2709. #ifdef HAVE_OPENCL
  2710. OPT_WITHOUT_ARG("--ndevs|-n",
  2711. print_ndevs_and_exit, &nDevs,
  2712. opt_hidden),
  2713. #endif
  2714. OPT_WITHOUT_ARG("--version|-V",
  2715. opt_version_and_exit, packagename,
  2716. "Display version and exit"),
  2717. OPT_ENDTABLE
  2718. };
  2719. static bool jobj_binary(const json_t *obj, const char *key,
  2720. void *buf, size_t buflen, bool required)
  2721. {
  2722. const char *hexstr;
  2723. json_t *tmp;
  2724. tmp = json_object_get(obj, key);
  2725. if (unlikely(!tmp)) {
  2726. if (unlikely(required))
  2727. applog(LOG_ERR, "JSON key '%s' not found", key);
  2728. return false;
  2729. }
  2730. hexstr = json_string_value(tmp);
  2731. if (unlikely(!hexstr)) {
  2732. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2733. return false;
  2734. }
  2735. if (!hex2bin(buf, hexstr, buflen))
  2736. return false;
  2737. return true;
  2738. }
  2739. static void calc_midstate(struct work *work)
  2740. {
  2741. union {
  2742. unsigned char c[64];
  2743. uint32_t i[16];
  2744. } data;
  2745. swap32yes(&data.i[0], work->data, 16);
  2746. sha256_ctx ctx;
  2747. sha256_init(&ctx);
  2748. sha256_update(&ctx, data.c, 64);
  2749. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2750. swap32tole(work->midstate, work->midstate, 8);
  2751. }
  2752. static
  2753. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2754. {
  2755. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2756. *tr = (struct bfg_tmpl_ref){
  2757. .tmpl = tmpl,
  2758. .refcount = 1,
  2759. };
  2760. mutex_init(&tr->mutex);
  2761. return tr;
  2762. }
  2763. static
  2764. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2765. {
  2766. mutex_lock(&tr->mutex);
  2767. ++tr->refcount;
  2768. mutex_unlock(&tr->mutex);
  2769. }
  2770. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2771. {
  2772. mutex_lock(&tr->mutex);
  2773. bool free_tmpl = !--tr->refcount;
  2774. mutex_unlock(&tr->mutex);
  2775. if (free_tmpl)
  2776. {
  2777. blktmpl_free(tr->tmpl);
  2778. mutex_destroy(&tr->mutex);
  2779. free(tr);
  2780. }
  2781. }
  2782. static struct work *make_work(void)
  2783. {
  2784. struct work *work = calloc(1, sizeof(struct work));
  2785. if (unlikely(!work))
  2786. quit(1, "Failed to calloc work in make_work");
  2787. cg_wlock(&control_lock);
  2788. work->id = total_work++;
  2789. cg_wunlock(&control_lock);
  2790. return work;
  2791. }
  2792. /* This is the central place all work that is about to be retired should be
  2793. * cleaned to remove any dynamically allocated arrays within the struct */
  2794. void clean_work(struct work *work)
  2795. {
  2796. free(work->job_id);
  2797. bytes_free(&work->nonce2);
  2798. free(work->nonce1);
  2799. if (work->device_data_free_func)
  2800. work->device_data_free_func(work);
  2801. if (work->tr)
  2802. tmpl_decref(work->tr);
  2803. memset(work, 0, sizeof(struct work));
  2804. }
  2805. /* All dynamically allocated work structs should be freed here to not leak any
  2806. * ram from arrays allocated within the work struct */
  2807. void free_work(struct work *work)
  2808. {
  2809. clean_work(work);
  2810. free(work);
  2811. }
  2812. 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";
  2813. #define workpadding_bin bfg_workpadding_bin
  2814. static const size_t block_info_str_sz = 3 /* ... */ + 16 /* block hash segment */ + 1;
  2815. static
  2816. void block_info_str(char * const out, const struct block_info * const blkinfo)
  2817. {
  2818. unsigned char hash_swap[32];
  2819. swap256(hash_swap, blkinfo->prevblkhash);
  2820. swap32tole(hash_swap, hash_swap, 32 / 4);
  2821. memset(out, '.', 3);
  2822. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2823. if (blkinfo->height > 0 && blkinfo->height < 1000000)
  2824. {
  2825. bin2hex(&out[3], &hash_swap[0x1c], 4);
  2826. snprintf(&out[11], block_info_str_sz-11, " #%6u", blkinfo->height);
  2827. }
  2828. else
  2829. bin2hex(&out[3], &hash_swap[0x18], 8);
  2830. }
  2831. #ifdef HAVE_CURSES
  2832. static void update_block_display(void);
  2833. #endif
  2834. // Must only be called with ch_lock held!
  2835. static
  2836. void __update_block_title(struct mining_goal_info * const goal)
  2837. {
  2838. struct blockchain_info * const blkchain = goal->blkchain;
  2839. if (!goal->current_goal_detail)
  2840. goal->current_goal_detail = malloc(block_info_str_sz);
  2841. block_info_str(goal->current_goal_detail, blkchain->currentblk);
  2842. #ifdef HAVE_CURSES
  2843. update_block_display();
  2844. #endif
  2845. }
  2846. static struct block_info *block_exists(const struct blockchain_info *, const void *);
  2847. static
  2848. void have_block_height(struct mining_goal_info * const goal, const void * const prevblkhash, uint32_t blkheight)
  2849. {
  2850. struct blockchain_info * const blkchain = goal->blkchain;
  2851. struct block_info * const blkinfo = block_exists(blkchain, prevblkhash);
  2852. if ((!blkinfo) || blkinfo->height)
  2853. return;
  2854. uint32_t block_id = ((uint32_t*)prevblkhash)[0];
  2855. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2856. cg_wlock(&ch_lock);
  2857. blkinfo->height = blkheight;
  2858. if (blkinfo == blkchain->currentblk)
  2859. {
  2860. blkchain->currentblk_subsidy = 5000000000LL >> (blkheight / 210000);
  2861. __update_block_title(goal);
  2862. }
  2863. cg_wunlock(&ch_lock);
  2864. }
  2865. static
  2866. void pool_set_opaque(struct pool *pool, bool opaque)
  2867. {
  2868. if (pool->swork.opaque == opaque)
  2869. return;
  2870. pool->swork.opaque = opaque;
  2871. if (opaque)
  2872. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2873. pool->pool_no);
  2874. else
  2875. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2876. pool->pool_no);
  2877. }
  2878. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2879. {
  2880. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2881. return true;
  2882. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2883. }
  2884. void pool_check_coinbase(struct pool * const pool, const uint8_t * const cbtxn, const size_t cbtxnsz)
  2885. {
  2886. if (uri_get_param_bool(pool->rpc_url, "skipcbcheck", false))
  2887. {}
  2888. else
  2889. if (!check_coinbase(cbtxn, cbtxnsz, &pool->cb_param))
  2890. {
  2891. if (pool->enabled == POOL_ENABLED)
  2892. {
  2893. applog(LOG_ERR, "Pool %d misbehaving (%s), disabling!", pool->pool_no, "coinbase check");
  2894. disable_pool(pool, POOL_MISBEHAVING);
  2895. }
  2896. }
  2897. else
  2898. if (pool->enabled == POOL_MISBEHAVING)
  2899. {
  2900. applog(LOG_NOTICE, "Pool %d no longer misbehaving, re-enabling!", pool->pool_no);
  2901. enable_pool(pool);
  2902. }
  2903. }
  2904. 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)
  2905. {
  2906. const int offsets = max(ntime_roll, 60);
  2907. *nrl = (struct ntime_roll_limits){
  2908. .min = ntime_base,
  2909. .max = ntime_base + ntime_roll,
  2910. .tv_ref = *tvp_ref,
  2911. .minoff = -offsets,
  2912. .maxoff = offsets,
  2913. };
  2914. }
  2915. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll, const struct timeval * const tvp_ref)
  2916. {
  2917. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll, tvp_ref);
  2918. }
  2919. int work_ntime_range(struct work * const work, const struct timeval * const tvp_earliest, const struct timeval * const tvp_latest, const int desired_roll)
  2920. {
  2921. const struct ntime_roll_limits * const nrl = &work->ntime_roll_limits;
  2922. const uint32_t ref_ntime = work_get_ntime(work);
  2923. const int earliest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_earliest);
  2924. const int latest_elapsed = timer_elapsed(&nrl->tv_ref, tvp_latest);
  2925. // minimum ntime is the latest possible result (add a second to spare) adjusted for minimum offset (or fixed minimum ntime)
  2926. uint32_t min_ntime = max(nrl->min, ref_ntime + latest_elapsed+1 + nrl->minoff);
  2927. // maximum ntime is the earliest possible result adjusted for maximum offset (or fixed maximum ntime)
  2928. uint32_t max_ntime = min(nrl->max, ref_ntime + earliest_elapsed + nrl->maxoff);
  2929. if (max_ntime < min_ntime)
  2930. return -1;
  2931. if (max_ntime - min_ntime > desired_roll)
  2932. {
  2933. // Adjust min_ntime upward for accuracy, when possible
  2934. const int mid_elapsed = ((latest_elapsed - earliest_elapsed) / 2) + earliest_elapsed;
  2935. uint32_t ideal_ntime = ref_ntime + mid_elapsed;
  2936. if (ideal_ntime > min_ntime)
  2937. min_ntime = min(ideal_ntime, max_ntime - desired_roll);
  2938. }
  2939. work_set_ntime(work, min_ntime);
  2940. return max_ntime - min_ntime;
  2941. }
  2942. #if BLKMAKER_VERSION > 1
  2943. static
  2944. bool goal_has_at_least_one_getcbaddr(const struct mining_goal_info * const goal)
  2945. {
  2946. for (int i = 0; i < total_pools; ++i)
  2947. {
  2948. struct pool * const pool = pools[i];
  2949. if (uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2950. return true;
  2951. }
  2952. return false;
  2953. }
  2954. static
  2955. void refresh_bitcoind_address(struct mining_goal_info * const goal, const bool fresh)
  2956. {
  2957. struct blockchain_info * const blkchain = goal->blkchain;
  2958. if (!goal_has_at_least_one_getcbaddr(goal))
  2959. return;
  2960. char getcbaddr_req[60];
  2961. CURL *curl = NULL;
  2962. json_t *json, *j2;
  2963. const char *s, *s2;
  2964. bytes_t newscript = BYTES_INIT;
  2965. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2966. for (int i = 0; i < total_pools; ++i)
  2967. {
  2968. struct pool * const pool = pools[i];
  2969. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2970. continue;
  2971. if (pool->goal != goal)
  2972. continue;
  2973. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2974. if (!curl)
  2975. {
  2976. curl = curl_easy_init();
  2977. if (unlikely(!curl))
  2978. {
  2979. applogfail(LOG_ERR, "curl_easy_init");
  2980. break;
  2981. }
  2982. }
  2983. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2984. if (unlikely((!json) || !json_is_null( (j2 = json_object_get(json, "error")) )))
  2985. {
  2986. const char *estrc;
  2987. char *estr = NULL;
  2988. if (!(json && j2))
  2989. estrc = NULL;
  2990. else
  2991. {
  2992. estrc = json_string_value(j2);
  2993. if (!estrc)
  2994. estrc = estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS);
  2995. }
  2996. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, estrc);
  2997. free(estr);
  2998. continue;
  2999. }
  3000. s = bfg_json_obj_string(json, "result", NULL);
  3001. if (unlikely(!s))
  3002. {
  3003. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  3004. continue;
  3005. }
  3006. s2 = set_b58addr(s, &newscript);
  3007. if (unlikely(s2))
  3008. {
  3009. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  3010. continue;
  3011. }
  3012. if (goal->generation_script)
  3013. {
  3014. if (bytes_eq(&newscript, goal->generation_script))
  3015. {
  3016. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  3017. break;
  3018. }
  3019. }
  3020. else
  3021. {
  3022. goal->generation_script = malloc(sizeof(*goal->generation_script));
  3023. bytes_init(goal->generation_script);
  3024. }
  3025. bytes_assimilate(goal->generation_script, &newscript);
  3026. coinbase_script_block_id = blkchain->currentblk->block_id;
  3027. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  3028. break;
  3029. }
  3030. bytes_free(&newscript);
  3031. if (curl)
  3032. curl_easy_cleanup(curl);
  3033. }
  3034. #endif
  3035. #define GBT_XNONCESZ (sizeof(uint32_t))
  3036. #if BLKMAKER_VERSION > 4
  3037. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  3038. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  3039. #endif
  3040. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  3041. {
  3042. json_t *res_val = json_object_get(val, "result");
  3043. json_t *tmp_val;
  3044. bool ret = false;
  3045. struct timeval tv_now;
  3046. if (unlikely(detect_algo == 1)) {
  3047. json_t *tmp = json_object_get(res_val, "algorithm");
  3048. const char *v = tmp ? json_string_value(tmp) : "";
  3049. if (strncasecmp(v, "scrypt", 6))
  3050. detect_algo = 2;
  3051. }
  3052. timer_set_now(&tv_now);
  3053. if (work->tr)
  3054. {
  3055. blktemplate_t * const tmpl = work->tr->tmpl;
  3056. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  3057. if (err) {
  3058. applog(LOG_ERR, "blktmpl error: %s", err);
  3059. return false;
  3060. }
  3061. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  3062. #if BLKMAKER_VERSION > 1
  3063. struct mining_goal_info * const goal = pool->goal;
  3064. const uint32_t tmpl_block_id = ((uint32_t*)tmpl->prevblk)[0];
  3065. if ((!tmpl->cbtxn) && coinbase_script_block_id != tmpl_block_id)
  3066. refresh_bitcoind_address(goal, false);
  3067. if (goal->generation_script)
  3068. {
  3069. bool newcb;
  3070. #if BLKMAKER_VERSION > 2
  3071. blkmk_init_generation2(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script), &newcb);
  3072. #else
  3073. newcb = !tmpl->cbtxn;
  3074. blkmk_init_generation(tmpl, bytes_buf(goal->generation_script), bytes_len(goal->generation_script));
  3075. #endif
  3076. if (newcb)
  3077. {
  3078. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  3079. if (ae < (ssize_t)sizeof(template_nonce))
  3080. 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);
  3081. ++template_nonce;
  3082. }
  3083. }
  3084. #endif
  3085. #if BLKMAKER_VERSION > 0
  3086. {
  3087. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  3088. static bool appenderr = false;
  3089. if (ae <= 0) {
  3090. if (opt_coinbase_sig) {
  3091. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  3092. appenderr = true;
  3093. }
  3094. } else if (ae >= 3 || opt_coinbase_sig) {
  3095. const char *cbappend = opt_coinbase_sig;
  3096. const char full[] = PACKAGE " " VERSION;
  3097. char *need_free = NULL;
  3098. if (!cbappend) {
  3099. if ((size_t)ae >= sizeof(full) - 1)
  3100. cbappend = full;
  3101. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  3102. {
  3103. const char *pos = strchr(full, '-');
  3104. size_t sz = (pos - full);
  3105. if (pos && ae > sz)
  3106. {
  3107. cbappend = need_free = malloc(sz + 1);
  3108. memcpy(need_free, full, sz);
  3109. need_free[sz] = '\0';
  3110. }
  3111. else
  3112. cbappend = PACKAGE;
  3113. }
  3114. else
  3115. cbappend = "BFG";
  3116. }
  3117. size_t cbappendsz = strlen(cbappend);
  3118. static bool truncatewarning = false;
  3119. if (cbappendsz <= (size_t)ae) {
  3120. if (cbappendsz < (size_t)ae)
  3121. // If we have space, include the trailing \0
  3122. ++cbappendsz;
  3123. ae = cbappendsz;
  3124. truncatewarning = false;
  3125. } else {
  3126. char *tmp = malloc(ae + 1);
  3127. memcpy(tmp, opt_coinbase_sig, ae);
  3128. tmp[ae] = '\0';
  3129. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  3130. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  3131. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  3132. free(tmp);
  3133. truncatewarning = true;
  3134. }
  3135. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  3136. free(need_free);
  3137. if (ae <= 0) {
  3138. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  3139. appenderr = true;
  3140. } else
  3141. appenderr = false;
  3142. }
  3143. }
  3144. #endif
  3145. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  3146. return false;
  3147. swap32yes(work->data, work->data, 80 / 4);
  3148. memcpy(&work->data[80], workpadding_bin, 48);
  3149. work->ntime_roll_limits = (struct ntime_roll_limits){
  3150. .min = tmpl->mintime,
  3151. .max = tmpl->maxtime,
  3152. .tv_ref = tv_now,
  3153. .minoff = tmpl->mintimeoff,
  3154. .maxoff = tmpl->maxtimeoff,
  3155. };
  3156. const struct blktmpl_longpoll_req *lp;
  3157. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  3158. free(pool->lp_id);
  3159. pool->lp_id = strdup(lp->id);
  3160. #if 0 /* This just doesn't work :( */
  3161. curl_socket_t sock = pool->lp_socket;
  3162. if (sock != CURL_SOCKET_BAD) {
  3163. pool->lp_socket = CURL_SOCKET_BAD;
  3164. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  3165. shutdown(sock, SHUT_RDWR);
  3166. }
  3167. #endif
  3168. }
  3169. }
  3170. else
  3171. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  3172. applog(LOG_ERR, "JSON inval data");
  3173. return false;
  3174. }
  3175. else
  3176. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  3177. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  3178. // Calculate it ourselves
  3179. applog(LOG_DEBUG, "Calculating midstate locally");
  3180. calc_midstate(work);
  3181. }
  3182. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  3183. applog(LOG_ERR, "JSON inval target");
  3184. return false;
  3185. }
  3186. if (work->tr)
  3187. {
  3188. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  3189. {
  3190. int p = (sizeof(work->target) - 1) - i;
  3191. unsigned char c = work->target[i];
  3192. work->target[i] = work->target[p];
  3193. work->target[p] = c;
  3194. }
  3195. }
  3196. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  3197. struct mining_goal_info * const goal = pool->goal;
  3198. uint32_t blkheight = json_number_value(tmp_val);
  3199. const void * const prevblkhash = &work->data[4];
  3200. have_block_height(goal, prevblkhash, blkheight);
  3201. }
  3202. memset(work->hash, 0, sizeof(work->hash));
  3203. work->tv_staged = tv_now;
  3204. #if BLKMAKER_VERSION > 4
  3205. if (work->tr)
  3206. {
  3207. blktemplate_t * const tmpl = work->tr->tmpl;
  3208. uint8_t buf[80];
  3209. int16_t expire;
  3210. uint8_t *cbtxn;
  3211. size_t cbtxnsz;
  3212. size_t cbextranonceoffset;
  3213. int branchcount;
  3214. libblkmaker_hash_t *branches;
  3215. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  3216. {
  3217. struct stratum_work * const swork = &pool->swork;
  3218. const size_t branchdatasz = branchcount * 0x20;
  3219. pool_check_coinbase(pool, cbtxn, cbtxnsz);
  3220. cg_wlock(&pool->data_lock);
  3221. swork->tr = work->tr;
  3222. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  3223. swork->nonce2_offset = cbextranonceoffset;
  3224. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  3225. swork->merkles = branchcount;
  3226. memcpy(swork->header1, &buf[0], 36);
  3227. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  3228. swork->tv_received = tv_now;
  3229. memcpy(swork->diffbits, &buf[72], 4);
  3230. memcpy(swork->target, work->target, sizeof(swork->target));
  3231. free(swork->job_id);
  3232. swork->job_id = NULL;
  3233. swork->clean = true;
  3234. swork->work_restart_id = pool->work_restart_id;
  3235. // FIXME: Do something with expire
  3236. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  3237. pool->nonce2 = 0;
  3238. cg_wunlock(&pool->data_lock);
  3239. }
  3240. else
  3241. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  3242. }
  3243. #endif // BLKMAKER_VERSION > 4
  3244. pool_set_opaque(pool, !work->tr);
  3245. ret = true;
  3246. return ret;
  3247. }
  3248. /* Returns whether the pool supports local work generation or not. */
  3249. static bool pool_localgen(struct pool *pool)
  3250. {
  3251. return (pool->last_work_copy || pool->has_stratum);
  3252. }
  3253. int dev_from_id(int thr_id)
  3254. {
  3255. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3256. return cgpu->device_id;
  3257. }
  3258. /* Create an exponentially decaying average over the opt_log_interval */
  3259. void decay_time(double *f, double fadd, double fsecs)
  3260. {
  3261. double ftotal, fprop;
  3262. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  3263. ftotal = 1.0 + fprop;
  3264. *f += (fadd * fprop);
  3265. *f /= ftotal;
  3266. }
  3267. static int __total_staged(void)
  3268. {
  3269. return HASH_COUNT(staged_work);
  3270. }
  3271. static int total_staged(void)
  3272. {
  3273. int ret;
  3274. mutex_lock(stgd_lock);
  3275. ret = __total_staged();
  3276. mutex_unlock(stgd_lock);
  3277. return ret;
  3278. }
  3279. #ifdef HAVE_CURSES
  3280. WINDOW *mainwin, *statuswin, *logwin;
  3281. #endif
  3282. double total_secs = 1.0;
  3283. #ifdef HAVE_CURSES
  3284. static char statusline[256];
  3285. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3286. static int statusy;
  3287. static int devsummaryYOffset;
  3288. static int total_lines;
  3289. #endif
  3290. #ifdef HAVE_OPENCL
  3291. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  3292. #endif
  3293. struct cgpu_info *cpus;
  3294. bool _bfg_console_cancel_disabled;
  3295. int _bfg_console_prev_cancelstate;
  3296. #ifdef HAVE_CURSES
  3297. #define lock_curses() bfg_console_lock()
  3298. #define unlock_curses() bfg_console_unlock()
  3299. static bool curses_active_locked(void)
  3300. {
  3301. bool ret;
  3302. lock_curses();
  3303. ret = curses_active;
  3304. if (!ret)
  3305. unlock_curses();
  3306. return ret;
  3307. }
  3308. // Cancellable getch
  3309. int my_cancellable_getch(void)
  3310. {
  3311. // This only works because the macro only hits direct getch() calls
  3312. typedef int (*real_getch_t)(void);
  3313. const real_getch_t real_getch = __real_getch;
  3314. int type, rv;
  3315. bool sct;
  3316. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  3317. rv = real_getch();
  3318. if (sct)
  3319. pthread_setcanceltype(type, &type);
  3320. return rv;
  3321. }
  3322. #ifdef PDCURSES
  3323. static
  3324. int bfg_wresize(WINDOW *win, int lines, int columns)
  3325. {
  3326. int rv = wresize(win, lines, columns);
  3327. int x, y;
  3328. getyx(win, y, x);
  3329. if (unlikely(y >= lines || x >= columns))
  3330. {
  3331. if (y >= lines)
  3332. y = lines - 1;
  3333. if (x >= columns)
  3334. x = columns - 1;
  3335. wmove(win, y, x);
  3336. }
  3337. return rv;
  3338. }
  3339. #else
  3340. # define bfg_wresize wresize
  3341. #endif
  3342. #endif
  3343. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  3344. {
  3345. va_list ap;
  3346. size_t presz = strlen(buf);
  3347. va_start(ap, fmt);
  3348. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  3349. va_end(ap);
  3350. }
  3351. double stats_elapsed(struct cgminer_stats *stats)
  3352. {
  3353. struct timeval now;
  3354. double elapsed;
  3355. if (stats->start_tv.tv_sec == 0)
  3356. elapsed = total_secs;
  3357. else {
  3358. cgtime(&now);
  3359. elapsed = tdiff(&now, &stats->start_tv);
  3360. }
  3361. if (elapsed < 1.0)
  3362. elapsed = 1.0;
  3363. return elapsed;
  3364. }
  3365. bool drv_ready(struct cgpu_info *cgpu)
  3366. {
  3367. switch (cgpu->status) {
  3368. case LIFE_INIT:
  3369. case LIFE_DEAD2:
  3370. return false;
  3371. default:
  3372. return true;
  3373. }
  3374. }
  3375. double cgpu_utility(struct cgpu_info *cgpu)
  3376. {
  3377. double dev_runtime = cgpu_runtime(cgpu);
  3378. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3379. }
  3380. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  3381. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  3382. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  3383. }while(0)
  3384. static float
  3385. utility_to_hashrate(double utility)
  3386. {
  3387. return utility * 0x4444444;
  3388. }
  3389. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  3390. static const int _unitbase = 4;
  3391. static
  3392. void pick_unit(float hashrate, unsigned char *unit)
  3393. {
  3394. unsigned char i;
  3395. if (hashrate == 0 || !isfinite(hashrate))
  3396. {
  3397. if (*unit < _unitbase)
  3398. *unit = _unitbase;
  3399. return;
  3400. }
  3401. hashrate *= 1e12;
  3402. for (i = 0; i < *unit; ++i)
  3403. hashrate /= 1e3;
  3404. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  3405. while (hashrate >= 999.95)
  3406. {
  3407. hashrate /= 1e3;
  3408. if (likely(_unitchar[*unit] != '?'))
  3409. ++*unit;
  3410. }
  3411. }
  3412. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  3413. enum h2bs_fmt {
  3414. H2B_NOUNIT, // "xxx.x"
  3415. H2B_SHORT, // "xxx.xMH/s"
  3416. H2B_SPACED, // "xxx.x MH/s"
  3417. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  3418. };
  3419. enum bfu_floatprec {
  3420. FUP_INTEGER,
  3421. FUP_HASHES,
  3422. FUP_BTC,
  3423. FUP_DIFF,
  3424. };
  3425. static
  3426. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  3427. {
  3428. char *s = buf;
  3429. unsigned char prec, i, unit;
  3430. int rv = 0;
  3431. if (unitin == -1)
  3432. {
  3433. unit = 0;
  3434. hashrate_pick_unit(hashrate, &unit);
  3435. }
  3436. else
  3437. unit = unitin;
  3438. hashrate *= 1e12;
  3439. for (i = 0; i < unit; ++i)
  3440. hashrate /= 1000;
  3441. switch (fprec)
  3442. {
  3443. case FUP_HASHES:
  3444. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  3445. if (hashrate >= 99.995 || unit < 6)
  3446. prec = 1;
  3447. else
  3448. prec = 2;
  3449. _SNP("%5.*f", prec, hashrate);
  3450. break;
  3451. case FUP_INTEGER:
  3452. _SNP("%3d", (int)hashrate);
  3453. break;
  3454. case FUP_BTC:
  3455. if (hashrate >= 99.995)
  3456. prec = 0;
  3457. else
  3458. prec = 2;
  3459. _SNP("%5.*f", prec, hashrate);
  3460. break;
  3461. case FUP_DIFF:
  3462. if (unit > _unitbase)
  3463. _SNP("%.3g", hashrate);
  3464. else
  3465. _SNP("%u", (unsigned int)hashrate);
  3466. }
  3467. if (fmt != H2B_NOUNIT)
  3468. {
  3469. char uc[3] = {_unitchar[unit], '\0'};
  3470. switch (fmt) {
  3471. case H2B_SPACED:
  3472. _SNP(" ");
  3473. default:
  3474. break;
  3475. case H2B_SHORTV:
  3476. if (isspace(uc[0]))
  3477. uc[0] = '\0';
  3478. }
  3479. if (uc[0] == '\xb5')
  3480. // Convert to UTF-8
  3481. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3482. _SNP("%s%s", uc, measurement);
  3483. }
  3484. return rv;
  3485. }
  3486. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3487. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3488. static
  3489. 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)
  3490. {
  3491. unsigned char unit = 0;
  3492. bool allzero = true;
  3493. int i;
  3494. size_t delimsz = 0;
  3495. char *buf = buflist[0];
  3496. size_t bufsz = bufszlist[0];
  3497. size_t itemwidth = (floatprec ? 5 : 3);
  3498. if (!isarray)
  3499. delimsz = strlen(delim);
  3500. for (i = 0; i < count; ++i)
  3501. if (numbers[i] != 0)
  3502. {
  3503. pick_unit(numbers[i], &unit);
  3504. allzero = false;
  3505. }
  3506. if (allzero)
  3507. unit = _unitbase;
  3508. --count;
  3509. for (i = 0; i < count; ++i)
  3510. {
  3511. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3512. if (isarray)
  3513. {
  3514. buf = buflist[i + 1];
  3515. bufsz = bufszlist[i + 1];
  3516. }
  3517. else
  3518. {
  3519. buf += itemwidth;
  3520. bufsz -= itemwidth;
  3521. if (delimsz > bufsz)
  3522. delimsz = bufsz;
  3523. memcpy(buf, delim, delimsz);
  3524. buf += delimsz;
  3525. bufsz -= delimsz;
  3526. }
  3527. }
  3528. // Last entry has the unit
  3529. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3530. return buflist[0];
  3531. }
  3532. #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)
  3533. #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)
  3534. static
  3535. int percentf3(char * const buf, size_t sz, double p, const double t)
  3536. {
  3537. char *s = buf;
  3538. int rv = 0;
  3539. if (!p)
  3540. _SNP("none");
  3541. else
  3542. if (t <= p)
  3543. _SNP("100%%");
  3544. else
  3545. {
  3546. p /= t;
  3547. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3548. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3549. else
  3550. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3551. _SNP("%.1f%%", p * 100); // "9.1%"
  3552. else
  3553. _SNP("%3.0f%%", p * 100); // " 99%"
  3554. }
  3555. return rv;
  3556. }
  3557. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3558. static
  3559. void test_decimal_width()
  3560. {
  3561. // The pipe character at end of each line should perfectly line up
  3562. char printbuf[512];
  3563. char testbuf1[64];
  3564. char testbuf2[64];
  3565. char testbuf3[64];
  3566. char testbuf4[64];
  3567. double testn;
  3568. int width;
  3569. int saved;
  3570. // Hotspots around 0.1 and 0.01
  3571. saved = -1;
  3572. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3573. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3574. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3575. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3576. if (unlikely((saved != -1) && (width != saved))) {
  3577. ++unittest_failures;
  3578. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3579. applog(LOG_ERR, "%s", printbuf);
  3580. }
  3581. saved = width;
  3582. }
  3583. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3584. saved = -1;
  3585. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3586. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3587. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3588. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3589. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3590. width = utf8_strlen(printbuf);
  3591. if (unlikely((saved != -1) && (width != saved))) {
  3592. ++unittest_failures;
  3593. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3594. applog(LOG_ERR, "%s", printbuf);
  3595. }
  3596. saved = width;
  3597. }
  3598. // Hotspot around unit transition boundary in pick_unit
  3599. saved = -1;
  3600. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3601. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3602. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3603. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3604. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3605. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3606. width = utf8_strlen(printbuf);
  3607. if (unlikely((saved != -1) && (width != saved))) {
  3608. ++unittest_failures;
  3609. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3610. applog(LOG_ERR, "%s", printbuf);
  3611. }
  3612. saved = width;
  3613. }
  3614. }
  3615. #ifdef HAVE_CURSES
  3616. static void adj_width(int var, int *length);
  3617. #endif
  3618. #ifdef HAVE_CURSES
  3619. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3620. static
  3621. 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)
  3622. {
  3623. char rejpcbuf[6];
  3624. char bnbuf[6];
  3625. adj_width(accepted, &awidth);
  3626. adj_width(rejected, &rwidth);
  3627. adj_width(stale, &swidth);
  3628. adj_width(hwerrs, &hwwidth);
  3629. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3630. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3631. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3632. cHr, aHr, uHr,
  3633. awidth, accepted,
  3634. rwidth, rejected,
  3635. swidth, stale,
  3636. rejpcbuf,
  3637. hwwidth, hwerrs,
  3638. bnbuf
  3639. );
  3640. }
  3641. static
  3642. const char *pool_proto_str(const struct pool * const pool)
  3643. {
  3644. if (pool->idle)
  3645. return "Dead ";
  3646. if (pool->has_stratum)
  3647. return "Strtm";
  3648. if (pool->lp_url && pool->proto != pool->lp_proto)
  3649. return "Mixed";
  3650. switch (pool->proto)
  3651. {
  3652. case PLP_GETBLOCKTEMPLATE:
  3653. return " GBT ";
  3654. case PLP_GETWORK:
  3655. return "GWork";
  3656. default:
  3657. return "Alive";
  3658. }
  3659. }
  3660. #endif
  3661. static inline
  3662. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3663. {
  3664. if (!(use_unicode && have_unicode_degrees))
  3665. maybe_unicode = false;
  3666. if (temp && *temp > 0.)
  3667. if (maybe_unicode)
  3668. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3669. else
  3670. snprintf(buf, bufsz, "%4.1fC", *temp);
  3671. else
  3672. {
  3673. if (temp)
  3674. snprintf(buf, bufsz, " ");
  3675. if (maybe_unicode)
  3676. tailsprintf(buf, bufsz, " ");
  3677. }
  3678. tailsprintf(buf, bufsz, " | ");
  3679. }
  3680. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3681. {
  3682. #ifndef HAVE_CURSES
  3683. assert(for_curses == false);
  3684. #endif
  3685. struct device_drv *drv = cgpu->drv;
  3686. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3687. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3688. char rejpcbuf[6];
  3689. char bnbuf[6];
  3690. double dev_runtime;
  3691. if (!opt_show_procs)
  3692. cgpu = cgpu->device;
  3693. dev_runtime = cgpu_runtime(cgpu);
  3694. double rolling, mhashes;
  3695. int accepted, rejected, stale;
  3696. double waccepted;
  3697. double wnotaccepted;
  3698. int hwerrs;
  3699. double bad_diff1, good_diff1;
  3700. rolling = mhashes = waccepted = wnotaccepted = 0;
  3701. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3702. {
  3703. struct cgpu_info *slave = cgpu;
  3704. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3705. {
  3706. slave->utility = slave->accepted / dev_runtime * 60;
  3707. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3708. rolling += slave->rolling;
  3709. mhashes += slave->total_mhashes;
  3710. if (opt_weighed_stats)
  3711. {
  3712. accepted += slave->diff_accepted;
  3713. rejected += slave->diff_rejected;
  3714. stale += slave->diff_stale;
  3715. }
  3716. else
  3717. {
  3718. accepted += slave->accepted;
  3719. rejected += slave->rejected;
  3720. stale += slave->stale;
  3721. }
  3722. waccepted += slave->diff_accepted;
  3723. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3724. hwerrs += slave->hw_errors;
  3725. bad_diff1 += slave->bad_diff1;
  3726. good_diff1 += slave->diff1;
  3727. if (opt_show_procs)
  3728. break;
  3729. }
  3730. }
  3731. double wtotal = (waccepted + wnotaccepted);
  3732. multi_format_unit_array2(
  3733. ((char*[]){cHr, aHr, uHr}),
  3734. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3735. true, "h/s", hashrate_style,
  3736. 3,
  3737. 1e6*rolling,
  3738. 1e6*mhashes / dev_runtime,
  3739. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3740. // Processor representation
  3741. #ifdef HAVE_CURSES
  3742. if (for_curses)
  3743. {
  3744. if (opt_show_procs)
  3745. snprintf(buf, bufsz, " %*s: ", -(5 + max_lpdigits), cgpu->proc_repr);
  3746. else
  3747. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3748. }
  3749. else
  3750. #endif
  3751. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3752. if (include_serial_in_statline && cgpu->dev_serial)
  3753. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3754. if (unlikely(cgpu->status == LIFE_INIT))
  3755. {
  3756. tailsprintf(buf, bufsz, "Initializing...");
  3757. return;
  3758. }
  3759. {
  3760. const size_t bufln = strlen(buf);
  3761. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3762. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3763. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3764. else
  3765. {
  3766. float temp = cgpu->temp;
  3767. if (!opt_show_procs)
  3768. {
  3769. // Find the highest temperature of all processors
  3770. struct cgpu_info *proc = cgpu;
  3771. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3772. if (proc->temp > temp)
  3773. temp = proc->temp;
  3774. }
  3775. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3776. }
  3777. }
  3778. #ifdef HAVE_CURSES
  3779. if (for_curses)
  3780. {
  3781. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3782. const char *cHrStats;
  3783. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3784. bool all_dead = true, all_off = true, all_rdrv = true;
  3785. struct cgpu_info *proc = cgpu;
  3786. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3787. {
  3788. switch (cHrStatsI) {
  3789. default:
  3790. if (proc->status == LIFE_WAIT)
  3791. cHrStatsI = 5;
  3792. case 5:
  3793. if (proc->deven == DEV_RECOVER_ERR)
  3794. cHrStatsI = 4;
  3795. case 4:
  3796. if (proc->deven == DEV_RECOVER)
  3797. cHrStatsI = 3;
  3798. case 3:
  3799. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3800. {
  3801. cHrStatsI = 1;
  3802. all_off = false;
  3803. }
  3804. else
  3805. {
  3806. if (likely(proc->deven == DEV_ENABLED))
  3807. all_off = false;
  3808. if (proc->deven != DEV_RECOVER_DRV)
  3809. all_rdrv = false;
  3810. }
  3811. case 1:
  3812. break;
  3813. }
  3814. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3815. all_dead = false;
  3816. if (opt_show_procs)
  3817. break;
  3818. }
  3819. if (unlikely(all_dead))
  3820. cHrStatsI = 0;
  3821. else
  3822. if (unlikely(all_off))
  3823. cHrStatsI = 2;
  3824. cHrStats = cHrStatsOpt[cHrStatsI];
  3825. if (cHrStatsI == 2 && all_rdrv)
  3826. cHrStats = " RST ";
  3827. format_statline(buf, bufsz,
  3828. cHrStats,
  3829. aHr, uHr,
  3830. accepted, rejected, stale,
  3831. wnotaccepted, waccepted,
  3832. hwerrs,
  3833. bad_diff1, bad_diff1 + good_diff1);
  3834. }
  3835. else
  3836. #endif
  3837. {
  3838. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3839. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3840. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3841. opt_log_interval,
  3842. cHr, aHr, uHr,
  3843. accepted,
  3844. rejected,
  3845. stale,
  3846. rejpcbuf,
  3847. hwerrs,
  3848. bnbuf
  3849. );
  3850. }
  3851. }
  3852. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3853. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3854. static void text_print_status(int thr_id)
  3855. {
  3856. struct cgpu_info *cgpu;
  3857. char logline[256];
  3858. cgpu = get_thr_cgpu(thr_id);
  3859. if (cgpu) {
  3860. get_statline(logline, sizeof(logline), cgpu);
  3861. printf("\n%s\r", logline);
  3862. fflush(stdout);
  3863. }
  3864. }
  3865. #ifdef HAVE_CURSES
  3866. static int attr_bad = A_BOLD;
  3867. #ifdef WIN32
  3868. #define swprintf snwprintf
  3869. #endif
  3870. static
  3871. void bfg_waddstr(WINDOW *win, const char *s)
  3872. {
  3873. const char *p = s;
  3874. int32_t w;
  3875. int wlen;
  3876. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3877. while (true)
  3878. {
  3879. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3880. {
  3881. // Printable ASCII
  3882. ++p;
  3883. }
  3884. if (p != s)
  3885. waddnstr(win, s, p - s);
  3886. w = utf8_decode(p, &wlen);
  3887. s = p += wlen;
  3888. switch(w)
  3889. {
  3890. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3891. case '\0':
  3892. return;
  3893. case 0xb5: // micro symbol
  3894. w = unicode_micro;
  3895. goto default_addch;
  3896. case 0xf000: // "bad" off
  3897. wattroff(win, attr_bad);
  3898. break;
  3899. case 0xf001: // "bad" on
  3900. wattron(win, attr_bad);
  3901. break;
  3902. #ifdef USE_UNICODE
  3903. case '|':
  3904. wadd_wch(win, WACS_VLINE);
  3905. break;
  3906. #endif
  3907. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3908. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3909. if (!use_unicode)
  3910. {
  3911. waddch(win, '-');
  3912. break;
  3913. }
  3914. #ifdef USE_UNICODE
  3915. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3916. break;
  3917. #endif
  3918. case 0x2022:
  3919. if (w > WCHAR_MAX || !iswprint(w))
  3920. w = '*';
  3921. default:
  3922. default_addch:
  3923. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3924. {
  3925. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3926. if (iswprint(REPLACEMENT_CHAR))
  3927. w = REPLACEMENT_CHAR;
  3928. else
  3929. #endif
  3930. w = '?';
  3931. }
  3932. {
  3933. #ifdef USE_UNICODE
  3934. wchar_t wbuf[0x10];
  3935. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3936. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3937. waddnwstr(win, wbuf, wbuflen);
  3938. #else
  3939. wprintw(win, "%lc", (wint_t)w);
  3940. #endif
  3941. }
  3942. }
  3943. }
  3944. }
  3945. static inline
  3946. void bfg_hline(WINDOW *win, int y)
  3947. {
  3948. int maxx, __maybe_unused maxy;
  3949. getmaxyx(win, maxy, maxx);
  3950. #ifdef USE_UNICODE
  3951. if (use_unicode)
  3952. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3953. else
  3954. #endif
  3955. mvwhline(win, y, 0, '-', maxx);
  3956. }
  3957. static
  3958. int bfg_win_linelen(WINDOW * const win)
  3959. {
  3960. int maxx;
  3961. int __maybe_unused y;
  3962. getmaxyx(win, y, maxx);
  3963. return maxx;
  3964. }
  3965. // Spaces until end of line, using current attributes (ie, not completely clear)
  3966. static
  3967. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3968. {
  3969. int x, maxx;
  3970. int __maybe_unused y;
  3971. getmaxyx(win, y, maxx);
  3972. getyx(win, y, x);
  3973. const int space_count = (maxx - x) - offset;
  3974. // Check for negative - terminal too narrow
  3975. if (space_count <= 0)
  3976. return;
  3977. char buf[space_count];
  3978. memset(buf, ' ', space_count);
  3979. waddnstr(win, buf, space_count);
  3980. }
  3981. static int menu_attr = A_REVERSE;
  3982. #define CURBUFSIZ 256
  3983. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3984. char tmp42[CURBUFSIZ]; \
  3985. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3986. wmove(win, y, x); \
  3987. bfg_waddstr(win, tmp42); \
  3988. } while (0)
  3989. #define cg_wprintw(win, fmt, ...) do { \
  3990. char tmp42[CURBUFSIZ]; \
  3991. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3992. bfg_waddstr(win, tmp42); \
  3993. } while (0)
  3994. static
  3995. void update_block_display_line(const int blky, struct mining_goal_info *goal)
  3996. {
  3997. struct blockchain_info * const blkchain = goal->blkchain;
  3998. struct block_info * const blkinfo = blkchain->currentblk;
  3999. double income;
  4000. char incomestr[ALLOC_H2B_SHORT+6+1];
  4001. if (blkinfo->height)
  4002. {
  4003. income = goal->diff_accepted * 3600 * blkchain->currentblk_subsidy / total_secs / goal->current_diff;
  4004. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  4005. }
  4006. else
  4007. strcpy(incomestr, "?");
  4008. int linelen = bfg_win_linelen(statuswin);
  4009. wmove(statuswin, blky, 0);
  4010. bfg_waddstr(statuswin, " Block");
  4011. if (!goal->is_default)
  4012. linelen -= strlen(goal->name) + 1;
  4013. linelen -= 6; // " Block"
  4014. if (blkinfo->height && blkinfo->height < 1000000)
  4015. {
  4016. cg_wprintw(statuswin, " #%6u", blkinfo->height);
  4017. linelen -= 8;
  4018. }
  4019. bfg_waddstr(statuswin, ":");
  4020. if (linelen > 55)
  4021. bfg_waddstr(statuswin, " ");
  4022. if (linelen >= 65)
  4023. bfg_waddstr(statuswin, "...");
  4024. {
  4025. char hexpbh[0x11];
  4026. if (!(blkinfo->height && blkinfo->height < 1000000))
  4027. {
  4028. bin2hex(hexpbh, &blkinfo->prevblkhash[4], 4);
  4029. bfg_waddstr(statuswin, hexpbh);
  4030. }
  4031. bin2hex(hexpbh, &blkinfo->prevblkhash[0], 4);
  4032. bfg_waddstr(statuswin, hexpbh);
  4033. }
  4034. if (linelen >= 55)
  4035. bfg_waddstr(statuswin, " ");
  4036. cg_wprintw(statuswin, " Diff:%s", goal->current_diff_str);
  4037. if (linelen >= 69)
  4038. bfg_waddstr(statuswin, " ");
  4039. cg_wprintw(statuswin, "(%s) ", goal->net_hashrate);
  4040. if (linelen >= 62)
  4041. {
  4042. if (linelen >= 69)
  4043. bfg_waddstr(statuswin, " ");
  4044. bfg_waddstr(statuswin, "Started:");
  4045. }
  4046. else
  4047. bfg_waddstr(statuswin, "S:");
  4048. if (linelen >= 69)
  4049. bfg_waddstr(statuswin, " ");
  4050. bfg_waddstr(statuswin, blkchain->currentblk_first_seen_time_str);
  4051. if (linelen >= 69)
  4052. bfg_waddstr(statuswin, " ");
  4053. cg_wprintw(statuswin, " I:%s", incomestr);
  4054. if (!goal->is_default)
  4055. cg_wprintw(statuswin, " %s", goal->name);
  4056. wclrtoeol(statuswin);
  4057. }
  4058. static bool pool_actively_in_use(const struct pool *, const struct pool *);
  4059. static
  4060. void update_block_display(void)
  4061. {
  4062. struct mining_goal_info *goal, *tmpgoal;
  4063. int blky = 3, i, total_found_goals = 0;
  4064. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  4065. {
  4066. for (i = 0; i < total_pools; ++i)
  4067. {
  4068. struct pool * const pool = pools[i];
  4069. if (pool->goal == goal && pool_actively_in_use(pool, NULL))
  4070. break;
  4071. }
  4072. if (i >= total_pools)
  4073. // no pools using this goal, so it's probably stale anyway
  4074. continue;
  4075. update_block_display_line(blky++, goal);
  4076. ++total_found_goals;
  4077. }
  4078. if (total_found_goals != active_goals)
  4079. {
  4080. active_goals = total_found_goals;
  4081. devcursor = 7 + active_goals;
  4082. switch_logsize();
  4083. }
  4084. }
  4085. static bool pool_unworkable(const struct pool *);
  4086. /* Must be called with curses mutex lock held and curses_active */
  4087. static void curses_print_status(const int ts)
  4088. {
  4089. struct pool *pool = currentpool;
  4090. struct timeval now, tv;
  4091. float efficiency;
  4092. int logdiv;
  4093. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  4094. wattron(statuswin, attr_title);
  4095. const int linelen = bfg_win_linelen(statuswin);
  4096. int titlelen = 1 + strlen(PACKAGE) + 1 + strlen(VERSION) + 3 + 21 + 3 + 19;
  4097. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " ");
  4098. if (titlelen + 17 < linelen)
  4099. cg_wprintw(statuswin, "version ");
  4100. cg_wprintw(statuswin, VERSION " - ");
  4101. if (titlelen + 9 < linelen)
  4102. cg_wprintw(statuswin, "Started: ");
  4103. else
  4104. if (titlelen + 7 <= linelen)
  4105. cg_wprintw(statuswin, "Start: ");
  4106. cg_wprintw(statuswin, "%s", datestamp);
  4107. timer_set_now(&now);
  4108. {
  4109. unsigned int days, hours;
  4110. div_t d;
  4111. timersub(&now, &miner_started, &tv);
  4112. d = div(tv.tv_sec, 86400);
  4113. days = d.quot;
  4114. d = div(d.rem, 3600);
  4115. hours = d.quot;
  4116. d = div(d.rem, 60);
  4117. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  4118. , days
  4119. , (days == 1) ? ' ' : 's'
  4120. , hours
  4121. , d.quot
  4122. , d.rem
  4123. );
  4124. }
  4125. bfg_wspctoeol(statuswin, 0);
  4126. wattroff(statuswin, attr_title);
  4127. wattron(statuswin, menu_attr);
  4128. wmove(statuswin, 1, 0);
  4129. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  4130. bfg_wspctoeol(statuswin, 14);
  4131. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  4132. wattroff(statuswin, menu_attr);
  4133. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  4134. char poolinfo[20], poolinfo2[20];
  4135. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  4136. double lowdiff = DBL_MAX, highdiff = -1;
  4137. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  4138. time_t oldest_work_restart = time(NULL) + 1;
  4139. struct pool *oldest_work_restart_pool = pools[0];
  4140. for (int i = 0; i < total_pools; ++i)
  4141. {
  4142. if (pool_unworkable(pools[i]))
  4143. continue;
  4144. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  4145. pool = pools[i];
  4146. ++workable_pools;
  4147. if (poolinfooff < sizeof(poolinfo))
  4148. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  4149. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  4150. if (pool_stats->last_diff < lowdiff)
  4151. {
  4152. lowdiff = pool_stats->last_diff;
  4153. lowdiff_pool = pool;
  4154. }
  4155. if (pool_stats->last_diff > highdiff)
  4156. {
  4157. highdiff = pool_stats->last_diff;
  4158. highdiff_pool = pool;
  4159. }
  4160. if (oldest_work_restart >= pool->work_restart_time)
  4161. {
  4162. oldest_work_restart = pool->work_restart_time;
  4163. oldest_work_restart_pool = pool;
  4164. }
  4165. }
  4166. if (unlikely(!workable_pools))
  4167. goto no_workable_pools;
  4168. if (workable_pools == 1)
  4169. goto one_workable_pool;
  4170. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  4171. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  4172. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  4173. else
  4174. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  4175. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  4176. poolinfo2,
  4177. lowdiff_pool->diff,
  4178. (lowdiff == highdiff) ? "" : "-",
  4179. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  4180. pool->goal->have_longpoll ? '+' : '-',
  4181. oldest_work_restart_pool->work_restart_timestamp);
  4182. }
  4183. else
  4184. if (pool_unworkable(pool))
  4185. {
  4186. no_workable_pools: ;
  4187. wattron(statuswin, attr_bad);
  4188. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  4189. wattroff(statuswin, attr_bad);
  4190. }
  4191. else
  4192. {
  4193. one_workable_pool: ;
  4194. char pooladdr[19];
  4195. {
  4196. const char *rawaddr = pool->sockaddr_url;
  4197. BFGINIT(rawaddr, pool->rpc_url);
  4198. size_t pooladdrlen = strlen(rawaddr);
  4199. if (pooladdrlen > 20)
  4200. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  4201. else
  4202. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  4203. }
  4204. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  4205. pool->pool_no, pooladdr, pool->diff,
  4206. pool->goal->have_longpoll ? '+' : '-', pool_proto_str(pool),
  4207. pool->work_restart_timestamp,
  4208. pool->rpc_user);
  4209. }
  4210. wclrtoeol(statuswin);
  4211. char bwstr[(ALLOC_H2B_SHORT*2)+3+1];
  4212. cg_mvwprintw(statuswin, devcursor - 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f BS:%s",
  4213. ts,
  4214. total_go + total_ro,
  4215. new_blocks,
  4216. total_submitting,
  4217. multi_format_unit2(bwstr, sizeof(bwstr),
  4218. false, "B/s", H2B_SHORT, "/", 2,
  4219. (float)(total_bytes_rcvd / total_secs),
  4220. (float)(total_bytes_sent / total_secs)),
  4221. efficiency,
  4222. best_share);
  4223. wclrtoeol(statuswin);
  4224. mvwaddstr(statuswin, devcursor - 3, 0, " ");
  4225. bfg_waddstr(statuswin, statusline);
  4226. wclrtoeol(statuswin);
  4227. int devdiv = devcursor - 2;
  4228. logdiv = statusy - 1;
  4229. bfg_hline(statuswin, devdiv);
  4230. bfg_hline(statuswin, logdiv);
  4231. #ifdef USE_UNICODE
  4232. if (use_unicode)
  4233. {
  4234. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  4235. if (opt_show_procs && !opt_compact)
  4236. offset += max_lpdigits; // proc letter(s)
  4237. if (have_unicode_degrees)
  4238. ++offset; // degrees symbol
  4239. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4240. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4241. offset += 24; // hashrates etc
  4242. mvwadd_wch(statuswin, devdiv, offset, WACS_PLUS);
  4243. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  4244. }
  4245. #endif
  4246. }
  4247. static void adj_width(int var, int *length)
  4248. {
  4249. if ((int)(log10(var) + 1) > *length)
  4250. (*length)++;
  4251. }
  4252. static int dev_width;
  4253. static void curses_print_devstatus(struct cgpu_info *cgpu)
  4254. {
  4255. char logline[256];
  4256. int ypos;
  4257. if (opt_compact)
  4258. return;
  4259. /* Check this isn't out of the window size */
  4260. if (opt_show_procs)
  4261. ypos = cgpu->cgminer_id;
  4262. else
  4263. {
  4264. if (cgpu->proc_id)
  4265. return;
  4266. ypos = cgpu->device_line_id;
  4267. }
  4268. ypos += devsummaryYOffset;
  4269. if (ypos < 0)
  4270. return;
  4271. ypos += devcursor - 1;
  4272. if (ypos >= statusy - 1)
  4273. return;
  4274. if (wmove(statuswin, ypos, 0) == ERR)
  4275. return;
  4276. get_statline2(logline, sizeof(logline), cgpu, true);
  4277. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  4278. wattron(statuswin, A_REVERSE);
  4279. bfg_waddstr(statuswin, logline);
  4280. wattroff(statuswin, A_REVERSE);
  4281. wclrtoeol(statuswin);
  4282. }
  4283. static
  4284. void _refresh_devstatus(const bool already_have_lock) {
  4285. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  4286. int i;
  4287. if (unlikely(!total_devices))
  4288. {
  4289. const int ypos = devcursor - 1;
  4290. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  4291. {
  4292. wattron(statuswin, attr_bad);
  4293. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  4294. wclrtoeol(statuswin);
  4295. wattroff(statuswin, attr_bad);
  4296. }
  4297. }
  4298. for (i = 0; i < total_devices; i++)
  4299. curses_print_devstatus(get_devices(i));
  4300. touchwin(statuswin);
  4301. wrefresh(statuswin);
  4302. if (!already_have_lock)
  4303. unlock_curses();
  4304. }
  4305. }
  4306. #define refresh_devstatus() _refresh_devstatus(false)
  4307. #endif
  4308. static void print_status(int thr_id)
  4309. {
  4310. if (!curses_active)
  4311. text_print_status(thr_id);
  4312. }
  4313. #ifdef HAVE_CURSES
  4314. static
  4315. bool set_statusy(int maxy)
  4316. {
  4317. if (loginput_size)
  4318. {
  4319. maxy -= loginput_size;
  4320. if (maxy < 0)
  4321. maxy = 0;
  4322. }
  4323. if (logstart < maxy)
  4324. maxy = logstart;
  4325. if (statusy == maxy)
  4326. return false;
  4327. statusy = maxy;
  4328. logcursor = statusy;
  4329. return true;
  4330. }
  4331. /* Check for window resize. Called with curses mutex locked */
  4332. static inline void change_logwinsize(void)
  4333. {
  4334. int x, y, logx, logy;
  4335. getmaxyx(mainwin, y, x);
  4336. if (x < 80 || y < 25)
  4337. return;
  4338. if (y > statusy + 2 && statusy < logstart) {
  4339. set_statusy(y - 2);
  4340. mvwin(logwin, logcursor, 0);
  4341. bfg_wresize(statuswin, statusy, x);
  4342. }
  4343. y -= logcursor;
  4344. getmaxyx(logwin, logy, logx);
  4345. /* Detect screen size change */
  4346. if (x != logx || y != logy)
  4347. bfg_wresize(logwin, y, x);
  4348. }
  4349. static void check_winsizes(void)
  4350. {
  4351. if (!use_curses)
  4352. return;
  4353. if (curses_active_locked()) {
  4354. int y, x;
  4355. x = getmaxx(statuswin);
  4356. if (set_statusy(LINES - 2))
  4357. {
  4358. erase();
  4359. bfg_wresize(statuswin, statusy, x);
  4360. getmaxyx(mainwin, y, x);
  4361. y -= logcursor;
  4362. bfg_wresize(logwin, y, x);
  4363. mvwin(logwin, logcursor, 0);
  4364. }
  4365. unlock_curses();
  4366. }
  4367. }
  4368. static int device_line_id_count;
  4369. static void switch_logsize(void)
  4370. {
  4371. if (curses_active_locked()) {
  4372. if (opt_compact) {
  4373. logstart = devcursor - 1;
  4374. logcursor = logstart + 1;
  4375. } else {
  4376. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  4377. logstart = devcursor + total_lines;
  4378. logcursor = logstart;
  4379. }
  4380. unlock_curses();
  4381. }
  4382. check_winsizes();
  4383. update_block_display();
  4384. }
  4385. /* For mandatory printing when mutex is already locked */
  4386. void _wlog(const char *str)
  4387. {
  4388. static bool newline;
  4389. size_t end = strlen(str) - 1;
  4390. if (newline)
  4391. bfg_waddstr(logwin, "\n");
  4392. if (str[end] == '\n')
  4393. {
  4394. char *s;
  4395. newline = true;
  4396. s = alloca(end + 1);
  4397. memcpy(s, str, end);
  4398. s[end] = '\0';
  4399. str = s;
  4400. }
  4401. else
  4402. newline = false;
  4403. bfg_waddstr(logwin, str);
  4404. }
  4405. /* Mandatory printing */
  4406. void _wlogprint(const char *str)
  4407. {
  4408. if (curses_active_locked()) {
  4409. _wlog(str);
  4410. unlock_curses();
  4411. }
  4412. }
  4413. #endif
  4414. #ifdef HAVE_CURSES
  4415. bool _log_curses_only(int prio, const char *datetime, const char *str)
  4416. {
  4417. bool high_prio;
  4418. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  4419. if (curses_active)
  4420. {
  4421. if (!loginput_size || high_prio) {
  4422. wlog(" %s %s\n", datetime, str);
  4423. if (high_prio) {
  4424. touchwin(logwin);
  4425. wrefresh(logwin);
  4426. }
  4427. }
  4428. return true;
  4429. }
  4430. return false;
  4431. }
  4432. void clear_logwin(void)
  4433. {
  4434. if (curses_active_locked()) {
  4435. wclear(logwin);
  4436. unlock_curses();
  4437. }
  4438. }
  4439. void logwin_update(void)
  4440. {
  4441. if (curses_active_locked()) {
  4442. touchwin(logwin);
  4443. wrefresh(logwin);
  4444. unlock_curses();
  4445. }
  4446. }
  4447. #endif
  4448. void enable_pool(struct pool * const pool)
  4449. {
  4450. if (pool->enabled != POOL_ENABLED) {
  4451. mutex_lock(&lp_lock);
  4452. enabled_pools++;
  4453. pool->enabled = POOL_ENABLED;
  4454. pthread_cond_broadcast(&lp_cond);
  4455. mutex_unlock(&lp_lock);
  4456. if (pool->prio < current_pool()->prio)
  4457. switch_pools(pool);
  4458. }
  4459. }
  4460. void disable_pool(struct pool * const pool, const enum pool_enable enable_status)
  4461. {
  4462. if (pool->enabled == POOL_DISABLED)
  4463. /* had been manually disabled before */
  4464. return;
  4465. if (pool->enabled != POOL_ENABLED)
  4466. {
  4467. /* has been programmatically disabled already, just change to the new status directly */
  4468. pool->enabled = enable_status;
  4469. return;
  4470. }
  4471. /* Fall into the lock area */
  4472. mutex_lock(&lp_lock);
  4473. --enabled_pools;
  4474. pool->enabled = enable_status;
  4475. mutex_unlock(&lp_lock);
  4476. if (pool == current_pool())
  4477. switch_pools(NULL);
  4478. }
  4479. static
  4480. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  4481. struct cgpu_info *cgpu;
  4482. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4483. const unsigned char *hashpart = &work->hash[0x1c - malgo->ui_skip_hash_bytes];
  4484. char shrdiffdisp[ALLOC_H2B_SHORTV];
  4485. const double tgtdiff = work->work_difficulty;
  4486. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  4487. char where[20];
  4488. cgpu = get_thr_cgpu(work->thr_id);
  4489. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  4490. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  4491. if (total_pools > 1)
  4492. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  4493. else
  4494. where[0] = '\0';
  4495. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  4496. disp,
  4497. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  4498. cgpu->proc_repr,
  4499. where,
  4500. shrdiffdisp, tgtdiffdisp,
  4501. reason,
  4502. resubmit ? "(resubmit)" : "",
  4503. worktime
  4504. );
  4505. }
  4506. static bool test_work_current(struct work *);
  4507. static void _submit_work_async(struct work *);
  4508. static
  4509. void maybe_local_submit(const struct work *work)
  4510. {
  4511. #if BLKMAKER_VERSION > 3
  4512. if (unlikely(work->block && work->tr))
  4513. {
  4514. // This is a block with a full template (GBT)
  4515. // Regardless of the result, submit to local bitcoind(s) as well
  4516. struct work *work_cp;
  4517. for (int i = 0; i < total_pools; ++i)
  4518. {
  4519. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  4520. continue;
  4521. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  4522. work_cp = copy_work(work);
  4523. work_cp->pool = pools[i];
  4524. work_cp->do_foreign_submit = true;
  4525. _submit_work_async(work_cp);
  4526. }
  4527. }
  4528. #endif
  4529. }
  4530. static
  4531. json_t *extract_reject_reason_j(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4532. {
  4533. if (json_is_string(res))
  4534. return res;
  4535. if ( (res = json_object_get(val, "reject-reason")) )
  4536. return res;
  4537. if (work->stratum && err && json_is_array(err) && json_array_size(err) >= 2 && (res = json_array_get(err, 1)) && json_is_string(res))
  4538. return res;
  4539. return NULL;
  4540. }
  4541. static
  4542. const char *extract_reject_reason(json_t * const val, json_t *res, json_t * const err, const struct work * const work)
  4543. {
  4544. json_t * const j = extract_reject_reason_j(val, res, err, work);
  4545. return j ? json_string_value(j) : NULL;
  4546. }
  4547. static
  4548. int put_in_parens(char * const buf, const size_t bufsz, const char * const s)
  4549. {
  4550. if (!s)
  4551. {
  4552. if (bufsz)
  4553. buf[0] = '\0';
  4554. return 0;
  4555. }
  4556. int p = snprintf(buf, bufsz, " (%s", s);
  4557. if (p >= bufsz - 1)
  4558. p = bufsz - 2;
  4559. strcpy(&buf[p], ")");
  4560. return p + 1;
  4561. }
  4562. /* Theoretically threads could race when modifying accepted and
  4563. * rejected values but the chance of two submits completing at the
  4564. * same time is zero so there is no point adding extra locking */
  4565. static void
  4566. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  4567. /*char *hashshow,*/ bool resubmit, char *worktime)
  4568. {
  4569. struct pool *pool = work->pool;
  4570. struct cgpu_info *cgpu;
  4571. cgpu = get_thr_cgpu(work->thr_id);
  4572. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  4573. struct mining_goal_info * const goal = pool->goal;
  4574. mutex_lock(&stats_lock);
  4575. cgpu->accepted++;
  4576. total_accepted++;
  4577. pool->accepted++;
  4578. cgpu->diff_accepted += work->work_difficulty;
  4579. total_diff_accepted += work->work_difficulty;
  4580. pool->diff_accepted += work->work_difficulty;
  4581. goal->diff_accepted += work->work_difficulty;
  4582. mutex_unlock(&stats_lock);
  4583. pool->seq_rejects = 0;
  4584. cgpu->last_share_pool = pool->pool_no;
  4585. cgpu->last_share_pool_time = time(NULL);
  4586. cgpu->last_share_diff = work->work_difficulty;
  4587. pool->last_share_time = cgpu->last_share_pool_time;
  4588. pool->last_share_diff = work->work_difficulty;
  4589. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  4590. if (!QUIET) {
  4591. share_result_msg(work, "Accepted", "", resubmit, worktime);
  4592. }
  4593. sharelog("accept", work);
  4594. if (opt_shares && total_diff_accepted >= opt_shares) {
  4595. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  4596. kill_work();
  4597. return;
  4598. }
  4599. /* Detect if a pool that has been temporarily disabled for
  4600. * continually rejecting shares has started accepting shares.
  4601. * This will only happen with the work returned from a
  4602. * longpoll */
  4603. if (unlikely(pool->enabled == POOL_REJECTING)) {
  4604. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  4605. enable_pool(pool);
  4606. }
  4607. if (unlikely(work->block)) {
  4608. // Force moving on to this new block :)
  4609. struct work fakework;
  4610. memset(&fakework, 0, sizeof(fakework));
  4611. fakework.pool = work->pool;
  4612. // Copy block version, bits, and time from share
  4613. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4614. memcpy(&fakework.data[68], &work->data[68], 8);
  4615. // Set prevblock to winning hash (swap32'd)
  4616. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4617. test_work_current(&fakework);
  4618. }
  4619. }
  4620. else
  4621. if (!hash_target_check(work->hash, work->target))
  4622. {
  4623. // This was submitted despite failing the proper target
  4624. // Quietly ignore the reject
  4625. char reason[32];
  4626. put_in_parens(reason, sizeof(reason), extract_reject_reason(val, res, err, work));
  4627. applog(LOG_DEBUG, "Share above target rejected%s by pool %u as expected, ignoring", reason, pool->pool_no);
  4628. } else {
  4629. mutex_lock(&stats_lock);
  4630. cgpu->rejected++;
  4631. total_rejected++;
  4632. pool->rejected++;
  4633. cgpu->diff_rejected += work->work_difficulty;
  4634. total_diff_rejected += work->work_difficulty;
  4635. pool->diff_rejected += work->work_difficulty;
  4636. pool->seq_rejects++;
  4637. mutex_unlock(&stats_lock);
  4638. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4639. if (!QUIET) {
  4640. char disposition[36] = "reject";
  4641. char reason[32];
  4642. const char *reasontmp = extract_reject_reason(val, res, err, work);
  4643. int n = put_in_parens(reason, sizeof(reason), reasontmp);
  4644. if (reason[0])
  4645. snprintf(&disposition[6], sizeof(disposition) - 6, ":%.*s", n - 3, &reason[2]);
  4646. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4647. sharelog(disposition, work);
  4648. }
  4649. /* Once we have more than a nominal amount of sequential rejects,
  4650. * at least 10 and more than 3 mins at the current utility,
  4651. * disable the pool because some pool error is likely to have
  4652. * ensued. Do not do this if we know the share just happened to
  4653. * be stale due to networking delays.
  4654. */
  4655. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4656. double utility = total_accepted / total_secs * 60;
  4657. if (pool->seq_rejects > utility * 3) {
  4658. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4659. pool->pool_no, pool->seq_rejects);
  4660. disable_pool(pool, POOL_REJECTING);
  4661. pool->seq_rejects = 0;
  4662. }
  4663. }
  4664. }
  4665. maybe_local_submit(work);
  4666. }
  4667. static char *submit_upstream_work_request(struct work *work)
  4668. {
  4669. char *hexstr = NULL;
  4670. char *s, *sd;
  4671. struct pool *pool = work->pool;
  4672. if (work->tr)
  4673. {
  4674. blktemplate_t * const tmpl = work->tr->tmpl;
  4675. json_t *req;
  4676. unsigned char data[80];
  4677. swap32yes(data, work->data, 80 / 4);
  4678. #if BLKMAKER_VERSION > 3
  4679. if (work->do_foreign_submit)
  4680. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4681. else
  4682. #endif
  4683. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4684. s = json_dumps(req, 0);
  4685. json_decref(req);
  4686. sd = malloc(161);
  4687. bin2hex(sd, data, 80);
  4688. } else {
  4689. /* build hex string */
  4690. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4691. bin2hex(hexstr, work->data, sizeof(work->data));
  4692. /* build JSON-RPC request */
  4693. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4694. s = realloc_strcat(s, hexstr);
  4695. s = realloc_strcat(s, "\" ], \"id\":1}");
  4696. free(hexstr);
  4697. sd = s;
  4698. }
  4699. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4700. if (work->tr)
  4701. free(sd);
  4702. else
  4703. s = realloc_strcat(s, "\n");
  4704. return s;
  4705. }
  4706. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4707. json_t *res, *err;
  4708. bool rc = false;
  4709. int thr_id = work->thr_id;
  4710. struct pool *pool = work->pool;
  4711. struct timeval tv_submit_reply;
  4712. time_t ts_submit_reply;
  4713. char worktime[200] = "";
  4714. cgtime(&tv_submit_reply);
  4715. ts_submit_reply = time(NULL);
  4716. if (unlikely(!val)) {
  4717. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4718. if (!pool_tset(pool, &pool->submit_fail)) {
  4719. total_ro++;
  4720. pool->remotefail_occasions++;
  4721. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4722. }
  4723. goto out;
  4724. } else if (pool_tclear(pool, &pool->submit_fail))
  4725. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4726. res = json_object_get(val, "result");
  4727. err = json_object_get(val, "error");
  4728. if (!QUIET) {
  4729. if (opt_worktime) {
  4730. char workclone[20];
  4731. struct tm _tm;
  4732. struct tm *tm, tm_getwork, tm_submit_reply;
  4733. tm = &_tm;
  4734. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4735. (struct timeval *)&(work->tv_getwork));
  4736. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4737. (struct timeval *)&(work->tv_getwork_reply));
  4738. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4739. (struct timeval *)&(work->tv_work_start));
  4740. double work_to_submit = tdiff(ptv_submit,
  4741. (struct timeval *)&(work->tv_work_found));
  4742. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4743. int diffplaces = 3;
  4744. localtime_r(&work->ts_getwork, tm);
  4745. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4746. localtime_r(&ts_submit_reply, tm);
  4747. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4748. if (work->clone) {
  4749. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4750. tdiff((struct timeval *)&(work->tv_cloned),
  4751. (struct timeval *)&(work->tv_getwork_reply)));
  4752. }
  4753. else
  4754. strcpy(workclone, "O");
  4755. if (work->work_difficulty < 1)
  4756. diffplaces = 6;
  4757. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  4758. const uint8_t * const prevblkhash = &work->data[4];
  4759. snprintf(worktime, sizeof(worktime),
  4760. " <-%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",
  4761. (unsigned long)be32toh(((uint32_t *)prevblkhash)[7 - malgo->worktime_skip_prevblk_u32]),
  4762. (unsigned long)be32toh(((uint32_t *)prevblkhash)[6 - malgo->worktime_skip_prevblk_u32]),
  4763. work->getwork_mode, diffplaces, work->work_difficulty,
  4764. tm_getwork.tm_hour, tm_getwork.tm_min,
  4765. tm_getwork.tm_sec, getwork_time, workclone,
  4766. getwork_to_work, work_time, work_to_submit, submit_time,
  4767. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4768. tm_submit_reply.tm_sec);
  4769. }
  4770. }
  4771. share_result(val, res, err, work, resubmit, worktime);
  4772. if (!opt_realquiet)
  4773. print_status(thr_id);
  4774. if (!want_per_device_stats) {
  4775. char logline[256];
  4776. struct cgpu_info *cgpu;
  4777. cgpu = get_thr_cgpu(thr_id);
  4778. get_statline(logline, sizeof(logline), cgpu);
  4779. applog(LOG_INFO, "%s", logline);
  4780. }
  4781. json_decref(val);
  4782. rc = true;
  4783. out:
  4784. return rc;
  4785. }
  4786. /* Specifies whether we can use this pool for work or not. */
  4787. static bool pool_unworkable(const struct pool * const pool)
  4788. {
  4789. if (pool->idle)
  4790. return true;
  4791. if (pool->enabled != POOL_ENABLED)
  4792. return true;
  4793. if (pool->has_stratum && !pool->stratum_active)
  4794. return true;
  4795. return false;
  4796. }
  4797. static struct pool *priority_pool(int);
  4798. static bool pool_unusable(struct pool *);
  4799. static
  4800. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4801. {
  4802. if (pool->enabled != POOL_ENABLED)
  4803. return false;
  4804. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4805. return true;
  4806. if (!cp)
  4807. cp = current_pool();
  4808. if (pool == cp)
  4809. return true;
  4810. // If we are the highest priority, workable pool for a given algorithm, we are needed
  4811. struct mining_algorithm * const malgo = pool->goal->malgo;
  4812. for (int i = 0; i < total_pools; ++i)
  4813. {
  4814. struct pool * const other_pool = priority_pool(i);
  4815. if (other_pool == pool)
  4816. return true;
  4817. if (pool_unusable(other_pool))
  4818. continue;
  4819. if (other_pool->goal->malgo == malgo)
  4820. break;
  4821. }
  4822. return false;
  4823. }
  4824. static
  4825. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4826. {
  4827. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4828. }
  4829. static
  4830. bool pool_supports_block_change_notification(struct pool * const pool)
  4831. {
  4832. return pool->has_stratum || pool->lp_url;
  4833. }
  4834. static
  4835. bool pool_has_active_block_change_notification(struct pool * const pool)
  4836. {
  4837. return pool->stratum_active || pool->lp_active;
  4838. }
  4839. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4840. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4841. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4842. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4843. * rolling average per 10 minutes and if pools start getting more, it biases
  4844. * away from them to distribute work evenly. The share count is reset to the
  4845. * rolling average every 10 minutes to not send all work to one pool after it
  4846. * has been disabled/out for an extended period. */
  4847. static
  4848. struct pool *select_balanced(struct pool *cp, struct mining_algorithm * const malgo)
  4849. {
  4850. int i, lowest = cp->shares;
  4851. struct pool *ret = cp, *failover_pool = NULL;
  4852. for (i = 0; i < total_pools; i++) {
  4853. struct pool *pool = pools[i];
  4854. if (malgo && pool->goal->malgo != malgo)
  4855. continue;
  4856. if (pool_unworkable(pool))
  4857. continue;
  4858. if (pool->failover_only)
  4859. {
  4860. BFGINIT(failover_pool, pool);
  4861. continue;
  4862. }
  4863. if (pool->shares < lowest) {
  4864. lowest = pool->shares;
  4865. ret = pool;
  4866. }
  4867. }
  4868. if (malgo && ret->goal->malgo != malgo)
  4869. // Yes, we want failover_pool even if it's NULL
  4870. ret = failover_pool;
  4871. else
  4872. if (pool_unworkable(ret) && failover_pool)
  4873. ret = failover_pool;
  4874. if (ret)
  4875. ++ret->shares;
  4876. return ret;
  4877. }
  4878. static
  4879. struct pool *select_loadbalance(struct mining_algorithm * const malgo)
  4880. {
  4881. static int rotating_pool = 0;
  4882. struct pool *pool;
  4883. bool avail = false;
  4884. int tested, i, rpsave;
  4885. for (i = 0; i < total_pools; i++) {
  4886. struct pool *tp = pools[i];
  4887. if (tp->quota_used < tp->quota_gcd) {
  4888. avail = true;
  4889. break;
  4890. }
  4891. }
  4892. /* There are no pools with quota, so reset them. */
  4893. if (!avail) {
  4894. for (i = 0; i < total_pools; i++)
  4895. {
  4896. struct pool * const tp = pools[i];
  4897. tp->quota_used -= tp->quota_gcd;
  4898. }
  4899. if (++rotating_pool >= total_pools)
  4900. rotating_pool = 0;
  4901. }
  4902. /* Try to find the first pool in the rotation that is usable */
  4903. // Look for the lowest integer quota_used / quota_gcd in case we are imbalanced by algorithm demands
  4904. struct pool *pool_lowest = NULL;
  4905. int lowest = INT_MAX;
  4906. rpsave = rotating_pool;
  4907. for (tested = 0; tested < total_pools; ++tested)
  4908. {
  4909. pool = pools[rotating_pool];
  4910. if (malgo && pool->goal->malgo != malgo)
  4911. goto continue_tested;
  4912. if (pool->quota_used < pool->quota_gcd)
  4913. {
  4914. ++pool->quota_used;
  4915. if (!pool_unworkable(pool))
  4916. goto out;
  4917. /* Failover-only flag for load-balance means distribute
  4918. * unused quota to priority pool 0. */
  4919. if (opt_fail_only)
  4920. priority_pool(0)->quota_used--;
  4921. }
  4922. if (malgo)
  4923. {
  4924. const int count = pool->quota_used / pool->quota_gcd;
  4925. if (count < lowest)
  4926. {
  4927. pool_lowest = pool;
  4928. lowest = count;
  4929. }
  4930. }
  4931. continue_tested: ;
  4932. if (++rotating_pool >= total_pools)
  4933. rotating_pool = 0;
  4934. }
  4935. // Even if pool_lowest is NULL, we want to return that to indicate failure
  4936. // Note it isn't possible to get here if !malgo
  4937. pool = pool_lowest;
  4938. out: ;
  4939. // Restore rotating_pool static, so malgo searches don't affect the usual load balancing
  4940. if (malgo)
  4941. rotating_pool = rpsave;
  4942. return pool;
  4943. }
  4944. static
  4945. struct pool *select_failover(struct mining_algorithm * const malgo)
  4946. {
  4947. int i;
  4948. for (i = 0; i < total_pools; i++) {
  4949. struct pool *tp = priority_pool(i);
  4950. if (malgo && tp->goal->malgo != malgo)
  4951. continue;
  4952. if (!pool_unusable(tp)) {
  4953. return tp;
  4954. }
  4955. }
  4956. return NULL;
  4957. }
  4958. static bool pool_active(struct pool *, bool pinging);
  4959. static void pool_died(struct pool *);
  4960. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4961. * it has any quota left. */
  4962. static inline struct pool *select_pool(bool lagging, struct mining_algorithm * const malgo)
  4963. {
  4964. struct pool *pool = NULL, *cp;
  4965. retry:
  4966. cp = current_pool();
  4967. if (pool_strategy == POOL_BALANCE) {
  4968. pool = select_balanced(cp, malgo);
  4969. if ((!pool) || pool_unworkable(pool))
  4970. goto simple_failover;
  4971. goto out;
  4972. }
  4973. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4974. if (malgo && cp->goal->malgo != malgo)
  4975. goto simple_failover;
  4976. pool = cp;
  4977. goto out;
  4978. } else
  4979. pool = select_loadbalance(malgo);
  4980. simple_failover:
  4981. /* If there are no alive pools with quota, choose according to
  4982. * priority. */
  4983. if (!pool) {
  4984. pool = select_failover(malgo);
  4985. }
  4986. /* If still nothing is usable, use the current pool */
  4987. if (!pool)
  4988. {
  4989. if (malgo && cp->goal->malgo != malgo)
  4990. {
  4991. applog(LOG_DEBUG, "Failed to select pool for specific mining algorithm '%s'", malgo->name);
  4992. return NULL;
  4993. }
  4994. pool = cp;
  4995. }
  4996. out:
  4997. if (!pool_actively_in_use(pool, cp))
  4998. {
  4999. if (!pool_active(pool, false))
  5000. {
  5001. pool_died(pool);
  5002. goto retry;
  5003. }
  5004. pool_tclear(pool, &pool->idle);
  5005. }
  5006. applog(LOG_DEBUG, "Selecting pool %d for %s%swork", pool->pool_no, malgo ? malgo->name : "", malgo ? " " : "");
  5007. return pool;
  5008. }
  5009. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  5010. double target_diff(const unsigned char *target)
  5011. {
  5012. double targ = 0;
  5013. signed int i;
  5014. for (i = 31; i >= 0; --i)
  5015. targ = (targ * 0x100) + target[i];
  5016. return DIFFEXACTONE / (targ ?: 1);
  5017. }
  5018. /*
  5019. * Calculate the work share difficulty
  5020. */
  5021. static void calc_diff(struct work *work, int known)
  5022. {
  5023. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  5024. double difficulty;
  5025. if (!known) {
  5026. work->work_difficulty = target_diff(work->target);
  5027. } else
  5028. work->work_difficulty = known;
  5029. difficulty = work->work_difficulty;
  5030. pool_stats->last_diff = difficulty;
  5031. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  5032. if (difficulty == pool_stats->min_diff)
  5033. pool_stats->min_diff_count++;
  5034. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  5035. pool_stats->min_diff = difficulty;
  5036. pool_stats->min_diff_count = 1;
  5037. }
  5038. if (difficulty == pool_stats->max_diff)
  5039. pool_stats->max_diff_count++;
  5040. else if (difficulty > pool_stats->max_diff) {
  5041. pool_stats->max_diff = difficulty;
  5042. pool_stats->max_diff_count = 1;
  5043. }
  5044. }
  5045. static void gen_stratum_work(struct pool *, struct work *);
  5046. static void pool_update_work_restart_time(struct pool *);
  5047. static void restart_threads(void);
  5048. static uint32_t benchmark_blkhdr[20];
  5049. static const int benchmark_update_interval = 1;
  5050. static
  5051. void *benchmark_intense_work_update_thread(void *userp)
  5052. {
  5053. pthread_detach(pthread_self());
  5054. RenameThread("benchmark-intense");
  5055. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5056. struct pool * const pool = userp;
  5057. struct stratum_work * const swork = &pool->swork;
  5058. uint8_t * const blkhdr = swork->header1;
  5059. while (true)
  5060. {
  5061. sleep(benchmark_update_interval);
  5062. cg_wlock(&pool->data_lock);
  5063. for (int i = 36; --i >= 0; )
  5064. if (++blkhdr[i])
  5065. break;
  5066. cg_wunlock(&pool->data_lock);
  5067. struct work *work = make_work();
  5068. gen_stratum_work(pool, work);
  5069. pool->swork.work_restart_id = ++pool->work_restart_id;
  5070. pool_update_work_restart_time(pool);
  5071. test_work_current(work);
  5072. free_work(work);
  5073. restart_threads();
  5074. }
  5075. return NULL;
  5076. }
  5077. static
  5078. void setup_benchmark_pool()
  5079. {
  5080. struct pool *pool;
  5081. want_longpoll = false;
  5082. // Temporarily disable opt_benchmark to avoid auto-removal
  5083. opt_benchmark = false;
  5084. pool = add_pool();
  5085. opt_benchmark = true;
  5086. pool->rpc_url = malloc(255);
  5087. strcpy(pool->rpc_url, "Benchmark");
  5088. pool_set_uri(pool, pool->rpc_url);
  5089. pool->rpc_user = pool->rpc_url;
  5090. pool->rpc_pass = pool->rpc_url;
  5091. enable_pool(pool);
  5092. pool->idle = false;
  5093. successful_connect = true;
  5094. {
  5095. uint32_t * const blkhdr = benchmark_blkhdr;
  5096. blkhdr[2] = htobe32(1);
  5097. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  5098. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  5099. }
  5100. {
  5101. struct stratum_work * const swork = &pool->swork;
  5102. const int branchcount = 15; // 1 MB block
  5103. const size_t branchdatasz = branchcount * 0x20;
  5104. const size_t coinbase_sz = (opt_benchmark_intense ? 250 : 6) * 1024;
  5105. bytes_resize(&swork->coinbase, coinbase_sz);
  5106. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  5107. swork->nonce2_offset = 0;
  5108. bytes_resize(&swork->merkle_bin, branchdatasz);
  5109. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  5110. swork->merkles = branchcount;
  5111. swork->header1[0] = '\xff';
  5112. memset(&swork->header1[1], '\0', 34);
  5113. swork->header1[35] = '\x01';
  5114. swork->ntime = 0x7fffffff;
  5115. timer_unset(&swork->tv_received);
  5116. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  5117. const struct mining_goal_info * const goal = get_mining_goal("default");
  5118. const struct mining_algorithm * const malgo = goal->malgo;
  5119. set_target_to_pdiff(swork->target, malgo->reasonable_low_nonce_diff);
  5120. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  5121. pool->nonce2 = 0;
  5122. }
  5123. if (opt_benchmark_intense)
  5124. {
  5125. pthread_t pth;
  5126. if (unlikely(pthread_create(&pth, NULL, benchmark_intense_work_update_thread, pool)))
  5127. applog(LOG_WARNING, "Failed to start benchmark intense work update thread");
  5128. }
  5129. }
  5130. void get_benchmark_work(struct work *work, bool use_swork)
  5131. {
  5132. if (use_swork)
  5133. {
  5134. struct timeval tv_now;
  5135. timer_set_now(&tv_now);
  5136. gen_stratum_work(pools[0], work);
  5137. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5138. work_set_simple_ntime_roll_limit(work, 0, &tv_now);
  5139. return;
  5140. }
  5141. struct pool * const pool = pools[0];
  5142. uint32_t * const blkhdr = benchmark_blkhdr;
  5143. for (int i = 16; i >= 0; --i)
  5144. if (++blkhdr[i])
  5145. break;
  5146. memcpy(&work->data[ 0], blkhdr, 80);
  5147. memcpy(&work->data[80], workpadding_bin, 48);
  5148. char hex[161];
  5149. bin2hex(hex, work->data, 80);
  5150. applog(LOG_DEBUG, "Generated benchmark header %s", hex);
  5151. calc_midstate(work);
  5152. memcpy(work->target, pool->swork.target, sizeof(work->target));
  5153. work->mandatory = true;
  5154. work->pool = pools[0];
  5155. cgtime(&work->tv_getwork);
  5156. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  5157. copy_time(&work->tv_staged, &work->tv_getwork);
  5158. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  5159. calc_diff(work, 0);
  5160. work_set_simple_ntime_roll_limit(work, 60, &work->tv_getwork);
  5161. }
  5162. static void wake_gws(void);
  5163. static void update_last_work(struct work *work)
  5164. {
  5165. if (!work->tr)
  5166. // Only save GBT jobs, since rollntime isn't coordinated well yet
  5167. return;
  5168. struct pool *pool = work->pool;
  5169. mutex_lock(&pool->last_work_lock);
  5170. if (pool->last_work_copy)
  5171. free_work(pool->last_work_copy);
  5172. pool->last_work_copy = copy_work(work);
  5173. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  5174. mutex_unlock(&pool->last_work_lock);
  5175. }
  5176. static
  5177. void gbt_req_target(json_t *req)
  5178. {
  5179. json_t *j;
  5180. json_t *n;
  5181. if (!request_target_str)
  5182. return;
  5183. j = json_object_get(req, "params");
  5184. if (!j)
  5185. {
  5186. n = json_array();
  5187. if (!n)
  5188. return;
  5189. if (json_object_set_new(req, "params", n))
  5190. goto erradd;
  5191. j = n;
  5192. }
  5193. n = json_array_get(j, 0);
  5194. if (!n)
  5195. {
  5196. n = json_object();
  5197. if (!n)
  5198. return;
  5199. if (json_array_append_new(j, n))
  5200. goto erradd;
  5201. }
  5202. j = n;
  5203. n = json_string(request_target_str);
  5204. if (!n)
  5205. return;
  5206. if (json_object_set_new(j, "target", n))
  5207. goto erradd;
  5208. return;
  5209. erradd:
  5210. json_decref(n);
  5211. }
  5212. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe, struct pool * const pool)
  5213. {
  5214. char *rpc_req;
  5215. clean_work(work);
  5216. switch (proto) {
  5217. case PLP_GETWORK:
  5218. work->getwork_mode = GETWORK_MODE_POOL;
  5219. return strdup(getwork_req);
  5220. case PLP_GETBLOCKTEMPLATE:
  5221. work->getwork_mode = GETWORK_MODE_GBT;
  5222. blktemplate_t * const tmpl = blktmpl_create();
  5223. if (!tmpl)
  5224. goto gbtfail2;
  5225. work->tr = tmpl_makeref(tmpl);
  5226. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  5227. if (!caps)
  5228. goto gbtfail;
  5229. caps |= GBT_LONGPOLL;
  5230. #if BLKMAKER_VERSION > 1
  5231. const struct mining_goal_info * const goal = pool->goal;
  5232. if (goal->generation_script || goal_has_at_least_one_getcbaddr(goal))
  5233. caps |= GBT_CBVALUE;
  5234. #endif
  5235. json_t *req = blktmpl_request_jansson(caps, lpid);
  5236. if (!req)
  5237. goto gbtfail;
  5238. if (probe)
  5239. gbt_req_target(req);
  5240. rpc_req = json_dumps(req, 0);
  5241. if (!rpc_req)
  5242. goto gbtfail;
  5243. json_decref(req);
  5244. return rpc_req;
  5245. default:
  5246. return NULL;
  5247. }
  5248. return NULL;
  5249. gbtfail:
  5250. tmpl_decref(work->tr);
  5251. work->tr = NULL;
  5252. gbtfail2:
  5253. return NULL;
  5254. }
  5255. #define prepare_rpc_req(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, false, pool)
  5256. #define prepare_rpc_req_probe(work, proto, lpid, pool) prepare_rpc_req2(work, proto, lpid, true, pool)
  5257. static const char *pool_protocol_name(enum pool_protocol proto)
  5258. {
  5259. switch (proto) {
  5260. case PLP_GETBLOCKTEMPLATE:
  5261. return "getblocktemplate";
  5262. case PLP_GETWORK:
  5263. return "getwork";
  5264. default:
  5265. return "UNKNOWN";
  5266. }
  5267. }
  5268. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  5269. {
  5270. switch (proto) {
  5271. case PLP_GETBLOCKTEMPLATE:
  5272. if (want_getwork)
  5273. return PLP_GETWORK;
  5274. default:
  5275. return PLP_NONE;
  5276. }
  5277. }
  5278. static bool get_upstream_work(struct work *work, CURL *curl)
  5279. {
  5280. struct pool *pool = work->pool;
  5281. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  5282. struct timeval tv_elapsed;
  5283. json_t *val = NULL;
  5284. bool rc = false;
  5285. char *url;
  5286. enum pool_protocol proto;
  5287. char *rpc_req;
  5288. if (pool->proto == PLP_NONE)
  5289. pool->proto = PLP_GETBLOCKTEMPLATE;
  5290. tryagain:
  5291. rpc_req = prepare_rpc_req(work, pool->proto, NULL, pool);
  5292. work->pool = pool;
  5293. if (!rpc_req)
  5294. return false;
  5295. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  5296. url = pool->rpc_url;
  5297. cgtime(&work->tv_getwork);
  5298. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  5299. false, &work->rolltime, pool, false);
  5300. pool_stats->getwork_attempts++;
  5301. free(rpc_req);
  5302. if (likely(val)) {
  5303. rc = work_decode(pool, work, val);
  5304. if (unlikely(!rc))
  5305. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  5306. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  5307. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  5308. pool->proto = proto;
  5309. goto tryagain;
  5310. } else
  5311. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  5312. cgtime(&work->tv_getwork_reply);
  5313. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  5314. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  5315. pool_stats->getwork_wait_rolling /= 1.63;
  5316. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  5317. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  5318. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  5319. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  5320. }
  5321. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  5322. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  5323. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  5324. }
  5325. pool_stats->getwork_calls++;
  5326. work->pool = pool;
  5327. work->longpoll = false;
  5328. calc_diff(work, 0);
  5329. total_getworks++;
  5330. pool->getwork_requested++;
  5331. if (rc)
  5332. update_last_work(work);
  5333. if (likely(val))
  5334. json_decref(val);
  5335. return rc;
  5336. }
  5337. #ifdef HAVE_CURSES
  5338. static void disable_curses(void)
  5339. {
  5340. if (curses_active_locked()) {
  5341. use_curses = false;
  5342. curses_active = false;
  5343. leaveok(logwin, false);
  5344. leaveok(statuswin, false);
  5345. leaveok(mainwin, false);
  5346. nocbreak();
  5347. echo();
  5348. delwin(logwin);
  5349. delwin(statuswin);
  5350. delwin(mainwin);
  5351. endwin();
  5352. #ifdef WIN32
  5353. // Move the cursor to after curses output.
  5354. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  5355. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5356. COORD coord;
  5357. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  5358. coord.X = 0;
  5359. coord.Y = csbi.dwSize.Y - 1;
  5360. SetConsoleCursorPosition(hout, coord);
  5361. }
  5362. #endif
  5363. unlock_curses();
  5364. }
  5365. }
  5366. #endif
  5367. static void __kill_work(void)
  5368. {
  5369. struct cgpu_info *cgpu;
  5370. struct thr_info *thr;
  5371. int i;
  5372. if (!successful_connect)
  5373. return;
  5374. applog(LOG_INFO, "Received kill message");
  5375. shutting_down = true;
  5376. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  5377. notifier_wake(submit_waiting_notifier);
  5378. #ifdef USE_LIBMICROHTTPD
  5379. httpsrv_stop();
  5380. #endif
  5381. applog(LOG_DEBUG, "Killing off watchpool thread");
  5382. /* Kill the watchpool thread */
  5383. thr = &control_thr[watchpool_thr_id];
  5384. thr_info_cancel(thr);
  5385. applog(LOG_DEBUG, "Killing off watchdog thread");
  5386. /* Kill the watchdog thread */
  5387. thr = &control_thr[watchdog_thr_id];
  5388. thr_info_cancel(thr);
  5389. applog(LOG_DEBUG, "Shutting down mining threads");
  5390. for (i = 0; i < mining_threads; i++) {
  5391. thr = get_thread(i);
  5392. if (!thr)
  5393. continue;
  5394. cgpu = thr->cgpu;
  5395. if (!cgpu)
  5396. continue;
  5397. if (!cgpu->threads)
  5398. continue;
  5399. cgpu->shutdown = true;
  5400. thr->work_restart = true;
  5401. notifier_wake(thr->notifier);
  5402. notifier_wake(thr->work_restart_notifier);
  5403. }
  5404. sleep(1);
  5405. applog(LOG_DEBUG, "Killing off mining threads");
  5406. /* Kill the mining threads*/
  5407. for (i = 0; i < mining_threads; i++) {
  5408. thr = get_thread(i);
  5409. if (!thr)
  5410. continue;
  5411. cgpu = thr->cgpu;
  5412. if (cgpu->threads)
  5413. {
  5414. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  5415. thr_info_cancel(thr);
  5416. }
  5417. cgpu->status = LIFE_DEAD2;
  5418. }
  5419. /* Stop the others */
  5420. applog(LOG_DEBUG, "Killing off API thread");
  5421. thr = &control_thr[api_thr_id];
  5422. thr_info_cancel(thr);
  5423. }
  5424. /* This should be the common exit path */
  5425. void kill_work(void)
  5426. {
  5427. __kill_work();
  5428. quit(0, "Shutdown signal received.");
  5429. }
  5430. static
  5431. #ifdef WIN32
  5432. #ifndef _WIN64
  5433. const
  5434. #endif
  5435. #endif
  5436. char **initial_args;
  5437. void _bfg_clean_up(bool);
  5438. void app_restart(void)
  5439. {
  5440. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  5441. __kill_work();
  5442. _bfg_clean_up(true);
  5443. #if defined(unix) || defined(__APPLE__)
  5444. if (forkpid > 0) {
  5445. kill(forkpid, SIGTERM);
  5446. forkpid = 0;
  5447. }
  5448. #endif
  5449. execv(initial_args[0], initial_args);
  5450. applog(LOG_WARNING, "Failed to restart application");
  5451. }
  5452. static void sighandler(int __maybe_unused sig)
  5453. {
  5454. /* Restore signal handlers so we can still quit if kill_work fails */
  5455. sigaction(SIGTERM, &termhandler, NULL);
  5456. sigaction(SIGINT, &inthandler, NULL);
  5457. kill_work();
  5458. }
  5459. static void start_longpoll(void);
  5460. static void stop_longpoll(void);
  5461. /* Called with pool_lock held. Recruit an extra curl if none are available for
  5462. * this pool. */
  5463. static void recruit_curl(struct pool *pool)
  5464. {
  5465. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  5466. if (unlikely(!ce))
  5467. quit(1, "Failed to calloc in recruit_curl");
  5468. ce->curl = curl_easy_init();
  5469. if (unlikely(!ce->curl))
  5470. quit(1, "Failed to init in recruit_curl");
  5471. LL_PREPEND(pool->curllist, ce);
  5472. pool->curls++;
  5473. }
  5474. /* Grab an available curl if there is one. If not, then recruit extra curls
  5475. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  5476. * and there are already 5 curls in circulation. Limit total number to the
  5477. * number of mining threads per pool as well to prevent blasting a pool during
  5478. * network delays/outages. */
  5479. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  5480. {
  5481. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  5482. bool recruited = false;
  5483. struct curl_ent *ce;
  5484. mutex_lock(&pool->pool_lock);
  5485. retry:
  5486. if (!pool->curls) {
  5487. recruit_curl(pool);
  5488. recruited = true;
  5489. } else if (!pool->curllist) {
  5490. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  5491. if (!blocking) {
  5492. mutex_unlock(&pool->pool_lock);
  5493. return NULL;
  5494. }
  5495. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  5496. goto retry;
  5497. } else {
  5498. recruit_curl(pool);
  5499. recruited = true;
  5500. }
  5501. }
  5502. ce = pool->curllist;
  5503. LL_DELETE(pool->curllist, ce);
  5504. mutex_unlock(&pool->pool_lock);
  5505. if (recruited)
  5506. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  5507. return ce;
  5508. }
  5509. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  5510. {
  5511. return pop_curl_entry3(pool, blocking ? 1 : 0);
  5512. }
  5513. __maybe_unused
  5514. static struct curl_ent *pop_curl_entry(struct pool *pool)
  5515. {
  5516. return pop_curl_entry3(pool, 1);
  5517. }
  5518. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  5519. {
  5520. mutex_lock(&pool->pool_lock);
  5521. if (!ce || !ce->curl)
  5522. quithere(1, "Attempted to add NULL");
  5523. LL_PREPEND(pool->curllist, ce);
  5524. cgtime(&ce->tv);
  5525. pthread_cond_broadcast(&pool->cr_cond);
  5526. mutex_unlock(&pool->pool_lock);
  5527. }
  5528. bool stale_work(struct work *work, bool share);
  5529. static inline bool should_roll(struct work *work)
  5530. {
  5531. struct timeval now;
  5532. time_t expiry;
  5533. if (!pool_actively_in_use(work->pool, NULL))
  5534. return false;
  5535. if (stale_work(work, false))
  5536. return false;
  5537. if (work->rolltime > opt_scantime)
  5538. expiry = work->rolltime;
  5539. else
  5540. expiry = opt_scantime;
  5541. expiry = expiry * 2 / 3;
  5542. /* We shouldn't roll if we're unlikely to get one shares' duration
  5543. * work out of doing so */
  5544. cgtime(&now);
  5545. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  5546. return false;
  5547. return true;
  5548. }
  5549. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  5550. * reject blocks as invalid. */
  5551. static inline bool can_roll(struct work *work)
  5552. {
  5553. if (work->stratum)
  5554. return false;
  5555. if (!(work->pool && !work->clone))
  5556. return false;
  5557. if (work->tr)
  5558. {
  5559. if (stale_work(work, false))
  5560. return false;
  5561. return blkmk_work_left(work->tr->tmpl);
  5562. }
  5563. return (work->rolltime &&
  5564. work->rolls < 7000 && !stale_work(work, false));
  5565. }
  5566. static void roll_work(struct work *work)
  5567. {
  5568. if (work->tr)
  5569. {
  5570. struct timeval tv_now;
  5571. cgtime(&tv_now);
  5572. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  5573. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  5574. swap32yes(work->data, work->data, 80 / 4);
  5575. calc_midstate(work);
  5576. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  5577. } else {
  5578. uint32_t *work_ntime;
  5579. uint32_t ntime;
  5580. work_ntime = (uint32_t *)(work->data + 68);
  5581. ntime = be32toh(*work_ntime);
  5582. ntime++;
  5583. *work_ntime = htobe32(ntime);
  5584. work_set_simple_ntime_roll_limit(work, 0, &work->ntime_roll_limits.tv_ref);
  5585. applog(LOG_DEBUG, "Successfully rolled time header in work");
  5586. }
  5587. local_work++;
  5588. work->rolls++;
  5589. work->blk.nonce = 0;
  5590. /* This is now a different work item so it needs a different ID for the
  5591. * hashtable */
  5592. work->id = total_work++;
  5593. }
  5594. /* Duplicates any dynamically allocated arrays within the work struct to
  5595. * prevent a copied work struct from freeing ram belonging to another struct */
  5596. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  5597. {
  5598. int id = work->id;
  5599. clean_work(work);
  5600. memcpy(work, base_work, sizeof(struct work));
  5601. /* Keep the unique new id assigned during make_work to prevent copied
  5602. * work from having the same id. */
  5603. work->id = id;
  5604. if (base_work->job_id)
  5605. work->job_id = strdup(base_work->job_id);
  5606. if (base_work->nonce1)
  5607. work->nonce1 = strdup(base_work->nonce1);
  5608. bytes_cpy(&work->nonce2, &base_work->nonce2);
  5609. if (base_work->tr)
  5610. tmpl_incref(base_work->tr);
  5611. if (noffset)
  5612. {
  5613. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  5614. uint32_t ntime = be32toh(*work_ntime);
  5615. ntime += noffset;
  5616. *work_ntime = htobe32(ntime);
  5617. }
  5618. if (work->device_data_dup_func)
  5619. work->device_data = work->device_data_dup_func(work);
  5620. }
  5621. /* Generates a copy of an existing work struct, creating fresh heap allocations
  5622. * for all dynamically allocated arrays within the struct. noffset is used for
  5623. * when a driver has internally rolled the ntime, noffset is a relative value.
  5624. * The macro copy_work() calls this function with an noffset of 0. */
  5625. struct work *copy_work_noffset(const struct work *base_work, int noffset)
  5626. {
  5627. struct work *work = make_work();
  5628. _copy_work(work, base_work, noffset);
  5629. return work;
  5630. }
  5631. void __copy_work(struct work *work, const struct work *base_work)
  5632. {
  5633. _copy_work(work, base_work, 0);
  5634. }
  5635. static struct work *make_clone(struct work *work)
  5636. {
  5637. struct work *work_clone = copy_work(work);
  5638. work_clone->clone = true;
  5639. cgtime((struct timeval *)&(work_clone->tv_cloned));
  5640. work_clone->longpoll = false;
  5641. work_clone->mandatory = false;
  5642. /* Make cloned work appear slightly older to bias towards keeping the
  5643. * master work item which can be further rolled */
  5644. work_clone->tv_staged.tv_sec -= 1;
  5645. return work_clone;
  5646. }
  5647. static void stage_work(struct work *work);
  5648. static bool clone_available(void)
  5649. {
  5650. struct work *work_clone = NULL, *work, *tmp;
  5651. bool cloned = false;
  5652. mutex_lock(stgd_lock);
  5653. if (!staged_rollable)
  5654. goto out_unlock;
  5655. HASH_ITER(hh, staged_work, work, tmp) {
  5656. if (can_roll(work) && should_roll(work)) {
  5657. roll_work(work);
  5658. work_clone = make_clone(work);
  5659. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  5660. roll_work(work);
  5661. cloned = true;
  5662. break;
  5663. }
  5664. }
  5665. out_unlock:
  5666. mutex_unlock(stgd_lock);
  5667. if (cloned) {
  5668. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  5669. stage_work(work_clone);
  5670. }
  5671. return cloned;
  5672. }
  5673. static void pool_died(struct pool *pool)
  5674. {
  5675. mutex_lock(&lp_lock);
  5676. if (!pool_tset(pool, &pool->idle)) {
  5677. cgtime(&pool->tv_idle);
  5678. pthread_cond_broadcast(&lp_cond);
  5679. mutex_unlock(&lp_lock);
  5680. if (pool == current_pool()) {
  5681. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  5682. switch_pools(NULL);
  5683. } else
  5684. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  5685. }
  5686. else
  5687. mutex_unlock(&lp_lock);
  5688. }
  5689. bool stale_work(struct work *work, bool share)
  5690. {
  5691. unsigned work_expiry;
  5692. struct pool *pool;
  5693. uint32_t block_id;
  5694. unsigned getwork_delay;
  5695. block_id = ((uint32_t*)work->data)[1];
  5696. pool = work->pool;
  5697. struct mining_goal_info * const goal = pool->goal;
  5698. struct blockchain_info * const blkchain = goal->blkchain;
  5699. /* Technically the rolltime should be correct but some pools
  5700. * advertise a broken expire= that is lower than a meaningful
  5701. * scantime */
  5702. if (work->rolltime >= opt_scantime || work->tr)
  5703. work_expiry = work->rolltime;
  5704. else
  5705. work_expiry = opt_expiry;
  5706. unsigned max_expiry = (goal->have_longpoll ? opt_expiry_lp : opt_expiry);
  5707. if (work_expiry > max_expiry)
  5708. work_expiry = max_expiry;
  5709. if (share) {
  5710. /* If the share isn't on this pool's latest block, it's stale */
  5711. if (pool->block_id && pool->block_id != block_id)
  5712. {
  5713. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  5714. return true;
  5715. }
  5716. /* If the pool doesn't want old shares, then any found in work before
  5717. * the most recent longpoll is stale */
  5718. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  5719. {
  5720. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5721. return true;
  5722. }
  5723. } else {
  5724. /* If this work isn't for the latest Bitcoin block, it's stale */
  5725. /* But only care about the current pool if failover-only */
  5726. if (enabled_pools <= 1 || opt_fail_only) {
  5727. if (pool->block_id && block_id != pool->block_id)
  5728. {
  5729. 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);
  5730. return true;
  5731. }
  5732. } else {
  5733. if (block_id != blkchain->currentblk->block_id)
  5734. {
  5735. 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);
  5736. return true;
  5737. }
  5738. }
  5739. /* If the pool has asked us to restart since this work, it's stale */
  5740. if (work->work_restart_id != pool->work_restart_id)
  5741. {
  5742. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5743. return true;
  5744. }
  5745. if (pool->has_stratum && work->job_id) {
  5746. bool same_job;
  5747. if (!pool->stratum_active || !pool->stratum_notify) {
  5748. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5749. return true;
  5750. }
  5751. same_job = true;
  5752. cg_rlock(&pool->data_lock);
  5753. if (strcmp(work->job_id, pool->swork.job_id))
  5754. same_job = false;
  5755. cg_runlock(&pool->data_lock);
  5756. if (!same_job) {
  5757. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5758. return true;
  5759. }
  5760. }
  5761. /* Factor in the average getwork delay of this pool, rounding it up to
  5762. * the nearest second */
  5763. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5764. if (unlikely(work_expiry <= getwork_delay + 5))
  5765. work_expiry = 5;
  5766. else
  5767. work_expiry -= getwork_delay;
  5768. }
  5769. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5770. if (elapsed_since_staged > work_expiry) {
  5771. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5772. return true;
  5773. }
  5774. /* If the user only wants strict failover, any work from a pool other than
  5775. * the current one is always considered stale */
  5776. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5777. {
  5778. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5779. return true;
  5780. }
  5781. return false;
  5782. }
  5783. double share_diff(const struct work *work)
  5784. {
  5785. double ret;
  5786. bool new_best = false;
  5787. ret = target_diff(work->hash);
  5788. cg_wlock(&control_lock);
  5789. if (unlikely(ret > best_diff)) {
  5790. new_best = true;
  5791. best_diff = ret;
  5792. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5793. }
  5794. if (unlikely(ret > work->pool->best_diff))
  5795. work->pool->best_diff = ret;
  5796. cg_wunlock(&control_lock);
  5797. if (unlikely(new_best))
  5798. applog(LOG_INFO, "New best share: %s", best_share);
  5799. return ret;
  5800. }
  5801. static
  5802. void work_check_for_block(struct work * const work)
  5803. {
  5804. struct pool * const pool = work->pool;
  5805. struct mining_goal_info * const goal = pool->goal;
  5806. work->share_diff = share_diff(work);
  5807. if (unlikely(work->share_diff >= goal->current_diff)) {
  5808. work->block = true;
  5809. work->pool->solved++;
  5810. found_blocks++;
  5811. work->mandatory = true;
  5812. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5813. }
  5814. }
  5815. static void submit_discard_share2(const char *reason, struct work *work)
  5816. {
  5817. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5818. sharelog(reason, work);
  5819. mutex_lock(&stats_lock);
  5820. ++total_stale;
  5821. ++cgpu->stale;
  5822. ++(work->pool->stale_shares);
  5823. total_diff_stale += work->work_difficulty;
  5824. cgpu->diff_stale += work->work_difficulty;
  5825. work->pool->diff_stale += work->work_difficulty;
  5826. mutex_unlock(&stats_lock);
  5827. }
  5828. static void submit_discard_share(struct work *work)
  5829. {
  5830. submit_discard_share2("discard", work);
  5831. }
  5832. struct submit_work_state {
  5833. struct work *work;
  5834. bool resubmit;
  5835. struct curl_ent *ce;
  5836. int failures;
  5837. struct timeval tv_staleexpire;
  5838. char *s;
  5839. struct timeval tv_submit;
  5840. struct submit_work_state *next;
  5841. };
  5842. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5843. {
  5844. long *p_timeout_us = userp;
  5845. const long max_ms = LONG_MAX / 1000;
  5846. if (max_ms < timeout_ms)
  5847. timeout_ms = max_ms;
  5848. *p_timeout_us = timeout_ms * 1000;
  5849. return 0;
  5850. }
  5851. static void sws_has_ce(struct submit_work_state *sws)
  5852. {
  5853. struct pool *pool = sws->work->pool;
  5854. sws->s = submit_upstream_work_request(sws->work);
  5855. cgtime(&sws->tv_submit);
  5856. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5857. }
  5858. static struct submit_work_state *begin_submission(struct work *work)
  5859. {
  5860. struct pool *pool;
  5861. struct submit_work_state *sws = NULL;
  5862. pool = work->pool;
  5863. sws = malloc(sizeof(*sws));
  5864. *sws = (struct submit_work_state){
  5865. .work = work,
  5866. };
  5867. work_check_for_block(work);
  5868. if (stale_work(work, true)) {
  5869. work->stale = true;
  5870. if (opt_submit_stale)
  5871. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5872. else if (pool->submit_old)
  5873. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5874. else {
  5875. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5876. submit_discard_share(work);
  5877. goto out;
  5878. }
  5879. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5880. }
  5881. if (work->stratum) {
  5882. char *s;
  5883. s = malloc(1024);
  5884. sws->s = s;
  5885. } else {
  5886. /* submit solution to bitcoin via JSON-RPC */
  5887. sws->ce = pop_curl_entry2(pool, false);
  5888. if (sws->ce) {
  5889. sws_has_ce(sws);
  5890. } else {
  5891. sws->next = pool->sws_waiting_on_curl;
  5892. pool->sws_waiting_on_curl = sws;
  5893. if (sws->next)
  5894. applog(LOG_DEBUG, "submit_thread queuing submission");
  5895. else
  5896. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5897. }
  5898. }
  5899. return sws;
  5900. out:
  5901. free(sws);
  5902. return NULL;
  5903. }
  5904. static bool retry_submission(struct submit_work_state *sws)
  5905. {
  5906. struct work *work = sws->work;
  5907. struct pool *pool = work->pool;
  5908. sws->resubmit = true;
  5909. if ((!work->stale) && stale_work(work, true)) {
  5910. work->stale = true;
  5911. if (opt_submit_stale)
  5912. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5913. else if (pool->submit_old)
  5914. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5915. else {
  5916. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5917. submit_discard_share(work);
  5918. return false;
  5919. }
  5920. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5921. }
  5922. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5923. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5924. submit_discard_share(work);
  5925. return false;
  5926. }
  5927. else if (work->stale) {
  5928. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5929. {
  5930. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5931. submit_discard_share(work);
  5932. return false;
  5933. }
  5934. }
  5935. /* pause, then restart work-request loop */
  5936. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5937. cgtime(&sws->tv_submit);
  5938. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5939. return true;
  5940. }
  5941. static void free_sws(struct submit_work_state *sws)
  5942. {
  5943. free(sws->s);
  5944. free_work(sws->work);
  5945. free(sws);
  5946. }
  5947. static void *submit_work_thread(__maybe_unused void *userdata)
  5948. {
  5949. int wip = 0;
  5950. CURLM *curlm;
  5951. long curlm_timeout_us = -1;
  5952. struct timeval curlm_timer;
  5953. struct submit_work_state *sws, **swsp;
  5954. struct submit_work_state *write_sws = NULL;
  5955. unsigned tsreduce = 0;
  5956. pthread_detach(pthread_self());
  5957. RenameThread("submit_work");
  5958. applog(LOG_DEBUG, "Creating extra submit work thread");
  5959. curlm = curl_multi_init();
  5960. curlm_timeout_us = -1;
  5961. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5962. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5963. fd_set rfds, wfds, efds;
  5964. int maxfd;
  5965. struct timeval tv_timeout, tv_now;
  5966. int n;
  5967. CURLMsg *cm;
  5968. FD_ZERO(&rfds);
  5969. while (1) {
  5970. mutex_lock(&submitting_lock);
  5971. total_submitting -= tsreduce;
  5972. tsreduce = 0;
  5973. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5974. notifier_read(submit_waiting_notifier);
  5975. }
  5976. // Receive any new submissions
  5977. while (submit_waiting) {
  5978. struct work *work = submit_waiting;
  5979. DL_DELETE(submit_waiting, work);
  5980. if ( (sws = begin_submission(work)) ) {
  5981. if (sws->ce)
  5982. curl_multi_add_handle(curlm, sws->ce->curl);
  5983. else if (sws->s) {
  5984. sws->next = write_sws;
  5985. write_sws = sws;
  5986. }
  5987. ++wip;
  5988. }
  5989. else {
  5990. --total_submitting;
  5991. free_work(work);
  5992. }
  5993. }
  5994. if (unlikely(shutting_down && !wip))
  5995. break;
  5996. mutex_unlock(&submitting_lock);
  5997. FD_ZERO(&rfds);
  5998. FD_ZERO(&wfds);
  5999. FD_ZERO(&efds);
  6000. tv_timeout.tv_sec = -1;
  6001. // Setup cURL with select
  6002. // Need to call perform to ensure the timeout gets updated
  6003. curl_multi_perform(curlm, &n);
  6004. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  6005. if (curlm_timeout_us >= 0)
  6006. {
  6007. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  6008. reduce_timeout_to(&tv_timeout, &curlm_timer);
  6009. }
  6010. // Setup waiting stratum submissions with select
  6011. for (sws = write_sws; sws; sws = sws->next)
  6012. {
  6013. struct pool *pool = sws->work->pool;
  6014. int fd = pool->sock;
  6015. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  6016. continue;
  6017. FD_SET(fd, &wfds);
  6018. set_maxfd(&maxfd, fd);
  6019. }
  6020. // Setup "submit waiting" notifier with select
  6021. FD_SET(submit_waiting_notifier[0], &rfds);
  6022. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  6023. // Wait for something interesting to happen :)
  6024. cgtime(&tv_now);
  6025. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  6026. FD_ZERO(&rfds);
  6027. continue;
  6028. }
  6029. // Handle any stratum ready-to-write results
  6030. for (swsp = &write_sws; (sws = *swsp); ) {
  6031. struct work *work = sws->work;
  6032. struct pool *pool = work->pool;
  6033. int fd = pool->sock;
  6034. bool sessionid_match;
  6035. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  6036. next_write_sws:
  6037. // TODO: Check if stale, possibly discard etc
  6038. swsp = &sws->next;
  6039. continue;
  6040. }
  6041. cg_rlock(&pool->data_lock);
  6042. // 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
  6043. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  6044. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  6045. cg_runlock(&pool->data_lock);
  6046. if (!sessionid_match)
  6047. {
  6048. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  6049. submit_discard_share2("disconnect", work);
  6050. ++tsreduce;
  6051. next_write_sws_del:
  6052. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  6053. FD_CLR(fd, &wfds);
  6054. // Delete sws for this submission, since we're done with it
  6055. *swsp = sws->next;
  6056. free_sws(sws);
  6057. --wip;
  6058. continue;
  6059. }
  6060. char *s = sws->s;
  6061. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  6062. int sshare_id;
  6063. uint32_t nonce;
  6064. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  6065. char noncehex[9];
  6066. char ntimehex[9];
  6067. sshare->work = copy_work(work);
  6068. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  6069. nonce = *((uint32_t *)(work->data + 76));
  6070. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6071. bin2hex(ntimehex, (void *)&work->data[68], 4);
  6072. mutex_lock(&sshare_lock);
  6073. /* Give the stratum share a unique id */
  6074. sshare_id =
  6075. sshare->id = swork_id++;
  6076. HASH_ADD_INT(stratum_shares, id, sshare);
  6077. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6078. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  6079. mutex_unlock(&sshare_lock);
  6080. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  6081. if (likely(stratum_send(pool, s, strlen(s)))) {
  6082. if (pool_tclear(pool, &pool->submit_fail))
  6083. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6084. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6085. goto next_write_sws_del;
  6086. } else if (!pool_tset(pool, &pool->submit_fail)) {
  6087. // Undo stuff
  6088. mutex_lock(&sshare_lock);
  6089. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  6090. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  6091. if (sshare)
  6092. HASH_DEL(stratum_shares, sshare);
  6093. mutex_unlock(&sshare_lock);
  6094. if (sshare)
  6095. {
  6096. free_work(sshare->work);
  6097. free(sshare);
  6098. }
  6099. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6100. total_ro++;
  6101. pool->remotefail_occasions++;
  6102. if (!sshare)
  6103. goto next_write_sws_del;
  6104. goto next_write_sws;
  6105. }
  6106. }
  6107. // Handle any cURL activities
  6108. curl_multi_perform(curlm, &n);
  6109. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  6110. if (cm->msg == CURLMSG_DONE)
  6111. {
  6112. bool finished;
  6113. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  6114. curl_multi_remove_handle(curlm, cm->easy_handle);
  6115. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  6116. if (!finished) {
  6117. if (retry_submission(sws))
  6118. curl_multi_add_handle(curlm, sws->ce->curl);
  6119. else
  6120. finished = true;
  6121. }
  6122. if (finished) {
  6123. --wip;
  6124. ++tsreduce;
  6125. struct pool *pool = sws->work->pool;
  6126. if (pool->sws_waiting_on_curl) {
  6127. pool->sws_waiting_on_curl->ce = sws->ce;
  6128. sws_has_ce(pool->sws_waiting_on_curl);
  6129. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  6130. curl_multi_add_handle(curlm, sws->ce->curl);
  6131. } else {
  6132. push_curl_entry(sws->ce, sws->work->pool);
  6133. }
  6134. free_sws(sws);
  6135. }
  6136. }
  6137. }
  6138. }
  6139. assert(!write_sws);
  6140. mutex_unlock(&submitting_lock);
  6141. curl_multi_cleanup(curlm);
  6142. applog(LOG_DEBUG, "submit_work thread exiting");
  6143. return NULL;
  6144. }
  6145. /* Find the pool that currently has the highest priority */
  6146. static struct pool *priority_pool(int choice)
  6147. {
  6148. struct pool *ret = NULL;
  6149. int i;
  6150. for (i = 0; i < total_pools; i++) {
  6151. struct pool *pool = pools[i];
  6152. if (pool->prio == choice) {
  6153. ret = pool;
  6154. break;
  6155. }
  6156. }
  6157. if (unlikely(!ret)) {
  6158. applog(LOG_ERR, "WTF No pool %d found!", choice);
  6159. return pools[choice];
  6160. }
  6161. return ret;
  6162. }
  6163. int prioritize_pools(char *param, int *pid)
  6164. {
  6165. char *ptr, *next;
  6166. int i, pr, prio = 0;
  6167. if (total_pools == 0) {
  6168. return MSG_NOPOOL;
  6169. }
  6170. if (param == NULL || *param == '\0') {
  6171. return MSG_MISPID;
  6172. }
  6173. bool pools_changed[total_pools];
  6174. int new_prio[total_pools];
  6175. for (i = 0; i < total_pools; ++i)
  6176. pools_changed[i] = false;
  6177. next = param;
  6178. while (next && *next) {
  6179. ptr = next;
  6180. next = strchr(ptr, ',');
  6181. if (next)
  6182. *(next++) = '\0';
  6183. i = atoi(ptr);
  6184. if (i < 0 || i >= total_pools) {
  6185. *pid = i;
  6186. return MSG_INVPID;
  6187. }
  6188. if (pools_changed[i]) {
  6189. *pid = i;
  6190. return MSG_DUPPID;
  6191. }
  6192. pools_changed[i] = true;
  6193. new_prio[i] = prio++;
  6194. }
  6195. // Only change them if no errors
  6196. for (i = 0; i < total_pools; i++) {
  6197. if (pools_changed[i])
  6198. pools[i]->prio = new_prio[i];
  6199. }
  6200. // In priority order, cycle through the unchanged pools and append them
  6201. for (pr = 0; pr < total_pools; pr++)
  6202. for (i = 0; i < total_pools; i++) {
  6203. if (!pools_changed[i] && pools[i]->prio == pr) {
  6204. pools[i]->prio = prio++;
  6205. pools_changed[i] = true;
  6206. break;
  6207. }
  6208. }
  6209. if (current_pool()->prio)
  6210. switch_pools(NULL);
  6211. return MSG_POOLPRIO;
  6212. }
  6213. void validate_pool_priorities(void)
  6214. {
  6215. // TODO: this should probably do some sort of logging
  6216. int i, j;
  6217. bool used[total_pools];
  6218. bool valid[total_pools];
  6219. for (i = 0; i < total_pools; i++)
  6220. used[i] = valid[i] = false;
  6221. for (i = 0; i < total_pools; i++) {
  6222. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  6223. if (!used[pools[i]->prio]) {
  6224. valid[i] = true;
  6225. used[pools[i]->prio] = true;
  6226. }
  6227. }
  6228. }
  6229. for (i = 0; i < total_pools; i++) {
  6230. if (!valid[i]) {
  6231. for (j = 0; j < total_pools; j++) {
  6232. if (!used[j]) {
  6233. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  6234. pools[i]->prio = j;
  6235. used[j] = true;
  6236. break;
  6237. }
  6238. }
  6239. }
  6240. }
  6241. }
  6242. static void clear_pool_work(struct pool *pool);
  6243. /* Specifies whether we can switch to this pool or not. */
  6244. static bool pool_unusable(struct pool *pool)
  6245. {
  6246. if (pool->idle)
  6247. return true;
  6248. if (pool->enabled != POOL_ENABLED)
  6249. return true;
  6250. return false;
  6251. }
  6252. void switch_pools(struct pool *selected)
  6253. {
  6254. struct pool *pool, *last_pool, *failover_pool = NULL;
  6255. int i, pool_no, next_pool;
  6256. if (selected)
  6257. enable_pool(selected);
  6258. cg_wlock(&control_lock);
  6259. last_pool = currentpool;
  6260. pool_no = currentpool->pool_no;
  6261. /* Switch selected to pool number 0 and move the rest down */
  6262. if (selected) {
  6263. if (selected->prio != 0) {
  6264. for (i = 0; i < total_pools; i++) {
  6265. pool = pools[i];
  6266. if (pool->prio < selected->prio)
  6267. pool->prio++;
  6268. }
  6269. selected->prio = 0;
  6270. }
  6271. }
  6272. switch (pool_strategy) {
  6273. /* All of these set to the master pool */
  6274. case POOL_BALANCE:
  6275. case POOL_FAILOVER:
  6276. case POOL_LOADBALANCE:
  6277. for (i = 0; i < total_pools; i++) {
  6278. pool = priority_pool(i);
  6279. if (pool_unusable(pool))
  6280. continue;
  6281. pool_no = pool->pool_no;
  6282. break;
  6283. }
  6284. break;
  6285. /* Both of these simply increment and cycle */
  6286. case POOL_ROUNDROBIN:
  6287. case POOL_ROTATE:
  6288. if (selected && !selected->idle) {
  6289. pool_no = selected->pool_no;
  6290. break;
  6291. }
  6292. next_pool = pool_no;
  6293. /* Select the next alive pool */
  6294. for (i = 1; i < total_pools; i++) {
  6295. next_pool++;
  6296. if (next_pool >= total_pools)
  6297. next_pool = 0;
  6298. pool = pools[next_pool];
  6299. if (pool_unusable(pool))
  6300. continue;
  6301. if (pool->failover_only)
  6302. {
  6303. BFGINIT(failover_pool, pool);
  6304. continue;
  6305. }
  6306. pool_no = next_pool;
  6307. break;
  6308. }
  6309. break;
  6310. default:
  6311. break;
  6312. }
  6313. pool = pools[pool_no];
  6314. if (pool_unusable(pool) && failover_pool)
  6315. pool = failover_pool;
  6316. currentpool = pool;
  6317. cg_wunlock(&control_lock);
  6318. mutex_lock(&lp_lock);
  6319. pthread_cond_broadcast(&lp_cond);
  6320. mutex_unlock(&lp_lock);
  6321. /* Set the lagging flag to avoid pool not providing work fast enough
  6322. * messages in failover only mode since we have to get all fresh work
  6323. * as in restart_threads */
  6324. if (opt_fail_only)
  6325. pool_tset(pool, &pool->lagging);
  6326. if (pool != last_pool)
  6327. {
  6328. pool->block_id = 0;
  6329. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  6330. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  6331. if (pool_localgen(pool) || opt_fail_only)
  6332. clear_pool_work(last_pool);
  6333. }
  6334. }
  6335. mutex_lock(&lp_lock);
  6336. pthread_cond_broadcast(&lp_cond);
  6337. mutex_unlock(&lp_lock);
  6338. #ifdef HAVE_CURSES
  6339. update_block_display();
  6340. #endif
  6341. }
  6342. static void discard_work(struct work *work)
  6343. {
  6344. if (!work->clone && !work->rolls && !work->mined) {
  6345. if (work->pool) {
  6346. work->pool->discarded_work++;
  6347. work->pool->quota_used--;
  6348. work->pool->works--;
  6349. }
  6350. total_discarded++;
  6351. applog(LOG_DEBUG, "Discarded work");
  6352. } else
  6353. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  6354. free_work(work);
  6355. }
  6356. static bool work_rollable(struct work *);
  6357. static
  6358. void unstage_work(struct work * const work)
  6359. {
  6360. HASH_DEL(staged_work, work);
  6361. --work_mining_algorithm(work)->staged;
  6362. if (work_rollable(work))
  6363. --staged_rollable;
  6364. staged_full = false;
  6365. }
  6366. static void wake_gws(void)
  6367. {
  6368. mutex_lock(stgd_lock);
  6369. pthread_cond_signal(&gws_cond);
  6370. mutex_unlock(stgd_lock);
  6371. }
  6372. static void discard_stale(void)
  6373. {
  6374. struct work *work, *tmp;
  6375. int stale = 0;
  6376. mutex_lock(stgd_lock);
  6377. HASH_ITER(hh, staged_work, work, tmp) {
  6378. if (stale_work(work, false)) {
  6379. unstage_work(work);
  6380. discard_work(work);
  6381. stale++;
  6382. }
  6383. }
  6384. pthread_cond_signal(&gws_cond);
  6385. mutex_unlock(stgd_lock);
  6386. if (stale)
  6387. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  6388. }
  6389. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  6390. {
  6391. bool rv;
  6392. struct timeval tv, orig;
  6393. ldiv_t d;
  6394. d = ldiv(ustime, 1000000);
  6395. tv = (struct timeval){
  6396. .tv_sec = d.quot,
  6397. .tv_usec = d.rem,
  6398. };
  6399. orig = work->tv_staged;
  6400. timersub(&orig, &tv, &work->tv_staged);
  6401. rv = stale_work(work, share);
  6402. work->tv_staged = orig;
  6403. return rv;
  6404. }
  6405. static
  6406. void pool_update_work_restart_time(struct pool * const pool)
  6407. {
  6408. pool->work_restart_time = time(NULL);
  6409. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  6410. }
  6411. static void restart_threads(void)
  6412. {
  6413. struct pool *cp = current_pool();
  6414. int i;
  6415. struct thr_info *thr;
  6416. /* Artificially set the lagging flag to avoid pool not providing work
  6417. * fast enough messages after every long poll */
  6418. pool_tset(cp, &cp->lagging);
  6419. /* Discard staged work that is now stale */
  6420. discard_stale();
  6421. rd_lock(&mining_thr_lock);
  6422. for (i = 0; i < mining_threads; i++)
  6423. {
  6424. thr = mining_thr[i];
  6425. thr->work_restart = true;
  6426. }
  6427. for (i = 0; i < mining_threads; i++)
  6428. {
  6429. thr = mining_thr[i];
  6430. notifier_wake(thr->work_restart_notifier);
  6431. }
  6432. rd_unlock(&mining_thr_lock);
  6433. }
  6434. void blkhashstr(char *rv, const unsigned char *hash)
  6435. {
  6436. unsigned char hash_swap[32];
  6437. swap256(hash_swap, hash);
  6438. swap32tole(hash_swap, hash_swap, 32 / 4);
  6439. bin2hex(rv, hash_swap, 32);
  6440. }
  6441. static
  6442. void set_curblock(struct mining_goal_info * const goal, struct block_info * const blkinfo)
  6443. {
  6444. struct blockchain_info * const blkchain = goal->blkchain;
  6445. blkchain->currentblk = blkinfo;
  6446. blkchain->currentblk_subsidy = 5000000000LL >> (blkinfo->height / 210000);
  6447. cg_wlock(&ch_lock);
  6448. __update_block_title(goal);
  6449. get_timestamp(blkchain->currentblk_first_seen_time_str, sizeof(blkchain->currentblk_first_seen_time_str), blkinfo->first_seen_time);
  6450. cg_wunlock(&ch_lock);
  6451. applog(LOG_INFO, "New block: %s diff %s (%s)", goal->current_goal_detail, goal->current_diff_str, goal->net_hashrate);
  6452. }
  6453. /* Search to see if this prevblkhash has been seen before */
  6454. static
  6455. struct block_info *block_exists(const struct blockchain_info * const blkchain, const void * const prevblkhash)
  6456. {
  6457. struct block_info *s;
  6458. rd_lock(&blk_lock);
  6459. HASH_FIND(hh, blkchain->blocks, prevblkhash, 0x20, s);
  6460. rd_unlock(&blk_lock);
  6461. return s;
  6462. }
  6463. static int block_sort(struct block_info * const blocka, struct block_info * const blockb)
  6464. {
  6465. return blocka->block_seen_order - blockb->block_seen_order;
  6466. }
  6467. static
  6468. void set_blockdiff(struct mining_goal_info * const goal, const struct work * const work)
  6469. {
  6470. unsigned char target[32];
  6471. double diff;
  6472. uint64_t diff64;
  6473. real_block_target(target, work->data);
  6474. diff = target_diff(target);
  6475. diff64 = diff;
  6476. suffix_string(diff64, goal->current_diff_str, sizeof(goal->current_diff_str), 0);
  6477. format_unit2(goal->net_hashrate, sizeof(goal->net_hashrate),
  6478. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  6479. if (unlikely(goal->current_diff != diff))
  6480. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", goal->current_diff_str, goal->net_hashrate);
  6481. goal->current_diff = diff;
  6482. }
  6483. static bool test_work_current(struct work *work)
  6484. {
  6485. bool ret = true;
  6486. if (work->mandatory)
  6487. return ret;
  6488. uint32_t block_id = ((uint32_t*)(work->data))[1];
  6489. const uint8_t * const prevblkhash = &work->data[4];
  6490. {
  6491. /* Hack to work around dud work sneaking into test */
  6492. bool dudwork = true;
  6493. for (int i = 8; i < 26; ++i)
  6494. if (work->data[i])
  6495. {
  6496. dudwork = false;
  6497. break;
  6498. }
  6499. if (dudwork)
  6500. goto out_free;
  6501. }
  6502. struct pool * const pool = work->pool;
  6503. struct mining_goal_info * const goal = pool->goal;
  6504. struct blockchain_info * const blkchain = goal->blkchain;
  6505. /* Search to see if this block exists yet and if not, consider it a
  6506. * new block and set the current block details to this one */
  6507. if (!block_exists(blkchain, prevblkhash))
  6508. {
  6509. struct block_info * const s = calloc(sizeof(struct block_info), 1);
  6510. int deleted_block = 0;
  6511. ret = false;
  6512. if (unlikely(!s))
  6513. quit (1, "test_work_current OOM");
  6514. memcpy(s->prevblkhash, prevblkhash, sizeof(s->prevblkhash));
  6515. s->block_id = block_id;
  6516. s->block_seen_order = new_blocks++;
  6517. s->first_seen_time = time(NULL);
  6518. wr_lock(&blk_lock);
  6519. /* Only keep the last hour's worth of blocks in memory since
  6520. * work from blocks before this is virtually impossible and we
  6521. * want to prevent memory usage from continually rising */
  6522. if (HASH_COUNT(blkchain->blocks) > 6)
  6523. {
  6524. struct block_info *oldblock;
  6525. HASH_SORT(blkchain->blocks, block_sort);
  6526. oldblock = blkchain->blocks;
  6527. deleted_block = oldblock->block_seen_order;
  6528. HASH_DEL(blkchain->blocks, oldblock);
  6529. free(oldblock);
  6530. }
  6531. HASH_ADD(hh, blkchain->blocks, prevblkhash, sizeof(s->prevblkhash), s);
  6532. set_blockdiff(goal, work);
  6533. wr_unlock(&blk_lock);
  6534. pool->block_id = block_id;
  6535. pool_update_work_restart_time(pool);
  6536. if (deleted_block)
  6537. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  6538. #if BLKMAKER_VERSION > 1
  6539. template_nonce = 0;
  6540. #endif
  6541. set_curblock(goal, s);
  6542. if (unlikely(new_blocks == 1))
  6543. goto out_free;
  6544. if (!work->stratum)
  6545. {
  6546. if (work->longpoll)
  6547. {
  6548. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  6549. pool->pool_no);
  6550. }
  6551. else
  6552. if (goal->have_longpoll)
  6553. applog(LOG_NOTICE, "New block detected on network before longpoll");
  6554. else
  6555. applog(LOG_NOTICE, "New block detected on network");
  6556. }
  6557. restart_threads();
  6558. }
  6559. else
  6560. {
  6561. bool restart = false;
  6562. if (unlikely(pool->block_id != block_id))
  6563. {
  6564. bool was_active = pool->block_id != 0;
  6565. pool->block_id = block_id;
  6566. pool_update_work_restart_time(pool);
  6567. if (!work->longpoll)
  6568. update_last_work(work);
  6569. if (was_active)
  6570. {
  6571. // Pool actively changed block
  6572. if (pool == current_pool())
  6573. restart = true;
  6574. if (block_id == blkchain->currentblk->block_id)
  6575. {
  6576. // Caught up, only announce if this pool is the one in use
  6577. if (restart)
  6578. applog(LOG_NOTICE, "%s %d caught up to new block",
  6579. work->longpoll ? "Longpoll from pool" : "Pool",
  6580. pool->pool_no);
  6581. }
  6582. else
  6583. {
  6584. // Switched to a block we know, but not the latest... why?
  6585. // This might detect pools trying to double-spend or 51%,
  6586. // but let's not make any accusations until it's had time
  6587. // in the real world.
  6588. char hexstr[65];
  6589. blkhashstr(hexstr, prevblkhash);
  6590. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  6591. work->longpoll ? "Longpoll from pool" : "Pool",
  6592. pool->pool_no,
  6593. hexstr);
  6594. }
  6595. }
  6596. }
  6597. if (work->longpoll)
  6598. {
  6599. struct pool * const cp = current_pool();
  6600. ++pool->work_restart_id;
  6601. if (work->tr && work->tr == pool->swork.tr)
  6602. pool->swork.work_restart_id = pool->work_restart_id;
  6603. update_last_work(work);
  6604. pool_update_work_restart_time(pool);
  6605. applog(
  6606. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  6607. "Longpoll from pool %d requested work update",
  6608. pool->pool_no);
  6609. if ((!restart) && pool == cp)
  6610. restart = true;
  6611. }
  6612. if (restart)
  6613. restart_threads();
  6614. }
  6615. work->longpoll = false;
  6616. out_free:
  6617. return ret;
  6618. }
  6619. static int tv_sort(struct work *worka, struct work *workb)
  6620. {
  6621. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  6622. }
  6623. static bool work_rollable(struct work *work)
  6624. {
  6625. return (!work->clone && work->rolltime);
  6626. }
  6627. static bool hash_push(struct work *work)
  6628. {
  6629. bool rc = true;
  6630. mutex_lock(stgd_lock);
  6631. if (work_rollable(work))
  6632. staged_rollable++;
  6633. ++work_mining_algorithm(work)->staged;
  6634. if (likely(!getq->frozen)) {
  6635. HASH_ADD_INT(staged_work, id, work);
  6636. HASH_SORT(staged_work, tv_sort);
  6637. } else
  6638. rc = false;
  6639. pthread_cond_broadcast(&getq->cond);
  6640. mutex_unlock(stgd_lock);
  6641. return rc;
  6642. }
  6643. static void stage_work(struct work *work)
  6644. {
  6645. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  6646. work->id, work->pool->pool_no);
  6647. work->work_restart_id = work->pool->work_restart_id;
  6648. work->pool->last_work_time = time(NULL);
  6649. cgtime(&work->pool->tv_last_work_time);
  6650. test_work_current(work);
  6651. work->pool->works++;
  6652. hash_push(work);
  6653. }
  6654. #ifdef HAVE_CURSES
  6655. int curses_int(const char *query)
  6656. {
  6657. int ret;
  6658. char *cvar;
  6659. cvar = curses_input(query);
  6660. if (unlikely(!cvar))
  6661. return -1;
  6662. ret = atoi(cvar);
  6663. free(cvar);
  6664. return ret;
  6665. }
  6666. #endif
  6667. #ifdef HAVE_CURSES
  6668. static bool input_pool(bool live);
  6669. #endif
  6670. #ifdef HAVE_CURSES
  6671. static void display_pool_summary(struct pool *pool)
  6672. {
  6673. double efficiency = 0.0;
  6674. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  6675. int pool_secs;
  6676. if (curses_active_locked()) {
  6677. wlog("Pool: %s Goal: %s\n", pool->rpc_url, pool->goal->name);
  6678. if (pool->solved)
  6679. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  6680. if (!pool->has_stratum)
  6681. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  6682. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  6683. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  6684. wlog(" Accepted shares: %d\n", pool->accepted);
  6685. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  6686. pool->rejected, pool->stale_shares,
  6687. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  6688. );
  6689. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  6690. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  6691. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  6692. wlog(" Network transfer: %s (%s)\n",
  6693. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  6694. (float)pool->cgminer_pool_stats.net_bytes_received,
  6695. (float)pool->cgminer_pool_stats.net_bytes_sent),
  6696. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  6697. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  6698. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  6699. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  6700. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  6701. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  6702. wlog(" Items worked on: %d\n", pool->works);
  6703. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  6704. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  6705. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  6706. unlock_curses();
  6707. }
  6708. }
  6709. #endif
  6710. /* We can't remove the memory used for this struct pool because there may
  6711. * still be work referencing it. We just remove it from the pools list */
  6712. void remove_pool(struct pool *pool)
  6713. {
  6714. int i, last_pool = total_pools - 1;
  6715. struct pool *other;
  6716. disable_pool(pool, POOL_DISABLED);
  6717. /* Boost priority of any lower prio than this one */
  6718. for (i = 0; i < total_pools; i++) {
  6719. other = pools[i];
  6720. if (other->prio > pool->prio)
  6721. other->prio--;
  6722. }
  6723. if (pool->pool_no < last_pool) {
  6724. /* Swap the last pool for this one */
  6725. (pools[last_pool])->pool_no = pool->pool_no;
  6726. pools[pool->pool_no] = pools[last_pool];
  6727. }
  6728. /* Give it an invalid number */
  6729. pool->pool_no = total_pools;
  6730. pool->removed = true;
  6731. pool->has_stratum = false;
  6732. total_pools--;
  6733. }
  6734. /* add a mutex if this needs to be thread safe in the future */
  6735. static struct JE {
  6736. char *buf;
  6737. struct JE *next;
  6738. } *jedata = NULL;
  6739. static void json_escape_free()
  6740. {
  6741. struct JE *jeptr = jedata;
  6742. struct JE *jenext;
  6743. jedata = NULL;
  6744. while (jeptr) {
  6745. jenext = jeptr->next;
  6746. free(jeptr->buf);
  6747. free(jeptr);
  6748. jeptr = jenext;
  6749. }
  6750. }
  6751. static
  6752. char *json_escape(const char *str)
  6753. {
  6754. struct JE *jeptr;
  6755. char *buf, *ptr;
  6756. /* 2x is the max, may as well just allocate that */
  6757. ptr = buf = malloc(strlen(str) * 2 + 1);
  6758. jeptr = malloc(sizeof(*jeptr));
  6759. jeptr->buf = buf;
  6760. jeptr->next = jedata;
  6761. jedata = jeptr;
  6762. while (*str) {
  6763. if (*str == '\\' || *str == '"')
  6764. *(ptr++) = '\\';
  6765. *(ptr++) = *(str++);
  6766. }
  6767. *ptr = '\0';
  6768. return buf;
  6769. }
  6770. static
  6771. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6772. {
  6773. if (!elist)
  6774. return;
  6775. static struct string_elist *entry;
  6776. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6777. bool first = true;
  6778. DL_FOREACH(elist, entry)
  6779. {
  6780. const char * const s = entry->string;
  6781. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6782. first = false;
  6783. }
  6784. fprintf(fcfg, "\n]");
  6785. }
  6786. void write_config(FILE *fcfg)
  6787. {
  6788. int i;
  6789. /* Write pool values */
  6790. fputs("{\n\"pools\" : [", fcfg);
  6791. for(i = 0; i < total_pools; i++) {
  6792. struct pool *pool = pools[i];
  6793. if (pool->failover_only)
  6794. // Don't write failover-only (automatically added) pools to the config file for now
  6795. continue;
  6796. if (pool->quota != 1) {
  6797. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6798. pool->quota,
  6799. json_escape(pool->rpc_url));
  6800. } else {
  6801. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6802. json_escape(pool->rpc_url));
  6803. }
  6804. if (pool->rpc_proxy)
  6805. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6806. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6807. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6808. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6809. if (pool->force_rollntime)
  6810. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6811. fprintf(fcfg, "\n\t}");
  6812. }
  6813. fputs("\n]\n", fcfg);
  6814. #ifdef HAVE_OPENCL
  6815. write_config_opencl(fcfg);
  6816. #endif
  6817. #ifdef WANT_CPUMINE
  6818. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6819. #endif
  6820. /* Simple bool and int options */
  6821. struct opt_table *opt;
  6822. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6823. char *p, *name = strdup(opt->names);
  6824. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6825. if (p[1] != '-')
  6826. continue;
  6827. if (opt->type & OPT_NOARG &&
  6828. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6829. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6830. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6831. if (opt->type & OPT_HASARG &&
  6832. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6833. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6834. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6835. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6836. opt->desc != opt_hidden &&
  6837. 0 <= *(int *)opt->u.arg)
  6838. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6839. }
  6840. }
  6841. /* Special case options */
  6842. if (request_target_str)
  6843. {
  6844. if (request_pdiff == (long)request_pdiff)
  6845. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6846. else
  6847. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6848. }
  6849. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6850. if (pool_strategy == POOL_BALANCE)
  6851. fputs(",\n\"balance\" : true", fcfg);
  6852. if (pool_strategy == POOL_LOADBALANCE)
  6853. fputs(",\n\"load-balance\" : true", fcfg);
  6854. if (pool_strategy == POOL_ROUNDROBIN)
  6855. fputs(",\n\"round-robin\" : true", fcfg);
  6856. if (pool_strategy == POOL_ROTATE)
  6857. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6858. #if defined(unix) || defined(__APPLE__)
  6859. if (opt_stderr_cmd && *opt_stderr_cmd)
  6860. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6861. #endif // defined(unix)
  6862. if (opt_kernel_path && *opt_kernel_path) {
  6863. char *kpath = strdup(opt_kernel_path);
  6864. if (kpath[strlen(kpath)-1] == '/')
  6865. kpath[strlen(kpath)-1] = 0;
  6866. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6867. free(kpath);
  6868. }
  6869. if (schedstart.enable)
  6870. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6871. if (schedstop.enable)
  6872. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6873. if (opt_socks_proxy && *opt_socks_proxy)
  6874. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6875. _write_config_string_elist(fcfg, "scan", scan_devices);
  6876. #ifdef USE_LIBMICROHTTPD
  6877. if (httpsrv_port != -1)
  6878. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6879. #endif
  6880. #ifdef USE_LIBEVENT
  6881. if (stratumsrv_port != -1)
  6882. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6883. #endif
  6884. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6885. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6886. if (opt_api_allow)
  6887. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6888. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6889. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6890. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6891. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6892. if (*opt_api_mcast_des)
  6893. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6894. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6895. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6896. if (opt_api_groups)
  6897. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6898. fputs("\n}\n", fcfg);
  6899. json_escape_free();
  6900. }
  6901. void zero_bestshare(void)
  6902. {
  6903. int i;
  6904. best_diff = 0;
  6905. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6906. for (i = 0; i < total_pools; i++) {
  6907. struct pool *pool = pools[i];
  6908. pool->best_diff = 0;
  6909. }
  6910. }
  6911. void zero_stats(void)
  6912. {
  6913. int i;
  6914. applog(LOG_DEBUG, "Zeroing stats");
  6915. cgtime(&total_tv_start);
  6916. miner_started = total_tv_start;
  6917. total_rolling = 0;
  6918. total_mhashes_done = 0;
  6919. total_getworks = 0;
  6920. total_accepted = 0;
  6921. total_rejected = 0;
  6922. hw_errors = 0;
  6923. total_stale = 0;
  6924. total_discarded = 0;
  6925. total_bytes_rcvd = total_bytes_sent = 0;
  6926. new_blocks = 0;
  6927. local_work = 0;
  6928. total_go = 0;
  6929. total_ro = 0;
  6930. total_secs = 1.0;
  6931. total_diff1 = 0;
  6932. total_bad_diff1 = 0;
  6933. found_blocks = 0;
  6934. total_diff_accepted = 0;
  6935. total_diff_rejected = 0;
  6936. total_diff_stale = 0;
  6937. #ifdef HAVE_CURSES
  6938. awidth = rwidth = swidth = hwwidth = 1;
  6939. #endif
  6940. struct mining_goal_info *goal, *tmpgoal;
  6941. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  6942. {
  6943. goal->diff_accepted = 0;
  6944. }
  6945. for (i = 0; i < total_pools; i++) {
  6946. struct pool *pool = pools[i];
  6947. pool->getwork_requested = 0;
  6948. pool->accepted = 0;
  6949. pool->rejected = 0;
  6950. pool->solved = 0;
  6951. pool->getwork_requested = 0;
  6952. pool->stale_shares = 0;
  6953. pool->discarded_work = 0;
  6954. pool->getfail_occasions = 0;
  6955. pool->remotefail_occasions = 0;
  6956. pool->last_share_time = 0;
  6957. pool->works = 0;
  6958. pool->diff1 = 0;
  6959. pool->diff_accepted = 0;
  6960. pool->diff_rejected = 0;
  6961. pool->diff_stale = 0;
  6962. pool->last_share_diff = 0;
  6963. pool->cgminer_stats.start_tv = total_tv_start;
  6964. pool->cgminer_stats.getwork_calls = 0;
  6965. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6966. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6967. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6968. pool->cgminer_pool_stats.getwork_calls = 0;
  6969. pool->cgminer_pool_stats.getwork_attempts = 0;
  6970. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6971. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6972. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6973. pool->cgminer_pool_stats.min_diff = 0;
  6974. pool->cgminer_pool_stats.max_diff = 0;
  6975. pool->cgminer_pool_stats.min_diff_count = 0;
  6976. pool->cgminer_pool_stats.max_diff_count = 0;
  6977. pool->cgminer_pool_stats.times_sent = 0;
  6978. pool->cgminer_pool_stats.bytes_sent = 0;
  6979. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6980. pool->cgminer_pool_stats.times_received = 0;
  6981. pool->cgminer_pool_stats.bytes_received = 0;
  6982. pool->cgminer_pool_stats.net_bytes_received = 0;
  6983. }
  6984. zero_bestshare();
  6985. for (i = 0; i < total_devices; ++i) {
  6986. struct cgpu_info *cgpu = get_devices(i);
  6987. mutex_lock(&hash_lock);
  6988. cgpu->total_mhashes = 0;
  6989. cgpu->accepted = 0;
  6990. cgpu->rejected = 0;
  6991. cgpu->stale = 0;
  6992. cgpu->hw_errors = 0;
  6993. cgpu->utility = 0.0;
  6994. cgpu->utility_diff1 = 0;
  6995. cgpu->last_share_pool_time = 0;
  6996. cgpu->bad_diff1 = 0;
  6997. cgpu->diff1 = 0;
  6998. cgpu->diff_accepted = 0;
  6999. cgpu->diff_rejected = 0;
  7000. cgpu->diff_stale = 0;
  7001. cgpu->last_share_diff = 0;
  7002. cgpu->thread_fail_init_count = 0;
  7003. cgpu->thread_zero_hash_count = 0;
  7004. cgpu->thread_fail_queue_count = 0;
  7005. cgpu->dev_sick_idle_60_count = 0;
  7006. cgpu->dev_dead_idle_600_count = 0;
  7007. cgpu->dev_nostart_count = 0;
  7008. cgpu->dev_over_heat_count = 0;
  7009. cgpu->dev_thermal_cutoff_count = 0;
  7010. cgpu->dev_comms_error_count = 0;
  7011. cgpu->dev_throttle_count = 0;
  7012. cgpu->cgminer_stats.start_tv = total_tv_start;
  7013. cgpu->cgminer_stats.getwork_calls = 0;
  7014. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  7015. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  7016. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  7017. mutex_unlock(&hash_lock);
  7018. if (cgpu->drv->zero_stats)
  7019. cgpu->drv->zero_stats(cgpu);
  7020. }
  7021. }
  7022. #ifdef HAVE_CURSES
  7023. static
  7024. void loginput_mode(const int size)
  7025. {
  7026. clear_logwin();
  7027. loginput_size = size;
  7028. check_winsizes();
  7029. }
  7030. static void display_pools(void)
  7031. {
  7032. struct pool *pool;
  7033. int selected, i, j;
  7034. char input;
  7035. loginput_mode(7 + total_pools);
  7036. immedok(logwin, true);
  7037. updated:
  7038. for (j = 0; j < total_pools; j++) {
  7039. for (i = 0; i < total_pools; i++) {
  7040. pool = pools[i];
  7041. if (pool->prio != j)
  7042. continue;
  7043. if (pool == current_pool())
  7044. wattron(logwin, A_BOLD);
  7045. if (pool->enabled != POOL_ENABLED || pool->failover_only)
  7046. wattron(logwin, A_DIM);
  7047. wlogprint("%d: ", pool->prio);
  7048. switch (pool->enabled) {
  7049. case POOL_ENABLED:
  7050. if (pool->failover_only)
  7051. wlogprint("Failover ");
  7052. else
  7053. wlogprint("Enabled ");
  7054. break;
  7055. case POOL_DISABLED:
  7056. wlogprint("Disabled ");
  7057. break;
  7058. case POOL_REJECTING:
  7059. wlogprint("Rejectin ");
  7060. break;
  7061. case POOL_MISBEHAVING:
  7062. wlogprint("Misbehav ");
  7063. break;
  7064. }
  7065. _wlogprint(pool_proto_str(pool));
  7066. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  7067. pool->quota,
  7068. pool->pool_no,
  7069. pool->rpc_url, pool->rpc_user);
  7070. wattroff(logwin, A_BOLD | A_DIM);
  7071. break; //for (i = 0; i < total_pools; i++)
  7072. }
  7073. }
  7074. retry:
  7075. wlogprint("\nCurrent pool management strategy: %s\n",
  7076. strategies[pool_strategy].s);
  7077. if (pool_strategy == POOL_ROTATE)
  7078. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  7079. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  7080. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  7081. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  7082. wlogprint("Or press any other key to continue\n");
  7083. logwin_update();
  7084. input = getch();
  7085. if (!strncasecmp(&input, "a", 1)) {
  7086. if (opt_benchmark)
  7087. {
  7088. wlogprint("Cannot add pools in benchmark mode");
  7089. goto retry;
  7090. }
  7091. input_pool(true);
  7092. goto updated;
  7093. } else if (!strncasecmp(&input, "r", 1)) {
  7094. if (total_pools <= 1) {
  7095. wlogprint("Cannot remove last pool");
  7096. goto retry;
  7097. }
  7098. selected = curses_int("Select pool number");
  7099. if (selected < 0 || selected >= total_pools) {
  7100. wlogprint("Invalid selection\n");
  7101. goto retry;
  7102. }
  7103. pool = pools[selected];
  7104. if (pool == current_pool())
  7105. switch_pools(NULL);
  7106. if (pool == current_pool()) {
  7107. wlogprint("Unable to remove pool due to activity\n");
  7108. goto retry;
  7109. }
  7110. remove_pool(pool);
  7111. goto updated;
  7112. } else if (!strncasecmp(&input, "s", 1)) {
  7113. selected = curses_int("Select pool number");
  7114. if (selected < 0 || selected >= total_pools) {
  7115. wlogprint("Invalid selection\n");
  7116. goto retry;
  7117. }
  7118. pool = pools[selected];
  7119. pool->failover_only = false;
  7120. switch_pools(pool);
  7121. goto updated;
  7122. } else if (!strncasecmp(&input, "d", 1)) {
  7123. if (enabled_pools <= 1) {
  7124. wlogprint("Cannot disable last pool");
  7125. goto retry;
  7126. }
  7127. selected = curses_int("Select pool number");
  7128. if (selected < 0 || selected >= total_pools) {
  7129. wlogprint("Invalid selection\n");
  7130. goto retry;
  7131. }
  7132. pool = pools[selected];
  7133. disable_pool(pool, POOL_DISABLED);
  7134. goto updated;
  7135. } else if (!strncasecmp(&input, "e", 1)) {
  7136. selected = curses_int("Select pool number");
  7137. if (selected < 0 || selected >= total_pools) {
  7138. wlogprint("Invalid selection\n");
  7139. goto retry;
  7140. }
  7141. pool = pools[selected];
  7142. pool->failover_only = false;
  7143. enable_pool(pool);
  7144. goto updated;
  7145. } else if (!strncasecmp(&input, "c", 1)) {
  7146. for (i = 0; i <= TOP_STRATEGY; i++)
  7147. wlogprint("%d: %s\n", i, strategies[i].s);
  7148. selected = curses_int("Select strategy number type");
  7149. if (selected < 0 || selected > TOP_STRATEGY) {
  7150. wlogprint("Invalid selection\n");
  7151. goto retry;
  7152. }
  7153. if (selected == POOL_ROTATE) {
  7154. opt_rotate_period = curses_int("Select interval in minutes");
  7155. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  7156. opt_rotate_period = 0;
  7157. wlogprint("Invalid selection\n");
  7158. goto retry;
  7159. }
  7160. }
  7161. mutex_lock(&lp_lock);
  7162. pool_strategy = selected;
  7163. pthread_cond_broadcast(&lp_cond);
  7164. mutex_unlock(&lp_lock);
  7165. switch_pools(NULL);
  7166. goto updated;
  7167. } else if (!strncasecmp(&input, "i", 1)) {
  7168. selected = curses_int("Select pool number");
  7169. if (selected < 0 || selected >= total_pools) {
  7170. wlogprint("Invalid selection\n");
  7171. goto retry;
  7172. }
  7173. pool = pools[selected];
  7174. display_pool_summary(pool);
  7175. goto retry;
  7176. } else if (!strncasecmp(&input, "q", 1)) {
  7177. selected = curses_int("Select pool number");
  7178. if (selected < 0 || selected >= total_pools) {
  7179. wlogprint("Invalid selection\n");
  7180. goto retry;
  7181. }
  7182. pool = pools[selected];
  7183. selected = curses_int("Set quota");
  7184. if (selected < 0) {
  7185. wlogprint("Invalid negative quota\n");
  7186. goto retry;
  7187. }
  7188. pool->quota = selected;
  7189. adjust_quota_gcd();
  7190. goto updated;
  7191. } else if (!strncasecmp(&input, "f", 1)) {
  7192. opt_fail_only ^= true;
  7193. goto updated;
  7194. } else if (!strncasecmp(&input, "p", 1)) {
  7195. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  7196. if (!prilist)
  7197. {
  7198. wlogprint("Not changing priorities\n");
  7199. goto retry;
  7200. }
  7201. int res = prioritize_pools(prilist, &i);
  7202. free(prilist);
  7203. switch (res) {
  7204. case MSG_NOPOOL:
  7205. wlogprint("No pools\n");
  7206. goto retry;
  7207. case MSG_MISPID:
  7208. wlogprint("Missing pool id parameter\n");
  7209. goto retry;
  7210. case MSG_INVPID:
  7211. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  7212. goto retry;
  7213. case MSG_DUPPID:
  7214. wlogprint("Duplicate pool specified %d\n", i);
  7215. goto retry;
  7216. case MSG_POOLPRIO:
  7217. default:
  7218. goto updated;
  7219. }
  7220. }
  7221. immedok(logwin, false);
  7222. loginput_mode(0);
  7223. }
  7224. static const char *summary_detail_level_str(void)
  7225. {
  7226. if (opt_compact)
  7227. return "compact";
  7228. if (opt_show_procs)
  7229. return "processors";
  7230. return "devices";
  7231. }
  7232. static void display_options(void)
  7233. {
  7234. int selected;
  7235. char input;
  7236. immedok(logwin, true);
  7237. loginput_mode(12);
  7238. retry:
  7239. clear_logwin();
  7240. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  7241. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  7242. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  7243. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  7244. opt_debug_console ? "on" : "off",
  7245. want_per_device_stats? "on" : "off",
  7246. opt_quiet ? "on" : "off",
  7247. opt_log_output ? "on" : "off",
  7248. opt_protocol ? "on" : "off",
  7249. opt_worktime ? "on" : "off",
  7250. summary_detail_level_str(),
  7251. opt_log_interval,
  7252. opt_weighed_stats ? "weighed" : "absolute");
  7253. wlogprint("Select an option or any other key to return\n");
  7254. logwin_update();
  7255. input = getch();
  7256. if (!strncasecmp(&input, "q", 1)) {
  7257. opt_quiet ^= true;
  7258. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  7259. goto retry;
  7260. } else if (!strncasecmp(&input, "v", 1)) {
  7261. opt_log_output ^= true;
  7262. if (opt_log_output)
  7263. opt_quiet = false;
  7264. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  7265. goto retry;
  7266. } else if (!strncasecmp(&input, "n", 1)) {
  7267. opt_log_output = false;
  7268. opt_debug_console = false;
  7269. opt_quiet = false;
  7270. opt_protocol = false;
  7271. opt_compact = false;
  7272. opt_show_procs = false;
  7273. devsummaryYOffset = 0;
  7274. want_per_device_stats = false;
  7275. wlogprint("Output mode reset to normal\n");
  7276. switch_logsize();
  7277. goto retry;
  7278. } else if (!strncasecmp(&input, "d", 1)) {
  7279. opt_debug = true;
  7280. opt_debug_console ^= true;
  7281. opt_log_output = opt_debug_console;
  7282. if (opt_debug_console)
  7283. opt_quiet = false;
  7284. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  7285. goto retry;
  7286. } else if (!strncasecmp(&input, "m", 1)) {
  7287. if (opt_compact)
  7288. opt_compact = false;
  7289. else
  7290. if (!opt_show_procs)
  7291. opt_show_procs = true;
  7292. else
  7293. {
  7294. opt_compact = true;
  7295. opt_show_procs = false;
  7296. devsummaryYOffset = 0;
  7297. }
  7298. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  7299. switch_logsize();
  7300. goto retry;
  7301. } else if (!strncasecmp(&input, "p", 1)) {
  7302. want_per_device_stats ^= true;
  7303. opt_log_output = want_per_device_stats;
  7304. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  7305. goto retry;
  7306. } else if (!strncasecmp(&input, "r", 1)) {
  7307. opt_protocol ^= true;
  7308. if (opt_protocol)
  7309. opt_quiet = false;
  7310. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  7311. goto retry;
  7312. } else if (!strncasecmp(&input, "c", 1))
  7313. clear_logwin();
  7314. else if (!strncasecmp(&input, "l", 1)) {
  7315. selected = curses_int("Interval in seconds");
  7316. if (selected < 0 || selected > 9999) {
  7317. wlogprint("Invalid selection\n");
  7318. goto retry;
  7319. }
  7320. opt_log_interval = selected;
  7321. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  7322. goto retry;
  7323. } else if (!strncasecmp(&input, "s", 1)) {
  7324. opt_realquiet = true;
  7325. } else if (!strncasecmp(&input, "w", 1)) {
  7326. opt_worktime ^= true;
  7327. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  7328. goto retry;
  7329. } else if (!strncasecmp(&input, "t", 1)) {
  7330. opt_weighed_stats ^= true;
  7331. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  7332. goto retry;
  7333. } else if (!strncasecmp(&input, "z", 1)) {
  7334. zero_stats();
  7335. goto retry;
  7336. }
  7337. immedok(logwin, false);
  7338. loginput_mode(0);
  7339. }
  7340. #endif
  7341. void default_save_file(char *filename)
  7342. {
  7343. #if defined(unix) || defined(__APPLE__)
  7344. if (getenv("HOME") && *getenv("HOME")) {
  7345. strcpy(filename, getenv("HOME"));
  7346. strcat(filename, "/");
  7347. }
  7348. else
  7349. strcpy(filename, "");
  7350. strcat(filename, ".bfgminer/");
  7351. mkdir(filename, 0777);
  7352. #else
  7353. strcpy(filename, "");
  7354. #endif
  7355. strcat(filename, def_conf);
  7356. }
  7357. #ifdef HAVE_CURSES
  7358. static void set_options(void)
  7359. {
  7360. int selected;
  7361. char input;
  7362. immedok(logwin, true);
  7363. loginput_mode(8);
  7364. retry:
  7365. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  7366. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  7367. "[W]rite config file\n[B]FGMiner restart\n",
  7368. opt_queue, opt_scantime, opt_expiry, opt_retries);
  7369. wlogprint("Select an option or any other key to return\n");
  7370. logwin_update();
  7371. input = getch();
  7372. if (!strncasecmp(&input, "q", 1)) {
  7373. selected = curses_int("Extra work items to queue");
  7374. if (selected < 0 || selected > 9999) {
  7375. wlogprint("Invalid selection\n");
  7376. goto retry;
  7377. }
  7378. opt_queue = selected;
  7379. goto retry;
  7380. } else if (!strncasecmp(&input, "l", 1)) {
  7381. if (want_longpoll)
  7382. stop_longpoll();
  7383. else
  7384. start_longpoll();
  7385. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  7386. goto retry;
  7387. } else if (!strncasecmp(&input, "s", 1)) {
  7388. selected = curses_int("Set scantime in seconds");
  7389. if (selected < 0 || selected > 9999) {
  7390. wlogprint("Invalid selection\n");
  7391. goto retry;
  7392. }
  7393. opt_scantime = selected;
  7394. goto retry;
  7395. } else if (!strncasecmp(&input, "e", 1)) {
  7396. selected = curses_int("Set expiry time in seconds");
  7397. if (selected < 0 || selected > 9999) {
  7398. wlogprint("Invalid selection\n");
  7399. goto retry;
  7400. }
  7401. opt_expiry = selected;
  7402. goto retry;
  7403. } else if (!strncasecmp(&input, "r", 1)) {
  7404. selected = curses_int("Retries before failing (-1 infinite)");
  7405. if (selected < -1 || selected > 9999) {
  7406. wlogprint("Invalid selection\n");
  7407. goto retry;
  7408. }
  7409. opt_retries = selected;
  7410. goto retry;
  7411. } else if (!strncasecmp(&input, "w", 1)) {
  7412. FILE *fcfg;
  7413. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  7414. default_save_file(filename);
  7415. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  7416. str = curses_input(prompt);
  7417. if (str) {
  7418. struct stat statbuf;
  7419. strcpy(filename, str);
  7420. free(str);
  7421. if (!stat(filename, &statbuf)) {
  7422. wlogprint("File exists, overwrite?\n");
  7423. input = getch();
  7424. if (strncasecmp(&input, "y", 1))
  7425. goto retry;
  7426. }
  7427. }
  7428. fcfg = fopen(filename, "w");
  7429. if (!fcfg) {
  7430. wlogprint("Cannot open or create file\n");
  7431. goto retry;
  7432. }
  7433. write_config(fcfg);
  7434. fclose(fcfg);
  7435. goto retry;
  7436. } else if (!strncasecmp(&input, "b", 1)) {
  7437. wlogprint("Are you sure?\n");
  7438. input = getch();
  7439. if (!strncasecmp(&input, "y", 1))
  7440. app_restart();
  7441. else
  7442. clear_logwin();
  7443. } else
  7444. clear_logwin();
  7445. loginput_mode(0);
  7446. immedok(logwin, false);
  7447. }
  7448. int scan_serial(const char *);
  7449. static
  7450. void _managetui_msg(const char *repr, const char **msg)
  7451. {
  7452. if (*msg)
  7453. {
  7454. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  7455. wattron(logwin, A_BOLD);
  7456. wlogprint("%s", *msg);
  7457. wattroff(logwin, A_BOLD);
  7458. *msg = NULL;
  7459. }
  7460. logwin_update();
  7461. }
  7462. void manage_device(void)
  7463. {
  7464. char logline[256];
  7465. const char *msg = NULL;
  7466. struct cgpu_info *cgpu;
  7467. const struct device_drv *drv;
  7468. selecting_device = true;
  7469. immedok(logwin, true);
  7470. loginput_mode(12);
  7471. devchange:
  7472. if (unlikely(!total_devices))
  7473. {
  7474. clear_logwin();
  7475. wlogprint("(no devices)\n");
  7476. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  7477. _managetui_msg("(none)", &msg);
  7478. int input = getch();
  7479. switch (input)
  7480. {
  7481. case '+': case '=': // add new device
  7482. goto addnew;
  7483. default:
  7484. goto out;
  7485. }
  7486. }
  7487. cgpu = devices[selected_device];
  7488. drv = cgpu->drv;
  7489. refresh_devstatus();
  7490. refresh:
  7491. clear_logwin();
  7492. wlogprint("Select processor to manage using up/down arrow keys\n");
  7493. get_statline3(logline, sizeof(logline), cgpu, true, true);
  7494. wattron(logwin, A_BOLD);
  7495. wlogprint("%s", logline);
  7496. wattroff(logwin, A_BOLD);
  7497. wlogprint("\n");
  7498. if (cgpu->dev_manufacturer)
  7499. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  7500. else
  7501. if (cgpu->dev_product)
  7502. wlogprint(" %s\n", cgpu->dev_product);
  7503. if (cgpu->dev_serial)
  7504. wlogprint("Serial: %s\n", cgpu->dev_serial);
  7505. if (cgpu->kname)
  7506. wlogprint("Kernel: %s\n", cgpu->kname);
  7507. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  7508. drv->proc_wlogprint_status(cgpu);
  7509. wlogprint("\n");
  7510. // TODO: Last share at TIMESTAMP on pool N
  7511. // TODO: Custom device info/commands
  7512. if (cgpu->deven != DEV_ENABLED)
  7513. wlogprint("[E]nable ");
  7514. if (cgpu->deven != DEV_DISABLED)
  7515. wlogprint("[D]isable ");
  7516. if (drv->identify_device)
  7517. wlogprint("[I]dentify ");
  7518. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  7519. drv->proc_tui_wlogprint_choices(cgpu);
  7520. wlogprint("\n");
  7521. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  7522. _managetui_msg(cgpu->proc_repr, &msg);
  7523. while (true)
  7524. {
  7525. int input = getch();
  7526. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  7527. switch (input) {
  7528. case 'd': case 'D':
  7529. if (cgpu->deven == DEV_DISABLED)
  7530. msg = "Processor already disabled\n";
  7531. else
  7532. {
  7533. cgpu->deven = DEV_DISABLED;
  7534. msg = "Processor being disabled\n";
  7535. }
  7536. goto refresh;
  7537. case 'e': case 'E':
  7538. if (cgpu->deven == DEV_ENABLED)
  7539. msg = "Processor already enabled\n";
  7540. else
  7541. {
  7542. proc_enable(cgpu);
  7543. msg = "Processor being enabled\n";
  7544. }
  7545. goto refresh;
  7546. case 'i': case 'I':
  7547. if (drv->identify_device && drv->identify_device(cgpu))
  7548. msg = "Identify command sent\n";
  7549. else
  7550. goto key_default;
  7551. goto refresh;
  7552. case KEY_DOWN:
  7553. if (selected_device >= total_devices - 1)
  7554. break;
  7555. ++selected_device;
  7556. goto devchange;
  7557. case KEY_UP:
  7558. if (selected_device <= 0)
  7559. break;
  7560. --selected_device;
  7561. goto devchange;
  7562. case KEY_NPAGE:
  7563. {
  7564. if (selected_device >= total_devices - 1)
  7565. break;
  7566. struct cgpu_info *mdev = devices[selected_device]->device;
  7567. do {
  7568. ++selected_device;
  7569. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  7570. goto devchange;
  7571. }
  7572. case KEY_PPAGE:
  7573. {
  7574. if (selected_device <= 0)
  7575. break;
  7576. struct cgpu_info *mdev = devices[selected_device]->device;
  7577. do {
  7578. --selected_device;
  7579. } while (devices[selected_device]->device == mdev && selected_device > 0);
  7580. goto devchange;
  7581. }
  7582. case '/': case '?': // find device
  7583. {
  7584. static char *pattern = NULL;
  7585. char *newpattern = curses_input("Enter pattern");
  7586. if (newpattern)
  7587. {
  7588. free(pattern);
  7589. pattern = newpattern;
  7590. }
  7591. else
  7592. if (!pattern)
  7593. pattern = calloc(1, 1);
  7594. int match = cgpu_search(pattern, selected_device + 1);
  7595. if (match == -1)
  7596. {
  7597. msg = "Couldn't find device\n";
  7598. goto refresh;
  7599. }
  7600. selected_device = match;
  7601. goto devchange;
  7602. }
  7603. case '+': case '=': // add new device
  7604. {
  7605. addnew:
  7606. clear_logwin();
  7607. _wlogprint(
  7608. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  7609. "Prefix by a driver name and colon to only probe a specific driver.\n"
  7610. "For example: erupter:"
  7611. #ifdef WIN32
  7612. "\\\\.\\COM40"
  7613. #elif defined(__APPLE__)
  7614. "/dev/cu.SLAB_USBtoUART"
  7615. #else
  7616. "/dev/ttyUSB39"
  7617. #endif
  7618. "\n"
  7619. );
  7620. char *scanser = curses_input("Enter target");
  7621. if (scan_serial(scanser))
  7622. {
  7623. selected_device = total_devices - 1;
  7624. msg = "Device scan succeeded\n";
  7625. }
  7626. else
  7627. msg = "No new devices found\n";
  7628. goto devchange;
  7629. }
  7630. case 'Q': case 'q':
  7631. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  7632. case '\x1b': // ESC
  7633. case KEY_ENTER:
  7634. case '\r': // Ctrl-M on Windows, with nonl
  7635. #ifdef PADENTER
  7636. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  7637. #endif
  7638. case '\n':
  7639. goto out;
  7640. default:
  7641. ;
  7642. key_default:
  7643. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  7644. {
  7645. msg = drv->proc_tui_handle_choice(cgpu, input);
  7646. if (msg)
  7647. goto refresh;
  7648. }
  7649. }
  7650. }
  7651. out:
  7652. selecting_device = false;
  7653. loginput_mode(0);
  7654. immedok(logwin, false);
  7655. }
  7656. void show_help(void)
  7657. {
  7658. loginput_mode(11);
  7659. // NOTE: wlogprint is a macro with a buffer limit
  7660. _wlogprint(
  7661. "LU: oldest explicit work update currently being used for new work\n"
  7662. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  7663. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  7664. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  7665. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7666. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7667. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7668. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  7669. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7670. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7671. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  7672. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7673. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7674. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  7675. "\n"
  7676. "devices/processors hashing (only for totals line), hottest temperature\n"
  7677. );
  7678. wlogprint(
  7679. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  7680. , opt_log_interval);
  7681. _wlogprint(
  7682. "A: accepted shares | R: rejected+discarded(% of total)\n"
  7683. "HW: hardware errors / % nonces invalid\n"
  7684. "\n"
  7685. "Press any key to clear"
  7686. );
  7687. logwin_update();
  7688. getch();
  7689. loginput_mode(0);
  7690. }
  7691. static void *input_thread(void __maybe_unused *userdata)
  7692. {
  7693. RenameThread("input");
  7694. if (!curses_active)
  7695. return NULL;
  7696. while (1) {
  7697. int input;
  7698. input = getch();
  7699. switch (input) {
  7700. case 'h': case 'H': case '?':
  7701. case KEY_F(1):
  7702. show_help();
  7703. break;
  7704. case 'q': case 'Q':
  7705. kill_work();
  7706. return NULL;
  7707. case 'd': case 'D':
  7708. display_options();
  7709. break;
  7710. case 'm': case 'M':
  7711. manage_device();
  7712. break;
  7713. case 'p': case 'P':
  7714. display_pools();
  7715. break;
  7716. case 's': case 'S':
  7717. set_options();
  7718. break;
  7719. #ifdef HAVE_CURSES
  7720. case KEY_DOWN:
  7721. {
  7722. const int visible_lines = logcursor - devcursor;
  7723. const int invisible_lines = total_lines - visible_lines;
  7724. if (devsummaryYOffset <= -invisible_lines)
  7725. break;
  7726. devsummaryYOffset -= 2;
  7727. }
  7728. case KEY_UP:
  7729. if (devsummaryYOffset == 0)
  7730. break;
  7731. ++devsummaryYOffset;
  7732. refresh_devstatus();
  7733. break;
  7734. case KEY_NPAGE:
  7735. {
  7736. const int visible_lines = logcursor - devcursor;
  7737. const int invisible_lines = total_lines - visible_lines;
  7738. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  7739. devsummaryYOffset = -invisible_lines;
  7740. else
  7741. devsummaryYOffset -= visible_lines;
  7742. refresh_devstatus();
  7743. break;
  7744. }
  7745. case KEY_PPAGE:
  7746. {
  7747. const int visible_lines = logcursor - devcursor;
  7748. if (devsummaryYOffset + visible_lines >= 0)
  7749. devsummaryYOffset = 0;
  7750. else
  7751. devsummaryYOffset += visible_lines;
  7752. refresh_devstatus();
  7753. break;
  7754. }
  7755. #endif
  7756. }
  7757. if (opt_realquiet) {
  7758. disable_curses();
  7759. break;
  7760. }
  7761. }
  7762. return NULL;
  7763. }
  7764. #endif
  7765. static void *api_thread(void *userdata)
  7766. {
  7767. struct thr_info *mythr = userdata;
  7768. pthread_detach(pthread_self());
  7769. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7770. RenameThread("rpc");
  7771. api(api_thr_id);
  7772. mythr->has_pth = false;
  7773. return NULL;
  7774. }
  7775. void thread_reportin(struct thr_info *thr)
  7776. {
  7777. cgtime(&thr->last);
  7778. thr->cgpu->status = LIFE_WELL;
  7779. thr->getwork = 0;
  7780. thr->cgpu->device_last_well = time(NULL);
  7781. }
  7782. void thread_reportout(struct thr_info *thr)
  7783. {
  7784. thr->getwork = time(NULL);
  7785. }
  7786. static void hashmeter(int thr_id, struct timeval *diff,
  7787. uint64_t hashes_done)
  7788. {
  7789. char logstatusline[256];
  7790. struct timeval temp_tv_end, total_diff;
  7791. double secs;
  7792. double local_secs;
  7793. static double local_mhashes_done = 0;
  7794. double local_mhashes = (double)hashes_done / 1000000.0;
  7795. bool showlog = false;
  7796. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7797. char rejpcbuf[6];
  7798. char bnbuf[6];
  7799. struct thr_info *thr;
  7800. /* Update the last time this thread reported in */
  7801. if (thr_id >= 0) {
  7802. thr = get_thread(thr_id);
  7803. cgtime(&(thr->last));
  7804. thr->cgpu->device_last_well = time(NULL);
  7805. }
  7806. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7807. /* So we can call hashmeter from a non worker thread */
  7808. if (thr_id >= 0) {
  7809. struct cgpu_info *cgpu = thr->cgpu;
  7810. int threadobj = cgpu->threads ?: 1;
  7811. double thread_rolling = 0.0;
  7812. int i;
  7813. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7814. thr_id, hashes_done, hashes_done / 1000 / secs);
  7815. /* Rolling average for each thread and each device */
  7816. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7817. for (i = 0; i < threadobj; i++)
  7818. thread_rolling += cgpu->thr[i]->rolling;
  7819. mutex_lock(&hash_lock);
  7820. decay_time(&cgpu->rolling, thread_rolling, secs);
  7821. cgpu->total_mhashes += local_mhashes;
  7822. mutex_unlock(&hash_lock);
  7823. // If needed, output detailed, per-device stats
  7824. if (want_per_device_stats) {
  7825. struct timeval now;
  7826. struct timeval elapsed;
  7827. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7828. cgtime(&now);
  7829. timersub(&now, last_msg_tv, &elapsed);
  7830. if (opt_log_interval <= elapsed.tv_sec) {
  7831. struct cgpu_info *cgpu = thr->cgpu;
  7832. char logline[255];
  7833. *last_msg_tv = now;
  7834. get_statline(logline, sizeof(logline), cgpu);
  7835. if (!curses_active) {
  7836. printf("\n%s\r", logline);
  7837. fflush(stdout);
  7838. } else
  7839. applog(LOG_INFO, "%s", logline);
  7840. }
  7841. }
  7842. }
  7843. /* Totals are updated by all threads so can race without locking */
  7844. mutex_lock(&hash_lock);
  7845. cgtime(&temp_tv_end);
  7846. timersub(&temp_tv_end, &total_tv_start, &total_diff);
  7847. total_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7848. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7849. total_mhashes_done += local_mhashes;
  7850. local_mhashes_done += local_mhashes;
  7851. /* Only update with opt_log_interval */
  7852. if (total_diff.tv_sec < opt_log_interval)
  7853. goto out_unlock;
  7854. showlog = true;
  7855. cgtime(&total_tv_end);
  7856. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7857. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7858. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7859. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7860. multi_format_unit_array2(
  7861. ((char*[]){cHr, aHr, uHr}),
  7862. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7863. true, "h/s", H2B_SHORT,
  7864. 3,
  7865. 1e6*total_rolling,
  7866. 1e6*total_mhashes_done / total_secs,
  7867. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7868. int ui_accepted, ui_rejected, ui_stale;
  7869. if (opt_weighed_stats)
  7870. {
  7871. ui_accepted = total_diff_accepted;
  7872. ui_rejected = total_diff_rejected;
  7873. ui_stale = total_diff_stale;
  7874. }
  7875. else
  7876. {
  7877. ui_accepted = total_accepted;
  7878. ui_rejected = total_rejected;
  7879. ui_stale = total_stale;
  7880. }
  7881. #ifdef HAVE_CURSES
  7882. if (curses_active_locked()) {
  7883. float temp = 0;
  7884. struct cgpu_info *proc, *last_working_dev = NULL;
  7885. int i, working_devs = 0, working_procs = 0;
  7886. int divx;
  7887. bool bad = false;
  7888. // Find the highest temperature of all processors
  7889. for (i = 0; i < total_devices; ++i)
  7890. {
  7891. proc = get_devices(i);
  7892. if (proc->temp > temp)
  7893. temp = proc->temp;
  7894. if (unlikely(proc->deven == DEV_DISABLED))
  7895. ; // Just need to block it off from both conditions
  7896. else
  7897. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7898. {
  7899. if (proc->rolling > .1)
  7900. {
  7901. ++working_procs;
  7902. if (proc->device != last_working_dev)
  7903. {
  7904. ++working_devs;
  7905. last_working_dev = proc->device;
  7906. }
  7907. }
  7908. }
  7909. else
  7910. bad = true;
  7911. }
  7912. if (working_devs == working_procs)
  7913. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7914. else
  7915. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7916. divx = 7;
  7917. if (opt_show_procs && !opt_compact)
  7918. divx += max_lpdigits;
  7919. if (bad)
  7920. {
  7921. divx += sizeof(U8_BAD_START)-1;
  7922. strcpy(&statusline[divx], U8_BAD_END);
  7923. divx += sizeof(U8_BAD_END)-1;
  7924. }
  7925. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7926. format_statline(statusline, sizeof(statusline),
  7927. cHr, aHr,
  7928. uHr,
  7929. ui_accepted,
  7930. ui_rejected,
  7931. ui_stale,
  7932. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7933. hw_errors,
  7934. total_bad_diff1, total_bad_diff1 + total_diff1);
  7935. unlock_curses();
  7936. }
  7937. #endif
  7938. // Add a space
  7939. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7940. uHr[5] = ' ';
  7941. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7942. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7943. snprintf(logstatusline, sizeof(logstatusline),
  7944. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7945. want_per_device_stats ? "ALL " : "",
  7946. opt_log_interval,
  7947. cHr, aHr,
  7948. uHr,
  7949. ui_accepted,
  7950. ui_rejected,
  7951. ui_stale,
  7952. rejpcbuf,
  7953. hw_errors,
  7954. bnbuf
  7955. );
  7956. local_mhashes_done = 0;
  7957. out_unlock:
  7958. mutex_unlock(&hash_lock);
  7959. if (showlog) {
  7960. if (!curses_active) {
  7961. if (want_per_device_stats)
  7962. printf("\n%s\r", logstatusline);
  7963. else
  7964. {
  7965. const int logstatusline_len = strlen(logstatusline);
  7966. int padding;
  7967. if (last_logstatusline_len > logstatusline_len)
  7968. padding = (last_logstatusline_len - logstatusline_len);
  7969. else
  7970. {
  7971. padding = 0;
  7972. if (last_logstatusline_len == -1)
  7973. puts("");
  7974. }
  7975. printf("%s%*s\r", logstatusline, padding, "");
  7976. last_logstatusline_len = logstatusline_len;
  7977. }
  7978. fflush(stdout);
  7979. } else
  7980. applog(LOG_INFO, "%s", logstatusline);
  7981. }
  7982. }
  7983. void hashmeter2(struct thr_info *thr)
  7984. {
  7985. struct timeval tv_now, tv_elapsed;
  7986. timerclear(&thr->tv_hashes_done);
  7987. cgtime(&tv_now);
  7988. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7989. /* Update the hashmeter at most 5 times per second */
  7990. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7991. tv_elapsed.tv_sec >= opt_log_interval) {
  7992. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7993. thr->hashes_done = 0;
  7994. thr->tv_lastupdate = tv_now;
  7995. }
  7996. }
  7997. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7998. struct stratum_share *sshare)
  7999. {
  8000. struct work *work = sshare->work;
  8001. share_result(val, res_val, err_val, work, false, "");
  8002. }
  8003. /* Parses stratum json responses and tries to find the id that the request
  8004. * matched to and treat it accordingly. */
  8005. bool parse_stratum_response(struct pool *pool, char *s)
  8006. {
  8007. json_t *val = NULL, *err_val, *res_val, *id_val;
  8008. struct stratum_share *sshare;
  8009. json_error_t err;
  8010. bool ret = false;
  8011. int id;
  8012. val = JSON_LOADS(s, &err);
  8013. if (!val) {
  8014. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  8015. goto out;
  8016. }
  8017. res_val = json_object_get(val, "result");
  8018. err_val = json_object_get(val, "error");
  8019. id_val = json_object_get(val, "id");
  8020. if (json_is_null(id_val) || !id_val) {
  8021. char *ss;
  8022. if (err_val)
  8023. ss = json_dumps(err_val, JSON_INDENT(3));
  8024. else
  8025. ss = strdup("(unknown reason)");
  8026. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  8027. free(ss);
  8028. goto out;
  8029. }
  8030. if (!json_is_integer(id_val)) {
  8031. if (json_is_string(id_val)
  8032. && !strncmp(json_string_value(id_val), "txlist", 6))
  8033. {
  8034. const bool is_array = json_is_array(res_val);
  8035. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  8036. is_array ? "transaction list" : "no-transaction-list response",
  8037. pool->pool_no, &json_string_value(id_val)[6]);
  8038. if (!is_array)
  8039. {
  8040. // No need to wait for a timeout
  8041. timer_unset(&pool->swork.tv_transparency);
  8042. pool_set_opaque(pool, true);
  8043. goto fishy;
  8044. }
  8045. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  8046. // We only care about a transaction list for the current job id
  8047. goto fishy;
  8048. // Check that the transactions actually hash to the merkle links
  8049. {
  8050. unsigned maxtx = 1 << pool->swork.merkles;
  8051. unsigned mintx = maxtx >> 1;
  8052. --maxtx;
  8053. unsigned acttx = (unsigned)json_array_size(res_val);
  8054. if (acttx < mintx || acttx > maxtx) {
  8055. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  8056. pool->pool_no, acttx, mintx, maxtx);
  8057. goto fishy;
  8058. }
  8059. // TODO: Check hashes match actual merkle links
  8060. }
  8061. pool_set_opaque(pool, false);
  8062. timer_unset(&pool->swork.tv_transparency);
  8063. fishy:
  8064. ret = true;
  8065. }
  8066. goto out;
  8067. }
  8068. id = json_integer_value(id_val);
  8069. mutex_lock(&sshare_lock);
  8070. HASH_FIND_INT(stratum_shares, &id, sshare);
  8071. if (sshare)
  8072. HASH_DEL(stratum_shares, sshare);
  8073. mutex_unlock(&sshare_lock);
  8074. if (!sshare) {
  8075. double pool_diff;
  8076. /* Since the share is untracked, we can only guess at what the
  8077. * work difficulty is based on the current pool diff. */
  8078. cg_rlock(&pool->data_lock);
  8079. pool_diff = target_diff(pool->swork.target);
  8080. cg_runlock(&pool->data_lock);
  8081. if (json_is_true(res_val)) {
  8082. struct mining_goal_info * const goal = pool->goal;
  8083. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  8084. /* We don't know what device this came from so we can't
  8085. * attribute the work to the relevant cgpu */
  8086. mutex_lock(&stats_lock);
  8087. total_accepted++;
  8088. pool->accepted++;
  8089. total_diff_accepted += pool_diff;
  8090. pool->diff_accepted += pool_diff;
  8091. goal->diff_accepted += pool_diff;
  8092. mutex_unlock(&stats_lock);
  8093. } else {
  8094. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  8095. mutex_lock(&stats_lock);
  8096. total_rejected++;
  8097. pool->rejected++;
  8098. total_diff_rejected += pool_diff;
  8099. pool->diff_rejected += pool_diff;
  8100. mutex_unlock(&stats_lock);
  8101. }
  8102. goto out;
  8103. }
  8104. else {
  8105. mutex_lock(&submitting_lock);
  8106. --total_submitting;
  8107. mutex_unlock(&submitting_lock);
  8108. }
  8109. stratum_share_result(val, res_val, err_val, sshare);
  8110. free_work(sshare->work);
  8111. free(sshare);
  8112. ret = true;
  8113. out:
  8114. if (val)
  8115. json_decref(val);
  8116. return ret;
  8117. }
  8118. static void shutdown_stratum(struct pool *pool)
  8119. {
  8120. // Shut down Stratum as if we never had it
  8121. pool->stratum_active = false;
  8122. pool->stratum_init = false;
  8123. pool->has_stratum = false;
  8124. shutdown(pool->sock, SHUT_RDWR);
  8125. free(pool->stratum_url);
  8126. if (pool->sockaddr_url == pool->stratum_url)
  8127. pool->sockaddr_url = NULL;
  8128. pool->stratum_url = NULL;
  8129. }
  8130. void clear_stratum_shares(struct pool *pool)
  8131. {
  8132. int my_mining_threads = mining_threads; // Cached outside of locking
  8133. struct stratum_share *sshare, *tmpshare;
  8134. struct work *work;
  8135. struct cgpu_info *cgpu;
  8136. double diff_cleared = 0;
  8137. double thr_diff_cleared[my_mining_threads];
  8138. int cleared = 0;
  8139. int thr_cleared[my_mining_threads];
  8140. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  8141. for (int i = 0; i < my_mining_threads; ++i)
  8142. {
  8143. thr_diff_cleared[i] = 0;
  8144. thr_cleared[i] = 0;
  8145. }
  8146. mutex_lock(&sshare_lock);
  8147. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8148. work = sshare->work;
  8149. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  8150. HASH_DEL(stratum_shares, sshare);
  8151. sharelog("disconnect", work);
  8152. diff_cleared += sshare->work->work_difficulty;
  8153. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  8154. ++thr_cleared[work->thr_id];
  8155. free_work(sshare->work);
  8156. free(sshare);
  8157. cleared++;
  8158. }
  8159. }
  8160. mutex_unlock(&sshare_lock);
  8161. if (cleared) {
  8162. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  8163. mutex_lock(&stats_lock);
  8164. pool->stale_shares += cleared;
  8165. total_stale += cleared;
  8166. pool->diff_stale += diff_cleared;
  8167. total_diff_stale += diff_cleared;
  8168. for (int i = 0; i < my_mining_threads; ++i)
  8169. if (thr_cleared[i])
  8170. {
  8171. cgpu = get_thr_cgpu(i);
  8172. cgpu->diff_stale += thr_diff_cleared[i];
  8173. cgpu->stale += thr_cleared[i];
  8174. }
  8175. mutex_unlock(&stats_lock);
  8176. mutex_lock(&submitting_lock);
  8177. total_submitting -= cleared;
  8178. mutex_unlock(&submitting_lock);
  8179. }
  8180. }
  8181. static void resubmit_stratum_shares(struct pool *pool)
  8182. {
  8183. struct stratum_share *sshare, *tmpshare;
  8184. struct work *work;
  8185. unsigned resubmitted = 0;
  8186. mutex_lock(&sshare_lock);
  8187. mutex_lock(&submitting_lock);
  8188. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8189. if (sshare->work->pool != pool)
  8190. continue;
  8191. HASH_DEL(stratum_shares, sshare);
  8192. work = sshare->work;
  8193. DL_APPEND(submit_waiting, work);
  8194. free(sshare);
  8195. ++resubmitted;
  8196. }
  8197. mutex_unlock(&submitting_lock);
  8198. mutex_unlock(&sshare_lock);
  8199. if (resubmitted) {
  8200. notifier_wake(submit_waiting_notifier);
  8201. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  8202. }
  8203. }
  8204. static void clear_pool_work(struct pool *pool)
  8205. {
  8206. struct work *work, *tmp;
  8207. int cleared = 0;
  8208. mutex_lock(stgd_lock);
  8209. HASH_ITER(hh, staged_work, work, tmp) {
  8210. if (work->pool == pool) {
  8211. unstage_work(work);
  8212. free_work(work);
  8213. cleared++;
  8214. }
  8215. }
  8216. mutex_unlock(stgd_lock);
  8217. }
  8218. static int cp_prio(void)
  8219. {
  8220. int prio;
  8221. cg_rlock(&control_lock);
  8222. prio = currentpool->prio;
  8223. cg_runlock(&control_lock);
  8224. return prio;
  8225. }
  8226. /* We only need to maintain a secondary pool connection when we need the
  8227. * capacity to get work from the backup pools while still on the primary */
  8228. static bool cnx_needed(struct pool *pool)
  8229. {
  8230. struct pool *cp;
  8231. // We want to keep a connection open for rejecting or misbehaving pools, to detect when/if they change their tune
  8232. if (pool->enabled == POOL_DISABLED)
  8233. return false;
  8234. /* Idle stratum pool needs something to kick it alive again */
  8235. if (pool->has_stratum && pool->idle)
  8236. return true;
  8237. /* Getwork pools without opt_fail_only need backup pools up to be able
  8238. * to leak shares */
  8239. cp = current_pool();
  8240. if (pool_actively_desired(pool, cp))
  8241. return true;
  8242. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  8243. return true;
  8244. /* Keep the connection open to allow any stray shares to be submitted
  8245. * on switching pools for 2 minutes. */
  8246. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  8247. return true;
  8248. /* If the pool has only just come to life and is higher priority than
  8249. * the current pool keep the connection open so we can fail back to
  8250. * it. */
  8251. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8252. return true;
  8253. if (pool_unworkable(cp))
  8254. return true;
  8255. /* We've run out of work, bring anything back to life. */
  8256. if (no_work)
  8257. return true;
  8258. // If the current pool lacks its own block change detection, see if we are needed for that
  8259. if (pool_active_lp_pool(cp) == pool)
  8260. return true;
  8261. return false;
  8262. }
  8263. static void wait_lpcurrent(struct pool *pool);
  8264. static void pool_resus(struct pool *pool);
  8265. static void stratum_resumed(struct pool *pool)
  8266. {
  8267. if (!pool->stratum_notify)
  8268. return;
  8269. if (pool_tclear(pool, &pool->idle)) {
  8270. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  8271. pool_resus(pool);
  8272. }
  8273. }
  8274. static bool supports_resume(struct pool *pool)
  8275. {
  8276. bool ret;
  8277. cg_rlock(&pool->data_lock);
  8278. ret = (pool->sessionid != NULL);
  8279. cg_runlock(&pool->data_lock);
  8280. return ret;
  8281. }
  8282. static bool pools_active;
  8283. /* One stratum thread per pool that has stratum waits on the socket checking
  8284. * for new messages and for the integrity of the socket connection. We reset
  8285. * the connection based on the integrity of the receive side only as the send
  8286. * side will eventually expire data it fails to send. */
  8287. static void *stratum_thread(void *userdata)
  8288. {
  8289. struct pool *pool = (struct pool *)userdata;
  8290. pthread_detach(pthread_self());
  8291. char threadname[20];
  8292. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  8293. RenameThread(threadname);
  8294. srand(time(NULL) + (intptr_t)userdata);
  8295. while (42) {
  8296. struct timeval timeout;
  8297. int sel_ret;
  8298. fd_set rd;
  8299. char *s;
  8300. int sock;
  8301. if (unlikely(!pool->has_stratum))
  8302. break;
  8303. /* Check to see whether we need to maintain this connection
  8304. * indefinitely or just bring it up when we switch to this
  8305. * pool */
  8306. while (true)
  8307. {
  8308. sock = pool->sock;
  8309. if (sock == INVSOCK)
  8310. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  8311. pool->pool_no);
  8312. else
  8313. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  8314. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  8315. pool->pool_no);
  8316. else
  8317. break;
  8318. suspend_stratum(pool);
  8319. clear_stratum_shares(pool);
  8320. clear_pool_work(pool);
  8321. wait_lpcurrent(pool);
  8322. if (!restart_stratum(pool)) {
  8323. pool_died(pool);
  8324. while (!restart_stratum(pool)) {
  8325. if (pool->removed)
  8326. goto out;
  8327. cgsleep_ms(30000);
  8328. }
  8329. }
  8330. }
  8331. FD_ZERO(&rd);
  8332. FD_SET(sock, &rd);
  8333. timeout.tv_sec = 120;
  8334. timeout.tv_usec = 0;
  8335. /* If we fail to receive any notify messages for 2 minutes we
  8336. * assume the connection has been dropped and treat this pool
  8337. * as dead */
  8338. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  8339. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  8340. s = NULL;
  8341. } else
  8342. s = recv_line(pool);
  8343. if (!s) {
  8344. if (!pool->has_stratum)
  8345. break;
  8346. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  8347. pool->getfail_occasions++;
  8348. total_go++;
  8349. mutex_lock(&pool->stratum_lock);
  8350. pool->stratum_active = pool->stratum_notify = false;
  8351. pool->sock = INVSOCK;
  8352. mutex_unlock(&pool->stratum_lock);
  8353. /* If the socket to our stratum pool disconnects, all
  8354. * submissions need to be discarded or resent. */
  8355. if (!supports_resume(pool))
  8356. clear_stratum_shares(pool);
  8357. else
  8358. resubmit_stratum_shares(pool);
  8359. clear_pool_work(pool);
  8360. if (pool == current_pool())
  8361. restart_threads();
  8362. if (restart_stratum(pool))
  8363. continue;
  8364. shutdown_stratum(pool);
  8365. pool_died(pool);
  8366. break;
  8367. }
  8368. /* Check this pool hasn't died while being a backup pool and
  8369. * has not had its idle flag cleared */
  8370. stratum_resumed(pool);
  8371. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  8372. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  8373. free(s);
  8374. if (pool->swork.clean) {
  8375. struct work *work = make_work();
  8376. /* Generate a single work item to update the current
  8377. * block database */
  8378. pool->swork.clean = false;
  8379. gen_stratum_work(pool, work);
  8380. /* Try to extract block height from coinbase scriptSig */
  8381. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  8382. unsigned char cb_height_sz;
  8383. cb_height_sz = bin_height[-1];
  8384. if (cb_height_sz == 3) {
  8385. // FIXME: The block number will overflow this by AD 2173
  8386. struct mining_goal_info * const goal = pool->goal;
  8387. const void * const prevblkhash = &work->data[4];
  8388. uint32_t height = 0;
  8389. memcpy(&height, bin_height, 3);
  8390. height = le32toh(height);
  8391. have_block_height(goal, prevblkhash, height);
  8392. }
  8393. pool->swork.work_restart_id =
  8394. ++pool->work_restart_id;
  8395. pool_update_work_restart_time(pool);
  8396. if (test_work_current(work)) {
  8397. /* Only accept a work update if this stratum
  8398. * connection is from the current pool */
  8399. struct pool * const cp = current_pool();
  8400. if (pool == cp)
  8401. restart_threads();
  8402. applog(
  8403. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  8404. "Stratum from pool %d requested work update", pool->pool_no);
  8405. } else
  8406. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  8407. free_work(work);
  8408. }
  8409. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  8410. // More than 4 timmills past since requested transactions
  8411. timer_unset(&pool->swork.tv_transparency);
  8412. pool_set_opaque(pool, true);
  8413. }
  8414. }
  8415. out:
  8416. return NULL;
  8417. }
  8418. static void init_stratum_thread(struct pool *pool)
  8419. {
  8420. struct mining_goal_info * const goal = pool->goal;
  8421. goal->have_longpoll = true;
  8422. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  8423. quit(1, "Failed to create stratum thread");
  8424. }
  8425. static void *longpoll_thread(void *userdata);
  8426. static bool stratum_works(struct pool *pool)
  8427. {
  8428. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  8429. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  8430. return false;
  8431. if (pool->stratum_active)
  8432. return true;
  8433. if (!initiate_stratum(pool))
  8434. return false;
  8435. return true;
  8436. }
  8437. static
  8438. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  8439. {
  8440. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  8441. }
  8442. static bool pool_active(struct pool *pool, bool pinging)
  8443. {
  8444. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  8445. bool ret = false;
  8446. json_t *val;
  8447. CURL *curl = NULL;
  8448. int rolltime;
  8449. char *rpc_req;
  8450. struct work *work;
  8451. enum pool_protocol proto;
  8452. if (pool->stratum_init)
  8453. {
  8454. if (pool->stratum_active)
  8455. return true;
  8456. }
  8457. else
  8458. if (!pool->idle)
  8459. {
  8460. timer_set_now(&tv_now);
  8461. if (pool_recently_got_work(pool, &tv_now))
  8462. return true;
  8463. }
  8464. mutex_lock(&pool->pool_test_lock);
  8465. if (pool->stratum_init)
  8466. {
  8467. ret = pool->stratum_active;
  8468. goto out;
  8469. }
  8470. timer_set_now(&tv_now);
  8471. if (pool->idle)
  8472. {
  8473. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  8474. goto out;
  8475. }
  8476. else
  8477. if (pool_recently_got_work(pool, &tv_now))
  8478. {
  8479. ret = true;
  8480. goto out;
  8481. }
  8482. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  8483. /* This is the central point we activate stratum when we can */
  8484. curl = curl_easy_init();
  8485. if (unlikely(!curl)) {
  8486. applog(LOG_ERR, "CURL initialisation failed");
  8487. goto out;
  8488. }
  8489. if (!(want_gbt || want_getwork))
  8490. goto nohttp;
  8491. work = make_work();
  8492. /* Probe for GBT support on first pass */
  8493. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  8494. tryagain:
  8495. rpc_req = prepare_rpc_req_probe(work, proto, NULL, pool);
  8496. work->pool = pool;
  8497. if (!rpc_req)
  8498. goto out;
  8499. pool->probed = false;
  8500. cgtime(&tv_getwork);
  8501. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  8502. true, false, &rolltime, pool, false);
  8503. cgtime(&tv_getwork_reply);
  8504. free(rpc_req);
  8505. /* Detect if a http getwork pool has an X-Stratum header at startup,
  8506. * and if so, switch to that in preference to getwork if it works */
  8507. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  8508. if (!pool->has_stratum) {
  8509. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  8510. if (!pool->rpc_url)
  8511. pool_set_uri(pool, strdup(pool->stratum_url));
  8512. pool->has_stratum = true;
  8513. }
  8514. free_work(work);
  8515. if (val)
  8516. json_decref(val);
  8517. retry_stratum:
  8518. ;
  8519. /* We create the stratum thread for each pool just after
  8520. * successful authorisation. Once the init flag has been set
  8521. * we never unset it and the stratum thread is responsible for
  8522. * setting/unsetting the active flag */
  8523. bool init = pool_tset(pool, &pool->stratum_init);
  8524. if (!init) {
  8525. ret = initiate_stratum(pool) && auth_stratum(pool);
  8526. if (ret)
  8527. {
  8528. detect_algo = 2;
  8529. init_stratum_thread(pool);
  8530. }
  8531. else
  8532. {
  8533. pool_tclear(pool, &pool->stratum_init);
  8534. pool->tv_idle = tv_getwork_reply;
  8535. }
  8536. goto out;
  8537. }
  8538. ret = pool->stratum_active;
  8539. goto out;
  8540. }
  8541. else if (pool->has_stratum)
  8542. shutdown_stratum(pool);
  8543. if (val) {
  8544. bool rc;
  8545. json_t *res;
  8546. res = json_object_get(val, "result");
  8547. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  8548. goto badwork;
  8549. work->rolltime = rolltime;
  8550. rc = work_decode(pool, work, val);
  8551. if (rc) {
  8552. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  8553. pool->pool_no, pool->rpc_url);
  8554. work->pool = pool;
  8555. copy_time(&work->tv_getwork, &tv_getwork);
  8556. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  8557. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  8558. calc_diff(work, 0);
  8559. update_last_work(work);
  8560. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  8561. stage_work(work);
  8562. total_getworks++;
  8563. pool->getwork_requested++;
  8564. ret = true;
  8565. pool->tv_idle = tv_getwork_reply;
  8566. } else {
  8567. badwork:
  8568. json_decref(val);
  8569. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  8570. pool->pool_no, pool->rpc_url);
  8571. pool->proto = proto = pool_protocol_fallback(proto);
  8572. if (PLP_NONE != proto)
  8573. goto tryagain;
  8574. pool->tv_idle = tv_getwork_reply;
  8575. free_work(work);
  8576. goto out;
  8577. }
  8578. json_decref(val);
  8579. if (proto != pool->proto) {
  8580. pool->proto = proto;
  8581. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  8582. }
  8583. if (pool->lp_url)
  8584. goto out;
  8585. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  8586. const struct blktmpl_longpoll_req *lp;
  8587. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  8588. // NOTE: work_decode takes care of lp id
  8589. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  8590. if (!pool->lp_url)
  8591. {
  8592. ret = false;
  8593. goto out;
  8594. }
  8595. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  8596. }
  8597. else
  8598. if (pool->hdr_path && want_getwork) {
  8599. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  8600. if (!pool->lp_url)
  8601. {
  8602. ret = false;
  8603. goto out;
  8604. }
  8605. pool->lp_proto = PLP_GETWORK;
  8606. } else
  8607. pool->lp_url = NULL;
  8608. if (want_longpoll && !pool->lp_started) {
  8609. pool->lp_started = true;
  8610. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8611. quit(1, "Failed to create pool longpoll thread");
  8612. }
  8613. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  8614. pool->proto = proto;
  8615. goto tryagain;
  8616. } else {
  8617. pool->tv_idle = tv_getwork_reply;
  8618. free_work(work);
  8619. nohttp:
  8620. /* If we failed to parse a getwork, this could be a stratum
  8621. * url without the prefix stratum+tcp:// so let's check it */
  8622. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  8623. pool->has_stratum = true;
  8624. goto retry_stratum;
  8625. }
  8626. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  8627. pool->pool_no, pool->rpc_url);
  8628. if (!pinging)
  8629. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  8630. }
  8631. out:
  8632. if (curl)
  8633. curl_easy_cleanup(curl);
  8634. mutex_unlock(&pool->pool_test_lock);
  8635. return ret;
  8636. }
  8637. static void pool_resus(struct pool *pool)
  8638. {
  8639. if (pool->enabled == POOL_ENABLED && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  8640. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  8641. else
  8642. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8643. }
  8644. static
  8645. void *cmd_idle_thread(void * const __maybe_unused userp)
  8646. {
  8647. pthread_detach(pthread_self());
  8648. RenameThread("cmd-idle");
  8649. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8650. sleep(opt_log_interval);
  8651. pthread_testcancel();
  8652. run_cmd(cmd_idle);
  8653. return NULL;
  8654. }
  8655. static struct work *hash_pop(struct cgpu_info * const proc)
  8656. {
  8657. int hc;
  8658. struct work *work, *work_found, *tmp;
  8659. enum {
  8660. HPWS_NONE = 0,
  8661. HPWS_LOWDIFF = 1,
  8662. HPWS_ROLLABLE = 2,
  8663. HPWS_PERFECT = 3,
  8664. } work_score = HPWS_NONE;
  8665. bool did_cmd_idle = false;
  8666. pthread_t cmd_idle_thr;
  8667. retry:
  8668. mutex_lock(stgd_lock);
  8669. while (true)
  8670. {
  8671. work_found = NULL;
  8672. work_score = 0;
  8673. hc = HASH_COUNT(staged_work);
  8674. HASH_ITER(hh, staged_work, work, tmp)
  8675. {
  8676. const struct mining_algorithm * const work_malgo = work_mining_algorithm(work);
  8677. const float min_nonce_diff = drv_min_nonce_diff(proc->drv, proc, work_malgo);
  8678. if (min_nonce_diff < work->work_difficulty)
  8679. {
  8680. if (unlikely(min_nonce_diff >= 0 && work_score < HPWS_LOWDIFF))
  8681. {
  8682. work_found = work;
  8683. work_score = HPWS_LOWDIFF;
  8684. }
  8685. continue;
  8686. }
  8687. if (work->rolltime && hc > staged_rollable)
  8688. {
  8689. if (work_score < HPWS_ROLLABLE)
  8690. {
  8691. work_found = work;
  8692. work_score = HPWS_ROLLABLE;
  8693. }
  8694. continue;
  8695. }
  8696. // Good match
  8697. work_found = work;
  8698. work_score = HPWS_PERFECT;
  8699. break;
  8700. }
  8701. if (work_found)
  8702. {
  8703. work = work_found;
  8704. break;
  8705. }
  8706. // Failed to get a usable work
  8707. if (unlikely(staged_full))
  8708. {
  8709. if (likely(opt_queue < 10 + mining_threads))
  8710. {
  8711. ++opt_queue;
  8712. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  8713. }
  8714. else
  8715. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  8716. staged_full = false; // Let it fill up before triggering an underrun again
  8717. no_work = true;
  8718. }
  8719. pthread_cond_signal(&gws_cond);
  8720. if (cmd_idle && !did_cmd_idle)
  8721. {
  8722. if (likely(!pthread_create(&cmd_idle_thr, NULL, cmd_idle_thread, NULL)))
  8723. did_cmd_idle = true;
  8724. }
  8725. pthread_cond_wait(&getq->cond, stgd_lock);
  8726. }
  8727. if (did_cmd_idle)
  8728. pthread_cancel(cmd_idle_thr);
  8729. no_work = false;
  8730. if (can_roll(work) && should_roll(work))
  8731. {
  8732. // Instead of consuming it, force it to be cloned and grab the clone
  8733. mutex_unlock(stgd_lock);
  8734. clone_available();
  8735. goto retry;
  8736. }
  8737. unstage_work(work);
  8738. /* Signal the getwork scheduler to look for more work */
  8739. pthread_cond_signal(&gws_cond);
  8740. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  8741. pthread_cond_signal(&getq->cond);
  8742. mutex_unlock(stgd_lock);
  8743. work->pool->last_work_time = time(NULL);
  8744. cgtime(&work->pool->tv_last_work_time);
  8745. return work;
  8746. }
  8747. /* Clones work by rolling it if possible, and returning a clone instead of the
  8748. * original work item which gets staged again to possibly be rolled again in
  8749. * the future */
  8750. static struct work *clone_work(struct work *work)
  8751. {
  8752. int mrs = mining_threads + opt_queue - total_staged();
  8753. struct work *work_clone;
  8754. bool cloned;
  8755. if (mrs < 1)
  8756. return work;
  8757. cloned = false;
  8758. work_clone = make_clone(work);
  8759. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  8760. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  8761. stage_work(work_clone);
  8762. roll_work(work);
  8763. work_clone = make_clone(work);
  8764. /* Roll it again to prevent duplicates should this be used
  8765. * directly later on */
  8766. roll_work(work);
  8767. cloned = true;
  8768. }
  8769. if (cloned) {
  8770. stage_work(work);
  8771. return work_clone;
  8772. }
  8773. free_work(work_clone);
  8774. return work;
  8775. }
  8776. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  8777. {
  8778. unsigned char hash1[32];
  8779. sha256(data, len, hash1);
  8780. sha256(hash1, 32, hash);
  8781. }
  8782. /* PDiff 1 is a 256 bit unsigned integer of
  8783. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  8784. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  8785. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  8786. static void pdiff_target_leadzero(void * const target_p, double diff)
  8787. {
  8788. uint8_t *target = target_p;
  8789. diff *= 0x100000000;
  8790. int skip = log2(diff) / 8;
  8791. if (skip)
  8792. {
  8793. if (skip > 0x1c)
  8794. skip = 0x1c;
  8795. diff /= pow(0x100, skip);
  8796. memset(target, 0, skip);
  8797. }
  8798. uint32_t n = 0xffffffff;
  8799. n = (double)n / diff;
  8800. n = htobe32(n);
  8801. memcpy(&target[skip], &n, sizeof(n));
  8802. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  8803. }
  8804. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  8805. {
  8806. unsigned char rtarget[32];
  8807. pdiff_target_leadzero(rtarget, pdiff);
  8808. swab256(dest_target, rtarget);
  8809. if (opt_debug) {
  8810. char htarget[65];
  8811. bin2hex(htarget, rtarget, 32);
  8812. applog(LOG_DEBUG, "Generated target %s", htarget);
  8813. }
  8814. }
  8815. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  8816. {
  8817. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  8818. }
  8819. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  8820. {
  8821. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  8822. int off;
  8823. void (*func)(void *, double) = funcp;
  8824. func(little_endian ? bufr : buf, diff);
  8825. if (little_endian)
  8826. swab256(buf, bufr);
  8827. swap32tobe(expect, expectp, 256/32);
  8828. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8829. for (off = 0; off < 28 && !buf[off]; ++off)
  8830. {}
  8831. if (memcmp(&buf[off], &expect[off], 4))
  8832. {
  8833. testfail: ;
  8834. ++unittest_failures;
  8835. char hexbuf[65], expectbuf[65];
  8836. bin2hex(hexbuf, buf, 32);
  8837. bin2hex(expectbuf, expect, 32);
  8838. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8839. funcname, diff, hexbuf, expectbuf);
  8840. }
  8841. if (!little_endian)
  8842. swab256(bufr, buf);
  8843. swab256(expectr, expect);
  8844. if (!hash_target_check(expectr, bufr))
  8845. goto testfail;
  8846. }
  8847. #define TEST_TARGET(func, le, expect, diff) \
  8848. _test_target(func, #func, le, expect, diff)
  8849. void test_target()
  8850. {
  8851. uint32_t expect[8] = {0};
  8852. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8853. expect[0] = 0x0000ffff;
  8854. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8855. expect[0] = 0;
  8856. expect[1] = 0xffff0000;
  8857. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8858. expect[1] >>= 1;
  8859. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8860. expect[1] >>= 3;
  8861. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8862. expect[1] >>= 4;
  8863. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8864. memset(&expect[1], '\xff', 28);
  8865. expect[0] = 0x0000ffff;
  8866. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8867. expect[0] = 0;
  8868. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8869. expect[1] >>= 1;
  8870. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8871. expect[1] >>= 3;
  8872. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8873. expect[1] >>= 4;
  8874. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8875. }
  8876. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8877. {
  8878. *dst = *src;
  8879. if (dst->tr)
  8880. tmpl_incref(dst->tr);
  8881. dst->nonce1 = maybe_strdup(src->nonce1);
  8882. dst->job_id = maybe_strdup(src->job_id);
  8883. bytes_cpy(&dst->coinbase, &src->coinbase);
  8884. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8885. }
  8886. void stratum_work_clean(struct stratum_work * const swork)
  8887. {
  8888. if (swork->tr)
  8889. tmpl_decref(swork->tr);
  8890. free(swork->nonce1);
  8891. free(swork->job_id);
  8892. bytes_free(&swork->coinbase);
  8893. bytes_free(&swork->merkle_bin);
  8894. }
  8895. bool pool_has_usable_swork(const struct pool * const pool)
  8896. {
  8897. if (opt_benchmark)
  8898. return true;
  8899. if (pool->swork.tr)
  8900. {
  8901. // GBT
  8902. struct timeval tv_now;
  8903. timer_set_now(&tv_now);
  8904. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8905. }
  8906. return pool->stratum_notify;
  8907. }
  8908. /* Generates stratum based work based on the most recent notify information
  8909. * from the pool. This will keep generating work while a pool is down so we use
  8910. * other means to detect when the pool has died in stratum_thread */
  8911. static void gen_stratum_work(struct pool *pool, struct work *work)
  8912. {
  8913. clean_work(work);
  8914. cg_wlock(&pool->data_lock);
  8915. pool->swork.data_lock_p = &pool->data_lock;
  8916. const int n2size = pool->swork.n2size;
  8917. bytes_resize(&work->nonce2, n2size);
  8918. if (pool->nonce2sz < n2size)
  8919. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8920. memcpy(bytes_buf(&work->nonce2),
  8921. #ifdef WORDS_BIGENDIAN
  8922. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8923. &((char*)&pool->nonce2)[pool->nonce2off],
  8924. #else
  8925. &pool->nonce2,
  8926. #endif
  8927. pool->nonce2sz);
  8928. pool->nonce2++;
  8929. work->pool = pool;
  8930. work->work_restart_id = pool->swork.work_restart_id;
  8931. gen_stratum_work2(work, &pool->swork);
  8932. cgtime(&work->tv_staged);
  8933. }
  8934. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8935. {
  8936. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8937. uint8_t *merkle_bin;
  8938. uint32_t *data32, *swap32;
  8939. int i;
  8940. /* Generate coinbase */
  8941. coinbase = bytes_buf(&swork->coinbase);
  8942. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8943. /* Downgrade to a read lock to read off the variables */
  8944. if (swork->data_lock_p)
  8945. cg_dwlock(swork->data_lock_p);
  8946. /* Generate merkle root */
  8947. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8948. memcpy(merkle_sha, merkle_root, 32);
  8949. merkle_bin = bytes_buf(&swork->merkle_bin);
  8950. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8951. memcpy(merkle_sha + 32, merkle_bin, 32);
  8952. gen_hash(merkle_sha, merkle_root, 64);
  8953. memcpy(merkle_sha, merkle_root, 32);
  8954. }
  8955. data32 = (uint32_t *)merkle_sha;
  8956. swap32 = (uint32_t *)merkle_root;
  8957. flip32(swap32, data32);
  8958. memcpy(&work->data[0], swork->header1, 36);
  8959. memcpy(&work->data[36], merkle_root, 32);
  8960. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8961. memcpy(&work->data[72], swork->diffbits, 4);
  8962. memset(&work->data[76], 0, 4); // nonce
  8963. memcpy(&work->data[80], workpadding_bin, 48);
  8964. work->ntime_roll_limits = swork->ntime_roll_limits;
  8965. /* Copy parameters required for share submission */
  8966. memcpy(work->target, swork->target, sizeof(work->target));
  8967. work->job_id = maybe_strdup(swork->job_id);
  8968. work->nonce1 = maybe_strdup(swork->nonce1);
  8969. if (swork->data_lock_p)
  8970. cg_runlock(swork->data_lock_p);
  8971. if (opt_debug)
  8972. {
  8973. char header[161];
  8974. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8975. bin2hex(header, work->data, 80);
  8976. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8977. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8978. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8979. }
  8980. calc_midstate(work);
  8981. local_work++;
  8982. work->stratum = true;
  8983. work->blk.nonce = 0;
  8984. work->id = total_work++;
  8985. work->longpoll = false;
  8986. work->getwork_mode = GETWORK_MODE_STRATUM;
  8987. calc_diff(work, 0);
  8988. }
  8989. void request_work(struct thr_info *thr)
  8990. {
  8991. struct cgpu_info *cgpu = thr->cgpu;
  8992. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8993. /* Tell the watchdog thread this thread is waiting on getwork and
  8994. * should not be restarted */
  8995. thread_reportout(thr);
  8996. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8997. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8998. {
  8999. if (proc->threads)
  9000. break;
  9001. thread_reportout(proc->thr[0]);
  9002. }
  9003. cgtime(&dev_stats->_get_start);
  9004. }
  9005. // FIXME: Make this non-blocking (and remove HACK above)
  9006. struct work *get_work(struct thr_info *thr)
  9007. {
  9008. const int thr_id = thr->id;
  9009. struct cgpu_info *cgpu = thr->cgpu;
  9010. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  9011. struct cgminer_stats *pool_stats;
  9012. struct timeval tv_get;
  9013. struct work *work = NULL;
  9014. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  9015. while (!work) {
  9016. work = hash_pop(cgpu);
  9017. if (stale_work(work, false)) {
  9018. staged_full = false; // It wasn't really full, since it was stale :(
  9019. discard_work(work);
  9020. work = NULL;
  9021. wake_gws();
  9022. }
  9023. }
  9024. last_getwork = time(NULL);
  9025. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  9026. cgpu->proc_repr, work->id, thr_id);
  9027. work->thr_id = thr_id;
  9028. thread_reportin(thr);
  9029. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  9030. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  9031. {
  9032. if (proc->threads)
  9033. break;
  9034. thread_reportin(proc->thr[0]);
  9035. }
  9036. work->mined = true;
  9037. work->blk.nonce = 0;
  9038. cgtime(&tv_get);
  9039. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  9040. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  9041. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  9042. dev_stats->getwork_wait_max = tv_get;
  9043. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  9044. dev_stats->getwork_wait_min = tv_get;
  9045. ++dev_stats->getwork_calls;
  9046. pool_stats = &(work->pool->cgminer_stats);
  9047. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  9048. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  9049. pool_stats->getwork_wait_max = tv_get;
  9050. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  9051. pool_stats->getwork_wait_min = tv_get;
  9052. ++pool_stats->getwork_calls;
  9053. if (work->work_difficulty < 1)
  9054. {
  9055. const float min_nonce_diff = drv_min_nonce_diff(cgpu->drv, cgpu, work_mining_algorithm(work));
  9056. if (unlikely(work->work_difficulty < min_nonce_diff))
  9057. {
  9058. if (min_nonce_diff - work->work_difficulty > 1./0x10000000)
  9059. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  9060. cgpu->proc_repr);
  9061. work->nonce_diff = min_nonce_diff;
  9062. }
  9063. else
  9064. work->nonce_diff = work->work_difficulty;
  9065. }
  9066. else
  9067. work->nonce_diff = 1;
  9068. return work;
  9069. }
  9070. struct dupe_hash_elem {
  9071. uint8_t hash[0x20];
  9072. struct timeval tv_prune;
  9073. UT_hash_handle hh;
  9074. };
  9075. static
  9076. void _submit_work_async(struct work *work)
  9077. {
  9078. applog(LOG_DEBUG, "Pushing submit work to work thread");
  9079. if (opt_benchmark)
  9080. {
  9081. json_t * const jn = json_null(), *result = NULL;
  9082. work_check_for_block(work);
  9083. {
  9084. static struct dupe_hash_elem *dupe_hashes;
  9085. struct dupe_hash_elem *dhe, *dhetmp;
  9086. HASH_FIND(hh, dupe_hashes, &work->hash, sizeof(dhe->hash), dhe);
  9087. if (dhe)
  9088. result = json_string("duplicate");
  9089. else
  9090. {
  9091. struct timeval tv_now;
  9092. timer_set_now(&tv_now);
  9093. // Prune old entries
  9094. HASH_ITER(hh, dupe_hashes, dhe, dhetmp)
  9095. {
  9096. if (!timer_passed(&dhe->tv_prune, &tv_now))
  9097. break;
  9098. HASH_DEL(dupe_hashes, dhe);
  9099. free(dhe);
  9100. }
  9101. dhe = malloc(sizeof(*dhe));
  9102. memcpy(dhe->hash, work->hash, sizeof(dhe->hash));
  9103. timer_set_delay(&dhe->tv_prune, &tv_now, 337500000);
  9104. HASH_ADD(hh, dupe_hashes, hash, sizeof(dhe->hash), dhe);
  9105. }
  9106. }
  9107. if (result)
  9108. {}
  9109. else
  9110. if (stale_work(work, true))
  9111. {
  9112. char stalemsg[0x10];
  9113. snprintf(stalemsg, sizeof(stalemsg), "stale %us", benchmark_update_interval * (work->pool->work_restart_id - work->work_restart_id));
  9114. result = json_string(stalemsg);
  9115. }
  9116. else
  9117. result = json_incref(jn);
  9118. share_result(jn, result, jn, work, false, "");
  9119. free_work(work);
  9120. json_decref(result);
  9121. json_decref(jn);
  9122. return;
  9123. }
  9124. mutex_lock(&submitting_lock);
  9125. ++total_submitting;
  9126. DL_APPEND(submit_waiting, work);
  9127. mutex_unlock(&submitting_lock);
  9128. notifier_wake(submit_waiting_notifier);
  9129. }
  9130. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  9131. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  9132. {
  9133. if (tv_work_found)
  9134. copy_time(&work->tv_work_found, tv_work_found);
  9135. _submit_work_async(work);
  9136. }
  9137. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  9138. {
  9139. struct cgpu_info * const cgpu = thr->cgpu;
  9140. if (bad_nonce_p)
  9141. {
  9142. if (bad_nonce_p == UNKNOWN_NONCE)
  9143. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  9144. cgpu->proc_repr);
  9145. else
  9146. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  9147. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  9148. }
  9149. mutex_lock(&stats_lock);
  9150. hw_errors++;
  9151. ++cgpu->hw_errors;
  9152. if (bad_nonce_p)
  9153. {
  9154. total_bad_diff1 += nonce_diff;
  9155. cgpu->bad_diff1 += nonce_diff;
  9156. }
  9157. mutex_unlock(&stats_lock);
  9158. if (thr->cgpu->drv->hw_error)
  9159. thr->cgpu->drv->hw_error(thr);
  9160. }
  9161. void work_hash(struct work * const work)
  9162. {
  9163. const struct mining_algorithm * const malgo = work_mining_algorithm(work);
  9164. malgo->hash_data_f(work->hash, work->data);
  9165. }
  9166. static
  9167. bool test_hash(const void * const phash, const float diff)
  9168. {
  9169. const uint32_t * const hash = phash;
  9170. if (diff >= 1.)
  9171. // FIXME: > 1 should check more
  9172. return !hash[7];
  9173. const uint32_t Htarg = (uint32_t)ceil((1. / diff) - 1);
  9174. const uint32_t tmp_hash7 = le32toh(hash[7]);
  9175. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  9176. (long unsigned int)Htarg,
  9177. (long unsigned int)tmp_hash7);
  9178. return (tmp_hash7 <= Htarg);
  9179. }
  9180. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  9181. {
  9182. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9183. *work_nonce = htole32(nonce);
  9184. work_hash(work);
  9185. if (!test_hash(work->hash, work->nonce_diff))
  9186. return TNR_BAD;
  9187. if (checktarget && !hash_target_check_v(work->hash, work->target))
  9188. {
  9189. bool high_hash = true;
  9190. struct pool * const pool = work->pool;
  9191. if (pool->stratum_active)
  9192. {
  9193. // 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
  9194. if (memcmp(pool->next_target, work->target, sizeof(work->target)))
  9195. {
  9196. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  9197. pool->pool_no);
  9198. if (hash_target_check_v(work->hash, pool->next_target))
  9199. high_hash = false;
  9200. }
  9201. }
  9202. if (high_hash)
  9203. return TNR_HIGH;
  9204. }
  9205. return TNR_GOOD;
  9206. }
  9207. /* Returns true if nonce for work was a valid share */
  9208. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  9209. {
  9210. return submit_noffset_nonce(thr, work, nonce, 0);
  9211. }
  9212. /* Allows drivers to submit work items where the driver has changed the ntime
  9213. * value by noffset. Must be only used with a work protocol that does not ntime
  9214. * roll itself intrinsically to generate work (eg stratum). We do not touch
  9215. * the original work struct, but the copy of it only. */
  9216. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  9217. int noffset)
  9218. {
  9219. struct work *work = make_work();
  9220. _copy_work(work, work_in, noffset);
  9221. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  9222. struct timeval tv_work_found;
  9223. enum test_nonce2_result res;
  9224. bool ret = true;
  9225. thread_reportout(thr);
  9226. cgtime(&tv_work_found);
  9227. *work_nonce = htole32(nonce);
  9228. work->thr_id = thr->id;
  9229. /* Do one last check before attempting to submit the work */
  9230. /* Side effect: sets work->data and work->hash for us */
  9231. res = test_nonce2(work, nonce);
  9232. if (unlikely(res == TNR_BAD))
  9233. {
  9234. inc_hw_errors(thr, work, nonce);
  9235. ret = false;
  9236. goto out;
  9237. }
  9238. mutex_lock(&stats_lock);
  9239. total_diff1 += work->nonce_diff;
  9240. thr ->cgpu->diff1 += work->nonce_diff;
  9241. work->pool->diff1 += work->nonce_diff;
  9242. thr->cgpu->last_device_valid_work = time(NULL);
  9243. mutex_unlock(&stats_lock);
  9244. if (noncelog_file)
  9245. noncelog(work);
  9246. if (res == TNR_HIGH)
  9247. {
  9248. // Share above target, normal
  9249. /* Check the diff of the share, even if it didn't reach the
  9250. * target, just to set the best share value if it's higher. */
  9251. share_diff(work);
  9252. goto out;
  9253. }
  9254. submit_work_async2(work, &tv_work_found);
  9255. work = NULL; // Taken by submit_work_async2
  9256. out:
  9257. if (work)
  9258. free_work(work);
  9259. thread_reportin(thr);
  9260. return ret;
  9261. }
  9262. // return true of we should stop working on this piece of work
  9263. // returning false means we will keep scanning for a nonce
  9264. // assumptions: work->blk.nonce is the number of nonces completed in the work
  9265. // see minerloop_scanhash comments for more details & usage
  9266. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t max_hashes)
  9267. {
  9268. if (work->blk.nonce == 0xffffffff || // known we are scanning a full nonce range
  9269. wdiff->tv_sec > opt_scantime || // scan-time has elapsed (user specified, default 60s)
  9270. work->blk.nonce >= 0xfffffffe - max_hashes || // are there enough nonces left in the work
  9271. max_hashes >= 0xfffffffe || // assume we are scanning a full nonce range
  9272. stale_work(work, false)) // work is stale
  9273. return true;
  9274. return false;
  9275. }
  9276. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  9277. {
  9278. struct cgpu_info *proc = thr->cgpu;
  9279. if (proc->threads > 1)
  9280. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  9281. else
  9282. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  9283. }
  9284. // Called by asynchronous minerloops, when they find their processor should be disabled
  9285. void mt_disable_start(struct thr_info *mythr)
  9286. {
  9287. struct cgpu_info *cgpu = mythr->cgpu;
  9288. struct device_drv *drv = cgpu->drv;
  9289. if (drv->thread_disable)
  9290. drv->thread_disable(mythr);
  9291. hashmeter2(mythr);
  9292. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  9293. mythr->rolling = mythr->cgpu->rolling = 0;
  9294. thread_reportout(mythr);
  9295. mythr->_mt_disable_called = true;
  9296. }
  9297. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  9298. * the driver tells us it's full so that it may extract the work item using
  9299. * the get_queued() function which adds it to the hashtable on
  9300. * cgpu->queued_work. */
  9301. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  9302. {
  9303. thread_reportout(mythr);
  9304. do {
  9305. bool need_work;
  9306. /* Do this lockless just to know if we need more unqueued work. */
  9307. need_work = (!cgpu->unqueued_work);
  9308. /* get_work is a blocking function so do it outside of lock
  9309. * to prevent deadlocks with other locks. */
  9310. if (need_work) {
  9311. struct work *work = get_work(mythr);
  9312. wr_lock(&cgpu->qlock);
  9313. /* Check we haven't grabbed work somehow between
  9314. * checking and picking up the lock. */
  9315. if (likely(!cgpu->unqueued_work))
  9316. cgpu->unqueued_work = work;
  9317. else
  9318. need_work = false;
  9319. wr_unlock(&cgpu->qlock);
  9320. if (unlikely(!need_work))
  9321. discard_work(work);
  9322. }
  9323. /* The queue_full function should be used by the driver to
  9324. * actually place work items on the physical device if it
  9325. * does have a queue. */
  9326. } while (drv->queue_full && !drv->queue_full(cgpu));
  9327. }
  9328. /* Add a work item to a cgpu's queued hashlist */
  9329. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  9330. {
  9331. cgpu->queued_count++;
  9332. HASH_ADD_INT(cgpu->queued_work, id, work);
  9333. }
  9334. /* This function is for retrieving one work item from the unqueued pointer and
  9335. * adding it to the hashtable of queued work. Code using this function must be
  9336. * able to handle NULL as a return which implies there is no work available. */
  9337. struct work *get_queued(struct cgpu_info *cgpu)
  9338. {
  9339. struct work *work = NULL;
  9340. wr_lock(&cgpu->qlock);
  9341. if (cgpu->unqueued_work) {
  9342. work = cgpu->unqueued_work;
  9343. if (unlikely(stale_work(work, false))) {
  9344. discard_work(work);
  9345. work = NULL;
  9346. wake_gws();
  9347. } else
  9348. __add_queued(cgpu, work);
  9349. cgpu->unqueued_work = NULL;
  9350. }
  9351. wr_unlock(&cgpu->qlock);
  9352. return work;
  9353. }
  9354. void add_queued(struct cgpu_info *cgpu, struct work *work)
  9355. {
  9356. wr_lock(&cgpu->qlock);
  9357. __add_queued(cgpu, work);
  9358. wr_unlock(&cgpu->qlock);
  9359. }
  9360. /* Get fresh work and add it to cgpu's queued hashlist */
  9361. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  9362. {
  9363. struct work *work = get_work(thr);
  9364. add_queued(cgpu, work);
  9365. return work;
  9366. }
  9367. /* This function is for finding an already queued work item in the
  9368. * given que hashtable. Code using this function must be able
  9369. * to handle NULL as a return which implies there is no matching work.
  9370. * The calling function must lock access to the que if it is required.
  9371. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9372. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9373. {
  9374. struct work *work, *tmp, *ret = NULL;
  9375. HASH_ITER(hh, que, work, tmp) {
  9376. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  9377. memcmp(work->data + offset, data, datalen) == 0) {
  9378. ret = work;
  9379. break;
  9380. }
  9381. }
  9382. return ret;
  9383. }
  9384. /* This function is for finding an already queued work item in the
  9385. * device's queued_work hashtable. Code using this function must be able
  9386. * to handle NULL as a return which implies there is no matching work.
  9387. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  9388. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9389. {
  9390. struct work *ret;
  9391. rd_lock(&cgpu->qlock);
  9392. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9393. rd_unlock(&cgpu->qlock);
  9394. return ret;
  9395. }
  9396. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9397. {
  9398. struct work *work, *ret = NULL;
  9399. rd_lock(&cgpu->qlock);
  9400. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9401. if (work)
  9402. ret = copy_work(work);
  9403. rd_unlock(&cgpu->qlock);
  9404. return ret;
  9405. }
  9406. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  9407. {
  9408. cgpu->queued_count--;
  9409. HASH_DEL(cgpu->queued_work, work);
  9410. }
  9411. /* This iterates over a queued hashlist finding work started more than secs
  9412. * seconds ago and discards the work as completed. The driver must set the
  9413. * work->tv_work_start value appropriately. Returns the number of items aged. */
  9414. int age_queued_work(struct cgpu_info *cgpu, double secs)
  9415. {
  9416. struct work *work, *tmp;
  9417. struct timeval tv_now;
  9418. int aged = 0;
  9419. cgtime(&tv_now);
  9420. wr_lock(&cgpu->qlock);
  9421. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  9422. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  9423. __work_completed(cgpu, work);
  9424. aged++;
  9425. }
  9426. }
  9427. wr_unlock(&cgpu->qlock);
  9428. return aged;
  9429. }
  9430. /* This function should be used by queued device drivers when they're sure
  9431. * the work struct is no longer in use. */
  9432. void work_completed(struct cgpu_info *cgpu, struct work *work)
  9433. {
  9434. wr_lock(&cgpu->qlock);
  9435. __work_completed(cgpu, work);
  9436. wr_unlock(&cgpu->qlock);
  9437. free_work(work);
  9438. }
  9439. /* Combines find_queued_work_bymidstate and work_completed in one function
  9440. * withOUT destroying the work so the driver must free it. */
  9441. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  9442. {
  9443. struct work *work;
  9444. wr_lock(&cgpu->qlock);
  9445. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  9446. if (work)
  9447. __work_completed(cgpu, work);
  9448. wr_unlock(&cgpu->qlock);
  9449. return work;
  9450. }
  9451. void flush_queue(struct cgpu_info *cgpu)
  9452. {
  9453. struct work *work = NULL;
  9454. wr_lock(&cgpu->qlock);
  9455. work = cgpu->unqueued_work;
  9456. cgpu->unqueued_work = NULL;
  9457. wr_unlock(&cgpu->qlock);
  9458. if (work) {
  9459. free_work(work);
  9460. applog(LOG_DEBUG, "Discarded queued work item");
  9461. }
  9462. }
  9463. /* This version of hash work is for devices that are fast enough to always
  9464. * perform a full nonce range and need a queue to maintain the device busy.
  9465. * Work creation and destruction is not done from within this function
  9466. * directly. */
  9467. void hash_queued_work(struct thr_info *mythr)
  9468. {
  9469. const long cycle = opt_log_interval / 5 ? : 1;
  9470. struct timeval tv_start = {0, 0}, tv_end;
  9471. struct cgpu_info *cgpu = mythr->cgpu;
  9472. struct device_drv *drv = cgpu->drv;
  9473. const int thr_id = mythr->id;
  9474. int64_t hashes_done = 0;
  9475. if (unlikely(cgpu->deven != DEV_ENABLED))
  9476. mt_disable(mythr);
  9477. while (likely(!cgpu->shutdown)) {
  9478. struct timeval diff;
  9479. int64_t hashes;
  9480. fill_queue(mythr, cgpu, drv, thr_id);
  9481. thread_reportin(mythr);
  9482. hashes = drv->scanwork(mythr);
  9483. /* Reset the bool here in case the driver looks for it
  9484. * synchronously in the scanwork loop. */
  9485. mythr->work_restart = false;
  9486. if (unlikely(hashes == -1 )) {
  9487. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  9488. cgpu->deven = DEV_DISABLED;
  9489. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  9490. mt_disable(mythr);
  9491. }
  9492. hashes_done += hashes;
  9493. cgtime(&tv_end);
  9494. timersub(&tv_end, &tv_start, &diff);
  9495. if (diff.tv_sec >= cycle) {
  9496. hashmeter(thr_id, &diff, hashes_done);
  9497. hashes_done = 0;
  9498. copy_time(&tv_start, &tv_end);
  9499. }
  9500. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  9501. mt_disable(mythr);
  9502. if (unlikely(mythr->work_restart)) {
  9503. flush_queue(cgpu);
  9504. if (drv->flush_work)
  9505. drv->flush_work(cgpu);
  9506. }
  9507. }
  9508. // cgpu->deven = DEV_DISABLED; set in miner_thread
  9509. }
  9510. // Called by minerloop, when it is re-enabling a processor
  9511. void mt_disable_finish(struct thr_info *mythr)
  9512. {
  9513. struct device_drv *drv = mythr->cgpu->drv;
  9514. thread_reportin(mythr);
  9515. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  9516. if (drv->thread_enable)
  9517. drv->thread_enable(mythr);
  9518. mythr->_mt_disable_called = false;
  9519. }
  9520. // Called by synchronous minerloops, when they find their processor should be disabled
  9521. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  9522. void mt_disable(struct thr_info *mythr)
  9523. {
  9524. const struct cgpu_info * const cgpu = mythr->cgpu;
  9525. mt_disable_start(mythr);
  9526. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  9527. do {
  9528. notifier_read(mythr->notifier);
  9529. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  9530. mt_disable_finish(mythr);
  9531. }
  9532. enum {
  9533. STAT_SLEEP_INTERVAL = 1,
  9534. STAT_CTR_INTERVAL = 10000000,
  9535. FAILURE_INTERVAL = 30,
  9536. };
  9537. /* Stage another work item from the work returned in a longpoll */
  9538. 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)
  9539. {
  9540. bool rc;
  9541. work->rolltime = rolltime;
  9542. rc = work_decode(pool, work, val);
  9543. if (unlikely(!rc)) {
  9544. applog(LOG_ERR, "Could not convert longpoll data to work");
  9545. free_work(work);
  9546. return;
  9547. }
  9548. total_getworks++;
  9549. pool->getwork_requested++;
  9550. work->pool = pool;
  9551. copy_time(&work->tv_getwork, tv_lp);
  9552. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  9553. calc_diff(work, 0);
  9554. if (pool->enabled == POOL_REJECTING)
  9555. work->mandatory = true;
  9556. work->longpoll = true;
  9557. work->getwork_mode = GETWORK_MODE_LP;
  9558. update_last_work(work);
  9559. /* We'll be checking this work item twice, but we already know it's
  9560. * from a new block so explicitly force the new block detection now
  9561. * rather than waiting for it to hit the stage thread. This also
  9562. * allows testwork to know whether LP discovered the block or not. */
  9563. test_work_current(work);
  9564. /* Don't use backup LPs as work if we have failover-only enabled. Use
  9565. * the longpoll work from a pool that has been rejecting shares as a
  9566. * way to detect when the pool has recovered.
  9567. */
  9568. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  9569. free_work(work);
  9570. return;
  9571. }
  9572. work = clone_work(work);
  9573. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  9574. stage_work(work);
  9575. applog(LOG_DEBUG, "Converted longpoll data to work");
  9576. }
  9577. /* If we want longpoll, enable it for the chosen default pool, or, if
  9578. * the pool does not support longpoll, find the first one that does
  9579. * and use its longpoll support */
  9580. static
  9581. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  9582. {
  9583. int i;
  9584. if (func(cp))
  9585. return cp;
  9586. for (i = 0; i < total_pools; i++) {
  9587. struct pool *pool = pools[i];
  9588. if (cp->goal != pool->goal)
  9589. continue;
  9590. if (func(pool))
  9591. return pool;
  9592. }
  9593. return NULL;
  9594. }
  9595. /* This will make the longpoll thread wait till it's the current pool, or it
  9596. * has been flagged as rejecting, before attempting to open any connections.
  9597. */
  9598. static void wait_lpcurrent(struct pool *pool)
  9599. {
  9600. mutex_lock(&lp_lock);
  9601. while (!cnx_needed(pool))
  9602. {
  9603. pool->lp_active = false;
  9604. pthread_cond_wait(&lp_cond, &lp_lock);
  9605. }
  9606. mutex_unlock(&lp_lock);
  9607. }
  9608. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  9609. struct pool *pool = vpool;
  9610. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  9611. pool->lp_socket = sock;
  9612. return sock;
  9613. }
  9614. static void *longpoll_thread(void *userdata)
  9615. {
  9616. struct pool *cp = (struct pool *)userdata;
  9617. /* This *pool is the source of the actual longpoll, not the pool we've
  9618. * tied it to */
  9619. struct timeval start, reply, end;
  9620. struct pool *pool = NULL;
  9621. char threadname[20];
  9622. CURL *curl = NULL;
  9623. int failures = 0;
  9624. char *lp_url;
  9625. int rolltime;
  9626. #ifndef HAVE_PTHREAD_CANCEL
  9627. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9628. #endif
  9629. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  9630. RenameThread(threadname);
  9631. curl = curl_easy_init();
  9632. if (unlikely(!curl)) {
  9633. applog(LOG_ERR, "CURL initialisation failed");
  9634. return NULL;
  9635. }
  9636. retry_pool:
  9637. pool = select_longpoll_pool(cp);
  9638. if (!pool) {
  9639. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  9640. while (!pool) {
  9641. cgsleep_ms(60000);
  9642. pool = select_longpoll_pool(cp);
  9643. }
  9644. }
  9645. if (pool->has_stratum) {
  9646. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9647. cp->rpc_url, pool->rpc_url);
  9648. goto out;
  9649. }
  9650. /* Any longpoll from any pool is enough for this to be true */
  9651. pool->goal->have_longpoll = true;
  9652. wait_lpcurrent(cp);
  9653. {
  9654. lp_url = pool->lp_url;
  9655. if (cp == pool)
  9656. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  9657. else
  9658. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  9659. }
  9660. while (42) {
  9661. json_t *val, *soval;
  9662. struct work *work = make_work();
  9663. char *lpreq;
  9664. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id, pool);
  9665. work->pool = pool;
  9666. if (!lpreq)
  9667. {
  9668. free_work(work);
  9669. goto lpfail;
  9670. }
  9671. wait_lpcurrent(cp);
  9672. cgtime(&start);
  9673. /* Longpoll connections can be persistent for a very long time
  9674. * and any number of issues could have come up in the meantime
  9675. * so always establish a fresh connection instead of relying on
  9676. * a persistent one. */
  9677. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  9678. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  9679. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  9680. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  9681. lpreq, false, true, &rolltime, pool, false);
  9682. pool->lp_socket = CURL_SOCKET_BAD;
  9683. cgtime(&reply);
  9684. free(lpreq);
  9685. if (likely(val)) {
  9686. soval = json_object_get(json_object_get(val, "result"), "submitold");
  9687. if (soval)
  9688. pool->submit_old = json_is_true(soval);
  9689. else
  9690. pool->submit_old = false;
  9691. convert_to_work(val, rolltime, pool, work, &start, &reply);
  9692. failures = 0;
  9693. json_decref(val);
  9694. } else {
  9695. /* Some pools regularly drop the longpoll request so
  9696. * only see this as longpoll failure if it happens
  9697. * immediately and just restart it the rest of the
  9698. * time. */
  9699. cgtime(&end);
  9700. free_work(work);
  9701. if (end.tv_sec - start.tv_sec <= 30)
  9702. {
  9703. if (failures == 1)
  9704. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  9705. lpfail:
  9706. cgsleep_ms(30000);
  9707. }
  9708. }
  9709. if (pool != cp) {
  9710. pool = select_longpoll_pool(cp);
  9711. if (pool->has_stratum) {
  9712. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  9713. cp->rpc_url, pool->rpc_url);
  9714. break;
  9715. }
  9716. if (unlikely(!pool))
  9717. goto retry_pool;
  9718. }
  9719. if (unlikely(pool->removed))
  9720. break;
  9721. }
  9722. out:
  9723. pool->lp_active = false;
  9724. curl_easy_cleanup(curl);
  9725. return NULL;
  9726. }
  9727. static void stop_longpoll(void)
  9728. {
  9729. int i;
  9730. want_longpoll = false;
  9731. for (i = 0; i < total_pools; ++i)
  9732. {
  9733. struct pool *pool = pools[i];
  9734. if (unlikely(!pool->lp_started))
  9735. continue;
  9736. pool->lp_started = false;
  9737. pthread_cancel(pool->longpoll_thread);
  9738. }
  9739. struct mining_goal_info *goal, *tmpgoal;
  9740. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  9741. {
  9742. goal->have_longpoll = false;
  9743. }
  9744. }
  9745. static void start_longpoll(void)
  9746. {
  9747. int i;
  9748. want_longpoll = true;
  9749. for (i = 0; i < total_pools; ++i)
  9750. {
  9751. struct pool *pool = pools[i];
  9752. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  9753. continue;
  9754. pool->lp_started = true;
  9755. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  9756. quit(1, "Failed to create pool longpoll thread");
  9757. }
  9758. }
  9759. void reinit_device(struct cgpu_info *cgpu)
  9760. {
  9761. if (cgpu->drv->reinit_device)
  9762. cgpu->drv->reinit_device(cgpu);
  9763. }
  9764. static struct timeval rotate_tv;
  9765. /* We reap curls if they are unused for over a minute */
  9766. static void reap_curl(struct pool *pool)
  9767. {
  9768. struct curl_ent *ent, *iter;
  9769. struct timeval now;
  9770. int reaped = 0;
  9771. cgtime(&now);
  9772. mutex_lock(&pool->pool_lock);
  9773. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  9774. if (pool->curls < 2)
  9775. break;
  9776. if (now.tv_sec - ent->tv.tv_sec > 300) {
  9777. reaped++;
  9778. pool->curls--;
  9779. LL_DELETE(pool->curllist, ent);
  9780. curl_easy_cleanup(ent->curl);
  9781. free(ent);
  9782. }
  9783. }
  9784. mutex_unlock(&pool->pool_lock);
  9785. if (reaped)
  9786. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  9787. }
  9788. static void *watchpool_thread(void __maybe_unused *userdata)
  9789. {
  9790. int intervals = 0;
  9791. #ifndef HAVE_PTHREAD_CANCEL
  9792. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9793. #endif
  9794. RenameThread("watchpool");
  9795. while (42) {
  9796. struct timeval now;
  9797. int i;
  9798. if (++intervals > 20)
  9799. intervals = 0;
  9800. cgtime(&now);
  9801. for (i = 0; i < total_pools; i++) {
  9802. struct pool *pool = pools[i];
  9803. if (!opt_benchmark)
  9804. reap_curl(pool);
  9805. /* Get a rolling utility per pool over 10 mins */
  9806. if (intervals > 19) {
  9807. int shares = pool->diff1 - pool->last_shares;
  9808. pool->last_shares = pool->diff1;
  9809. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  9810. pool->shares = pool->utility;
  9811. }
  9812. if (pool->enabled == POOL_DISABLED)
  9813. continue;
  9814. /* Don't start testing any pools if the test threads
  9815. * from startup are still doing their first attempt. */
  9816. if (unlikely(pool->testing)) {
  9817. pthread_join(pool->test_thread, NULL);
  9818. }
  9819. /* Test pool is idle once every minute */
  9820. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  9821. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  9822. pool_resus(pool);
  9823. }
  9824. /* Only switch pools if the failback pool has been
  9825. * alive for more than 5 minutes (default) to prevent
  9826. * intermittently failing pools from being used. */
  9827. 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)
  9828. {
  9829. if (opt_fail_switch_delay % 60)
  9830. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  9831. pool->pool_no, pool->rpc_url,
  9832. opt_fail_switch_delay,
  9833. (opt_fail_switch_delay == 1 ? "" : "s"));
  9834. else
  9835. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  9836. pool->pool_no, pool->rpc_url,
  9837. opt_fail_switch_delay / 60,
  9838. (opt_fail_switch_delay == 60 ? "" : "s"));
  9839. switch_pools(NULL);
  9840. }
  9841. }
  9842. if (current_pool()->idle)
  9843. switch_pools(NULL);
  9844. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  9845. cgtime(&rotate_tv);
  9846. switch_pools(NULL);
  9847. }
  9848. cgsleep_ms(30000);
  9849. }
  9850. return NULL;
  9851. }
  9852. void mt_enable(struct thr_info *thr)
  9853. {
  9854. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  9855. notifier_wake(thr->notifier);
  9856. }
  9857. void proc_enable(struct cgpu_info *cgpu)
  9858. {
  9859. int j;
  9860. cgpu->deven = DEV_ENABLED;
  9861. for (j = cgpu->threads ?: 1; j--; )
  9862. mt_enable(cgpu->thr[j]);
  9863. }
  9864. #define device_recovered(cgpu) proc_enable(cgpu)
  9865. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  9866. {
  9867. struct string_elist *setstr_elist;
  9868. const char *p, *p2;
  9869. char replybuf[0x2000];
  9870. size_t L;
  9871. DL_FOREACH(opt_set_device_list, setstr_elist)
  9872. {
  9873. const char * const setstr = setstr_elist->string;
  9874. p = strchr(setstr, ':');
  9875. if (!p)
  9876. p = setstr;
  9877. {
  9878. L = p - setstr;
  9879. char pattern[L + 1];
  9880. if (L)
  9881. memcpy(pattern, setstr, L);
  9882. pattern[L] = '\0';
  9883. if (!cgpu_match(pattern, cgpu))
  9884. continue;
  9885. }
  9886. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  9887. cgpu->proc_repr, __func__, setstr);
  9888. if (p[0] == ':')
  9889. ++p;
  9890. p2 = strchr(p, '=');
  9891. if (!p2)
  9892. {
  9893. L = strlen(p);
  9894. p2 = "";
  9895. }
  9896. else
  9897. {
  9898. L = p2 - p;
  9899. ++p2;
  9900. }
  9901. char opt[L + 1];
  9902. if (L)
  9903. memcpy(opt, p, L);
  9904. opt[L] = '\0';
  9905. L = strlen(p2);
  9906. char setval[L + 1];
  9907. if (L)
  9908. memcpy(setval, p2, L);
  9909. setval[L] = '\0';
  9910. enum bfg_set_device_replytype success;
  9911. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9912. switch (success)
  9913. {
  9914. case SDR_OK:
  9915. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9916. cgpu->proc_repr, setstr,
  9917. p ? ": " : "", p ?: "");
  9918. break;
  9919. case SDR_ERR:
  9920. case SDR_HELP:
  9921. case SDR_UNKNOWN:
  9922. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9923. cgpu->proc_repr, setstr, p);
  9924. break;
  9925. case SDR_AUTO:
  9926. case SDR_NOSUPP:
  9927. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9928. cgpu->proc_repr, setstr);
  9929. }
  9930. }
  9931. cgpu->already_set_defaults = true;
  9932. }
  9933. 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)
  9934. {
  9935. struct device_drv dummy_drv = *drv;
  9936. struct cgpu_info dummy_cgpu = {
  9937. .drv = &dummy_drv,
  9938. .device = &dummy_cgpu,
  9939. .device_id = -1,
  9940. .proc_id = -1,
  9941. .device_data = userp,
  9942. .device_path = devpath,
  9943. .dev_serial = serial,
  9944. };
  9945. strcpy(dummy_cgpu.proc_repr, drv->name);
  9946. switch (mode)
  9947. {
  9948. case 0:
  9949. dummy_drv.set_device = datap;
  9950. break;
  9951. case 1:
  9952. dummy_drv.set_device = NULL;
  9953. dummy_cgpu.set_device_funcs = datap;
  9954. break;
  9955. }
  9956. cgpu_set_defaults(&dummy_cgpu);
  9957. }
  9958. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9959. * the screen at regular intervals, and restarts threads if they appear to have
  9960. * died. */
  9961. #define WATCHDOG_SICK_TIME 60
  9962. #define WATCHDOG_DEAD_TIME 600
  9963. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9964. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9965. static void *watchdog_thread(void __maybe_unused *userdata)
  9966. {
  9967. const unsigned int interval = WATCHDOG_INTERVAL;
  9968. struct timeval zero_tv;
  9969. #ifndef HAVE_PTHREAD_CANCEL
  9970. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9971. #endif
  9972. RenameThread("watchdog");
  9973. memset(&zero_tv, 0, sizeof(struct timeval));
  9974. cgtime(&rotate_tv);
  9975. while (1) {
  9976. int i;
  9977. struct timeval now;
  9978. sleep(interval);
  9979. discard_stale();
  9980. hashmeter(-1, &zero_tv, 0);
  9981. #ifdef HAVE_CURSES
  9982. const int ts = total_staged();
  9983. if (curses_active_locked()) {
  9984. change_logwinsize();
  9985. curses_print_status(ts);
  9986. _refresh_devstatus(true);
  9987. touchwin(logwin);
  9988. wrefresh(logwin);
  9989. unlock_curses();
  9990. }
  9991. #endif
  9992. cgtime(&now);
  9993. if (!sched_paused && !should_run()) {
  9994. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9995. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9996. if (!schedstart.enable) {
  9997. quit(0, "Terminating execution as planned");
  9998. break;
  9999. }
  10000. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  10001. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10002. sched_paused = true;
  10003. rd_lock(&mining_thr_lock);
  10004. for (i = 0; i < mining_threads; i++)
  10005. mining_thr[i]->pause = true;
  10006. rd_unlock(&mining_thr_lock);
  10007. } else if (sched_paused && should_run()) {
  10008. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  10009. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  10010. if (schedstop.enable)
  10011. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  10012. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  10013. sched_paused = false;
  10014. for (i = 0; i < mining_threads; i++) {
  10015. struct thr_info *thr;
  10016. thr = get_thread(i);
  10017. thr->pause = false;
  10018. }
  10019. for (i = 0; i < total_devices; ++i)
  10020. {
  10021. struct cgpu_info *cgpu = get_devices(i);
  10022. /* Don't touch disabled devices */
  10023. if (cgpu->deven == DEV_DISABLED)
  10024. continue;
  10025. proc_enable(cgpu);
  10026. }
  10027. }
  10028. for (i = 0; i < total_devices; ++i) {
  10029. struct cgpu_info *cgpu = get_devices(i);
  10030. if (!cgpu->disable_watchdog)
  10031. bfg_watchdog(cgpu, &now);
  10032. }
  10033. }
  10034. return NULL;
  10035. }
  10036. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  10037. {
  10038. struct thr_info *thr = cgpu->thr[0];
  10039. enum dev_enable *denable;
  10040. char *dev_str = cgpu->proc_repr;
  10041. if (likely(drv_ready(cgpu)))
  10042. {
  10043. if (unlikely(!cgpu->already_set_defaults))
  10044. cgpu_set_defaults(cgpu);
  10045. if (cgpu->drv->get_stats)
  10046. cgpu->drv->get_stats(cgpu);
  10047. }
  10048. denable = &cgpu->deven;
  10049. if (cgpu->drv->watchdog)
  10050. cgpu->drv->watchdog(cgpu, tvp_now);
  10051. /* Thread is disabled */
  10052. if (*denable == DEV_DISABLED)
  10053. return;
  10054. else
  10055. if (*denable == DEV_RECOVER_ERR) {
  10056. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  10057. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  10058. dev_str);
  10059. if (cgpu->reinit_backoff < 300)
  10060. cgpu->reinit_backoff *= 2;
  10061. device_recovered(cgpu);
  10062. }
  10063. return;
  10064. }
  10065. else
  10066. if (*denable == DEV_RECOVER) {
  10067. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  10068. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  10069. dev_str);
  10070. device_recovered(cgpu);
  10071. }
  10072. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10073. return;
  10074. }
  10075. else
  10076. if (cgpu->temp > cgpu->cutofftemp)
  10077. {
  10078. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  10079. dev_str, (int)cgpu->temp);
  10080. *denable = DEV_RECOVER;
  10081. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  10082. run_cmd(cmd_idle);
  10083. }
  10084. if (thr->getwork) {
  10085. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  10086. int thrid;
  10087. bool cgpu_idle = true;
  10088. thr->rolling = 0;
  10089. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  10090. if (!cgpu->thr[thrid]->getwork)
  10091. cgpu_idle = false;
  10092. if (cgpu_idle) {
  10093. cgpu->rolling = 0;
  10094. cgpu->status = LIFE_WAIT;
  10095. }
  10096. }
  10097. return;
  10098. }
  10099. else if (cgpu->status == LIFE_WAIT)
  10100. cgpu->status = LIFE_WELL;
  10101. #ifdef WANT_CPUMINE
  10102. if (!strcmp(cgpu->drv->dname, "cpu"))
  10103. return;
  10104. #endif
  10105. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  10106. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  10107. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  10108. cgpu->status = LIFE_WELL;
  10109. cgpu->device_last_well = time(NULL);
  10110. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  10111. thr->rolling = cgpu->rolling = 0;
  10112. cgpu->status = LIFE_SICK;
  10113. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  10114. cgtime(&thr->sick);
  10115. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  10116. run_cmd(cmd_sick);
  10117. if (opt_restart && cgpu->drv->reinit_device) {
  10118. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  10119. reinit_device(cgpu);
  10120. }
  10121. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  10122. cgpu->status = LIFE_DEAD;
  10123. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  10124. cgtime(&thr->sick);
  10125. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  10126. run_cmd(cmd_dead);
  10127. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  10128. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  10129. /* Attempt to restart a GPU that's sick or dead once every minute */
  10130. cgtime(&thr->sick);
  10131. if (opt_restart)
  10132. reinit_device(cgpu);
  10133. }
  10134. }
  10135. static void log_print_status(struct cgpu_info *cgpu)
  10136. {
  10137. char logline[255];
  10138. get_statline(logline, sizeof(logline), cgpu);
  10139. applog(LOG_WARNING, "%s", logline);
  10140. }
  10141. void print_summary(void)
  10142. {
  10143. struct timeval diff;
  10144. int hours, mins, secs, i;
  10145. double utility, efficiency = 0.0;
  10146. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  10147. int pool_secs;
  10148. timersub(&total_tv_end, &total_tv_start, &diff);
  10149. hours = diff.tv_sec / 3600;
  10150. mins = (diff.tv_sec % 3600) / 60;
  10151. secs = diff.tv_sec % 60;
  10152. utility = total_accepted / total_secs * 60;
  10153. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  10154. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  10155. applog(LOG_WARNING, "Started at %s", datestamp);
  10156. if (total_pools == 1)
  10157. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  10158. #ifdef WANT_CPUMINE
  10159. if (opt_n_threads > 0)
  10160. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  10161. #endif
  10162. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  10163. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  10164. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  10165. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  10166. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  10167. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  10168. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  10169. total_rejected, total_stale,
  10170. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  10171. );
  10172. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  10173. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  10174. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  10175. applog(LOG_WARNING, "Network transfer: %s (%s)",
  10176. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10177. (float)total_bytes_rcvd,
  10178. (float)total_bytes_sent),
  10179. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10180. (float)(total_bytes_rcvd / total_secs),
  10181. (float)(total_bytes_sent / total_secs)));
  10182. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  10183. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  10184. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  10185. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  10186. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  10187. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  10188. if (total_pools > 1) {
  10189. for (i = 0; i < total_pools; i++) {
  10190. struct pool *pool = pools[i];
  10191. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  10192. if (pool->solved)
  10193. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  10194. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  10195. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  10196. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  10197. pool->rejected, pool->stale_shares,
  10198. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  10199. );
  10200. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  10201. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  10202. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  10203. applog(LOG_WARNING, " Network transfer: %s (%s)",
  10204. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  10205. (float)pool->cgminer_pool_stats.net_bytes_received,
  10206. (float)pool->cgminer_pool_stats.net_bytes_sent),
  10207. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  10208. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  10209. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  10210. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  10211. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  10212. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  10213. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  10214. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  10215. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  10216. }
  10217. }
  10218. if (opt_quit_summary != BQS_NONE)
  10219. {
  10220. if (opt_quit_summary == BQS_DEFAULT)
  10221. {
  10222. if (total_devices < 25)
  10223. opt_quit_summary = BQS_PROCS;
  10224. else
  10225. opt_quit_summary = BQS_DEVS;
  10226. }
  10227. if (opt_quit_summary == BQS_DETAILED)
  10228. include_serial_in_statline = true;
  10229. applog(LOG_WARNING, "Summary of per device statistics:\n");
  10230. for (i = 0; i < total_devices; ++i) {
  10231. struct cgpu_info *cgpu = get_devices(i);
  10232. if (!cgpu->proc_id)
  10233. {
  10234. // Device summary line
  10235. opt_show_procs = false;
  10236. log_print_status(cgpu);
  10237. opt_show_procs = true;
  10238. }
  10239. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  10240. log_print_status(cgpu);
  10241. }
  10242. }
  10243. if (opt_shares) {
  10244. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  10245. if (opt_shares > total_diff_accepted)
  10246. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  10247. }
  10248. applog(LOG_WARNING, " ");
  10249. fflush(stderr);
  10250. fflush(stdout);
  10251. }
  10252. void _bfg_clean_up(bool restarting)
  10253. {
  10254. #ifdef HAVE_OPENCL
  10255. clear_adl(nDevs);
  10256. #endif
  10257. #ifdef HAVE_LIBUSB
  10258. if (likely(have_libusb))
  10259. libusb_exit(NULL);
  10260. #endif
  10261. cgtime(&total_tv_end);
  10262. #ifdef WIN32
  10263. timeEndPeriod(1);
  10264. #endif
  10265. if (!restarting) {
  10266. /* Attempting to disable curses or print a summary during a
  10267. * restart can lead to a deadlock. */
  10268. #ifdef HAVE_CURSES
  10269. disable_curses();
  10270. #endif
  10271. if (!opt_realquiet && successful_connect)
  10272. print_summary();
  10273. }
  10274. if (opt_n_threads > 0)
  10275. free(cpus);
  10276. curl_global_cleanup();
  10277. #ifdef WIN32
  10278. WSACleanup();
  10279. #endif
  10280. }
  10281. void _quit(int status)
  10282. {
  10283. if (status) {
  10284. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  10285. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  10286. int *p = NULL;
  10287. // NOTE debugger can bypass with: p = &p
  10288. *p = status; // Segfault, hopefully dumping core
  10289. }
  10290. }
  10291. #if defined(unix) || defined(__APPLE__)
  10292. if (forkpid > 0) {
  10293. kill(forkpid, SIGTERM);
  10294. forkpid = 0;
  10295. }
  10296. #endif
  10297. exit(status);
  10298. }
  10299. #ifdef HAVE_CURSES
  10300. char *curses_input(const char *query)
  10301. {
  10302. char *input;
  10303. echo();
  10304. input = malloc(255);
  10305. if (!input)
  10306. quit(1, "Failed to malloc input");
  10307. leaveok(logwin, false);
  10308. wlogprint("%s:\n", query);
  10309. wgetnstr(logwin, input, 255);
  10310. if (!strlen(input))
  10311. {
  10312. free(input);
  10313. input = NULL;
  10314. }
  10315. leaveok(logwin, true);
  10316. noecho();
  10317. return input;
  10318. }
  10319. #endif
  10320. static void *test_pool_thread(void *arg)
  10321. {
  10322. struct pool *pool = (struct pool *)arg;
  10323. if (pool_active(pool, false)) {
  10324. pool_tset(pool, &pool->lagging);
  10325. pool_tclear(pool, &pool->idle);
  10326. bool first_pool = false;
  10327. cg_wlock(&control_lock);
  10328. if (!pools_active) {
  10329. currentpool = pool;
  10330. if (pool->pool_no != 0)
  10331. first_pool = true;
  10332. pools_active = true;
  10333. }
  10334. cg_wunlock(&control_lock);
  10335. if (unlikely(first_pool))
  10336. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  10337. else
  10338. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  10339. switch_pools(NULL);
  10340. } else
  10341. pool_died(pool);
  10342. pool->testing = false;
  10343. return NULL;
  10344. }
  10345. /* Always returns true that the pool details were added unless we are not
  10346. * live, implying this is the only pool being added, so if no pools are
  10347. * active it returns false. */
  10348. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  10349. {
  10350. size_t siz;
  10351. pool_set_uri(pool, url);
  10352. pool->rpc_user = user;
  10353. pool->rpc_pass = pass;
  10354. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10355. pool->rpc_userpass = malloc(siz);
  10356. if (!pool->rpc_userpass)
  10357. quit(1, "Failed to malloc userpass");
  10358. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10359. pool->testing = true;
  10360. pool->idle = true;
  10361. enable_pool(pool);
  10362. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10363. if (!live) {
  10364. pthread_join(pool->test_thread, NULL);
  10365. return pools_active;
  10366. }
  10367. return true;
  10368. }
  10369. #ifdef HAVE_CURSES
  10370. static bool input_pool(bool live)
  10371. {
  10372. char *url = NULL, *user = NULL, *pass = NULL;
  10373. struct pool *pool;
  10374. bool ret = false;
  10375. immedok(logwin, true);
  10376. wlogprint("Input server details.\n");
  10377. url = curses_input("URL");
  10378. if (!url)
  10379. goto out;
  10380. user = curses_input("Username");
  10381. if (!user)
  10382. goto out;
  10383. pass = curses_input("Password");
  10384. if (!pass)
  10385. pass = calloc(1, 1);
  10386. pool = add_pool();
  10387. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  10388. strncmp(url, "https://", 8)) {
  10389. char *httpinput;
  10390. httpinput = malloc(256);
  10391. if (!httpinput)
  10392. quit(1, "Failed to malloc httpinput");
  10393. strcpy(httpinput, "http://");
  10394. strncat(httpinput, url, 248);
  10395. free(url);
  10396. url = httpinput;
  10397. }
  10398. ret = add_pool_details(pool, live, url, user, pass);
  10399. out:
  10400. immedok(logwin, false);
  10401. if (!ret) {
  10402. if (url)
  10403. free(url);
  10404. if (user)
  10405. free(user);
  10406. if (pass)
  10407. free(pass);
  10408. }
  10409. return ret;
  10410. }
  10411. #endif
  10412. #if BLKMAKER_VERSION > 1
  10413. static
  10414. bool _add_local_gbt(const char * const filepath, void *userp)
  10415. {
  10416. const bool * const live_p = userp;
  10417. struct pool *pool;
  10418. char buf[0x100];
  10419. char *rpcuser = NULL, *rpcpass = NULL, *rpcconnect = NULL;
  10420. int rpcport = 0, rpcssl = -101;
  10421. FILE * const F = fopen(filepath, "r");
  10422. if (!F)
  10423. applogr(false, LOG_WARNING, "%s: Failed to open %s for reading", "add_local_gbt", filepath);
  10424. while (fgets(buf, sizeof(buf), F))
  10425. {
  10426. if (!strncasecmp(buf, "rpcuser=", 8))
  10427. rpcuser = trimmed_strdup(&buf[8]);
  10428. else
  10429. if (!strncasecmp(buf, "rpcpassword=", 12))
  10430. rpcpass = trimmed_strdup(&buf[12]);
  10431. else
  10432. if (!strncasecmp(buf, "rpcport=", 8))
  10433. rpcport = atoi(&buf[8]);
  10434. else
  10435. if (!strncasecmp(buf, "rpcssl=", 7))
  10436. rpcssl = atoi(&buf[7]);
  10437. else
  10438. if (!strncasecmp(buf, "rpcconnect=", 11))
  10439. rpcconnect = trimmed_strdup(&buf[11]);
  10440. else
  10441. continue;
  10442. if (rpcuser && rpcpass && rpcport && rpcssl != -101 && rpcconnect)
  10443. break;
  10444. }
  10445. fclose(F);
  10446. if (!rpcpass)
  10447. {
  10448. applog(LOG_DEBUG, "%s: Did not find rpcpassword in %s", "add_local_gbt", filepath);
  10449. err:
  10450. free(rpcuser);
  10451. free(rpcpass);
  10452. goto out;
  10453. }
  10454. if (!rpcport)
  10455. rpcport = 8332;
  10456. if (rpcssl == -101)
  10457. rpcssl = 0;
  10458. const bool have_cbaddr = get_mining_goal("default")->generation_script;
  10459. const int uri_sz = 0x30;
  10460. char * const uri = malloc(uri_sz);
  10461. snprintf(uri, uri_sz, "http%s://%s:%d/%s#allblocks", rpcssl ? "s" : "", rpcconnect ?: "localhost", rpcport, have_cbaddr ? "" : "#getcbaddr");
  10462. char hfuri[0x40];
  10463. if (rpcconnect)
  10464. snprintf(hfuri, sizeof(hfuri), "%s:%d", rpcconnect, rpcport);
  10465. else
  10466. snprintf(hfuri, sizeof(hfuri), "port %d", rpcport);
  10467. applog(LOG_DEBUG, "Local bitcoin RPC server on %s found in %s", hfuri, filepath);
  10468. for (int i = 0; i < total_pools; ++i)
  10469. {
  10470. struct pool *pool = pools[i];
  10471. if (!(strcmp(pool->rpc_url, uri) || strcmp(pool->rpc_pass, rpcpass)))
  10472. {
  10473. applog(LOG_DEBUG, "Server on %s is already configured, not adding as failover", hfuri);
  10474. free(uri);
  10475. goto err;
  10476. }
  10477. }
  10478. pool = add_pool();
  10479. if (!pool)
  10480. {
  10481. applog(LOG_ERR, "%s: Error adding pool for bitcoin configured in %s", "add_local_gbt", filepath);
  10482. goto err;
  10483. }
  10484. if (!rpcuser)
  10485. rpcuser = "";
  10486. pool->quota = 0;
  10487. adjust_quota_gcd();
  10488. pool->failover_only = true;
  10489. add_pool_details(pool, *live_p, uri, rpcuser, rpcpass);
  10490. applog(LOG_NOTICE, "Added local bitcoin RPC server on %s as pool %d", hfuri, pool->pool_no);
  10491. out:
  10492. return false;
  10493. }
  10494. static
  10495. void add_local_gbt(bool live)
  10496. {
  10497. appdata_file_call("Bitcoin", "bitcoin.conf", _add_local_gbt, &live);
  10498. }
  10499. #endif
  10500. #if defined(unix) || defined(__APPLE__)
  10501. static void fork_monitor()
  10502. {
  10503. // Make a pipe: [readFD, writeFD]
  10504. int pfd[2];
  10505. int r = pipe(pfd);
  10506. if (r < 0) {
  10507. perror("pipe - failed to create pipe for --monitor");
  10508. exit(1);
  10509. }
  10510. // Make stderr write end of pipe
  10511. fflush(stderr);
  10512. r = dup2(pfd[1], 2);
  10513. if (r < 0) {
  10514. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  10515. exit(1);
  10516. }
  10517. r = close(pfd[1]);
  10518. if (r < 0) {
  10519. perror("close - failed to close write end of pipe for --monitor");
  10520. exit(1);
  10521. }
  10522. // Don't allow a dying monitor to kill the main process
  10523. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  10524. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  10525. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  10526. perror("signal - failed to edit signal mask for --monitor");
  10527. exit(1);
  10528. }
  10529. // Fork a child process
  10530. forkpid = fork();
  10531. if (forkpid < 0) {
  10532. perror("fork - failed to fork child process for --monitor");
  10533. exit(1);
  10534. }
  10535. // Child: launch monitor command
  10536. if (0 == forkpid) {
  10537. // Make stdin read end of pipe
  10538. r = dup2(pfd[0], 0);
  10539. if (r < 0) {
  10540. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  10541. exit(1);
  10542. }
  10543. close(pfd[0]);
  10544. if (r < 0) {
  10545. perror("close - in child, failed to close read end of pipe for --monitor");
  10546. exit(1);
  10547. }
  10548. // Launch user specified command
  10549. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  10550. perror("execl - in child failed to exec user specified command for --monitor");
  10551. exit(1);
  10552. }
  10553. // Parent: clean up unused fds and bail
  10554. r = close(pfd[0]);
  10555. if (r < 0) {
  10556. perror("close - failed to close read end of pipe for --monitor");
  10557. exit(1);
  10558. }
  10559. }
  10560. #endif // defined(unix)
  10561. #ifdef HAVE_CURSES
  10562. #ifdef USE_UNICODE
  10563. static
  10564. wchar_t select_unicode_char(const wchar_t *opt)
  10565. {
  10566. for ( ; *opt; ++opt)
  10567. if (iswprint(*opt))
  10568. return *opt;
  10569. return '?';
  10570. }
  10571. #endif
  10572. void enable_curses(void) {
  10573. int x;
  10574. __maybe_unused int y;
  10575. lock_curses();
  10576. if (curses_active) {
  10577. unlock_curses();
  10578. return;
  10579. }
  10580. #ifdef USE_UNICODE
  10581. if (use_unicode)
  10582. {
  10583. setlocale(LC_CTYPE, "");
  10584. if (iswprint(0xb0))
  10585. have_unicode_degrees = true;
  10586. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  10587. }
  10588. #endif
  10589. mainwin = initscr();
  10590. start_color();
  10591. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  10592. if (ERR != use_default_colors())
  10593. default_bgcolor = -1;
  10594. #endif
  10595. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  10596. {
  10597. menu_attr = COLOR_PAIR(1);
  10598. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  10599. attr_bad |= COLOR_PAIR(2);
  10600. }
  10601. keypad(mainwin, true);
  10602. getmaxyx(mainwin, y, x);
  10603. statuswin = newwin(logstart, x, 0, 0);
  10604. leaveok(statuswin, true);
  10605. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  10606. // We resize the window later anyway, so just start it off at 1 :)
  10607. logwin = newwin(1, 0, logcursor, 0);
  10608. idlok(logwin, true);
  10609. scrollok(logwin, true);
  10610. leaveok(logwin, true);
  10611. cbreak();
  10612. noecho();
  10613. nonl();
  10614. curses_active = true;
  10615. statusy = logstart;
  10616. unlock_curses();
  10617. }
  10618. #endif
  10619. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  10620. #ifndef WANT_CPUMINE
  10621. struct device_drv cpu_drv;
  10622. struct device_drv cpu_drv = {
  10623. .name = "CPU",
  10624. };
  10625. #endif
  10626. static int cgminer_id_count = 0;
  10627. static int device_line_id_count;
  10628. void register_device(struct cgpu_info *cgpu)
  10629. {
  10630. cgpu->deven = DEV_ENABLED;
  10631. wr_lock(&devices_lock);
  10632. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  10633. wr_unlock(&devices_lock);
  10634. if (!cgpu->proc_id)
  10635. cgpu->device_line_id = device_line_id_count++;
  10636. int thr_objs = cgpu->threads ?: 1;
  10637. mining_threads += thr_objs;
  10638. base_queue += thr_objs + cgpu->extra_work_queue;
  10639. {
  10640. const struct device_drv * const drv = cgpu->drv;
  10641. struct mining_algorithm *malgo;
  10642. LL_FOREACH(mining_algorithms, malgo)
  10643. {
  10644. if (drv_min_nonce_diff(drv, cgpu, malgo) < 0)
  10645. continue;
  10646. malgo->base_queue += thr_objs + cgpu->extra_work_queue;
  10647. }
  10648. }
  10649. #ifdef HAVE_CURSES
  10650. adj_width(mining_threads, &dev_width);
  10651. #endif
  10652. rwlock_init(&cgpu->qlock);
  10653. cgpu->queued_work = NULL;
  10654. }
  10655. struct _cgpu_devid_counter {
  10656. char name[4];
  10657. int lastid;
  10658. UT_hash_handle hh;
  10659. };
  10660. void renumber_cgpu(struct cgpu_info *cgpu)
  10661. {
  10662. static struct _cgpu_devid_counter *devids = NULL;
  10663. struct _cgpu_devid_counter *d;
  10664. HASH_FIND_STR(devids, cgpu->drv->name, d);
  10665. if (d)
  10666. cgpu->device_id = ++d->lastid;
  10667. else {
  10668. d = malloc(sizeof(*d));
  10669. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  10670. cgpu->device_id = d->lastid = 0;
  10671. HASH_ADD_STR(devids, name, d);
  10672. }
  10673. // Build repr strings
  10674. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  10675. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  10676. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  10677. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  10678. const int lpcount = cgpu->procs;
  10679. if (lpcount > 1)
  10680. {
  10681. int ns;
  10682. struct cgpu_info *slave;
  10683. int lpdigits = 1;
  10684. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  10685. ++lpdigits;
  10686. if (lpdigits > max_lpdigits)
  10687. max_lpdigits = lpdigits;
  10688. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  10689. cgpu->proc_repr[5 + lpdigits] = '\0';
  10690. ns = strlen(cgpu->proc_repr_ns);
  10691. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  10692. slave = cgpu;
  10693. for (int i = 1; i < lpcount; ++i)
  10694. {
  10695. slave = slave->next_proc;
  10696. strcpy(slave->proc_repr, cgpu->proc_repr);
  10697. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  10698. for (int x = i, y = lpdigits; --y, x; x /= 26)
  10699. {
  10700. slave->proc_repr_ns[ns + y] =
  10701. slave->proc_repr[5 + y] += (x % 26);
  10702. }
  10703. }
  10704. }
  10705. }
  10706. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  10707. {
  10708. sha256(buffer, length, digest);
  10709. return true;
  10710. }
  10711. static
  10712. bool drv_algo_check(const struct device_drv * const drv)
  10713. {
  10714. struct mining_goal_info *goal, *tmpgoal;
  10715. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  10716. {
  10717. if (drv_min_nonce_diff(drv, NULL, goal->malgo) >= 0)
  10718. return true;
  10719. }
  10720. return false;
  10721. }
  10722. #ifndef HAVE_PTHREAD_CANCEL
  10723. extern void setup_pthread_cancel_workaround();
  10724. extern struct sigaction pcwm_orig_term_handler;
  10725. #endif
  10726. bool bfg_need_detect_rescan;
  10727. extern void probe_device(struct lowlevel_device_info *);
  10728. static void schedule_rescan(const struct timeval *);
  10729. static
  10730. void drv_detect_all()
  10731. {
  10732. bool rescanning = false;
  10733. rescan:
  10734. bfg_need_detect_rescan = false;
  10735. #ifdef HAVE_BFG_LOWLEVEL
  10736. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  10737. LL_FOREACH_SAFE(infolist, info, infotmp)
  10738. probe_device(info);
  10739. LL_FOREACH_SAFE(infolist, info, infotmp)
  10740. pthread_join(info->probe_pth, NULL);
  10741. #endif
  10742. struct driver_registration *reg, *tmp;
  10743. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  10744. {
  10745. const struct device_drv * const drv = reg->drv;
  10746. if (!(drv_algo_check(drv) && drv->drv_detect))
  10747. continue;
  10748. drv->drv_detect();
  10749. }
  10750. #ifdef HAVE_BFG_LOWLEVEL
  10751. lowlevel_scan_free();
  10752. #endif
  10753. if (bfg_need_detect_rescan)
  10754. {
  10755. if (rescanning)
  10756. {
  10757. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  10758. struct timeval tv_when;
  10759. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  10760. schedule_rescan(&tv_when);
  10761. }
  10762. else
  10763. {
  10764. rescanning = true;
  10765. applog(LOG_DEBUG, "Device rescan requested");
  10766. goto rescan;
  10767. }
  10768. }
  10769. }
  10770. static
  10771. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  10772. {
  10773. struct thr_info *thr;
  10774. int j;
  10775. struct device_drv *api = cgpu->drv;
  10776. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10777. int threadobj = cgpu->threads;
  10778. if (!threadobj)
  10779. // Create a fake thread object to handle hashmeter etc
  10780. threadobj = 1;
  10781. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  10782. cgpu->thr[threadobj] = NULL;
  10783. cgpu->status = LIFE_INIT;
  10784. if (opt_devices_enabled_list)
  10785. {
  10786. struct string_elist *enablestr_elist;
  10787. cgpu->deven = DEV_DISABLED;
  10788. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  10789. {
  10790. const char * const enablestr = enablestr_elist->string;
  10791. if (cgpu_match(enablestr, cgpu))
  10792. {
  10793. cgpu->deven = DEV_ENABLED;
  10794. break;
  10795. }
  10796. }
  10797. }
  10798. cgpu->max_hashes = 0;
  10799. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  10800. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  10801. // Setup thread structs before starting any of the threads, in case they try to interact
  10802. for (j = 0; j < threadobj; ++j, ++*kp) {
  10803. thr = get_thread(*kp);
  10804. thr->id = *kp;
  10805. thr->cgpu = cgpu;
  10806. thr->device_thread = j;
  10807. thr->work_restart_notifier[1] = INVSOCK;
  10808. thr->mutex_request[1] = INVSOCK;
  10809. thr->_job_transition_in_progress = true;
  10810. timerclear(&thr->tv_morework);
  10811. thr->scanhash_working = true;
  10812. thr->hashes_done = 0;
  10813. timerclear(&thr->tv_hashes_done);
  10814. cgtime(&thr->tv_lastupdate);
  10815. thr->tv_poll.tv_sec = -1;
  10816. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  10817. cgpu->thr[j] = thr;
  10818. }
  10819. if (!cgpu->device->threads)
  10820. notifier_init_invalid(cgpu->thr[0]->notifier);
  10821. else
  10822. if (!cgpu->threads)
  10823. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  10824. else
  10825. for (j = 0; j < cgpu->threads; ++j)
  10826. {
  10827. thr = cgpu->thr[j];
  10828. notifier_init(thr->notifier);
  10829. }
  10830. }
  10831. static
  10832. void start_cgpu(struct cgpu_info *cgpu)
  10833. {
  10834. struct thr_info *thr;
  10835. int j;
  10836. for (j = 0; j < cgpu->threads; ++j) {
  10837. thr = cgpu->thr[j];
  10838. /* Enable threads for devices set not to mine but disable
  10839. * their queue in case we wish to enable them later */
  10840. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  10841. continue;
  10842. thread_reportout(thr);
  10843. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  10844. quit(1, "thread %d create failed", thr->id);
  10845. notifier_wake(thr->notifier);
  10846. }
  10847. if (cgpu->deven == DEV_ENABLED)
  10848. proc_enable(cgpu);
  10849. }
  10850. static
  10851. void _scan_serial(void *p)
  10852. {
  10853. const char *s = p;
  10854. struct string_elist *iter, *tmp;
  10855. struct string_elist *orig_scan_devices = scan_devices;
  10856. if (s)
  10857. {
  10858. // Make temporary scan_devices list
  10859. scan_devices = NULL;
  10860. string_elist_add("noauto", &scan_devices);
  10861. add_serial(s);
  10862. }
  10863. drv_detect_all();
  10864. if (s)
  10865. {
  10866. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  10867. {
  10868. string_elist_del(&scan_devices, iter);
  10869. }
  10870. scan_devices = orig_scan_devices;
  10871. }
  10872. }
  10873. #ifdef HAVE_BFG_LOWLEVEL
  10874. static
  10875. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  10876. {
  10877. if (!(false
  10878. || (info->serial && !strcasecmp(ser, info->serial))
  10879. || (info->path && !strcasecmp(ser, info->path ))
  10880. || (info->devid && !strcasecmp(ser, info->devid ))
  10881. ))
  10882. {
  10883. char *devid = devpath_to_devid(ser);
  10884. if (!devid)
  10885. return false;
  10886. const bool different = strcmp(info->devid, devid);
  10887. free(devid);
  10888. if (different)
  10889. return false;
  10890. }
  10891. return true;
  10892. }
  10893. static
  10894. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  10895. {
  10896. struct driver_registration *dreg;
  10897. char dname[dnamelen];
  10898. int i;
  10899. for (i = 0; i < dnamelen; ++i)
  10900. dname[i] = tolower(_dname[i]);
  10901. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  10902. if (!dreg)
  10903. {
  10904. for (i = 0; i < dnamelen; ++i)
  10905. dname[i] = toupper(_dname[i]);
  10906. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  10907. if (!dreg)
  10908. return NULL;
  10909. }
  10910. if (!drv_algo_check(dreg->drv))
  10911. return NULL;
  10912. return dreg->drv;
  10913. }
  10914. static
  10915. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  10916. {
  10917. bfg_probe_result_flags = 0;
  10918. if (drv->lowl_probe(info))
  10919. {
  10920. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  10921. return true;
  10922. }
  10923. else
  10924. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  10925. *request_rescan_p = true;
  10926. return false;
  10927. }
  10928. bool dummy_check_never_true = false;
  10929. static
  10930. void *probe_device_thread(void *p)
  10931. {
  10932. struct lowlevel_device_info * const infolist = p;
  10933. struct lowlevel_device_info *info = infolist;
  10934. bool request_rescan = false;
  10935. {
  10936. char threadname[5 + strlen(info->devid) + 1];
  10937. sprintf(threadname, "probe_%s", info->devid);
  10938. RenameThread(threadname);
  10939. }
  10940. // If already in use, ignore
  10941. if (bfg_claim_any(NULL, NULL, info->devid))
  10942. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  10943. __func__, info->product);
  10944. // if lowlevel device matches specific user assignment, probe requested driver(s)
  10945. struct string_elist *sd_iter, *sd_tmp;
  10946. struct driver_registration *dreg, *dreg_tmp;
  10947. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10948. {
  10949. const char * const dname = sd_iter->string;
  10950. const char * const colon = strpbrk(dname, ":@");
  10951. if (!(colon && colon != dname))
  10952. continue;
  10953. const char * const ser = &colon[1];
  10954. LL_FOREACH2(infolist, info, same_devid_next)
  10955. {
  10956. if (!_probe_device_match(info, ser))
  10957. continue;
  10958. const size_t dnamelen = (colon - dname);
  10959. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10960. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10961. continue;
  10962. if (_probe_device_do_probe(drv, info, &request_rescan))
  10963. return NULL;
  10964. }
  10965. }
  10966. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  10967. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10968. {
  10969. const struct device_drv * const drv = dreg->drv;
  10970. if (!drv_algo_check(drv))
  10971. continue;
  10972. // Check for "noauto" flag
  10973. // NOTE: driver-specific configuration overrides general
  10974. bool doauto = true;
  10975. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10976. {
  10977. const char * const dname = sd_iter->string;
  10978. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10979. const char *colon = strchr(dname, ':');
  10980. if (!colon)
  10981. colon = &dname[-1];
  10982. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  10983. continue;
  10984. const ssize_t dnamelen = (colon - dname);
  10985. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  10986. continue;
  10987. doauto = (tolower(colon[1]) == 'a');
  10988. if (dnamelen != -1)
  10989. break;
  10990. }
  10991. if (doauto && drv->lowl_match)
  10992. {
  10993. LL_FOREACH2(infolist, info, same_devid_next)
  10994. {
  10995. /*
  10996. The below call to applog is absolutely necessary
  10997. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  10998. Mac OS X using Homebrew results in a binary that segfaults on startup
  10999. There are two unresolved issues:
  11000. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  11001. in debug symbols being available to help troubleshoot the issue
  11002. 2) The issue disappears when unrelated code changes are made, such as adding the following
  11003. call to applog with infolist and / or p
  11004. We would encourage revisiting this in the future to come up with a more concrete solution
  11005. Reproducing should only require commenting / removing the following line and installing
  11006. BFGMiner using "brew install bfgminer --HEAD"
  11007. */
  11008. if (dummy_check_never_true)
  11009. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  11010. if (!drv->lowl_match(info))
  11011. continue;
  11012. if (_probe_device_do_probe(drv, info, &request_rescan))
  11013. return NULL;
  11014. }
  11015. }
  11016. }
  11017. // probe driver(s) with 'all' enabled
  11018. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  11019. {
  11020. const char * const dname = sd_iter->string;
  11021. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  11022. const char * const colon = strchr(dname, ':');
  11023. if (!colon)
  11024. {
  11025. LL_FOREACH2(infolist, info, same_devid_next)
  11026. {
  11027. if (
  11028. #ifdef NEED_BFG_LOWL_VCOM
  11029. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  11030. #endif
  11031. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  11032. {
  11033. bool dont_rescan = false;
  11034. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  11035. {
  11036. const struct device_drv * const drv = dreg->drv;
  11037. if (!drv_algo_check(drv))
  11038. continue;
  11039. if (drv->lowl_probe_by_name_only)
  11040. continue;
  11041. if (!drv->lowl_probe)
  11042. continue;
  11043. if (_probe_device_do_probe(drv, info, NULL))
  11044. return NULL;
  11045. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  11046. dont_rescan = true;
  11047. }
  11048. if (opt_hotplug && !dont_rescan)
  11049. request_rescan = true;
  11050. break;
  11051. }
  11052. }
  11053. continue;
  11054. }
  11055. if (strcasecmp(&colon[1], "all"))
  11056. continue;
  11057. const size_t dnamelen = (colon - dname);
  11058. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  11059. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  11060. continue;
  11061. LL_FOREACH2(infolist, info, same_devid_next)
  11062. {
  11063. if (info->lowl->exclude_from_all)
  11064. continue;
  11065. if (_probe_device_do_probe(drv, info, NULL))
  11066. return NULL;
  11067. }
  11068. }
  11069. // Only actually request a rescan if we never found any cgpu
  11070. if (request_rescan)
  11071. bfg_need_detect_rescan = true;
  11072. return NULL;
  11073. }
  11074. void probe_device(struct lowlevel_device_info * const info)
  11075. {
  11076. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  11077. }
  11078. #endif
  11079. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  11080. {
  11081. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  11082. int devcount, i, mining_threads_new = 0;
  11083. unsigned int k;
  11084. struct cgpu_info *cgpu;
  11085. struct thr_info *thr;
  11086. void *p;
  11087. mutex_lock(&mutex);
  11088. devcount = total_devices;
  11089. addfunc(arg);
  11090. if (!total_devices_new)
  11091. goto out;
  11092. wr_lock(&devices_lock);
  11093. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  11094. if (unlikely(!p))
  11095. {
  11096. wr_unlock(&devices_lock);
  11097. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  11098. goto out;
  11099. }
  11100. devices = p;
  11101. wr_unlock(&devices_lock);
  11102. for (i = 0; i < total_devices_new; ++i)
  11103. {
  11104. cgpu = devices_new[i];
  11105. mining_threads_new += cgpu->threads ?: 1;
  11106. }
  11107. wr_lock(&mining_thr_lock);
  11108. mining_threads_new += mining_threads;
  11109. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  11110. if (unlikely(!p))
  11111. {
  11112. wr_unlock(&mining_thr_lock);
  11113. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  11114. goto out;
  11115. }
  11116. mining_thr = p;
  11117. wr_unlock(&mining_thr_lock);
  11118. for (i = mining_threads; i < mining_threads_new; ++i) {
  11119. mining_thr[i] = calloc(1, sizeof(*thr));
  11120. if (!mining_thr[i])
  11121. {
  11122. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  11123. for ( ; --i >= mining_threads; )
  11124. free(mining_thr[i]);
  11125. goto out;
  11126. }
  11127. }
  11128. k = mining_threads;
  11129. for (i = 0; i < total_devices_new; ++i)
  11130. {
  11131. cgpu = devices_new[i];
  11132. allocate_cgpu(cgpu, &k);
  11133. }
  11134. for (i = 0; i < total_devices_new; ++i)
  11135. {
  11136. cgpu = devices_new[i];
  11137. start_cgpu(cgpu);
  11138. register_device(cgpu);
  11139. ++total_devices;
  11140. }
  11141. #ifdef HAVE_CURSES
  11142. switch_logsize();
  11143. #endif
  11144. out:
  11145. total_devices_new = 0;
  11146. devcount = total_devices - devcount;
  11147. mutex_unlock(&mutex);
  11148. return devcount;
  11149. }
  11150. int scan_serial(const char *s)
  11151. {
  11152. return create_new_cgpus(_scan_serial, (void*)s);
  11153. }
  11154. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  11155. static bool rescan_active;
  11156. static struct timeval tv_rescan;
  11157. static notifier_t rescan_notifier;
  11158. static
  11159. void *rescan_thread(__maybe_unused void *p)
  11160. {
  11161. pthread_detach(pthread_self());
  11162. RenameThread("rescan");
  11163. struct timeval tv_timeout, tv_now;
  11164. fd_set rfds;
  11165. while (true)
  11166. {
  11167. mutex_lock(&rescan_mutex);
  11168. tv_timeout = tv_rescan;
  11169. if (!timer_isset(&tv_timeout))
  11170. {
  11171. rescan_active = false;
  11172. mutex_unlock(&rescan_mutex);
  11173. break;
  11174. }
  11175. mutex_unlock(&rescan_mutex);
  11176. FD_ZERO(&rfds);
  11177. FD_SET(rescan_notifier[0], &rfds);
  11178. const int maxfd = rescan_notifier[0];
  11179. timer_set_now(&tv_now);
  11180. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  11181. notifier_read(rescan_notifier);
  11182. mutex_lock(&rescan_mutex);
  11183. if (timer_passed(&tv_rescan, NULL))
  11184. {
  11185. timer_unset(&tv_rescan);
  11186. mutex_unlock(&rescan_mutex);
  11187. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  11188. scan_serial(NULL);
  11189. }
  11190. else
  11191. mutex_unlock(&rescan_mutex);
  11192. }
  11193. return NULL;
  11194. }
  11195. static
  11196. void _schedule_rescan(const struct timeval * const tvp_when)
  11197. {
  11198. if (rescan_active)
  11199. {
  11200. if (timercmp(tvp_when, &tv_rescan, <))
  11201. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  11202. else
  11203. {
  11204. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  11205. tv_rescan = *tvp_when;
  11206. }
  11207. return;
  11208. }
  11209. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  11210. tv_rescan = *tvp_when;
  11211. rescan_active = true;
  11212. static pthread_t pth;
  11213. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  11214. applog(LOG_ERR, "Failed to start rescan thread");
  11215. }
  11216. static
  11217. void schedule_rescan(const struct timeval * const tvp_when)
  11218. {
  11219. mutex_lock(&rescan_mutex);
  11220. _schedule_rescan(tvp_when);
  11221. mutex_unlock(&rescan_mutex);
  11222. }
  11223. static
  11224. void hotplug_trigger()
  11225. {
  11226. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  11227. struct timeval tv_now;
  11228. timer_set_now(&tv_now);
  11229. schedule_rescan(&tv_now);
  11230. }
  11231. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  11232. static
  11233. void *hotplug_thread(__maybe_unused void *p)
  11234. {
  11235. pthread_detach(pthread_self());
  11236. RenameThread("hotplug");
  11237. struct udev * const udev = udev_new();
  11238. if (unlikely(!udev))
  11239. applogfailr(NULL, LOG_ERR, "udev_new");
  11240. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  11241. if (unlikely(!mon))
  11242. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  11243. if (unlikely(udev_monitor_enable_receiving(mon)))
  11244. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  11245. const int epfd = epoll_create(1);
  11246. if (unlikely(epfd == -1))
  11247. applogfailr(NULL, LOG_ERR, "epoll_create");
  11248. {
  11249. const int fd = udev_monitor_get_fd(mon);
  11250. struct epoll_event ev = {
  11251. .events = EPOLLIN | EPOLLPRI,
  11252. .data.fd = fd,
  11253. };
  11254. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  11255. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  11256. }
  11257. struct epoll_event ev;
  11258. int rv;
  11259. bool pending = false;
  11260. while (true)
  11261. {
  11262. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  11263. if (rv == -1)
  11264. {
  11265. if (errno == EAGAIN || errno == EINTR)
  11266. continue;
  11267. break;
  11268. }
  11269. if (!rv)
  11270. {
  11271. hotplug_trigger();
  11272. pending = false;
  11273. continue;
  11274. }
  11275. struct udev_device * const device = udev_monitor_receive_device(mon);
  11276. if (!device)
  11277. continue;
  11278. const char * const action = udev_device_get_action(device);
  11279. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  11280. if (!strcmp(action, "add"))
  11281. pending = true;
  11282. udev_device_unref(device);
  11283. }
  11284. applogfailr(NULL, LOG_ERR, "epoll_wait");
  11285. }
  11286. #elif defined(WIN32)
  11287. static UINT_PTR _hotplug_wintimer_id;
  11288. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  11289. {
  11290. KillTimer(NULL, _hotplug_wintimer_id);
  11291. _hotplug_wintimer_id = 0;
  11292. hotplug_trigger();
  11293. }
  11294. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  11295. {
  11296. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  11297. {
  11298. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  11299. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  11300. }
  11301. return DefWindowProc(hwnd, msg, wParam, lParam);
  11302. }
  11303. static
  11304. void *hotplug_thread(__maybe_unused void *p)
  11305. {
  11306. pthread_detach(pthread_self());
  11307. WNDCLASS DummyWinCls = {
  11308. .lpszClassName = "BFGDummyWinCls",
  11309. .lpfnWndProc = hotplug_win_callback,
  11310. };
  11311. ATOM a = RegisterClass(&DummyWinCls);
  11312. if (unlikely(!a))
  11313. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  11314. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  11315. if (unlikely(!hwnd))
  11316. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  11317. MSG msg;
  11318. while (GetMessage(&msg, NULL, 0, 0))
  11319. {
  11320. TranslateMessage(&msg);
  11321. DispatchMessage(&msg);
  11322. }
  11323. quit(0, "WM_QUIT received");
  11324. return NULL;
  11325. }
  11326. #endif
  11327. #ifdef HAVE_BFG_HOTPLUG
  11328. static
  11329. void hotplug_start()
  11330. {
  11331. pthread_t pth;
  11332. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  11333. applog(LOG_ERR, "Failed to start hotplug thread");
  11334. }
  11335. #endif
  11336. static void probe_pools(void)
  11337. {
  11338. int i;
  11339. for (i = 0; i < total_pools; i++) {
  11340. struct pool *pool = pools[i];
  11341. pool->testing = true;
  11342. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  11343. }
  11344. }
  11345. static void raise_fd_limits(void)
  11346. {
  11347. #ifdef HAVE_SETRLIMIT
  11348. struct rlimit fdlimit;
  11349. rlim_t old_soft_limit;
  11350. char frombuf[0x10] = "unlimited";
  11351. char hardbuf[0x10] = "unlimited";
  11352. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  11353. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  11354. old_soft_limit = fdlimit.rlim_cur;
  11355. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  11356. fdlimit.rlim_cur = FD_SETSIZE;
  11357. else
  11358. fdlimit.rlim_cur = fdlimit.rlim_max;
  11359. if (fdlimit.rlim_max != RLIM_INFINITY)
  11360. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  11361. if (old_soft_limit != RLIM_INFINITY)
  11362. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  11363. if (fdlimit.rlim_cur == old_soft_limit)
  11364. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11365. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  11366. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  11367. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11368. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11369. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  11370. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  11371. #else
  11372. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  11373. #endif
  11374. }
  11375. static
  11376. void bfg_atexit(void)
  11377. {
  11378. puts("");
  11379. }
  11380. extern void bfg_init_threadlocal();
  11381. extern void stratumsrv_start();
  11382. extern void test_aan_pll(void);
  11383. int main(int argc, char *argv[])
  11384. {
  11385. struct sigaction handler;
  11386. struct thr_info *thr;
  11387. unsigned int k;
  11388. int i;
  11389. int rearrange_pools = 0;
  11390. char *s;
  11391. #ifdef WIN32
  11392. LoadLibrary("backtrace.dll");
  11393. #endif
  11394. atexit(bfg_atexit);
  11395. b58_sha256_impl = my_blkmaker_sha256_callback;
  11396. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  11397. bfg_init_threadlocal();
  11398. #ifndef HAVE_PTHREAD_CANCEL
  11399. setup_pthread_cancel_workaround();
  11400. #endif
  11401. bfg_init_checksums();
  11402. #ifdef WIN32
  11403. {
  11404. WSADATA wsa;
  11405. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  11406. if (i)
  11407. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  11408. }
  11409. #endif
  11410. /* This dangerous functions tramples random dynamically allocated
  11411. * variables so do it before anything at all */
  11412. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  11413. quit(1, "Failed to curl_global_init");
  11414. initial_args = malloc(sizeof(char *) * (argc + 1));
  11415. for (i = 0; i < argc; i++)
  11416. initial_args[i] = strdup(argv[i]);
  11417. initial_args[argc] = NULL;
  11418. mutex_init(&hash_lock);
  11419. mutex_init(&console_lock);
  11420. cglock_init(&control_lock);
  11421. mutex_init(&stats_lock);
  11422. mutex_init(&sharelog_lock);
  11423. cglock_init(&ch_lock);
  11424. mutex_init(&sshare_lock);
  11425. rwlock_init(&blk_lock);
  11426. rwlock_init(&netacc_lock);
  11427. rwlock_init(&mining_thr_lock);
  11428. rwlock_init(&devices_lock);
  11429. mutex_init(&lp_lock);
  11430. if (unlikely(pthread_cond_init(&lp_cond, bfg_condattr)))
  11431. quit(1, "Failed to pthread_cond_init lp_cond");
  11432. if (unlikely(pthread_cond_init(&gws_cond, bfg_condattr)))
  11433. quit(1, "Failed to pthread_cond_init gws_cond");
  11434. notifier_init(submit_waiting_notifier);
  11435. timer_unset(&tv_rescan);
  11436. notifier_init(rescan_notifier);
  11437. /* Create a unique get work queue */
  11438. getq = tq_new();
  11439. if (!getq)
  11440. quit(1, "Failed to create getq");
  11441. /* We use the getq mutex as the staged lock */
  11442. stgd_lock = &getq->mutex;
  11443. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  11444. #ifdef WANT_CPUMINE
  11445. init_max_name_len();
  11446. #endif
  11447. handler.sa_handler = &sighandler;
  11448. handler.sa_flags = 0;
  11449. sigemptyset(&handler.sa_mask);
  11450. #ifdef HAVE_PTHREAD_CANCEL
  11451. sigaction(SIGTERM, &handler, &termhandler);
  11452. #else
  11453. // Need to let pthread_cancel emulation handle SIGTERM first
  11454. termhandler = pcwm_orig_term_handler;
  11455. pcwm_orig_term_handler = handler;
  11456. #endif
  11457. sigaction(SIGINT, &handler, &inthandler);
  11458. #ifndef WIN32
  11459. signal(SIGPIPE, SIG_IGN);
  11460. #else
  11461. timeBeginPeriod(1);
  11462. #endif
  11463. opt_kernel_path = CGMINER_PREFIX;
  11464. cgminer_path = alloca(PATH_MAX);
  11465. s = strdup(argv[0]);
  11466. strcpy(cgminer_path, dirname(s));
  11467. free(s);
  11468. strcat(cgminer_path, "/");
  11469. #if defined(WANT_CPUMINE) && defined(WIN32)
  11470. {
  11471. char buf[32];
  11472. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  11473. if (gev > 0 && gev < sizeof(buf))
  11474. {
  11475. setup_benchmark_pool();
  11476. double rate = bench_algo_stage3(atoi(buf));
  11477. // Write result to shared memory for parent
  11478. char unique_name[64];
  11479. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  11480. {
  11481. HANDLE map_handle = CreateFileMapping(
  11482. INVALID_HANDLE_VALUE, // use paging file
  11483. NULL, // default security attributes
  11484. PAGE_READWRITE, // read/write access
  11485. 0, // size: high 32-bits
  11486. 4096, // size: low 32-bits
  11487. unique_name // name of map object
  11488. );
  11489. if (NULL != map_handle) {
  11490. void *shared_mem = MapViewOfFile(
  11491. map_handle, // object to map view of
  11492. FILE_MAP_WRITE, // read/write access
  11493. 0, // high offset: map from
  11494. 0, // low offset: beginning
  11495. 0 // default: map entire file
  11496. );
  11497. if (NULL != shared_mem)
  11498. CopyMemory(shared_mem, &rate, sizeof(rate));
  11499. (void)UnmapViewOfFile(shared_mem);
  11500. }
  11501. (void)CloseHandle(map_handle);
  11502. }
  11503. exit(0);
  11504. }
  11505. }
  11506. #endif
  11507. #ifdef HAVE_CURSES
  11508. devcursor = 8;
  11509. logstart = devcursor;
  11510. logcursor = logstart;
  11511. #endif
  11512. mutex_init(&submitting_lock);
  11513. #ifdef HAVE_OPENCL
  11514. opencl_early_init();
  11515. #endif
  11516. schedstart.tm.tm_sec = 1;
  11517. schedstop .tm.tm_sec = 1;
  11518. opt_register_table(opt_early_table, NULL);
  11519. opt_register_table(opt_config_table, NULL);
  11520. opt_register_table(opt_cmdline_table, NULL);
  11521. opt_early_parse(argc, argv, applog_and_exit);
  11522. if (!config_loaded)
  11523. {
  11524. load_default_config();
  11525. rearrange_pools = total_pools;
  11526. }
  11527. opt_free_table();
  11528. /* parse command line */
  11529. opt_register_table(opt_config_table,
  11530. "Options for both config file and command line");
  11531. opt_register_table(opt_cmdline_table,
  11532. "Options for command line only");
  11533. opt_parse(&argc, argv, applog_and_exit);
  11534. if (argc != 1)
  11535. quit(1, "Unexpected extra commandline arguments");
  11536. if (rearrange_pools && rearrange_pools < total_pools)
  11537. {
  11538. // Prioritise commandline pools before default-config pools
  11539. for (i = 0; i < rearrange_pools; ++i)
  11540. pools[i]->prio += rearrange_pools;
  11541. for ( ; i < total_pools; ++i)
  11542. pools[i]->prio -= rearrange_pools;
  11543. }
  11544. #ifndef HAVE_PTHREAD_CANCEL
  11545. // Can't do this any earlier, or config isn't loaded
  11546. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  11547. #endif
  11548. #ifdef HAVE_PWD_H
  11549. struct passwd *user_info = NULL;
  11550. if (opt_setuid != NULL) {
  11551. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  11552. quit(1, "Unable to find setuid user information");
  11553. }
  11554. }
  11555. #endif
  11556. #ifdef HAVE_CHROOT
  11557. if (chroot_dir != NULL) {
  11558. #ifdef HAVE_PWD_H
  11559. if (user_info == NULL && getuid() == 0) {
  11560. applog(LOG_WARNING, "Running as root inside chroot");
  11561. }
  11562. #endif
  11563. if (chroot(chroot_dir) != 0) {
  11564. quit(1, "Unable to chroot");
  11565. }
  11566. if (chdir("/"))
  11567. quit(1, "Unable to chdir to chroot");
  11568. }
  11569. #endif
  11570. #ifdef HAVE_PWD_H
  11571. if (user_info != NULL) {
  11572. if (setgid((*user_info).pw_gid) != 0)
  11573. quit(1, "Unable to setgid");
  11574. if (setuid((*user_info).pw_uid) != 0)
  11575. quit(1, "Unable to setuid");
  11576. }
  11577. #endif
  11578. raise_fd_limits();
  11579. if (opt_benchmark) {
  11580. while (total_pools)
  11581. remove_pool(pools[0]);
  11582. setup_benchmark_pool();
  11583. }
  11584. if (opt_unittest) {
  11585. test_cgpu_match();
  11586. test_intrange();
  11587. test_decimal_width();
  11588. test_domain_funcs();
  11589. #ifdef USE_SCRYPT
  11590. test_scrypt();
  11591. #endif
  11592. test_target();
  11593. test_uri_get_param();
  11594. utf8_test();
  11595. #ifdef USE_JINGTIAN
  11596. test_aan_pll();
  11597. #endif
  11598. if (unittest_failures)
  11599. quit(1, "Unit tests failed");
  11600. }
  11601. #ifdef HAVE_CURSES
  11602. if (opt_realquiet || opt_display_devs)
  11603. use_curses = false;
  11604. setlocale(LC_ALL, "C");
  11605. if (use_curses)
  11606. enable_curses();
  11607. #endif
  11608. #ifdef HAVE_LIBUSB
  11609. int err = libusb_init(NULL);
  11610. if (err)
  11611. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  11612. else
  11613. have_libusb = true;
  11614. #endif
  11615. applog(LOG_WARNING, "Started %s", packagename);
  11616. {
  11617. struct bfg_loaded_configfile *configfile;
  11618. LL_FOREACH(bfg_loaded_configfiles, configfile)
  11619. {
  11620. char * const cnfbuf = configfile->filename;
  11621. int fileconf_load = configfile->fileconf_load;
  11622. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  11623. switch (fileconf_load) {
  11624. case 0:
  11625. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  11626. applog(LOG_WARNING, "Configuration file could not be used.");
  11627. break;
  11628. case -1:
  11629. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  11630. if (use_curses)
  11631. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  11632. break;
  11633. default:
  11634. break;
  11635. }
  11636. }
  11637. }
  11638. i = strlen(opt_kernel_path) + 2;
  11639. char __kernel_path[i];
  11640. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  11641. opt_kernel_path = __kernel_path;
  11642. if (want_per_device_stats)
  11643. opt_log_output = true;
  11644. bfg_devapi_init();
  11645. drv_detect_all();
  11646. total_devices = total_devices_new;
  11647. devices = devices_new;
  11648. total_devices_new = 0;
  11649. devices_new = NULL;
  11650. if (opt_display_devs) {
  11651. int devcount = 0;
  11652. applog(LOG_ERR, "Devices detected:");
  11653. for (i = 0; i < total_devices; ++i) {
  11654. struct cgpu_info *cgpu = devices[i];
  11655. char buf[0x100];
  11656. if (cgpu->device != cgpu)
  11657. continue;
  11658. if (cgpu->name)
  11659. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  11660. else
  11661. if (cgpu->dev_manufacturer)
  11662. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  11663. else
  11664. if (cgpu->dev_product)
  11665. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  11666. else
  11667. strcpy(buf, " Device");
  11668. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  11669. if (cgpu->dev_serial)
  11670. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  11671. if (cgpu->device_path)
  11672. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  11673. tailsprintf(buf, sizeof(buf), ")");
  11674. _applog(LOG_NOTICE, buf);
  11675. ++devcount;
  11676. }
  11677. quit(0, "%d devices listed", devcount);
  11678. }
  11679. mining_threads = 0;
  11680. for (i = 0; i < total_devices; ++i)
  11681. register_device(devices[i]);
  11682. if (!total_devices) {
  11683. applog(LOG_WARNING, "No devices detected!");
  11684. if (use_curses)
  11685. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  11686. else
  11687. applog(LOG_WARNING, "Waiting for devices");
  11688. }
  11689. #ifdef HAVE_CURSES
  11690. switch_logsize();
  11691. #endif
  11692. #if BLKMAKER_VERSION > 1
  11693. if (opt_load_bitcoin_conf && !(get_mining_goal("default")->malgo->algo != POW_SHA256D || opt_benchmark))
  11694. add_local_gbt(total_pools);
  11695. #endif
  11696. if (!total_pools) {
  11697. applog(LOG_WARNING, "Need to specify at least one pool server.");
  11698. #ifdef HAVE_CURSES
  11699. if (!use_curses || !input_pool(false))
  11700. #endif
  11701. quit(1, "Pool setup failed");
  11702. }
  11703. for (i = 0; i < total_pools; i++) {
  11704. struct pool *pool = pools[i];
  11705. size_t siz;
  11706. if (!pool->rpc_url)
  11707. quit(1, "No URI supplied for pool %u", i);
  11708. if (!pool->rpc_userpass) {
  11709. if (!pool->rpc_user || !pool->rpc_pass)
  11710. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  11711. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  11712. pool->rpc_userpass = malloc(siz);
  11713. if (!pool->rpc_userpass)
  11714. quit(1, "Failed to malloc userpass");
  11715. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  11716. }
  11717. }
  11718. /* Set the currentpool to pool with priority 0 */
  11719. validate_pool_priorities();
  11720. for (i = 0; i < total_pools; i++) {
  11721. struct pool *pool = pools[i];
  11722. if (!pool->prio)
  11723. currentpool = pool;
  11724. }
  11725. #ifdef HAVE_SYSLOG_H
  11726. if (use_syslog)
  11727. openlog(PACKAGE, LOG_PID, LOG_USER);
  11728. #endif
  11729. #if defined(unix) || defined(__APPLE__)
  11730. if (opt_stderr_cmd)
  11731. fork_monitor();
  11732. #endif // defined(unix)
  11733. mining_thr = calloc(mining_threads, sizeof(thr));
  11734. if (!mining_thr)
  11735. quit(1, "Failed to calloc mining_thr");
  11736. for (i = 0; i < mining_threads; i++) {
  11737. mining_thr[i] = calloc(1, sizeof(*thr));
  11738. if (!mining_thr[i])
  11739. quit(1, "Failed to calloc mining_thr[%d]", i);
  11740. }
  11741. total_control_threads = 6;
  11742. control_thr = calloc(total_control_threads, sizeof(*thr));
  11743. if (!control_thr)
  11744. quit(1, "Failed to calloc control_thr");
  11745. if (opt_benchmark)
  11746. goto begin_bench;
  11747. applog(LOG_NOTICE, "Probing for an alive pool");
  11748. do {
  11749. bool still_testing;
  11750. int i;
  11751. /* Look for at least one active pool before starting */
  11752. probe_pools();
  11753. do {
  11754. sleep(1);
  11755. if (pools_active)
  11756. break;
  11757. still_testing = false;
  11758. for (int i = 0; i < total_pools; ++i)
  11759. if (pools[i]->testing)
  11760. still_testing = true;
  11761. } while (still_testing);
  11762. if (!pools_active) {
  11763. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  11764. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  11765. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  11766. for (i = 0; i < total_pools; i++) {
  11767. struct pool *pool;
  11768. pool = pools[i];
  11769. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  11770. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  11771. }
  11772. #ifdef HAVE_CURSES
  11773. if (use_curses) {
  11774. halfdelay(150);
  11775. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  11776. if (getch() != ERR)
  11777. quit(0, "No servers could be used! Exiting.");
  11778. cbreak();
  11779. } else
  11780. #endif
  11781. quit(0, "No servers could be used! Exiting.");
  11782. }
  11783. } while (!pools_active);
  11784. #ifdef USE_SCRYPT
  11785. if (detect_algo == 1 && get_mining_goal("default")->malgo->algo != POW_SCRYPT) {
  11786. applog(LOG_NOTICE, "Detected scrypt algorithm");
  11787. set_malgo_scrypt();
  11788. }
  11789. #endif
  11790. detect_algo = 0;
  11791. begin_bench:
  11792. total_mhashes_done = 0;
  11793. for (i = 0; i < total_devices; i++) {
  11794. struct cgpu_info *cgpu = devices[i];
  11795. cgpu->rolling = cgpu->total_mhashes = 0;
  11796. }
  11797. cgtime(&total_tv_start);
  11798. cgtime(&total_tv_end);
  11799. miner_started = total_tv_start;
  11800. time_t miner_start_ts = time(NULL);
  11801. if (schedstart.tm.tm_sec)
  11802. localtime_r(&miner_start_ts, &schedstart.tm);
  11803. if (schedstop.tm.tm_sec)
  11804. localtime_r(&miner_start_ts, &schedstop .tm);
  11805. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  11806. // Initialise processors and threads
  11807. k = 0;
  11808. for (i = 0; i < total_devices; ++i) {
  11809. struct cgpu_info *cgpu = devices[i];
  11810. allocate_cgpu(cgpu, &k);
  11811. }
  11812. // Start threads
  11813. for (i = 0; i < total_devices; ++i) {
  11814. struct cgpu_info *cgpu = devices[i];
  11815. start_cgpu(cgpu);
  11816. }
  11817. #ifdef HAVE_OPENCL
  11818. for (i = 0; i < nDevs; i++)
  11819. pause_dynamic_threads(i);
  11820. #endif
  11821. #ifdef WANT_CPUMINE
  11822. if (opt_n_threads > 0)
  11823. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  11824. opt_n_threads, algo_names[opt_algo]);
  11825. #endif
  11826. cgtime(&total_tv_start);
  11827. cgtime(&total_tv_end);
  11828. if (!opt_benchmark)
  11829. {
  11830. pthread_t submit_thread;
  11831. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  11832. quit(1, "submit_work thread create failed");
  11833. }
  11834. watchpool_thr_id = 1;
  11835. thr = &control_thr[watchpool_thr_id];
  11836. /* start watchpool thread */
  11837. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  11838. quit(1, "watchpool thread create failed");
  11839. pthread_detach(thr->pth);
  11840. watchdog_thr_id = 2;
  11841. thr = &control_thr[watchdog_thr_id];
  11842. /* start watchdog thread */
  11843. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  11844. quit(1, "watchdog thread create failed");
  11845. pthread_detach(thr->pth);
  11846. #ifdef HAVE_OPENCL
  11847. /* Create reinit gpu thread */
  11848. gpur_thr_id = 3;
  11849. thr = &control_thr[gpur_thr_id];
  11850. thr->q = tq_new();
  11851. if (!thr->q)
  11852. quit(1, "tq_new failed for gpur_thr_id");
  11853. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  11854. quit(1, "reinit_gpu thread create failed");
  11855. #endif
  11856. /* Create API socket thread */
  11857. api_thr_id = 4;
  11858. thr = &control_thr[api_thr_id];
  11859. if (thr_info_create(thr, NULL, api_thread, thr))
  11860. quit(1, "API thread create failed");
  11861. #ifdef USE_LIBMICROHTTPD
  11862. if (httpsrv_port != -1)
  11863. httpsrv_start(httpsrv_port);
  11864. #endif
  11865. #ifdef USE_LIBEVENT
  11866. if (stratumsrv_port != -1)
  11867. stratumsrv_start();
  11868. #endif
  11869. #ifdef HAVE_BFG_HOTPLUG
  11870. if (opt_hotplug)
  11871. hotplug_start();
  11872. #endif
  11873. #ifdef HAVE_CURSES
  11874. /* Create curses input thread for keyboard input. Create this last so
  11875. * that we know all threads are created since this can call kill_work
  11876. * to try and shut down ll previous threads. */
  11877. input_thr_id = 5;
  11878. thr = &control_thr[input_thr_id];
  11879. if (thr_info_create(thr, NULL, input_thread, thr))
  11880. quit(1, "input thread create failed");
  11881. pthread_detach(thr->pth);
  11882. #endif
  11883. /* Just to be sure */
  11884. if (total_control_threads != 6)
  11885. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  11886. /* Once everything is set up, main() becomes the getwork scheduler */
  11887. while (42) {
  11888. int ts, max_staged = opt_queue;
  11889. struct pool *pool, *cp;
  11890. bool lagging = false;
  11891. struct curl_ent *ce;
  11892. struct work *work;
  11893. struct mining_algorithm *malgo = NULL;
  11894. cp = current_pool();
  11895. // Generally, each processor needs a new work, and all at once during work restarts
  11896. max_staged += base_queue;
  11897. mutex_lock(stgd_lock);
  11898. ts = __total_staged();
  11899. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  11900. lagging = true;
  11901. /* Wait until hash_pop tells us we need to create more work */
  11902. if (ts > max_staged) {
  11903. {
  11904. LL_FOREACH(mining_algorithms, malgo)
  11905. {
  11906. if (!malgo->goal_refs)
  11907. continue;
  11908. if (!malgo->base_queue)
  11909. continue;
  11910. if (malgo->staged < malgo->base_queue + opt_queue)
  11911. {
  11912. mutex_unlock(stgd_lock);
  11913. goto need_malgo_queued;
  11914. }
  11915. }
  11916. malgo = NULL;
  11917. }
  11918. staged_full = true;
  11919. pthread_cond_wait(&gws_cond, stgd_lock);
  11920. ts = __total_staged();
  11921. }
  11922. mutex_unlock(stgd_lock);
  11923. if (ts > max_staged)
  11924. continue;
  11925. need_malgo_queued: ;
  11926. work = make_work();
  11927. if (lagging && !pool_tset(cp, &cp->lagging)) {
  11928. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  11929. cp->getfail_occasions++;
  11930. total_go++;
  11931. }
  11932. pool = select_pool(lagging, malgo);
  11933. retry:
  11934. if (pool->has_stratum) {
  11935. while (!pool->stratum_active || !pool->stratum_notify) {
  11936. struct pool *altpool = select_pool(true, malgo);
  11937. if (altpool == pool && pool->has_stratum)
  11938. cgsleep_ms(5000);
  11939. pool = altpool;
  11940. goto retry;
  11941. }
  11942. gen_stratum_work(pool, work);
  11943. applog(LOG_DEBUG, "Generated stratum work");
  11944. stage_work(work);
  11945. continue;
  11946. }
  11947. if (pool->last_work_copy) {
  11948. mutex_lock(&pool->last_work_lock);
  11949. struct work *last_work = pool->last_work_copy;
  11950. if (!last_work)
  11951. {}
  11952. else
  11953. if (can_roll(last_work) && should_roll(last_work)) {
  11954. struct timeval tv_now;
  11955. cgtime(&tv_now);
  11956. free_work(work);
  11957. work = make_clone(pool->last_work_copy);
  11958. mutex_unlock(&pool->last_work_lock);
  11959. roll_work(work);
  11960. 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));
  11961. stage_work(work);
  11962. continue;
  11963. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  11964. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  11965. } else {
  11966. free_work(last_work);
  11967. pool->last_work_copy = NULL;
  11968. }
  11969. mutex_unlock(&pool->last_work_lock);
  11970. }
  11971. if (clone_available()) {
  11972. applog(LOG_DEBUG, "Cloned getwork work");
  11973. free_work(work);
  11974. continue;
  11975. }
  11976. if (opt_benchmark) {
  11977. get_benchmark_work(work, opt_benchmark_intense);
  11978. applog(LOG_DEBUG, "Generated benchmark work");
  11979. stage_work(work);
  11980. continue;
  11981. }
  11982. work->pool = pool;
  11983. ce = pop_curl_entry3(pool, 2);
  11984. /* obtain new work from bitcoin via JSON-RPC */
  11985. if (!get_upstream_work(work, ce->curl)) {
  11986. struct pool *next_pool;
  11987. /* Make sure the pool just hasn't stopped serving
  11988. * requests but is up as we'll keep hammering it */
  11989. push_curl_entry(ce, pool);
  11990. ++pool->seq_getfails;
  11991. pool_died(pool);
  11992. next_pool = select_pool(!opt_fail_only, malgo);
  11993. if (pool == next_pool) {
  11994. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  11995. cgsleep_ms(5000);
  11996. } else {
  11997. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  11998. pool = next_pool;
  11999. }
  12000. goto retry;
  12001. }
  12002. if (ts >= max_staged)
  12003. pool_tclear(pool, &pool->lagging);
  12004. if (pool_tclear(pool, &pool->idle))
  12005. pool_resus(pool);
  12006. applog(LOG_DEBUG, "Generated getwork work");
  12007. stage_work(work);
  12008. push_curl_entry(ce, pool);
  12009. }
  12010. return 0;
  12011. }