miner.c 280 KB

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