miner.c 306 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2012-2013 Andrew Smith
  5. * Copyright 2010 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef HAVE_CURSES
  14. #ifdef USE_UNICODE
  15. #define PDC_WIDE
  16. #endif
  17. // Must be before stdbool, since pdcurses typedefs bool :/
  18. #include <curses.h>
  19. #endif
  20. #include <ctype.h>
  21. #include <limits.h>
  22. #include <locale.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30. #include <time.h>
  31. #include <math.h>
  32. #include <stdarg.h>
  33. #include <assert.h>
  34. #include <signal.h>
  35. #include <wctype.h>
  36. #include <sys/stat.h>
  37. #include <sys/types.h>
  38. #include <dirent.h>
  39. #ifdef HAVE_PWD_H
  40. #include <pwd.h>
  41. #endif
  42. #ifndef WIN32
  43. #include <sys/resource.h>
  44. #include <sys/socket.h>
  45. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  46. #include <libudev.h>
  47. #include <sys/epoll.h>
  48. #define HAVE_BFG_HOTPLUG
  49. #endif
  50. #else
  51. #include <winsock2.h>
  52. #include <windows.h>
  53. #include <dbt.h>
  54. #define HAVE_BFG_HOTPLUG
  55. #endif
  56. #include <ccan/opt/opt.h>
  57. #include <jansson.h>
  58. #include <curl/curl.h>
  59. #include <libgen.h>
  60. #include <sha2.h>
  61. #include <utlist.h>
  62. #include <blkmaker.h>
  63. #include <blkmaker_jansson.h>
  64. #include <blktemplate.h>
  65. #include "compat.h"
  66. #include "deviceapi.h"
  67. #include "logging.h"
  68. #include "miner.h"
  69. #include "adl.h"
  70. #include "driver-cpu.h"
  71. #include "driver-opencl.h"
  72. #include "bench_block.h"
  73. #include "scrypt.h"
  74. #ifdef USE_AVALON
  75. #include "driver-avalon.h"
  76. #endif
  77. #ifdef HAVE_BFG_LOWLEVEL
  78. #include "lowlevel.h"
  79. #endif
  80. #if defined(unix) || defined(__APPLE__)
  81. #include <errno.h>
  82. #include <fcntl.h>
  83. #include <sys/wait.h>
  84. #endif
  85. #ifdef USE_SCRYPT
  86. #include "scrypt.h"
  87. #endif
  88. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  89. # define USE_FPGA
  90. #endif
  91. enum bfg_quit_summary {
  92. BQS_DEFAULT,
  93. BQS_NONE,
  94. BQS_DEVS,
  95. BQS_PROCS,
  96. BQS_DETAILED,
  97. };
  98. struct strategies strategies[] = {
  99. { "Failover" },
  100. { "Round Robin" },
  101. { "Rotate" },
  102. { "Load Balance" },
  103. { "Balance" },
  104. };
  105. static char packagename[256];
  106. bool opt_protocol;
  107. bool opt_dev_protocol;
  108. static bool opt_benchmark;
  109. static bool want_longpoll = true;
  110. static bool want_gbt = true;
  111. static bool want_getwork = true;
  112. #if BLKMAKER_VERSION > 1
  113. struct _cbscript_t {
  114. char *data;
  115. size_t sz;
  116. };
  117. static struct _cbscript_t opt_coinbase_script;
  118. static uint32_t template_nonce;
  119. #endif
  120. #if BLKMAKER_VERSION > 0
  121. char *opt_coinbase_sig;
  122. #endif
  123. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  124. static bool include_serial_in_statline;
  125. char *request_target_str;
  126. float request_pdiff = 1.0;
  127. double request_bdiff;
  128. static bool want_stratum = true;
  129. bool have_longpoll;
  130. int opt_skip_checks;
  131. bool want_per_device_stats;
  132. bool use_syslog;
  133. bool opt_quiet_work_updates;
  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. int opt_bench_algo = -1;
  149. unsigned long long global_hashrate;
  150. static bool opt_unittest = false;
  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. bool opt_scrypt;
  161. #else
  162. static char detect_algo;
  163. #endif
  164. bool opt_restart = true;
  165. #ifdef USE_LIBMICROHTTPD
  166. #include "httpsrv.h"
  167. int httpsrv_port = -1;
  168. #endif
  169. #ifdef USE_LIBEVENT
  170. int stratumsrv_port = -1;
  171. #endif
  172. const
  173. int rescan_delay_ms = 1000;
  174. #ifdef HAVE_BFG_HOTPLUG
  175. bool opt_hotplug = 1;
  176. const
  177. int hotplug_delay_ms = 100;
  178. #else
  179. const bool opt_hotplug;
  180. #endif
  181. struct string_elist *scan_devices;
  182. static struct string_elist *opt_set_device_list;
  183. bool opt_force_dev_init;
  184. static struct string_elist *opt_devices_enabled_list;
  185. static bool opt_display_devs;
  186. int total_devices;
  187. struct cgpu_info **devices;
  188. int total_devices_new;
  189. struct cgpu_info **devices_new;
  190. bool have_opencl;
  191. int opt_n_threads = -1;
  192. int mining_threads;
  193. int num_processors;
  194. #ifdef HAVE_CURSES
  195. bool use_curses = true;
  196. #else
  197. bool use_curses;
  198. #endif
  199. #ifdef HAVE_LIBUSB
  200. bool have_libusb;
  201. #endif
  202. static bool opt_submit_stale = true;
  203. static int opt_shares;
  204. static int opt_submit_threads = 0x40;
  205. bool opt_fail_only;
  206. bool opt_autofan;
  207. bool opt_autoengine;
  208. bool opt_noadl;
  209. char *opt_api_allow = NULL;
  210. char *opt_api_groups;
  211. char *opt_api_description = PACKAGE_STRING;
  212. int opt_api_port = 4028;
  213. bool opt_api_listen;
  214. bool opt_api_mcast;
  215. char *opt_api_mcast_addr = API_MCAST_ADDR;
  216. char *opt_api_mcast_code = API_MCAST_CODE;
  217. char *opt_api_mcast_des = "";
  218. int opt_api_mcast_port = 4028;
  219. bool opt_api_network;
  220. bool opt_delaynet;
  221. bool opt_disable_pool;
  222. static bool no_work;
  223. bool opt_worktime;
  224. bool opt_weighed_stats;
  225. char *opt_kernel_path;
  226. char *cgminer_path;
  227. #if defined(USE_BITFORCE)
  228. bool opt_bfl_noncerange;
  229. #endif
  230. #define QUIET (opt_quiet || opt_realquiet)
  231. struct thr_info *control_thr;
  232. struct thr_info **mining_thr;
  233. static int gwsched_thr_id;
  234. static int watchpool_thr_id;
  235. static int watchdog_thr_id;
  236. #ifdef HAVE_CURSES
  237. static int input_thr_id;
  238. #endif
  239. int gpur_thr_id;
  240. static int api_thr_id;
  241. static int total_control_threads;
  242. pthread_mutex_t hash_lock;
  243. static pthread_mutex_t *stgd_lock;
  244. pthread_mutex_t console_lock;
  245. cglock_t ch_lock;
  246. static pthread_rwlock_t blk_lock;
  247. static pthread_mutex_t sshare_lock;
  248. pthread_rwlock_t netacc_lock;
  249. pthread_rwlock_t mining_thr_lock;
  250. pthread_rwlock_t devices_lock;
  251. static pthread_mutex_t lp_lock;
  252. static pthread_cond_t lp_cond;
  253. pthread_cond_t gws_cond;
  254. bool shutting_down;
  255. double total_rolling;
  256. double total_mhashes_done;
  257. static struct timeval total_tv_start, total_tv_end;
  258. static struct timeval miner_started;
  259. cglock_t control_lock;
  260. pthread_mutex_t stats_lock;
  261. static pthread_mutex_t submitting_lock;
  262. static int total_submitting;
  263. static struct work *submit_waiting;
  264. notifier_t submit_waiting_notifier;
  265. int hw_errors;
  266. int total_accepted, total_rejected;
  267. int total_getworks, total_stale, total_discarded;
  268. uint64_t total_bytes_rcvd, total_bytes_sent;
  269. double total_diff1, total_bad_diff1;
  270. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  271. static int staged_rollable;
  272. unsigned int new_blocks;
  273. unsigned int found_blocks;
  274. unsigned int local_work;
  275. unsigned int total_go, total_ro;
  276. struct pool **pools;
  277. static struct pool *currentpool = NULL;
  278. int total_pools, enabled_pools;
  279. enum pool_strategy pool_strategy = POOL_FAILOVER;
  280. int opt_rotate_period;
  281. static int total_urls, total_users, total_passes;
  282. static
  283. #ifndef HAVE_CURSES
  284. const
  285. #endif
  286. bool curses_active;
  287. #ifdef HAVE_CURSES
  288. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  289. const
  290. #endif
  291. short default_bgcolor = COLOR_BLACK;
  292. static int attr_title = A_BOLD;
  293. #endif
  294. static
  295. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  296. bool use_unicode;
  297. static
  298. bool have_unicode_degrees;
  299. static
  300. wchar_t unicode_micro = 'u';
  301. #else
  302. const bool use_unicode;
  303. static
  304. const bool have_unicode_degrees;
  305. static
  306. const char unicode_micro = 'u';
  307. #endif
  308. #ifdef HAVE_CURSES
  309. #define U8_BAD_START "\xef\x80\x81"
  310. #define U8_BAD_END "\xef\x80\x80"
  311. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  312. bool selecting_device;
  313. unsigned selected_device;
  314. #endif
  315. static char current_block[40];
  316. /* Protected by ch_lock */
  317. static char *current_hash;
  318. static uint32_t current_block_id;
  319. char *current_fullhash;
  320. static char datestamp[40];
  321. static char blocktime[32];
  322. time_t block_time;
  323. static char best_share[8] = "0";
  324. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  325. static char block_diff[8];
  326. static char net_hashrate[10];
  327. uint64_t best_diff = 0;
  328. static bool known_blkheight_current;
  329. static uint32_t known_blkheight;
  330. static uint32_t known_blkheight_blkid;
  331. static uint64_t block_subsidy;
  332. struct block {
  333. char hash[40];
  334. UT_hash_handle hh;
  335. int block_no;
  336. };
  337. static struct block *blocks = NULL;
  338. int swork_id;
  339. /* For creating a hash database of stratum shares submitted that have not had
  340. * a response yet */
  341. struct stratum_share {
  342. UT_hash_handle hh;
  343. bool block;
  344. struct work *work;
  345. int id;
  346. };
  347. static struct stratum_share *stratum_shares = NULL;
  348. char *opt_socks_proxy = NULL;
  349. static const char def_conf[] = "bfgminer.conf";
  350. static bool config_loaded;
  351. static int include_count;
  352. #define JSON_INCLUDE_CONF "include"
  353. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  354. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  355. #define JSON_MAX_DEPTH 10
  356. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  357. char *cmd_idle, *cmd_sick, *cmd_dead;
  358. #if defined(unix) || defined(__APPLE__)
  359. static char *opt_stderr_cmd = NULL;
  360. static int forkpid;
  361. #endif // defined(unix)
  362. #ifdef HAVE_CHROOT
  363. char *chroot_dir;
  364. #endif
  365. #ifdef HAVE_PWD_H
  366. char *opt_setuid;
  367. #endif
  368. struct sigaction termhandler, inthandler;
  369. struct thread_q *getq;
  370. static int total_work;
  371. static bool staged_full;
  372. struct work *staged_work = NULL;
  373. struct schedtime {
  374. bool enable;
  375. struct tm tm;
  376. };
  377. struct schedtime schedstart;
  378. struct schedtime schedstop;
  379. bool sched_paused;
  380. static bool time_before(struct tm *tm1, struct tm *tm2)
  381. {
  382. if (tm1->tm_hour < tm2->tm_hour)
  383. return true;
  384. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  385. return true;
  386. return false;
  387. }
  388. static bool should_run(void)
  389. {
  390. struct tm tm;
  391. time_t tt;
  392. bool within_range;
  393. if (!schedstart.enable && !schedstop.enable)
  394. return true;
  395. tt = time(NULL);
  396. localtime_r(&tt, &tm);
  397. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  398. if (time_before(&schedstop.tm, &schedstart.tm))
  399. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  400. else
  401. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  402. if (within_range && !schedstop.enable)
  403. /* This is a once off event with no stop time set */
  404. schedstart.enable = false;
  405. return within_range;
  406. }
  407. void get_datestamp(char *f, size_t fsiz, time_t tt)
  408. {
  409. struct tm _tm;
  410. struct tm *tm = &_tm;
  411. if (tt == INVALID_TIMESTAMP)
  412. tt = time(NULL);
  413. localtime_r(&tt, tm);
  414. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  415. tm->tm_year + 1900,
  416. tm->tm_mon + 1,
  417. tm->tm_mday,
  418. tm->tm_hour,
  419. tm->tm_min,
  420. tm->tm_sec);
  421. }
  422. static
  423. void get_timestamp(char *f, size_t fsiz, time_t tt)
  424. {
  425. struct tm _tm;
  426. struct tm *tm = &_tm;
  427. localtime_r(&tt, tm);
  428. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  429. tm->tm_hour,
  430. tm->tm_min,
  431. tm->tm_sec);
  432. }
  433. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  434. static char exit_buf[512];
  435. static void applog_and_exit(const char *fmt, ...)
  436. {
  437. va_list ap;
  438. va_start(ap, fmt);
  439. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  440. va_end(ap);
  441. _applog(LOG_ERR, exit_buf);
  442. exit(1);
  443. }
  444. char *devpath_to_devid(const char *devpath)
  445. {
  446. #ifndef WIN32
  447. struct stat my_stat;
  448. if (stat(devpath, &my_stat))
  449. return NULL;
  450. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  451. memcpy(devs, "dev_t:", 6);
  452. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  453. #else
  454. if (!strncmp(devpath, "\\\\.\\", 4))
  455. devpath += 4;
  456. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  457. return NULL;
  458. devpath += 3;
  459. char *p;
  460. strtol(devpath, &p, 10);
  461. if (p[0])
  462. return NULL;
  463. const int sz = (p - devpath);
  464. char *devs = malloc(4 + sz + 1);
  465. sprintf(devs, "com:%s", devpath);
  466. #endif
  467. return devs;
  468. }
  469. static
  470. bool devpaths_match(const char * const ap, const char * const bp)
  471. {
  472. char * const a = devpath_to_devid(ap);
  473. if (!a)
  474. return false;
  475. char * const b = devpath_to_devid(bp);
  476. bool rv = false;
  477. if (b)
  478. {
  479. rv = !strcmp(a, b);
  480. free(b);
  481. }
  482. free(a);
  483. return rv;
  484. }
  485. static
  486. int proc_letter_to_number(const char *s, const char ** const rem)
  487. {
  488. int n = 0, c;
  489. for ( ; s[0]; ++s)
  490. {
  491. if (unlikely(n > INT_MAX / 26))
  492. break;
  493. c = tolower(s[0]) - 'a';
  494. if (unlikely(c < 0 || c > 25))
  495. break;
  496. if (unlikely(INT_MAX - c < n))
  497. break;
  498. n = (n * 26) + c;
  499. }
  500. *rem = s;
  501. return n;
  502. }
  503. static
  504. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  505. {
  506. // all - matches anything
  507. // d0 - matches all processors of device 0
  508. // d0-3 - matches all processors of device 0, 1, 2, or 3
  509. // d0a - matches first processor of device 0
  510. // 0 - matches processor 0
  511. // 0-4 - matches processors 0, 1, 2, 3, or 4
  512. // ___ - matches all processors on all devices using driver/name ___
  513. // ___0 - matches all processors of 0th device using driver/name ___
  514. // ___0a - matches first processor of 0th device using driver/name ___
  515. // @* - matches device with serial or path *
  516. // @*@a - matches first processor of device with serial or path *
  517. // ___@* - matches device with serial or path * using driver/name ___
  518. if (!strcasecmp(pattern, "all"))
  519. return true;
  520. const struct device_drv * const drv = cgpu->drv;
  521. const char *p = pattern, *p2;
  522. size_t L;
  523. int n, i, c = -1;
  524. int n2;
  525. int proc_first = -1, proc_last = -1;
  526. struct cgpu_info *device;
  527. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  528. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  529. // dname or name
  530. p = &pattern[L];
  531. else
  532. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  533. // d#
  534. ++p;
  535. else
  536. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  537. // # or @
  538. {}
  539. else
  540. return false;
  541. L = p - pattern;
  542. while (isspace(p[0]))
  543. ++p;
  544. if (p[0] == '@')
  545. {
  546. // Serial/path
  547. const char * const ser = &p[1];
  548. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  549. {}
  550. p2 = (p[0] == '@') ? &p[1] : p;
  551. const size_t serlen = (p - ser);
  552. p = "";
  553. n = n2 = 0;
  554. const char * const devpath = cgpu->device_path ?: "";
  555. const char * const devser = cgpu->dev_serial ?: "";
  556. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  557. {} // Match
  558. else
  559. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  560. {} // Match
  561. else
  562. {
  563. char devpath2[serlen + 1];
  564. memcpy(devpath2, ser, serlen);
  565. devpath2[serlen] = '\0';
  566. if (!devpaths_match(devpath, ser))
  567. return false;
  568. }
  569. }
  570. else
  571. {
  572. if (isdigit(p[0]))
  573. n = strtol(p, (void*)&p2, 0);
  574. else
  575. {
  576. n = 0;
  577. p2 = p;
  578. }
  579. if (p2[0] == '-')
  580. {
  581. ++p2;
  582. if (p2[0] && isdigit(p2[0]))
  583. n2 = strtol(p2, (void*)&p2, 0);
  584. else
  585. n2 = INT_MAX;
  586. }
  587. else
  588. n2 = n;
  589. if (p == pattern)
  590. {
  591. if (!p[0])
  592. return true;
  593. if (p2 && p2[0])
  594. goto invsyntax;
  595. for (i = n; i <= n2; ++i)
  596. {
  597. if (i >= total_devices)
  598. break;
  599. if (cgpu == devices[i])
  600. return true;
  601. }
  602. return false;
  603. }
  604. }
  605. if (p2[0])
  606. {
  607. proc_first = proc_letter_to_number(&p2[0], &p2);
  608. if (p2[0] == '-')
  609. {
  610. ++p2;
  611. if (p2[0])
  612. proc_last = proc_letter_to_number(p2, &p2);
  613. else
  614. proc_last = INT_MAX;
  615. }
  616. else
  617. proc_last = proc_first;
  618. if (p2[0])
  619. goto invsyntax;
  620. }
  621. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  622. {
  623. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  624. (!L) ||
  625. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  626. {} // Matched name or dname
  627. else
  628. return false;
  629. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  630. return false;
  631. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  632. return false;
  633. return true;
  634. }
  635. // d#
  636. c = -1;
  637. for (i = 0; ; ++i)
  638. {
  639. if (i == total_devices)
  640. return false;
  641. if (devices[i]->device != devices[i])
  642. continue;
  643. ++c;
  644. if (c < n)
  645. continue;
  646. if (c > n2)
  647. break;
  648. for (device = devices[i]; device; device = device->next_proc)
  649. {
  650. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  651. continue;
  652. if (device == cgpu)
  653. return true;
  654. }
  655. }
  656. return false;
  657. invsyntax:
  658. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  659. return false;
  660. }
  661. #define TEST_CGPU_MATCH(pattern) \
  662. if (!cgpu_match(pattern, &cgpu)) \
  663. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  664. // END TEST_CGPU_MATCH
  665. #define TEST_CGPU_NOMATCH(pattern) \
  666. if (cgpu_match(pattern, &cgpu)) \
  667. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  668. // END TEST_CGPU_MATCH
  669. static __maybe_unused
  670. void test_cgpu_match()
  671. {
  672. struct device_drv drv = {
  673. .dname = "test",
  674. .name = "TST",
  675. };
  676. struct cgpu_info cgpu = {
  677. .drv = &drv,
  678. .device = &cgpu,
  679. .device_id = 1,
  680. .proc_id = 1,
  681. .proc_repr = "TST 1b",
  682. }, cgpu0a = {
  683. .drv = &drv,
  684. .device = &cgpu0a,
  685. .device_id = 0,
  686. .proc_id = 0,
  687. .proc_repr = "TST 0a",
  688. }, cgpu1a = {
  689. .drv = &drv,
  690. .device = &cgpu0a,
  691. .device_id = 1,
  692. .proc_id = 0,
  693. .proc_repr = "TST 1a",
  694. };
  695. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  696. devices = devices_list;
  697. total_devices = 3;
  698. TEST_CGPU_MATCH("all")
  699. TEST_CGPU_MATCH("d1")
  700. TEST_CGPU_NOMATCH("d2")
  701. TEST_CGPU_MATCH("d0-5")
  702. TEST_CGPU_NOMATCH("d0-0")
  703. TEST_CGPU_NOMATCH("d2-5")
  704. TEST_CGPU_MATCH("d-1")
  705. TEST_CGPU_MATCH("d1-")
  706. TEST_CGPU_NOMATCH("d-0")
  707. TEST_CGPU_NOMATCH("d2-")
  708. TEST_CGPU_MATCH("2")
  709. TEST_CGPU_NOMATCH("3")
  710. TEST_CGPU_MATCH("1-2")
  711. TEST_CGPU_MATCH("2-3")
  712. TEST_CGPU_NOMATCH("1-1")
  713. TEST_CGPU_NOMATCH("3-4")
  714. TEST_CGPU_MATCH("TST")
  715. TEST_CGPU_MATCH("test")
  716. TEST_CGPU_MATCH("tst")
  717. TEST_CGPU_MATCH("TEST")
  718. TEST_CGPU_NOMATCH("TSF")
  719. TEST_CGPU_NOMATCH("TS")
  720. TEST_CGPU_NOMATCH("TSTF")
  721. TEST_CGPU_MATCH("TST1")
  722. TEST_CGPU_MATCH("test1")
  723. TEST_CGPU_MATCH("TST0-1")
  724. TEST_CGPU_MATCH("TST 1")
  725. TEST_CGPU_MATCH("TST 1-2")
  726. TEST_CGPU_MATCH("TEST 1-2")
  727. TEST_CGPU_NOMATCH("TST2")
  728. TEST_CGPU_NOMATCH("TST2-3")
  729. TEST_CGPU_NOMATCH("TST0-0")
  730. TEST_CGPU_MATCH("TST1b")
  731. TEST_CGPU_MATCH("tst1b")
  732. TEST_CGPU_NOMATCH("TST1c")
  733. TEST_CGPU_NOMATCH("TST1bb")
  734. TEST_CGPU_MATCH("TST0-1b")
  735. TEST_CGPU_NOMATCH("TST0-1c")
  736. TEST_CGPU_MATCH("TST1a-d")
  737. TEST_CGPU_NOMATCH("TST1a-a")
  738. TEST_CGPU_NOMATCH("TST1-a")
  739. TEST_CGPU_NOMATCH("TST1c-z")
  740. TEST_CGPU_NOMATCH("TST1c-")
  741. TEST_CGPU_MATCH("@")
  742. TEST_CGPU_NOMATCH("@abc")
  743. TEST_CGPU_MATCH("@@b")
  744. TEST_CGPU_NOMATCH("@@c")
  745. TEST_CGPU_MATCH("TST@")
  746. TEST_CGPU_NOMATCH("TST@abc")
  747. TEST_CGPU_MATCH("TST@@b")
  748. TEST_CGPU_NOMATCH("TST@@c")
  749. TEST_CGPU_MATCH("TST@@b-f")
  750. TEST_CGPU_NOMATCH("TST@@c-f")
  751. TEST_CGPU_NOMATCH("TST@@-a")
  752. cgpu.device_path = "/dev/test";
  753. cgpu.dev_serial = "testy";
  754. TEST_CGPU_MATCH("TST@/dev/test")
  755. TEST_CGPU_MATCH("TST@testy")
  756. TEST_CGPU_NOMATCH("TST@")
  757. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  758. TEST_CGPU_NOMATCH("TST@testy3@b")
  759. TEST_CGPU_MATCH("TST@/dev/test@b")
  760. TEST_CGPU_MATCH("TST@testy@b")
  761. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  762. TEST_CGPU_NOMATCH("TST@testy@c")
  763. cgpu.device_path = "usb:000:999";
  764. TEST_CGPU_MATCH("TST@usb:000:999")
  765. drv.dname = "test7";
  766. TEST_CGPU_MATCH("test7")
  767. TEST_CGPU_MATCH("TEST7")
  768. TEST_CGPU_NOMATCH("test&")
  769. TEST_CGPU_MATCH("test7 1-2")
  770. TEST_CGPU_MATCH("test7@testy@b")
  771. }
  772. static
  773. int cgpu_search(const char * const pattern, const int first)
  774. {
  775. int i;
  776. struct cgpu_info *cgpu;
  777. #define CHECK_CGPU_SEARCH do{ \
  778. cgpu = get_devices(i); \
  779. if (cgpu_match(pattern, cgpu)) \
  780. return i; \
  781. }while(0)
  782. for (i = first; i < total_devices; ++i)
  783. CHECK_CGPU_SEARCH;
  784. for (i = 0; i < first; ++i)
  785. CHECK_CGPU_SEARCH;
  786. #undef CHECK_CGPU_SEARCH
  787. return -1;
  788. }
  789. static pthread_mutex_t sharelog_lock;
  790. static FILE *sharelog_file = NULL;
  791. struct thr_info *get_thread(int thr_id)
  792. {
  793. struct thr_info *thr;
  794. rd_lock(&mining_thr_lock);
  795. thr = mining_thr[thr_id];
  796. rd_unlock(&mining_thr_lock);
  797. return thr;
  798. }
  799. static struct cgpu_info *get_thr_cgpu(int thr_id)
  800. {
  801. struct thr_info *thr = get_thread(thr_id);
  802. return thr->cgpu;
  803. }
  804. struct cgpu_info *get_devices(int id)
  805. {
  806. struct cgpu_info *cgpu;
  807. rd_lock(&devices_lock);
  808. cgpu = devices[id];
  809. rd_unlock(&devices_lock);
  810. return cgpu;
  811. }
  812. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  813. static FILE *noncelog_file = NULL;
  814. static
  815. void noncelog(const struct work * const work)
  816. {
  817. const int thr_id = work->thr_id;
  818. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  819. char buf[0x200], hash[65], data[161], midstate[65];
  820. int rv;
  821. size_t ret;
  822. bin2hex(hash, work->hash, 32);
  823. bin2hex(data, work->data, 80);
  824. bin2hex(midstate, work->midstate, 32);
  825. // timestamp,proc,hash,data,midstate
  826. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  827. (unsigned long)time(NULL), proc->proc_repr_ns,
  828. hash, data, midstate);
  829. if (unlikely(rv < 1))
  830. {
  831. applog(LOG_ERR, "noncelog printf error");
  832. return;
  833. }
  834. mutex_lock(&noncelog_lock);
  835. ret = fwrite(buf, rv, 1, noncelog_file);
  836. fflush(noncelog_file);
  837. mutex_unlock(&noncelog_lock);
  838. if (ret != 1)
  839. applog(LOG_ERR, "noncelog fwrite error");
  840. }
  841. static void sharelog(const char*disposition, const struct work*work)
  842. {
  843. char target[(sizeof(work->target) * 2) + 1];
  844. char hash[(sizeof(work->hash) * 2) + 1];
  845. char data[(sizeof(work->data) * 2) + 1];
  846. struct cgpu_info *cgpu;
  847. unsigned long int t;
  848. struct pool *pool;
  849. int thr_id, rv;
  850. char s[1024];
  851. size_t ret;
  852. if (!sharelog_file)
  853. return;
  854. thr_id = work->thr_id;
  855. cgpu = get_thr_cgpu(thr_id);
  856. pool = work->pool;
  857. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  858. bin2hex(target, work->target, sizeof(work->target));
  859. bin2hex(hash, work->hash, sizeof(work->hash));
  860. bin2hex(data, work->data, sizeof(work->data));
  861. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  862. 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);
  863. if (rv >= (int)(sizeof(s)))
  864. s[sizeof(s) - 1] = '\0';
  865. else if (rv < 0) {
  866. applog(LOG_ERR, "sharelog printf error");
  867. return;
  868. }
  869. mutex_lock(&sharelog_lock);
  870. ret = fwrite(s, rv, 1, sharelog_file);
  871. fflush(sharelog_file);
  872. mutex_unlock(&sharelog_lock);
  873. if (ret != 1)
  874. applog(LOG_ERR, "sharelog fwrite error");
  875. }
  876. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  877. /* Adjust all the pools' quota to the greatest common denominator after a pool
  878. * has been added or the quotas changed. */
  879. void adjust_quota_gcd(void)
  880. {
  881. unsigned long gcd, lowest_quota = ~0UL, quota;
  882. struct pool *pool;
  883. int i;
  884. for (i = 0; i < total_pools; i++) {
  885. pool = pools[i];
  886. quota = pool->quota;
  887. if (!quota)
  888. continue;
  889. if (quota < lowest_quota)
  890. lowest_quota = quota;
  891. }
  892. if (likely(lowest_quota < ~0UL)) {
  893. gcd = lowest_quota;
  894. for (i = 0; i < total_pools; i++) {
  895. pool = pools[i];
  896. quota = pool->quota;
  897. if (!quota)
  898. continue;
  899. while (quota % gcd)
  900. gcd--;
  901. }
  902. } else
  903. gcd = 1;
  904. for (i = 0; i < total_pools; i++) {
  905. pool = pools[i];
  906. pool->quota_used *= global_quota_gcd;
  907. pool->quota_used /= gcd;
  908. pool->quota_gcd = pool->quota / gcd;
  909. }
  910. global_quota_gcd = gcd;
  911. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  912. }
  913. /* Return value is ignored if not called from add_pool_details */
  914. struct pool *add_pool(void)
  915. {
  916. struct pool *pool;
  917. pool = calloc(sizeof(struct pool), 1);
  918. if (!pool)
  919. quit(1, "Failed to malloc pool in add_pool");
  920. pool->pool_no = pool->prio = total_pools;
  921. mutex_init(&pool->last_work_lock);
  922. mutex_init(&pool->pool_lock);
  923. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  924. quit(1, "Failed to pthread_cond_init in add_pool");
  925. cglock_init(&pool->data_lock);
  926. mutex_init(&pool->stratum_lock);
  927. timer_unset(&pool->swork.tv_transparency);
  928. /* Make sure the pool doesn't think we've been idle since time 0 */
  929. pool->tv_idle.tv_sec = ~0UL;
  930. cgtime(&pool->cgminer_stats.start_tv);
  931. pool->rpc_proxy = NULL;
  932. pool->quota = 1;
  933. adjust_quota_gcd();
  934. pool->sock = INVSOCK;
  935. pool->lp_socket = CURL_SOCKET_BAD;
  936. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  937. pools[total_pools++] = pool;
  938. return pool;
  939. }
  940. /* Pool variant of test and set */
  941. static bool pool_tset(struct pool *pool, bool *var)
  942. {
  943. bool ret;
  944. mutex_lock(&pool->pool_lock);
  945. ret = *var;
  946. *var = true;
  947. mutex_unlock(&pool->pool_lock);
  948. return ret;
  949. }
  950. bool pool_tclear(struct pool *pool, bool *var)
  951. {
  952. bool ret;
  953. mutex_lock(&pool->pool_lock);
  954. ret = *var;
  955. *var = false;
  956. mutex_unlock(&pool->pool_lock);
  957. return ret;
  958. }
  959. struct pool *current_pool(void)
  960. {
  961. struct pool *pool;
  962. cg_rlock(&control_lock);
  963. pool = currentpool;
  964. cg_runlock(&control_lock);
  965. return pool;
  966. }
  967. // Copied from ccan/opt/helpers.c
  968. static char *arg_bad(const char *fmt, const char *arg)
  969. {
  970. char *str = malloc(strlen(fmt) + strlen(arg));
  971. sprintf(str, fmt, arg);
  972. return str;
  973. }
  974. static
  975. char *opt_set_floatval(const char *arg, float *f)
  976. {
  977. char *endp;
  978. errno = 0;
  979. *f = strtof(arg, &endp);
  980. if (*endp || !arg[0])
  981. return arg_bad("'%s' is not a number", arg);
  982. if (errno)
  983. return arg_bad("'%s' is out of range", arg);
  984. return NULL;
  985. }
  986. static
  987. void opt_show_floatval(char buf[OPT_SHOW_LEN], const float *f)
  988. {
  989. snprintf(buf, OPT_SHOW_LEN, "%.1f", *f);
  990. }
  991. static
  992. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  993. {
  994. return opt_set_bool(b);
  995. }
  996. char *set_int_range(const char *arg, int *i, int min, int max)
  997. {
  998. char *err = opt_set_intval(arg, i);
  999. if (err)
  1000. return err;
  1001. if (*i < min || *i > max)
  1002. return "Value out of range";
  1003. return NULL;
  1004. }
  1005. static char *set_int_0_to_9999(const char *arg, int *i)
  1006. {
  1007. return set_int_range(arg, i, 0, 9999);
  1008. }
  1009. static char *set_int_1_to_65535(const char *arg, int *i)
  1010. {
  1011. return set_int_range(arg, i, 1, 65535);
  1012. }
  1013. static char *set_int_0_to_10(const char *arg, int *i)
  1014. {
  1015. return set_int_range(arg, i, 0, 10);
  1016. }
  1017. static char *set_int_1_to_10(const char *arg, int *i)
  1018. {
  1019. return set_int_range(arg, i, 1, 10);
  1020. }
  1021. char *set_strdup(const char *arg, char **p)
  1022. {
  1023. *p = strdup((char *)arg);
  1024. return NULL;
  1025. }
  1026. #if BLKMAKER_VERSION > 1
  1027. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  1028. {
  1029. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1030. if (!scriptsz)
  1031. return "Invalid address";
  1032. char *script = malloc(scriptsz);
  1033. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1034. free(script);
  1035. return "Failed to convert address to script";
  1036. }
  1037. p->data = script;
  1038. p->sz = scriptsz;
  1039. return NULL;
  1040. }
  1041. #endif
  1042. static
  1043. char *set_quit_summary(const char * const arg)
  1044. {
  1045. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1046. opt_quit_summary = BQS_NONE;
  1047. else
  1048. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1049. opt_quit_summary = BQS_DEVS;
  1050. else
  1051. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1052. opt_quit_summary = BQS_PROCS;
  1053. else
  1054. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1055. opt_quit_summary = BQS_DETAILED;
  1056. else
  1057. return "Quit summary must be one of none/devs/procs/detailed";
  1058. return NULL;
  1059. }
  1060. static void bdiff_target_leadzero(unsigned char *target, double diff);
  1061. char *set_request_diff(const char *arg, float *p)
  1062. {
  1063. unsigned char target[32];
  1064. char *e = opt_set_floatval(arg, p);
  1065. if (e)
  1066. return e;
  1067. request_bdiff = (double)*p * 0.9999847412109375;
  1068. bdiff_target_leadzero(target, request_bdiff);
  1069. request_target_str = malloc(65);
  1070. bin2hex(request_target_str, target, 32);
  1071. return NULL;
  1072. }
  1073. #ifdef NEED_BFG_LOWL_VCOM
  1074. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1075. #ifdef WIN32
  1076. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1077. {
  1078. char dev[PATH_MAX];
  1079. char *devp = dev;
  1080. size_t bufLen = 0x100;
  1081. tryagain: ;
  1082. char buf[bufLen];
  1083. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1084. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1085. bufLen *= 2;
  1086. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1087. goto tryagain;
  1088. }
  1089. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1090. }
  1091. size_t tLen;
  1092. memcpy(devp, "\\\\.\\", 4);
  1093. devp = &devp[4];
  1094. for (char *t = buf; *t; t += tLen) {
  1095. tLen = strlen(t) + 1;
  1096. if (strncmp("COM", t, 3))
  1097. continue;
  1098. memcpy(devp, t, tLen);
  1099. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1100. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1101. }
  1102. }
  1103. #else
  1104. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1105. {
  1106. char dev[PATH_MAX];
  1107. char *devp = dev;
  1108. DIR *D;
  1109. struct dirent *de;
  1110. const char devdir[] = "/dev";
  1111. const size_t devdirlen = sizeof(devdir) - 1;
  1112. char *devpath = devp;
  1113. char *devfile = devpath + devdirlen + 1;
  1114. D = opendir(devdir);
  1115. if (!D)
  1116. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1117. memcpy(devpath, devdir, devdirlen);
  1118. devpath[devdirlen] = '/';
  1119. while ( (de = readdir(D)) ) {
  1120. if (!strncmp(de->d_name, "cu.", 3)
  1121. //don't probe Bluetooth devices - causes bus errors and segfaults
  1122. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1123. goto trydev;
  1124. if (strncmp(de->d_name, "tty", 3))
  1125. continue;
  1126. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1127. continue;
  1128. trydev:
  1129. strcpy(devfile, de->d_name);
  1130. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1131. }
  1132. closedir(D);
  1133. }
  1134. #endif
  1135. #endif
  1136. static char *add_serial(const char *arg)
  1137. {
  1138. string_elist_add(arg, &scan_devices);
  1139. return NULL;
  1140. }
  1141. static
  1142. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1143. {
  1144. string_elist_add(arg, elist);
  1145. return NULL;
  1146. }
  1147. bool get_intrange(const char *arg, int *val1, int *val2)
  1148. {
  1149. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1150. char *p, *p2;
  1151. *val1 = strtol(arg, &p, 0);
  1152. if (arg == p)
  1153. // Zero-length ending number, invalid
  1154. return false;
  1155. while (true)
  1156. {
  1157. if (!p[0])
  1158. {
  1159. *val2 = *val1;
  1160. return true;
  1161. }
  1162. if (p[0] == '-')
  1163. break;
  1164. if (!isspace(p[0]))
  1165. // Garbage, invalid
  1166. return false;
  1167. ++p;
  1168. }
  1169. p2 = &p[1];
  1170. *val2 = strtol(p2, &p, 0);
  1171. if (p2 == p)
  1172. // Zero-length ending number, invalid
  1173. return false;
  1174. while (true)
  1175. {
  1176. if (!p[0])
  1177. return true;
  1178. if (!isspace(p[0]))
  1179. // Garbage, invalid
  1180. return false;
  1181. ++p;
  1182. }
  1183. }
  1184. static
  1185. void _test_intrange(const char *s, const int v[2])
  1186. {
  1187. int a[2];
  1188. if (!get_intrange(s, &a[0], &a[1]))
  1189. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1190. for (int i = 0; i < 2; ++i)
  1191. if (unlikely(a[i] != v[i]))
  1192. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1193. }
  1194. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1195. static
  1196. void _test_intrange_fail(const char *s)
  1197. {
  1198. int a[2];
  1199. if (get_intrange(s, &a[0], &a[1]))
  1200. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1201. }
  1202. static
  1203. void test_intrange()
  1204. {
  1205. _test_intrange("-1--2", -1, -2);
  1206. _test_intrange("-1-2", -1, 2);
  1207. _test_intrange("1--2", 1, -2);
  1208. _test_intrange("1-2", 1, 2);
  1209. _test_intrange("111-222", 111, 222);
  1210. _test_intrange(" 11 - 22 ", 11, 22);
  1211. _test_intrange("+11-+22", 11, 22);
  1212. _test_intrange("-1", -1, -1);
  1213. _test_intrange_fail("all");
  1214. _test_intrange_fail("1-");
  1215. _test_intrange_fail("");
  1216. _test_intrange_fail("1-54x");
  1217. }
  1218. static char *set_devices(char *arg)
  1219. {
  1220. if (*arg) {
  1221. if (*arg == '?') {
  1222. opt_display_devs = true;
  1223. return NULL;
  1224. }
  1225. } else
  1226. return "Invalid device parameters";
  1227. string_elist_add(arg, &opt_devices_enabled_list);
  1228. return NULL;
  1229. }
  1230. static char *set_balance(enum pool_strategy *strategy)
  1231. {
  1232. *strategy = POOL_BALANCE;
  1233. return NULL;
  1234. }
  1235. static char *set_loadbalance(enum pool_strategy *strategy)
  1236. {
  1237. *strategy = POOL_LOADBALANCE;
  1238. return NULL;
  1239. }
  1240. static char *set_rotate(const char *arg, int *i)
  1241. {
  1242. pool_strategy = POOL_ROTATE;
  1243. return set_int_range(arg, i, 0, 9999);
  1244. }
  1245. static char *set_rr(enum pool_strategy *strategy)
  1246. {
  1247. *strategy = POOL_ROUNDROBIN;
  1248. return NULL;
  1249. }
  1250. /* Detect that url is for a stratum protocol either via the presence of
  1251. * stratum+tcp or by detecting a stratum server response */
  1252. bool detect_stratum(struct pool *pool, char *url)
  1253. {
  1254. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1255. return false;
  1256. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1257. pool->rpc_url = strdup(url);
  1258. pool->has_stratum = true;
  1259. pool->stratum_url = pool->sockaddr_url;
  1260. return true;
  1261. }
  1262. return false;
  1263. }
  1264. static struct pool *add_url(void)
  1265. {
  1266. total_urls++;
  1267. if (total_urls > total_pools)
  1268. add_pool();
  1269. return pools[total_urls - 1];
  1270. }
  1271. static void setup_url(struct pool *pool, char *arg)
  1272. {
  1273. if (detect_stratum(pool, arg))
  1274. return;
  1275. opt_set_charp(arg, &pool->rpc_url);
  1276. if (strncmp(arg, "http://", 7) &&
  1277. strncmp(arg, "https://", 8)) {
  1278. const size_t L = strlen(arg);
  1279. char *httpinput;
  1280. httpinput = malloc(8 + L);
  1281. if (!httpinput)
  1282. quit(1, "Failed to malloc httpinput");
  1283. sprintf(httpinput, "http://%s", arg);
  1284. pool->rpc_url = httpinput;
  1285. }
  1286. }
  1287. static char *set_url(char *arg)
  1288. {
  1289. struct pool *pool = add_url();
  1290. setup_url(pool, arg);
  1291. return NULL;
  1292. }
  1293. static char *set_quota(char *arg)
  1294. {
  1295. char *semicolon = strchr(arg, ';'), *url;
  1296. int len, qlen, quota;
  1297. struct pool *pool;
  1298. if (!semicolon)
  1299. return "No semicolon separated quota;URL pair found";
  1300. len = strlen(arg);
  1301. *semicolon = '\0';
  1302. qlen = strlen(arg);
  1303. if (!qlen)
  1304. return "No parameter for quota found";
  1305. len -= qlen + 1;
  1306. if (len < 1)
  1307. return "No parameter for URL found";
  1308. quota = atoi(arg);
  1309. if (quota < 0)
  1310. return "Invalid negative parameter for quota set";
  1311. url = arg + qlen + 1;
  1312. pool = add_url();
  1313. setup_url(pool, url);
  1314. pool->quota = quota;
  1315. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1316. adjust_quota_gcd();
  1317. return NULL;
  1318. }
  1319. static char *set_user(const char *arg)
  1320. {
  1321. struct pool *pool;
  1322. total_users++;
  1323. if (total_users > total_pools)
  1324. add_pool();
  1325. pool = pools[total_users - 1];
  1326. opt_set_charp(arg, &pool->rpc_user);
  1327. return NULL;
  1328. }
  1329. static char *set_pass(const char *arg)
  1330. {
  1331. struct pool *pool;
  1332. total_passes++;
  1333. if (total_passes > total_pools)
  1334. add_pool();
  1335. pool = pools[total_passes - 1];
  1336. opt_set_charp(arg, &pool->rpc_pass);
  1337. return NULL;
  1338. }
  1339. static char *set_userpass(const char *arg)
  1340. {
  1341. struct pool *pool;
  1342. char *updup;
  1343. if (total_users != total_passes)
  1344. return "User + pass options must be balanced before userpass";
  1345. ++total_users;
  1346. ++total_passes;
  1347. if (total_users > total_pools)
  1348. add_pool();
  1349. pool = pools[total_users - 1];
  1350. updup = strdup(arg);
  1351. opt_set_charp(arg, &pool->rpc_userpass);
  1352. pool->rpc_user = strtok(updup, ":");
  1353. if (!pool->rpc_user)
  1354. return "Failed to find : delimited user info";
  1355. pool->rpc_pass = strtok(NULL, ":");
  1356. if (!pool->rpc_pass)
  1357. pool->rpc_pass = "";
  1358. return NULL;
  1359. }
  1360. static char *set_pool_priority(const char *arg)
  1361. {
  1362. struct pool *pool;
  1363. if (!total_pools)
  1364. return "Usage of --pool-priority before pools are defined does not make sense";
  1365. pool = pools[total_pools - 1];
  1366. opt_set_intval(arg, &pool->prio);
  1367. return NULL;
  1368. }
  1369. static char *set_pool_proxy(const char *arg)
  1370. {
  1371. struct pool *pool;
  1372. if (!total_pools)
  1373. return "Usage of --pool-proxy before pools are defined does not make sense";
  1374. if (!our_curl_supports_proxy_uris())
  1375. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1376. pool = pools[total_pools - 1];
  1377. opt_set_charp(arg, &pool->rpc_proxy);
  1378. return NULL;
  1379. }
  1380. static char *set_pool_force_rollntime(const char *arg)
  1381. {
  1382. struct pool *pool;
  1383. if (!total_pools)
  1384. return "Usage of --force-rollntime before pools are defined does not make sense";
  1385. pool = pools[total_pools - 1];
  1386. opt_set_intval(arg, &pool->force_rollntime);
  1387. return NULL;
  1388. }
  1389. static char *enable_debug(bool *flag)
  1390. {
  1391. *flag = true;
  1392. opt_debug_console = true;
  1393. /* Turn on verbose output, too. */
  1394. opt_log_output = true;
  1395. return NULL;
  1396. }
  1397. static char *set_schedtime(const char *arg, struct schedtime *st)
  1398. {
  1399. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1400. {
  1401. if (strcasecmp(arg, "now"))
  1402. return "Invalid time set, should be HH:MM";
  1403. } else
  1404. schedstop.tm.tm_sec = 0;
  1405. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1406. return "Invalid time set.";
  1407. st->enable = true;
  1408. return NULL;
  1409. }
  1410. static
  1411. char *set_log_file(char *arg)
  1412. {
  1413. char *r = "";
  1414. long int i = strtol(arg, &r, 10);
  1415. int fd, stderr_fd = fileno(stderr);
  1416. if ((!*r) && i >= 0 && i <= INT_MAX)
  1417. fd = i;
  1418. else
  1419. if (!strcmp(arg, "-"))
  1420. {
  1421. fd = fileno(stdout);
  1422. if (unlikely(fd == -1))
  1423. return "Standard output missing for log-file";
  1424. }
  1425. else
  1426. {
  1427. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1428. if (unlikely(fd == -1))
  1429. return "Failed to open log-file";
  1430. }
  1431. close(stderr_fd);
  1432. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1433. return "Failed to dup2 for log-file";
  1434. close(fd);
  1435. return NULL;
  1436. }
  1437. static
  1438. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1439. {
  1440. char *r = "";
  1441. long int i = strtol(arg, &r, 10);
  1442. static char *err = NULL;
  1443. const size_t errbufsz = 0x100;
  1444. free(err);
  1445. err = NULL;
  1446. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1447. *F = fdopen((int)i, mode);
  1448. if (!*F)
  1449. {
  1450. err = malloc(errbufsz);
  1451. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1452. (int)i, purpose);
  1453. return err;
  1454. }
  1455. } else if (!strcmp(arg, "-")) {
  1456. *F = (mode[0] == 'a') ? stdout : stdin;
  1457. if (!*F)
  1458. {
  1459. err = malloc(errbufsz);
  1460. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1461. (mode[0] == 'a') ? "out" : "in", purpose);
  1462. return err;
  1463. }
  1464. } else {
  1465. *F = fopen(arg, mode);
  1466. if (!*F)
  1467. {
  1468. err = malloc(errbufsz);
  1469. snprintf(err, errbufsz, "Failed to open %s for %s",
  1470. arg, purpose);
  1471. return err;
  1472. }
  1473. }
  1474. return NULL;
  1475. }
  1476. static char *set_noncelog(char *arg)
  1477. {
  1478. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1479. }
  1480. static char *set_sharelog(char *arg)
  1481. {
  1482. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1483. }
  1484. char *set_temp_cutoff(char *arg)
  1485. {
  1486. if (strchr(arg, ','))
  1487. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1488. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1489. char buf[0x100];
  1490. snprintf(buf, sizeof(buf), "all:temp-cutoff=%s", arg);
  1491. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1492. string_elist_add(buf, &opt_set_device_list);
  1493. return NULL;
  1494. }
  1495. char *set_temp_target(char *arg)
  1496. {
  1497. if (strchr(arg, ','))
  1498. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1499. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1500. char buf[0x100];
  1501. snprintf(buf, sizeof(buf), "all:temp-target=%s", arg);
  1502. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1503. string_elist_add(buf, &opt_set_device_list);
  1504. return NULL;
  1505. }
  1506. static char *set_api_allow(const char *arg)
  1507. {
  1508. opt_set_charp(arg, &opt_api_allow);
  1509. return NULL;
  1510. }
  1511. static char *set_api_groups(const char *arg)
  1512. {
  1513. opt_set_charp(arg, &opt_api_groups);
  1514. return NULL;
  1515. }
  1516. static char *set_api_description(const char *arg)
  1517. {
  1518. opt_set_charp(arg, &opt_api_description);
  1519. return NULL;
  1520. }
  1521. static char *set_api_mcast_des(const char *arg)
  1522. {
  1523. opt_set_charp(arg, &opt_api_mcast_des);
  1524. return NULL;
  1525. }
  1526. #ifdef USE_ICARUS
  1527. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1528. static char *set_icarus_options(const char *arg)
  1529. {
  1530. if (strchr(arg, ','))
  1531. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1532. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1533. char *opts = strdup(arg), *argdup;
  1534. argdup = opts;
  1535. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1536. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1537. char buf[0x100], *saveptr, *opt;
  1538. for (int i = 0; i < 4; ++i, ++sdf)
  1539. {
  1540. opt = strtok_r(opts, ":", &saveptr);
  1541. opts = NULL;
  1542. if (!opt)
  1543. break;
  1544. if (!opt[0])
  1545. continue;
  1546. for (int j = 0; j < 4; ++j)
  1547. {
  1548. snprintf(buf, sizeof(buf), "%s:%s=%s", drivers[j], sdf->optname, opt);
  1549. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1550. string_elist_add(buf, &opt_set_device_list);
  1551. }
  1552. }
  1553. free(argdup);
  1554. return NULL;
  1555. }
  1556. static char *set_icarus_timing(const char *arg)
  1557. {
  1558. if (strchr(arg, ','))
  1559. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1560. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1561. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1562. char buf[0x100];
  1563. for (int j = 0; j < 4; ++j)
  1564. {
  1565. snprintf(buf, sizeof(buf), "%s:timing=%s", drivers[j], arg);
  1566. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1567. string_elist_add(buf, &opt_set_device_list);
  1568. }
  1569. return NULL;
  1570. }
  1571. #endif
  1572. #ifdef USE_AVALON
  1573. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1574. static char *set_avalon_options(const char *arg)
  1575. {
  1576. if (strchr(arg, ','))
  1577. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1578. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1579. char *opts = strdup(arg), *argdup;
  1580. argdup = opts;
  1581. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1582. char buf[0x100], *saveptr, *opt;
  1583. for (int i = 0; i < 5; ++i, ++sdf)
  1584. {
  1585. opt = strtok_r(opts, ":", &saveptr);
  1586. opts = NULL;
  1587. if (!opt)
  1588. break;
  1589. if (!opt[0])
  1590. continue;
  1591. snprintf(buf, sizeof(buf), "avalon:%s=%s", sdf->optname, opt);
  1592. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1593. string_elist_add(buf, &opt_set_device_list);
  1594. }
  1595. free(argdup);
  1596. return NULL;
  1597. }
  1598. #endif
  1599. #ifdef USE_KLONDIKE
  1600. static char *set_klondike_options(const char *arg)
  1601. {
  1602. char buf[0x100];
  1603. int hashclock;
  1604. double temptarget;
  1605. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1606. {
  1607. default:
  1608. return "Unrecognised --klondike-options";
  1609. case 2:
  1610. snprintf(buf, sizeof(buf), "klondike:temp-target=%lf", temptarget);
  1611. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1612. string_elist_add(buf, &opt_set_device_list);
  1613. // fallthru
  1614. case 1:
  1615. snprintf(buf, sizeof(buf), "klondike:clock=%d", hashclock);
  1616. applog(LOG_DEBUG, "%s: Using --set-device %s", __func__, buf);
  1617. string_elist_add(buf, &opt_set_device_list);
  1618. }
  1619. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1620. return NULL;
  1621. }
  1622. #endif
  1623. __maybe_unused
  1624. static char *set_null(const char __maybe_unused *arg)
  1625. {
  1626. return NULL;
  1627. }
  1628. /* These options are available from config file or commandline */
  1629. static struct opt_table opt_config_table[] = {
  1630. #ifdef WANT_CPUMINE
  1631. OPT_WITH_ARG("--algo",
  1632. set_algo, show_algo, &opt_algo,
  1633. "Specify sha256 implementation for CPU mining:\n"
  1634. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1635. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1636. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1637. #ifdef WANT_SSE2_4WAY
  1638. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1639. #endif
  1640. #ifdef WANT_VIA_PADLOCK
  1641. "\n\tvia\t\tVIA padlock implementation"
  1642. #endif
  1643. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1644. #ifdef WANT_CRYPTOPP_ASM32
  1645. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1646. #endif
  1647. #ifdef WANT_X8632_SSE2
  1648. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1649. #endif
  1650. #ifdef WANT_X8664_SSE2
  1651. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1652. #endif
  1653. #ifdef WANT_X8664_SSE4
  1654. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1655. #endif
  1656. #ifdef WANT_ALTIVEC_4WAY
  1657. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1658. #endif
  1659. ),
  1660. OPT_WITH_ARG("-a",
  1661. set_algo, show_algo, &opt_algo,
  1662. opt_hidden),
  1663. #endif
  1664. OPT_WITH_ARG("--api-allow",
  1665. set_api_allow, NULL, NULL,
  1666. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1667. OPT_WITH_ARG("--api-description",
  1668. set_api_description, NULL, NULL,
  1669. "Description placed in the API status header, default: BFGMiner version"),
  1670. OPT_WITH_ARG("--api-groups",
  1671. set_api_groups, NULL, NULL,
  1672. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1673. OPT_WITHOUT_ARG("--api-listen",
  1674. opt_set_bool, &opt_api_listen,
  1675. "Enable API, default: disabled"),
  1676. OPT_WITHOUT_ARG("--api-mcast",
  1677. opt_set_bool, &opt_api_mcast,
  1678. "Enable API Multicast listener, default: disabled"),
  1679. OPT_WITH_ARG("--api-mcast-addr",
  1680. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1681. "API Multicast listen address"),
  1682. OPT_WITH_ARG("--api-mcast-code",
  1683. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1684. "Code expected in the API Multicast message, don't use '-'"),
  1685. OPT_WITH_ARG("--api-mcast-des",
  1686. set_api_mcast_des, NULL, NULL,
  1687. "Description appended to the API Multicast reply, default: ''"),
  1688. OPT_WITH_ARG("--api-mcast-port",
  1689. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1690. "API Multicast listen port"),
  1691. OPT_WITHOUT_ARG("--api-network",
  1692. opt_set_bool, &opt_api_network,
  1693. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1694. OPT_WITH_ARG("--api-port",
  1695. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1696. "Port number of miner API"),
  1697. #ifdef HAVE_ADL
  1698. OPT_WITHOUT_ARG("--auto-fan",
  1699. opt_set_bool, &opt_autofan,
  1700. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  1701. OPT_WITHOUT_ARG("--auto-gpu",
  1702. opt_set_bool, &opt_autoengine,
  1703. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  1704. #endif
  1705. OPT_WITHOUT_ARG("--balance",
  1706. set_balance, &pool_strategy,
  1707. "Change multipool strategy from failover to even share balance"),
  1708. OPT_WITHOUT_ARG("--benchmark",
  1709. opt_set_bool, &opt_benchmark,
  1710. "Run BFGMiner in benchmark mode - produces no shares"),
  1711. #if defined(USE_BITFORCE)
  1712. OPT_WITHOUT_ARG("--bfl-range",
  1713. opt_set_bool, &opt_bfl_noncerange,
  1714. "Use nonce range on bitforce devices if supported"),
  1715. #endif
  1716. #ifdef WANT_CPUMINE
  1717. OPT_WITH_ARG("--bench-algo",
  1718. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  1719. opt_hidden),
  1720. #endif
  1721. #ifdef HAVE_CHROOT
  1722. OPT_WITH_ARG("--chroot-dir",
  1723. opt_set_charp, NULL, &chroot_dir,
  1724. "Chroot to a directory right after startup"),
  1725. #endif
  1726. OPT_WITH_ARG("--cmd-idle",
  1727. opt_set_charp, NULL, &cmd_idle,
  1728. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1729. OPT_WITH_ARG("--cmd-sick",
  1730. opt_set_charp, NULL, &cmd_sick,
  1731. "Execute a command when a device is declared sick"),
  1732. OPT_WITH_ARG("--cmd-dead",
  1733. opt_set_charp, NULL, &cmd_dead,
  1734. "Execute a command when a device is declared dead"),
  1735. #if BLKMAKER_VERSION > 1
  1736. OPT_WITH_ARG("--coinbase-addr",
  1737. set_b58addr, NULL, &opt_coinbase_script,
  1738. "Set coinbase payout address for solo mining"),
  1739. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1740. set_b58addr, NULL, &opt_coinbase_script,
  1741. opt_hidden),
  1742. #endif
  1743. #if BLKMAKER_VERSION > 0
  1744. OPT_WITH_ARG("--coinbase-sig",
  1745. set_strdup, NULL, &opt_coinbase_sig,
  1746. "Set coinbase signature when possible"),
  1747. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1748. set_strdup, NULL, &opt_coinbase_sig,
  1749. opt_hidden),
  1750. #endif
  1751. #ifdef HAVE_CURSES
  1752. OPT_WITHOUT_ARG("--compact",
  1753. opt_set_bool, &opt_compact,
  1754. "Use compact display without per device statistics"),
  1755. #endif
  1756. #ifdef WANT_CPUMINE
  1757. OPT_WITH_ARG("--cpu-threads",
  1758. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1759. "Number of miner CPU threads"),
  1760. OPT_WITH_ARG("-t",
  1761. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1762. opt_hidden),
  1763. #endif
  1764. OPT_WITHOUT_ARG("--debug|-D",
  1765. enable_debug, &opt_debug,
  1766. "Enable debug output"),
  1767. OPT_WITHOUT_ARG("--debuglog",
  1768. opt_set_bool, &opt_debug,
  1769. "Enable debug logging"),
  1770. OPT_WITHOUT_ARG("--device-protocol-dump",
  1771. opt_set_bool, &opt_dev_protocol,
  1772. "Verbose dump of device protocol-level activities"),
  1773. OPT_WITH_ARG("--device|-d",
  1774. set_devices, NULL, NULL,
  1775. "Enable only devices matching pattern (default: all)"),
  1776. OPT_WITHOUT_ARG("--disable-rejecting",
  1777. opt_set_bool, &opt_disable_pool,
  1778. "Automatically disable pools that continually reject shares"),
  1779. #ifdef USE_LIBMICROHTTPD
  1780. OPT_WITH_ARG("--http-port",
  1781. opt_set_intval, opt_show_intval, &httpsrv_port,
  1782. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1783. #endif
  1784. OPT_WITH_ARG("--expiry",
  1785. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1786. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1787. OPT_WITH_ARG("-E",
  1788. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1789. opt_hidden),
  1790. OPT_WITH_ARG("--expiry-lp",
  1791. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1792. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1793. OPT_WITHOUT_ARG("--failover-only",
  1794. opt_set_bool, &opt_fail_only,
  1795. "Don't leak work to backup pools when primary pool is lagging"),
  1796. #ifdef USE_FPGA
  1797. OPT_WITHOUT_ARG("--force-dev-init",
  1798. opt_set_bool, &opt_force_dev_init,
  1799. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1800. #endif
  1801. #ifdef HAVE_OPENCL
  1802. OPT_WITH_ARG("--gpu-dyninterval",
  1803. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1804. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  1805. OPT_WITH_ARG("--gpu-platform",
  1806. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1807. "Select OpenCL platform ID to use for GPU mining"),
  1808. OPT_WITH_ARG("--gpu-threads",
  1809. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1810. "Number of threads per GPU (1 - 10) - one value for all or separate by commas for per card"),
  1811. OPT_WITH_ARG("-g",
  1812. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1813. opt_hidden),
  1814. #ifdef HAVE_ADL
  1815. OPT_WITH_ARG("--gpu-engine",
  1816. set_gpu_engine, NULL, NULL,
  1817. "GPU engine (over)clock range in MHz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  1818. OPT_WITH_ARG("--gpu-fan",
  1819. set_gpu_fan, NULL, NULL,
  1820. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  1821. OPT_WITH_ARG("--gpu-map",
  1822. set_gpu_map, NULL, NULL,
  1823. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1824. OPT_WITH_ARG("--gpu-memclock",
  1825. set_gpu_memclock, NULL, NULL,
  1826. "Set the GPU memory (over)clock in MHz - one value for all or separate by commas for per card"),
  1827. OPT_WITH_ARG("--gpu-memdiff",
  1828. set_gpu_memdiff, NULL, NULL,
  1829. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  1830. OPT_WITH_ARG("--gpu-powertune",
  1831. set_gpu_powertune, NULL, NULL,
  1832. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  1833. OPT_WITHOUT_ARG("--gpu-reorder",
  1834. opt_set_bool, &opt_reorder,
  1835. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1836. OPT_WITH_ARG("--gpu-vddc",
  1837. set_gpu_vddc, NULL, NULL,
  1838. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  1839. #endif
  1840. #ifdef USE_SCRYPT
  1841. OPT_WITH_ARG("--lookup-gap",
  1842. set_lookup_gap, NULL, NULL,
  1843. "Set GPU lookup gap for scrypt mining, comma separated"),
  1844. OPT_WITH_ARG("--intensity",
  1845. set_intensity, NULL, NULL,
  1846. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1847. " -> " MAX_SCRYPT_INTENSITY_STR
  1848. ",default: d to maintain desktop interactivity)"),
  1849. #else
  1850. OPT_WITH_ARG("--intensity",
  1851. set_intensity, NULL, NULL,
  1852. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1853. " -> " MAX_SHA_INTENSITY_STR
  1854. ",default: d to maintain desktop interactivity)"),
  1855. #endif
  1856. OPT_WITH_ARG("-I",
  1857. set_intensity, NULL, NULL,
  1858. opt_hidden),
  1859. #endif
  1860. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1861. OPT_WITH_ARG("--kernel-path",
  1862. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1863. "Specify a path to where bitstream and kernel files are"),
  1864. OPT_WITH_ARG("-K",
  1865. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1866. opt_hidden),
  1867. #endif
  1868. #ifdef HAVE_OPENCL
  1869. OPT_WITH_ARG("--kernel",
  1870. set_kernel, NULL, NULL,
  1871. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  1872. OPT_WITH_ARG("-k",
  1873. set_kernel, NULL, NULL,
  1874. opt_hidden),
  1875. #endif
  1876. #ifdef USE_ICARUS
  1877. OPT_WITH_ARG("--icarus-options",
  1878. set_icarus_options, NULL, NULL,
  1879. opt_hidden),
  1880. OPT_WITH_ARG("--icarus-timing",
  1881. set_icarus_timing, NULL, NULL,
  1882. opt_hidden),
  1883. #endif
  1884. #ifdef USE_AVALON
  1885. OPT_WITH_ARG("--avalon-options",
  1886. set_avalon_options, NULL, NULL,
  1887. opt_hidden),
  1888. #endif
  1889. #ifdef USE_KLONDIKE
  1890. OPT_WITH_ARG("--klondike-options",
  1891. set_klondike_options, NULL, NULL,
  1892. "Set klondike options clock:temptarget"),
  1893. #endif
  1894. OPT_WITHOUT_ARG("--load-balance",
  1895. set_loadbalance, &pool_strategy,
  1896. "Change multipool strategy from failover to quota based balance"),
  1897. OPT_WITH_ARG("--log|-l",
  1898. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1899. "Interval in seconds between log output"),
  1900. OPT_WITH_ARG("--log-file|-L",
  1901. set_log_file, NULL, NULL,
  1902. "Append log file for output messages"),
  1903. OPT_WITH_ARG("--logfile",
  1904. set_log_file, NULL, NULL,
  1905. opt_hidden),
  1906. OPT_WITHOUT_ARG("--log-microseconds",
  1907. opt_set_bool, &opt_log_microseconds,
  1908. "Include microseconds in log output"),
  1909. #if defined(unix) || defined(__APPLE__)
  1910. OPT_WITH_ARG("--monitor|-m",
  1911. opt_set_charp, NULL, &opt_stderr_cmd,
  1912. "Use custom pipe cmd for output messages"),
  1913. #endif // defined(unix)
  1914. OPT_WITHOUT_ARG("--net-delay",
  1915. opt_set_bool, &opt_delaynet,
  1916. "Impose small delays in networking to avoid overloading slow routers"),
  1917. OPT_WITHOUT_ARG("--no-adl",
  1918. opt_set_bool, &opt_noadl,
  1919. #ifdef HAVE_ADL
  1920. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1921. #else
  1922. opt_hidden
  1923. #endif
  1924. ),
  1925. OPT_WITHOUT_ARG("--no-gbt",
  1926. opt_set_invbool, &want_gbt,
  1927. "Disable getblocktemplate support"),
  1928. OPT_WITHOUT_ARG("--no-getwork",
  1929. opt_set_invbool, &want_getwork,
  1930. "Disable getwork support"),
  1931. OPT_WITHOUT_ARG("--no-hotplug",
  1932. #ifdef HAVE_BFG_HOTPLUG
  1933. opt_set_invbool, &opt_hotplug,
  1934. "Disable hotplug detection"
  1935. #else
  1936. set_null, &opt_hotplug,
  1937. opt_hidden
  1938. #endif
  1939. ),
  1940. OPT_WITHOUT_ARG("--no-longpoll",
  1941. opt_set_invbool, &want_longpoll,
  1942. "Disable X-Long-Polling support"),
  1943. OPT_WITHOUT_ARG("--no-pool-disable",
  1944. opt_set_invbool, &opt_disable_pool,
  1945. opt_hidden),
  1946. OPT_WITHOUT_ARG("--no-restart",
  1947. opt_set_invbool, &opt_restart,
  1948. "Do not attempt to restart devices that hang"
  1949. ),
  1950. OPT_WITHOUT_ARG("--no-show-processors",
  1951. opt_set_invbool, &opt_show_procs,
  1952. opt_hidden),
  1953. OPT_WITHOUT_ARG("--no-show-procs",
  1954. opt_set_invbool, &opt_show_procs,
  1955. opt_hidden),
  1956. OPT_WITHOUT_ARG("--no-stratum",
  1957. opt_set_invbool, &want_stratum,
  1958. "Disable Stratum detection"),
  1959. OPT_WITHOUT_ARG("--no-submit-stale",
  1960. opt_set_invbool, &opt_submit_stale,
  1961. "Don't submit shares if they are detected as stale"),
  1962. #ifdef HAVE_OPENCL
  1963. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1964. opt_set_invbool, &opt_opencl_binaries,
  1965. "Don't attempt to use or save OpenCL kernel binaries"),
  1966. #endif
  1967. OPT_WITHOUT_ARG("--no-unicode",
  1968. #ifdef USE_UNICODE
  1969. opt_set_invbool, &use_unicode,
  1970. "Don't use Unicode characters in TUI"
  1971. #else
  1972. set_null, &use_unicode,
  1973. opt_hidden
  1974. #endif
  1975. ),
  1976. OPT_WITH_ARG("--noncelog",
  1977. set_noncelog, NULL, NULL,
  1978. "Create log of all nonces found"),
  1979. OPT_WITH_ARG("--pass|-p",
  1980. set_pass, NULL, NULL,
  1981. "Password for bitcoin JSON-RPC server"),
  1982. OPT_WITHOUT_ARG("--per-device-stats",
  1983. opt_set_bool, &want_per_device_stats,
  1984. "Force verbose mode and output per-device statistics"),
  1985. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  1986. set_userpass, NULL, NULL,
  1987. opt_hidden),
  1988. OPT_WITH_ARG("--pool-priority",
  1989. set_pool_priority, NULL, NULL,
  1990. "Priority for just the previous-defined pool"),
  1991. OPT_WITH_ARG("--pool-proxy|-x",
  1992. set_pool_proxy, NULL, NULL,
  1993. "Proxy URI to use for connecting to just the previous-defined pool"),
  1994. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1995. set_pool_force_rollntime, NULL, NULL,
  1996. opt_hidden),
  1997. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1998. opt_set_bool, &opt_protocol,
  1999. "Verbose dump of protocol-level activities"),
  2000. OPT_WITH_ARG("--queue|-Q",
  2001. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2002. "Minimum number of work items to have queued (0+)"),
  2003. OPT_WITHOUT_ARG("--quiet|-q",
  2004. opt_set_bool, &opt_quiet,
  2005. "Disable logging output, display status and errors"),
  2006. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2007. opt_set_bool, &opt_quiet_work_updates,
  2008. opt_hidden),
  2009. OPT_WITH_ARG("--quit-summary",
  2010. set_quit_summary, NULL, NULL,
  2011. "Summary printed when you quit: none/devs/procs/detailed"),
  2012. OPT_WITH_ARG("--quota|-U",
  2013. set_quota, NULL, NULL,
  2014. "quota;URL combination for server with load-balance strategy quotas"),
  2015. OPT_WITHOUT_ARG("--real-quiet",
  2016. opt_set_bool, &opt_realquiet,
  2017. "Disable all output"),
  2018. OPT_WITH_ARG("--request-diff",
  2019. set_request_diff, opt_show_floatval, &request_pdiff,
  2020. "Request a specific difficulty from pools"),
  2021. OPT_WITH_ARG("--retries",
  2022. opt_set_intval, opt_show_intval, &opt_retries,
  2023. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2024. OPT_WITH_ARG("--retry-pause",
  2025. set_null, NULL, NULL,
  2026. opt_hidden),
  2027. OPT_WITH_ARG("--rotate",
  2028. set_rotate, opt_show_intval, &opt_rotate_period,
  2029. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2030. OPT_WITHOUT_ARG("--round-robin",
  2031. set_rr, &pool_strategy,
  2032. "Change multipool strategy from failover to round robin on failure"),
  2033. OPT_WITH_ARG("--scan|-S",
  2034. add_serial, NULL, NULL,
  2035. "Configure how to scan for mining devices"),
  2036. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2037. add_serial, NULL, NULL,
  2038. opt_hidden),
  2039. OPT_WITH_ARG("--scan-time",
  2040. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2041. "Upper bound on time spent scanning current work, in seconds"),
  2042. OPT_WITH_ARG("-s",
  2043. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2044. opt_hidden),
  2045. OPT_WITH_ARG("--scantime",
  2046. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2047. opt_hidden),
  2048. OPT_WITH_ARG("--sched-start",
  2049. set_schedtime, NULL, &schedstart,
  2050. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2051. OPT_WITH_ARG("--sched-stop",
  2052. set_schedtime, NULL, &schedstop,
  2053. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2054. #ifdef USE_SCRYPT
  2055. OPT_WITHOUT_ARG("--scrypt",
  2056. opt_set_bool, &opt_scrypt,
  2057. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2058. #endif
  2059. OPT_WITH_ARG("--set-device",
  2060. opt_string_elist_add, NULL, &opt_set_device_list,
  2061. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2062. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2063. OPT_WITH_ARG("--shaders",
  2064. set_shaders, NULL, NULL,
  2065. "GPU shaders per card for tuning scrypt, comma separated"),
  2066. #endif
  2067. #ifdef HAVE_PWD_H
  2068. OPT_WITH_ARG("--setuid",
  2069. opt_set_charp, NULL, &opt_setuid,
  2070. "Username of an unprivileged user to run as"),
  2071. #endif
  2072. OPT_WITH_ARG("--sharelog",
  2073. set_sharelog, NULL, NULL,
  2074. "Append share log to file"),
  2075. OPT_WITH_ARG("--shares",
  2076. opt_set_intval, NULL, &opt_shares,
  2077. "Quit after mining N shares (default: unlimited)"),
  2078. OPT_WITHOUT_ARG("--show-processors",
  2079. opt_set_bool, &opt_show_procs,
  2080. "Show per processor statistics in summary"),
  2081. OPT_WITHOUT_ARG("--show-procs",
  2082. opt_set_bool, &opt_show_procs,
  2083. opt_hidden),
  2084. OPT_WITH_ARG("--skip-security-checks",
  2085. set_int_0_to_9999, NULL, &opt_skip_checks,
  2086. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2087. OPT_WITH_ARG("--socks-proxy",
  2088. opt_set_charp, NULL, &opt_socks_proxy,
  2089. "Set socks proxy (host:port)"),
  2090. #ifdef USE_LIBEVENT
  2091. OPT_WITH_ARG("--stratum-port",
  2092. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2093. "Port number to listen on for stratum miners (-1 means disabled)"),
  2094. #endif
  2095. OPT_WITHOUT_ARG("--submit-stale",
  2096. opt_set_bool, &opt_submit_stale,
  2097. opt_hidden),
  2098. OPT_WITH_ARG("--submit-threads",
  2099. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2100. "Minimum number of concurrent share submissions (default: 64)"),
  2101. #ifdef HAVE_SYSLOG_H
  2102. OPT_WITHOUT_ARG("--syslog",
  2103. opt_set_bool, &use_syslog,
  2104. "Use system log for output messages (default: standard error)"),
  2105. #endif
  2106. OPT_WITH_ARG("--temp-cutoff",
  2107. set_temp_cutoff, NULL, &opt_cutofftemp,
  2108. opt_hidden),
  2109. OPT_WITH_ARG("--temp-hysteresis",
  2110. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2111. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2112. #ifdef HAVE_ADL
  2113. OPT_WITH_ARG("--temp-overheat",
  2114. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2115. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  2116. #endif
  2117. OPT_WITH_ARG("--temp-target",
  2118. set_temp_target, NULL, NULL,
  2119. opt_hidden),
  2120. OPT_WITHOUT_ARG("--text-only|-T",
  2121. opt_set_invbool, &use_curses,
  2122. #ifdef HAVE_CURSES
  2123. "Disable ncurses formatted screen output"
  2124. #else
  2125. opt_hidden
  2126. #endif
  2127. ),
  2128. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2129. OPT_WITH_ARG("--thread-concurrency",
  2130. set_thread_concurrency, NULL, NULL,
  2131. "Set GPU thread concurrency for scrypt mining, comma separated"),
  2132. #endif
  2133. #ifdef USE_UNICODE
  2134. OPT_WITHOUT_ARG("--unicode",
  2135. opt_set_bool, &use_unicode,
  2136. "Use Unicode characters in TUI"),
  2137. #endif
  2138. OPT_WITH_ARG("--url|-o",
  2139. set_url, NULL, NULL,
  2140. "URL for bitcoin JSON-RPC server"),
  2141. OPT_WITH_ARG("--user|-u",
  2142. set_user, NULL, NULL,
  2143. "Username for bitcoin JSON-RPC server"),
  2144. #ifdef HAVE_OPENCL
  2145. OPT_WITH_ARG("--vectors",
  2146. set_vector, NULL, NULL,
  2147. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  2148. OPT_WITH_ARG("-v",
  2149. set_vector, NULL, NULL,
  2150. opt_hidden),
  2151. #endif
  2152. OPT_WITHOUT_ARG("--verbose",
  2153. opt_set_bool, &opt_log_output,
  2154. "Log verbose output to stderr as well as status output"),
  2155. OPT_WITHOUT_ARG("--weighed-stats",
  2156. opt_set_bool, &opt_weighed_stats,
  2157. "Display statistics weighed to difficulty 1"),
  2158. #ifdef HAVE_OPENCL
  2159. OPT_WITH_ARG("--worksize",
  2160. set_worksize, NULL, NULL,
  2161. "Override detected optimal worksize - one value or comma separated list"),
  2162. OPT_WITH_ARG("-w",
  2163. set_worksize, NULL, NULL,
  2164. opt_hidden),
  2165. #endif
  2166. OPT_WITHOUT_ARG("--unittest",
  2167. opt_set_bool, &opt_unittest, opt_hidden),
  2168. OPT_WITH_ARG("--userpass|-O",
  2169. set_userpass, NULL, NULL,
  2170. "Username:Password pair for bitcoin JSON-RPC server"),
  2171. OPT_WITHOUT_ARG("--worktime",
  2172. opt_set_bool, &opt_worktime,
  2173. "Display extra work time debug information"),
  2174. OPT_WITH_ARG("--pools",
  2175. opt_set_bool, NULL, NULL, opt_hidden),
  2176. OPT_ENDTABLE
  2177. };
  2178. static char *load_config(const char *arg, void __maybe_unused *unused);
  2179. static int fileconf_load;
  2180. static char *parse_config(json_t *config, bool fileconf)
  2181. {
  2182. static char err_buf[200];
  2183. struct opt_table *opt;
  2184. json_t *val;
  2185. if (fileconf && !fileconf_load)
  2186. fileconf_load = 1;
  2187. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2188. char *p, *name, *sp;
  2189. /* We don't handle subtables. */
  2190. assert(!(opt->type & OPT_SUBTABLE));
  2191. if (!opt->names)
  2192. continue;
  2193. /* Pull apart the option name(s). */
  2194. name = strdup(opt->names);
  2195. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2196. char *err = "Invalid value";
  2197. /* Ignore short options. */
  2198. if (p[1] != '-')
  2199. continue;
  2200. val = json_object_get(config, p+2);
  2201. if (!val)
  2202. continue;
  2203. if (opt->type & OPT_HASARG) {
  2204. if (json_is_string(val)) {
  2205. err = opt->cb_arg(json_string_value(val),
  2206. opt->u.arg);
  2207. } else if (json_is_number(val)) {
  2208. char buf[256], *p, *q;
  2209. snprintf(buf, 256, "%f", json_number_value(val));
  2210. if ( (p = strchr(buf, '.')) ) {
  2211. // Trim /\.0*$/ to work properly with integer-only arguments
  2212. q = p;
  2213. while (*(++q) == '0') {}
  2214. if (*q == '\0')
  2215. *p = '\0';
  2216. }
  2217. err = opt->cb_arg(buf, opt->u.arg);
  2218. } else if (json_is_array(val)) {
  2219. int n, size = json_array_size(val);
  2220. err = NULL;
  2221. for (n = 0; n < size && !err; n++) {
  2222. if (json_is_string(json_array_get(val, n)))
  2223. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2224. else if (json_is_object(json_array_get(val, n)))
  2225. err = parse_config(json_array_get(val, n), false);
  2226. }
  2227. }
  2228. } else if (opt->type & OPT_NOARG) {
  2229. if (json_is_true(val))
  2230. err = opt->cb(opt->u.arg);
  2231. else if (json_is_boolean(val)) {
  2232. if (opt->cb == (void*)opt_set_bool)
  2233. err = opt_set_invbool(opt->u.arg);
  2234. else if (opt->cb == (void*)opt_set_invbool)
  2235. err = opt_set_bool(opt->u.arg);
  2236. }
  2237. }
  2238. if (err) {
  2239. /* Allow invalid values to be in configuration
  2240. * file, just skipping over them provided the
  2241. * JSON is still valid after that. */
  2242. if (fileconf) {
  2243. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2244. fileconf_load = -1;
  2245. } else {
  2246. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2247. p, err);
  2248. return err_buf;
  2249. }
  2250. }
  2251. }
  2252. free(name);
  2253. }
  2254. val = json_object_get(config, JSON_INCLUDE_CONF);
  2255. if (val && json_is_string(val))
  2256. return load_config(json_string_value(val), NULL);
  2257. return NULL;
  2258. }
  2259. char *cnfbuf = NULL;
  2260. static char *load_config(const char *arg, void __maybe_unused *unused)
  2261. {
  2262. json_error_t err;
  2263. json_t *config;
  2264. char *json_error;
  2265. size_t siz;
  2266. if (!cnfbuf)
  2267. cnfbuf = strdup(arg);
  2268. if (++include_count > JSON_MAX_DEPTH)
  2269. return JSON_MAX_DEPTH_ERR;
  2270. #if JANSSON_MAJOR_VERSION > 1
  2271. config = json_load_file(arg, 0, &err);
  2272. #else
  2273. config = json_load_file(arg, &err);
  2274. #endif
  2275. if (!json_is_object(config)) {
  2276. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2277. json_error = malloc(siz);
  2278. if (!json_error)
  2279. quit(1, "Malloc failure in json error");
  2280. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2281. return json_error;
  2282. }
  2283. config_loaded = true;
  2284. /* Parse the config now, so we can override it. That can keep pointers
  2285. * so don't free config object. */
  2286. return parse_config(config, true);
  2287. }
  2288. static void load_default_config(void)
  2289. {
  2290. cnfbuf = malloc(PATH_MAX);
  2291. #if defined(unix)
  2292. if (getenv("HOME") && *getenv("HOME")) {
  2293. strcpy(cnfbuf, getenv("HOME"));
  2294. strcat(cnfbuf, "/");
  2295. } else
  2296. strcpy(cnfbuf, "");
  2297. char *dirp = cnfbuf + strlen(cnfbuf);
  2298. strcpy(dirp, ".bfgminer/");
  2299. strcat(dirp, def_conf);
  2300. if (access(cnfbuf, R_OK))
  2301. // No BFGMiner config, try Cgminer's...
  2302. strcpy(dirp, ".cgminer/cgminer.conf");
  2303. #else
  2304. strcpy(cnfbuf, "");
  2305. strcat(cnfbuf, def_conf);
  2306. #endif
  2307. if (!access(cnfbuf, R_OK))
  2308. load_config(cnfbuf, NULL);
  2309. else {
  2310. free(cnfbuf);
  2311. cnfbuf = NULL;
  2312. }
  2313. }
  2314. extern const char *opt_argv0;
  2315. static char *opt_verusage_and_exit(const char *extra)
  2316. {
  2317. puts(packagename);
  2318. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2319. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2320. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2321. printf(" Options:%s\n", BFG_OPTLIST);
  2322. printf("%s", opt_usage(opt_argv0, extra));
  2323. fflush(stdout);
  2324. exit(0);
  2325. }
  2326. /* These options are parsed before anything else */
  2327. static struct opt_table opt_early_table[] = {
  2328. OPT_EARLY_WITH_ARG("--config|-c",
  2329. set_bool_ignore_arg, NULL, &config_loaded,
  2330. opt_hidden),
  2331. OPT_EARLY_WITHOUT_ARG("--no-config",
  2332. opt_set_bool, &config_loaded,
  2333. "Inhibit loading default config file"),
  2334. OPT_ENDTABLE
  2335. };
  2336. /* These options are available from commandline only */
  2337. static struct opt_table opt_cmdline_table[] = {
  2338. OPT_WITH_ARG("--config|-c",
  2339. load_config, NULL, NULL,
  2340. "Load a JSON-format configuration file\n"
  2341. "See example.conf for an example configuration."),
  2342. OPT_EARLY_WITHOUT_ARG("--no-config",
  2343. opt_set_bool, &config_loaded,
  2344. "Inhibit loading default config file"),
  2345. OPT_WITHOUT_ARG("--help|-h",
  2346. opt_verusage_and_exit, NULL,
  2347. "Print this message"),
  2348. #ifdef HAVE_OPENCL
  2349. OPT_WITHOUT_ARG("--ndevs|-n",
  2350. print_ndevs_and_exit, &nDevs,
  2351. opt_hidden),
  2352. #endif
  2353. OPT_WITHOUT_ARG("--version|-V",
  2354. opt_version_and_exit, packagename,
  2355. "Display version and exit"),
  2356. OPT_ENDTABLE
  2357. };
  2358. static bool jobj_binary(const json_t *obj, const char *key,
  2359. void *buf, size_t buflen, bool required)
  2360. {
  2361. const char *hexstr;
  2362. json_t *tmp;
  2363. tmp = json_object_get(obj, key);
  2364. if (unlikely(!tmp)) {
  2365. if (unlikely(required))
  2366. applog(LOG_ERR, "JSON key '%s' not found", key);
  2367. return false;
  2368. }
  2369. hexstr = json_string_value(tmp);
  2370. if (unlikely(!hexstr)) {
  2371. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2372. return false;
  2373. }
  2374. if (!hex2bin(buf, hexstr, buflen))
  2375. return false;
  2376. return true;
  2377. }
  2378. static void calc_midstate(struct work *work)
  2379. {
  2380. union {
  2381. unsigned char c[64];
  2382. uint32_t i[16];
  2383. } data;
  2384. swap32yes(&data.i[0], work->data, 16);
  2385. sha256_ctx ctx;
  2386. sha256_init(&ctx);
  2387. sha256_update(&ctx, data.c, 64);
  2388. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2389. swap32tole(work->midstate, work->midstate, 8);
  2390. }
  2391. static struct work *make_work(void)
  2392. {
  2393. struct work *work = calloc(1, sizeof(struct work));
  2394. if (unlikely(!work))
  2395. quit(1, "Failed to calloc work in make_work");
  2396. cg_wlock(&control_lock);
  2397. work->id = total_work++;
  2398. cg_wunlock(&control_lock);
  2399. return work;
  2400. }
  2401. /* This is the central place all work that is about to be retired should be
  2402. * cleaned to remove any dynamically allocated arrays within the struct */
  2403. void clean_work(struct work *work)
  2404. {
  2405. free(work->job_id);
  2406. bytes_free(&work->nonce2);
  2407. free(work->nonce1);
  2408. if (work->device_data_free_func)
  2409. work->device_data_free_func(work);
  2410. if (work->tmpl) {
  2411. struct pool *pool = work->pool;
  2412. mutex_lock(&pool->pool_lock);
  2413. bool free_tmpl = !--*work->tmpl_refcount;
  2414. mutex_unlock(&pool->pool_lock);
  2415. if (free_tmpl) {
  2416. blktmpl_free(work->tmpl);
  2417. free(work->tmpl_refcount);
  2418. }
  2419. }
  2420. memset(work, 0, sizeof(struct work));
  2421. }
  2422. /* All dynamically allocated work structs should be freed here to not leak any
  2423. * ram from arrays allocated within the work struct */
  2424. void free_work(struct work *work)
  2425. {
  2426. clean_work(work);
  2427. free(work);
  2428. }
  2429. static const char *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";
  2430. // Must only be called with ch_lock held!
  2431. static
  2432. void __update_block_title(const unsigned char *hash_swap)
  2433. {
  2434. if (hash_swap) {
  2435. char tmp[17];
  2436. // Only provided when the block has actually changed
  2437. free(current_hash);
  2438. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2439. bin2hex(tmp, &hash_swap[24], 8);
  2440. memset(current_hash, '.', 3);
  2441. memcpy(&current_hash[3], tmp, 17);
  2442. known_blkheight_current = false;
  2443. } else if (likely(known_blkheight_current)) {
  2444. return;
  2445. }
  2446. if (current_block_id == known_blkheight_blkid) {
  2447. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2448. if (known_blkheight < 1000000) {
  2449. memmove(&current_hash[3], &current_hash[11], 8);
  2450. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2451. }
  2452. known_blkheight_current = true;
  2453. }
  2454. }
  2455. static
  2456. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2457. {
  2458. if (known_blkheight == blkheight)
  2459. return;
  2460. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2461. cg_wlock(&ch_lock);
  2462. known_blkheight = blkheight;
  2463. known_blkheight_blkid = block_id;
  2464. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2465. if (block_id == current_block_id)
  2466. __update_block_title(NULL);
  2467. cg_wunlock(&ch_lock);
  2468. }
  2469. static
  2470. void pool_set_opaque(struct pool *pool, bool opaque)
  2471. {
  2472. if (pool->swork.opaque == opaque)
  2473. return;
  2474. pool->swork.opaque = opaque;
  2475. if (opaque)
  2476. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2477. pool->pool_no);
  2478. else
  2479. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2480. pool->pool_no);
  2481. }
  2482. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2483. {
  2484. json_t *res_val = json_object_get(val, "result");
  2485. json_t *tmp_val;
  2486. bool ret = false;
  2487. if (unlikely(detect_algo == 1)) {
  2488. json_t *tmp = json_object_get(res_val, "algorithm");
  2489. const char *v = tmp ? json_string_value(tmp) : "";
  2490. if (strncasecmp(v, "scrypt", 6))
  2491. detect_algo = 2;
  2492. }
  2493. if (work->tmpl) {
  2494. struct timeval tv_now;
  2495. cgtime(&tv_now);
  2496. const char *err = blktmpl_add_jansson(work->tmpl, res_val, tv_now.tv_sec);
  2497. if (err) {
  2498. applog(LOG_ERR, "blktmpl error: %s", err);
  2499. return false;
  2500. }
  2501. work->rolltime = blkmk_time_left(work->tmpl, tv_now.tv_sec);
  2502. #if BLKMAKER_VERSION > 1
  2503. if (opt_coinbase_script.sz)
  2504. {
  2505. bool newcb;
  2506. #if BLKMAKER_VERSION > 2
  2507. blkmk_init_generation2(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  2508. #else
  2509. newcb = !work->tmpl->cbtxn;
  2510. blkmk_init_generation(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  2511. #endif
  2512. if (newcb)
  2513. {
  2514. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, &template_nonce, sizeof(template_nonce));
  2515. if (ae < (ssize_t)sizeof(template_nonce))
  2516. 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);
  2517. ++template_nonce;
  2518. }
  2519. }
  2520. #endif
  2521. #if BLKMAKER_VERSION > 0
  2522. {
  2523. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  2524. static bool appenderr = false;
  2525. if (ae <= 0) {
  2526. if (opt_coinbase_sig) {
  2527. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2528. appenderr = true;
  2529. }
  2530. } else if (ae >= 3 || opt_coinbase_sig) {
  2531. const char *cbappend = opt_coinbase_sig;
  2532. const char full[] = PACKAGE " " VERSION;
  2533. if (!cbappend) {
  2534. if ((size_t)ae >= sizeof(full) - 1)
  2535. cbappend = full;
  2536. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2537. cbappend = PACKAGE;
  2538. else
  2539. cbappend = "BFG";
  2540. }
  2541. size_t cbappendsz = strlen(cbappend);
  2542. static bool truncatewarning = false;
  2543. if (cbappendsz <= (size_t)ae) {
  2544. if (cbappendsz < (size_t)ae)
  2545. // If we have space, include the trailing \0
  2546. ++cbappendsz;
  2547. ae = cbappendsz;
  2548. truncatewarning = false;
  2549. } else {
  2550. char *tmp = malloc(ae + 1);
  2551. memcpy(tmp, opt_coinbase_sig, ae);
  2552. tmp[ae] = '\0';
  2553. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2554. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2555. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2556. free(tmp);
  2557. truncatewarning = true;
  2558. }
  2559. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  2560. if (ae <= 0) {
  2561. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2562. appenderr = true;
  2563. } else
  2564. appenderr = false;
  2565. }
  2566. }
  2567. #endif
  2568. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2569. return false;
  2570. swap32yes(work->data, work->data, 80 / 4);
  2571. memcpy(&work->data[80], workpadding_bin, 48);
  2572. const struct blktmpl_longpoll_req *lp;
  2573. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2574. free(pool->lp_id);
  2575. pool->lp_id = strdup(lp->id);
  2576. #if 0 /* This just doesn't work :( */
  2577. curl_socket_t sock = pool->lp_socket;
  2578. if (sock != CURL_SOCKET_BAD) {
  2579. pool->lp_socket = CURL_SOCKET_BAD;
  2580. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2581. shutdown(sock, SHUT_RDWR);
  2582. }
  2583. #endif
  2584. }
  2585. }
  2586. else
  2587. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2588. applog(LOG_ERR, "JSON inval data");
  2589. return false;
  2590. }
  2591. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2592. // Calculate it ourselves
  2593. applog(LOG_DEBUG, "Calculating midstate locally");
  2594. calc_midstate(work);
  2595. }
  2596. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2597. applog(LOG_ERR, "JSON inval target");
  2598. return false;
  2599. }
  2600. if (work->tmpl) {
  2601. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2602. {
  2603. int p = (sizeof(work->target) - 1) - i;
  2604. unsigned char c = work->target[i];
  2605. work->target[i] = work->target[p];
  2606. work->target[p] = c;
  2607. }
  2608. }
  2609. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2610. uint32_t blkheight = json_number_value(tmp_val);
  2611. uint32_t block_id = ((uint32_t*)work->data)[1];
  2612. have_block_height(block_id, blkheight);
  2613. }
  2614. memset(work->hash, 0, sizeof(work->hash));
  2615. cgtime(&work->tv_staged);
  2616. pool_set_opaque(pool, !work->tmpl);
  2617. ret = true;
  2618. return ret;
  2619. }
  2620. /* Returns whether the pool supports local work generation or not. */
  2621. static bool pool_localgen(struct pool *pool)
  2622. {
  2623. return (pool->last_work_copy || pool->has_stratum);
  2624. }
  2625. int dev_from_id(int thr_id)
  2626. {
  2627. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2628. return cgpu->device_id;
  2629. }
  2630. /* Create an exponentially decaying average over the opt_log_interval */
  2631. void decay_time(double *f, double fadd, double fsecs)
  2632. {
  2633. double ftotal, fprop;
  2634. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2635. ftotal = 1.0 + fprop;
  2636. *f += (fadd * fprop);
  2637. *f /= ftotal;
  2638. }
  2639. static int __total_staged(void)
  2640. {
  2641. return HASH_COUNT(staged_work);
  2642. }
  2643. static int total_staged(void)
  2644. {
  2645. int ret;
  2646. mutex_lock(stgd_lock);
  2647. ret = __total_staged();
  2648. mutex_unlock(stgd_lock);
  2649. return ret;
  2650. }
  2651. #ifdef HAVE_CURSES
  2652. WINDOW *mainwin, *statuswin, *logwin;
  2653. #endif
  2654. double total_secs = 1.0;
  2655. static char statusline[256];
  2656. /* logstart is where the log window should start */
  2657. static int devcursor, logstart, logcursor;
  2658. #ifdef HAVE_CURSES
  2659. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2660. static int statusy;
  2661. static int devsummaryYOffset;
  2662. static int total_lines;
  2663. #endif
  2664. #ifdef HAVE_OPENCL
  2665. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2666. #endif
  2667. struct cgpu_info *cpus;
  2668. bool _bfg_console_cancel_disabled;
  2669. int _bfg_console_prev_cancelstate;
  2670. #ifdef HAVE_CURSES
  2671. #define lock_curses() bfg_console_lock()
  2672. #define unlock_curses() bfg_console_unlock()
  2673. static bool curses_active_locked(void)
  2674. {
  2675. bool ret;
  2676. lock_curses();
  2677. ret = curses_active;
  2678. if (!ret)
  2679. unlock_curses();
  2680. return ret;
  2681. }
  2682. // Cancellable getch
  2683. int my_cancellable_getch(void)
  2684. {
  2685. // This only works because the macro only hits direct getch() calls
  2686. typedef int (*real_getch_t)(void);
  2687. const real_getch_t real_getch = __real_getch;
  2688. int type, rv;
  2689. bool sct;
  2690. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2691. rv = real_getch();
  2692. if (sct)
  2693. pthread_setcanceltype(type, &type);
  2694. return rv;
  2695. }
  2696. #ifdef PDCURSES
  2697. static
  2698. int bfg_wresize(WINDOW *win, int lines, int columns)
  2699. {
  2700. int rv = wresize(win, lines, columns);
  2701. int x, y;
  2702. getyx(win, y, x);
  2703. if (unlikely(y >= lines || x >= columns))
  2704. {
  2705. if (y >= lines)
  2706. y = lines - 1;
  2707. if (x >= columns)
  2708. x = columns - 1;
  2709. wmove(win, y, x);
  2710. }
  2711. return rv;
  2712. }
  2713. #else
  2714. # define bfg_wresize wresize
  2715. #endif
  2716. #endif
  2717. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2718. {
  2719. va_list ap;
  2720. size_t presz = strlen(buf);
  2721. va_start(ap, fmt);
  2722. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2723. va_end(ap);
  2724. }
  2725. double stats_elapsed(struct cgminer_stats *stats)
  2726. {
  2727. struct timeval now;
  2728. double elapsed;
  2729. if (stats->start_tv.tv_sec == 0)
  2730. elapsed = total_secs;
  2731. else {
  2732. cgtime(&now);
  2733. elapsed = tdiff(&now, &stats->start_tv);
  2734. }
  2735. if (elapsed < 1.0)
  2736. elapsed = 1.0;
  2737. return elapsed;
  2738. }
  2739. bool drv_ready(struct cgpu_info *cgpu)
  2740. {
  2741. switch (cgpu->status) {
  2742. case LIFE_INIT:
  2743. case LIFE_DEAD2:
  2744. return false;
  2745. default:
  2746. return true;
  2747. }
  2748. }
  2749. double cgpu_utility(struct cgpu_info *cgpu)
  2750. {
  2751. double dev_runtime = cgpu_runtime(cgpu);
  2752. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2753. }
  2754. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  2755. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  2756. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  2757. }while(0)
  2758. static float
  2759. utility_to_hashrate(double utility)
  2760. {
  2761. return utility * 0x4444444;
  2762. }
  2763. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2764. static const int _unitbase = 4;
  2765. static
  2766. void pick_unit(float hashrate, unsigned char *unit)
  2767. {
  2768. unsigned char i;
  2769. if (hashrate == 0)
  2770. {
  2771. if (*unit < _unitbase)
  2772. *unit = _unitbase;
  2773. return;
  2774. }
  2775. hashrate *= 1e12;
  2776. for (i = 0; i < *unit; ++i)
  2777. hashrate /= 1e3;
  2778. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  2779. while (hashrate >= 999.95)
  2780. {
  2781. hashrate /= 1e3;
  2782. if (likely(_unitchar[*unit] != '?'))
  2783. ++*unit;
  2784. }
  2785. }
  2786. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2787. enum h2bs_fmt {
  2788. H2B_NOUNIT, // "xxx.x"
  2789. H2B_SHORT, // "xxx.xMH/s"
  2790. H2B_SPACED, // "xxx.x MH/s"
  2791. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  2792. };
  2793. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  2794. enum bfu_floatprec {
  2795. FUP_INTEGER,
  2796. FUP_HASHES,
  2797. FUP_BTC,
  2798. FUP_DIFF,
  2799. };
  2800. static
  2801. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2802. {
  2803. char *s = buf;
  2804. unsigned char prec, i, unit;
  2805. int rv = 0;
  2806. if (unitin == -1)
  2807. {
  2808. unit = 0;
  2809. hashrate_pick_unit(hashrate, &unit);
  2810. }
  2811. else
  2812. unit = unitin;
  2813. hashrate *= 1e12;
  2814. for (i = 0; i < unit; ++i)
  2815. hashrate /= 1000;
  2816. switch (fprec)
  2817. {
  2818. case FUP_HASHES:
  2819. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  2820. if (hashrate >= 99.995 || unit < 6)
  2821. prec = 1;
  2822. else
  2823. prec = 2;
  2824. _SNP("%5.*f", prec, hashrate);
  2825. break;
  2826. case FUP_INTEGER:
  2827. _SNP("%3d", (int)hashrate);
  2828. break;
  2829. case FUP_BTC:
  2830. if (hashrate >= 99.995)
  2831. prec = 0;
  2832. else
  2833. prec = 2;
  2834. _SNP("%5.*f", prec, hashrate);
  2835. break;
  2836. case FUP_DIFF:
  2837. if (unit > _unitbase)
  2838. _SNP("%.3g", hashrate);
  2839. else
  2840. _SNP("%u", (unsigned int)hashrate);
  2841. }
  2842. switch (fmt) {
  2843. case H2B_SPACED:
  2844. _SNP(" ");
  2845. case H2B_SHORT:
  2846. _SNP("%c%s", _unitchar[unit], measurement);
  2847. default:
  2848. break;
  2849. case H2B_SHORTV:
  2850. _SNP("%.1s%s", (unit == _unitbase) ? "" : &_unitchar[unit], measurement);
  2851. }
  2852. return rv;
  2853. }
  2854. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  2855. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  2856. static
  2857. 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)
  2858. {
  2859. unsigned char unit = 0;
  2860. bool allzero = true;
  2861. int i;
  2862. size_t delimsz = 0;
  2863. char *buf = buflist[0];
  2864. size_t bufsz = bufszlist[0];
  2865. size_t itemwidth = (floatprec ? 5 : 3);
  2866. if (!isarray)
  2867. delimsz = strlen(delim);
  2868. for (i = 0; i < count; ++i)
  2869. if (numbers[i] != 0)
  2870. {
  2871. pick_unit(numbers[i], &unit);
  2872. allzero = false;
  2873. }
  2874. if (allzero)
  2875. unit = _unitbase;
  2876. --count;
  2877. for (i = 0; i < count; ++i)
  2878. {
  2879. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  2880. if (isarray)
  2881. {
  2882. buf = buflist[i + 1];
  2883. bufsz = bufszlist[i + 1];
  2884. }
  2885. else
  2886. {
  2887. buf += itemwidth;
  2888. bufsz -= itemwidth;
  2889. if (delimsz > bufsz)
  2890. delimsz = bufsz;
  2891. memcpy(buf, delim, delimsz);
  2892. buf += delimsz;
  2893. bufsz -= delimsz;
  2894. }
  2895. }
  2896. // Last entry has the unit
  2897. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  2898. return buflist[0];
  2899. }
  2900. #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)
  2901. #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)
  2902. static
  2903. int percentf3(char * const buf, size_t sz, double p, const double t)
  2904. {
  2905. char *s = buf;
  2906. int rv = 0;
  2907. if (!p)
  2908. _SNP("none");
  2909. else
  2910. if (t <= p)
  2911. _SNP("100%%");
  2912. else
  2913. {
  2914. p /= t;
  2915. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  2916. _SNP(".%02.0f%%", p * 10000); // ".01%"
  2917. else
  2918. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  2919. _SNP("%.1f%%", p * 100); // "9.1%"
  2920. else
  2921. _SNP("%3.0f%%", p * 100); // " 99%"
  2922. }
  2923. return rv;
  2924. }
  2925. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  2926. static
  2927. void test_decimal_width()
  2928. {
  2929. // The pipe character at end of each line should perfectly line up
  2930. char printbuf[512];
  2931. char testbuf1[64];
  2932. char testbuf2[64];
  2933. char testbuf3[64];
  2934. char testbuf4[64];
  2935. double testn;
  2936. int width;
  2937. int saved;
  2938. // Hotspots around 0.1 and 0.01
  2939. saved = -1;
  2940. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  2941. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  2942. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  2943. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  2944. if (unlikely((saved != -1) && (width != saved))) {
  2945. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  2946. applog(LOG_ERR, "%s", printbuf);
  2947. }
  2948. saved = width;
  2949. }
  2950. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  2951. saved = -1;
  2952. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  2953. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2954. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2955. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2956. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  2957. if (unlikely((saved != -1) && (width != saved))) {
  2958. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  2959. applog(LOG_ERR, "%s", printbuf);
  2960. }
  2961. saved = width;
  2962. }
  2963. // Hotspot around unit transition boundary in pick_unit
  2964. saved = -1;
  2965. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  2966. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2967. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2968. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2969. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  2970. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  2971. if (unlikely((saved != -1) && (width != saved))) {
  2972. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  2973. applog(LOG_ERR, "%s", printbuf);
  2974. }
  2975. saved = width;
  2976. }
  2977. }
  2978. #ifdef HAVE_CURSES
  2979. static void adj_width(int var, int *length);
  2980. #endif
  2981. #ifdef HAVE_CURSES
  2982. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  2983. static
  2984. void format_statline(char *buf, size_t bufsz, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, int wnotaccepted, int waccepted, int hwerrs, int bad_diff1, int allnonces)
  2985. {
  2986. char rejpcbuf[6];
  2987. char bnbuf[6];
  2988. adj_width(accepted, &awidth);
  2989. adj_width(rejected, &rwidth);
  2990. adj_width(stale, &swidth);
  2991. adj_width(hwerrs, &hwwidth);
  2992. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  2993. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  2994. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  2995. cHr, aHr, uHr,
  2996. awidth, accepted,
  2997. rwidth, rejected,
  2998. swidth, stale,
  2999. rejpcbuf,
  3000. hwwidth, hwerrs,
  3001. bnbuf
  3002. );
  3003. }
  3004. #endif
  3005. static inline
  3006. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3007. {
  3008. if (!(use_unicode && have_unicode_degrees))
  3009. maybe_unicode = false;
  3010. if (temp && *temp > 0.)
  3011. if (maybe_unicode)
  3012. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3013. else
  3014. snprintf(buf, bufsz, "%4.1fC", *temp);
  3015. else
  3016. {
  3017. if (temp)
  3018. snprintf(buf, bufsz, " ");
  3019. if (maybe_unicode)
  3020. tailsprintf(buf, bufsz, " ");
  3021. }
  3022. tailsprintf(buf, bufsz, " | ");
  3023. }
  3024. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3025. {
  3026. #ifndef HAVE_CURSES
  3027. assert(for_curses == false);
  3028. #endif
  3029. struct device_drv *drv = cgpu->drv;
  3030. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3031. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[hashrate_style]];
  3032. char rejpcbuf[6];
  3033. char bnbuf[6];
  3034. double dev_runtime;
  3035. if (!opt_show_procs)
  3036. cgpu = cgpu->device;
  3037. dev_runtime = cgpu_runtime(cgpu);
  3038. double rolling, mhashes;
  3039. int accepted, rejected, stale;
  3040. double waccepted;
  3041. double wnotaccepted;
  3042. int hwerrs;
  3043. double bad_diff1, good_diff1;
  3044. rolling = mhashes = waccepted = wnotaccepted = 0;
  3045. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3046. {
  3047. struct cgpu_info *slave = cgpu;
  3048. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3049. {
  3050. slave->utility = slave->accepted / dev_runtime * 60;
  3051. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3052. rolling += slave->rolling;
  3053. mhashes += slave->total_mhashes;
  3054. if (opt_weighed_stats)
  3055. {
  3056. accepted += slave->diff_accepted;
  3057. rejected += slave->diff_rejected;
  3058. stale += slave->diff_stale;
  3059. }
  3060. else
  3061. {
  3062. accepted += slave->accepted;
  3063. rejected += slave->rejected;
  3064. stale += slave->stale;
  3065. }
  3066. waccepted += slave->diff_accepted;
  3067. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3068. hwerrs += slave->hw_errors;
  3069. bad_diff1 += slave->bad_diff1;
  3070. good_diff1 += slave->diff1;
  3071. if (opt_show_procs)
  3072. break;
  3073. }
  3074. }
  3075. double wtotal = (waccepted + wnotaccepted);
  3076. multi_format_unit_array2(
  3077. ((char*[]){cHr, aHr, uHr}),
  3078. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[hashrate_style]}),
  3079. true, "h/s", hashrate_style,
  3080. 3,
  3081. 1e6*rolling,
  3082. 1e6*mhashes / dev_runtime,
  3083. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3084. // Processor representation
  3085. #ifdef HAVE_CURSES
  3086. if (for_curses)
  3087. {
  3088. if (opt_show_procs)
  3089. snprintf(buf, bufsz, " %"PRIprepr": ", cgpu->proc_repr);
  3090. else
  3091. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3092. }
  3093. else
  3094. #endif
  3095. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3096. if (include_serial_in_statline && cgpu->dev_serial)
  3097. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3098. if (unlikely(cgpu->status == LIFE_INIT))
  3099. {
  3100. tailsprintf(buf, bufsz, "Initializing...");
  3101. return;
  3102. }
  3103. {
  3104. const size_t bufln = strlen(buf);
  3105. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3106. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3107. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3108. else
  3109. {
  3110. float temp = cgpu->temp;
  3111. if (!opt_show_procs)
  3112. {
  3113. // Find the highest temperature of all processors
  3114. struct cgpu_info *proc = cgpu;
  3115. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3116. if (proc->temp > temp)
  3117. temp = proc->temp;
  3118. }
  3119. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3120. }
  3121. }
  3122. #ifdef HAVE_CURSES
  3123. if (for_curses)
  3124. {
  3125. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3126. const char *cHrStats;
  3127. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3128. bool all_dead = true, all_off = true, all_rdrv = true;
  3129. struct cgpu_info *proc = cgpu;
  3130. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3131. {
  3132. switch (cHrStatsI) {
  3133. default:
  3134. if (proc->status == LIFE_WAIT)
  3135. cHrStatsI = 5;
  3136. case 5:
  3137. if (proc->deven == DEV_RECOVER_ERR)
  3138. cHrStatsI = 4;
  3139. case 4:
  3140. if (proc->deven == DEV_RECOVER)
  3141. cHrStatsI = 3;
  3142. case 3:
  3143. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3144. {
  3145. cHrStatsI = 1;
  3146. all_off = false;
  3147. }
  3148. else
  3149. {
  3150. if (likely(proc->deven == DEV_ENABLED))
  3151. all_off = false;
  3152. if (proc->deven != DEV_RECOVER_DRV)
  3153. all_rdrv = false;
  3154. }
  3155. case 1:
  3156. break;
  3157. }
  3158. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3159. all_dead = false;
  3160. if (opt_show_procs)
  3161. break;
  3162. }
  3163. if (unlikely(all_dead))
  3164. cHrStatsI = 0;
  3165. else
  3166. if (unlikely(all_off))
  3167. cHrStatsI = 2;
  3168. cHrStats = cHrStatsOpt[cHrStatsI];
  3169. if (cHrStatsI == 2 && all_rdrv)
  3170. cHrStats = " RST ";
  3171. format_statline(buf, bufsz,
  3172. cHrStats,
  3173. aHr, uHr,
  3174. accepted, rejected, stale,
  3175. wnotaccepted, waccepted,
  3176. hwerrs,
  3177. bad_diff1, bad_diff1 + good_diff1);
  3178. }
  3179. else
  3180. #endif
  3181. {
  3182. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3183. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3184. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3185. opt_log_interval,
  3186. cHr, aHr, uHr,
  3187. accepted,
  3188. rejected,
  3189. stale,
  3190. rejpcbuf,
  3191. hwerrs,
  3192. bnbuf
  3193. );
  3194. }
  3195. }
  3196. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3197. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3198. static void text_print_status(int thr_id)
  3199. {
  3200. struct cgpu_info *cgpu;
  3201. char logline[256];
  3202. cgpu = get_thr_cgpu(thr_id);
  3203. if (cgpu) {
  3204. get_statline(logline, sizeof(logline), cgpu);
  3205. printf("%s\n", logline);
  3206. }
  3207. }
  3208. #ifdef HAVE_CURSES
  3209. static int attr_bad = A_BOLD;
  3210. #ifdef WIN32
  3211. #define swprintf snwprintf
  3212. #endif
  3213. static
  3214. void bfg_waddstr(WINDOW *win, const char *s)
  3215. {
  3216. const char *p = s;
  3217. int32_t w;
  3218. int wlen;
  3219. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3220. while (true)
  3221. {
  3222. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3223. {
  3224. // Printable ASCII
  3225. ++p;
  3226. }
  3227. if (p != s)
  3228. waddnstr(win, s, p - s);
  3229. w = utf8_decode(p, &wlen);
  3230. if (unlikely(p[0] == '\xb5')) // HACK for Mu (SI prefix micro-)
  3231. {
  3232. w = unicode_micro;
  3233. wlen = 1;
  3234. }
  3235. s = p += wlen;
  3236. switch(w)
  3237. {
  3238. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3239. case '\0':
  3240. return;
  3241. case 0xf000: // "bad" off
  3242. wattroff(win, attr_bad);
  3243. break;
  3244. case 0xf001: // "bad" on
  3245. wattron(win, attr_bad);
  3246. break;
  3247. #ifdef USE_UNICODE
  3248. case '|':
  3249. wadd_wch(win, WACS_VLINE);
  3250. break;
  3251. #endif
  3252. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3253. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3254. if (!use_unicode)
  3255. {
  3256. waddch(win, '-');
  3257. break;
  3258. }
  3259. #ifdef USE_UNICODE
  3260. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3261. break;
  3262. #endif
  3263. case 0x2022:
  3264. if (w > WCHAR_MAX || !iswprint(w))
  3265. w = '*';
  3266. default:
  3267. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3268. {
  3269. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3270. if (iswprint(REPLACEMENT_CHAR))
  3271. w = REPLACEMENT_CHAR;
  3272. else
  3273. #endif
  3274. w = '?';
  3275. }
  3276. {
  3277. #ifdef USE_UNICODE
  3278. wchar_t wbuf[0x10];
  3279. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3280. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3281. waddnwstr(win, wbuf, wbuflen);
  3282. #else
  3283. wprintw(win, "%lc", (wint_t)w);
  3284. #endif
  3285. }
  3286. }
  3287. }
  3288. }
  3289. static inline
  3290. void bfg_hline(WINDOW *win, int y)
  3291. {
  3292. int maxx, __maybe_unused maxy;
  3293. getmaxyx(win, maxy, maxx);
  3294. #ifdef USE_UNICODE
  3295. if (use_unicode)
  3296. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3297. else
  3298. #endif
  3299. mvwhline(win, y, 0, '-', maxx);
  3300. }
  3301. // Spaces until end of line, using current attributes (ie, not completely clear)
  3302. static
  3303. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3304. {
  3305. int x, maxx;
  3306. int __maybe_unused y;
  3307. getmaxyx(win, y, maxx);
  3308. getyx(win, y, x);
  3309. const int space_count = (maxx - x) - offset;
  3310. // Check for negative - terminal too narrow
  3311. if (space_count <= 0)
  3312. return;
  3313. char buf[space_count];
  3314. memset(buf, ' ', space_count);
  3315. waddnstr(win, buf, space_count);
  3316. }
  3317. static int menu_attr = A_REVERSE;
  3318. #define CURBUFSIZ 256
  3319. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3320. char tmp42[CURBUFSIZ]; \
  3321. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3322. wmove(win, y, x); \
  3323. bfg_waddstr(win, tmp42); \
  3324. } while (0)
  3325. #define cg_wprintw(win, fmt, ...) do { \
  3326. char tmp42[CURBUFSIZ]; \
  3327. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3328. bfg_waddstr(win, tmp42); \
  3329. } while (0)
  3330. /* Must be called with curses mutex lock held and curses_active */
  3331. static void curses_print_status(const int ts)
  3332. {
  3333. struct pool *pool = currentpool;
  3334. struct timeval now, tv;
  3335. float efficiency;
  3336. double income;
  3337. int logdiv;
  3338. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3339. wattron(statuswin, attr_title);
  3340. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3341. timer_set_now(&now);
  3342. {
  3343. unsigned int days, hours;
  3344. div_t d;
  3345. timersub(&now, &miner_started, &tv);
  3346. d = div(tv.tv_sec, 86400);
  3347. days = d.quot;
  3348. d = div(d.rem, 3600);
  3349. hours = d.quot;
  3350. d = div(d.rem, 60);
  3351. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3352. , days
  3353. , (days == 1) ? ' ' : 's'
  3354. , hours
  3355. , d.quot
  3356. , d.rem
  3357. );
  3358. }
  3359. bfg_wspctoeol(statuswin, 0);
  3360. wattroff(statuswin, attr_title);
  3361. wattron(statuswin, menu_attr);
  3362. wmove(statuswin, 1, 0);
  3363. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3364. bfg_wspctoeol(statuswin, 14);
  3365. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3366. wattroff(statuswin, menu_attr);
  3367. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  3368. cg_mvwprintw(statuswin, 2, 0, " Connected to multiple pools with%s block change notify",
  3369. have_longpoll ? "": "out");
  3370. } else if (pool->has_stratum) {
  3371. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with stratum as user %s",
  3372. pool->sockaddr_url, pool->diff, pool->rpc_user);
  3373. } else {
  3374. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with%s LP as user %s",
  3375. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out", pool->rpc_user);
  3376. }
  3377. wclrtoeol(statuswin);
  3378. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3379. current_hash, block_diff, net_hashrate, blocktime);
  3380. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3381. char bwstr[12], incomestr[13];
  3382. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3383. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3384. ts,
  3385. total_go + total_ro,
  3386. new_blocks,
  3387. total_submitting,
  3388. multi_format_unit2(bwstr, sizeof(bwstr),
  3389. false, "B/s", H2B_SHORT, "/", 2,
  3390. (float)(total_bytes_rcvd / total_secs),
  3391. (float)(total_bytes_sent / total_secs)),
  3392. efficiency,
  3393. incomestr,
  3394. best_share);
  3395. wclrtoeol(statuswin);
  3396. mvwaddstr(statuswin, 5, 0, " ");
  3397. bfg_waddstr(statuswin, statusline);
  3398. wclrtoeol(statuswin);
  3399. logdiv = statusy - 1;
  3400. bfg_hline(statuswin, 6);
  3401. bfg_hline(statuswin, logdiv);
  3402. #ifdef USE_UNICODE
  3403. if (use_unicode)
  3404. {
  3405. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3406. if (opt_show_procs && !opt_compact)
  3407. ++offset; // proc letter
  3408. if (have_unicode_degrees)
  3409. ++offset; // degrees symbol
  3410. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3411. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3412. offset += 24; // hashrates etc
  3413. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3414. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3415. }
  3416. #endif
  3417. }
  3418. static void adj_width(int var, int *length)
  3419. {
  3420. if ((int)(log10(var) + 1) > *length)
  3421. (*length)++;
  3422. }
  3423. static int dev_width;
  3424. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3425. {
  3426. char logline[256];
  3427. int ypos;
  3428. if (opt_compact)
  3429. return;
  3430. /* Check this isn't out of the window size */
  3431. if (opt_show_procs)
  3432. ypos = cgpu->cgminer_id;
  3433. else
  3434. {
  3435. if (cgpu->proc_id)
  3436. return;
  3437. ypos = cgpu->device_line_id;
  3438. }
  3439. ypos += devsummaryYOffset;
  3440. if (ypos < 0)
  3441. return;
  3442. ypos += devcursor - 1;
  3443. if (ypos >= statusy - 1)
  3444. return;
  3445. if (wmove(statuswin, ypos, 0) == ERR)
  3446. return;
  3447. get_statline2(logline, sizeof(logline), cgpu, true);
  3448. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3449. wattron(statuswin, A_REVERSE);
  3450. bfg_waddstr(statuswin, logline);
  3451. wattroff(statuswin, A_REVERSE);
  3452. wclrtoeol(statuswin);
  3453. }
  3454. static
  3455. void _refresh_devstatus(const bool already_have_lock) {
  3456. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  3457. int i;
  3458. if (unlikely(!total_devices))
  3459. {
  3460. const int ypos = devcursor - 1;
  3461. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  3462. {
  3463. wattron(statuswin, attr_bad);
  3464. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  3465. wclrtoeol(statuswin);
  3466. wattroff(statuswin, attr_bad);
  3467. }
  3468. }
  3469. for (i = 0; i < total_devices; i++)
  3470. curses_print_devstatus(get_devices(i));
  3471. touchwin(statuswin);
  3472. wrefresh(statuswin);
  3473. if (!already_have_lock)
  3474. unlock_curses();
  3475. }
  3476. }
  3477. #define refresh_devstatus() _refresh_devstatus(false)
  3478. #endif
  3479. static void print_status(int thr_id)
  3480. {
  3481. if (!curses_active)
  3482. text_print_status(thr_id);
  3483. }
  3484. #ifdef HAVE_CURSES
  3485. static
  3486. bool set_statusy(int maxy)
  3487. {
  3488. if (loginput_size)
  3489. {
  3490. maxy -= loginput_size;
  3491. if (maxy < 0)
  3492. maxy = 0;
  3493. }
  3494. if (logstart < maxy)
  3495. maxy = logstart;
  3496. if (statusy == maxy)
  3497. return false;
  3498. statusy = maxy;
  3499. logcursor = statusy;
  3500. return true;
  3501. }
  3502. /* Check for window resize. Called with curses mutex locked */
  3503. static inline void change_logwinsize(void)
  3504. {
  3505. int x, y, logx, logy;
  3506. getmaxyx(mainwin, y, x);
  3507. if (x < 80 || y < 25)
  3508. return;
  3509. if (y > statusy + 2 && statusy < logstart) {
  3510. set_statusy(y - 2);
  3511. mvwin(logwin, logcursor, 0);
  3512. bfg_wresize(statuswin, statusy, x);
  3513. }
  3514. y -= logcursor;
  3515. getmaxyx(logwin, logy, logx);
  3516. /* Detect screen size change */
  3517. if (x != logx || y != logy)
  3518. bfg_wresize(logwin, y, x);
  3519. }
  3520. static void check_winsizes(void)
  3521. {
  3522. if (!use_curses)
  3523. return;
  3524. if (curses_active_locked()) {
  3525. int y, x;
  3526. x = getmaxx(statuswin);
  3527. if (set_statusy(LINES - 2))
  3528. {
  3529. erase();
  3530. bfg_wresize(statuswin, statusy, x);
  3531. getmaxyx(mainwin, y, x);
  3532. y -= logcursor;
  3533. bfg_wresize(logwin, y, x);
  3534. mvwin(logwin, logcursor, 0);
  3535. }
  3536. unlock_curses();
  3537. }
  3538. }
  3539. static int device_line_id_count;
  3540. static void switch_logsize(void)
  3541. {
  3542. if (curses_active_locked()) {
  3543. if (opt_compact) {
  3544. logstart = devcursor - 1;
  3545. logcursor = logstart + 1;
  3546. } else {
  3547. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  3548. logstart = devcursor + total_lines;
  3549. logcursor = logstart;
  3550. }
  3551. unlock_curses();
  3552. }
  3553. check_winsizes();
  3554. }
  3555. /* For mandatory printing when mutex is already locked */
  3556. void _wlog(const char *str)
  3557. {
  3558. static bool newline;
  3559. size_t end = strlen(str) - 1;
  3560. if (newline)
  3561. bfg_waddstr(logwin, "\n");
  3562. if (str[end] == '\n')
  3563. {
  3564. char *s;
  3565. newline = true;
  3566. s = alloca(end + 1);
  3567. memcpy(s, str, end);
  3568. s[end] = '\0';
  3569. str = s;
  3570. }
  3571. else
  3572. newline = false;
  3573. bfg_waddstr(logwin, str);
  3574. }
  3575. /* Mandatory printing */
  3576. void _wlogprint(const char *str)
  3577. {
  3578. if (curses_active_locked()) {
  3579. _wlog(str);
  3580. unlock_curses();
  3581. }
  3582. }
  3583. #endif
  3584. #ifdef HAVE_CURSES
  3585. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3586. {
  3587. bool high_prio;
  3588. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3589. if (curses_active)
  3590. {
  3591. if (!loginput_size || high_prio) {
  3592. wlog(" %s %s\n", datetime, str);
  3593. if (high_prio) {
  3594. touchwin(logwin);
  3595. wrefresh(logwin);
  3596. }
  3597. }
  3598. return true;
  3599. }
  3600. return false;
  3601. }
  3602. void clear_logwin(void)
  3603. {
  3604. if (curses_active_locked()) {
  3605. wclear(logwin);
  3606. unlock_curses();
  3607. }
  3608. }
  3609. void logwin_update(void)
  3610. {
  3611. if (curses_active_locked()) {
  3612. touchwin(logwin);
  3613. wrefresh(logwin);
  3614. unlock_curses();
  3615. }
  3616. }
  3617. #endif
  3618. static void enable_pool(struct pool *pool)
  3619. {
  3620. if (pool->enabled != POOL_ENABLED) {
  3621. enabled_pools++;
  3622. pool->enabled = POOL_ENABLED;
  3623. }
  3624. }
  3625. #ifdef HAVE_CURSES
  3626. static void disable_pool(struct pool *pool)
  3627. {
  3628. if (pool->enabled == POOL_ENABLED)
  3629. enabled_pools--;
  3630. pool->enabled = POOL_DISABLED;
  3631. }
  3632. #endif
  3633. static void reject_pool(struct pool *pool)
  3634. {
  3635. if (pool->enabled == POOL_ENABLED)
  3636. enabled_pools--;
  3637. pool->enabled = POOL_REJECTING;
  3638. }
  3639. static uint64_t share_diff(const struct work *);
  3640. static
  3641. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3642. struct cgpu_info *cgpu;
  3643. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3644. char shrdiffdisp[16];
  3645. int tgtdiff = floor(work->work_difficulty);
  3646. char tgtdiffdisp[16];
  3647. char where[20];
  3648. cgpu = get_thr_cgpu(work->thr_id);
  3649. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3650. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3651. if (total_pools > 1)
  3652. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  3653. else
  3654. where[0] = '\0';
  3655. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  3656. disp,
  3657. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  3658. cgpu->proc_repr,
  3659. where,
  3660. shrdiffdisp, tgtdiffdisp,
  3661. reason,
  3662. resubmit ? "(resubmit)" : "",
  3663. worktime
  3664. );
  3665. }
  3666. static bool test_work_current(struct work *);
  3667. static void _submit_work_async(struct work *);
  3668. static
  3669. void maybe_local_submit(const struct work *work)
  3670. {
  3671. #if BLKMAKER_VERSION > 3
  3672. if (unlikely(work->block && work->tmpl))
  3673. {
  3674. // This is a block with a full template (GBT)
  3675. // Regardless of the result, submit to local bitcoind(s) as well
  3676. struct work *work_cp;
  3677. char *p;
  3678. for (int i = 0; i < total_pools; ++i)
  3679. {
  3680. p = strchr(pools[i]->rpc_url, '#');
  3681. if (likely(!(p && strstr(&p[1], "allblocks"))))
  3682. continue;
  3683. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  3684. work_cp = copy_work(work);
  3685. work_cp->pool = pools[i];
  3686. work_cp->do_foreign_submit = true;
  3687. _submit_work_async(work_cp);
  3688. }
  3689. }
  3690. #endif
  3691. }
  3692. /* Theoretically threads could race when modifying accepted and
  3693. * rejected values but the chance of two submits completing at the
  3694. * same time is zero so there is no point adding extra locking */
  3695. static void
  3696. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3697. /*char *hashshow,*/ bool resubmit, char *worktime)
  3698. {
  3699. struct pool *pool = work->pool;
  3700. struct cgpu_info *cgpu;
  3701. cgpu = get_thr_cgpu(work->thr_id);
  3702. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  3703. mutex_lock(&stats_lock);
  3704. cgpu->accepted++;
  3705. total_accepted++;
  3706. pool->accepted++;
  3707. cgpu->diff_accepted += work->work_difficulty;
  3708. total_diff_accepted += work->work_difficulty;
  3709. pool->diff_accepted += work->work_difficulty;
  3710. mutex_unlock(&stats_lock);
  3711. pool->seq_rejects = 0;
  3712. cgpu->last_share_pool = pool->pool_no;
  3713. cgpu->last_share_pool_time = time(NULL);
  3714. cgpu->last_share_diff = work->work_difficulty;
  3715. pool->last_share_time = cgpu->last_share_pool_time;
  3716. pool->last_share_diff = work->work_difficulty;
  3717. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3718. if (!QUIET) {
  3719. share_result_msg(work, "Accepted", "", resubmit, worktime);
  3720. }
  3721. sharelog("accept", work);
  3722. if (opt_shares && total_diff_accepted >= opt_shares) {
  3723. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  3724. kill_work();
  3725. return;
  3726. }
  3727. /* Detect if a pool that has been temporarily disabled for
  3728. * continually rejecting shares has started accepting shares.
  3729. * This will only happen with the work returned from a
  3730. * longpoll */
  3731. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3732. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3733. enable_pool(pool);
  3734. switch_pools(NULL);
  3735. }
  3736. if (unlikely(work->block)) {
  3737. // Force moving on to this new block :)
  3738. struct work fakework;
  3739. memset(&fakework, 0, sizeof(fakework));
  3740. fakework.pool = work->pool;
  3741. // Copy block version, bits, and time from share
  3742. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  3743. memcpy(&fakework.data[68], &work->data[68], 8);
  3744. // Set prevblock to winning hash (swap32'd)
  3745. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  3746. test_work_current(&fakework);
  3747. }
  3748. } else {
  3749. mutex_lock(&stats_lock);
  3750. cgpu->rejected++;
  3751. total_rejected++;
  3752. pool->rejected++;
  3753. cgpu->diff_rejected += work->work_difficulty;
  3754. total_diff_rejected += work->work_difficulty;
  3755. pool->diff_rejected += work->work_difficulty;
  3756. pool->seq_rejects++;
  3757. mutex_unlock(&stats_lock);
  3758. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  3759. if (!QUIET) {
  3760. char where[20];
  3761. char disposition[36] = "reject";
  3762. char reason[32];
  3763. strcpy(reason, "");
  3764. if (total_pools > 1)
  3765. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  3766. else
  3767. strcpy(where, "");
  3768. if (!json_is_string(res))
  3769. res = json_object_get(val, "reject-reason");
  3770. if (res) {
  3771. const char *reasontmp = json_string_value(res);
  3772. size_t reasonLen = strlen(reasontmp);
  3773. if (reasonLen > 28)
  3774. reasonLen = 28;
  3775. reason[0] = ' '; reason[1] = '(';
  3776. memcpy(2 + reason, reasontmp, reasonLen);
  3777. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  3778. memcpy(disposition + 7, reasontmp, reasonLen);
  3779. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  3780. } else if (work->stratum && err && json_is_array(err)) {
  3781. json_t *reason_val = json_array_get(err, 1);
  3782. char *reason_str;
  3783. if (reason_val && json_is_string(reason_val)) {
  3784. reason_str = (char *)json_string_value(reason_val);
  3785. snprintf(reason, 31, " (%s)", reason_str);
  3786. }
  3787. }
  3788. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  3789. sharelog(disposition, work);
  3790. }
  3791. /* Once we have more than a nominal amount of sequential rejects,
  3792. * at least 10 and more than 3 mins at the current utility,
  3793. * disable the pool because some pool error is likely to have
  3794. * ensued. Do not do this if we know the share just happened to
  3795. * be stale due to networking delays.
  3796. */
  3797. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  3798. double utility = total_accepted / total_secs * 60;
  3799. if (pool->seq_rejects > utility * 3) {
  3800. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  3801. pool->pool_no, pool->seq_rejects);
  3802. reject_pool(pool);
  3803. if (pool == current_pool())
  3804. switch_pools(NULL);
  3805. pool->seq_rejects = 0;
  3806. }
  3807. }
  3808. }
  3809. maybe_local_submit(work);
  3810. }
  3811. static char *submit_upstream_work_request(struct work *work)
  3812. {
  3813. char *hexstr = NULL;
  3814. char *s, *sd;
  3815. struct pool *pool = work->pool;
  3816. if (work->tmpl) {
  3817. json_t *req;
  3818. unsigned char data[80];
  3819. swap32yes(data, work->data, 80 / 4);
  3820. #if BLKMAKER_VERSION > 3
  3821. if (work->do_foreign_submit)
  3822. req = blkmk_submit_foreign_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3823. else
  3824. #endif
  3825. req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3826. s = json_dumps(req, 0);
  3827. json_decref(req);
  3828. sd = malloc(161);
  3829. bin2hex(sd, data, 80);
  3830. } else {
  3831. /* build hex string */
  3832. hexstr = malloc((sizeof(work->data) * 2) + 1);
  3833. bin2hex(hexstr, work->data, sizeof(work->data));
  3834. /* build JSON-RPC request */
  3835. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  3836. s = realloc_strcat(s, hexstr);
  3837. s = realloc_strcat(s, "\" ], \"id\":1}");
  3838. free(hexstr);
  3839. sd = s;
  3840. }
  3841. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  3842. if (work->tmpl)
  3843. free(sd);
  3844. else
  3845. s = realloc_strcat(s, "\n");
  3846. return s;
  3847. }
  3848. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  3849. json_t *res, *err;
  3850. bool rc = false;
  3851. int thr_id = work->thr_id;
  3852. struct pool *pool = work->pool;
  3853. struct timeval tv_submit_reply;
  3854. time_t ts_submit_reply;
  3855. char worktime[200] = "";
  3856. cgtime(&tv_submit_reply);
  3857. ts_submit_reply = time(NULL);
  3858. if (unlikely(!val)) {
  3859. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  3860. if (!pool_tset(pool, &pool->submit_fail)) {
  3861. total_ro++;
  3862. pool->remotefail_occasions++;
  3863. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  3864. }
  3865. goto out;
  3866. } else if (pool_tclear(pool, &pool->submit_fail))
  3867. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  3868. res = json_object_get(val, "result");
  3869. err = json_object_get(val, "error");
  3870. if (!QUIET) {
  3871. if (opt_worktime) {
  3872. char workclone[20];
  3873. struct tm _tm;
  3874. struct tm *tm, tm_getwork, tm_submit_reply;
  3875. tm = &_tm;
  3876. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  3877. (struct timeval *)&(work->tv_getwork));
  3878. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  3879. (struct timeval *)&(work->tv_getwork_reply));
  3880. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  3881. (struct timeval *)&(work->tv_work_start));
  3882. double work_to_submit = tdiff(ptv_submit,
  3883. (struct timeval *)&(work->tv_work_found));
  3884. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  3885. int diffplaces = 3;
  3886. localtime_r(&work->ts_getwork, tm);
  3887. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3888. localtime_r(&ts_submit_reply, tm);
  3889. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3890. if (work->clone) {
  3891. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  3892. tdiff((struct timeval *)&(work->tv_cloned),
  3893. (struct timeval *)&(work->tv_getwork_reply)));
  3894. }
  3895. else
  3896. strcpy(workclone, "O");
  3897. if (work->work_difficulty < 1)
  3898. diffplaces = 6;
  3899. snprintf(worktime, sizeof(worktime),
  3900. " <-%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",
  3901. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3902. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3903. work->getwork_mode, diffplaces, work->work_difficulty,
  3904. tm_getwork.tm_hour, tm_getwork.tm_min,
  3905. tm_getwork.tm_sec, getwork_time, workclone,
  3906. getwork_to_work, work_time, work_to_submit, submit_time,
  3907. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3908. tm_submit_reply.tm_sec);
  3909. }
  3910. }
  3911. share_result(val, res, err, work, resubmit, worktime);
  3912. if (!opt_realquiet)
  3913. print_status(thr_id);
  3914. if (!want_per_device_stats) {
  3915. char logline[256];
  3916. struct cgpu_info *cgpu;
  3917. cgpu = get_thr_cgpu(thr_id);
  3918. get_statline(logline, sizeof(logline), cgpu);
  3919. applog(LOG_INFO, "%s", logline);
  3920. }
  3921. json_decref(val);
  3922. rc = true;
  3923. out:
  3924. return rc;
  3925. }
  3926. /* Specifies whether we can use this pool for work or not. */
  3927. static bool pool_unworkable(struct pool *pool)
  3928. {
  3929. if (pool->idle)
  3930. return true;
  3931. if (pool->enabled != POOL_ENABLED)
  3932. return true;
  3933. if (pool->has_stratum && !pool->stratum_active)
  3934. return true;
  3935. return false;
  3936. }
  3937. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3938. * rolling average per 10 minutes and if pools start getting more, it biases
  3939. * away from them to distribute work evenly. The share count is reset to the
  3940. * rolling average every 10 minutes to not send all work to one pool after it
  3941. * has been disabled/out for an extended period. */
  3942. static struct pool *select_balanced(struct pool *cp)
  3943. {
  3944. int i, lowest = cp->shares;
  3945. struct pool *ret = cp;
  3946. for (i = 0; i < total_pools; i++) {
  3947. struct pool *pool = pools[i];
  3948. if (pool_unworkable(pool))
  3949. continue;
  3950. if (pool->shares < lowest) {
  3951. lowest = pool->shares;
  3952. ret = pool;
  3953. }
  3954. }
  3955. ret->shares++;
  3956. return ret;
  3957. }
  3958. static bool pool_active(struct pool *, bool pinging);
  3959. static void pool_died(struct pool *);
  3960. static struct pool *priority_pool(int choice);
  3961. static bool pool_unusable(struct pool *pool);
  3962. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  3963. * it has any quota left. */
  3964. static inline struct pool *select_pool(bool lagging)
  3965. {
  3966. static int rotating_pool = 0;
  3967. struct pool *pool, *cp;
  3968. bool avail = false;
  3969. int tested, i;
  3970. cp = current_pool();
  3971. retry:
  3972. if (pool_strategy == POOL_BALANCE) {
  3973. pool = select_balanced(cp);
  3974. goto out;
  3975. }
  3976. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  3977. pool = cp;
  3978. goto out;
  3979. } else
  3980. pool = NULL;
  3981. for (i = 0; i < total_pools; i++) {
  3982. struct pool *tp = pools[i];
  3983. if (tp->quota_used < tp->quota_gcd) {
  3984. avail = true;
  3985. break;
  3986. }
  3987. }
  3988. /* There are no pools with quota, so reset them. */
  3989. if (!avail) {
  3990. for (i = 0; i < total_pools; i++)
  3991. pools[i]->quota_used = 0;
  3992. if (++rotating_pool >= total_pools)
  3993. rotating_pool = 0;
  3994. }
  3995. /* Try to find the first pool in the rotation that is usable */
  3996. tested = 0;
  3997. while (!pool && tested++ < total_pools) {
  3998. pool = pools[rotating_pool];
  3999. if (pool->quota_used++ < pool->quota_gcd) {
  4000. if (!pool_unworkable(pool))
  4001. break;
  4002. /* Failover-only flag for load-balance means distribute
  4003. * unused quota to priority pool 0. */
  4004. if (opt_fail_only)
  4005. priority_pool(0)->quota_used--;
  4006. }
  4007. pool = NULL;
  4008. if (++rotating_pool >= total_pools)
  4009. rotating_pool = 0;
  4010. }
  4011. /* If there are no alive pools with quota, choose according to
  4012. * priority. */
  4013. if (!pool) {
  4014. for (i = 0; i < total_pools; i++) {
  4015. struct pool *tp = priority_pool(i);
  4016. if (!pool_unusable(tp)) {
  4017. pool = tp;
  4018. break;
  4019. }
  4020. }
  4021. }
  4022. /* If still nothing is usable, use the current pool */
  4023. if (!pool)
  4024. pool = cp;
  4025. out:
  4026. if (cp != pool)
  4027. {
  4028. if (!pool_active(pool, false))
  4029. {
  4030. pool_died(pool);
  4031. goto retry;
  4032. }
  4033. pool_tclear(pool, &pool->idle);
  4034. }
  4035. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4036. return pool;
  4037. }
  4038. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4039. static const uint64_t diffone = 0xFFFF000000000000ull;
  4040. static double target_diff(const unsigned char *target)
  4041. {
  4042. double targ = 0;
  4043. signed int i;
  4044. for (i = 31; i >= 0; --i)
  4045. targ = (targ * 0x100) + target[i];
  4046. return DIFFEXACTONE / (targ ?: 1);
  4047. }
  4048. /*
  4049. * Calculate the work share difficulty
  4050. */
  4051. static void calc_diff(struct work *work, int known)
  4052. {
  4053. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4054. double difficulty;
  4055. if (!known) {
  4056. work->work_difficulty = target_diff(work->target);
  4057. } else
  4058. work->work_difficulty = known;
  4059. difficulty = work->work_difficulty;
  4060. pool_stats->last_diff = difficulty;
  4061. suffix_string((uint64_t)difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4062. if (difficulty == pool_stats->min_diff)
  4063. pool_stats->min_diff_count++;
  4064. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4065. pool_stats->min_diff = difficulty;
  4066. pool_stats->min_diff_count = 1;
  4067. }
  4068. if (difficulty == pool_stats->max_diff)
  4069. pool_stats->max_diff_count++;
  4070. else if (difficulty > pool_stats->max_diff) {
  4071. pool_stats->max_diff = difficulty;
  4072. pool_stats->max_diff_count = 1;
  4073. }
  4074. }
  4075. static void get_benchmark_work(struct work *work)
  4076. {
  4077. // Use a random work block pulled from a pool
  4078. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  4079. size_t bench_size = sizeof(*work);
  4080. size_t work_size = sizeof(bench_block);
  4081. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  4082. memset(work, 0, sizeof(*work));
  4083. memcpy(work, &bench_block, min_size);
  4084. work->mandatory = true;
  4085. work->pool = pools[0];
  4086. cgtime(&work->tv_getwork);
  4087. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4088. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4089. calc_diff(work, 0);
  4090. }
  4091. static void wake_gws(void);
  4092. static void update_last_work(struct work *work)
  4093. {
  4094. if (!work->tmpl)
  4095. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4096. return;
  4097. struct pool *pool = work->pool;
  4098. mutex_lock(&pool->last_work_lock);
  4099. if (pool->last_work_copy)
  4100. free_work(pool->last_work_copy);
  4101. pool->last_work_copy = copy_work(work);
  4102. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4103. mutex_unlock(&pool->last_work_lock);
  4104. }
  4105. static
  4106. void gbt_req_target(json_t *req)
  4107. {
  4108. json_t *j;
  4109. json_t *n;
  4110. if (!request_target_str)
  4111. return;
  4112. j = json_object_get(req, "params");
  4113. if (!j)
  4114. {
  4115. n = json_array();
  4116. if (!n)
  4117. return;
  4118. if (json_object_set_new(req, "params", n))
  4119. goto erradd;
  4120. j = n;
  4121. }
  4122. n = json_array_get(j, 0);
  4123. if (!n)
  4124. {
  4125. n = json_object();
  4126. if (!n)
  4127. return;
  4128. if (json_array_append_new(j, n))
  4129. goto erradd;
  4130. }
  4131. j = n;
  4132. n = json_string(request_target_str);
  4133. if (!n)
  4134. return;
  4135. if (json_object_set_new(j, "target", n))
  4136. goto erradd;
  4137. return;
  4138. erradd:
  4139. json_decref(n);
  4140. }
  4141. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4142. {
  4143. char *rpc_req;
  4144. clean_work(work);
  4145. switch (proto) {
  4146. case PLP_GETWORK:
  4147. work->getwork_mode = GETWORK_MODE_POOL;
  4148. return strdup(getwork_req);
  4149. case PLP_GETBLOCKTEMPLATE:
  4150. work->getwork_mode = GETWORK_MODE_GBT;
  4151. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  4152. if (!work->tmpl_refcount)
  4153. return NULL;
  4154. work->tmpl = blktmpl_create();
  4155. if (!work->tmpl)
  4156. goto gbtfail2;
  4157. *work->tmpl_refcount = 1;
  4158. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  4159. if (!caps)
  4160. goto gbtfail;
  4161. caps |= GBT_LONGPOLL;
  4162. #if BLKMAKER_VERSION > 1
  4163. if (opt_coinbase_script.sz)
  4164. caps |= GBT_CBVALUE;
  4165. #endif
  4166. json_t *req = blktmpl_request_jansson(caps, lpid);
  4167. if (!req)
  4168. goto gbtfail;
  4169. if (probe)
  4170. gbt_req_target(req);
  4171. rpc_req = json_dumps(req, 0);
  4172. if (!rpc_req)
  4173. goto gbtfail;
  4174. json_decref(req);
  4175. return rpc_req;
  4176. default:
  4177. return NULL;
  4178. }
  4179. return NULL;
  4180. gbtfail:
  4181. blktmpl_free(work->tmpl);
  4182. work->tmpl = NULL;
  4183. gbtfail2:
  4184. free(work->tmpl_refcount);
  4185. work->tmpl_refcount = NULL;
  4186. return NULL;
  4187. }
  4188. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4189. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4190. static const char *pool_protocol_name(enum pool_protocol proto)
  4191. {
  4192. switch (proto) {
  4193. case PLP_GETBLOCKTEMPLATE:
  4194. return "getblocktemplate";
  4195. case PLP_GETWORK:
  4196. return "getwork";
  4197. default:
  4198. return "UNKNOWN";
  4199. }
  4200. }
  4201. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4202. {
  4203. switch (proto) {
  4204. case PLP_GETBLOCKTEMPLATE:
  4205. if (want_getwork)
  4206. return PLP_GETWORK;
  4207. default:
  4208. return PLP_NONE;
  4209. }
  4210. }
  4211. static bool get_upstream_work(struct work *work, CURL *curl)
  4212. {
  4213. struct pool *pool = work->pool;
  4214. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4215. struct timeval tv_elapsed;
  4216. json_t *val = NULL;
  4217. bool rc = false;
  4218. char *url;
  4219. enum pool_protocol proto;
  4220. char *rpc_req;
  4221. if (pool->proto == PLP_NONE)
  4222. pool->proto = PLP_GETBLOCKTEMPLATE;
  4223. tryagain:
  4224. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4225. work->pool = pool;
  4226. if (!rpc_req)
  4227. return false;
  4228. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4229. url = pool->rpc_url;
  4230. cgtime(&work->tv_getwork);
  4231. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4232. false, &work->rolltime, pool, false);
  4233. pool_stats->getwork_attempts++;
  4234. free(rpc_req);
  4235. if (likely(val)) {
  4236. rc = work_decode(pool, work, val);
  4237. if (unlikely(!rc))
  4238. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4239. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4240. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4241. pool->proto = proto;
  4242. goto tryagain;
  4243. } else
  4244. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4245. cgtime(&work->tv_getwork_reply);
  4246. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4247. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4248. pool_stats->getwork_wait_rolling /= 1.63;
  4249. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4250. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4251. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4252. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4253. }
  4254. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4255. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4256. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4257. }
  4258. pool_stats->getwork_calls++;
  4259. work->pool = pool;
  4260. work->longpoll = false;
  4261. calc_diff(work, 0);
  4262. total_getworks++;
  4263. pool->getwork_requested++;
  4264. if (rc)
  4265. update_last_work(work);
  4266. if (likely(val))
  4267. json_decref(val);
  4268. return rc;
  4269. }
  4270. #ifdef HAVE_CURSES
  4271. static void disable_curses(void)
  4272. {
  4273. if (curses_active_locked()) {
  4274. use_curses = false;
  4275. curses_active = false;
  4276. leaveok(logwin, false);
  4277. leaveok(statuswin, false);
  4278. leaveok(mainwin, false);
  4279. nocbreak();
  4280. echo();
  4281. delwin(logwin);
  4282. delwin(statuswin);
  4283. delwin(mainwin);
  4284. endwin();
  4285. #ifdef WIN32
  4286. // Move the cursor to after curses output.
  4287. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4288. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4289. COORD coord;
  4290. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4291. coord.X = 0;
  4292. coord.Y = csbi.dwSize.Y - 1;
  4293. SetConsoleCursorPosition(hout, coord);
  4294. }
  4295. #endif
  4296. unlock_curses();
  4297. }
  4298. }
  4299. #endif
  4300. static void __kill_work(void)
  4301. {
  4302. struct cgpu_info *cgpu;
  4303. struct thr_info *thr;
  4304. int i;
  4305. if (!successful_connect)
  4306. return;
  4307. applog(LOG_INFO, "Received kill message");
  4308. shutting_down = true;
  4309. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4310. notifier_wake(submit_waiting_notifier);
  4311. #ifdef USE_LIBMICROHTTPD
  4312. httpsrv_stop();
  4313. #endif
  4314. applog(LOG_DEBUG, "Killing off watchpool thread");
  4315. /* Kill the watchpool thread */
  4316. thr = &control_thr[watchpool_thr_id];
  4317. thr_info_cancel(thr);
  4318. applog(LOG_DEBUG, "Killing off watchdog thread");
  4319. /* Kill the watchdog thread */
  4320. thr = &control_thr[watchdog_thr_id];
  4321. thr_info_cancel(thr);
  4322. applog(LOG_DEBUG, "Shutting down mining threads");
  4323. for (i = 0; i < mining_threads; i++) {
  4324. thr = get_thread(i);
  4325. if (!thr)
  4326. continue;
  4327. cgpu = thr->cgpu;
  4328. if (!cgpu)
  4329. continue;
  4330. if (!cgpu->threads)
  4331. continue;
  4332. cgpu->shutdown = true;
  4333. thr->work_restart = true;
  4334. notifier_wake(thr->notifier);
  4335. notifier_wake(thr->work_restart_notifier);
  4336. }
  4337. sleep(1);
  4338. applog(LOG_DEBUG, "Killing off mining threads");
  4339. /* Kill the mining threads*/
  4340. for (i = 0; i < mining_threads; i++) {
  4341. thr = get_thread(i);
  4342. if (!thr)
  4343. continue;
  4344. cgpu = thr->cgpu;
  4345. if (cgpu->threads)
  4346. {
  4347. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4348. thr_info_cancel(thr);
  4349. }
  4350. cgpu->status = LIFE_DEAD2;
  4351. }
  4352. /* Stop the others */
  4353. applog(LOG_DEBUG, "Killing off API thread");
  4354. thr = &control_thr[api_thr_id];
  4355. thr_info_cancel(thr);
  4356. }
  4357. /* This should be the common exit path */
  4358. void kill_work(void)
  4359. {
  4360. __kill_work();
  4361. quit(0, "Shutdown signal received.");
  4362. }
  4363. static
  4364. #ifdef WIN32
  4365. #ifndef _WIN64
  4366. const
  4367. #endif
  4368. #endif
  4369. char **initial_args;
  4370. void _bfg_clean_up(bool);
  4371. void app_restart(void)
  4372. {
  4373. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4374. __kill_work();
  4375. _bfg_clean_up(true);
  4376. #if defined(unix) || defined(__APPLE__)
  4377. if (forkpid > 0) {
  4378. kill(forkpid, SIGTERM);
  4379. forkpid = 0;
  4380. }
  4381. #endif
  4382. execv(initial_args[0], initial_args);
  4383. applog(LOG_WARNING, "Failed to restart application");
  4384. }
  4385. static void sighandler(int __maybe_unused sig)
  4386. {
  4387. /* Restore signal handlers so we can still quit if kill_work fails */
  4388. sigaction(SIGTERM, &termhandler, NULL);
  4389. sigaction(SIGINT, &inthandler, NULL);
  4390. kill_work();
  4391. }
  4392. static void start_longpoll(void);
  4393. static void stop_longpoll(void);
  4394. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4395. * this pool. */
  4396. static void recruit_curl(struct pool *pool)
  4397. {
  4398. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4399. if (unlikely(!ce))
  4400. quit(1, "Failed to calloc in recruit_curl");
  4401. ce->curl = curl_easy_init();
  4402. if (unlikely(!ce->curl))
  4403. quit(1, "Failed to init in recruit_curl");
  4404. LL_PREPEND(pool->curllist, ce);
  4405. pool->curls++;
  4406. }
  4407. /* Grab an available curl if there is one. If not, then recruit extra curls
  4408. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4409. * and there are already 5 curls in circulation. Limit total number to the
  4410. * number of mining threads per pool as well to prevent blasting a pool during
  4411. * network delays/outages. */
  4412. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4413. {
  4414. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4415. bool recruited = false;
  4416. struct curl_ent *ce;
  4417. mutex_lock(&pool->pool_lock);
  4418. retry:
  4419. if (!pool->curls) {
  4420. recruit_curl(pool);
  4421. recruited = true;
  4422. } else if (!pool->curllist) {
  4423. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4424. if (!blocking) {
  4425. mutex_unlock(&pool->pool_lock);
  4426. return NULL;
  4427. }
  4428. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4429. goto retry;
  4430. } else {
  4431. recruit_curl(pool);
  4432. recruited = true;
  4433. }
  4434. }
  4435. ce = pool->curllist;
  4436. LL_DELETE(pool->curllist, ce);
  4437. mutex_unlock(&pool->pool_lock);
  4438. if (recruited)
  4439. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4440. return ce;
  4441. }
  4442. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4443. {
  4444. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4445. }
  4446. __maybe_unused
  4447. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4448. {
  4449. return pop_curl_entry3(pool, 1);
  4450. }
  4451. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4452. {
  4453. mutex_lock(&pool->pool_lock);
  4454. if (!ce || !ce->curl)
  4455. quithere(1, "Attempted to add NULL");
  4456. LL_PREPEND(pool->curllist, ce);
  4457. cgtime(&ce->tv);
  4458. pthread_cond_broadcast(&pool->cr_cond);
  4459. mutex_unlock(&pool->pool_lock);
  4460. }
  4461. bool stale_work(struct work *work, bool share);
  4462. static inline bool should_roll(struct work *work)
  4463. {
  4464. struct timeval now;
  4465. time_t expiry;
  4466. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  4467. return false;
  4468. if (stale_work(work, false))
  4469. return false;
  4470. if (work->rolltime > opt_scantime)
  4471. expiry = work->rolltime;
  4472. else
  4473. expiry = opt_scantime;
  4474. expiry = expiry * 2 / 3;
  4475. /* We shouldn't roll if we're unlikely to get one shares' duration
  4476. * work out of doing so */
  4477. cgtime(&now);
  4478. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4479. return false;
  4480. return true;
  4481. }
  4482. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4483. * reject blocks as invalid. */
  4484. static inline bool can_roll(struct work *work)
  4485. {
  4486. if (work->stratum)
  4487. return false;
  4488. if (!(work->pool && !work->clone))
  4489. return false;
  4490. if (work->tmpl) {
  4491. if (stale_work(work, false))
  4492. return false;
  4493. return blkmk_work_left(work->tmpl);
  4494. }
  4495. return (work->rolltime &&
  4496. work->rolls < 7000 && !stale_work(work, false));
  4497. }
  4498. static void roll_work(struct work *work)
  4499. {
  4500. if (work->tmpl) {
  4501. struct timeval tv_now;
  4502. cgtime(&tv_now);
  4503. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4504. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4505. swap32yes(work->data, work->data, 80 / 4);
  4506. calc_midstate(work);
  4507. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4508. } else {
  4509. uint32_t *work_ntime;
  4510. uint32_t ntime;
  4511. work_ntime = (uint32_t *)(work->data + 68);
  4512. ntime = be32toh(*work_ntime);
  4513. ntime++;
  4514. *work_ntime = htobe32(ntime);
  4515. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4516. }
  4517. local_work++;
  4518. work->rolls++;
  4519. work->blk.nonce = 0;
  4520. /* This is now a different work item so it needs a different ID for the
  4521. * hashtable */
  4522. work->id = total_work++;
  4523. }
  4524. /* Duplicates any dynamically allocated arrays within the work struct to
  4525. * prevent a copied work struct from freeing ram belonging to another struct */
  4526. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4527. {
  4528. int id = work->id;
  4529. clean_work(work);
  4530. memcpy(work, base_work, sizeof(struct work));
  4531. /* Keep the unique new id assigned during make_work to prevent copied
  4532. * work from having the same id. */
  4533. work->id = id;
  4534. if (base_work->job_id)
  4535. work->job_id = strdup(base_work->job_id);
  4536. if (base_work->nonce1)
  4537. work->nonce1 = strdup(base_work->nonce1);
  4538. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4539. if (base_work->tmpl) {
  4540. struct pool *pool = work->pool;
  4541. mutex_lock(&pool->pool_lock);
  4542. ++*work->tmpl_refcount;
  4543. mutex_unlock(&pool->pool_lock);
  4544. }
  4545. if (noffset)
  4546. {
  4547. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4548. uint32_t ntime = be32toh(*work_ntime);
  4549. ntime += noffset;
  4550. *work_ntime = htobe32(ntime);
  4551. }
  4552. if (work->device_data_dup_func)
  4553. work->device_data = work->device_data_dup_func(work);
  4554. }
  4555. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4556. * for all dynamically allocated arrays within the struct */
  4557. struct work *copy_work(const struct work *base_work)
  4558. {
  4559. struct work *work = make_work();
  4560. _copy_work(work, base_work, 0);
  4561. return work;
  4562. }
  4563. void __copy_work(struct work *work, const struct work *base_work)
  4564. {
  4565. _copy_work(work, base_work, 0);
  4566. }
  4567. static struct work *make_clone(struct work *work)
  4568. {
  4569. struct work *work_clone = copy_work(work);
  4570. work_clone->clone = true;
  4571. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4572. work_clone->longpoll = false;
  4573. work_clone->mandatory = false;
  4574. /* Make cloned work appear slightly older to bias towards keeping the
  4575. * master work item which can be further rolled */
  4576. work_clone->tv_staged.tv_sec -= 1;
  4577. return work_clone;
  4578. }
  4579. static void stage_work(struct work *work);
  4580. static bool clone_available(void)
  4581. {
  4582. struct work *work_clone = NULL, *work, *tmp;
  4583. bool cloned = false;
  4584. mutex_lock(stgd_lock);
  4585. if (!staged_rollable)
  4586. goto out_unlock;
  4587. HASH_ITER(hh, staged_work, work, tmp) {
  4588. if (can_roll(work) && should_roll(work)) {
  4589. roll_work(work);
  4590. work_clone = make_clone(work);
  4591. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  4592. roll_work(work);
  4593. cloned = true;
  4594. break;
  4595. }
  4596. }
  4597. out_unlock:
  4598. mutex_unlock(stgd_lock);
  4599. if (cloned) {
  4600. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4601. stage_work(work_clone);
  4602. }
  4603. return cloned;
  4604. }
  4605. static void pool_died(struct pool *pool)
  4606. {
  4607. if (!pool_tset(pool, &pool->idle)) {
  4608. cgtime(&pool->tv_idle);
  4609. if (pool == current_pool()) {
  4610. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4611. switch_pools(NULL);
  4612. } else
  4613. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4614. }
  4615. }
  4616. bool stale_work(struct work *work, bool share)
  4617. {
  4618. unsigned work_expiry;
  4619. struct pool *pool;
  4620. uint32_t block_id;
  4621. unsigned getwork_delay;
  4622. if (opt_benchmark)
  4623. return false;
  4624. block_id = ((uint32_t*)work->data)[1];
  4625. pool = work->pool;
  4626. /* Technically the rolltime should be correct but some pools
  4627. * advertise a broken expire= that is lower than a meaningful
  4628. * scantime */
  4629. if (work->rolltime >= opt_scantime || work->tmpl)
  4630. work_expiry = work->rolltime;
  4631. else
  4632. work_expiry = opt_expiry;
  4633. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4634. if (work_expiry > max_expiry)
  4635. work_expiry = max_expiry;
  4636. if (share) {
  4637. /* If the share isn't on this pool's latest block, it's stale */
  4638. if (pool->block_id && pool->block_id != block_id)
  4639. {
  4640. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4641. return true;
  4642. }
  4643. /* If the pool doesn't want old shares, then any found in work before
  4644. * the most recent longpoll is stale */
  4645. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4646. {
  4647. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4648. return true;
  4649. }
  4650. } else {
  4651. /* If this work isn't for the latest Bitcoin block, it's stale */
  4652. /* But only care about the current pool if failover-only */
  4653. if (enabled_pools <= 1 || opt_fail_only) {
  4654. if (pool->block_id && block_id != pool->block_id)
  4655. {
  4656. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4657. return true;
  4658. }
  4659. } else {
  4660. if (block_id != current_block_id)
  4661. {
  4662. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4663. return true;
  4664. }
  4665. }
  4666. /* If the pool has asked us to restart since this work, it's stale */
  4667. if (work->work_restart_id != pool->work_restart_id)
  4668. {
  4669. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4670. return true;
  4671. }
  4672. if (pool->has_stratum && work->job_id) {
  4673. bool same_job;
  4674. if (!pool->stratum_active || !pool->stratum_notify) {
  4675. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4676. return true;
  4677. }
  4678. same_job = true;
  4679. cg_rlock(&pool->data_lock);
  4680. if (strcmp(work->job_id, pool->swork.job_id))
  4681. same_job = false;
  4682. cg_runlock(&pool->data_lock);
  4683. if (!same_job) {
  4684. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4685. return true;
  4686. }
  4687. }
  4688. /* Factor in the average getwork delay of this pool, rounding it up to
  4689. * the nearest second */
  4690. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  4691. if (unlikely(work_expiry <= getwork_delay + 5))
  4692. work_expiry = 5;
  4693. else
  4694. work_expiry -= getwork_delay;
  4695. }
  4696. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  4697. if (elapsed_since_staged > work_expiry) {
  4698. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  4699. return true;
  4700. }
  4701. /* If the user only wants strict failover, any work from a pool other than
  4702. * the current one is always considered stale */
  4703. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  4704. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4705. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  4706. return true;
  4707. }
  4708. return false;
  4709. }
  4710. static uint64_t share_diff(const struct work *work)
  4711. {
  4712. uint64_t ret;
  4713. bool new_best = false;
  4714. ret = target_diff(work->hash);
  4715. cg_wlock(&control_lock);
  4716. if (unlikely(ret > best_diff)) {
  4717. new_best = true;
  4718. best_diff = ret;
  4719. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4720. }
  4721. if (unlikely(ret > work->pool->best_diff))
  4722. work->pool->best_diff = ret;
  4723. cg_wunlock(&control_lock);
  4724. if (unlikely(new_best))
  4725. applog(LOG_INFO, "New best share: %s", best_share);
  4726. return ret;
  4727. }
  4728. static void regen_hash(struct work *work)
  4729. {
  4730. hash_data(work->hash, work->data);
  4731. }
  4732. static void rebuild_hash(struct work *work)
  4733. {
  4734. if (opt_scrypt)
  4735. scrypt_regenhash(work);
  4736. else
  4737. regen_hash(work);
  4738. work->share_diff = share_diff(work);
  4739. if (unlikely(work->share_diff >= current_diff)) {
  4740. work->block = true;
  4741. work->pool->solved++;
  4742. found_blocks++;
  4743. work->mandatory = true;
  4744. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  4745. }
  4746. }
  4747. static void submit_discard_share2(const char *reason, struct work *work)
  4748. {
  4749. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  4750. sharelog(reason, work);
  4751. mutex_lock(&stats_lock);
  4752. ++total_stale;
  4753. ++cgpu->stale;
  4754. ++(work->pool->stale_shares);
  4755. total_diff_stale += work->work_difficulty;
  4756. cgpu->diff_stale += work->work_difficulty;
  4757. work->pool->diff_stale += work->work_difficulty;
  4758. mutex_unlock(&stats_lock);
  4759. }
  4760. static void submit_discard_share(struct work *work)
  4761. {
  4762. submit_discard_share2("discard", work);
  4763. }
  4764. struct submit_work_state {
  4765. struct work *work;
  4766. bool resubmit;
  4767. struct curl_ent *ce;
  4768. int failures;
  4769. struct timeval tv_staleexpire;
  4770. char *s;
  4771. struct timeval tv_submit;
  4772. struct submit_work_state *next;
  4773. };
  4774. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  4775. {
  4776. long *p_timeout_us = userp;
  4777. const long max_ms = LONG_MAX / 1000;
  4778. if (max_ms < timeout_ms)
  4779. timeout_ms = max_ms;
  4780. *p_timeout_us = timeout_ms * 1000;
  4781. return 0;
  4782. }
  4783. static void sws_has_ce(struct submit_work_state *sws)
  4784. {
  4785. struct pool *pool = sws->work->pool;
  4786. sws->s = submit_upstream_work_request(sws->work);
  4787. cgtime(&sws->tv_submit);
  4788. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4789. }
  4790. static struct submit_work_state *begin_submission(struct work *work)
  4791. {
  4792. struct pool *pool;
  4793. struct submit_work_state *sws = NULL;
  4794. pool = work->pool;
  4795. sws = malloc(sizeof(*sws));
  4796. *sws = (struct submit_work_state){
  4797. .work = work,
  4798. };
  4799. rebuild_hash(work);
  4800. if (stale_work(work, true)) {
  4801. work->stale = true;
  4802. if (opt_submit_stale)
  4803. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4804. else if (pool->submit_old)
  4805. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4806. else {
  4807. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4808. submit_discard_share(work);
  4809. goto out;
  4810. }
  4811. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4812. }
  4813. if (work->stratum) {
  4814. char *s;
  4815. s = malloc(1024);
  4816. sws->s = s;
  4817. } else {
  4818. /* submit solution to bitcoin via JSON-RPC */
  4819. sws->ce = pop_curl_entry2(pool, false);
  4820. if (sws->ce) {
  4821. sws_has_ce(sws);
  4822. } else {
  4823. sws->next = pool->sws_waiting_on_curl;
  4824. pool->sws_waiting_on_curl = sws;
  4825. if (sws->next)
  4826. applog(LOG_DEBUG, "submit_thread queuing submission");
  4827. else
  4828. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  4829. }
  4830. }
  4831. return sws;
  4832. out:
  4833. free(sws);
  4834. return NULL;
  4835. }
  4836. static bool retry_submission(struct submit_work_state *sws)
  4837. {
  4838. struct work *work = sws->work;
  4839. struct pool *pool = work->pool;
  4840. sws->resubmit = true;
  4841. if ((!work->stale) && stale_work(work, true)) {
  4842. work->stale = true;
  4843. if (opt_submit_stale)
  4844. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  4845. else if (pool->submit_old)
  4846. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  4847. else {
  4848. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  4849. submit_discard_share(work);
  4850. return false;
  4851. }
  4852. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4853. }
  4854. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  4855. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  4856. submit_discard_share(work);
  4857. return false;
  4858. }
  4859. else if (work->stale) {
  4860. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  4861. {
  4862. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  4863. submit_discard_share(work);
  4864. return false;
  4865. }
  4866. }
  4867. /* pause, then restart work-request loop */
  4868. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  4869. cgtime(&sws->tv_submit);
  4870. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4871. return true;
  4872. }
  4873. static void free_sws(struct submit_work_state *sws)
  4874. {
  4875. free(sws->s);
  4876. free_work(sws->work);
  4877. free(sws);
  4878. }
  4879. static void *submit_work_thread(__maybe_unused void *userdata)
  4880. {
  4881. int wip = 0;
  4882. CURLM *curlm;
  4883. long curlm_timeout_us = -1;
  4884. struct timeval curlm_timer;
  4885. struct submit_work_state *sws, **swsp;
  4886. struct submit_work_state *write_sws = NULL;
  4887. unsigned tsreduce = 0;
  4888. pthread_detach(pthread_self());
  4889. RenameThread("submit_work");
  4890. applog(LOG_DEBUG, "Creating extra submit work thread");
  4891. curlm = curl_multi_init();
  4892. curlm_timeout_us = -1;
  4893. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  4894. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  4895. fd_set rfds, wfds, efds;
  4896. int maxfd;
  4897. struct timeval tv_timeout, tv_now;
  4898. int n;
  4899. CURLMsg *cm;
  4900. FD_ZERO(&rfds);
  4901. while (1) {
  4902. mutex_lock(&submitting_lock);
  4903. total_submitting -= tsreduce;
  4904. tsreduce = 0;
  4905. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  4906. notifier_read(submit_waiting_notifier);
  4907. }
  4908. // Receive any new submissions
  4909. while (submit_waiting) {
  4910. struct work *work = submit_waiting;
  4911. DL_DELETE(submit_waiting, work);
  4912. if ( (sws = begin_submission(work)) ) {
  4913. if (sws->ce)
  4914. curl_multi_add_handle(curlm, sws->ce->curl);
  4915. else if (sws->s) {
  4916. sws->next = write_sws;
  4917. write_sws = sws;
  4918. }
  4919. ++wip;
  4920. }
  4921. else {
  4922. --total_submitting;
  4923. free_work(work);
  4924. }
  4925. }
  4926. if (unlikely(shutting_down && !wip))
  4927. break;
  4928. mutex_unlock(&submitting_lock);
  4929. FD_ZERO(&rfds);
  4930. FD_ZERO(&wfds);
  4931. FD_ZERO(&efds);
  4932. tv_timeout.tv_sec = -1;
  4933. // Setup cURL with select
  4934. // Need to call perform to ensure the timeout gets updated
  4935. curl_multi_perform(curlm, &n);
  4936. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  4937. if (curlm_timeout_us >= 0)
  4938. {
  4939. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  4940. reduce_timeout_to(&tv_timeout, &curlm_timer);
  4941. }
  4942. // Setup waiting stratum submissions with select
  4943. for (sws = write_sws; sws; sws = sws->next)
  4944. {
  4945. struct pool *pool = sws->work->pool;
  4946. int fd = pool->sock;
  4947. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  4948. continue;
  4949. FD_SET(fd, &wfds);
  4950. set_maxfd(&maxfd, fd);
  4951. }
  4952. // Setup "submit waiting" notifier with select
  4953. FD_SET(submit_waiting_notifier[0], &rfds);
  4954. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  4955. // Wait for something interesting to happen :)
  4956. cgtime(&tv_now);
  4957. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  4958. FD_ZERO(&rfds);
  4959. continue;
  4960. }
  4961. // Handle any stratum ready-to-write results
  4962. for (swsp = &write_sws; (sws = *swsp); ) {
  4963. struct work *work = sws->work;
  4964. struct pool *pool = work->pool;
  4965. int fd = pool->sock;
  4966. bool sessionid_match;
  4967. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  4968. next_write_sws:
  4969. // TODO: Check if stale, possibly discard etc
  4970. swsp = &sws->next;
  4971. continue;
  4972. }
  4973. cg_rlock(&pool->data_lock);
  4974. // 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
  4975. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  4976. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  4977. cg_runlock(&pool->data_lock);
  4978. if (!sessionid_match)
  4979. {
  4980. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4981. submit_discard_share2("disconnect", work);
  4982. ++tsreduce;
  4983. next_write_sws_del:
  4984. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  4985. FD_CLR(fd, &wfds);
  4986. // Delete sws for this submission, since we're done with it
  4987. *swsp = sws->next;
  4988. free_sws(sws);
  4989. --wip;
  4990. continue;
  4991. }
  4992. char *s = sws->s;
  4993. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  4994. int sshare_id;
  4995. uint32_t nonce;
  4996. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  4997. char noncehex[9];
  4998. char ntimehex[9];
  4999. sshare->work = copy_work(work);
  5000. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5001. nonce = *((uint32_t *)(work->data + 76));
  5002. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5003. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5004. mutex_lock(&sshare_lock);
  5005. /* Give the stratum share a unique id */
  5006. sshare_id =
  5007. sshare->id = swork_id++;
  5008. HASH_ADD_INT(stratum_shares, id, sshare);
  5009. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5010. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5011. mutex_unlock(&sshare_lock);
  5012. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5013. if (likely(stratum_send(pool, s, strlen(s)))) {
  5014. if (pool_tclear(pool, &pool->submit_fail))
  5015. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5016. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5017. goto next_write_sws_del;
  5018. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5019. // Undo stuff
  5020. mutex_lock(&sshare_lock);
  5021. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5022. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5023. if (sshare)
  5024. HASH_DEL(stratum_shares, sshare);
  5025. mutex_unlock(&sshare_lock);
  5026. if (sshare)
  5027. {
  5028. free_work(sshare->work);
  5029. free(sshare);
  5030. }
  5031. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5032. total_ro++;
  5033. pool->remotefail_occasions++;
  5034. if (!sshare)
  5035. goto next_write_sws_del;
  5036. goto next_write_sws;
  5037. }
  5038. }
  5039. // Handle any cURL activities
  5040. curl_multi_perform(curlm, &n);
  5041. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5042. if (cm->msg == CURLMSG_DONE)
  5043. {
  5044. bool finished;
  5045. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5046. curl_multi_remove_handle(curlm, cm->easy_handle);
  5047. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5048. if (!finished) {
  5049. if (retry_submission(sws))
  5050. curl_multi_add_handle(curlm, sws->ce->curl);
  5051. else
  5052. finished = true;
  5053. }
  5054. if (finished) {
  5055. --wip;
  5056. ++tsreduce;
  5057. struct pool *pool = sws->work->pool;
  5058. if (pool->sws_waiting_on_curl) {
  5059. pool->sws_waiting_on_curl->ce = sws->ce;
  5060. sws_has_ce(pool->sws_waiting_on_curl);
  5061. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5062. curl_multi_add_handle(curlm, sws->ce->curl);
  5063. } else {
  5064. push_curl_entry(sws->ce, sws->work->pool);
  5065. }
  5066. free_sws(sws);
  5067. }
  5068. }
  5069. }
  5070. }
  5071. assert(!write_sws);
  5072. mutex_unlock(&submitting_lock);
  5073. curl_multi_cleanup(curlm);
  5074. applog(LOG_DEBUG, "submit_work thread exiting");
  5075. return NULL;
  5076. }
  5077. /* Find the pool that currently has the highest priority */
  5078. static struct pool *priority_pool(int choice)
  5079. {
  5080. struct pool *ret = NULL;
  5081. int i;
  5082. for (i = 0; i < total_pools; i++) {
  5083. struct pool *pool = pools[i];
  5084. if (pool->prio == choice) {
  5085. ret = pool;
  5086. break;
  5087. }
  5088. }
  5089. if (unlikely(!ret)) {
  5090. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5091. return pools[choice];
  5092. }
  5093. return ret;
  5094. }
  5095. int prioritize_pools(char *param, int *pid)
  5096. {
  5097. char *ptr, *next;
  5098. int i, pr, prio = 0;
  5099. if (total_pools == 0) {
  5100. return MSG_NOPOOL;
  5101. }
  5102. if (param == NULL || *param == '\0') {
  5103. return MSG_MISPID;
  5104. }
  5105. bool pools_changed[total_pools];
  5106. int new_prio[total_pools];
  5107. for (i = 0; i < total_pools; ++i)
  5108. pools_changed[i] = false;
  5109. next = param;
  5110. while (next && *next) {
  5111. ptr = next;
  5112. next = strchr(ptr, ',');
  5113. if (next)
  5114. *(next++) = '\0';
  5115. i = atoi(ptr);
  5116. if (i < 0 || i >= total_pools) {
  5117. *pid = i;
  5118. return MSG_INVPID;
  5119. }
  5120. if (pools_changed[i]) {
  5121. *pid = i;
  5122. return MSG_DUPPID;
  5123. }
  5124. pools_changed[i] = true;
  5125. new_prio[i] = prio++;
  5126. }
  5127. // Only change them if no errors
  5128. for (i = 0; i < total_pools; i++) {
  5129. if (pools_changed[i])
  5130. pools[i]->prio = new_prio[i];
  5131. }
  5132. // In priority order, cycle through the unchanged pools and append them
  5133. for (pr = 0; pr < total_pools; pr++)
  5134. for (i = 0; i < total_pools; i++) {
  5135. if (!pools_changed[i] && pools[i]->prio == pr) {
  5136. pools[i]->prio = prio++;
  5137. pools_changed[i] = true;
  5138. break;
  5139. }
  5140. }
  5141. if (current_pool()->prio)
  5142. switch_pools(NULL);
  5143. return MSG_POOLPRIO;
  5144. }
  5145. void validate_pool_priorities(void)
  5146. {
  5147. // TODO: this should probably do some sort of logging
  5148. int i, j;
  5149. bool used[total_pools];
  5150. bool valid[total_pools];
  5151. for (i = 0; i < total_pools; i++)
  5152. used[i] = valid[i] = false;
  5153. for (i = 0; i < total_pools; i++) {
  5154. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5155. if (!used[pools[i]->prio]) {
  5156. valid[i] = true;
  5157. used[pools[i]->prio] = true;
  5158. }
  5159. }
  5160. }
  5161. for (i = 0; i < total_pools; i++) {
  5162. if (!valid[i]) {
  5163. for (j = 0; j < total_pools; j++) {
  5164. if (!used[j]) {
  5165. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5166. pools[i]->prio = j;
  5167. used[j] = true;
  5168. break;
  5169. }
  5170. }
  5171. }
  5172. }
  5173. }
  5174. static void clear_pool_work(struct pool *pool);
  5175. /* Specifies whether we can switch to this pool or not. */
  5176. static bool pool_unusable(struct pool *pool)
  5177. {
  5178. if (pool->idle)
  5179. return true;
  5180. if (pool->enabled != POOL_ENABLED)
  5181. return true;
  5182. return false;
  5183. }
  5184. void switch_pools(struct pool *selected)
  5185. {
  5186. struct pool *pool, *last_pool;
  5187. int i, pool_no, next_pool;
  5188. cg_wlock(&control_lock);
  5189. last_pool = currentpool;
  5190. pool_no = currentpool->pool_no;
  5191. /* Switch selected to pool number 0 and move the rest down */
  5192. if (selected) {
  5193. if (selected->prio != 0) {
  5194. for (i = 0; i < total_pools; i++) {
  5195. pool = pools[i];
  5196. if (pool->prio < selected->prio)
  5197. pool->prio++;
  5198. }
  5199. selected->prio = 0;
  5200. }
  5201. }
  5202. switch (pool_strategy) {
  5203. /* All of these set to the master pool */
  5204. case POOL_BALANCE:
  5205. case POOL_FAILOVER:
  5206. case POOL_LOADBALANCE:
  5207. for (i = 0; i < total_pools; i++) {
  5208. pool = priority_pool(i);
  5209. if (pool_unusable(pool))
  5210. continue;
  5211. pool_no = pool->pool_no;
  5212. break;
  5213. }
  5214. break;
  5215. /* Both of these simply increment and cycle */
  5216. case POOL_ROUNDROBIN:
  5217. case POOL_ROTATE:
  5218. if (selected && !selected->idle) {
  5219. pool_no = selected->pool_no;
  5220. break;
  5221. }
  5222. next_pool = pool_no;
  5223. /* Select the next alive pool */
  5224. for (i = 1; i < total_pools; i++) {
  5225. next_pool++;
  5226. if (next_pool >= total_pools)
  5227. next_pool = 0;
  5228. pool = pools[next_pool];
  5229. if (pool_unusable(pool))
  5230. continue;
  5231. pool_no = next_pool;
  5232. break;
  5233. }
  5234. break;
  5235. default:
  5236. break;
  5237. }
  5238. currentpool = pools[pool_no];
  5239. pool = currentpool;
  5240. cg_wunlock(&control_lock);
  5241. /* Set the lagging flag to avoid pool not providing work fast enough
  5242. * messages in failover only mode since we have to get all fresh work
  5243. * as in restart_threads */
  5244. if (opt_fail_only)
  5245. pool_tset(pool, &pool->lagging);
  5246. if (pool != last_pool)
  5247. {
  5248. pool->block_id = 0;
  5249. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5250. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5251. if (pool_localgen(pool) || opt_fail_only)
  5252. clear_pool_work(last_pool);
  5253. }
  5254. }
  5255. mutex_lock(&lp_lock);
  5256. pthread_cond_broadcast(&lp_cond);
  5257. mutex_unlock(&lp_lock);
  5258. }
  5259. static void discard_work(struct work *work)
  5260. {
  5261. if (!work->clone && !work->rolls && !work->mined) {
  5262. if (work->pool) {
  5263. work->pool->discarded_work++;
  5264. work->pool->quota_used--;
  5265. work->pool->works--;
  5266. }
  5267. total_discarded++;
  5268. applog(LOG_DEBUG, "Discarded work");
  5269. } else
  5270. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5271. free_work(work);
  5272. }
  5273. static void wake_gws(void)
  5274. {
  5275. mutex_lock(stgd_lock);
  5276. pthread_cond_signal(&gws_cond);
  5277. mutex_unlock(stgd_lock);
  5278. }
  5279. static void discard_stale(void)
  5280. {
  5281. struct work *work, *tmp;
  5282. int stale = 0;
  5283. mutex_lock(stgd_lock);
  5284. HASH_ITER(hh, staged_work, work, tmp) {
  5285. if (stale_work(work, false)) {
  5286. HASH_DEL(staged_work, work);
  5287. discard_work(work);
  5288. stale++;
  5289. staged_full = false;
  5290. }
  5291. }
  5292. pthread_cond_signal(&gws_cond);
  5293. mutex_unlock(stgd_lock);
  5294. if (stale)
  5295. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5296. }
  5297. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5298. {
  5299. bool rv;
  5300. struct timeval tv, orig;
  5301. ldiv_t d;
  5302. d = ldiv(ustime, 1000000);
  5303. tv = (struct timeval){
  5304. .tv_sec = d.quot,
  5305. .tv_usec = d.rem,
  5306. };
  5307. orig = work->tv_staged;
  5308. timersub(&orig, &tv, &work->tv_staged);
  5309. rv = stale_work(work, share);
  5310. work->tv_staged = orig;
  5311. return rv;
  5312. }
  5313. static void restart_threads(void)
  5314. {
  5315. struct pool *cp = current_pool();
  5316. int i;
  5317. struct thr_info *thr;
  5318. /* Artificially set the lagging flag to avoid pool not providing work
  5319. * fast enough messages after every long poll */
  5320. pool_tset(cp, &cp->lagging);
  5321. /* Discard staged work that is now stale */
  5322. discard_stale();
  5323. rd_lock(&mining_thr_lock);
  5324. for (i = 0; i < mining_threads; i++)
  5325. {
  5326. thr = mining_thr[i];
  5327. thr->work_restart = true;
  5328. }
  5329. for (i = 0; i < mining_threads; i++)
  5330. {
  5331. thr = mining_thr[i];
  5332. notifier_wake(thr->work_restart_notifier);
  5333. }
  5334. rd_unlock(&mining_thr_lock);
  5335. }
  5336. static
  5337. void blkhashstr(char *rv, const unsigned char *hash)
  5338. {
  5339. unsigned char hash_swap[32];
  5340. swap256(hash_swap, hash);
  5341. swap32tole(hash_swap, hash_swap, 32 / 4);
  5342. bin2hex(rv, hash_swap, 32);
  5343. }
  5344. static void set_curblock(char *hexstr, unsigned char *hash)
  5345. {
  5346. unsigned char hash_swap[32];
  5347. current_block_id = ((uint32_t*)hash)[0];
  5348. strcpy(current_block, hexstr);
  5349. swap256(hash_swap, hash);
  5350. swap32tole(hash_swap, hash_swap, 32 / 4);
  5351. cg_wlock(&ch_lock);
  5352. block_time = time(NULL);
  5353. __update_block_title(hash_swap);
  5354. free(current_fullhash);
  5355. current_fullhash = malloc(65);
  5356. bin2hex(current_fullhash, hash_swap, 32);
  5357. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5358. cg_wunlock(&ch_lock);
  5359. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5360. }
  5361. /* Search to see if this string is from a block that has been seen before */
  5362. static bool block_exists(char *hexstr)
  5363. {
  5364. struct block *s;
  5365. rd_lock(&blk_lock);
  5366. HASH_FIND_STR(blocks, hexstr, s);
  5367. rd_unlock(&blk_lock);
  5368. if (s)
  5369. return true;
  5370. return false;
  5371. }
  5372. /* Tests if this work is from a block that has been seen before */
  5373. static inline bool from_existing_block(struct work *work)
  5374. {
  5375. char hexstr[37];
  5376. bool ret;
  5377. bin2hex(hexstr, work->data + 8, 18);
  5378. ret = block_exists(hexstr);
  5379. return ret;
  5380. }
  5381. static int block_sort(struct block *blocka, struct block *blockb)
  5382. {
  5383. return blocka->block_no - blockb->block_no;
  5384. }
  5385. static void set_blockdiff(const struct work *work)
  5386. {
  5387. unsigned char target[32];
  5388. double diff;
  5389. uint64_t diff64;
  5390. real_block_target(target, work->data);
  5391. diff = target_diff(target);
  5392. diff64 = diff;
  5393. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5394. format_unit2(net_hashrate, sizeof(net_hashrate),
  5395. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5396. if (unlikely(current_diff != diff))
  5397. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5398. current_diff = diff;
  5399. }
  5400. static bool test_work_current(struct work *work)
  5401. {
  5402. bool ret = true;
  5403. char hexstr[65];
  5404. if (work->mandatory)
  5405. return ret;
  5406. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5407. /* Hack to work around dud work sneaking into test */
  5408. bin2hex(hexstr, work->data + 8, 18);
  5409. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5410. goto out_free;
  5411. /* Search to see if this block exists yet and if not, consider it a
  5412. * new block and set the current block details to this one */
  5413. if (!block_exists(hexstr)) {
  5414. struct block *s = calloc(sizeof(struct block), 1);
  5415. int deleted_block = 0;
  5416. ret = false;
  5417. if (unlikely(!s))
  5418. quit (1, "test_work_current OOM");
  5419. strcpy(s->hash, hexstr);
  5420. s->block_no = new_blocks++;
  5421. wr_lock(&blk_lock);
  5422. /* Only keep the last hour's worth of blocks in memory since
  5423. * work from blocks before this is virtually impossible and we
  5424. * want to prevent memory usage from continually rising */
  5425. if (HASH_COUNT(blocks) > 6) {
  5426. struct block *oldblock;
  5427. HASH_SORT(blocks, block_sort);
  5428. oldblock = blocks;
  5429. deleted_block = oldblock->block_no;
  5430. HASH_DEL(blocks, oldblock);
  5431. free(oldblock);
  5432. }
  5433. HASH_ADD_STR(blocks, hash, s);
  5434. set_blockdiff(work);
  5435. wr_unlock(&blk_lock);
  5436. work->pool->block_id = block_id;
  5437. if (deleted_block)
  5438. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5439. #if BLKMAKER_VERSION > 1
  5440. template_nonce = 0;
  5441. #endif
  5442. set_curblock(hexstr, &work->data[4]);
  5443. if (unlikely(new_blocks == 1))
  5444. goto out_free;
  5445. if (!work->stratum) {
  5446. if (work->longpoll) {
  5447. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5448. work->pool->pool_no);
  5449. } else if (have_longpoll)
  5450. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5451. else
  5452. applog(LOG_NOTICE, "New block detected on network");
  5453. }
  5454. restart_threads();
  5455. } else {
  5456. bool restart = false;
  5457. struct pool *curpool = NULL;
  5458. if (unlikely(work->pool->block_id != block_id)) {
  5459. bool was_active = work->pool->block_id != 0;
  5460. work->pool->block_id = block_id;
  5461. if (!work->longpoll)
  5462. update_last_work(work);
  5463. if (was_active) { // Pool actively changed block
  5464. if (work->pool == (curpool = current_pool()))
  5465. restart = true;
  5466. if (block_id == current_block_id) {
  5467. // Caught up, only announce if this pool is the one in use
  5468. if (restart)
  5469. applog(LOG_NOTICE, "%s %d caught up to new block",
  5470. work->longpoll ? "Longpoll from pool" : "Pool",
  5471. work->pool->pool_no);
  5472. } else {
  5473. // Switched to a block we know, but not the latest... why?
  5474. // This might detect pools trying to double-spend or 51%,
  5475. // but let's not make any accusations until it's had time
  5476. // in the real world.
  5477. blkhashstr(hexstr, &work->data[4]);
  5478. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5479. work->longpoll ? "Longpoll from pool" : "Pool",
  5480. work->pool->pool_no,
  5481. hexstr);
  5482. }
  5483. }
  5484. }
  5485. if (work->longpoll) {
  5486. ++work->pool->work_restart_id;
  5487. update_last_work(work);
  5488. if ((!restart) && work->pool == current_pool()) {
  5489. applog(
  5490. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  5491. "Longpoll from pool %d requested work update",
  5492. work->pool->pool_no);
  5493. restart = true;
  5494. }
  5495. }
  5496. if (restart)
  5497. restart_threads();
  5498. }
  5499. work->longpoll = false;
  5500. out_free:
  5501. return ret;
  5502. }
  5503. static int tv_sort(struct work *worka, struct work *workb)
  5504. {
  5505. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5506. }
  5507. static bool work_rollable(struct work *work)
  5508. {
  5509. return (!work->clone && work->rolltime);
  5510. }
  5511. static bool hash_push(struct work *work)
  5512. {
  5513. bool rc = true;
  5514. mutex_lock(stgd_lock);
  5515. if (work_rollable(work))
  5516. staged_rollable++;
  5517. if (likely(!getq->frozen)) {
  5518. HASH_ADD_INT(staged_work, id, work);
  5519. HASH_SORT(staged_work, tv_sort);
  5520. } else
  5521. rc = false;
  5522. pthread_cond_broadcast(&getq->cond);
  5523. mutex_unlock(stgd_lock);
  5524. return rc;
  5525. }
  5526. static void stage_work(struct work *work)
  5527. {
  5528. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  5529. work->id, work->pool->pool_no);
  5530. work->work_restart_id = work->pool->work_restart_id;
  5531. work->pool->last_work_time = time(NULL);
  5532. cgtime(&work->pool->tv_last_work_time);
  5533. test_work_current(work);
  5534. work->pool->works++;
  5535. hash_push(work);
  5536. }
  5537. #ifdef HAVE_CURSES
  5538. int curses_int(const char *query)
  5539. {
  5540. int ret;
  5541. char *cvar;
  5542. cvar = curses_input(query);
  5543. if (unlikely(!cvar))
  5544. return -1;
  5545. ret = atoi(cvar);
  5546. free(cvar);
  5547. return ret;
  5548. }
  5549. #endif
  5550. #ifdef HAVE_CURSES
  5551. static bool input_pool(bool live);
  5552. #endif
  5553. #ifdef HAVE_CURSES
  5554. static void display_pool_summary(struct pool *pool)
  5555. {
  5556. double efficiency = 0.0;
  5557. char xfer[17], bw[19];
  5558. int pool_secs;
  5559. if (curses_active_locked()) {
  5560. wlog("Pool: %s\n", pool->rpc_url);
  5561. if (pool->solved)
  5562. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5563. if (!pool->has_stratum)
  5564. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5565. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5566. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5567. wlog(" Accepted shares: %d\n", pool->accepted);
  5568. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5569. pool->rejected, pool->stale_shares,
  5570. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5571. );
  5572. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5573. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5574. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5575. wlog(" Network transfer: %s (%s)\n",
  5576. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5577. (float)pool->cgminer_pool_stats.net_bytes_received,
  5578. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5579. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5580. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5581. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5582. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5583. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5584. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5585. wlog(" Items worked on: %d\n", pool->works);
  5586. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5587. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5588. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5589. unlock_curses();
  5590. }
  5591. }
  5592. #endif
  5593. /* We can't remove the memory used for this struct pool because there may
  5594. * still be work referencing it. We just remove it from the pools list */
  5595. void remove_pool(struct pool *pool)
  5596. {
  5597. int i, last_pool = total_pools - 1;
  5598. struct pool *other;
  5599. /* Boost priority of any lower prio than this one */
  5600. for (i = 0; i < total_pools; i++) {
  5601. other = pools[i];
  5602. if (other->prio > pool->prio)
  5603. other->prio--;
  5604. }
  5605. if (pool->pool_no < last_pool) {
  5606. /* Swap the last pool for this one */
  5607. (pools[last_pool])->pool_no = pool->pool_no;
  5608. pools[pool->pool_no] = pools[last_pool];
  5609. }
  5610. /* Give it an invalid number */
  5611. pool->pool_no = total_pools;
  5612. pool->removed = true;
  5613. pool->has_stratum = false;
  5614. total_pools--;
  5615. }
  5616. /* add a mutex if this needs to be thread safe in the future */
  5617. static struct JE {
  5618. char *buf;
  5619. struct JE *next;
  5620. } *jedata = NULL;
  5621. static void json_escape_free()
  5622. {
  5623. struct JE *jeptr = jedata;
  5624. struct JE *jenext;
  5625. jedata = NULL;
  5626. while (jeptr) {
  5627. jenext = jeptr->next;
  5628. free(jeptr->buf);
  5629. free(jeptr);
  5630. jeptr = jenext;
  5631. }
  5632. }
  5633. static
  5634. char *json_escape(const char *str)
  5635. {
  5636. struct JE *jeptr;
  5637. char *buf, *ptr;
  5638. /* 2x is the max, may as well just allocate that */
  5639. ptr = buf = malloc(strlen(str) * 2 + 1);
  5640. jeptr = malloc(sizeof(*jeptr));
  5641. jeptr->buf = buf;
  5642. jeptr->next = jedata;
  5643. jedata = jeptr;
  5644. while (*str) {
  5645. if (*str == '\\' || *str == '"')
  5646. *(ptr++) = '\\';
  5647. *(ptr++) = *(str++);
  5648. }
  5649. *ptr = '\0';
  5650. return buf;
  5651. }
  5652. static
  5653. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  5654. {
  5655. if (!elist)
  5656. return;
  5657. static struct string_elist *entry;
  5658. fprintf(fcfg, ",\n\"%s\" : [", configname);
  5659. bool first = true;
  5660. DL_FOREACH(elist, entry)
  5661. {
  5662. const char * const s = entry->string;
  5663. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  5664. first = false;
  5665. }
  5666. fprintf(fcfg, "\n]");
  5667. }
  5668. void write_config(FILE *fcfg)
  5669. {
  5670. int i;
  5671. /* Write pool values */
  5672. fputs("{\n\"pools\" : [", fcfg);
  5673. for(i = 0; i < total_pools; i++) {
  5674. struct pool *pool = pools[i];
  5675. if (pool->quota != 1) {
  5676. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  5677. pool->quota,
  5678. json_escape(pool->rpc_url));
  5679. } else {
  5680. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  5681. json_escape(pool->rpc_url));
  5682. }
  5683. if (pool->rpc_proxy)
  5684. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  5685. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  5686. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  5687. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  5688. if (pool->force_rollntime)
  5689. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  5690. fprintf(fcfg, "\n\t}");
  5691. }
  5692. fputs("\n]\n", fcfg);
  5693. #ifdef HAVE_OPENCL
  5694. write_config_opencl(fcfg);
  5695. #endif
  5696. #ifdef WANT_CPUMINE
  5697. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  5698. #endif
  5699. /* Simple bool and int options */
  5700. struct opt_table *opt;
  5701. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5702. char *p, *name = strdup(opt->names);
  5703. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5704. if (p[1] != '-')
  5705. continue;
  5706. if (opt->type & OPT_NOARG &&
  5707. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5708. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  5709. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5710. if (opt->type & OPT_HASARG &&
  5711. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5712. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5713. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5714. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  5715. opt->desc != opt_hidden &&
  5716. 0 <= *(int *)opt->u.arg)
  5717. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5718. }
  5719. }
  5720. /* Special case options */
  5721. if (request_target_str)
  5722. {
  5723. if (request_pdiff == (long)request_pdiff)
  5724. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  5725. else
  5726. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  5727. }
  5728. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  5729. if (pool_strategy == POOL_BALANCE)
  5730. fputs(",\n\"balance\" : true", fcfg);
  5731. if (pool_strategy == POOL_LOADBALANCE)
  5732. fputs(",\n\"load-balance\" : true", fcfg);
  5733. if (pool_strategy == POOL_ROUNDROBIN)
  5734. fputs(",\n\"round-robin\" : true", fcfg);
  5735. if (pool_strategy == POOL_ROTATE)
  5736. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5737. #if defined(unix) || defined(__APPLE__)
  5738. if (opt_stderr_cmd && *opt_stderr_cmd)
  5739. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  5740. #endif // defined(unix)
  5741. if (opt_kernel_path && *opt_kernel_path) {
  5742. char *kpath = strdup(opt_kernel_path);
  5743. if (kpath[strlen(kpath)-1] == '/')
  5744. kpath[strlen(kpath)-1] = 0;
  5745. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  5746. free(kpath);
  5747. }
  5748. if (schedstart.enable)
  5749. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5750. if (schedstop.enable)
  5751. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5752. if (opt_socks_proxy && *opt_socks_proxy)
  5753. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  5754. _write_config_string_elist(fcfg, "scan", scan_devices);
  5755. #ifdef USE_LIBMICROHTTPD
  5756. if (httpsrv_port != -1)
  5757. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  5758. #endif
  5759. #ifdef USE_LIBEVENT
  5760. if (stratumsrv_port != -1)
  5761. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  5762. #endif
  5763. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  5764. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  5765. if (opt_api_allow)
  5766. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  5767. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  5768. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  5769. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  5770. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  5771. if (*opt_api_mcast_des)
  5772. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  5773. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  5774. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  5775. if (opt_api_groups)
  5776. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  5777. fputs("\n}\n", fcfg);
  5778. json_escape_free();
  5779. }
  5780. void zero_bestshare(void)
  5781. {
  5782. int i;
  5783. best_diff = 0;
  5784. memset(best_share, 0, 8);
  5785. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5786. for (i = 0; i < total_pools; i++) {
  5787. struct pool *pool = pools[i];
  5788. pool->best_diff = 0;
  5789. }
  5790. }
  5791. void zero_stats(void)
  5792. {
  5793. int i;
  5794. applog(LOG_DEBUG, "Zeroing stats");
  5795. cgtime(&total_tv_start);
  5796. miner_started = total_tv_start;
  5797. total_rolling = 0;
  5798. total_mhashes_done = 0;
  5799. total_getworks = 0;
  5800. total_accepted = 0;
  5801. total_rejected = 0;
  5802. hw_errors = 0;
  5803. total_stale = 0;
  5804. total_discarded = 0;
  5805. total_bytes_rcvd = total_bytes_sent = 0;
  5806. new_blocks = 0;
  5807. local_work = 0;
  5808. total_go = 0;
  5809. total_ro = 0;
  5810. total_secs = 1.0;
  5811. total_diff1 = 0;
  5812. total_bad_diff1 = 0;
  5813. found_blocks = 0;
  5814. total_diff_accepted = 0;
  5815. total_diff_rejected = 0;
  5816. total_diff_stale = 0;
  5817. #ifdef HAVE_CURSES
  5818. awidth = rwidth = swidth = hwwidth = 1;
  5819. #endif
  5820. for (i = 0; i < total_pools; i++) {
  5821. struct pool *pool = pools[i];
  5822. pool->getwork_requested = 0;
  5823. pool->accepted = 0;
  5824. pool->rejected = 0;
  5825. pool->solved = 0;
  5826. pool->getwork_requested = 0;
  5827. pool->stale_shares = 0;
  5828. pool->discarded_work = 0;
  5829. pool->getfail_occasions = 0;
  5830. pool->remotefail_occasions = 0;
  5831. pool->last_share_time = 0;
  5832. pool->diff1 = 0;
  5833. pool->diff_accepted = 0;
  5834. pool->diff_rejected = 0;
  5835. pool->diff_stale = 0;
  5836. pool->last_share_diff = 0;
  5837. pool->cgminer_stats.start_tv = total_tv_start;
  5838. pool->cgminer_stats.getwork_calls = 0;
  5839. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5840. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5841. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5842. pool->cgminer_pool_stats.getwork_calls = 0;
  5843. pool->cgminer_pool_stats.getwork_attempts = 0;
  5844. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5845. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  5846. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  5847. pool->cgminer_pool_stats.min_diff = 0;
  5848. pool->cgminer_pool_stats.max_diff = 0;
  5849. pool->cgminer_pool_stats.min_diff_count = 0;
  5850. pool->cgminer_pool_stats.max_diff_count = 0;
  5851. pool->cgminer_pool_stats.times_sent = 0;
  5852. pool->cgminer_pool_stats.bytes_sent = 0;
  5853. pool->cgminer_pool_stats.net_bytes_sent = 0;
  5854. pool->cgminer_pool_stats.times_received = 0;
  5855. pool->cgminer_pool_stats.bytes_received = 0;
  5856. pool->cgminer_pool_stats.net_bytes_received = 0;
  5857. }
  5858. zero_bestshare();
  5859. for (i = 0; i < total_devices; ++i) {
  5860. struct cgpu_info *cgpu = get_devices(i);
  5861. mutex_lock(&hash_lock);
  5862. cgpu->total_mhashes = 0;
  5863. cgpu->accepted = 0;
  5864. cgpu->rejected = 0;
  5865. cgpu->stale = 0;
  5866. cgpu->hw_errors = 0;
  5867. cgpu->utility = 0.0;
  5868. cgpu->utility_diff1 = 0;
  5869. cgpu->last_share_pool_time = 0;
  5870. cgpu->bad_diff1 = 0;
  5871. cgpu->diff1 = 0;
  5872. cgpu->diff_accepted = 0;
  5873. cgpu->diff_rejected = 0;
  5874. cgpu->diff_stale = 0;
  5875. cgpu->last_share_diff = 0;
  5876. cgpu->thread_fail_init_count = 0;
  5877. cgpu->thread_zero_hash_count = 0;
  5878. cgpu->thread_fail_queue_count = 0;
  5879. cgpu->dev_sick_idle_60_count = 0;
  5880. cgpu->dev_dead_idle_600_count = 0;
  5881. cgpu->dev_nostart_count = 0;
  5882. cgpu->dev_over_heat_count = 0;
  5883. cgpu->dev_thermal_cutoff_count = 0;
  5884. cgpu->dev_comms_error_count = 0;
  5885. cgpu->dev_throttle_count = 0;
  5886. cgpu->cgminer_stats.start_tv = total_tv_start;
  5887. cgpu->cgminer_stats.getwork_calls = 0;
  5888. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5889. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5890. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5891. mutex_unlock(&hash_lock);
  5892. }
  5893. }
  5894. #ifdef HAVE_CURSES
  5895. static
  5896. void loginput_mode(const int size)
  5897. {
  5898. clear_logwin();
  5899. loginput_size = size;
  5900. check_winsizes();
  5901. }
  5902. static void display_pools(void)
  5903. {
  5904. struct pool *pool;
  5905. int selected, i, j;
  5906. char input;
  5907. loginput_mode(7 + total_pools);
  5908. immedok(logwin, true);
  5909. updated:
  5910. for (j = 0; j < total_pools; j++) {
  5911. for (i = 0; i < total_pools; i++) {
  5912. pool = pools[i];
  5913. if (pool->prio != j)
  5914. continue;
  5915. if (pool == current_pool())
  5916. wattron(logwin, A_BOLD);
  5917. if (pool->enabled != POOL_ENABLED)
  5918. wattron(logwin, A_DIM);
  5919. wlogprint("%d: ", pool->prio);
  5920. switch (pool->enabled) {
  5921. case POOL_ENABLED:
  5922. wlogprint("Enabled ");
  5923. break;
  5924. case POOL_DISABLED:
  5925. wlogprint("Disabled ");
  5926. break;
  5927. case POOL_REJECTING:
  5928. wlogprint("Rejectin ");
  5929. break;
  5930. }
  5931. if (pool->idle)
  5932. wlogprint("Dead ");
  5933. else
  5934. if (pool->has_stratum)
  5935. wlogprint("Strtm");
  5936. else
  5937. if (pool->lp_url && pool->proto != pool->lp_proto)
  5938. wlogprint("Mixed");
  5939. else
  5940. switch (pool->proto) {
  5941. case PLP_GETBLOCKTEMPLATE:
  5942. wlogprint(" GBT ");
  5943. break;
  5944. case PLP_GETWORK:
  5945. wlogprint("GWork");
  5946. break;
  5947. default:
  5948. wlogprint("Alive");
  5949. }
  5950. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  5951. pool->quota,
  5952. pool->pool_no,
  5953. pool->rpc_url, pool->rpc_user);
  5954. wattroff(logwin, A_BOLD | A_DIM);
  5955. break; //for (i = 0; i < total_pools; i++)
  5956. }
  5957. }
  5958. retry:
  5959. wlogprint("\nCurrent pool management strategy: %s\n",
  5960. strategies[pool_strategy].s);
  5961. if (pool_strategy == POOL_ROTATE)
  5962. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  5963. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  5964. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  5965. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  5966. wlogprint("Or press any other key to continue\n");
  5967. logwin_update();
  5968. input = getch();
  5969. if (!strncasecmp(&input, "a", 1)) {
  5970. input_pool(true);
  5971. goto updated;
  5972. } else if (!strncasecmp(&input, "r", 1)) {
  5973. if (total_pools <= 1) {
  5974. wlogprint("Cannot remove last pool");
  5975. goto retry;
  5976. }
  5977. selected = curses_int("Select pool number");
  5978. if (selected < 0 || selected >= total_pools) {
  5979. wlogprint("Invalid selection\n");
  5980. goto retry;
  5981. }
  5982. pool = pools[selected];
  5983. if (pool == current_pool())
  5984. switch_pools(NULL);
  5985. if (pool == current_pool()) {
  5986. wlogprint("Unable to remove pool due to activity\n");
  5987. goto retry;
  5988. }
  5989. disable_pool(pool);
  5990. remove_pool(pool);
  5991. goto updated;
  5992. } else if (!strncasecmp(&input, "s", 1)) {
  5993. selected = curses_int("Select pool number");
  5994. if (selected < 0 || selected >= total_pools) {
  5995. wlogprint("Invalid selection\n");
  5996. goto retry;
  5997. }
  5998. pool = pools[selected];
  5999. enable_pool(pool);
  6000. switch_pools(pool);
  6001. goto updated;
  6002. } else if (!strncasecmp(&input, "d", 1)) {
  6003. if (enabled_pools <= 1) {
  6004. wlogprint("Cannot disable last pool");
  6005. goto retry;
  6006. }
  6007. selected = curses_int("Select pool number");
  6008. if (selected < 0 || selected >= total_pools) {
  6009. wlogprint("Invalid selection\n");
  6010. goto retry;
  6011. }
  6012. pool = pools[selected];
  6013. disable_pool(pool);
  6014. if (pool == current_pool())
  6015. switch_pools(NULL);
  6016. goto updated;
  6017. } else if (!strncasecmp(&input, "e", 1)) {
  6018. selected = curses_int("Select pool number");
  6019. if (selected < 0 || selected >= total_pools) {
  6020. wlogprint("Invalid selection\n");
  6021. goto retry;
  6022. }
  6023. pool = pools[selected];
  6024. enable_pool(pool);
  6025. if (pool->prio < current_pool()->prio)
  6026. switch_pools(pool);
  6027. goto updated;
  6028. } else if (!strncasecmp(&input, "c", 1)) {
  6029. for (i = 0; i <= TOP_STRATEGY; i++)
  6030. wlogprint("%d: %s\n", i, strategies[i].s);
  6031. selected = curses_int("Select strategy number type");
  6032. if (selected < 0 || selected > TOP_STRATEGY) {
  6033. wlogprint("Invalid selection\n");
  6034. goto retry;
  6035. }
  6036. if (selected == POOL_ROTATE) {
  6037. opt_rotate_period = curses_int("Select interval in minutes");
  6038. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6039. opt_rotate_period = 0;
  6040. wlogprint("Invalid selection\n");
  6041. goto retry;
  6042. }
  6043. }
  6044. pool_strategy = selected;
  6045. switch_pools(NULL);
  6046. goto updated;
  6047. } else if (!strncasecmp(&input, "i", 1)) {
  6048. selected = curses_int("Select pool number");
  6049. if (selected < 0 || selected >= total_pools) {
  6050. wlogprint("Invalid selection\n");
  6051. goto retry;
  6052. }
  6053. pool = pools[selected];
  6054. display_pool_summary(pool);
  6055. goto retry;
  6056. } else if (!strncasecmp(&input, "q", 1)) {
  6057. selected = curses_int("Select pool number");
  6058. if (selected < 0 || selected >= total_pools) {
  6059. wlogprint("Invalid selection\n");
  6060. goto retry;
  6061. }
  6062. pool = pools[selected];
  6063. selected = curses_int("Set quota");
  6064. if (selected < 0) {
  6065. wlogprint("Invalid negative quota\n");
  6066. goto retry;
  6067. }
  6068. pool->quota = selected;
  6069. adjust_quota_gcd();
  6070. goto updated;
  6071. } else if (!strncasecmp(&input, "f", 1)) {
  6072. opt_fail_only ^= true;
  6073. goto updated;
  6074. } else if (!strncasecmp(&input, "p", 1)) {
  6075. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6076. if (!prilist)
  6077. {
  6078. wlogprint("Not changing priorities\n");
  6079. goto retry;
  6080. }
  6081. int res = prioritize_pools(prilist, &i);
  6082. free(prilist);
  6083. switch (res) {
  6084. case MSG_NOPOOL:
  6085. wlogprint("No pools\n");
  6086. goto retry;
  6087. case MSG_MISPID:
  6088. wlogprint("Missing pool id parameter\n");
  6089. goto retry;
  6090. case MSG_INVPID:
  6091. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6092. goto retry;
  6093. case MSG_DUPPID:
  6094. wlogprint("Duplicate pool specified %d\n", i);
  6095. goto retry;
  6096. case MSG_POOLPRIO:
  6097. default:
  6098. goto updated;
  6099. }
  6100. }
  6101. immedok(logwin, false);
  6102. loginput_mode(0);
  6103. }
  6104. static const char *summary_detail_level_str(void)
  6105. {
  6106. if (opt_compact)
  6107. return "compact";
  6108. if (opt_show_procs)
  6109. return "processors";
  6110. return "devices";
  6111. }
  6112. static void display_options(void)
  6113. {
  6114. int selected;
  6115. char input;
  6116. immedok(logwin, true);
  6117. loginput_mode(12);
  6118. retry:
  6119. clear_logwin();
  6120. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6121. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6122. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6123. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6124. opt_debug_console ? "on" : "off",
  6125. want_per_device_stats? "on" : "off",
  6126. opt_quiet ? "on" : "off",
  6127. opt_log_output ? "on" : "off",
  6128. opt_protocol ? "on" : "off",
  6129. opt_worktime ? "on" : "off",
  6130. summary_detail_level_str(),
  6131. opt_log_interval,
  6132. opt_weighed_stats ? "weighed" : "absolute");
  6133. wlogprint("Select an option or any other key to return\n");
  6134. logwin_update();
  6135. input = getch();
  6136. if (!strncasecmp(&input, "q", 1)) {
  6137. opt_quiet ^= true;
  6138. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6139. goto retry;
  6140. } else if (!strncasecmp(&input, "v", 1)) {
  6141. opt_log_output ^= true;
  6142. if (opt_log_output)
  6143. opt_quiet = false;
  6144. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6145. goto retry;
  6146. } else if (!strncasecmp(&input, "n", 1)) {
  6147. opt_log_output = false;
  6148. opt_debug_console = false;
  6149. opt_quiet = false;
  6150. opt_protocol = false;
  6151. opt_compact = false;
  6152. opt_show_procs = false;
  6153. devsummaryYOffset = 0;
  6154. want_per_device_stats = false;
  6155. wlogprint("Output mode reset to normal\n");
  6156. switch_logsize();
  6157. goto retry;
  6158. } else if (!strncasecmp(&input, "d", 1)) {
  6159. opt_debug = true;
  6160. opt_debug_console ^= true;
  6161. opt_log_output = opt_debug_console;
  6162. if (opt_debug_console)
  6163. opt_quiet = false;
  6164. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6165. goto retry;
  6166. } else if (!strncasecmp(&input, "m", 1)) {
  6167. if (opt_compact)
  6168. opt_compact = false;
  6169. else
  6170. if (!opt_show_procs)
  6171. opt_show_procs = true;
  6172. else
  6173. {
  6174. opt_compact = true;
  6175. opt_show_procs = false;
  6176. devsummaryYOffset = 0;
  6177. }
  6178. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6179. switch_logsize();
  6180. goto retry;
  6181. } else if (!strncasecmp(&input, "p", 1)) {
  6182. want_per_device_stats ^= true;
  6183. opt_log_output = want_per_device_stats;
  6184. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6185. goto retry;
  6186. } else if (!strncasecmp(&input, "r", 1)) {
  6187. opt_protocol ^= true;
  6188. if (opt_protocol)
  6189. opt_quiet = false;
  6190. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6191. goto retry;
  6192. } else if (!strncasecmp(&input, "c", 1))
  6193. clear_logwin();
  6194. else if (!strncasecmp(&input, "l", 1)) {
  6195. selected = curses_int("Interval in seconds");
  6196. if (selected < 0 || selected > 9999) {
  6197. wlogprint("Invalid selection\n");
  6198. goto retry;
  6199. }
  6200. opt_log_interval = selected;
  6201. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6202. goto retry;
  6203. } else if (!strncasecmp(&input, "s", 1)) {
  6204. opt_realquiet = true;
  6205. } else if (!strncasecmp(&input, "w", 1)) {
  6206. opt_worktime ^= true;
  6207. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6208. goto retry;
  6209. } else if (!strncasecmp(&input, "t", 1)) {
  6210. opt_weighed_stats ^= true;
  6211. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  6212. goto retry;
  6213. } else if (!strncasecmp(&input, "z", 1)) {
  6214. zero_stats();
  6215. goto retry;
  6216. }
  6217. immedok(logwin, false);
  6218. loginput_mode(0);
  6219. }
  6220. #endif
  6221. void default_save_file(char *filename)
  6222. {
  6223. #if defined(unix) || defined(__APPLE__)
  6224. if (getenv("HOME") && *getenv("HOME")) {
  6225. strcpy(filename, getenv("HOME"));
  6226. strcat(filename, "/");
  6227. }
  6228. else
  6229. strcpy(filename, "");
  6230. strcat(filename, ".bfgminer/");
  6231. mkdir(filename, 0777);
  6232. #else
  6233. strcpy(filename, "");
  6234. #endif
  6235. strcat(filename, def_conf);
  6236. }
  6237. #ifdef HAVE_CURSES
  6238. static void set_options(void)
  6239. {
  6240. int selected;
  6241. char input;
  6242. immedok(logwin, true);
  6243. loginput_mode(8);
  6244. retry:
  6245. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6246. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6247. "[W]rite config file\n[B]FGMiner restart\n",
  6248. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6249. wlogprint("Select an option or any other key to return\n");
  6250. logwin_update();
  6251. input = getch();
  6252. if (!strncasecmp(&input, "q", 1)) {
  6253. selected = curses_int("Extra work items to queue");
  6254. if (selected < 0 || selected > 9999) {
  6255. wlogprint("Invalid selection\n");
  6256. goto retry;
  6257. }
  6258. opt_queue = selected;
  6259. goto retry;
  6260. } else if (!strncasecmp(&input, "l", 1)) {
  6261. if (want_longpoll)
  6262. stop_longpoll();
  6263. else
  6264. start_longpoll();
  6265. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6266. goto retry;
  6267. } else if (!strncasecmp(&input, "s", 1)) {
  6268. selected = curses_int("Set scantime in seconds");
  6269. if (selected < 0 || selected > 9999) {
  6270. wlogprint("Invalid selection\n");
  6271. goto retry;
  6272. }
  6273. opt_scantime = selected;
  6274. goto retry;
  6275. } else if (!strncasecmp(&input, "e", 1)) {
  6276. selected = curses_int("Set expiry time in seconds");
  6277. if (selected < 0 || selected > 9999) {
  6278. wlogprint("Invalid selection\n");
  6279. goto retry;
  6280. }
  6281. opt_expiry = selected;
  6282. goto retry;
  6283. } else if (!strncasecmp(&input, "r", 1)) {
  6284. selected = curses_int("Retries before failing (-1 infinite)");
  6285. if (selected < -1 || selected > 9999) {
  6286. wlogprint("Invalid selection\n");
  6287. goto retry;
  6288. }
  6289. opt_retries = selected;
  6290. goto retry;
  6291. } else if (!strncasecmp(&input, "w", 1)) {
  6292. FILE *fcfg;
  6293. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6294. default_save_file(filename);
  6295. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6296. str = curses_input(prompt);
  6297. if (str) {
  6298. struct stat statbuf;
  6299. strcpy(filename, str);
  6300. free(str);
  6301. if (!stat(filename, &statbuf)) {
  6302. wlogprint("File exists, overwrite?\n");
  6303. input = getch();
  6304. if (strncasecmp(&input, "y", 1))
  6305. goto retry;
  6306. }
  6307. }
  6308. fcfg = fopen(filename, "w");
  6309. if (!fcfg) {
  6310. wlogprint("Cannot open or create file\n");
  6311. goto retry;
  6312. }
  6313. write_config(fcfg);
  6314. fclose(fcfg);
  6315. goto retry;
  6316. } else if (!strncasecmp(&input, "b", 1)) {
  6317. wlogprint("Are you sure?\n");
  6318. input = getch();
  6319. if (!strncasecmp(&input, "y", 1))
  6320. app_restart();
  6321. else
  6322. clear_logwin();
  6323. } else
  6324. clear_logwin();
  6325. loginput_mode(0);
  6326. immedok(logwin, false);
  6327. }
  6328. int scan_serial(const char *);
  6329. static
  6330. void _managetui_msg(const char *repr, const char **msg)
  6331. {
  6332. if (*msg)
  6333. {
  6334. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6335. wattron(logwin, A_BOLD);
  6336. wlogprint("%s", *msg);
  6337. wattroff(logwin, A_BOLD);
  6338. *msg = NULL;
  6339. }
  6340. logwin_update();
  6341. }
  6342. void manage_device(void)
  6343. {
  6344. char logline[256];
  6345. const char *msg = NULL;
  6346. struct cgpu_info *cgpu;
  6347. const struct device_drv *drv;
  6348. selecting_device = true;
  6349. immedok(logwin, true);
  6350. loginput_mode(12);
  6351. devchange:
  6352. if (unlikely(!total_devices))
  6353. {
  6354. clear_logwin();
  6355. wlogprint("(no devices)\n");
  6356. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6357. _managetui_msg("(none)", &msg);
  6358. int input = getch();
  6359. switch (input)
  6360. {
  6361. case '+': case '=': // add new device
  6362. goto addnew;
  6363. default:
  6364. goto out;
  6365. }
  6366. }
  6367. cgpu = devices[selected_device];
  6368. drv = cgpu->drv;
  6369. refresh_devstatus();
  6370. refresh:
  6371. clear_logwin();
  6372. wlogprint("Select processor to manage using up/down arrow keys\n");
  6373. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6374. wattron(logwin, A_BOLD);
  6375. wlogprint("%s", logline);
  6376. wattroff(logwin, A_BOLD);
  6377. wlogprint("\n");
  6378. if (cgpu->dev_manufacturer)
  6379. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6380. else
  6381. if (cgpu->dev_product)
  6382. wlogprint(" %s\n", cgpu->dev_product);
  6383. if (cgpu->dev_serial)
  6384. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6385. if (cgpu->kname)
  6386. wlogprint("Kernel: %s\n", cgpu->kname);
  6387. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6388. drv->proc_wlogprint_status(cgpu);
  6389. wlogprint("\n");
  6390. // TODO: Last share at TIMESTAMP on pool N
  6391. // TODO: Custom device info/commands
  6392. if (cgpu->deven != DEV_ENABLED)
  6393. wlogprint("[E]nable ");
  6394. if (cgpu->deven != DEV_DISABLED)
  6395. wlogprint("[D]isable ");
  6396. if (drv->identify_device)
  6397. wlogprint("[I]dentify ");
  6398. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6399. drv->proc_tui_wlogprint_choices(cgpu);
  6400. wlogprint("\n");
  6401. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6402. _managetui_msg(cgpu->proc_repr, &msg);
  6403. while (true)
  6404. {
  6405. int input = getch();
  6406. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6407. switch (input) {
  6408. case 'd': case 'D':
  6409. if (cgpu->deven == DEV_DISABLED)
  6410. msg = "Processor already disabled\n";
  6411. else
  6412. {
  6413. cgpu->deven = DEV_DISABLED;
  6414. msg = "Processor being disabled\n";
  6415. }
  6416. goto refresh;
  6417. case 'e': case 'E':
  6418. if (cgpu->deven == DEV_ENABLED)
  6419. msg = "Processor already enabled\n";
  6420. else
  6421. {
  6422. proc_enable(cgpu);
  6423. msg = "Processor being enabled\n";
  6424. }
  6425. goto refresh;
  6426. case 'i': case 'I':
  6427. if (drv->identify_device && drv->identify_device(cgpu))
  6428. msg = "Identify command sent\n";
  6429. else
  6430. goto key_default;
  6431. goto refresh;
  6432. case KEY_DOWN:
  6433. if (selected_device >= total_devices - 1)
  6434. break;
  6435. ++selected_device;
  6436. goto devchange;
  6437. case KEY_UP:
  6438. if (selected_device <= 0)
  6439. break;
  6440. --selected_device;
  6441. goto devchange;
  6442. case KEY_NPAGE:
  6443. {
  6444. if (selected_device >= total_devices - 1)
  6445. break;
  6446. struct cgpu_info *mdev = devices[selected_device]->device;
  6447. do {
  6448. ++selected_device;
  6449. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6450. goto devchange;
  6451. }
  6452. case KEY_PPAGE:
  6453. {
  6454. if (selected_device <= 0)
  6455. break;
  6456. struct cgpu_info *mdev = devices[selected_device]->device;
  6457. do {
  6458. --selected_device;
  6459. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6460. goto devchange;
  6461. }
  6462. case '/': case '?': // find device
  6463. {
  6464. static char *pattern = NULL;
  6465. char *newpattern = curses_input("Enter pattern");
  6466. if (newpattern)
  6467. {
  6468. free(pattern);
  6469. pattern = newpattern;
  6470. }
  6471. else
  6472. if (!pattern)
  6473. pattern = calloc(1, 1);
  6474. int match = cgpu_search(pattern, selected_device + 1);
  6475. if (match == -1)
  6476. {
  6477. msg = "Couldn't find device\n";
  6478. goto refresh;
  6479. }
  6480. selected_device = match;
  6481. goto devchange;
  6482. }
  6483. case '+': case '=': // add new device
  6484. {
  6485. addnew:
  6486. clear_logwin();
  6487. _wlogprint(
  6488. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6489. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6490. "For example: erupter:"
  6491. #ifdef WIN32
  6492. "\\\\.\\COM40"
  6493. #elif defined(__APPLE__)
  6494. "/dev/cu.SLAB_USBtoUART"
  6495. #else
  6496. "/dev/ttyUSB39"
  6497. #endif
  6498. "\n"
  6499. );
  6500. char *scanser = curses_input("Enter target");
  6501. if (scan_serial(scanser))
  6502. {
  6503. selected_device = total_devices - 1;
  6504. msg = "Device scan succeeded\n";
  6505. }
  6506. else
  6507. msg = "No new devices found\n";
  6508. goto devchange;
  6509. }
  6510. case 'Q': case 'q':
  6511. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6512. case '\x1b': // ESC
  6513. case KEY_ENTER:
  6514. case '\r': // Ctrl-M on Windows, with nonl
  6515. #ifdef PADENTER
  6516. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6517. #endif
  6518. case '\n':
  6519. goto out;
  6520. default:
  6521. ;
  6522. key_default:
  6523. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6524. {
  6525. msg = drv->proc_tui_handle_choice(cgpu, input);
  6526. if (msg)
  6527. goto refresh;
  6528. }
  6529. }
  6530. }
  6531. out:
  6532. selecting_device = false;
  6533. loginput_mode(0);
  6534. immedok(logwin, false);
  6535. }
  6536. void show_help(void)
  6537. {
  6538. loginput_mode(10);
  6539. // NOTE: wlogprint is a macro with a buffer limit
  6540. _wlogprint(
  6541. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6542. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6543. "E: # shares * diff per 2kB bw | U: shares/minute | BS: best share ever found\n"
  6544. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6545. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6546. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6547. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  6548. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6549. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6550. U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6551. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6552. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6553. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6554. "\n"
  6555. "devices/processors hashing (only for totals line), hottest temperature\n"
  6556. );
  6557. wlogprint(
  6558. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6559. , opt_log_interval);
  6560. _wlogprint(
  6561. "A: accepted shares | R: rejected+discarded(%% of total)\n"
  6562. "HW: hardware errors / %% nonces invalid\n"
  6563. "\n"
  6564. "Press any key to clear"
  6565. );
  6566. logwin_update();
  6567. getch();
  6568. loginput_mode(0);
  6569. }
  6570. static void *input_thread(void __maybe_unused *userdata)
  6571. {
  6572. RenameThread("input");
  6573. if (!curses_active)
  6574. return NULL;
  6575. while (1) {
  6576. int input;
  6577. input = getch();
  6578. switch (input) {
  6579. case 'h': case 'H': case '?':
  6580. case KEY_F(1):
  6581. show_help();
  6582. break;
  6583. case 'q': case 'Q':
  6584. kill_work();
  6585. return NULL;
  6586. case 'd': case 'D':
  6587. display_options();
  6588. break;
  6589. case 'm': case 'M':
  6590. manage_device();
  6591. break;
  6592. case 'p': case 'P':
  6593. display_pools();
  6594. break;
  6595. case 's': case 'S':
  6596. set_options();
  6597. break;
  6598. #ifdef HAVE_CURSES
  6599. case KEY_DOWN:
  6600. {
  6601. const int visible_lines = logcursor - devcursor;
  6602. const int invisible_lines = total_lines - visible_lines;
  6603. if (devsummaryYOffset <= -invisible_lines)
  6604. break;
  6605. devsummaryYOffset -= 2;
  6606. }
  6607. case KEY_UP:
  6608. if (devsummaryYOffset == 0)
  6609. break;
  6610. ++devsummaryYOffset;
  6611. refresh_devstatus();
  6612. break;
  6613. case KEY_NPAGE:
  6614. {
  6615. const int visible_lines = logcursor - devcursor;
  6616. const int invisible_lines = total_lines - visible_lines;
  6617. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  6618. devsummaryYOffset = -invisible_lines;
  6619. else
  6620. devsummaryYOffset -= visible_lines;
  6621. refresh_devstatus();
  6622. break;
  6623. }
  6624. case KEY_PPAGE:
  6625. {
  6626. const int visible_lines = logcursor - devcursor;
  6627. if (devsummaryYOffset + visible_lines >= 0)
  6628. devsummaryYOffset = 0;
  6629. else
  6630. devsummaryYOffset += visible_lines;
  6631. refresh_devstatus();
  6632. break;
  6633. }
  6634. #endif
  6635. }
  6636. if (opt_realquiet) {
  6637. disable_curses();
  6638. break;
  6639. }
  6640. }
  6641. return NULL;
  6642. }
  6643. #endif
  6644. static void *api_thread(void *userdata)
  6645. {
  6646. struct thr_info *mythr = userdata;
  6647. pthread_detach(pthread_self());
  6648. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6649. RenameThread("rpc");
  6650. api(api_thr_id);
  6651. mythr->has_pth = false;
  6652. return NULL;
  6653. }
  6654. void thread_reportin(struct thr_info *thr)
  6655. {
  6656. cgtime(&thr->last);
  6657. thr->cgpu->status = LIFE_WELL;
  6658. thr->getwork = 0;
  6659. thr->cgpu->device_last_well = time(NULL);
  6660. }
  6661. void thread_reportout(struct thr_info *thr)
  6662. {
  6663. thr->getwork = time(NULL);
  6664. }
  6665. static void hashmeter(int thr_id, struct timeval *diff,
  6666. uint64_t hashes_done)
  6667. {
  6668. char logstatusline[256];
  6669. struct timeval temp_tv_end, total_diff;
  6670. double secs;
  6671. double local_secs;
  6672. static double local_mhashes_done = 0;
  6673. double local_mhashes = (double)hashes_done / 1000000.0;
  6674. bool showlog = false;
  6675. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  6676. char rejpcbuf[6];
  6677. char bnbuf[6];
  6678. struct thr_info *thr;
  6679. /* Update the last time this thread reported in */
  6680. if (thr_id >= 0) {
  6681. thr = get_thread(thr_id);
  6682. cgtime(&(thr->last));
  6683. thr->cgpu->device_last_well = time(NULL);
  6684. }
  6685. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  6686. /* So we can call hashmeter from a non worker thread */
  6687. if (thr_id >= 0) {
  6688. struct cgpu_info *cgpu = thr->cgpu;
  6689. int threadobj = cgpu->threads ?: 1;
  6690. double thread_rolling = 0.0;
  6691. int i;
  6692. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  6693. thr_id, hashes_done, hashes_done / 1000 / secs);
  6694. /* Rolling average for each thread and each device */
  6695. decay_time(&thr->rolling, local_mhashes / secs, secs);
  6696. for (i = 0; i < threadobj; i++)
  6697. thread_rolling += cgpu->thr[i]->rolling;
  6698. mutex_lock(&hash_lock);
  6699. decay_time(&cgpu->rolling, thread_rolling, secs);
  6700. cgpu->total_mhashes += local_mhashes;
  6701. mutex_unlock(&hash_lock);
  6702. // If needed, output detailed, per-device stats
  6703. if (want_per_device_stats) {
  6704. struct timeval now;
  6705. struct timeval elapsed;
  6706. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  6707. cgtime(&now);
  6708. timersub(&now, last_msg_tv, &elapsed);
  6709. if (opt_log_interval <= elapsed.tv_sec) {
  6710. struct cgpu_info *cgpu = thr->cgpu;
  6711. char logline[255];
  6712. *last_msg_tv = now;
  6713. get_statline(logline, sizeof(logline), cgpu);
  6714. if (!curses_active) {
  6715. printf("%s \r", logline);
  6716. fflush(stdout);
  6717. } else
  6718. applog(LOG_INFO, "%s", logline);
  6719. }
  6720. }
  6721. }
  6722. /* Totals are updated by all threads so can race without locking */
  6723. mutex_lock(&hash_lock);
  6724. cgtime(&temp_tv_end);
  6725. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  6726. total_mhashes_done += local_mhashes;
  6727. local_mhashes_done += local_mhashes;
  6728. /* Only update with opt_log_interval */
  6729. if (total_diff.tv_sec < opt_log_interval)
  6730. goto out_unlock;
  6731. showlog = true;
  6732. cgtime(&total_tv_end);
  6733. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  6734. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  6735. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  6736. timersub(&total_tv_end, &total_tv_start, &total_diff);
  6737. total_secs = (double)total_diff.tv_sec +
  6738. ((double)total_diff.tv_usec / 1000000.0);
  6739. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  6740. multi_format_unit_array2(
  6741. ((char*[]){cHr, aHr, uHr}),
  6742. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_SPACED]}),
  6743. true, "h/s", H2B_SHORT,
  6744. 3,
  6745. 1e6*total_rolling,
  6746. 1e6*total_mhashes_done / total_secs,
  6747. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  6748. int ui_accepted, ui_rejected, ui_stale;
  6749. if (opt_weighed_stats)
  6750. {
  6751. ui_accepted = total_diff_accepted;
  6752. ui_rejected = total_diff_rejected;
  6753. ui_stale = total_diff_stale;
  6754. }
  6755. else
  6756. {
  6757. ui_accepted = total_accepted;
  6758. ui_rejected = total_rejected;
  6759. ui_stale = total_stale;
  6760. }
  6761. #ifdef HAVE_CURSES
  6762. if (curses_active_locked()) {
  6763. float temp = 0;
  6764. struct cgpu_info *proc, *last_working_dev = NULL;
  6765. int i, working_devs = 0, working_procs = 0;
  6766. int divx;
  6767. bool bad = false;
  6768. // Find the highest temperature of all processors
  6769. for (i = 0; i < total_devices; ++i)
  6770. {
  6771. proc = get_devices(i);
  6772. if (proc->temp > temp)
  6773. temp = proc->temp;
  6774. if (unlikely(proc->deven == DEV_DISABLED))
  6775. ; // Just need to block it off from both conditions
  6776. else
  6777. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  6778. {
  6779. if (proc->rolling > .1)
  6780. {
  6781. ++working_procs;
  6782. if (proc->device != last_working_dev)
  6783. {
  6784. ++working_devs;
  6785. last_working_dev = proc->device;
  6786. }
  6787. }
  6788. }
  6789. else
  6790. bad = true;
  6791. }
  6792. if (working_devs == working_procs)
  6793. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  6794. else
  6795. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  6796. divx = 7;
  6797. if (opt_show_procs && !opt_compact)
  6798. ++divx;
  6799. if (bad)
  6800. {
  6801. divx += sizeof(U8_BAD_START)-1;
  6802. strcpy(&statusline[divx], U8_BAD_END);
  6803. divx += sizeof(U8_BAD_END)-1;
  6804. }
  6805. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  6806. format_statline(statusline, sizeof(statusline),
  6807. cHr, aHr,
  6808. uHr,
  6809. ui_accepted,
  6810. ui_rejected,
  6811. ui_stale,
  6812. total_diff_rejected + total_diff_stale, total_diff_accepted,
  6813. hw_errors,
  6814. total_bad_diff1, total_bad_diff1 + total_diff1);
  6815. unlock_curses();
  6816. }
  6817. #endif
  6818. // Add a space
  6819. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  6820. uHr[5] = ' ';
  6821. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  6822. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  6823. snprintf(logstatusline, sizeof(logstatusline),
  6824. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  6825. want_per_device_stats ? "ALL " : "",
  6826. opt_log_interval,
  6827. cHr, aHr,
  6828. uHr,
  6829. ui_accepted,
  6830. ui_rejected,
  6831. ui_stale,
  6832. rejpcbuf,
  6833. hw_errors,
  6834. bnbuf
  6835. );
  6836. local_mhashes_done = 0;
  6837. out_unlock:
  6838. mutex_unlock(&hash_lock);
  6839. if (showlog) {
  6840. if (!curses_active) {
  6841. printf("%s \r", logstatusline);
  6842. fflush(stdout);
  6843. } else
  6844. applog(LOG_INFO, "%s", logstatusline);
  6845. }
  6846. }
  6847. void hashmeter2(struct thr_info *thr)
  6848. {
  6849. struct timeval tv_now, tv_elapsed;
  6850. timerclear(&thr->tv_hashes_done);
  6851. cgtime(&tv_now);
  6852. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  6853. /* Update the hashmeter at most 5 times per second */
  6854. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  6855. tv_elapsed.tv_sec >= opt_log_interval) {
  6856. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  6857. thr->hashes_done = 0;
  6858. thr->tv_lastupdate = tv_now;
  6859. }
  6860. }
  6861. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  6862. struct stratum_share *sshare)
  6863. {
  6864. struct work *work = sshare->work;
  6865. share_result(val, res_val, err_val, work, false, "");
  6866. }
  6867. /* Parses stratum json responses and tries to find the id that the request
  6868. * matched to and treat it accordingly. */
  6869. bool parse_stratum_response(struct pool *pool, char *s)
  6870. {
  6871. json_t *val = NULL, *err_val, *res_val, *id_val;
  6872. struct stratum_share *sshare;
  6873. json_error_t err;
  6874. bool ret = false;
  6875. int id;
  6876. val = JSON_LOADS(s, &err);
  6877. if (!val) {
  6878. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  6879. goto out;
  6880. }
  6881. res_val = json_object_get(val, "result");
  6882. err_val = json_object_get(val, "error");
  6883. id_val = json_object_get(val, "id");
  6884. if (json_is_null(id_val) || !id_val) {
  6885. char *ss;
  6886. if (err_val)
  6887. ss = json_dumps(err_val, JSON_INDENT(3));
  6888. else
  6889. ss = strdup("(unknown reason)");
  6890. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  6891. free(ss);
  6892. goto out;
  6893. }
  6894. if (!json_is_integer(id_val)) {
  6895. if (json_is_string(id_val)
  6896. && !strncmp(json_string_value(id_val), "txlist", 6))
  6897. {
  6898. const bool is_array = json_is_array(res_val);
  6899. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  6900. is_array ? "transaction list" : "no-transaction-list response",
  6901. pool->pool_no, &json_string_value(id_val)[6]);
  6902. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id) || !is_array)
  6903. // We only care about a transaction list for the current job id
  6904. goto fishy;
  6905. // Check that the transactions actually hash to the merkle links
  6906. {
  6907. unsigned maxtx = 1 << pool->swork.merkles;
  6908. unsigned mintx = maxtx >> 1;
  6909. --maxtx;
  6910. unsigned acttx = (unsigned)json_array_size(res_val);
  6911. if (acttx < mintx || acttx > maxtx) {
  6912. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  6913. pool->pool_no, acttx, mintx, maxtx);
  6914. goto fishy;
  6915. }
  6916. // TODO: Check hashes match actual merkle links
  6917. }
  6918. pool_set_opaque(pool, false);
  6919. timer_unset(&pool->swork.tv_transparency);
  6920. fishy:
  6921. ret = true;
  6922. }
  6923. goto out;
  6924. }
  6925. id = json_integer_value(id_val);
  6926. mutex_lock(&sshare_lock);
  6927. HASH_FIND_INT(stratum_shares, &id, sshare);
  6928. if (sshare)
  6929. HASH_DEL(stratum_shares, sshare);
  6930. mutex_unlock(&sshare_lock);
  6931. if (!sshare) {
  6932. double pool_diff;
  6933. /* Since the share is untracked, we can only guess at what the
  6934. * work difficulty is based on the current pool diff. */
  6935. cg_rlock(&pool->data_lock);
  6936. pool_diff = pool->swork.diff;
  6937. cg_runlock(&pool->data_lock);
  6938. if (json_is_true(res_val)) {
  6939. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  6940. /* We don't know what device this came from so we can't
  6941. * attribute the work to the relevant cgpu */
  6942. mutex_lock(&stats_lock);
  6943. total_accepted++;
  6944. pool->accepted++;
  6945. total_diff_accepted += pool_diff;
  6946. pool->diff_accepted += pool_diff;
  6947. mutex_unlock(&stats_lock);
  6948. } else {
  6949. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  6950. mutex_lock(&stats_lock);
  6951. total_rejected++;
  6952. pool->rejected++;
  6953. total_diff_rejected += pool_diff;
  6954. pool->diff_rejected += pool_diff;
  6955. mutex_unlock(&stats_lock);
  6956. }
  6957. goto out;
  6958. }
  6959. else {
  6960. mutex_lock(&submitting_lock);
  6961. --total_submitting;
  6962. mutex_unlock(&submitting_lock);
  6963. }
  6964. stratum_share_result(val, res_val, err_val, sshare);
  6965. free_work(sshare->work);
  6966. free(sshare);
  6967. ret = true;
  6968. out:
  6969. if (val)
  6970. json_decref(val);
  6971. return ret;
  6972. }
  6973. static void shutdown_stratum(struct pool *pool)
  6974. {
  6975. // Shut down Stratum as if we never had it
  6976. pool->stratum_active = false;
  6977. pool->stratum_init = false;
  6978. pool->has_stratum = false;
  6979. shutdown(pool->sock, SHUT_RDWR);
  6980. free(pool->stratum_url);
  6981. if (pool->sockaddr_url == pool->stratum_url)
  6982. pool->sockaddr_url = NULL;
  6983. pool->stratum_url = NULL;
  6984. }
  6985. void clear_stratum_shares(struct pool *pool)
  6986. {
  6987. int my_mining_threads = mining_threads; // Cached outside of locking
  6988. struct stratum_share *sshare, *tmpshare;
  6989. struct work *work;
  6990. struct cgpu_info *cgpu;
  6991. double diff_cleared = 0;
  6992. double thr_diff_cleared[my_mining_threads];
  6993. int cleared = 0;
  6994. int thr_cleared[my_mining_threads];
  6995. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  6996. for (int i = 0; i < my_mining_threads; ++i)
  6997. {
  6998. thr_diff_cleared[i] = 0;
  6999. thr_cleared[i] = 0;
  7000. }
  7001. mutex_lock(&sshare_lock);
  7002. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7003. work = sshare->work;
  7004. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7005. HASH_DEL(stratum_shares, sshare);
  7006. sharelog("disconnect", work);
  7007. diff_cleared += sshare->work->work_difficulty;
  7008. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7009. ++thr_cleared[work->thr_id];
  7010. free_work(sshare->work);
  7011. free(sshare);
  7012. cleared++;
  7013. }
  7014. }
  7015. mutex_unlock(&sshare_lock);
  7016. if (cleared) {
  7017. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7018. mutex_lock(&stats_lock);
  7019. pool->stale_shares += cleared;
  7020. total_stale += cleared;
  7021. pool->diff_stale += diff_cleared;
  7022. total_diff_stale += diff_cleared;
  7023. for (int i = 0; i < my_mining_threads; ++i)
  7024. if (thr_cleared[i])
  7025. {
  7026. cgpu = get_thr_cgpu(i);
  7027. cgpu->diff_stale += thr_diff_cleared[i];
  7028. cgpu->stale += thr_cleared[i];
  7029. }
  7030. mutex_unlock(&stats_lock);
  7031. mutex_lock(&submitting_lock);
  7032. total_submitting -= cleared;
  7033. mutex_unlock(&submitting_lock);
  7034. }
  7035. }
  7036. static void resubmit_stratum_shares(struct pool *pool)
  7037. {
  7038. struct stratum_share *sshare, *tmpshare;
  7039. struct work *work;
  7040. unsigned resubmitted = 0;
  7041. mutex_lock(&sshare_lock);
  7042. mutex_lock(&submitting_lock);
  7043. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7044. if (sshare->work->pool != pool)
  7045. continue;
  7046. HASH_DEL(stratum_shares, sshare);
  7047. work = sshare->work;
  7048. DL_APPEND(submit_waiting, work);
  7049. free(sshare);
  7050. ++resubmitted;
  7051. }
  7052. mutex_unlock(&submitting_lock);
  7053. mutex_unlock(&sshare_lock);
  7054. if (resubmitted) {
  7055. notifier_wake(submit_waiting_notifier);
  7056. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7057. }
  7058. }
  7059. static void clear_pool_work(struct pool *pool)
  7060. {
  7061. struct work *work, *tmp;
  7062. int cleared = 0;
  7063. mutex_lock(stgd_lock);
  7064. HASH_ITER(hh, staged_work, work, tmp) {
  7065. if (work->pool == pool) {
  7066. HASH_DEL(staged_work, work);
  7067. free_work(work);
  7068. cleared++;
  7069. staged_full = false;
  7070. }
  7071. }
  7072. mutex_unlock(stgd_lock);
  7073. }
  7074. static int cp_prio(void)
  7075. {
  7076. int prio;
  7077. cg_rlock(&control_lock);
  7078. prio = currentpool->prio;
  7079. cg_runlock(&control_lock);
  7080. return prio;
  7081. }
  7082. /* We only need to maintain a secondary pool connection when we need the
  7083. * capacity to get work from the backup pools while still on the primary */
  7084. static bool cnx_needed(struct pool *pool)
  7085. {
  7086. struct pool *cp;
  7087. if (pool->enabled != POOL_ENABLED)
  7088. return false;
  7089. /* Balance strategies need all pools online */
  7090. if (pool_strategy == POOL_BALANCE)
  7091. return true;
  7092. if (pool_strategy == POOL_LOADBALANCE)
  7093. return true;
  7094. /* Idle stratum pool needs something to kick it alive again */
  7095. if (pool->has_stratum && pool->idle)
  7096. return true;
  7097. /* Getwork pools without opt_fail_only need backup pools up to be able
  7098. * to leak shares */
  7099. cp = current_pool();
  7100. if (cp == pool)
  7101. return true;
  7102. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7103. return true;
  7104. /* Keep the connection open to allow any stray shares to be submitted
  7105. * on switching pools for 2 minutes. */
  7106. if (!timer_passed(&pool->tv_last_work_time, NULL))
  7107. return true;
  7108. /* If the pool has only just come to life and is higher priority than
  7109. * the current pool keep the connection open so we can fail back to
  7110. * it. */
  7111. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7112. return true;
  7113. if (pool_unworkable(cp))
  7114. return true;
  7115. /* We've run out of work, bring anything back to life. */
  7116. if (no_work)
  7117. return true;
  7118. return false;
  7119. }
  7120. static void wait_lpcurrent(struct pool *pool);
  7121. static void pool_resus(struct pool *pool);
  7122. static void gen_stratum_work(struct pool *pool, struct work *work);
  7123. static void stratum_resumed(struct pool *pool)
  7124. {
  7125. if (!pool->stratum_notify)
  7126. return;
  7127. if (pool_tclear(pool, &pool->idle)) {
  7128. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7129. pool_resus(pool);
  7130. }
  7131. }
  7132. static bool supports_resume(struct pool *pool)
  7133. {
  7134. bool ret;
  7135. cg_rlock(&pool->data_lock);
  7136. ret = (pool->sessionid != NULL);
  7137. cg_runlock(&pool->data_lock);
  7138. return ret;
  7139. }
  7140. /* One stratum thread per pool that has stratum waits on the socket checking
  7141. * for new messages and for the integrity of the socket connection. We reset
  7142. * the connection based on the integrity of the receive side only as the send
  7143. * side will eventually expire data it fails to send. */
  7144. static void *stratum_thread(void *userdata)
  7145. {
  7146. struct pool *pool = (struct pool *)userdata;
  7147. pthread_detach(pthread_self());
  7148. char threadname[20];
  7149. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7150. RenameThread(threadname);
  7151. srand(time(NULL) + (intptr_t)userdata);
  7152. while (42) {
  7153. struct timeval timeout;
  7154. int sel_ret;
  7155. fd_set rd;
  7156. char *s;
  7157. int sock;
  7158. if (unlikely(!pool->has_stratum))
  7159. break;
  7160. /* Check to see whether we need to maintain this connection
  7161. * indefinitely or just bring it up when we switch to this
  7162. * pool */
  7163. while (true)
  7164. {
  7165. sock = pool->sock;
  7166. if (sock == INVSOCK)
  7167. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  7168. pool->pool_no);
  7169. else
  7170. if (!sock_full(pool) && !cnx_needed(pool))
  7171. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  7172. pool->pool_no);
  7173. else
  7174. break;
  7175. suspend_stratum(pool);
  7176. clear_stratum_shares(pool);
  7177. clear_pool_work(pool);
  7178. wait_lpcurrent(pool);
  7179. if (!restart_stratum(pool)) {
  7180. pool_died(pool);
  7181. while (!restart_stratum(pool)) {
  7182. if (pool->removed)
  7183. goto out;
  7184. cgsleep_ms(30000);
  7185. }
  7186. }
  7187. }
  7188. FD_ZERO(&rd);
  7189. FD_SET(sock, &rd);
  7190. timeout.tv_sec = 120;
  7191. timeout.tv_usec = 0;
  7192. /* If we fail to receive any notify messages for 2 minutes we
  7193. * assume the connection has been dropped and treat this pool
  7194. * as dead */
  7195. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7196. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7197. s = NULL;
  7198. } else
  7199. s = recv_line(pool);
  7200. if (!s) {
  7201. if (!pool->has_stratum)
  7202. break;
  7203. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7204. pool->getfail_occasions++;
  7205. total_go++;
  7206. mutex_lock(&pool->stratum_lock);
  7207. pool->stratum_active = pool->stratum_notify = false;
  7208. pool->sock = INVSOCK;
  7209. mutex_unlock(&pool->stratum_lock);
  7210. /* If the socket to our stratum pool disconnects, all
  7211. * submissions need to be discarded or resent. */
  7212. if (!supports_resume(pool))
  7213. clear_stratum_shares(pool);
  7214. else
  7215. resubmit_stratum_shares(pool);
  7216. clear_pool_work(pool);
  7217. if (pool == current_pool())
  7218. restart_threads();
  7219. if (restart_stratum(pool))
  7220. continue;
  7221. shutdown_stratum(pool);
  7222. pool_died(pool);
  7223. break;
  7224. }
  7225. /* Check this pool hasn't died while being a backup pool and
  7226. * has not had its idle flag cleared */
  7227. stratum_resumed(pool);
  7228. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7229. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7230. free(s);
  7231. if (pool->swork.clean) {
  7232. struct work *work = make_work();
  7233. /* Generate a single work item to update the current
  7234. * block database */
  7235. pool->swork.clean = false;
  7236. gen_stratum_work(pool, work);
  7237. /* Try to extract block height from coinbase scriptSig */
  7238. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7239. unsigned char cb_height_sz;
  7240. cb_height_sz = bin_height[-1];
  7241. if (cb_height_sz == 3) {
  7242. // FIXME: The block number will overflow this by AD 2173
  7243. uint32_t block_id = ((uint32_t*)work->data)[1];
  7244. uint32_t height = 0;
  7245. memcpy(&height, bin_height, 3);
  7246. height = le32toh(height);
  7247. have_block_height(block_id, height);
  7248. }
  7249. ++pool->work_restart_id;
  7250. if (test_work_current(work)) {
  7251. /* Only accept a work update if this stratum
  7252. * connection is from the current pool */
  7253. if (pool == current_pool()) {
  7254. restart_threads();
  7255. applog(
  7256. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  7257. "Stratum from pool %d requested work update", pool->pool_no);
  7258. }
  7259. } else
  7260. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7261. free_work(work);
  7262. }
  7263. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7264. // More than 4 timmills past since requested transactions
  7265. timer_unset(&pool->swork.tv_transparency);
  7266. pool_set_opaque(pool, true);
  7267. }
  7268. }
  7269. out:
  7270. return NULL;
  7271. }
  7272. static void init_stratum_thread(struct pool *pool)
  7273. {
  7274. have_longpoll = true;
  7275. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7276. quit(1, "Failed to create stratum thread");
  7277. }
  7278. static void *longpoll_thread(void *userdata);
  7279. static bool stratum_works(struct pool *pool)
  7280. {
  7281. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7282. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7283. return false;
  7284. if (pool->stratum_active)
  7285. return true;
  7286. if (!initiate_stratum(pool))
  7287. return false;
  7288. return true;
  7289. }
  7290. static bool pool_active(struct pool *pool, bool pinging)
  7291. {
  7292. struct timeval tv_getwork, tv_getwork_reply;
  7293. bool ret = false;
  7294. json_t *val;
  7295. CURL *curl;
  7296. int rolltime;
  7297. char *rpc_req;
  7298. struct work *work;
  7299. enum pool_protocol proto;
  7300. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7301. /* This is the central point we activate stratum when we can */
  7302. curl = curl_easy_init();
  7303. if (unlikely(!curl)) {
  7304. applog(LOG_ERR, "CURL initialisation failed");
  7305. return false;
  7306. }
  7307. if (!(want_gbt || want_getwork))
  7308. goto nohttp;
  7309. work = make_work();
  7310. /* Probe for GBT support on first pass */
  7311. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7312. tryagain:
  7313. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7314. work->pool = pool;
  7315. if (!rpc_req)
  7316. goto out;
  7317. pool->probed = false;
  7318. cgtime(&tv_getwork);
  7319. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7320. true, false, &rolltime, pool, false);
  7321. cgtime(&tv_getwork_reply);
  7322. free(rpc_req);
  7323. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7324. * and if so, switch to that in preference to getwork if it works */
  7325. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  7326. if (!pool->has_stratum) {
  7327. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7328. if (!pool->rpc_url)
  7329. pool->rpc_url = strdup(pool->stratum_url);
  7330. pool->has_stratum = true;
  7331. }
  7332. free_work(work);
  7333. if (val)
  7334. json_decref(val);
  7335. retry_stratum:
  7336. curl_easy_cleanup(curl);
  7337. /* We create the stratum thread for each pool just after
  7338. * successful authorisation. Once the init flag has been set
  7339. * we never unset it and the stratum thread is responsible for
  7340. * setting/unsetting the active flag */
  7341. bool init = pool_tset(pool, &pool->stratum_init);
  7342. if (!init) {
  7343. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  7344. if (ret)
  7345. {
  7346. detect_algo = 2;
  7347. init_stratum_thread(pool);
  7348. }
  7349. else
  7350. pool_tclear(pool, &pool->stratum_init);
  7351. return ret;
  7352. }
  7353. return pool->stratum_active;
  7354. }
  7355. else if (pool->has_stratum)
  7356. shutdown_stratum(pool);
  7357. if (val) {
  7358. bool rc;
  7359. json_t *res;
  7360. res = json_object_get(val, "result");
  7361. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7362. goto badwork;
  7363. work->rolltime = rolltime;
  7364. rc = work_decode(pool, work, val);
  7365. if (rc) {
  7366. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7367. pool->pool_no, pool->rpc_url);
  7368. work->pool = pool;
  7369. copy_time(&work->tv_getwork, &tv_getwork);
  7370. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7371. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7372. calc_diff(work, 0);
  7373. update_last_work(work);
  7374. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7375. stage_work(work);
  7376. total_getworks++;
  7377. pool->getwork_requested++;
  7378. ret = true;
  7379. cgtime(&pool->tv_idle);
  7380. } else {
  7381. badwork:
  7382. json_decref(val);
  7383. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7384. pool->pool_no, pool->rpc_url);
  7385. pool->proto = proto = pool_protocol_fallback(proto);
  7386. if (PLP_NONE != proto)
  7387. goto tryagain;
  7388. free_work(work);
  7389. goto out;
  7390. }
  7391. json_decref(val);
  7392. if (proto != pool->proto) {
  7393. pool->proto = proto;
  7394. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7395. }
  7396. if (pool->lp_url)
  7397. goto out;
  7398. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7399. const struct blktmpl_longpoll_req *lp;
  7400. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  7401. // NOTE: work_decode takes care of lp id
  7402. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7403. if (!pool->lp_url)
  7404. {
  7405. ret = false;
  7406. goto out;
  7407. }
  7408. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7409. }
  7410. else
  7411. if (pool->hdr_path && want_getwork) {
  7412. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7413. if (!pool->lp_url)
  7414. {
  7415. ret = false;
  7416. goto out;
  7417. }
  7418. pool->lp_proto = PLP_GETWORK;
  7419. } else
  7420. pool->lp_url = NULL;
  7421. if (want_longpoll && !pool->lp_started) {
  7422. pool->lp_started = true;
  7423. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7424. quit(1, "Failed to create pool longpoll thread");
  7425. }
  7426. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7427. pool->proto = proto;
  7428. goto tryagain;
  7429. } else {
  7430. free_work(work);
  7431. nohttp:
  7432. /* If we failed to parse a getwork, this could be a stratum
  7433. * url without the prefix stratum+tcp:// so let's check it */
  7434. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  7435. pool->has_stratum = true;
  7436. goto retry_stratum;
  7437. }
  7438. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7439. pool->pool_no, pool->rpc_url);
  7440. if (!pinging)
  7441. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7442. }
  7443. out:
  7444. curl_easy_cleanup(curl);
  7445. return ret;
  7446. }
  7447. static void pool_resus(struct pool *pool)
  7448. {
  7449. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7450. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7451. else
  7452. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7453. }
  7454. static struct work *hash_pop(void)
  7455. {
  7456. struct work *work = NULL, *tmp;
  7457. int hc;
  7458. struct timespec ts;
  7459. retry:
  7460. mutex_lock(stgd_lock);
  7461. while (!HASH_COUNT(staged_work))
  7462. {
  7463. if (unlikely(staged_full))
  7464. {
  7465. if (likely(opt_queue < 10 + mining_threads))
  7466. {
  7467. ++opt_queue;
  7468. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7469. }
  7470. else
  7471. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7472. staged_full = false; // Let it fill up before triggering an underrun again
  7473. no_work = true;
  7474. }
  7475. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7476. pthread_cond_signal(&gws_cond);
  7477. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7478. {
  7479. run_cmd(cmd_idle);
  7480. pthread_cond_signal(&gws_cond);
  7481. pthread_cond_wait(&getq->cond, stgd_lock);
  7482. }
  7483. }
  7484. no_work = false;
  7485. hc = HASH_COUNT(staged_work);
  7486. /* Find clone work if possible, to allow masters to be reused */
  7487. if (hc > staged_rollable) {
  7488. HASH_ITER(hh, staged_work, work, tmp) {
  7489. if (!work_rollable(work))
  7490. break;
  7491. }
  7492. } else
  7493. work = staged_work;
  7494. if (can_roll(work) && should_roll(work))
  7495. {
  7496. // Instead of consuming it, force it to be cloned and grab the clone
  7497. mutex_unlock(stgd_lock);
  7498. clone_available();
  7499. goto retry;
  7500. }
  7501. HASH_DEL(staged_work, work);
  7502. if (work_rollable(work))
  7503. staged_rollable--;
  7504. /* Signal the getwork scheduler to look for more work */
  7505. pthread_cond_signal(&gws_cond);
  7506. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7507. pthread_cond_signal(&getq->cond);
  7508. mutex_unlock(stgd_lock);
  7509. work->pool->last_work_time = time(NULL);
  7510. cgtime(&work->pool->tv_last_work_time);
  7511. return work;
  7512. }
  7513. /* Clones work by rolling it if possible, and returning a clone instead of the
  7514. * original work item which gets staged again to possibly be rolled again in
  7515. * the future */
  7516. static struct work *clone_work(struct work *work)
  7517. {
  7518. int mrs = mining_threads + opt_queue - total_staged();
  7519. struct work *work_clone;
  7520. bool cloned;
  7521. if (mrs < 1)
  7522. return work;
  7523. cloned = false;
  7524. work_clone = make_clone(work);
  7525. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7526. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7527. stage_work(work_clone);
  7528. roll_work(work);
  7529. work_clone = make_clone(work);
  7530. /* Roll it again to prevent duplicates should this be used
  7531. * directly later on */
  7532. roll_work(work);
  7533. cloned = true;
  7534. }
  7535. if (cloned) {
  7536. stage_work(work);
  7537. return work_clone;
  7538. }
  7539. free_work(work_clone);
  7540. return work;
  7541. }
  7542. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7543. {
  7544. unsigned char hash1[32];
  7545. sha256(data, len, hash1);
  7546. sha256(hash1, 32, hash);
  7547. }
  7548. /* Diff 1 is a 256 bit unsigned integer of
  7549. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  7550. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  7551. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7552. static void bdiff_target_leadzero(unsigned char *target, double diff)
  7553. {
  7554. uint64_t *data64, h64;
  7555. double d64;
  7556. d64 = diffone;
  7557. d64 /= diff;
  7558. d64 = ceil(d64);
  7559. h64 = d64;
  7560. memset(target, 0, 32);
  7561. if (d64 < 18446744073709551616.0) {
  7562. unsigned char *rtarget = target;
  7563. memset(rtarget, 0, 32);
  7564. if (opt_scrypt)
  7565. data64 = (uint64_t *)(rtarget + 2);
  7566. else
  7567. data64 = (uint64_t *)(rtarget + 4);
  7568. *data64 = htobe64(h64);
  7569. } else {
  7570. /* Support for the classic all FFs just-below-1 diff */
  7571. if (opt_scrypt)
  7572. memset(&target[2], 0xff, 30);
  7573. else
  7574. memset(&target[4], 0xff, 28);
  7575. }
  7576. }
  7577. void set_target(unsigned char *dest_target, double diff)
  7578. {
  7579. unsigned char rtarget[32];
  7580. bdiff_target_leadzero(rtarget, diff);
  7581. swab256(dest_target, rtarget);
  7582. if (opt_debug) {
  7583. char htarget[65];
  7584. bin2hex(htarget, rtarget, 32);
  7585. applog(LOG_DEBUG, "Generated target %s", htarget);
  7586. }
  7587. }
  7588. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  7589. {
  7590. *dst = *src;
  7591. dst->job_id = strdup(src->job_id);
  7592. bytes_cpy(&dst->coinbase, &src->coinbase);
  7593. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  7594. }
  7595. void stratum_work_clean(struct stratum_work * const swork)
  7596. {
  7597. free(swork->job_id);
  7598. bytes_free(&swork->coinbase);
  7599. bytes_free(&swork->merkle_bin);
  7600. }
  7601. /* Generates stratum based work based on the most recent notify information
  7602. * from the pool. This will keep generating work while a pool is down so we use
  7603. * other means to detect when the pool has died in stratum_thread */
  7604. static void gen_stratum_work(struct pool *pool, struct work *work)
  7605. {
  7606. clean_work(work);
  7607. cg_wlock(&pool->data_lock);
  7608. pool->swork.data_lock_p = &pool->data_lock;
  7609. bytes_resize(&work->nonce2, pool->n2size);
  7610. if (pool->nonce2sz < pool->n2size)
  7611. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  7612. memcpy(bytes_buf(&work->nonce2),
  7613. #ifdef WORDS_BIGENDIAN
  7614. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  7615. &((char*)&pool->nonce2)[pool->nonce2off],
  7616. #else
  7617. &pool->nonce2,
  7618. #endif
  7619. pool->nonce2sz);
  7620. pool->nonce2++;
  7621. work->pool = pool;
  7622. work->work_restart_id = work->pool->work_restart_id;
  7623. gen_stratum_work2(work, &pool->swork, pool->nonce1);
  7624. cgtime(&work->tv_staged);
  7625. }
  7626. void gen_stratum_work2(struct work *work, struct stratum_work *swork, const char *nonce1)
  7627. {
  7628. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  7629. uint8_t *merkle_bin;
  7630. uint32_t *data32, *swap32;
  7631. int i;
  7632. /* Generate coinbase */
  7633. coinbase = bytes_buf(&swork->coinbase);
  7634. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7635. /* Downgrade to a read lock to read off the variables */
  7636. if (swork->data_lock_p)
  7637. cg_dwlock(swork->data_lock_p);
  7638. /* Generate merkle root */
  7639. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  7640. memcpy(merkle_sha, merkle_root, 32);
  7641. merkle_bin = bytes_buf(&swork->merkle_bin);
  7642. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  7643. memcpy(merkle_sha + 32, merkle_bin, 32);
  7644. gen_hash(merkle_sha, merkle_root, 64);
  7645. memcpy(merkle_sha, merkle_root, 32);
  7646. }
  7647. data32 = (uint32_t *)merkle_sha;
  7648. swap32 = (uint32_t *)merkle_root;
  7649. flip32(swap32, data32);
  7650. memcpy(&work->data[0], swork->header1, 36);
  7651. memcpy(&work->data[36], merkle_root, 32);
  7652. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  7653. memcpy(&work->data[72], swork->diffbits, 4);
  7654. memset(&work->data[76], 0, 4); // nonce
  7655. memcpy(&work->data[80], workpadding_bin, 48);
  7656. /* Store the stratum work diff to check it still matches the pool's
  7657. * stratum diff when submitting shares */
  7658. work->sdiff = swork->diff;
  7659. /* Copy parameters required for share submission */
  7660. work->job_id = strdup(swork->job_id);
  7661. work->nonce1 = strdup(nonce1);
  7662. if (swork->data_lock_p)
  7663. cg_runlock(swork->data_lock_p);
  7664. if (opt_debug)
  7665. {
  7666. char header[161];
  7667. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  7668. bin2hex(header, work->data, 80);
  7669. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7670. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7671. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  7672. }
  7673. calc_midstate(work);
  7674. set_target(work->target, work->sdiff);
  7675. local_work++;
  7676. work->stratum = true;
  7677. work->blk.nonce = 0;
  7678. work->id = total_work++;
  7679. work->longpoll = false;
  7680. work->getwork_mode = GETWORK_MODE_STRATUM;
  7681. /* Nominally allow a driver to ntime roll 60 seconds */
  7682. work->drv_rolllimit = 60;
  7683. calc_diff(work, 0);
  7684. }
  7685. void request_work(struct thr_info *thr)
  7686. {
  7687. struct cgpu_info *cgpu = thr->cgpu;
  7688. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7689. /* Tell the watchdog thread this thread is waiting on getwork and
  7690. * should not be restarted */
  7691. thread_reportout(thr);
  7692. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  7693. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7694. {
  7695. if (proc->threads)
  7696. break;
  7697. thread_reportout(proc->thr[0]);
  7698. }
  7699. cgtime(&dev_stats->_get_start);
  7700. }
  7701. // FIXME: Make this non-blocking (and remove HACK above)
  7702. struct work *get_work(struct thr_info *thr)
  7703. {
  7704. const int thr_id = thr->id;
  7705. struct cgpu_info *cgpu = thr->cgpu;
  7706. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7707. struct cgminer_stats *pool_stats;
  7708. struct timeval tv_get;
  7709. struct work *work = NULL;
  7710. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  7711. while (!work) {
  7712. work = hash_pop();
  7713. if (stale_work(work, false)) {
  7714. staged_full = false; // It wasn't really full, since it was stale :(
  7715. discard_work(work);
  7716. work = NULL;
  7717. wake_gws();
  7718. }
  7719. }
  7720. last_getwork = time(NULL);
  7721. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  7722. cgpu->proc_repr, work->id, thr_id);
  7723. work->thr_id = thr_id;
  7724. thread_reportin(thr);
  7725. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  7726. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7727. {
  7728. if (proc->threads)
  7729. break;
  7730. thread_reportin(proc->thr[0]);
  7731. }
  7732. work->mined = true;
  7733. work->blk.nonce = 0;
  7734. cgtime(&tv_get);
  7735. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  7736. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  7737. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  7738. dev_stats->getwork_wait_max = tv_get;
  7739. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  7740. dev_stats->getwork_wait_min = tv_get;
  7741. ++dev_stats->getwork_calls;
  7742. pool_stats = &(work->pool->cgminer_stats);
  7743. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  7744. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  7745. pool_stats->getwork_wait_max = tv_get;
  7746. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  7747. pool_stats->getwork_wait_min = tv_get;
  7748. ++pool_stats->getwork_calls;
  7749. if (work->work_difficulty < 1)
  7750. {
  7751. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  7752. {
  7753. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  7754. cgpu->proc_repr);
  7755. work->nonce_diff = cgpu->min_nonce_diff;
  7756. }
  7757. else
  7758. work->nonce_diff = work->work_difficulty;
  7759. }
  7760. else
  7761. work->nonce_diff = 1;
  7762. return work;
  7763. }
  7764. static
  7765. void _submit_work_async(struct work *work)
  7766. {
  7767. applog(LOG_DEBUG, "Pushing submit work to work thread");
  7768. mutex_lock(&submitting_lock);
  7769. ++total_submitting;
  7770. DL_APPEND(submit_waiting, work);
  7771. mutex_unlock(&submitting_lock);
  7772. notifier_wake(submit_waiting_notifier);
  7773. }
  7774. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  7775. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  7776. {
  7777. if (tv_work_found)
  7778. copy_time(&work->tv_work_found, tv_work_found);
  7779. _submit_work_async(work);
  7780. }
  7781. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  7782. {
  7783. struct cgpu_info * const cgpu = thr->cgpu;
  7784. if (bad_nonce_p)
  7785. {
  7786. if (bad_nonce_p == UNKNOWN_NONCE)
  7787. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  7788. cgpu->proc_repr);
  7789. else
  7790. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  7791. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  7792. }
  7793. mutex_lock(&stats_lock);
  7794. hw_errors++;
  7795. ++cgpu->hw_errors;
  7796. if (bad_nonce_p)
  7797. {
  7798. total_bad_diff1 += nonce_diff;
  7799. cgpu->bad_diff1 += nonce_diff;
  7800. }
  7801. mutex_unlock(&stats_lock);
  7802. if (thr->cgpu->drv->hw_error)
  7803. thr->cgpu->drv->hw_error(thr);
  7804. }
  7805. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  7806. {
  7807. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  7808. hash_data(work->hash, work->data);
  7809. if (hash2_32[7] != 0)
  7810. return TNR_BAD;
  7811. if (!checktarget)
  7812. return TNR_GOOD;
  7813. if (!hash_target_check_v(work->hash, work->target))
  7814. return TNR_HIGH;
  7815. return TNR_GOOD;
  7816. }
  7817. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  7818. {
  7819. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7820. *work_nonce = htole32(nonce);
  7821. #ifdef USE_SCRYPT
  7822. if (opt_scrypt)
  7823. // NOTE: Depends on scrypt_test return matching enum values
  7824. return scrypt_test(work->data, work->target, nonce);
  7825. #endif
  7826. return hashtest2(work, checktarget);
  7827. }
  7828. /* Returns true if nonce for work was a valid share */
  7829. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  7830. {
  7831. return submit_noffset_nonce(thr, work, nonce, 0);
  7832. }
  7833. /* Allows drivers to submit work items where the driver has changed the ntime
  7834. * value by noffset. Must be only used with a work protocol that does not ntime
  7835. * roll itself intrinsically to generate work (eg stratum). We do not touch
  7836. * the original work struct, but the copy of it only. */
  7837. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  7838. int noffset)
  7839. {
  7840. struct work *work = make_work();
  7841. _copy_work(work, work_in, noffset);
  7842. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7843. struct timeval tv_work_found;
  7844. enum test_nonce2_result res;
  7845. bool ret = true;
  7846. thread_reportout(thr);
  7847. cgtime(&tv_work_found);
  7848. *work_nonce = htole32(nonce);
  7849. work->thr_id = thr->id;
  7850. /* Do one last check before attempting to submit the work */
  7851. /* Side effect: sets work->data for us */
  7852. res = test_nonce2(work, nonce);
  7853. if (unlikely(res == TNR_BAD))
  7854. {
  7855. inc_hw_errors(thr, work, nonce);
  7856. ret = false;
  7857. goto out;
  7858. }
  7859. mutex_lock(&stats_lock);
  7860. total_diff1 += work->nonce_diff;
  7861. thr ->cgpu->diff1 += work->nonce_diff;
  7862. work->pool->diff1 += work->nonce_diff;
  7863. thr->cgpu->last_device_valid_work = time(NULL);
  7864. mutex_unlock(&stats_lock);
  7865. if (noncelog_file)
  7866. noncelog(work);
  7867. if (res == TNR_HIGH)
  7868. {
  7869. // Share above target, normal
  7870. /* Check the diff of the share, even if it didn't reach the
  7871. * target, just to set the best share value if it's higher. */
  7872. share_diff(work);
  7873. goto out;
  7874. }
  7875. submit_work_async2(work, &tv_work_found);
  7876. work = NULL; // Taken by submit_work_async2
  7877. out:
  7878. if (work)
  7879. free_work(work);
  7880. thread_reportin(thr);
  7881. return ret;
  7882. }
  7883. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  7884. {
  7885. if (wdiff->tv_sec > opt_scantime ||
  7886. work->blk.nonce >= 0xfffffffe - hashes ||
  7887. hashes >= 0xfffffffe ||
  7888. stale_work(work, false))
  7889. return true;
  7890. return false;
  7891. }
  7892. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  7893. {
  7894. struct cgpu_info *proc = thr->cgpu;
  7895. if (proc->threads > 1)
  7896. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  7897. else
  7898. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  7899. }
  7900. // Called by asynchronous minerloops, when they find their processor should be disabled
  7901. void mt_disable_start(struct thr_info *mythr)
  7902. {
  7903. struct cgpu_info *cgpu = mythr->cgpu;
  7904. struct device_drv *drv = cgpu->drv;
  7905. if (drv->thread_disable)
  7906. drv->thread_disable(mythr);
  7907. hashmeter2(mythr);
  7908. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  7909. mythr->rolling = mythr->cgpu->rolling = 0;
  7910. thread_reportout(mythr);
  7911. mythr->_mt_disable_called = true;
  7912. }
  7913. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  7914. * the driver tells us it's full so that it may extract the work item using
  7915. * the get_queued() function which adds it to the hashtable on
  7916. * cgpu->queued_work. */
  7917. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  7918. {
  7919. thread_reportout(mythr);
  7920. do {
  7921. bool need_work;
  7922. /* Do this lockless just to know if we need more unqueued work. */
  7923. need_work = (!cgpu->unqueued_work);
  7924. /* get_work is a blocking function so do it outside of lock
  7925. * to prevent deadlocks with other locks. */
  7926. if (need_work) {
  7927. struct work *work = get_work(mythr);
  7928. wr_lock(&cgpu->qlock);
  7929. /* Check we haven't grabbed work somehow between
  7930. * checking and picking up the lock. */
  7931. if (likely(!cgpu->unqueued_work))
  7932. cgpu->unqueued_work = work;
  7933. else
  7934. need_work = false;
  7935. wr_unlock(&cgpu->qlock);
  7936. if (unlikely(!need_work))
  7937. discard_work(work);
  7938. }
  7939. /* The queue_full function should be used by the driver to
  7940. * actually place work items on the physical device if it
  7941. * does have a queue. */
  7942. } while (drv->queue_full && !drv->queue_full(cgpu));
  7943. }
  7944. /* Add a work item to a cgpu's queued hashlist */
  7945. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  7946. {
  7947. cgpu->queued_count++;
  7948. HASH_ADD_INT(cgpu->queued_work, id, work);
  7949. }
  7950. /* This function is for retrieving one work item from the unqueued pointer and
  7951. * adding it to the hashtable of queued work. Code using this function must be
  7952. * able to handle NULL as a return which implies there is no work available. */
  7953. struct work *get_queued(struct cgpu_info *cgpu)
  7954. {
  7955. struct work *work = NULL;
  7956. wr_lock(&cgpu->qlock);
  7957. if (cgpu->unqueued_work) {
  7958. work = cgpu->unqueued_work;
  7959. __add_queued(cgpu, work);
  7960. cgpu->unqueued_work = NULL;
  7961. }
  7962. wr_unlock(&cgpu->qlock);
  7963. return work;
  7964. }
  7965. void add_queued(struct cgpu_info *cgpu, struct work *work)
  7966. {
  7967. wr_lock(&cgpu->qlock);
  7968. __add_queued(cgpu, work);
  7969. wr_unlock(&cgpu->qlock);
  7970. }
  7971. /* Get fresh work and add it to cgpu's queued hashlist */
  7972. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  7973. {
  7974. struct work *work = get_work(thr);
  7975. add_queued(cgpu, work);
  7976. return work;
  7977. }
  7978. /* This function is for finding an already queued work item in the
  7979. * given que hashtable. Code using this function must be able
  7980. * to handle NULL as a return which implies there is no matching work.
  7981. * The calling function must lock access to the que if it is required.
  7982. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7983. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7984. {
  7985. struct work *work, *tmp, *ret = NULL;
  7986. HASH_ITER(hh, que, work, tmp) {
  7987. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  7988. memcmp(work->data + offset, data, datalen) == 0) {
  7989. ret = work;
  7990. break;
  7991. }
  7992. }
  7993. return ret;
  7994. }
  7995. /* This function is for finding an already queued work item in the
  7996. * device's queued_work hashtable. Code using this function must be able
  7997. * to handle NULL as a return which implies there is no matching work.
  7998. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7999. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8000. {
  8001. struct work *ret;
  8002. rd_lock(&cgpu->qlock);
  8003. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8004. rd_unlock(&cgpu->qlock);
  8005. return ret;
  8006. }
  8007. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8008. {
  8009. struct work *work, *ret = NULL;
  8010. rd_lock(&cgpu->qlock);
  8011. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8012. if (work)
  8013. ret = copy_work(work);
  8014. rd_unlock(&cgpu->qlock);
  8015. return ret;
  8016. }
  8017. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8018. {
  8019. cgpu->queued_count--;
  8020. HASH_DEL(cgpu->queued_work, work);
  8021. }
  8022. /* This function should be used by queued device drivers when they're sure
  8023. * the work struct is no longer in use. */
  8024. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8025. {
  8026. wr_lock(&cgpu->qlock);
  8027. __work_completed(cgpu, work);
  8028. wr_unlock(&cgpu->qlock);
  8029. free_work(work);
  8030. }
  8031. /* Combines find_queued_work_bymidstate and work_completed in one function
  8032. * withOUT destroying the work so the driver must free it. */
  8033. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8034. {
  8035. struct work *work;
  8036. wr_lock(&cgpu->qlock);
  8037. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8038. if (work)
  8039. __work_completed(cgpu, work);
  8040. wr_unlock(&cgpu->qlock);
  8041. return work;
  8042. }
  8043. static void flush_queue(struct cgpu_info *cgpu)
  8044. {
  8045. struct work *work = NULL;
  8046. wr_lock(&cgpu->qlock);
  8047. work = cgpu->unqueued_work;
  8048. cgpu->unqueued_work = NULL;
  8049. wr_unlock(&cgpu->qlock);
  8050. if (work) {
  8051. free_work(work);
  8052. applog(LOG_DEBUG, "Discarded queued work item");
  8053. }
  8054. }
  8055. /* This version of hash work is for devices that are fast enough to always
  8056. * perform a full nonce range and need a queue to maintain the device busy.
  8057. * Work creation and destruction is not done from within this function
  8058. * directly. */
  8059. void hash_queued_work(struct thr_info *mythr)
  8060. {
  8061. const long cycle = opt_log_interval / 5 ? : 1;
  8062. struct timeval tv_start = {0, 0}, tv_end;
  8063. struct cgpu_info *cgpu = mythr->cgpu;
  8064. struct device_drv *drv = cgpu->drv;
  8065. const int thr_id = mythr->id;
  8066. int64_t hashes_done = 0;
  8067. if (unlikely(cgpu->deven != DEV_ENABLED))
  8068. mt_disable(mythr);
  8069. while (likely(!cgpu->shutdown)) {
  8070. struct timeval diff;
  8071. int64_t hashes;
  8072. fill_queue(mythr, cgpu, drv, thr_id);
  8073. thread_reportin(mythr);
  8074. hashes = drv->scanwork(mythr);
  8075. /* Reset the bool here in case the driver looks for it
  8076. * synchronously in the scanwork loop. */
  8077. mythr->work_restart = false;
  8078. if (unlikely(hashes == -1 )) {
  8079. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8080. cgpu->deven = DEV_DISABLED;
  8081. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8082. mt_disable(mythr);
  8083. }
  8084. hashes_done += hashes;
  8085. cgtime(&tv_end);
  8086. timersub(&tv_end, &tv_start, &diff);
  8087. if (diff.tv_sec >= cycle) {
  8088. hashmeter(thr_id, &diff, hashes_done);
  8089. hashes_done = 0;
  8090. copy_time(&tv_start, &tv_end);
  8091. }
  8092. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8093. mt_disable(mythr);
  8094. if (unlikely(mythr->work_restart)) {
  8095. flush_queue(cgpu);
  8096. if (drv->flush_work)
  8097. drv->flush_work(cgpu);
  8098. }
  8099. }
  8100. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8101. }
  8102. // Called by minerloop, when it is re-enabling a processor
  8103. void mt_disable_finish(struct thr_info *mythr)
  8104. {
  8105. struct device_drv *drv = mythr->cgpu->drv;
  8106. thread_reportin(mythr);
  8107. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8108. if (drv->thread_enable)
  8109. drv->thread_enable(mythr);
  8110. mythr->_mt_disable_called = false;
  8111. }
  8112. // Called by synchronous minerloops, when they find their processor should be disabled
  8113. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8114. void mt_disable(struct thr_info *mythr)
  8115. {
  8116. const struct cgpu_info * const cgpu = mythr->cgpu;
  8117. mt_disable_start(mythr);
  8118. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8119. do {
  8120. notifier_read(mythr->notifier);
  8121. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8122. mt_disable_finish(mythr);
  8123. }
  8124. enum {
  8125. STAT_SLEEP_INTERVAL = 1,
  8126. STAT_CTR_INTERVAL = 10000000,
  8127. FAILURE_INTERVAL = 30,
  8128. };
  8129. /* Stage another work item from the work returned in a longpoll */
  8130. 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)
  8131. {
  8132. bool rc;
  8133. work->rolltime = rolltime;
  8134. rc = work_decode(pool, work, val);
  8135. if (unlikely(!rc)) {
  8136. applog(LOG_ERR, "Could not convert longpoll data to work");
  8137. free_work(work);
  8138. return;
  8139. }
  8140. total_getworks++;
  8141. pool->getwork_requested++;
  8142. work->pool = pool;
  8143. copy_time(&work->tv_getwork, tv_lp);
  8144. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8145. calc_diff(work, 0);
  8146. if (pool->enabled == POOL_REJECTING)
  8147. work->mandatory = true;
  8148. work->longpoll = true;
  8149. work->getwork_mode = GETWORK_MODE_LP;
  8150. update_last_work(work);
  8151. /* We'll be checking this work item twice, but we already know it's
  8152. * from a new block so explicitly force the new block detection now
  8153. * rather than waiting for it to hit the stage thread. This also
  8154. * allows testwork to know whether LP discovered the block or not. */
  8155. test_work_current(work);
  8156. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8157. * the longpoll work from a pool that has been rejecting shares as a
  8158. * way to detect when the pool has recovered.
  8159. */
  8160. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8161. free_work(work);
  8162. return;
  8163. }
  8164. work = clone_work(work);
  8165. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8166. stage_work(work);
  8167. applog(LOG_DEBUG, "Converted longpoll data to work");
  8168. }
  8169. /* If we want longpoll, enable it for the chosen default pool, or, if
  8170. * the pool does not support longpoll, find the first one that does
  8171. * and use its longpoll support */
  8172. static struct pool *select_longpoll_pool(struct pool *cp)
  8173. {
  8174. int i;
  8175. if (cp->lp_url)
  8176. return cp;
  8177. for (i = 0; i < total_pools; i++) {
  8178. struct pool *pool = pools[i];
  8179. if (pool->has_stratum || pool->lp_url)
  8180. return pool;
  8181. }
  8182. return NULL;
  8183. }
  8184. /* This will make the longpoll thread wait till it's the current pool, or it
  8185. * has been flagged as rejecting, before attempting to open any connections.
  8186. */
  8187. static void wait_lpcurrent(struct pool *pool)
  8188. {
  8189. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  8190. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  8191. pool_strategy != POOL_BALANCE))) {
  8192. mutex_lock(&lp_lock);
  8193. pthread_cond_wait(&lp_cond, &lp_lock);
  8194. mutex_unlock(&lp_lock);
  8195. }
  8196. }
  8197. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8198. struct pool *pool = vpool;
  8199. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  8200. pool->lp_socket = sock;
  8201. return sock;
  8202. }
  8203. static void *longpoll_thread(void *userdata)
  8204. {
  8205. struct pool *cp = (struct pool *)userdata;
  8206. /* This *pool is the source of the actual longpoll, not the pool we've
  8207. * tied it to */
  8208. struct timeval start, reply, end;
  8209. struct pool *pool = NULL;
  8210. char threadname[20];
  8211. CURL *curl = NULL;
  8212. int failures = 0;
  8213. char *lp_url;
  8214. int rolltime;
  8215. #ifndef HAVE_PTHREAD_CANCEL
  8216. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8217. #endif
  8218. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8219. RenameThread(threadname);
  8220. curl = curl_easy_init();
  8221. if (unlikely(!curl)) {
  8222. applog(LOG_ERR, "CURL initialisation failed");
  8223. return NULL;
  8224. }
  8225. retry_pool:
  8226. pool = select_longpoll_pool(cp);
  8227. if (!pool) {
  8228. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8229. while (!pool) {
  8230. cgsleep_ms(60000);
  8231. pool = select_longpoll_pool(cp);
  8232. }
  8233. }
  8234. if (pool->has_stratum) {
  8235. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8236. cp->rpc_url, pool->rpc_url);
  8237. goto out;
  8238. }
  8239. /* Any longpoll from any pool is enough for this to be true */
  8240. have_longpoll = true;
  8241. wait_lpcurrent(cp);
  8242. {
  8243. lp_url = pool->lp_url;
  8244. if (cp == pool)
  8245. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8246. else
  8247. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8248. }
  8249. while (42) {
  8250. json_t *val, *soval;
  8251. struct work *work = make_work();
  8252. char *lpreq;
  8253. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  8254. work->pool = pool;
  8255. if (!lpreq)
  8256. {
  8257. free_work(work);
  8258. goto lpfail;
  8259. }
  8260. wait_lpcurrent(cp);
  8261. cgtime(&start);
  8262. /* Longpoll connections can be persistent for a very long time
  8263. * and any number of issues could have come up in the meantime
  8264. * so always establish a fresh connection instead of relying on
  8265. * a persistent one. */
  8266. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8267. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  8268. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  8269. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8270. lpreq, false, true, &rolltime, pool, false);
  8271. pool->lp_socket = CURL_SOCKET_BAD;
  8272. cgtime(&reply);
  8273. free(lpreq);
  8274. if (likely(val)) {
  8275. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8276. if (soval)
  8277. pool->submit_old = json_is_true(soval);
  8278. else
  8279. pool->submit_old = false;
  8280. convert_to_work(val, rolltime, pool, work, &start, &reply);
  8281. failures = 0;
  8282. json_decref(val);
  8283. } else {
  8284. /* Some pools regularly drop the longpoll request so
  8285. * only see this as longpoll failure if it happens
  8286. * immediately and just restart it the rest of the
  8287. * time. */
  8288. cgtime(&end);
  8289. free_work(work);
  8290. if (end.tv_sec - start.tv_sec > 30)
  8291. continue;
  8292. if (failures == 1)
  8293. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8294. lpfail:
  8295. cgsleep_ms(30000);
  8296. }
  8297. if (pool != cp) {
  8298. pool = select_longpoll_pool(cp);
  8299. if (pool->has_stratum) {
  8300. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8301. cp->rpc_url, pool->rpc_url);
  8302. break;
  8303. }
  8304. if (unlikely(!pool))
  8305. goto retry_pool;
  8306. }
  8307. if (unlikely(pool->removed))
  8308. break;
  8309. }
  8310. out:
  8311. curl_easy_cleanup(curl);
  8312. return NULL;
  8313. }
  8314. static void stop_longpoll(void)
  8315. {
  8316. int i;
  8317. want_longpoll = false;
  8318. for (i = 0; i < total_pools; ++i)
  8319. {
  8320. struct pool *pool = pools[i];
  8321. if (unlikely(!pool->lp_started))
  8322. continue;
  8323. pool->lp_started = false;
  8324. pthread_cancel(pool->longpoll_thread);
  8325. }
  8326. have_longpoll = false;
  8327. }
  8328. static void start_longpoll(void)
  8329. {
  8330. int i;
  8331. want_longpoll = true;
  8332. for (i = 0; i < total_pools; ++i)
  8333. {
  8334. struct pool *pool = pools[i];
  8335. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  8336. continue;
  8337. pool->lp_started = true;
  8338. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8339. quit(1, "Failed to create pool longpoll thread");
  8340. }
  8341. }
  8342. void reinit_device(struct cgpu_info *cgpu)
  8343. {
  8344. if (cgpu->drv->reinit_device)
  8345. cgpu->drv->reinit_device(cgpu);
  8346. }
  8347. static struct timeval rotate_tv;
  8348. /* We reap curls if they are unused for over a minute */
  8349. static void reap_curl(struct pool *pool)
  8350. {
  8351. struct curl_ent *ent, *iter;
  8352. struct timeval now;
  8353. int reaped = 0;
  8354. cgtime(&now);
  8355. mutex_lock(&pool->pool_lock);
  8356. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  8357. if (pool->curls < 2)
  8358. break;
  8359. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8360. reaped++;
  8361. pool->curls--;
  8362. LL_DELETE(pool->curllist, ent);
  8363. curl_easy_cleanup(ent->curl);
  8364. free(ent);
  8365. }
  8366. }
  8367. mutex_unlock(&pool->pool_lock);
  8368. if (reaped)
  8369. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8370. }
  8371. static void *watchpool_thread(void __maybe_unused *userdata)
  8372. {
  8373. int intervals = 0;
  8374. #ifndef HAVE_PTHREAD_CANCEL
  8375. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8376. #endif
  8377. RenameThread("watchpool");
  8378. while (42) {
  8379. struct timeval now;
  8380. int i;
  8381. if (++intervals > 20)
  8382. intervals = 0;
  8383. cgtime(&now);
  8384. for (i = 0; i < total_pools; i++) {
  8385. struct pool *pool = pools[i];
  8386. if (!opt_benchmark)
  8387. reap_curl(pool);
  8388. /* Get a rolling utility per pool over 10 mins */
  8389. if (intervals > 19) {
  8390. int shares = pool->diff1 - pool->last_shares;
  8391. pool->last_shares = pool->diff1;
  8392. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  8393. pool->shares = pool->utility;
  8394. }
  8395. if (pool->enabled == POOL_DISABLED)
  8396. continue;
  8397. /* Don't start testing any pools if the test threads
  8398. * from startup are still doing their first attempt. */
  8399. if (unlikely(pool->testing)) {
  8400. pthread_join(pool->test_thread, NULL);
  8401. }
  8402. /* Test pool is idle once every minute */
  8403. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  8404. cgtime(&pool->tv_idle);
  8405. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  8406. pool_resus(pool);
  8407. }
  8408. /* Only switch pools if the failback pool has been
  8409. * alive for more than 5 minutes to prevent
  8410. * intermittently failing pools from being used. */
  8411. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8412. now.tv_sec - pool->tv_idle.tv_sec > 300) {
  8413. applog(LOG_WARNING, "Pool %d %s stable for 5 mins",
  8414. pool->pool_no, pool->rpc_url);
  8415. switch_pools(NULL);
  8416. }
  8417. }
  8418. if (current_pool()->idle)
  8419. switch_pools(NULL);
  8420. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8421. cgtime(&rotate_tv);
  8422. switch_pools(NULL);
  8423. }
  8424. cgsleep_ms(30000);
  8425. }
  8426. return NULL;
  8427. }
  8428. void mt_enable(struct thr_info *thr)
  8429. {
  8430. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  8431. notifier_wake(thr->notifier);
  8432. }
  8433. void proc_enable(struct cgpu_info *cgpu)
  8434. {
  8435. int j;
  8436. cgpu->deven = DEV_ENABLED;
  8437. for (j = cgpu->threads ?: 1; j--; )
  8438. mt_enable(cgpu->thr[j]);
  8439. }
  8440. #define device_recovered(cgpu) proc_enable(cgpu)
  8441. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  8442. {
  8443. struct string_elist *setstr_elist;
  8444. const char *p, *p2;
  8445. char replybuf[0x2000];
  8446. size_t L;
  8447. DL_FOREACH(opt_set_device_list, setstr_elist)
  8448. {
  8449. const char * const setstr = setstr_elist->string;
  8450. p = strchr(setstr, ':');
  8451. if (!p)
  8452. p = setstr;
  8453. {
  8454. L = p - setstr;
  8455. char pattern[L + 1];
  8456. if (L)
  8457. memcpy(pattern, setstr, L);
  8458. pattern[L] = '\0';
  8459. if (!cgpu_match(pattern, cgpu))
  8460. continue;
  8461. }
  8462. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  8463. cgpu->proc_repr, __func__, setstr);
  8464. if (p[0] == ':')
  8465. ++p;
  8466. p2 = strchr(p, '=');
  8467. if (!p2)
  8468. {
  8469. L = strlen(p);
  8470. p2 = "";
  8471. }
  8472. else
  8473. {
  8474. L = p2 - p;
  8475. ++p2;
  8476. }
  8477. char opt[L + 1];
  8478. if (L)
  8479. memcpy(opt, p, L);
  8480. opt[L] = '\0';
  8481. L = strlen(p2);
  8482. char setval[L + 1];
  8483. if (L)
  8484. memcpy(setval, p2, L);
  8485. setval[L] = '\0';
  8486. enum bfg_set_device_replytype success;
  8487. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  8488. switch (success)
  8489. {
  8490. case SDR_OK:
  8491. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  8492. cgpu->proc_repr, setstr,
  8493. p ? ": " : "", p ?: "");
  8494. break;
  8495. case SDR_ERR:
  8496. case SDR_HELP:
  8497. case SDR_UNKNOWN:
  8498. applog(LOG_WARNING, "%"PRIpreprv": Applying rule %s: %s",
  8499. cgpu->proc_repr, setstr, p);
  8500. break;
  8501. case SDR_AUTO:
  8502. case SDR_NOSUPP:
  8503. applog(LOG_WARNING, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  8504. cgpu->proc_repr, setstr);
  8505. }
  8506. }
  8507. cgpu->already_set_defaults = true;
  8508. }
  8509. 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)
  8510. {
  8511. struct device_drv dummy_drv = *drv;
  8512. struct cgpu_info dummy_cgpu = {
  8513. .drv = &dummy_drv,
  8514. .device = &dummy_cgpu,
  8515. .device_id = -1,
  8516. .proc_id = -1,
  8517. .device_data = userp,
  8518. .device_path = devpath,
  8519. .dev_serial = serial,
  8520. };
  8521. strcpy(dummy_cgpu.proc_repr, drv->name);
  8522. switch (mode)
  8523. {
  8524. case 0:
  8525. dummy_drv.set_device = datap;
  8526. break;
  8527. case 1:
  8528. dummy_drv.set_device = NULL;
  8529. dummy_cgpu.set_device_funcs = datap;
  8530. break;
  8531. }
  8532. cgpu_set_defaults(&dummy_cgpu);
  8533. }
  8534. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  8535. * the screen at regular intervals, and restarts threads if they appear to have
  8536. * died. */
  8537. #define WATCHDOG_SICK_TIME 60
  8538. #define WATCHDOG_DEAD_TIME 600
  8539. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  8540. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  8541. static void *watchdog_thread(void __maybe_unused *userdata)
  8542. {
  8543. const unsigned int interval = WATCHDOG_INTERVAL;
  8544. struct timeval zero_tv;
  8545. #ifndef HAVE_PTHREAD_CANCEL
  8546. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8547. #endif
  8548. RenameThread("watchdog");
  8549. memset(&zero_tv, 0, sizeof(struct timeval));
  8550. cgtime(&rotate_tv);
  8551. while (1) {
  8552. int i;
  8553. struct timeval now;
  8554. sleep(interval);
  8555. discard_stale();
  8556. hashmeter(-1, &zero_tv, 0);
  8557. #ifdef HAVE_CURSES
  8558. const int ts = total_staged();
  8559. if (curses_active_locked()) {
  8560. change_logwinsize();
  8561. curses_print_status(ts);
  8562. _refresh_devstatus(true);
  8563. touchwin(logwin);
  8564. wrefresh(logwin);
  8565. unlock_curses();
  8566. }
  8567. #endif
  8568. cgtime(&now);
  8569. if (!sched_paused && !should_run()) {
  8570. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  8571. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8572. if (!schedstart.enable) {
  8573. quit(0, "Terminating execution as planned");
  8574. break;
  8575. }
  8576. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  8577. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8578. sched_paused = true;
  8579. rd_lock(&mining_thr_lock);
  8580. for (i = 0; i < mining_threads; i++)
  8581. mining_thr[i]->pause = true;
  8582. rd_unlock(&mining_thr_lock);
  8583. } else if (sched_paused && should_run()) {
  8584. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  8585. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8586. if (schedstop.enable)
  8587. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  8588. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8589. sched_paused = false;
  8590. for (i = 0; i < mining_threads; i++) {
  8591. struct thr_info *thr;
  8592. thr = get_thread(i);
  8593. thr->pause = false;
  8594. }
  8595. for (i = 0; i < total_devices; ++i)
  8596. {
  8597. struct cgpu_info *cgpu = get_devices(i);
  8598. /* Don't touch disabled devices */
  8599. if (cgpu->deven == DEV_DISABLED)
  8600. continue;
  8601. proc_enable(cgpu);
  8602. }
  8603. }
  8604. for (i = 0; i < total_devices; ++i) {
  8605. struct cgpu_info *cgpu = get_devices(i);
  8606. if (!cgpu->disable_watchdog)
  8607. bfg_watchdog(cgpu, &now);
  8608. }
  8609. }
  8610. return NULL;
  8611. }
  8612. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  8613. {
  8614. struct thr_info *thr = cgpu->thr[0];
  8615. enum dev_enable *denable;
  8616. char *dev_str = cgpu->proc_repr;
  8617. if (likely(drv_ready(cgpu)))
  8618. {
  8619. if (unlikely(!cgpu->already_set_defaults))
  8620. cgpu_set_defaults(cgpu);
  8621. if (cgpu->drv->get_stats)
  8622. cgpu->drv->get_stats(cgpu);
  8623. }
  8624. denable = &cgpu->deven;
  8625. if (cgpu->drv->watchdog)
  8626. cgpu->drv->watchdog(cgpu, tvp_now);
  8627. /* Thread is disabled */
  8628. if (*denable == DEV_DISABLED)
  8629. return;
  8630. else
  8631. if (*denable == DEV_RECOVER_ERR) {
  8632. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  8633. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  8634. dev_str);
  8635. if (cgpu->reinit_backoff < 300)
  8636. cgpu->reinit_backoff *= 2;
  8637. device_recovered(cgpu);
  8638. }
  8639. return;
  8640. }
  8641. else
  8642. if (*denable == DEV_RECOVER) {
  8643. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  8644. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  8645. dev_str);
  8646. device_recovered(cgpu);
  8647. }
  8648. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8649. return;
  8650. }
  8651. else
  8652. if (cgpu->temp > cgpu->cutofftemp)
  8653. {
  8654. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  8655. dev_str, (int)cgpu->temp);
  8656. *denable = DEV_RECOVER;
  8657. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8658. run_cmd(cmd_idle);
  8659. }
  8660. if (thr->getwork) {
  8661. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  8662. int thrid;
  8663. bool cgpu_idle = true;
  8664. thr->rolling = 0;
  8665. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  8666. if (!cgpu->thr[thrid]->getwork)
  8667. cgpu_idle = false;
  8668. if (cgpu_idle) {
  8669. cgpu->rolling = 0;
  8670. cgpu->status = LIFE_WAIT;
  8671. }
  8672. }
  8673. return;
  8674. }
  8675. else if (cgpu->status == LIFE_WAIT)
  8676. cgpu->status = LIFE_WELL;
  8677. #ifdef WANT_CPUMINE
  8678. if (!strcmp(cgpu->drv->dname, "cpu"))
  8679. return;
  8680. #endif
  8681. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  8682. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  8683. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  8684. cgpu->status = LIFE_WELL;
  8685. cgpu->device_last_well = time(NULL);
  8686. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  8687. thr->rolling = cgpu->rolling = 0;
  8688. cgpu->status = LIFE_SICK;
  8689. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  8690. cgtime(&thr->sick);
  8691. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  8692. run_cmd(cmd_sick);
  8693. if (opt_restart && cgpu->drv->reinit_device) {
  8694. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  8695. reinit_device(cgpu);
  8696. }
  8697. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  8698. cgpu->status = LIFE_DEAD;
  8699. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  8700. cgtime(&thr->sick);
  8701. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  8702. run_cmd(cmd_dead);
  8703. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  8704. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  8705. /* Attempt to restart a GPU that's sick or dead once every minute */
  8706. cgtime(&thr->sick);
  8707. if (opt_restart)
  8708. reinit_device(cgpu);
  8709. }
  8710. }
  8711. static void log_print_status(struct cgpu_info *cgpu)
  8712. {
  8713. char logline[255];
  8714. get_statline(logline, sizeof(logline), cgpu);
  8715. applog(LOG_WARNING, "%s", logline);
  8716. }
  8717. void print_summary(void)
  8718. {
  8719. struct timeval diff;
  8720. int hours, mins, secs, i;
  8721. double utility, efficiency = 0.0;
  8722. char xfer[17], bw[19];
  8723. int pool_secs;
  8724. timersub(&total_tv_end, &total_tv_start, &diff);
  8725. hours = diff.tv_sec / 3600;
  8726. mins = (diff.tv_sec % 3600) / 60;
  8727. secs = diff.tv_sec % 60;
  8728. utility = total_accepted / total_secs * 60;
  8729. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  8730. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  8731. applog(LOG_WARNING, "Started at %s", datestamp);
  8732. if (total_pools == 1)
  8733. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  8734. #ifdef WANT_CPUMINE
  8735. if (opt_n_threads)
  8736. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  8737. #endif
  8738. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  8739. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  8740. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  8741. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  8742. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  8743. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  8744. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  8745. total_rejected, total_stale,
  8746. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  8747. );
  8748. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  8749. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  8750. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  8751. applog(LOG_WARNING, "Network transfer: %s (%s)",
  8752. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8753. (float)total_bytes_rcvd,
  8754. (float)total_bytes_sent),
  8755. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8756. (float)(total_bytes_rcvd / total_secs),
  8757. (float)(total_bytes_sent / total_secs)));
  8758. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  8759. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  8760. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  8761. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  8762. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  8763. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  8764. if (total_pools > 1) {
  8765. for (i = 0; i < total_pools; i++) {
  8766. struct pool *pool = pools[i];
  8767. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  8768. if (pool->solved)
  8769. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  8770. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  8771. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  8772. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  8773. pool->rejected, pool->stale_shares,
  8774. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  8775. );
  8776. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  8777. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  8778. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  8779. applog(LOG_WARNING, " Network transfer: %s (%s)",
  8780. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8781. (float)pool->cgminer_pool_stats.net_bytes_received,
  8782. (float)pool->cgminer_pool_stats.net_bytes_sent),
  8783. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8784. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  8785. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  8786. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  8787. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  8788. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  8789. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  8790. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  8791. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  8792. }
  8793. }
  8794. if (opt_quit_summary != BQS_NONE)
  8795. {
  8796. if (opt_quit_summary == BQS_DETAILED)
  8797. include_serial_in_statline = true;
  8798. applog(LOG_WARNING, "Summary of per device statistics:\n");
  8799. for (i = 0; i < total_devices; ++i) {
  8800. struct cgpu_info *cgpu = get_devices(i);
  8801. if (!cgpu->proc_id)
  8802. {
  8803. // Device summary line
  8804. opt_show_procs = false;
  8805. log_print_status(cgpu);
  8806. opt_show_procs = true;
  8807. }
  8808. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  8809. log_print_status(cgpu);
  8810. }
  8811. }
  8812. if (opt_shares) {
  8813. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  8814. if (opt_shares > total_diff_accepted)
  8815. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  8816. }
  8817. applog(LOG_WARNING, " ");
  8818. fflush(stderr);
  8819. fflush(stdout);
  8820. }
  8821. void _bfg_clean_up(bool restarting)
  8822. {
  8823. #ifdef HAVE_OPENCL
  8824. clear_adl(nDevs);
  8825. #endif
  8826. #ifdef HAVE_LIBUSB
  8827. if (likely(have_libusb))
  8828. libusb_exit(NULL);
  8829. #endif
  8830. cgtime(&total_tv_end);
  8831. #ifdef WIN32
  8832. timeEndPeriod(1);
  8833. #endif
  8834. if (!restarting) {
  8835. /* Attempting to disable curses or print a summary during a
  8836. * restart can lead to a deadlock. */
  8837. #ifdef HAVE_CURSES
  8838. disable_curses();
  8839. #endif
  8840. if (!opt_realquiet && successful_connect)
  8841. print_summary();
  8842. }
  8843. if (opt_n_threads)
  8844. free(cpus);
  8845. curl_global_cleanup();
  8846. #ifdef WIN32
  8847. WSACleanup();
  8848. #endif
  8849. }
  8850. void _quit(int status)
  8851. {
  8852. if (status) {
  8853. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  8854. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  8855. int *p = NULL;
  8856. // NOTE debugger can bypass with: p = &p
  8857. *p = status; // Segfault, hopefully dumping core
  8858. }
  8859. }
  8860. #if defined(unix) || defined(__APPLE__)
  8861. if (forkpid > 0) {
  8862. kill(forkpid, SIGTERM);
  8863. forkpid = 0;
  8864. }
  8865. #endif
  8866. exit(status);
  8867. }
  8868. #ifdef HAVE_CURSES
  8869. char *curses_input(const char *query)
  8870. {
  8871. char *input;
  8872. echo();
  8873. input = malloc(255);
  8874. if (!input)
  8875. quit(1, "Failed to malloc input");
  8876. leaveok(logwin, false);
  8877. wlogprint("%s:\n", query);
  8878. wgetnstr(logwin, input, 255);
  8879. if (!strlen(input))
  8880. {
  8881. free(input);
  8882. input = NULL;
  8883. }
  8884. leaveok(logwin, true);
  8885. noecho();
  8886. return input;
  8887. }
  8888. #endif
  8889. static bool pools_active = false;
  8890. static void *test_pool_thread(void *arg)
  8891. {
  8892. struct pool *pool = (struct pool *)arg;
  8893. if (pool_active(pool, false)) {
  8894. pool_tset(pool, &pool->lagging);
  8895. pool_tclear(pool, &pool->idle);
  8896. bool first_pool = false;
  8897. cg_wlock(&control_lock);
  8898. if (!pools_active) {
  8899. currentpool = pool;
  8900. if (pool->pool_no != 0)
  8901. first_pool = true;
  8902. pools_active = true;
  8903. }
  8904. cg_wunlock(&control_lock);
  8905. if (unlikely(first_pool))
  8906. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  8907. else
  8908. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8909. switch_pools(NULL);
  8910. } else
  8911. pool_died(pool);
  8912. pool->testing = false;
  8913. return NULL;
  8914. }
  8915. /* Always returns true that the pool details were added unless we are not
  8916. * live, implying this is the only pool being added, so if no pools are
  8917. * active it returns false. */
  8918. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  8919. {
  8920. size_t siz;
  8921. pool->rpc_url = url;
  8922. pool->rpc_user = user;
  8923. pool->rpc_pass = pass;
  8924. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8925. pool->rpc_userpass = malloc(siz);
  8926. if (!pool->rpc_userpass)
  8927. quit(1, "Failed to malloc userpass");
  8928. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8929. pool->testing = true;
  8930. pool->idle = true;
  8931. enable_pool(pool);
  8932. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8933. if (!live) {
  8934. pthread_join(pool->test_thread, NULL);
  8935. return pools_active;
  8936. }
  8937. return true;
  8938. }
  8939. #ifdef HAVE_CURSES
  8940. static bool input_pool(bool live)
  8941. {
  8942. char *url = NULL, *user = NULL, *pass = NULL;
  8943. struct pool *pool;
  8944. bool ret = false;
  8945. immedok(logwin, true);
  8946. wlogprint("Input server details.\n");
  8947. url = curses_input("URL");
  8948. if (!url)
  8949. goto out;
  8950. user = curses_input("Username");
  8951. if (!user)
  8952. goto out;
  8953. pass = curses_input("Password");
  8954. if (!pass)
  8955. pass = calloc(1, 1);
  8956. pool = add_pool();
  8957. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  8958. strncmp(url, "https://", 8)) {
  8959. char *httpinput;
  8960. httpinput = malloc(256);
  8961. if (!httpinput)
  8962. quit(1, "Failed to malloc httpinput");
  8963. strcpy(httpinput, "http://");
  8964. strncat(httpinput, url, 248);
  8965. free(url);
  8966. url = httpinput;
  8967. }
  8968. ret = add_pool_details(pool, live, url, user, pass);
  8969. out:
  8970. immedok(logwin, false);
  8971. if (!ret) {
  8972. if (url)
  8973. free(url);
  8974. if (user)
  8975. free(user);
  8976. if (pass)
  8977. free(pass);
  8978. }
  8979. return ret;
  8980. }
  8981. #endif
  8982. #if defined(unix) || defined(__APPLE__)
  8983. static void fork_monitor()
  8984. {
  8985. // Make a pipe: [readFD, writeFD]
  8986. int pfd[2];
  8987. int r = pipe(pfd);
  8988. if (r < 0) {
  8989. perror("pipe - failed to create pipe for --monitor");
  8990. exit(1);
  8991. }
  8992. // Make stderr write end of pipe
  8993. fflush(stderr);
  8994. r = dup2(pfd[1], 2);
  8995. if (r < 0) {
  8996. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  8997. exit(1);
  8998. }
  8999. r = close(pfd[1]);
  9000. if (r < 0) {
  9001. perror("close - failed to close write end of pipe for --monitor");
  9002. exit(1);
  9003. }
  9004. // Don't allow a dying monitor to kill the main process
  9005. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9006. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9007. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9008. perror("signal - failed to edit signal mask for --monitor");
  9009. exit(1);
  9010. }
  9011. // Fork a child process
  9012. forkpid = fork();
  9013. if (forkpid < 0) {
  9014. perror("fork - failed to fork child process for --monitor");
  9015. exit(1);
  9016. }
  9017. // Child: launch monitor command
  9018. if (0 == forkpid) {
  9019. // Make stdin read end of pipe
  9020. r = dup2(pfd[0], 0);
  9021. if (r < 0) {
  9022. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9023. exit(1);
  9024. }
  9025. close(pfd[0]);
  9026. if (r < 0) {
  9027. perror("close - in child, failed to close read end of pipe for --monitor");
  9028. exit(1);
  9029. }
  9030. // Launch user specified command
  9031. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9032. perror("execl - in child failed to exec user specified command for --monitor");
  9033. exit(1);
  9034. }
  9035. // Parent: clean up unused fds and bail
  9036. r = close(pfd[0]);
  9037. if (r < 0) {
  9038. perror("close - failed to close read end of pipe for --monitor");
  9039. exit(1);
  9040. }
  9041. }
  9042. #endif // defined(unix)
  9043. #ifdef HAVE_CURSES
  9044. #ifdef USE_UNICODE
  9045. static
  9046. wchar_t select_unicode_char(const wchar_t *opt)
  9047. {
  9048. for ( ; *opt; ++opt)
  9049. if (iswprint(*opt))
  9050. return *opt;
  9051. return '?';
  9052. }
  9053. #endif
  9054. void enable_curses(void) {
  9055. int x;
  9056. __maybe_unused int y;
  9057. lock_curses();
  9058. if (curses_active) {
  9059. unlock_curses();
  9060. return;
  9061. }
  9062. #ifdef USE_UNICODE
  9063. if (use_unicode)
  9064. {
  9065. setlocale(LC_CTYPE, "");
  9066. if (iswprint(0xb0))
  9067. have_unicode_degrees = true;
  9068. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  9069. }
  9070. #endif
  9071. mainwin = initscr();
  9072. start_color();
  9073. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  9074. if (ERR != use_default_colors())
  9075. default_bgcolor = -1;
  9076. #endif
  9077. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  9078. {
  9079. menu_attr = COLOR_PAIR(1);
  9080. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  9081. attr_bad |= COLOR_PAIR(2);
  9082. }
  9083. keypad(mainwin, true);
  9084. getmaxyx(mainwin, y, x);
  9085. statuswin = newwin(logstart, x, 0, 0);
  9086. leaveok(statuswin, true);
  9087. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  9088. // We resize the window later anyway, so just start it off at 1 :)
  9089. logwin = newwin(1, 0, logcursor, 0);
  9090. idlok(logwin, true);
  9091. scrollok(logwin, true);
  9092. leaveok(logwin, true);
  9093. cbreak();
  9094. noecho();
  9095. nonl();
  9096. curses_active = true;
  9097. statusy = logstart;
  9098. unlock_curses();
  9099. }
  9100. #endif
  9101. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  9102. #ifndef WANT_CPUMINE
  9103. struct device_drv cpu_drv;
  9104. struct device_drv cpu_drv = {
  9105. .name = "CPU",
  9106. };
  9107. #endif
  9108. static int cgminer_id_count = 0;
  9109. static int device_line_id_count;
  9110. void register_device(struct cgpu_info *cgpu)
  9111. {
  9112. cgpu->deven = DEV_ENABLED;
  9113. wr_lock(&devices_lock);
  9114. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9115. wr_unlock(&devices_lock);
  9116. if (!cgpu->proc_id)
  9117. cgpu->device_line_id = device_line_id_count++;
  9118. mining_threads += cgpu->threads ?: 1;
  9119. #ifdef HAVE_CURSES
  9120. adj_width(mining_threads, &dev_width);
  9121. #endif
  9122. rwlock_init(&cgpu->qlock);
  9123. cgpu->queued_work = NULL;
  9124. }
  9125. struct _cgpu_devid_counter {
  9126. char name[4];
  9127. int lastid;
  9128. UT_hash_handle hh;
  9129. };
  9130. void renumber_cgpu(struct cgpu_info *cgpu)
  9131. {
  9132. static struct _cgpu_devid_counter *devids = NULL;
  9133. struct _cgpu_devid_counter *d;
  9134. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9135. if (d)
  9136. cgpu->device_id = ++d->lastid;
  9137. else {
  9138. d = malloc(sizeof(*d));
  9139. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9140. cgpu->device_id = d->lastid = 0;
  9141. HASH_ADD_STR(devids, name, d);
  9142. }
  9143. }
  9144. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  9145. {
  9146. sha256(buffer, length, digest);
  9147. return true;
  9148. }
  9149. #ifndef HAVE_PTHREAD_CANCEL
  9150. extern void setup_pthread_cancel_workaround();
  9151. extern struct sigaction pcwm_orig_term_handler;
  9152. #endif
  9153. bool bfg_need_detect_rescan;
  9154. extern void probe_device(struct lowlevel_device_info *);
  9155. static void schedule_rescan(const struct timeval *);
  9156. static
  9157. void drv_detect_all()
  9158. {
  9159. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  9160. bool rescanning = false;
  9161. rescan:
  9162. bfg_need_detect_rescan = false;
  9163. #ifdef HAVE_BFG_LOWLEVEL
  9164. if (!opt_scrypt)
  9165. {
  9166. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  9167. LL_FOREACH_SAFE(infolist, info, infotmp)
  9168. probe_device(info);
  9169. LL_FOREACH_SAFE(infolist, info, infotmp)
  9170. pthread_join(info->probe_pth, NULL);
  9171. }
  9172. #endif
  9173. struct driver_registration *reg, *tmp;
  9174. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  9175. {
  9176. const struct device_drv * const drv = reg->drv;
  9177. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  9178. if (0 == (algos & algomatch) || !drv->drv_detect)
  9179. continue;
  9180. drv->drv_detect();
  9181. }
  9182. #ifdef HAVE_BFG_LOWLEVEL
  9183. if (!opt_scrypt)
  9184. lowlevel_scan_free();
  9185. #endif
  9186. if (bfg_need_detect_rescan)
  9187. {
  9188. if (rescanning)
  9189. {
  9190. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  9191. struct timeval tv_when;
  9192. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  9193. schedule_rescan(&tv_when);
  9194. }
  9195. else
  9196. {
  9197. rescanning = true;
  9198. applog(LOG_DEBUG, "Device rescan requested");
  9199. goto rescan;
  9200. }
  9201. }
  9202. }
  9203. static
  9204. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  9205. {
  9206. struct thr_info *thr;
  9207. int j;
  9208. struct device_drv *api = cgpu->drv;
  9209. if (!cgpu->devtype)
  9210. cgpu->devtype = "PGA";
  9211. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9212. int threadobj = cgpu->threads;
  9213. if (!threadobj)
  9214. // Create a fake thread object to handle hashmeter etc
  9215. threadobj = 1;
  9216. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  9217. cgpu->thr[threadobj] = NULL;
  9218. cgpu->status = LIFE_INIT;
  9219. if (opt_devices_enabled_list)
  9220. {
  9221. struct string_elist *enablestr_elist;
  9222. cgpu->deven = DEV_DISABLED;
  9223. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  9224. {
  9225. const char * const enablestr = enablestr_elist->string;
  9226. if (cgpu_match(enablestr, cgpu))
  9227. {
  9228. cgpu->deven = DEV_ENABLED;
  9229. break;
  9230. }
  9231. }
  9232. }
  9233. cgpu->max_hashes = 0;
  9234. BFGINIT(cgpu->min_nonce_diff, 1);
  9235. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  9236. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  9237. // Setup thread structs before starting any of the threads, in case they try to interact
  9238. for (j = 0; j < threadobj; ++j, ++*kp) {
  9239. thr = get_thread(*kp);
  9240. thr->id = *kp;
  9241. thr->cgpu = cgpu;
  9242. thr->device_thread = j;
  9243. thr->work_restart_notifier[1] = INVSOCK;
  9244. thr->mutex_request[1] = INVSOCK;
  9245. thr->_job_transition_in_progress = true;
  9246. timerclear(&thr->tv_morework);
  9247. thr->scanhash_working = true;
  9248. thr->hashes_done = 0;
  9249. timerclear(&thr->tv_hashes_done);
  9250. cgtime(&thr->tv_lastupdate);
  9251. thr->tv_poll.tv_sec = -1;
  9252. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  9253. cgpu->thr[j] = thr;
  9254. }
  9255. if (!cgpu->device->threads)
  9256. notifier_init_invalid(cgpu->thr[0]->notifier);
  9257. else
  9258. if (!cgpu->threads)
  9259. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  9260. else
  9261. for (j = 0; j < cgpu->threads; ++j)
  9262. {
  9263. thr = cgpu->thr[j];
  9264. notifier_init(thr->notifier);
  9265. }
  9266. }
  9267. static
  9268. void start_cgpu(struct cgpu_info *cgpu)
  9269. {
  9270. struct thr_info *thr;
  9271. int j;
  9272. for (j = 0; j < cgpu->threads; ++j) {
  9273. thr = cgpu->thr[j];
  9274. /* Enable threads for devices set not to mine but disable
  9275. * their queue in case we wish to enable them later */
  9276. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  9277. continue;
  9278. thread_reportout(thr);
  9279. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9280. quit(1, "thread %d create failed", thr->id);
  9281. notifier_wake(thr->notifier);
  9282. }
  9283. if (cgpu->deven == DEV_ENABLED)
  9284. proc_enable(cgpu);
  9285. }
  9286. static
  9287. void _scan_serial(void *p)
  9288. {
  9289. const char *s = p;
  9290. struct string_elist *iter, *tmp;
  9291. struct string_elist *orig_scan_devices = scan_devices;
  9292. if (s)
  9293. {
  9294. // Make temporary scan_devices list
  9295. scan_devices = NULL;
  9296. string_elist_add("noauto", &scan_devices);
  9297. add_serial(s);
  9298. }
  9299. drv_detect_all();
  9300. if (s)
  9301. {
  9302. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  9303. {
  9304. string_elist_del(&scan_devices, iter);
  9305. }
  9306. scan_devices = orig_scan_devices;
  9307. }
  9308. }
  9309. #ifdef HAVE_BFG_LOWLEVEL
  9310. static
  9311. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  9312. {
  9313. if (!(false
  9314. || (info->serial && !strcasecmp(ser, info->serial))
  9315. || (info->path && !strcasecmp(ser, info->path ))
  9316. || (info->devid && !strcasecmp(ser, info->devid ))
  9317. ))
  9318. {
  9319. char *devid = devpath_to_devid(ser);
  9320. if (!devid)
  9321. return false;
  9322. const bool different = strcmp(info->devid, devid);
  9323. free(devid);
  9324. if (different)
  9325. return false;
  9326. }
  9327. return true;
  9328. }
  9329. static
  9330. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  9331. {
  9332. struct driver_registration *dreg;
  9333. char dname[dnamelen];
  9334. int i;
  9335. for (i = 0; i < dnamelen; ++i)
  9336. dname[i] = tolower(_dname[i]);
  9337. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  9338. if (!dreg)
  9339. {
  9340. for (i = 0; i < dnamelen; ++i)
  9341. dname[i] = toupper(_dname[i]);
  9342. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  9343. if (!dreg)
  9344. return NULL;
  9345. }
  9346. return dreg->drv;
  9347. }
  9348. static
  9349. bool _probe_device_internal(struct lowlevel_device_info * const info, const char * const dname, const size_t dnamelen)
  9350. {
  9351. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9352. if (!(drv && drv->lowl_probe))
  9353. return false;
  9354. return drv->lowl_probe(info);
  9355. }
  9356. static
  9357. void *probe_device_thread(void *p)
  9358. {
  9359. struct lowlevel_device_info * const infolist = p;
  9360. struct lowlevel_device_info *info = infolist;
  9361. {
  9362. char threadname[5 + strlen(info->devid) + 1];
  9363. sprintf(threadname, "probe_%s", info->devid);
  9364. RenameThread(threadname);
  9365. }
  9366. // If already in use, ignore
  9367. if (bfg_claim_any(NULL, NULL, info->devid))
  9368. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  9369. __func__, info->product);
  9370. // if lowlevel device matches specific user assignment, probe requested driver(s)
  9371. struct string_elist *sd_iter, *sd_tmp;
  9372. struct driver_registration *dreg, *dreg_tmp;
  9373. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9374. {
  9375. const char * const dname = sd_iter->string;
  9376. const char * const colon = strpbrk(dname, ":@");
  9377. if (!(colon && colon != dname))
  9378. continue;
  9379. const char * const ser = &colon[1];
  9380. LL_FOREACH2(infolist, info, same_devid_next)
  9381. {
  9382. if (!_probe_device_match(info, ser))
  9383. continue;
  9384. const size_t dnamelen = (colon - dname);
  9385. if (_probe_device_internal(info, dname, dnamelen))
  9386. return NULL;
  9387. else
  9388. if (opt_hotplug)
  9389. bfg_need_detect_rescan = true;
  9390. }
  9391. }
  9392. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  9393. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9394. {
  9395. const struct device_drv * const drv = dreg->drv;
  9396. // Check for "noauto" flag
  9397. // NOTE: driver-specific configuration overrides general
  9398. bool doauto = true;
  9399. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9400. {
  9401. const char * const dname = sd_iter->string;
  9402. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9403. const char *colon = strchr(dname, ':');
  9404. if (!colon)
  9405. colon = &dname[-1];
  9406. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  9407. continue;
  9408. const ssize_t dnamelen = (colon - dname);
  9409. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  9410. continue;
  9411. doauto = (tolower(colon[1]) == 'a');
  9412. if (dnamelen != -1)
  9413. break;
  9414. }
  9415. if (doauto && drv->lowl_match)
  9416. {
  9417. LL_FOREACH2(infolist, info, same_devid_next)
  9418. {
  9419. if (!drv->lowl_match(info))
  9420. continue;
  9421. if (drv->lowl_probe(info))
  9422. return NULL;
  9423. else
  9424. if (opt_hotplug)
  9425. bfg_need_detect_rescan = true;
  9426. }
  9427. }
  9428. }
  9429. // probe driver(s) with 'all' enabled
  9430. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9431. {
  9432. const char * const dname = sd_iter->string;
  9433. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9434. const char * const colon = strchr(dname, ':');
  9435. if (!colon)
  9436. {
  9437. LL_FOREACH2(infolist, info, same_devid_next)
  9438. {
  9439. if (
  9440. #ifdef NEED_BFG_LOWL_VCOM
  9441. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  9442. #endif
  9443. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  9444. {
  9445. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9446. {
  9447. const struct device_drv * const drv = dreg->drv;
  9448. if (drv->lowl_probe_by_name_only)
  9449. continue;
  9450. if (!drv->lowl_probe)
  9451. continue;
  9452. if (drv->lowl_probe(info))
  9453. return NULL;
  9454. }
  9455. if (opt_hotplug)
  9456. bfg_need_detect_rescan = true;
  9457. break;
  9458. }
  9459. }
  9460. continue;
  9461. }
  9462. if (strcasecmp(&colon[1], "all"))
  9463. continue;
  9464. const size_t dnamelen = (colon - dname);
  9465. LL_FOREACH2(infolist, info, same_devid_next)
  9466. {
  9467. if (_probe_device_internal(info, dname, dnamelen))
  9468. return NULL;
  9469. }
  9470. }
  9471. return NULL;
  9472. }
  9473. void probe_device(struct lowlevel_device_info * const info)
  9474. {
  9475. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  9476. }
  9477. #endif
  9478. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  9479. {
  9480. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  9481. int devcount, i, mining_threads_new = 0;
  9482. unsigned int k;
  9483. struct cgpu_info *cgpu;
  9484. struct thr_info *thr;
  9485. void *p;
  9486. mutex_lock(&mutex);
  9487. devcount = total_devices;
  9488. addfunc(arg);
  9489. if (!total_devices_new)
  9490. goto out;
  9491. wr_lock(&devices_lock);
  9492. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  9493. if (unlikely(!p))
  9494. {
  9495. wr_unlock(&devices_lock);
  9496. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  9497. goto out;
  9498. }
  9499. devices = p;
  9500. wr_unlock(&devices_lock);
  9501. for (i = 0; i < total_devices_new; ++i)
  9502. {
  9503. cgpu = devices_new[i];
  9504. mining_threads_new += cgpu->threads ?: 1;
  9505. }
  9506. wr_lock(&mining_thr_lock);
  9507. mining_threads_new += mining_threads;
  9508. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  9509. if (unlikely(!p))
  9510. {
  9511. wr_unlock(&mining_thr_lock);
  9512. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  9513. goto out;
  9514. }
  9515. mining_thr = p;
  9516. wr_unlock(&mining_thr_lock);
  9517. for (i = mining_threads; i < mining_threads_new; ++i) {
  9518. mining_thr[i] = calloc(1, sizeof(*thr));
  9519. if (!mining_thr[i])
  9520. {
  9521. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  9522. for ( ; --i >= mining_threads; )
  9523. free(mining_thr[i]);
  9524. goto out;
  9525. }
  9526. }
  9527. k = mining_threads;
  9528. for (i = 0; i < total_devices_new; ++i)
  9529. {
  9530. cgpu = devices_new[i];
  9531. allocate_cgpu(cgpu, &k);
  9532. }
  9533. for (i = 0; i < total_devices_new; ++i)
  9534. {
  9535. cgpu = devices_new[i];
  9536. start_cgpu(cgpu);
  9537. register_device(cgpu);
  9538. ++total_devices;
  9539. }
  9540. #ifdef HAVE_CURSES
  9541. switch_logsize();
  9542. #endif
  9543. out:
  9544. total_devices_new = 0;
  9545. devcount = total_devices - devcount;
  9546. mutex_unlock(&mutex);
  9547. return devcount;
  9548. }
  9549. int scan_serial(const char *s)
  9550. {
  9551. return create_new_cgpus(_scan_serial, (void*)s);
  9552. }
  9553. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  9554. static bool rescan_active;
  9555. static struct timeval tv_rescan;
  9556. static notifier_t rescan_notifier;
  9557. static
  9558. void *rescan_thread(__maybe_unused void *p)
  9559. {
  9560. pthread_detach(pthread_self());
  9561. RenameThread("rescan");
  9562. struct timeval tv_timeout, tv_now;
  9563. fd_set rfds;
  9564. while (true)
  9565. {
  9566. mutex_lock(&rescan_mutex);
  9567. tv_timeout = tv_rescan;
  9568. if (!timer_isset(&tv_timeout))
  9569. {
  9570. rescan_active = false;
  9571. mutex_unlock(&rescan_mutex);
  9572. break;
  9573. }
  9574. mutex_unlock(&rescan_mutex);
  9575. FD_ZERO(&rfds);
  9576. FD_SET(rescan_notifier[0], &rfds);
  9577. const int maxfd = rescan_notifier[0];
  9578. timer_set_now(&tv_now);
  9579. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  9580. notifier_read(rescan_notifier);
  9581. mutex_lock(&rescan_mutex);
  9582. if (timer_passed(&tv_rescan, NULL))
  9583. {
  9584. timer_unset(&tv_rescan);
  9585. mutex_unlock(&rescan_mutex);
  9586. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  9587. scan_serial(NULL);
  9588. }
  9589. else
  9590. mutex_unlock(&rescan_mutex);
  9591. }
  9592. return NULL;
  9593. }
  9594. static
  9595. void _schedule_rescan(const struct timeval * const tvp_when)
  9596. {
  9597. if (rescan_active)
  9598. {
  9599. if (timercmp(tvp_when, &tv_rescan, <))
  9600. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  9601. else
  9602. {
  9603. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  9604. tv_rescan = *tvp_when;
  9605. }
  9606. return;
  9607. }
  9608. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  9609. tv_rescan = *tvp_when;
  9610. rescan_active = true;
  9611. static pthread_t pth;
  9612. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  9613. applog(LOG_ERR, "Failed to start rescan thread");
  9614. }
  9615. static
  9616. void schedule_rescan(const struct timeval * const tvp_when)
  9617. {
  9618. mutex_lock(&rescan_mutex);
  9619. _schedule_rescan(tvp_when);
  9620. mutex_unlock(&rescan_mutex);
  9621. }
  9622. #ifdef HAVE_BFG_HOTPLUG
  9623. static
  9624. void hotplug_trigger()
  9625. {
  9626. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  9627. struct timeval tv_now;
  9628. timer_set_now(&tv_now);
  9629. schedule_rescan(&tv_now);
  9630. }
  9631. #endif
  9632. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  9633. static
  9634. void *hotplug_thread(__maybe_unused void *p)
  9635. {
  9636. pthread_detach(pthread_self());
  9637. RenameThread("hotplug");
  9638. struct udev * const udev = udev_new();
  9639. if (unlikely(!udev))
  9640. applogfailr(NULL, LOG_ERR, "udev_new");
  9641. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  9642. if (unlikely(!mon))
  9643. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  9644. if (unlikely(udev_monitor_enable_receiving(mon)))
  9645. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  9646. const int epfd = epoll_create(1);
  9647. if (unlikely(epfd == -1))
  9648. applogfailr(NULL, LOG_ERR, "epoll_create");
  9649. {
  9650. const int fd = udev_monitor_get_fd(mon);
  9651. struct epoll_event ev = {
  9652. .events = EPOLLIN | EPOLLPRI,
  9653. .data.fd = fd,
  9654. };
  9655. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  9656. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  9657. }
  9658. struct epoll_event ev;
  9659. int rv;
  9660. bool pending = false;
  9661. while (true)
  9662. {
  9663. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  9664. if (rv == -1)
  9665. {
  9666. if (errno == EAGAIN || errno == EINTR)
  9667. continue;
  9668. break;
  9669. }
  9670. if (!rv)
  9671. {
  9672. hotplug_trigger();
  9673. pending = false;
  9674. continue;
  9675. }
  9676. struct udev_device * const device = udev_monitor_receive_device(mon);
  9677. if (!device)
  9678. continue;
  9679. const char * const action = udev_device_get_action(device);
  9680. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  9681. if (strcmp(action, "add"))
  9682. continue;
  9683. pending = true;
  9684. }
  9685. applogfailr(NULL, LOG_ERR, "epoll_wait");
  9686. }
  9687. #elif defined(WIN32)
  9688. static UINT_PTR _hotplug_wintimer_id;
  9689. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  9690. {
  9691. KillTimer(NULL, _hotplug_wintimer_id);
  9692. _hotplug_wintimer_id = 0;
  9693. hotplug_trigger();
  9694. }
  9695. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  9696. {
  9697. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  9698. {
  9699. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  9700. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  9701. }
  9702. return DefWindowProc(hwnd, msg, wParam, lParam);
  9703. }
  9704. static
  9705. void *hotplug_thread(__maybe_unused void *p)
  9706. {
  9707. pthread_detach(pthread_self());
  9708. WNDCLASS DummyWinCls = {
  9709. .lpszClassName = "BFGDummyWinCls",
  9710. .lpfnWndProc = hotplug_win_callback,
  9711. };
  9712. ATOM a = RegisterClass(&DummyWinCls);
  9713. if (unlikely(!a))
  9714. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  9715. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  9716. if (unlikely(!hwnd))
  9717. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  9718. MSG msg;
  9719. while (GetMessage(&msg, NULL, 0, 0))
  9720. {
  9721. TranslateMessage(&msg);
  9722. DispatchMessage(&msg);
  9723. }
  9724. quit(0, "WM_QUIT received");
  9725. return NULL;
  9726. }
  9727. #endif
  9728. #ifdef HAVE_BFG_HOTPLUG
  9729. static
  9730. void hotplug_start()
  9731. {
  9732. pthread_t pth;
  9733. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  9734. applog(LOG_ERR, "Failed to start hotplug thread");
  9735. }
  9736. #endif
  9737. static void probe_pools(void)
  9738. {
  9739. int i;
  9740. for (i = 0; i < total_pools; i++) {
  9741. struct pool *pool = pools[i];
  9742. pool->testing = true;
  9743. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9744. }
  9745. }
  9746. static void raise_fd_limits(void)
  9747. {
  9748. #ifdef HAVE_SETRLIMIT
  9749. struct rlimit fdlimit;
  9750. unsigned long old_soft_limit;
  9751. char frombuf[0x10] = "unlimited";
  9752. char hardbuf[0x10] = "unlimited";
  9753. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  9754. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  9755. old_soft_limit = fdlimit.rlim_cur;
  9756. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  9757. fdlimit.rlim_cur = FD_SETSIZE;
  9758. else
  9759. fdlimit.rlim_cur = fdlimit.rlim_max;
  9760. if (fdlimit.rlim_max != RLIM_INFINITY)
  9761. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  9762. if (old_soft_limit != RLIM_INFINITY)
  9763. snprintf(frombuf, sizeof(frombuf), "%lu", old_soft_limit);
  9764. if (fdlimit.rlim_cur == old_soft_limit)
  9765. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9766. old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  9767. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  9768. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9769. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9770. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9771. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9772. #else
  9773. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  9774. #endif
  9775. }
  9776. extern void bfg_init_threadlocal();
  9777. extern void stratumsrv_start();
  9778. int main(int argc, char *argv[])
  9779. {
  9780. struct sigaction handler;
  9781. struct thr_info *thr;
  9782. struct block *block;
  9783. unsigned int k;
  9784. int i;
  9785. int rearrange_pools = 0;
  9786. char *s;
  9787. #ifdef WIN32
  9788. LoadLibrary("backtrace.dll");
  9789. #endif
  9790. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  9791. bfg_init_threadlocal();
  9792. #ifndef HAVE_PTHREAD_CANCEL
  9793. setup_pthread_cancel_workaround();
  9794. #endif
  9795. bfg_init_checksums();
  9796. #ifdef WIN32
  9797. {
  9798. WSADATA wsa;
  9799. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  9800. if (i)
  9801. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  9802. }
  9803. #endif
  9804. /* This dangerous functions tramples random dynamically allocated
  9805. * variables so do it before anything at all */
  9806. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  9807. quit(1, "Failed to curl_global_init");
  9808. initial_args = malloc(sizeof(char *) * (argc + 1));
  9809. for (i = 0; i < argc; i++)
  9810. initial_args[i] = strdup(argv[i]);
  9811. initial_args[argc] = NULL;
  9812. mutex_init(&hash_lock);
  9813. mutex_init(&console_lock);
  9814. cglock_init(&control_lock);
  9815. mutex_init(&stats_lock);
  9816. mutex_init(&sharelog_lock);
  9817. cglock_init(&ch_lock);
  9818. mutex_init(&sshare_lock);
  9819. rwlock_init(&blk_lock);
  9820. rwlock_init(&netacc_lock);
  9821. rwlock_init(&mining_thr_lock);
  9822. rwlock_init(&devices_lock);
  9823. mutex_init(&lp_lock);
  9824. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  9825. quit(1, "Failed to pthread_cond_init lp_cond");
  9826. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  9827. quit(1, "Failed to pthread_cond_init gws_cond");
  9828. notifier_init(submit_waiting_notifier);
  9829. timer_unset(&tv_rescan);
  9830. notifier_init(rescan_notifier);
  9831. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  9832. #ifdef WANT_CPUMINE
  9833. init_max_name_len();
  9834. #endif
  9835. handler.sa_handler = &sighandler;
  9836. handler.sa_flags = 0;
  9837. sigemptyset(&handler.sa_mask);
  9838. #ifdef HAVE_PTHREAD_CANCEL
  9839. sigaction(SIGTERM, &handler, &termhandler);
  9840. #else
  9841. // Need to let pthread_cancel emulation handle SIGTERM first
  9842. termhandler = pcwm_orig_term_handler;
  9843. pcwm_orig_term_handler = handler;
  9844. #endif
  9845. sigaction(SIGINT, &handler, &inthandler);
  9846. #ifndef WIN32
  9847. signal(SIGPIPE, SIG_IGN);
  9848. #else
  9849. timeBeginPeriod(1);
  9850. #endif
  9851. opt_kernel_path = CGMINER_PREFIX;
  9852. cgminer_path = alloca(PATH_MAX);
  9853. s = strdup(argv[0]);
  9854. strcpy(cgminer_path, dirname(s));
  9855. free(s);
  9856. strcat(cgminer_path, "/");
  9857. #ifdef WANT_CPUMINE
  9858. // Hack to make cgminer silent when called recursively on WIN32
  9859. int skip_to_bench = 0;
  9860. #if defined(WIN32)
  9861. char buf[32];
  9862. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  9863. skip_to_bench = 1;
  9864. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  9865. skip_to_bench = 1;
  9866. #endif // defined(WIN32)
  9867. #endif
  9868. devcursor = 8;
  9869. logstart = devcursor;
  9870. logcursor = logstart;
  9871. block = calloc(sizeof(struct block), 1);
  9872. if (unlikely(!block))
  9873. quit (1, "main OOM");
  9874. for (i = 0; i < 36; i++)
  9875. strcat(block->hash, "0");
  9876. HASH_ADD_STR(blocks, hash, block);
  9877. strcpy(current_block, block->hash);
  9878. mutex_init(&submitting_lock);
  9879. #ifdef HAVE_OPENCL
  9880. opencl_early_init();
  9881. #endif
  9882. schedstart.tm.tm_sec = 1;
  9883. schedstop .tm.tm_sec = 1;
  9884. opt_register_table(opt_early_table, NULL);
  9885. opt_register_table(opt_config_table, NULL);
  9886. opt_register_table(opt_cmdline_table, NULL);
  9887. opt_early_parse(argc, argv, applog_and_exit);
  9888. if (!config_loaded)
  9889. {
  9890. load_default_config();
  9891. rearrange_pools = total_pools;
  9892. }
  9893. opt_free_table();
  9894. /* parse command line */
  9895. opt_register_table(opt_config_table,
  9896. "Options for both config file and command line");
  9897. opt_register_table(opt_cmdline_table,
  9898. "Options for command line only");
  9899. opt_parse(&argc, argv, applog_and_exit);
  9900. if (argc != 1)
  9901. quit(1, "Unexpected extra commandline arguments");
  9902. if (rearrange_pools && rearrange_pools < total_pools)
  9903. {
  9904. // Prioritise commandline pools before default-config pools
  9905. for (i = 0; i < rearrange_pools; ++i)
  9906. pools[i]->prio += rearrange_pools;
  9907. for ( ; i < total_pools; ++i)
  9908. pools[i]->prio -= rearrange_pools;
  9909. }
  9910. #ifndef HAVE_PTHREAD_CANCEL
  9911. // Can't do this any earlier, or config isn't loaded
  9912. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  9913. #endif
  9914. #ifdef HAVE_PWD_H
  9915. struct passwd *user_info = NULL;
  9916. if (opt_setuid != NULL) {
  9917. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  9918. quit(1, "Unable to find setuid user information");
  9919. }
  9920. }
  9921. #endif
  9922. #ifdef HAVE_CHROOT
  9923. if (chroot_dir != NULL) {
  9924. #ifdef HAVE_PWD_H
  9925. if (user_info == NULL && getuid() == 0) {
  9926. applog(LOG_WARNING, "Running as root inside chroot");
  9927. }
  9928. #endif
  9929. if (chroot(chroot_dir) != 0) {
  9930. quit(1, "Unable to chroot");
  9931. }
  9932. if (chdir("/"))
  9933. quit(1, "Unable to chdir to chroot");
  9934. }
  9935. #endif
  9936. #ifdef HAVE_PWD_H
  9937. if (user_info != NULL) {
  9938. if (setgid((*user_info).pw_gid) != 0)
  9939. quit(1, "Unable to setgid");
  9940. if (setuid((*user_info).pw_uid) != 0)
  9941. quit(1, "Unable to setuid");
  9942. }
  9943. #endif
  9944. raise_fd_limits();
  9945. if (opt_benchmark) {
  9946. struct pool *pool;
  9947. if (opt_scrypt)
  9948. quit(1, "Cannot use benchmark mode with scrypt");
  9949. want_longpoll = false;
  9950. pool = add_pool();
  9951. pool->rpc_url = malloc(255);
  9952. strcpy(pool->rpc_url, "Benchmark");
  9953. pool->rpc_user = pool->rpc_url;
  9954. pool->rpc_pass = pool->rpc_url;
  9955. enable_pool(pool);
  9956. pool->idle = false;
  9957. successful_connect = true;
  9958. }
  9959. if (opt_unittest) {
  9960. test_cgpu_match();
  9961. test_intrange();
  9962. test_decimal_width();
  9963. utf8_test();
  9964. }
  9965. #ifdef HAVE_CURSES
  9966. if (opt_realquiet || opt_display_devs)
  9967. use_curses = false;
  9968. setlocale(LC_ALL, "C");
  9969. if (use_curses)
  9970. enable_curses();
  9971. #endif
  9972. #ifdef HAVE_LIBUSB
  9973. int err = libusb_init(NULL);
  9974. if (err)
  9975. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  9976. else
  9977. have_libusb = true;
  9978. #endif
  9979. applog(LOG_WARNING, "Started %s", packagename);
  9980. if (cnfbuf) {
  9981. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  9982. switch (fileconf_load) {
  9983. case 0:
  9984. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  9985. applog(LOG_WARNING, "Configuration file could not be used.");
  9986. break;
  9987. case -1:
  9988. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  9989. if (use_curses)
  9990. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  9991. break;
  9992. default:
  9993. break;
  9994. }
  9995. free(cnfbuf);
  9996. cnfbuf = NULL;
  9997. }
  9998. i = strlen(opt_kernel_path) + 2;
  9999. char __kernel_path[i];
  10000. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  10001. opt_kernel_path = __kernel_path;
  10002. if (want_per_device_stats)
  10003. opt_log_output = true;
  10004. #ifdef WANT_CPUMINE
  10005. #ifdef USE_SCRYPT
  10006. if (opt_scrypt)
  10007. set_scrypt_algo(&opt_algo);
  10008. else
  10009. #endif
  10010. if (0 <= opt_bench_algo) {
  10011. double rate = bench_algo_stage3(opt_bench_algo);
  10012. if (!skip_to_bench)
  10013. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  10014. else {
  10015. // Write result to shared memory for parent
  10016. #if defined(WIN32)
  10017. char unique_name[64];
  10018. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  10019. HANDLE map_handle = CreateFileMapping(
  10020. INVALID_HANDLE_VALUE, // use paging file
  10021. NULL, // default security attributes
  10022. PAGE_READWRITE, // read/write access
  10023. 0, // size: high 32-bits
  10024. 4096, // size: low 32-bits
  10025. unique_name // name of map object
  10026. );
  10027. if (NULL != map_handle) {
  10028. void *shared_mem = MapViewOfFile(
  10029. map_handle, // object to map view of
  10030. FILE_MAP_WRITE, // read/write access
  10031. 0, // high offset: map from
  10032. 0, // low offset: beginning
  10033. 0 // default: map entire file
  10034. );
  10035. if (NULL != shared_mem)
  10036. CopyMemory(shared_mem, &rate, sizeof(rate));
  10037. (void)UnmapViewOfFile(shared_mem);
  10038. }
  10039. (void)CloseHandle(map_handle);
  10040. }
  10041. #endif
  10042. }
  10043. exit(0);
  10044. }
  10045. #endif
  10046. bfg_devapi_init();
  10047. drv_detect_all();
  10048. total_devices = total_devices_new;
  10049. devices = devices_new;
  10050. total_devices_new = 0;
  10051. devices_new = NULL;
  10052. if (opt_display_devs) {
  10053. int devcount = 0;
  10054. applog(LOG_ERR, "Devices detected:");
  10055. for (i = 0; i < total_devices; ++i) {
  10056. struct cgpu_info *cgpu = devices[i];
  10057. char buf[0x100];
  10058. if (cgpu->device != cgpu)
  10059. continue;
  10060. if (cgpu->name)
  10061. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  10062. else
  10063. if (cgpu->dev_manufacturer)
  10064. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  10065. else
  10066. if (cgpu->dev_product)
  10067. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  10068. else
  10069. strcpy(buf, " Device");
  10070. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  10071. if (cgpu->dev_serial)
  10072. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  10073. if (cgpu->device_path)
  10074. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  10075. tailsprintf(buf, sizeof(buf), ")");
  10076. _applog(LOG_NOTICE, buf);
  10077. ++devcount;
  10078. }
  10079. quit(0, "%d devices listed", devcount);
  10080. }
  10081. mining_threads = 0;
  10082. for (i = 0; i < total_devices; ++i)
  10083. register_device(devices[i]);
  10084. if (!total_devices) {
  10085. applog(LOG_WARNING, "No devices detected!");
  10086. if (use_curses)
  10087. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  10088. else
  10089. applog(LOG_WARNING, "Waiting for devices");
  10090. }
  10091. if (opt_quit_summary == BQS_DEFAULT)
  10092. {
  10093. if (total_devices < 25)
  10094. opt_quit_summary = BQS_PROCS;
  10095. else
  10096. opt_quit_summary = BQS_DEVS;
  10097. }
  10098. #ifdef HAVE_CURSES
  10099. switch_logsize();
  10100. #endif
  10101. if (!total_pools) {
  10102. applog(LOG_WARNING, "Need to specify at least one pool server.");
  10103. #ifdef HAVE_CURSES
  10104. if (!use_curses || !input_pool(false))
  10105. #endif
  10106. quit(1, "Pool setup failed");
  10107. }
  10108. for (i = 0; i < total_pools; i++) {
  10109. struct pool *pool = pools[i];
  10110. size_t siz;
  10111. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10112. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  10113. if (!pool->rpc_url)
  10114. quit(1, "No URI supplied for pool %u", i);
  10115. if (!pool->rpc_userpass) {
  10116. if (!pool->rpc_user || !pool->rpc_pass)
  10117. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  10118. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10119. pool->rpc_userpass = malloc(siz);
  10120. if (!pool->rpc_userpass)
  10121. quit(1, "Failed to malloc userpass");
  10122. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10123. }
  10124. }
  10125. /* Set the currentpool to pool with priority 0 */
  10126. validate_pool_priorities();
  10127. for (i = 0; i < total_pools; i++) {
  10128. struct pool *pool = pools[i];
  10129. if (!pool->prio)
  10130. currentpool = pool;
  10131. }
  10132. #ifdef HAVE_SYSLOG_H
  10133. if (use_syslog)
  10134. openlog(PACKAGE, LOG_PID, LOG_USER);
  10135. #endif
  10136. #if defined(unix) || defined(__APPLE__)
  10137. if (opt_stderr_cmd)
  10138. fork_monitor();
  10139. #endif // defined(unix)
  10140. mining_thr = calloc(mining_threads, sizeof(thr));
  10141. if (!mining_thr)
  10142. quit(1, "Failed to calloc mining_thr");
  10143. for (i = 0; i < mining_threads; i++) {
  10144. mining_thr[i] = calloc(1, sizeof(*thr));
  10145. if (!mining_thr[i])
  10146. quit(1, "Failed to calloc mining_thr[%d]", i);
  10147. }
  10148. total_control_threads = 6;
  10149. control_thr = calloc(total_control_threads, sizeof(*thr));
  10150. if (!control_thr)
  10151. quit(1, "Failed to calloc control_thr");
  10152. gwsched_thr_id = 0;
  10153. /* Create a unique get work queue */
  10154. getq = tq_new();
  10155. if (!getq)
  10156. quit(1, "Failed to create getq");
  10157. /* We use the getq mutex as the staged lock */
  10158. stgd_lock = &getq->mutex;
  10159. if (opt_benchmark)
  10160. goto begin_bench;
  10161. for (i = 0; i < total_pools; i++) {
  10162. struct pool *pool = pools[i];
  10163. enable_pool(pool);
  10164. pool->idle = true;
  10165. }
  10166. applog(LOG_NOTICE, "Probing for an alive pool");
  10167. do {
  10168. bool still_testing;
  10169. int i;
  10170. /* Look for at least one active pool before starting */
  10171. probe_pools();
  10172. do {
  10173. sleep(1);
  10174. if (pools_active)
  10175. break;
  10176. still_testing = false;
  10177. for (int i = 0; i < total_pools; ++i)
  10178. if (pools[i]->testing)
  10179. still_testing = true;
  10180. } while (still_testing);
  10181. if (!pools_active) {
  10182. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  10183. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  10184. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  10185. for (i = 0; i < total_pools; i++) {
  10186. struct pool *pool;
  10187. pool = pools[i];
  10188. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  10189. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  10190. }
  10191. #ifdef HAVE_CURSES
  10192. if (use_curses) {
  10193. halfdelay(150);
  10194. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  10195. if (getch() != ERR)
  10196. quit(0, "No servers could be used! Exiting.");
  10197. cbreak();
  10198. } else
  10199. #endif
  10200. quit(0, "No servers could be used! Exiting.");
  10201. }
  10202. } while (!pools_active);
  10203. #ifdef USE_SCRYPT
  10204. if (detect_algo == 1 && !opt_scrypt) {
  10205. applog(LOG_NOTICE, "Detected scrypt algorithm");
  10206. opt_scrypt = true;
  10207. }
  10208. #endif
  10209. detect_algo = 0;
  10210. begin_bench:
  10211. total_mhashes_done = 0;
  10212. for (i = 0; i < total_devices; i++) {
  10213. struct cgpu_info *cgpu = devices[i];
  10214. cgpu->rolling = cgpu->total_mhashes = 0;
  10215. }
  10216. cgtime(&total_tv_start);
  10217. cgtime(&total_tv_end);
  10218. miner_started = total_tv_start;
  10219. time_t miner_start_ts = time(NULL);
  10220. if (schedstart.tm.tm_sec)
  10221. localtime_r(&miner_start_ts, &schedstart.tm);
  10222. if (schedstop.tm.tm_sec)
  10223. localtime_r(&miner_start_ts, &schedstop .tm);
  10224. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  10225. // Initialise processors and threads
  10226. k = 0;
  10227. for (i = 0; i < total_devices; ++i) {
  10228. struct cgpu_info *cgpu = devices[i];
  10229. allocate_cgpu(cgpu, &k);
  10230. }
  10231. // Start threads
  10232. for (i = 0; i < total_devices; ++i) {
  10233. struct cgpu_info *cgpu = devices[i];
  10234. start_cgpu(cgpu);
  10235. }
  10236. #ifdef HAVE_OPENCL
  10237. for (i = 0; i < nDevs; i++)
  10238. pause_dynamic_threads(i);
  10239. #endif
  10240. #ifdef WANT_CPUMINE
  10241. applog(LOG_INFO, "%d cpu miner threads started, "
  10242. "using SHA256 '%s' algorithm.",
  10243. opt_n_threads,
  10244. algo_names[opt_algo]);
  10245. #endif
  10246. cgtime(&total_tv_start);
  10247. cgtime(&total_tv_end);
  10248. {
  10249. pthread_t submit_thread;
  10250. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  10251. quit(1, "submit_work thread create failed");
  10252. }
  10253. watchpool_thr_id = 1;
  10254. thr = &control_thr[watchpool_thr_id];
  10255. /* start watchpool thread */
  10256. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  10257. quit(1, "watchpool thread create failed");
  10258. pthread_detach(thr->pth);
  10259. watchdog_thr_id = 2;
  10260. thr = &control_thr[watchdog_thr_id];
  10261. /* start watchdog thread */
  10262. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  10263. quit(1, "watchdog thread create failed");
  10264. pthread_detach(thr->pth);
  10265. #ifdef HAVE_OPENCL
  10266. /* Create reinit gpu thread */
  10267. gpur_thr_id = 3;
  10268. thr = &control_thr[gpur_thr_id];
  10269. thr->q = tq_new();
  10270. if (!thr->q)
  10271. quit(1, "tq_new failed for gpur_thr_id");
  10272. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  10273. quit(1, "reinit_gpu thread create failed");
  10274. #endif
  10275. /* Create API socket thread */
  10276. api_thr_id = 4;
  10277. thr = &control_thr[api_thr_id];
  10278. if (thr_info_create(thr, NULL, api_thread, thr))
  10279. quit(1, "API thread create failed");
  10280. #ifdef USE_LIBMICROHTTPD
  10281. if (httpsrv_port != -1)
  10282. httpsrv_start(httpsrv_port);
  10283. #endif
  10284. #ifdef USE_LIBEVENT
  10285. if (stratumsrv_port != -1)
  10286. stratumsrv_start();
  10287. #endif
  10288. #ifdef HAVE_BFG_HOTPLUG
  10289. if (opt_hotplug && !opt_scrypt)
  10290. hotplug_start();
  10291. #endif
  10292. #ifdef HAVE_CURSES
  10293. /* Create curses input thread for keyboard input. Create this last so
  10294. * that we know all threads are created since this can call kill_work
  10295. * to try and shut down ll previous threads. */
  10296. input_thr_id = 5;
  10297. thr = &control_thr[input_thr_id];
  10298. if (thr_info_create(thr, NULL, input_thread, thr))
  10299. quit(1, "input thread create failed");
  10300. pthread_detach(thr->pth);
  10301. #endif
  10302. /* Just to be sure */
  10303. if (total_control_threads != 6)
  10304. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  10305. /* Once everything is set up, main() becomes the getwork scheduler */
  10306. while (42) {
  10307. int ts, max_staged = opt_queue;
  10308. struct pool *pool, *cp;
  10309. bool lagging = false;
  10310. struct curl_ent *ce;
  10311. struct work *work;
  10312. cp = current_pool();
  10313. // Generally, each processor needs a new work, and all at once during work restarts
  10314. max_staged += mining_threads;
  10315. mutex_lock(stgd_lock);
  10316. ts = __total_staged();
  10317. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  10318. lagging = true;
  10319. /* Wait until hash_pop tells us we need to create more work */
  10320. if (ts > max_staged) {
  10321. staged_full = true;
  10322. pthread_cond_wait(&gws_cond, stgd_lock);
  10323. ts = __total_staged();
  10324. }
  10325. mutex_unlock(stgd_lock);
  10326. if (ts > max_staged)
  10327. continue;
  10328. work = make_work();
  10329. if (lagging && !pool_tset(cp, &cp->lagging)) {
  10330. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  10331. cp->getfail_occasions++;
  10332. total_go++;
  10333. }
  10334. pool = select_pool(lagging);
  10335. retry:
  10336. if (pool->has_stratum) {
  10337. while (!pool->stratum_active || !pool->stratum_notify) {
  10338. struct pool *altpool = select_pool(true);
  10339. if (altpool == pool && pool->has_stratum)
  10340. cgsleep_ms(5000);
  10341. pool = altpool;
  10342. goto retry;
  10343. }
  10344. gen_stratum_work(pool, work);
  10345. applog(LOG_DEBUG, "Generated stratum work");
  10346. stage_work(work);
  10347. continue;
  10348. }
  10349. if (pool->last_work_copy) {
  10350. mutex_lock(&pool->last_work_lock);
  10351. struct work *last_work = pool->last_work_copy;
  10352. if (!last_work)
  10353. {}
  10354. else
  10355. if (can_roll(last_work) && should_roll(last_work)) {
  10356. struct timeval tv_now;
  10357. cgtime(&tv_now);
  10358. free_work(work);
  10359. work = make_clone(pool->last_work_copy);
  10360. mutex_unlock(&pool->last_work_lock);
  10361. roll_work(work);
  10362. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tmpl, tv_now.tv_sec));
  10363. stage_work(work);
  10364. continue;
  10365. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  10366. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  10367. } else {
  10368. free_work(last_work);
  10369. pool->last_work_copy = NULL;
  10370. }
  10371. mutex_unlock(&pool->last_work_lock);
  10372. }
  10373. if (clone_available()) {
  10374. applog(LOG_DEBUG, "Cloned getwork work");
  10375. free_work(work);
  10376. continue;
  10377. }
  10378. if (opt_benchmark) {
  10379. get_benchmark_work(work);
  10380. applog(LOG_DEBUG, "Generated benchmark work");
  10381. stage_work(work);
  10382. continue;
  10383. }
  10384. work->pool = pool;
  10385. ce = pop_curl_entry3(pool, 2);
  10386. /* obtain new work from bitcoin via JSON-RPC */
  10387. if (!get_upstream_work(work, ce->curl)) {
  10388. struct pool *next_pool;
  10389. /* Make sure the pool just hasn't stopped serving
  10390. * requests but is up as we'll keep hammering it */
  10391. push_curl_entry(ce, pool);
  10392. ++pool->seq_getfails;
  10393. pool_died(pool);
  10394. next_pool = select_pool(!opt_fail_only);
  10395. if (pool == next_pool) {
  10396. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  10397. cgsleep_ms(5000);
  10398. } else {
  10399. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  10400. pool = next_pool;
  10401. }
  10402. goto retry;
  10403. }
  10404. if (ts >= max_staged)
  10405. pool_tclear(pool, &pool->lagging);
  10406. if (pool_tclear(pool, &pool->idle))
  10407. pool_resus(pool);
  10408. applog(LOG_DEBUG, "Generated getwork work");
  10409. stage_work(work);
  10410. push_curl_entry(ce, pool);
  10411. }
  10412. return 0;
  10413. }