miner.c 280 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971
  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 LP",
  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. if (++rotating_pool >= total_pools)
  3522. rotating_pool = 0;
  3523. continue;
  3524. }
  3525. if (!pool_unworkable(pool))
  3526. break;
  3527. pool = NULL;
  3528. }
  3529. /* If there are no alive pools with quota, choose according to
  3530. * priority. */
  3531. if (!pool) {
  3532. for (i = 0; i < total_pools; i++) {
  3533. struct pool *tp = priority_pool(i);
  3534. if (!pool_unusable(tp)) {
  3535. pool = tp;
  3536. break;
  3537. }
  3538. }
  3539. }
  3540. /* If still nothing is usable, use the current pool */
  3541. if (!pool)
  3542. pool = cp;
  3543. have_pool:
  3544. if (cp != pool)
  3545. {
  3546. if (!pool_active(pool, false))
  3547. {
  3548. pool_died(pool);
  3549. goto retry;
  3550. }
  3551. pool_tclear(pool, &pool->idle);
  3552. }
  3553. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  3554. return pool;
  3555. }
  3556. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  3557. static const uint64_t diffone = 0xFFFF000000000000ull;
  3558. static double target_diff(const unsigned char *target)
  3559. {
  3560. double targ = 0;
  3561. signed int i;
  3562. for (i = 31; i >= 0; --i)
  3563. targ = (targ * 0x100) + target[i];
  3564. return DIFFEXACTONE / (targ ?: 1);
  3565. }
  3566. /*
  3567. * Calculate the work share difficulty
  3568. */
  3569. static void calc_diff(struct work *work, int known)
  3570. {
  3571. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3572. double difficulty;
  3573. if (!known) {
  3574. work->work_difficulty = target_diff(work->target);
  3575. } else
  3576. work->work_difficulty = known;
  3577. difficulty = work->work_difficulty;
  3578. pool_stats->last_diff = difficulty;
  3579. suffix_string((uint64_t)difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  3580. if (difficulty == pool_stats->min_diff)
  3581. pool_stats->min_diff_count++;
  3582. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3583. pool_stats->min_diff = difficulty;
  3584. pool_stats->min_diff_count = 1;
  3585. }
  3586. if (difficulty == pool_stats->max_diff)
  3587. pool_stats->max_diff_count++;
  3588. else if (difficulty > pool_stats->max_diff) {
  3589. pool_stats->max_diff = difficulty;
  3590. pool_stats->max_diff_count = 1;
  3591. }
  3592. }
  3593. static void get_benchmark_work(struct work *work)
  3594. {
  3595. // Use a random work block pulled from a pool
  3596. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  3597. size_t bench_size = sizeof(*work);
  3598. size_t work_size = sizeof(bench_block);
  3599. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  3600. memset(work, 0, sizeof(*work));
  3601. memcpy(work, &bench_block, min_size);
  3602. work->mandatory = true;
  3603. work->pool = pools[0];
  3604. cgtime(&work->tv_getwork);
  3605. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3606. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3607. calc_diff(work, 0);
  3608. }
  3609. static void wake_gws(void);
  3610. static void update_last_work(struct work *work)
  3611. {
  3612. if (!work->tmpl)
  3613. // Only save GBT jobs, since rollntime isn't coordinated well yet
  3614. return;
  3615. struct pool *pool = work->pool;
  3616. mutex_lock(&pool->last_work_lock);
  3617. if (pool->last_work_copy)
  3618. free_work(pool->last_work_copy);
  3619. pool->last_work_copy = copy_work(work);
  3620. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  3621. mutex_unlock(&pool->last_work_lock);
  3622. }
  3623. static
  3624. void gbt_req_target(json_t *req)
  3625. {
  3626. json_t *j;
  3627. json_t *n;
  3628. if (!request_target_str)
  3629. return;
  3630. j = json_object_get(req, "params");
  3631. if (!j)
  3632. {
  3633. n = json_array();
  3634. if (!n)
  3635. return;
  3636. if (json_object_set_new(req, "params", n))
  3637. goto erradd;
  3638. j = n;
  3639. }
  3640. n = json_array_get(j, 0);
  3641. if (!n)
  3642. {
  3643. n = json_object();
  3644. if (!n)
  3645. return;
  3646. if (json_array_append_new(j, n))
  3647. goto erradd;
  3648. }
  3649. j = n;
  3650. n = json_string(request_target_str);
  3651. if (!n)
  3652. return;
  3653. if (json_object_set_new(j, "target", n))
  3654. goto erradd;
  3655. return;
  3656. erradd:
  3657. json_decref(n);
  3658. }
  3659. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  3660. {
  3661. char *rpc_req;
  3662. clean_work(work);
  3663. switch (proto) {
  3664. case PLP_GETWORK:
  3665. work->getwork_mode = GETWORK_MODE_POOL;
  3666. return strdup(getwork_req);
  3667. case PLP_GETBLOCKTEMPLATE:
  3668. work->getwork_mode = GETWORK_MODE_GBT;
  3669. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  3670. if (!work->tmpl_refcount)
  3671. return NULL;
  3672. work->tmpl = blktmpl_create();
  3673. if (!work->tmpl)
  3674. goto gbtfail2;
  3675. *work->tmpl_refcount = 1;
  3676. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  3677. if (!caps)
  3678. goto gbtfail;
  3679. caps |= GBT_LONGPOLL;
  3680. #if BLKMAKER_VERSION > 1
  3681. if (opt_coinbase_script.sz)
  3682. caps |= GBT_CBVALUE;
  3683. #endif
  3684. json_t *req = blktmpl_request_jansson(caps, lpid);
  3685. if (!req)
  3686. goto gbtfail;
  3687. if (probe)
  3688. gbt_req_target(req);
  3689. rpc_req = json_dumps(req, 0);
  3690. if (!rpc_req)
  3691. goto gbtfail;
  3692. json_decref(req);
  3693. return rpc_req;
  3694. default:
  3695. return NULL;
  3696. }
  3697. return NULL;
  3698. gbtfail:
  3699. blktmpl_free(work->tmpl);
  3700. work->tmpl = NULL;
  3701. gbtfail2:
  3702. free(work->tmpl_refcount);
  3703. work->tmpl_refcount = NULL;
  3704. return NULL;
  3705. }
  3706. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  3707. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  3708. static const char *pool_protocol_name(enum pool_protocol proto)
  3709. {
  3710. switch (proto) {
  3711. case PLP_GETBLOCKTEMPLATE:
  3712. return "getblocktemplate";
  3713. case PLP_GETWORK:
  3714. return "getwork";
  3715. default:
  3716. return "UNKNOWN";
  3717. }
  3718. }
  3719. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  3720. {
  3721. switch (proto) {
  3722. case PLP_GETBLOCKTEMPLATE:
  3723. if (want_getwork)
  3724. return PLP_GETWORK;
  3725. default:
  3726. return PLP_NONE;
  3727. }
  3728. }
  3729. static bool get_upstream_work(struct work *work, CURL *curl)
  3730. {
  3731. struct pool *pool = work->pool;
  3732. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  3733. struct timeval tv_elapsed;
  3734. json_t *val = NULL;
  3735. bool rc = false;
  3736. char *url;
  3737. enum pool_protocol proto;
  3738. char *rpc_req;
  3739. if (pool->proto == PLP_NONE)
  3740. pool->proto = PLP_GETBLOCKTEMPLATE;
  3741. tryagain:
  3742. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  3743. work->pool = pool;
  3744. if (!rpc_req)
  3745. return false;
  3746. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  3747. url = pool->rpc_url;
  3748. cgtime(&work->tv_getwork);
  3749. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  3750. false, &work->rolltime, pool, false);
  3751. pool_stats->getwork_attempts++;
  3752. free(rpc_req);
  3753. if (likely(val)) {
  3754. rc = work_decode(pool, work, val);
  3755. if (unlikely(!rc))
  3756. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  3757. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  3758. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  3759. pool->proto = proto;
  3760. goto tryagain;
  3761. } else
  3762. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  3763. cgtime(&work->tv_getwork_reply);
  3764. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  3765. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  3766. pool_stats->getwork_wait_rolling /= 1.63;
  3767. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  3768. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  3769. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  3770. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  3771. }
  3772. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  3773. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  3774. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  3775. }
  3776. pool_stats->getwork_calls++;
  3777. work->pool = pool;
  3778. work->longpoll = false;
  3779. calc_diff(work, 0);
  3780. total_getworks++;
  3781. pool->getwork_requested++;
  3782. if (rc)
  3783. update_last_work(work);
  3784. if (likely(val))
  3785. json_decref(val);
  3786. return rc;
  3787. }
  3788. #ifdef HAVE_CURSES
  3789. static void disable_curses(void)
  3790. {
  3791. if (curses_active_locked()) {
  3792. use_curses = false;
  3793. curses_active = false;
  3794. leaveok(logwin, false);
  3795. leaveok(statuswin, false);
  3796. leaveok(mainwin, false);
  3797. nocbreak();
  3798. echo();
  3799. delwin(logwin);
  3800. delwin(statuswin);
  3801. delwin(mainwin);
  3802. endwin();
  3803. #ifdef WIN32
  3804. // Move the cursor to after curses output.
  3805. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  3806. CONSOLE_SCREEN_BUFFER_INFO csbi;
  3807. COORD coord;
  3808. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  3809. coord.X = 0;
  3810. coord.Y = csbi.dwSize.Y - 1;
  3811. SetConsoleCursorPosition(hout, coord);
  3812. }
  3813. #endif
  3814. unlock_curses();
  3815. }
  3816. }
  3817. #endif
  3818. static void __kill_work(void)
  3819. {
  3820. struct thr_info *thr;
  3821. int i;
  3822. if (!successful_connect)
  3823. return;
  3824. applog(LOG_INFO, "Received kill message");
  3825. shutting_down = true;
  3826. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  3827. notifier_wake(submit_waiting_notifier);
  3828. #ifdef USE_LIBMICROHTTPD
  3829. httpsrv_stop();
  3830. #endif
  3831. applog(LOG_DEBUG, "Killing off watchpool thread");
  3832. /* Kill the watchpool thread */
  3833. thr = &control_thr[watchpool_thr_id];
  3834. thr_info_cancel(thr);
  3835. applog(LOG_DEBUG, "Killing off watchdog thread");
  3836. /* Kill the watchdog thread */
  3837. thr = &control_thr[watchdog_thr_id];
  3838. thr_info_cancel(thr);
  3839. applog(LOG_DEBUG, "Shutting down mining threads");
  3840. for (i = 0; i < mining_threads; i++) {
  3841. struct cgpu_info *cgpu;
  3842. thr = get_thread(i);
  3843. if (!thr)
  3844. continue;
  3845. cgpu = thr->cgpu;
  3846. if (!cgpu)
  3847. continue;
  3848. if (!cgpu->threads)
  3849. continue;
  3850. cgpu->shutdown = true;
  3851. thr->work_restart = true;
  3852. notifier_wake(thr->notifier);
  3853. notifier_wake(thr->work_restart_notifier);
  3854. }
  3855. sleep(1);
  3856. applog(LOG_DEBUG, "Killing off mining threads");
  3857. /* Kill the mining threads*/
  3858. for (i = 0; i < mining_threads; i++) {
  3859. thr = get_thread(i);
  3860. if (!(thr && thr->cgpu->threads))
  3861. continue;
  3862. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  3863. thr_info_cancel(thr);
  3864. }
  3865. applog(LOG_DEBUG, "Killing off stage thread");
  3866. /* Stop the others */
  3867. thr = &control_thr[stage_thr_id];
  3868. thr_info_cancel(thr);
  3869. applog(LOG_DEBUG, "Killing off API thread");
  3870. thr = &control_thr[api_thr_id];
  3871. thr_info_cancel(thr);
  3872. }
  3873. /* This should be the common exit path */
  3874. void kill_work(void)
  3875. {
  3876. __kill_work();
  3877. quit(0, "Shutdown signal received.");
  3878. }
  3879. static
  3880. #ifdef WIN32
  3881. #ifndef _WIN64
  3882. const
  3883. #endif
  3884. #endif
  3885. char **initial_args;
  3886. void _bfg_clean_up(void);
  3887. void app_restart(void)
  3888. {
  3889. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  3890. __kill_work();
  3891. _bfg_clean_up();
  3892. #if defined(unix) || defined(__APPLE__)
  3893. if (forkpid > 0) {
  3894. kill(forkpid, SIGTERM);
  3895. forkpid = 0;
  3896. }
  3897. #endif
  3898. execv(initial_args[0], initial_args);
  3899. applog(LOG_WARNING, "Failed to restart application");
  3900. }
  3901. static void sighandler(int __maybe_unused sig)
  3902. {
  3903. /* Restore signal handlers so we can still quit if kill_work fails */
  3904. sigaction(SIGTERM, &termhandler, NULL);
  3905. sigaction(SIGINT, &inthandler, NULL);
  3906. kill_work();
  3907. }
  3908. static void start_longpoll(void);
  3909. static void stop_longpoll(void);
  3910. /* Called with pool_lock held. Recruit an extra curl if none are available for
  3911. * this pool. */
  3912. static void recruit_curl(struct pool *pool)
  3913. {
  3914. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  3915. if (unlikely(!ce))
  3916. quit(1, "Failed to calloc in recruit_curl");
  3917. ce->curl = curl_easy_init();
  3918. if (unlikely(!ce->curl))
  3919. quit(1, "Failed to init in recruit_curl");
  3920. LL_PREPEND(pool->curllist, ce);
  3921. pool->curls++;
  3922. }
  3923. /* Grab an available curl if there is one. If not, then recruit extra curls
  3924. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  3925. * and there are already 5 curls in circulation. Limit total number to the
  3926. * number of mining threads per pool as well to prevent blasting a pool during
  3927. * network delays/outages. */
  3928. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  3929. {
  3930. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  3931. bool recruited = false;
  3932. struct curl_ent *ce;
  3933. mutex_lock(&pool->pool_lock);
  3934. retry:
  3935. if (!pool->curls) {
  3936. recruit_curl(pool);
  3937. recruited = true;
  3938. } else if (!pool->curllist) {
  3939. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  3940. if (!blocking) {
  3941. mutex_unlock(&pool->pool_lock);
  3942. return NULL;
  3943. }
  3944. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  3945. goto retry;
  3946. } else {
  3947. recruit_curl(pool);
  3948. recruited = true;
  3949. }
  3950. }
  3951. ce = pool->curllist;
  3952. LL_DELETE(pool->curllist, ce);
  3953. mutex_unlock(&pool->pool_lock);
  3954. if (recruited)
  3955. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  3956. return ce;
  3957. }
  3958. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  3959. {
  3960. return pop_curl_entry3(pool, blocking ? 1 : 0);
  3961. }
  3962. __maybe_unused
  3963. static struct curl_ent *pop_curl_entry(struct pool *pool)
  3964. {
  3965. return pop_curl_entry3(pool, 1);
  3966. }
  3967. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  3968. {
  3969. mutex_lock(&pool->pool_lock);
  3970. if (!ce || !ce->curl)
  3971. quithere(1, "Attempted to add NULL");
  3972. LL_PREPEND(pool->curllist, ce);
  3973. cgtime(&ce->tv);
  3974. pthread_cond_broadcast(&pool->cr_cond);
  3975. mutex_unlock(&pool->pool_lock);
  3976. }
  3977. bool stale_work(struct work *work, bool share);
  3978. static inline bool should_roll(struct work *work)
  3979. {
  3980. struct timeval now;
  3981. time_t expiry;
  3982. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  3983. return false;
  3984. if (stale_work(work, false))
  3985. return false;
  3986. if (work->rolltime > opt_scantime)
  3987. expiry = work->rolltime;
  3988. else
  3989. expiry = opt_scantime;
  3990. expiry = expiry * 2 / 3;
  3991. /* We shouldn't roll if we're unlikely to get one shares' duration
  3992. * work out of doing so */
  3993. cgtime(&now);
  3994. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  3995. return false;
  3996. return true;
  3997. }
  3998. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3999. * reject blocks as invalid. */
  4000. static inline bool can_roll(struct work *work)
  4001. {
  4002. if (work->stratum)
  4003. return false;
  4004. if (!(work->pool && !work->clone))
  4005. return false;
  4006. if (work->tmpl) {
  4007. if (stale_work(work, false))
  4008. return false;
  4009. return blkmk_work_left(work->tmpl);
  4010. }
  4011. return (work->rolltime &&
  4012. work->rolls < 7000 && !stale_work(work, false));
  4013. }
  4014. static void roll_work(struct work *work)
  4015. {
  4016. if (work->tmpl) {
  4017. struct timeval tv_now;
  4018. cgtime(&tv_now);
  4019. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4020. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4021. swap32yes(work->data, work->data, 80 / 4);
  4022. calc_midstate(work);
  4023. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4024. } else {
  4025. uint32_t *work_ntime;
  4026. uint32_t ntime;
  4027. work_ntime = (uint32_t *)(work->data + 68);
  4028. ntime = be32toh(*work_ntime);
  4029. ntime++;
  4030. *work_ntime = htobe32(ntime);
  4031. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4032. }
  4033. local_work++;
  4034. work->rolls++;
  4035. work->blk.nonce = 0;
  4036. /* This is now a different work item so it needs a different ID for the
  4037. * hashtable */
  4038. work->id = total_work++;
  4039. }
  4040. /* Duplicates any dynamically allocated arrays within the work struct to
  4041. * prevent a copied work struct from freeing ram belonging to another struct */
  4042. void __copy_work(struct work *work, const struct work *base_work)
  4043. {
  4044. int id = work->id;
  4045. clean_work(work);
  4046. memcpy(work, base_work, sizeof(struct work));
  4047. /* Keep the unique new id assigned during make_work to prevent copied
  4048. * work from having the same id. */
  4049. work->id = id;
  4050. if (base_work->job_id)
  4051. work->job_id = strdup(base_work->job_id);
  4052. if (base_work->nonce1)
  4053. work->nonce1 = strdup(base_work->nonce1);
  4054. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4055. if (base_work->tmpl) {
  4056. struct pool *pool = work->pool;
  4057. mutex_lock(&pool->pool_lock);
  4058. ++*work->tmpl_refcount;
  4059. mutex_unlock(&pool->pool_lock);
  4060. }
  4061. }
  4062. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4063. * for all dynamically allocated arrays within the struct */
  4064. struct work *copy_work(const struct work *base_work)
  4065. {
  4066. struct work *work = make_work();
  4067. __copy_work(work, base_work);
  4068. return work;
  4069. }
  4070. static struct work *make_clone(struct work *work)
  4071. {
  4072. struct work *work_clone = copy_work(work);
  4073. work_clone->clone = true;
  4074. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4075. work_clone->longpoll = false;
  4076. work_clone->mandatory = false;
  4077. /* Make cloned work appear slightly older to bias towards keeping the
  4078. * master work item which can be further rolled */
  4079. work_clone->tv_staged.tv_sec -= 1;
  4080. return work_clone;
  4081. }
  4082. static void stage_work(struct work *work);
  4083. static bool clone_available(void)
  4084. {
  4085. struct work *work_clone = NULL, *work, *tmp;
  4086. bool cloned = false;
  4087. mutex_lock(stgd_lock);
  4088. if (!staged_rollable)
  4089. goto out_unlock;
  4090. HASH_ITER(hh, staged_work, work, tmp) {
  4091. if (can_roll(work) && should_roll(work)) {
  4092. roll_work(work);
  4093. work_clone = make_clone(work);
  4094. roll_work(work);
  4095. cloned = true;
  4096. break;
  4097. }
  4098. }
  4099. out_unlock:
  4100. mutex_unlock(stgd_lock);
  4101. if (cloned) {
  4102. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4103. stage_work(work_clone);
  4104. }
  4105. return cloned;
  4106. }
  4107. static void pool_died(struct pool *pool)
  4108. {
  4109. if (!pool_tset(pool, &pool->idle)) {
  4110. cgtime(&pool->tv_idle);
  4111. if (pool == current_pool()) {
  4112. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4113. switch_pools(NULL);
  4114. } else
  4115. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4116. }
  4117. }
  4118. bool stale_work(struct work *work, bool share)
  4119. {
  4120. unsigned work_expiry;
  4121. struct pool *pool;
  4122. uint32_t block_id;
  4123. unsigned getwork_delay;
  4124. if (opt_benchmark)
  4125. return false;
  4126. block_id = ((uint32_t*)work->data)[1];
  4127. pool = work->pool;
  4128. /* Technically the rolltime should be correct but some pools
  4129. * advertise a broken expire= that is lower than a meaningful
  4130. * scantime */
  4131. if (work->rolltime >= opt_scantime || work->tmpl)
  4132. work_expiry = work->rolltime;
  4133. else
  4134. work_expiry = opt_expiry;
  4135. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4136. if (work_expiry > max_expiry)
  4137. work_expiry = max_expiry;
  4138. if (share) {
  4139. /* If the share isn't on this pool's latest block, it's stale */
  4140. if (pool->block_id && pool->block_id != block_id)
  4141. {
  4142. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4143. return true;
  4144. }
  4145. /* If the pool doesn't want old shares, then any found in work before
  4146. * the most recent longpoll is stale */
  4147. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4148. {
  4149. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4150. return true;
  4151. }
  4152. } else {
  4153. /* If this work isn't for the latest Bitcoin block, it's stale */
  4154. /* But only care about the current pool if failover-only */
  4155. if (enabled_pools <= 1 || opt_fail_only) {
  4156. if (pool->block_id && block_id != pool->block_id)
  4157. {
  4158. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4159. return true;
  4160. }
  4161. } else {
  4162. if (block_id != current_block_id)
  4163. {
  4164. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4165. return true;
  4166. }
  4167. }
  4168. /* If the pool has asked us to restart since this work, it's stale */
  4169. if (work->work_restart_id != pool->work_restart_id)
  4170. {
  4171. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4172. return true;
  4173. }
  4174. if (pool->has_stratum && work->job_id) {
  4175. bool same_job;
  4176. if (!pool->stratum_active || !pool->stratum_notify) {
  4177. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4178. return true;
  4179. }
  4180. same_job = true;
  4181. cg_rlock(&pool->data_lock);
  4182. if (strcmp(work->job_id, pool->swork.job_id))
  4183. same_job = false;
  4184. cg_runlock(&pool->data_lock);
  4185. if (!same_job) {
  4186. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4187. return true;
  4188. }
  4189. }
  4190. /* Factor in the average getwork delay of this pool, rounding it up to
  4191. * the nearest second */
  4192. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  4193. if (unlikely(work_expiry <= getwork_delay + 5))
  4194. work_expiry = 5;
  4195. else
  4196. work_expiry -= getwork_delay;
  4197. }
  4198. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  4199. if (elapsed_since_staged > work_expiry) {
  4200. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  4201. return true;
  4202. }
  4203. /* If the user only wants strict failover, any work from a pool other than
  4204. * the current one is always considered stale */
  4205. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  4206. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4207. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  4208. return true;
  4209. }
  4210. return false;
  4211. }
  4212. static uint64_t share_diff(const struct work *work)
  4213. {
  4214. uint64_t ret;
  4215. bool new_best = false;
  4216. ret = target_diff(work->hash);
  4217. cg_wlock(&control_lock);
  4218. if (unlikely(ret > best_diff)) {
  4219. new_best = true;
  4220. best_diff = ret;
  4221. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4222. }
  4223. if (unlikely(ret > work->pool->best_diff))
  4224. work->pool->best_diff = ret;
  4225. cg_wunlock(&control_lock);
  4226. if (unlikely(new_best))
  4227. applog(LOG_INFO, "New best share: %s", best_share);
  4228. return ret;
  4229. }
  4230. static void regen_hash(struct work *work)
  4231. {
  4232. hash_data(work->hash, work->data);
  4233. }
  4234. static void rebuild_hash(struct work *work)
  4235. {
  4236. if (opt_scrypt)
  4237. scrypt_regenhash(work);
  4238. else
  4239. regen_hash(work);
  4240. work->share_diff = share_diff(work);
  4241. if (unlikely(work->share_diff >= current_diff)) {
  4242. work->block = true;
  4243. work->pool->solved++;
  4244. found_blocks++;
  4245. work->mandatory = true;
  4246. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  4247. }
  4248. }
  4249. static void submit_discard_share2(const char *reason, struct work *work)
  4250. {
  4251. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  4252. sharelog(reason, work);
  4253. mutex_lock(&stats_lock);
  4254. ++total_stale;
  4255. ++cgpu->stale;
  4256. ++(work->pool->stale_shares);
  4257. total_diff_stale += work->work_difficulty;
  4258. cgpu->diff_stale += work->work_difficulty;
  4259. work->pool->diff_stale += work->work_difficulty;
  4260. mutex_unlock(&stats_lock);
  4261. }
  4262. static void submit_discard_share(struct work *work)
  4263. {
  4264. submit_discard_share2("discard", work);
  4265. }
  4266. struct submit_work_state {
  4267. struct work *work;
  4268. bool resubmit;
  4269. struct curl_ent *ce;
  4270. int failures;
  4271. struct timeval tv_staleexpire;
  4272. char *s;
  4273. struct timeval tv_submit;
  4274. struct submit_work_state *next;
  4275. };
  4276. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  4277. {
  4278. long *p_timeout_us = userp;
  4279. const long max_ms = LONG_MAX / 1000;
  4280. if (max_ms < timeout_ms)
  4281. timeout_ms = max_ms;
  4282. *p_timeout_us = timeout_ms * 1000;
  4283. return 0;
  4284. }
  4285. static void sws_has_ce(struct submit_work_state *sws)
  4286. {
  4287. struct pool *pool = sws->work->pool;
  4288. sws->s = submit_upstream_work_request(sws->work);
  4289. cgtime(&sws->tv_submit);
  4290. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4291. }
  4292. static struct submit_work_state *begin_submission(struct work *work)
  4293. {
  4294. struct pool *pool;
  4295. struct submit_work_state *sws = NULL;
  4296. pool = work->pool;
  4297. sws = malloc(sizeof(*sws));
  4298. *sws = (struct submit_work_state){
  4299. .work = work,
  4300. };
  4301. rebuild_hash(work);
  4302. if (stale_work(work, true)) {
  4303. work->stale = true;
  4304. if (opt_submit_stale)
  4305. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4306. else if (pool->submit_old)
  4307. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4308. else {
  4309. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4310. submit_discard_share(work);
  4311. goto out;
  4312. }
  4313. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4314. }
  4315. if (work->stratum) {
  4316. char *s;
  4317. s = malloc(1024);
  4318. sws->s = s;
  4319. } else {
  4320. /* submit solution to bitcoin via JSON-RPC */
  4321. sws->ce = pop_curl_entry2(pool, false);
  4322. if (sws->ce) {
  4323. sws_has_ce(sws);
  4324. } else {
  4325. sws->next = pool->sws_waiting_on_curl;
  4326. pool->sws_waiting_on_curl = sws;
  4327. if (sws->next)
  4328. applog(LOG_DEBUG, "submit_thread queuing submission");
  4329. else
  4330. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  4331. }
  4332. }
  4333. return sws;
  4334. out:
  4335. free(sws);
  4336. return NULL;
  4337. }
  4338. static bool retry_submission(struct submit_work_state *sws)
  4339. {
  4340. struct work *work = sws->work;
  4341. struct pool *pool = work->pool;
  4342. sws->resubmit = true;
  4343. if ((!work->stale) && stale_work(work, true)) {
  4344. work->stale = true;
  4345. if (opt_submit_stale)
  4346. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  4347. else if (pool->submit_old)
  4348. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  4349. else {
  4350. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  4351. submit_discard_share(work);
  4352. return false;
  4353. }
  4354. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4355. }
  4356. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  4357. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  4358. submit_discard_share(work);
  4359. return false;
  4360. }
  4361. else if (work->stale) {
  4362. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  4363. {
  4364. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  4365. submit_discard_share(work);
  4366. return false;
  4367. }
  4368. }
  4369. /* pause, then restart work-request loop */
  4370. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  4371. cgtime(&sws->tv_submit);
  4372. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4373. return true;
  4374. }
  4375. static void free_sws(struct submit_work_state *sws)
  4376. {
  4377. free(sws->s);
  4378. free_work(sws->work);
  4379. free(sws);
  4380. }
  4381. static void *submit_work_thread(__maybe_unused void *userdata)
  4382. {
  4383. int wip = 0;
  4384. CURLM *curlm;
  4385. long curlm_timeout_us = -1;
  4386. struct timeval curlm_timer;
  4387. struct submit_work_state *sws, **swsp;
  4388. struct submit_work_state *write_sws = NULL;
  4389. unsigned tsreduce = 0;
  4390. pthread_detach(pthread_self());
  4391. RenameThread("submit_work");
  4392. applog(LOG_DEBUG, "Creating extra submit work thread");
  4393. curlm = curl_multi_init();
  4394. curlm_timeout_us = -1;
  4395. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  4396. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  4397. fd_set rfds, wfds, efds;
  4398. int maxfd;
  4399. struct timeval tv_timeout, tv_now;
  4400. int n;
  4401. CURLMsg *cm;
  4402. FD_ZERO(&rfds);
  4403. while (1) {
  4404. mutex_lock(&submitting_lock);
  4405. total_submitting -= tsreduce;
  4406. tsreduce = 0;
  4407. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  4408. notifier_read(submit_waiting_notifier);
  4409. }
  4410. // Receive any new submissions
  4411. while (submit_waiting) {
  4412. struct work *work = submit_waiting;
  4413. DL_DELETE(submit_waiting, work);
  4414. if ( (sws = begin_submission(work)) ) {
  4415. if (sws->ce)
  4416. curl_multi_add_handle(curlm, sws->ce->curl);
  4417. else if (sws->s) {
  4418. sws->next = write_sws;
  4419. write_sws = sws;
  4420. }
  4421. ++wip;
  4422. }
  4423. else {
  4424. --total_submitting;
  4425. free_work(work);
  4426. }
  4427. }
  4428. if (unlikely(shutting_down && !wip))
  4429. break;
  4430. mutex_unlock(&submitting_lock);
  4431. FD_ZERO(&rfds);
  4432. FD_ZERO(&wfds);
  4433. FD_ZERO(&efds);
  4434. tv_timeout.tv_sec = -1;
  4435. // Setup cURL with select
  4436. // Need to call perform to ensure the timeout gets updated
  4437. curl_multi_perform(curlm, &n);
  4438. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  4439. if (curlm_timeout_us >= 0)
  4440. {
  4441. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  4442. reduce_timeout_to(&tv_timeout, &curlm_timer);
  4443. }
  4444. // Setup waiting stratum submissions with select
  4445. for (sws = write_sws; sws; sws = sws->next)
  4446. {
  4447. struct pool *pool = sws->work->pool;
  4448. int fd = pool->sock;
  4449. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  4450. continue;
  4451. FD_SET(fd, &wfds);
  4452. set_maxfd(&maxfd, fd);
  4453. }
  4454. // Setup "submit waiting" notifier with select
  4455. FD_SET(submit_waiting_notifier[0], &rfds);
  4456. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  4457. // Wait for something interesting to happen :)
  4458. cgtime(&tv_now);
  4459. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  4460. FD_ZERO(&rfds);
  4461. continue;
  4462. }
  4463. // Handle any stratum ready-to-write results
  4464. for (swsp = &write_sws; (sws = *swsp); ) {
  4465. struct work *work = sws->work;
  4466. struct pool *pool = work->pool;
  4467. int fd = pool->sock;
  4468. bool sessionid_match;
  4469. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  4470. next_write_sws:
  4471. // TODO: Check if stale, possibly discard etc
  4472. swsp = &sws->next;
  4473. continue;
  4474. }
  4475. cg_rlock(&pool->data_lock);
  4476. // 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
  4477. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  4478. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  4479. cg_runlock(&pool->data_lock);
  4480. if (!sessionid_match)
  4481. {
  4482. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4483. submit_discard_share2("disconnect", work);
  4484. ++tsreduce;
  4485. next_write_sws_del:
  4486. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  4487. FD_CLR(fd, &wfds);
  4488. // Delete sws for this submission, since we're done with it
  4489. *swsp = sws->next;
  4490. free_sws(sws);
  4491. --wip;
  4492. continue;
  4493. }
  4494. char *s = sws->s;
  4495. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  4496. int sshare_id;
  4497. uint32_t nonce;
  4498. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  4499. char noncehex[9];
  4500. char ntimehex[9];
  4501. sshare->work = copy_work(work);
  4502. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  4503. nonce = *((uint32_t *)(work->data + 76));
  4504. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  4505. bin2hex(ntimehex, (void *)&work->data[68], 4);
  4506. mutex_lock(&sshare_lock);
  4507. /* Give the stratum share a unique id */
  4508. sshare_id =
  4509. sshare->id = swork_id++;
  4510. HASH_ADD_INT(stratum_shares, id, sshare);
  4511. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  4512. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  4513. mutex_unlock(&sshare_lock);
  4514. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  4515. if (likely(stratum_send(pool, s, strlen(s)))) {
  4516. if (pool_tclear(pool, &pool->submit_fail))
  4517. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4518. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  4519. goto next_write_sws_del;
  4520. } else if (!pool_tset(pool, &pool->submit_fail)) {
  4521. // Undo stuff
  4522. mutex_lock(&sshare_lock);
  4523. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  4524. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  4525. if (sshare)
  4526. HASH_DEL(stratum_shares, sshare);
  4527. mutex_unlock(&sshare_lock);
  4528. if (sshare)
  4529. {
  4530. free_work(sshare->work);
  4531. free(sshare);
  4532. }
  4533. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  4534. total_ro++;
  4535. pool->remotefail_occasions++;
  4536. if (!sshare)
  4537. goto next_write_sws_del;
  4538. goto next_write_sws;
  4539. }
  4540. }
  4541. // Handle any cURL activities
  4542. curl_multi_perform(curlm, &n);
  4543. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  4544. if (cm->msg == CURLMSG_DONE)
  4545. {
  4546. bool finished;
  4547. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  4548. curl_multi_remove_handle(curlm, cm->easy_handle);
  4549. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  4550. if (!finished) {
  4551. if (retry_submission(sws))
  4552. curl_multi_add_handle(curlm, sws->ce->curl);
  4553. else
  4554. finished = true;
  4555. }
  4556. if (finished) {
  4557. --wip;
  4558. ++tsreduce;
  4559. struct pool *pool = sws->work->pool;
  4560. if (pool->sws_waiting_on_curl) {
  4561. pool->sws_waiting_on_curl->ce = sws->ce;
  4562. sws_has_ce(pool->sws_waiting_on_curl);
  4563. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  4564. curl_multi_add_handle(curlm, sws->ce->curl);
  4565. } else {
  4566. push_curl_entry(sws->ce, sws->work->pool);
  4567. }
  4568. free_sws(sws);
  4569. }
  4570. }
  4571. }
  4572. }
  4573. assert(!write_sws);
  4574. mutex_unlock(&submitting_lock);
  4575. curl_multi_cleanup(curlm);
  4576. applog(LOG_DEBUG, "submit_work thread exiting");
  4577. return NULL;
  4578. }
  4579. /* Find the pool that currently has the highest priority */
  4580. static struct pool *priority_pool(int choice)
  4581. {
  4582. struct pool *ret = NULL;
  4583. int i;
  4584. for (i = 0; i < total_pools; i++) {
  4585. struct pool *pool = pools[i];
  4586. if (pool->prio == choice) {
  4587. ret = pool;
  4588. break;
  4589. }
  4590. }
  4591. if (unlikely(!ret)) {
  4592. applog(LOG_ERR, "WTF No pool %d found!", choice);
  4593. return pools[choice];
  4594. }
  4595. return ret;
  4596. }
  4597. int prioritize_pools(char *param, int *pid)
  4598. {
  4599. char *ptr, *next;
  4600. int i, pr, prio = 0;
  4601. if (total_pools == 0) {
  4602. return MSG_NOPOOL;
  4603. }
  4604. if (param == NULL || *param == '\0') {
  4605. return MSG_MISPID;
  4606. }
  4607. bool pools_changed[total_pools];
  4608. int new_prio[total_pools];
  4609. for (i = 0; i < total_pools; ++i)
  4610. pools_changed[i] = false;
  4611. next = param;
  4612. while (next && *next) {
  4613. ptr = next;
  4614. next = strchr(ptr, ',');
  4615. if (next)
  4616. *(next++) = '\0';
  4617. i = atoi(ptr);
  4618. if (i < 0 || i >= total_pools) {
  4619. *pid = i;
  4620. return MSG_INVPID;
  4621. }
  4622. if (pools_changed[i]) {
  4623. *pid = i;
  4624. return MSG_DUPPID;
  4625. }
  4626. pools_changed[i] = true;
  4627. new_prio[i] = prio++;
  4628. }
  4629. // Only change them if no errors
  4630. for (i = 0; i < total_pools; i++) {
  4631. if (pools_changed[i])
  4632. pools[i]->prio = new_prio[i];
  4633. }
  4634. // In priority order, cycle through the unchanged pools and append them
  4635. for (pr = 0; pr < total_pools; pr++)
  4636. for (i = 0; i < total_pools; i++) {
  4637. if (!pools_changed[i] && pools[i]->prio == pr) {
  4638. pools[i]->prio = prio++;
  4639. pools_changed[i] = true;
  4640. break;
  4641. }
  4642. }
  4643. if (current_pool()->prio)
  4644. switch_pools(NULL);
  4645. return MSG_POOLPRIO;
  4646. }
  4647. void validate_pool_priorities(void)
  4648. {
  4649. // TODO: this should probably do some sort of logging
  4650. int i, j;
  4651. bool used[total_pools];
  4652. bool valid[total_pools];
  4653. for (i = 0; i < total_pools; i++)
  4654. used[i] = valid[i] = false;
  4655. for (i = 0; i < total_pools; i++) {
  4656. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  4657. if (!used[pools[i]->prio]) {
  4658. valid[i] = true;
  4659. used[pools[i]->prio] = true;
  4660. }
  4661. }
  4662. }
  4663. for (i = 0; i < total_pools; i++) {
  4664. if (!valid[i]) {
  4665. for (j = 0; j < total_pools; j++) {
  4666. if (!used[j]) {
  4667. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  4668. pools[i]->prio = j;
  4669. used[j] = true;
  4670. break;
  4671. }
  4672. }
  4673. }
  4674. }
  4675. }
  4676. static void clear_pool_work(struct pool *pool);
  4677. /* Specifies whether we can switch to this pool or not. */
  4678. static bool pool_unusable(struct pool *pool)
  4679. {
  4680. if (pool->idle)
  4681. return true;
  4682. if (pool->enabled != POOL_ENABLED)
  4683. return true;
  4684. return false;
  4685. }
  4686. void switch_pools(struct pool *selected)
  4687. {
  4688. struct pool *pool, *last_pool;
  4689. int i, pool_no, next_pool;
  4690. cg_wlock(&control_lock);
  4691. last_pool = currentpool;
  4692. pool_no = currentpool->pool_no;
  4693. /* Switch selected to pool number 0 and move the rest down */
  4694. if (selected) {
  4695. if (selected->prio != 0) {
  4696. for (i = 0; i < total_pools; i++) {
  4697. pool = pools[i];
  4698. if (pool->prio < selected->prio)
  4699. pool->prio++;
  4700. }
  4701. selected->prio = 0;
  4702. }
  4703. }
  4704. switch (pool_strategy) {
  4705. /* All of these set to the master pool */
  4706. case POOL_BALANCE:
  4707. case POOL_FAILOVER:
  4708. case POOL_LOADBALANCE:
  4709. for (i = 0; i < total_pools; i++) {
  4710. pool = priority_pool(i);
  4711. if (pool_unusable(pool))
  4712. continue;
  4713. pool_no = pool->pool_no;
  4714. break;
  4715. }
  4716. break;
  4717. /* Both of these simply increment and cycle */
  4718. case POOL_ROUNDROBIN:
  4719. case POOL_ROTATE:
  4720. if (selected && !selected->idle) {
  4721. pool_no = selected->pool_no;
  4722. break;
  4723. }
  4724. next_pool = pool_no;
  4725. /* Select the next alive pool */
  4726. for (i = 1; i < total_pools; i++) {
  4727. next_pool++;
  4728. if (next_pool >= total_pools)
  4729. next_pool = 0;
  4730. pool = pools[next_pool];
  4731. if (pool_unusable(pool))
  4732. continue;
  4733. pool_no = next_pool;
  4734. break;
  4735. }
  4736. break;
  4737. default:
  4738. break;
  4739. }
  4740. currentpool = pools[pool_no];
  4741. pool = currentpool;
  4742. cg_wunlock(&control_lock);
  4743. /* Set the lagging flag to avoid pool not providing work fast enough
  4744. * messages in failover only mode since we have to get all fresh work
  4745. * as in restart_threads */
  4746. if (opt_fail_only)
  4747. pool_tset(pool, &pool->lagging);
  4748. if (pool != last_pool)
  4749. {
  4750. pool->block_id = 0;
  4751. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4752. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  4753. if (pool_localgen(pool) || opt_fail_only)
  4754. clear_pool_work(last_pool);
  4755. }
  4756. }
  4757. mutex_lock(&lp_lock);
  4758. pthread_cond_broadcast(&lp_cond);
  4759. mutex_unlock(&lp_lock);
  4760. }
  4761. static void discard_work(struct work *work)
  4762. {
  4763. if (!work->clone && !work->rolls && !work->mined) {
  4764. if (work->pool)
  4765. work->pool->discarded_work++;
  4766. total_discarded++;
  4767. applog(LOG_DEBUG, "Discarded work");
  4768. } else
  4769. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  4770. free_work(work);
  4771. }
  4772. static void wake_gws(void)
  4773. {
  4774. mutex_lock(stgd_lock);
  4775. pthread_cond_signal(&gws_cond);
  4776. mutex_unlock(stgd_lock);
  4777. }
  4778. static void discard_stale(void)
  4779. {
  4780. struct work *work, *tmp;
  4781. int stale = 0;
  4782. mutex_lock(stgd_lock);
  4783. HASH_ITER(hh, staged_work, work, tmp) {
  4784. if (stale_work(work, false)) {
  4785. HASH_DEL(staged_work, work);
  4786. discard_work(work);
  4787. stale++;
  4788. staged_full = false;
  4789. }
  4790. }
  4791. pthread_cond_signal(&gws_cond);
  4792. mutex_unlock(stgd_lock);
  4793. if (stale)
  4794. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  4795. }
  4796. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  4797. {
  4798. bool rv;
  4799. struct timeval tv, orig;
  4800. ldiv_t d;
  4801. d = ldiv(ustime, 1000000);
  4802. tv = (struct timeval){
  4803. .tv_sec = d.quot,
  4804. .tv_usec = d.rem,
  4805. };
  4806. orig = work->tv_staged;
  4807. timersub(&orig, &tv, &work->tv_staged);
  4808. rv = stale_work(work, share);
  4809. work->tv_staged = orig;
  4810. return rv;
  4811. }
  4812. static void restart_threads(void)
  4813. {
  4814. struct pool *cp = current_pool();
  4815. int i;
  4816. struct thr_info *thr;
  4817. /* Artificially set the lagging flag to avoid pool not providing work
  4818. * fast enough messages after every long poll */
  4819. pool_tset(cp, &cp->lagging);
  4820. /* Discard staged work that is now stale */
  4821. discard_stale();
  4822. rd_lock(&mining_thr_lock);
  4823. for (i = 0; i < mining_threads; i++)
  4824. {
  4825. thr = mining_thr[i];
  4826. thr->work_restart = true;
  4827. }
  4828. for (i = 0; i < mining_threads; i++)
  4829. {
  4830. thr = mining_thr[i];
  4831. notifier_wake(thr->work_restart_notifier);
  4832. }
  4833. rd_unlock(&mining_thr_lock);
  4834. }
  4835. static
  4836. void blkhashstr(char *rv, const unsigned char *hash)
  4837. {
  4838. unsigned char hash_swap[32];
  4839. swap256(hash_swap, hash);
  4840. swap32tole(hash_swap, hash_swap, 32 / 4);
  4841. bin2hex(rv, hash_swap, 32);
  4842. }
  4843. static void set_curblock(char *hexstr, unsigned char *hash)
  4844. {
  4845. unsigned char hash_swap[32];
  4846. current_block_id = ((uint32_t*)hash)[0];
  4847. strcpy(current_block, hexstr);
  4848. swap256(hash_swap, hash);
  4849. swap32tole(hash_swap, hash_swap, 32 / 4);
  4850. cg_wlock(&ch_lock);
  4851. block_time = time(NULL);
  4852. __update_block_title(hash_swap);
  4853. free(current_fullhash);
  4854. current_fullhash = malloc(65);
  4855. bin2hex(current_fullhash, hash_swap, 32);
  4856. get_timestamp(blocktime, sizeof(blocktime), block_time);
  4857. cg_wunlock(&ch_lock);
  4858. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  4859. }
  4860. /* Search to see if this string is from a block that has been seen before */
  4861. static bool block_exists(char *hexstr)
  4862. {
  4863. struct block *s;
  4864. rd_lock(&blk_lock);
  4865. HASH_FIND_STR(blocks, hexstr, s);
  4866. rd_unlock(&blk_lock);
  4867. if (s)
  4868. return true;
  4869. return false;
  4870. }
  4871. /* Tests if this work is from a block that has been seen before */
  4872. static inline bool from_existing_block(struct work *work)
  4873. {
  4874. char hexstr[37];
  4875. bool ret;
  4876. bin2hex(hexstr, work->data + 8, 18);
  4877. ret = block_exists(hexstr);
  4878. return ret;
  4879. }
  4880. static int block_sort(struct block *blocka, struct block *blockb)
  4881. {
  4882. return blocka->block_no - blockb->block_no;
  4883. }
  4884. static void set_blockdiff(const struct work *work)
  4885. {
  4886. unsigned char target[32];
  4887. double diff;
  4888. uint64_t diff64;
  4889. real_block_target(target, work->data);
  4890. diff = target_diff(target);
  4891. diff64 = diff;
  4892. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  4893. format_unit2(net_hashrate, sizeof(net_hashrate),
  4894. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  4895. if (unlikely(current_diff != diff))
  4896. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  4897. current_diff = diff;
  4898. }
  4899. static bool test_work_current(struct work *work)
  4900. {
  4901. bool ret = true;
  4902. char hexstr[37];
  4903. if (work->mandatory)
  4904. return ret;
  4905. uint32_t block_id = ((uint32_t*)(work->data))[1];
  4906. /* Hack to work around dud work sneaking into test */
  4907. bin2hex(hexstr, work->data + 8, 18);
  4908. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  4909. goto out_free;
  4910. /* Search to see if this block exists yet and if not, consider it a
  4911. * new block and set the current block details to this one */
  4912. if (!block_exists(hexstr)) {
  4913. struct block *s = calloc(sizeof(struct block), 1);
  4914. int deleted_block = 0;
  4915. ret = false;
  4916. if (unlikely(!s))
  4917. quit (1, "test_work_current OOM");
  4918. strcpy(s->hash, hexstr);
  4919. s->block_no = new_blocks++;
  4920. wr_lock(&blk_lock);
  4921. /* Only keep the last hour's worth of blocks in memory since
  4922. * work from blocks before this is virtually impossible and we
  4923. * want to prevent memory usage from continually rising */
  4924. if (HASH_COUNT(blocks) > 6) {
  4925. struct block *oldblock;
  4926. HASH_SORT(blocks, block_sort);
  4927. oldblock = blocks;
  4928. deleted_block = oldblock->block_no;
  4929. HASH_DEL(blocks, oldblock);
  4930. free(oldblock);
  4931. }
  4932. HASH_ADD_STR(blocks, hash, s);
  4933. set_blockdiff(work);
  4934. wr_unlock(&blk_lock);
  4935. work->pool->block_id = block_id;
  4936. if (deleted_block)
  4937. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  4938. #if BLKMAKER_VERSION > 1
  4939. template_nonce = 0;
  4940. #endif
  4941. set_curblock(hexstr, &work->data[4]);
  4942. if (unlikely(new_blocks == 1))
  4943. goto out_free;
  4944. if (!work->stratum) {
  4945. if (work->longpoll) {
  4946. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  4947. work->pool->pool_no);
  4948. } else if (have_longpoll)
  4949. applog(LOG_NOTICE, "New block detected on network before longpoll");
  4950. else
  4951. applog(LOG_NOTICE, "New block detected on network");
  4952. }
  4953. restart_threads();
  4954. } else {
  4955. bool restart = false;
  4956. struct pool *curpool = NULL;
  4957. if (unlikely(work->pool->block_id != block_id)) {
  4958. bool was_active = work->pool->block_id != 0;
  4959. work->pool->block_id = block_id;
  4960. if (!work->longpoll)
  4961. update_last_work(work);
  4962. if (was_active) { // Pool actively changed block
  4963. if (work->pool == (curpool = current_pool()))
  4964. restart = true;
  4965. if (block_id == current_block_id) {
  4966. // Caught up, only announce if this pool is the one in use
  4967. if (restart)
  4968. applog(LOG_NOTICE, "%s %d caught up to new block",
  4969. work->longpoll ? "Longpoll from pool" : "Pool",
  4970. work->pool->pool_no);
  4971. } else {
  4972. // Switched to a block we know, but not the latest... why?
  4973. // This might detect pools trying to double-spend or 51%,
  4974. // but let's not make any accusations until it's had time
  4975. // in the real world.
  4976. blkhashstr(hexstr, &work->data[4]);
  4977. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  4978. work->longpoll ? "Longpoll from pool" : "Pool",
  4979. work->pool->pool_no,
  4980. hexstr);
  4981. }
  4982. }
  4983. }
  4984. if (work->longpoll) {
  4985. ++work->pool->work_restart_id;
  4986. update_last_work(work);
  4987. if ((!restart) && work->pool == current_pool()) {
  4988. applog(
  4989. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  4990. "Longpoll from pool %d requested work update",
  4991. work->pool->pool_no);
  4992. restart = true;
  4993. }
  4994. }
  4995. if (restart)
  4996. restart_threads();
  4997. }
  4998. work->longpoll = false;
  4999. out_free:
  5000. return ret;
  5001. }
  5002. static int tv_sort(struct work *worka, struct work *workb)
  5003. {
  5004. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5005. }
  5006. static bool work_rollable(struct work *work)
  5007. {
  5008. return (!work->clone && work->rolltime);
  5009. }
  5010. static bool hash_push(struct work *work)
  5011. {
  5012. bool rc = true;
  5013. mutex_lock(stgd_lock);
  5014. if (work_rollable(work))
  5015. staged_rollable++;
  5016. if (likely(!getq->frozen)) {
  5017. HASH_ADD_INT(staged_work, id, work);
  5018. HASH_SORT(staged_work, tv_sort);
  5019. } else
  5020. rc = false;
  5021. pthread_cond_broadcast(&getq->cond);
  5022. mutex_unlock(stgd_lock);
  5023. return rc;
  5024. }
  5025. static void *stage_thread(void *userdata)
  5026. {
  5027. struct thr_info *mythr = userdata;
  5028. bool ok = true;
  5029. #ifndef HAVE_PTHREAD_CANCEL
  5030. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5031. #endif
  5032. RenameThread("stage");
  5033. while (ok) {
  5034. struct work *work = NULL;
  5035. applog(LOG_DEBUG, "Popping work to stage thread");
  5036. work = tq_pop(mythr->q, NULL);
  5037. if (unlikely(!work)) {
  5038. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  5039. ok = false;
  5040. break;
  5041. }
  5042. work->work_restart_id = work->pool->work_restart_id;
  5043. test_work_current(work);
  5044. applog(LOG_DEBUG, "Pushing work to getwork queue (queued=%c)", work->queued?'Y':'N');
  5045. if (unlikely(!hash_push(work))) {
  5046. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  5047. continue;
  5048. }
  5049. }
  5050. tq_freeze(mythr->q);
  5051. return NULL;
  5052. }
  5053. static void stage_work(struct work *work)
  5054. {
  5055. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  5056. work->work_restart_id = work->pool->work_restart_id;
  5057. work->pool->last_work_time = time(NULL);
  5058. cgtime(&work->pool->tv_last_work_time);
  5059. test_work_current(work);
  5060. hash_push(work);
  5061. }
  5062. #ifdef HAVE_CURSES
  5063. int curses_int(const char *query)
  5064. {
  5065. int ret;
  5066. char *cvar;
  5067. cvar = curses_input(query);
  5068. ret = atoi(cvar);
  5069. free(cvar);
  5070. return ret;
  5071. }
  5072. #endif
  5073. #ifdef HAVE_CURSES
  5074. static bool input_pool(bool live);
  5075. #endif
  5076. #ifdef HAVE_CURSES
  5077. static void display_pool_summary(struct pool *pool)
  5078. {
  5079. double efficiency = 0.0;
  5080. char xfer[17], bw[19];
  5081. int pool_secs;
  5082. if (curses_active_locked()) {
  5083. wlog("Pool: %s\n", pool->rpc_url);
  5084. if (pool->solved)
  5085. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5086. if (!pool->has_stratum)
  5087. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5088. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5089. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5090. wlog(" Accepted shares: %d\n", pool->accepted);
  5091. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5092. pool->rejected, pool->stale_shares,
  5093. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5094. );
  5095. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5096. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5097. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5098. wlog(" Network transfer: %s (%s)\n",
  5099. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5100. (float)pool->cgminer_pool_stats.net_bytes_received,
  5101. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5102. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5103. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5104. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5105. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5106. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5107. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5108. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5109. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5110. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5111. unlock_curses();
  5112. }
  5113. }
  5114. #endif
  5115. /* We can't remove the memory used for this struct pool because there may
  5116. * still be work referencing it. We just remove it from the pools list */
  5117. void remove_pool(struct pool *pool)
  5118. {
  5119. int i, last_pool = total_pools - 1;
  5120. struct pool *other;
  5121. /* Boost priority of any lower prio than this one */
  5122. for (i = 0; i < total_pools; i++) {
  5123. other = pools[i];
  5124. if (other->prio > pool->prio)
  5125. other->prio--;
  5126. }
  5127. if (pool->pool_no < last_pool) {
  5128. /* Swap the last pool for this one */
  5129. (pools[last_pool])->pool_no = pool->pool_no;
  5130. pools[pool->pool_no] = pools[last_pool];
  5131. }
  5132. /* Give it an invalid number */
  5133. pool->pool_no = total_pools;
  5134. pool->removed = true;
  5135. pool->has_stratum = false;
  5136. total_pools--;
  5137. }
  5138. /* add a mutex if this needs to be thread safe in the future */
  5139. static struct JE {
  5140. char *buf;
  5141. struct JE *next;
  5142. } *jedata = NULL;
  5143. static void json_escape_free()
  5144. {
  5145. struct JE *jeptr = jedata;
  5146. struct JE *jenext;
  5147. jedata = NULL;
  5148. while (jeptr) {
  5149. jenext = jeptr->next;
  5150. free(jeptr->buf);
  5151. free(jeptr);
  5152. jeptr = jenext;
  5153. }
  5154. }
  5155. static char *json_escape(char *str)
  5156. {
  5157. struct JE *jeptr;
  5158. char *buf, *ptr;
  5159. /* 2x is the max, may as well just allocate that */
  5160. ptr = buf = malloc(strlen(str) * 2 + 1);
  5161. jeptr = malloc(sizeof(*jeptr));
  5162. jeptr->buf = buf;
  5163. jeptr->next = jedata;
  5164. jedata = jeptr;
  5165. while (*str) {
  5166. if (*str == '\\' || *str == '"')
  5167. *(ptr++) = '\\';
  5168. *(ptr++) = *(str++);
  5169. }
  5170. *ptr = '\0';
  5171. return buf;
  5172. }
  5173. void _write_config_temps(FILE *fcfg, const char *configname, size_t settingoffset, size_t defoffset)
  5174. {
  5175. int i, commas;
  5176. int *setp, allset;
  5177. uint8_t *defp;
  5178. for (i = 0; ; ++i)
  5179. {
  5180. if (i == total_devices)
  5181. // All defaults
  5182. return;
  5183. setp = ((void*)devices[i]) + settingoffset;
  5184. defp = ((void*)devices[i]) + defoffset;
  5185. allset = *setp;
  5186. if (*setp != *defp)
  5187. break;
  5188. }
  5189. fprintf(fcfg, ",\n\"%s\" : \"", configname);
  5190. for (i = 1; ; ++i)
  5191. {
  5192. if (i == total_devices)
  5193. {
  5194. // All the same
  5195. fprintf(fcfg, "%d\"", allset);
  5196. return;
  5197. }
  5198. setp = ((void*)devices[i]) + settingoffset;
  5199. if (allset != *setp)
  5200. break;
  5201. }
  5202. commas = 0;
  5203. for (i = 0; i < total_devices; ++i)
  5204. {
  5205. setp = ((void*)devices[i]) + settingoffset;
  5206. defp = ((void*)devices[i]) + defoffset;
  5207. if (*setp != *defp)
  5208. {
  5209. for ( ; commas; --commas)
  5210. fputs(",", fcfg);
  5211. fprintf(fcfg, "%d", *setp);
  5212. }
  5213. ++commas;
  5214. }
  5215. fputs("\"", fcfg);
  5216. }
  5217. #define write_config_temps(fcfg, configname, settingname) \
  5218. _write_config_temps(fcfg, configname, offsetof(struct cgpu_info, settingname), offsetof(struct cgpu_info, settingname ## _default))
  5219. void write_config(FILE *fcfg)
  5220. {
  5221. int i;
  5222. /* Write pool values */
  5223. fputs("{\n\"pools\" : [", fcfg);
  5224. for(i = 0; i < total_pools; i++) {
  5225. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  5226. if (pools[i]->rpc_proxy)
  5227. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  5228. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  5229. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pools[i]->rpc_pass));
  5230. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pools[i]->prio);
  5231. if (pools[i]->force_rollntime)
  5232. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pools[i]->force_rollntime);
  5233. fprintf(fcfg, "\n\t}");
  5234. }
  5235. fputs("\n]\n", fcfg);
  5236. write_config_temps(fcfg, "temp-cutoff", cutofftemp);
  5237. write_config_temps(fcfg, "temp-target", targettemp);
  5238. #ifdef HAVE_OPENCL
  5239. if (nDevs) {
  5240. /* Write GPU device values */
  5241. fputs(",\n\"intensity\" : \"", fcfg);
  5242. for(i = 0; i < nDevs; i++)
  5243. {
  5244. if (i > 0)
  5245. fputc(',', fcfg);
  5246. if (gpus[i].dynamic)
  5247. fputc('d', fcfg);
  5248. else
  5249. fprintf(fcfg, "%d", gpus[i].intensity);
  5250. }
  5251. fputs("\",\n\"vectors\" : \"", fcfg);
  5252. for(i = 0; i < nDevs; i++)
  5253. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5254. gpus[i].vwidth);
  5255. fputs("\",\n\"worksize\" : \"", fcfg);
  5256. for(i = 0; i < nDevs; i++)
  5257. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5258. (int)gpus[i].work_size);
  5259. fputs("\",\n\"kernel\" : \"", fcfg);
  5260. for(i = 0; i < nDevs; i++) {
  5261. fprintf(fcfg, "%s", i > 0 ? "," : "");
  5262. switch (gpus[i].kernel) {
  5263. case KL_NONE: // Shouldn't happen
  5264. break;
  5265. case KL_POCLBM:
  5266. fprintf(fcfg, "poclbm");
  5267. break;
  5268. case KL_PHATK:
  5269. fprintf(fcfg, "phatk");
  5270. break;
  5271. case KL_DIAKGCN:
  5272. fprintf(fcfg, "diakgcn");
  5273. break;
  5274. case KL_DIABLO:
  5275. fprintf(fcfg, "diablo");
  5276. break;
  5277. case KL_SCRYPT:
  5278. fprintf(fcfg, "scrypt");
  5279. break;
  5280. }
  5281. }
  5282. #ifdef USE_SCRYPT
  5283. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  5284. for(i = 0; i < nDevs; i++)
  5285. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5286. (int)gpus[i].opt_lg);
  5287. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  5288. for(i = 0; i < nDevs; i++)
  5289. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5290. (int)gpus[i].opt_tc);
  5291. fputs("\",\n\"shaders\" : \"", fcfg);
  5292. for(i = 0; i < nDevs; i++)
  5293. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5294. (int)gpus[i].shaders);
  5295. #endif
  5296. #ifdef HAVE_ADL
  5297. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  5298. for(i = 0; i < nDevs; i++)
  5299. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  5300. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  5301. for(i = 0; i < nDevs; i++)
  5302. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  5303. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  5304. for(i = 0; i < nDevs; i++)
  5305. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  5306. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  5307. for(i = 0; i < nDevs; i++)
  5308. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  5309. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  5310. for(i = 0; i < nDevs; i++)
  5311. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  5312. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  5313. for(i = 0; i < nDevs; i++)
  5314. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  5315. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  5316. for(i = 0; i < nDevs; i++)
  5317. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  5318. #endif
  5319. fputs("\"", fcfg);
  5320. }
  5321. #endif
  5322. #ifdef HAVE_ADL
  5323. if (opt_reorder)
  5324. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  5325. #endif
  5326. #ifdef WANT_CPUMINE
  5327. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  5328. #endif
  5329. /* Simple bool and int options */
  5330. struct opt_table *opt;
  5331. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5332. char *p, *name = strdup(opt->names);
  5333. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5334. if (p[1] != '-')
  5335. continue;
  5336. if (opt->type & OPT_NOARG &&
  5337. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5338. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  5339. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5340. if (opt->type & OPT_HASARG &&
  5341. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5342. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5343. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5344. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  5345. opt->desc != opt_hidden &&
  5346. 0 <= *(int *)opt->u.arg)
  5347. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5348. }
  5349. }
  5350. /* Special case options */
  5351. if (request_target_str)
  5352. {
  5353. if (request_pdiff == (long)request_pdiff)
  5354. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  5355. else
  5356. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  5357. }
  5358. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  5359. if (pool_strategy == POOL_BALANCE)
  5360. fputs(",\n\"balance\" : true", fcfg);
  5361. if (pool_strategy == POOL_LOADBALANCE)
  5362. fputs(",\n\"load-balance\" : true", fcfg);
  5363. if (pool_strategy == POOL_ROUNDROBIN)
  5364. fputs(",\n\"round-robin\" : true", fcfg);
  5365. if (pool_strategy == POOL_ROTATE)
  5366. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5367. #if defined(unix) || defined(__APPLE__)
  5368. if (opt_stderr_cmd && *opt_stderr_cmd)
  5369. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  5370. #endif // defined(unix)
  5371. if (opt_kernel_path && *opt_kernel_path) {
  5372. char *kpath = strdup(opt_kernel_path);
  5373. if (kpath[strlen(kpath)-1] == '/')
  5374. kpath[strlen(kpath)-1] = 0;
  5375. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  5376. free(kpath);
  5377. }
  5378. if (schedstart.enable)
  5379. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5380. if (schedstop.enable)
  5381. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5382. if (opt_socks_proxy && *opt_socks_proxy)
  5383. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  5384. // We can only remove devices or disable them by default, but not both...
  5385. if (!(opt_removedisabled && opt_devs_enabled))
  5386. {
  5387. // Don't need to remove any, so we can set defaults here
  5388. for (i = 0; i < total_devices; ++i)
  5389. if (devices[i]->deven == DEV_DISABLED)
  5390. {
  5391. // At least one device is in fact disabled, so include device params
  5392. fprintf(fcfg, ",\n\"device\" : [");
  5393. bool first = true;
  5394. for (i = 0; i < total_devices; ++i)
  5395. if (devices[i]->deven != DEV_DISABLED)
  5396. {
  5397. fprintf(fcfg, "%s\n\t%d", first ? "" : ",", i);
  5398. first = false;
  5399. }
  5400. fprintf(fcfg, "\n]");
  5401. break;
  5402. }
  5403. }
  5404. else
  5405. if (opt_devs_enabled) {
  5406. // Mark original device params and remove-disabled
  5407. fprintf(fcfg, ",\n\"device\" : [");
  5408. bool first = true;
  5409. for (i = 0; i < MAX_DEVICES; i++) {
  5410. if (devices_enabled[i]) {
  5411. fprintf(fcfg, "%s\n\t%d", first ? "" : ",", i);
  5412. first = false;
  5413. }
  5414. }
  5415. fprintf(fcfg, "\n]");
  5416. fprintf(fcfg, ",\n\"remove-disabled\" : true");
  5417. }
  5418. if (opt_api_allow)
  5419. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  5420. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  5421. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  5422. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  5423. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  5424. if (*opt_api_mcast_des)
  5425. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  5426. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  5427. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  5428. if (opt_api_groups)
  5429. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  5430. if (opt_icarus_options)
  5431. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  5432. if (opt_icarus_timing)
  5433. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  5434. fputs("\n}\n", fcfg);
  5435. json_escape_free();
  5436. }
  5437. void zero_bestshare(void)
  5438. {
  5439. int i;
  5440. best_diff = 0;
  5441. memset(best_share, 0, 8);
  5442. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5443. for (i = 0; i < total_pools; i++) {
  5444. struct pool *pool = pools[i];
  5445. pool->best_diff = 0;
  5446. }
  5447. }
  5448. void zero_stats(void)
  5449. {
  5450. int i;
  5451. applog(LOG_DEBUG, "Zeroing stats");
  5452. cgtime(&total_tv_start);
  5453. miner_started = total_tv_start;
  5454. total_mhashes_done = 0;
  5455. total_getworks = 0;
  5456. total_accepted = 0;
  5457. total_rejected = 0;
  5458. hw_errors = 0;
  5459. total_stale = 0;
  5460. total_discarded = 0;
  5461. total_bytes_rcvd = total_bytes_sent = 0;
  5462. new_blocks = 0;
  5463. local_work = 0;
  5464. total_go = 0;
  5465. total_ro = 0;
  5466. total_secs = 1.0;
  5467. total_diff1 = 0;
  5468. total_bad_nonces = 0;
  5469. found_blocks = 0;
  5470. total_diff_accepted = 0;
  5471. total_diff_rejected = 0;
  5472. total_diff_stale = 0;
  5473. #ifdef HAVE_CURSES
  5474. awidth = rwidth = swidth = hwwidth = 1;
  5475. #endif
  5476. for (i = 0; i < total_pools; i++) {
  5477. struct pool *pool = pools[i];
  5478. pool->getwork_requested = 0;
  5479. pool->accepted = 0;
  5480. pool->rejected = 0;
  5481. pool->solved = 0;
  5482. pool->getwork_requested = 0;
  5483. pool->stale_shares = 0;
  5484. pool->discarded_work = 0;
  5485. pool->getfail_occasions = 0;
  5486. pool->remotefail_occasions = 0;
  5487. pool->last_share_time = 0;
  5488. pool->diff1 = 0;
  5489. pool->diff_accepted = 0;
  5490. pool->diff_rejected = 0;
  5491. pool->diff_stale = 0;
  5492. pool->last_share_diff = 0;
  5493. pool->cgminer_stats.start_tv = total_tv_start;
  5494. pool->cgminer_stats.getwork_calls = 0;
  5495. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5496. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5497. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5498. pool->cgminer_pool_stats.getwork_calls = 0;
  5499. pool->cgminer_pool_stats.getwork_attempts = 0;
  5500. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5501. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  5502. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  5503. pool->cgminer_pool_stats.min_diff = 0;
  5504. pool->cgminer_pool_stats.max_diff = 0;
  5505. pool->cgminer_pool_stats.min_diff_count = 0;
  5506. pool->cgminer_pool_stats.max_diff_count = 0;
  5507. pool->cgminer_pool_stats.times_sent = 0;
  5508. pool->cgminer_pool_stats.bytes_sent = 0;
  5509. pool->cgminer_pool_stats.net_bytes_sent = 0;
  5510. pool->cgminer_pool_stats.times_received = 0;
  5511. pool->cgminer_pool_stats.bytes_received = 0;
  5512. pool->cgminer_pool_stats.net_bytes_received = 0;
  5513. }
  5514. zero_bestshare();
  5515. for (i = 0; i < total_devices; ++i) {
  5516. struct cgpu_info *cgpu = get_devices(i);
  5517. mutex_lock(&hash_lock);
  5518. cgpu->total_mhashes = 0;
  5519. cgpu->accepted = 0;
  5520. cgpu->rejected = 0;
  5521. cgpu->stale = 0;
  5522. cgpu->hw_errors = 0;
  5523. cgpu->utility = 0.0;
  5524. cgpu->utility_diff1 = 0;
  5525. cgpu->last_share_pool_time = 0;
  5526. cgpu->bad_nonces = 0;
  5527. cgpu->diff1 = 0;
  5528. cgpu->diff_accepted = 0;
  5529. cgpu->diff_rejected = 0;
  5530. cgpu->diff_stale = 0;
  5531. cgpu->last_share_diff = 0;
  5532. cgpu->thread_fail_init_count = 0;
  5533. cgpu->thread_zero_hash_count = 0;
  5534. cgpu->thread_fail_queue_count = 0;
  5535. cgpu->dev_sick_idle_60_count = 0;
  5536. cgpu->dev_dead_idle_600_count = 0;
  5537. cgpu->dev_nostart_count = 0;
  5538. cgpu->dev_over_heat_count = 0;
  5539. cgpu->dev_thermal_cutoff_count = 0;
  5540. cgpu->dev_comms_error_count = 0;
  5541. cgpu->dev_throttle_count = 0;
  5542. cgpu->cgminer_stats.start_tv = total_tv_start;
  5543. cgpu->cgminer_stats.getwork_calls = 0;
  5544. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5545. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5546. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5547. mutex_unlock(&hash_lock);
  5548. }
  5549. }
  5550. #ifdef HAVE_CURSES
  5551. static void display_pools(void)
  5552. {
  5553. struct pool *pool;
  5554. int selected, i, j;
  5555. char input;
  5556. opt_loginput = true;
  5557. immedok(logwin, true);
  5558. clear_logwin();
  5559. updated:
  5560. for (j = 0; j < total_pools; j++) {
  5561. for (i = 0; i < total_pools; i++) {
  5562. pool = pools[i];
  5563. if (pool->prio != j)
  5564. continue;
  5565. if (pool == current_pool())
  5566. wattron(logwin, A_BOLD);
  5567. if (pool->enabled != POOL_ENABLED)
  5568. wattron(logwin, A_DIM);
  5569. wlogprint("%d: ", pool->prio);
  5570. switch (pool->enabled) {
  5571. case POOL_ENABLED:
  5572. wlogprint("Enabled ");
  5573. break;
  5574. case POOL_DISABLED:
  5575. wlogprint("Disabled ");
  5576. break;
  5577. case POOL_REJECTING:
  5578. wlogprint("Rejectin ");
  5579. break;
  5580. }
  5581. if (pool->idle)
  5582. wlogprint("Dead ");
  5583. else
  5584. if (pool->has_stratum)
  5585. wlogprint("Strtm");
  5586. else
  5587. if (pool->lp_url && pool->proto != pool->lp_proto)
  5588. wlogprint("Mixed");
  5589. else
  5590. switch (pool->proto) {
  5591. case PLP_GETBLOCKTEMPLATE:
  5592. wlogprint(" GBT ");
  5593. break;
  5594. case PLP_GETWORK:
  5595. wlogprint("GWork");
  5596. break;
  5597. default:
  5598. wlogprint("Alive");
  5599. }
  5600. wlogprint(" Pool %d: %s User:%s\n",
  5601. pool->pool_no,
  5602. pool->rpc_url, pool->rpc_user);
  5603. wattroff(logwin, A_BOLD | A_DIM);
  5604. break; //for (i = 0; i < total_pools; i++)
  5605. }
  5606. }
  5607. retry:
  5608. wlogprint("\nCurrent pool management strategy: %s\n",
  5609. strategies[pool_strategy].s);
  5610. if (pool_strategy == POOL_ROTATE)
  5611. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  5612. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  5613. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool [P]rioritize pool\n");
  5614. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  5615. wlogprint("Or press any other key to continue\n");
  5616. logwin_update();
  5617. input = getch();
  5618. if (!strncasecmp(&input, "a", 1)) {
  5619. input_pool(true);
  5620. goto updated;
  5621. } else if (!strncasecmp(&input, "r", 1)) {
  5622. if (total_pools <= 1) {
  5623. wlogprint("Cannot remove last pool");
  5624. goto retry;
  5625. }
  5626. selected = curses_int("Select pool number");
  5627. if (selected < 0 || selected >= total_pools) {
  5628. wlogprint("Invalid selection\n");
  5629. goto retry;
  5630. }
  5631. pool = pools[selected];
  5632. if (pool == current_pool())
  5633. switch_pools(NULL);
  5634. if (pool == current_pool()) {
  5635. wlogprint("Unable to remove pool due to activity\n");
  5636. goto retry;
  5637. }
  5638. disable_pool(pool);
  5639. remove_pool(pool);
  5640. goto updated;
  5641. } else if (!strncasecmp(&input, "s", 1)) {
  5642. selected = curses_int("Select pool number");
  5643. if (selected < 0 || selected >= total_pools) {
  5644. wlogprint("Invalid selection\n");
  5645. goto retry;
  5646. }
  5647. pool = pools[selected];
  5648. enable_pool(pool);
  5649. switch_pools(pool);
  5650. goto updated;
  5651. } else if (!strncasecmp(&input, "d", 1)) {
  5652. if (enabled_pools <= 1) {
  5653. wlogprint("Cannot disable last pool");
  5654. goto retry;
  5655. }
  5656. selected = curses_int("Select pool number");
  5657. if (selected < 0 || selected >= total_pools) {
  5658. wlogprint("Invalid selection\n");
  5659. goto retry;
  5660. }
  5661. pool = pools[selected];
  5662. disable_pool(pool);
  5663. if (pool == current_pool())
  5664. switch_pools(NULL);
  5665. goto updated;
  5666. } else if (!strncasecmp(&input, "e", 1)) {
  5667. selected = curses_int("Select pool number");
  5668. if (selected < 0 || selected >= total_pools) {
  5669. wlogprint("Invalid selection\n");
  5670. goto retry;
  5671. }
  5672. pool = pools[selected];
  5673. enable_pool(pool);
  5674. if (pool->prio < current_pool()->prio)
  5675. switch_pools(pool);
  5676. goto updated;
  5677. } else if (!strncasecmp(&input, "c", 1)) {
  5678. for (i = 0; i <= TOP_STRATEGY; i++)
  5679. wlogprint("%d: %s\n", i, strategies[i].s);
  5680. selected = curses_int("Select strategy number type");
  5681. if (selected < 0 || selected > TOP_STRATEGY) {
  5682. wlogprint("Invalid selection\n");
  5683. goto retry;
  5684. }
  5685. if (selected == POOL_ROTATE) {
  5686. opt_rotate_period = curses_int("Select interval in minutes");
  5687. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  5688. opt_rotate_period = 0;
  5689. wlogprint("Invalid selection\n");
  5690. goto retry;
  5691. }
  5692. }
  5693. pool_strategy = selected;
  5694. switch_pools(NULL);
  5695. goto updated;
  5696. } else if (!strncasecmp(&input, "i", 1)) {
  5697. selected = curses_int("Select pool number");
  5698. if (selected < 0 || selected >= total_pools) {
  5699. wlogprint("Invalid selection\n");
  5700. goto retry;
  5701. }
  5702. pool = pools[selected];
  5703. display_pool_summary(pool);
  5704. goto retry;
  5705. } else if (!strncasecmp(&input, "f", 1)) {
  5706. opt_fail_only ^= true;
  5707. goto updated;
  5708. } else if (!strncasecmp(&input, "p", 1)) {
  5709. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  5710. int res = prioritize_pools(prilist, &i);
  5711. free(prilist);
  5712. switch (res) {
  5713. case MSG_NOPOOL:
  5714. wlogprint("No pools\n");
  5715. goto retry;
  5716. case MSG_MISPID:
  5717. wlogprint("Missing pool id parameter\n");
  5718. goto retry;
  5719. case MSG_INVPID:
  5720. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  5721. goto retry;
  5722. case MSG_DUPPID:
  5723. wlogprint("Duplicate pool specified %d\n", i);
  5724. goto retry;
  5725. case MSG_POOLPRIO:
  5726. default:
  5727. goto updated;
  5728. }
  5729. } else
  5730. clear_logwin();
  5731. immedok(logwin, false);
  5732. opt_loginput = false;
  5733. }
  5734. static const char *summary_detail_level_str(void)
  5735. {
  5736. if (opt_compact)
  5737. return "compact";
  5738. if (opt_show_procs)
  5739. return "processors";
  5740. return "devices";
  5741. }
  5742. static void display_options(void)
  5743. {
  5744. int selected;
  5745. char input;
  5746. opt_loginput = true;
  5747. immedok(logwin, true);
  5748. retry:
  5749. clear_logwin();
  5750. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  5751. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  5752. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  5753. "[L]og interval:%d\n[Z]ero statistics\n",
  5754. opt_debug_console ? "on" : "off",
  5755. want_per_device_stats? "on" : "off",
  5756. opt_quiet ? "on" : "off",
  5757. opt_log_output ? "on" : "off",
  5758. opt_protocol ? "on" : "off",
  5759. opt_worktime ? "on" : "off",
  5760. summary_detail_level_str(),
  5761. opt_log_interval);
  5762. wlogprint("Select an option or any other key to return\n");
  5763. logwin_update();
  5764. input = getch();
  5765. if (!strncasecmp(&input, "q", 1)) {
  5766. opt_quiet ^= true;
  5767. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  5768. goto retry;
  5769. } else if (!strncasecmp(&input, "v", 1)) {
  5770. opt_log_output ^= true;
  5771. if (opt_log_output)
  5772. opt_quiet = false;
  5773. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  5774. goto retry;
  5775. } else if (!strncasecmp(&input, "n", 1)) {
  5776. opt_log_output = false;
  5777. opt_debug_console = false;
  5778. opt_quiet = false;
  5779. opt_protocol = false;
  5780. opt_compact = false;
  5781. opt_show_procs = false;
  5782. devsummaryYOffset = 0;
  5783. want_per_device_stats = false;
  5784. wlogprint("Output mode reset to normal\n");
  5785. switch_logsize();
  5786. goto retry;
  5787. } else if (!strncasecmp(&input, "d", 1)) {
  5788. opt_debug = true;
  5789. opt_debug_console ^= true;
  5790. opt_log_output = opt_debug_console;
  5791. if (opt_debug_console)
  5792. opt_quiet = false;
  5793. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  5794. goto retry;
  5795. } else if (!strncasecmp(&input, "m", 1)) {
  5796. if (opt_compact)
  5797. opt_compact = false;
  5798. else
  5799. if (!opt_show_procs)
  5800. opt_show_procs = true;
  5801. else
  5802. {
  5803. opt_compact = true;
  5804. opt_show_procs = false;
  5805. devsummaryYOffset = 0;
  5806. }
  5807. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  5808. switch_logsize();
  5809. goto retry;
  5810. } else if (!strncasecmp(&input, "p", 1)) {
  5811. want_per_device_stats ^= true;
  5812. opt_log_output = want_per_device_stats;
  5813. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  5814. goto retry;
  5815. } else if (!strncasecmp(&input, "r", 1)) {
  5816. opt_protocol ^= true;
  5817. if (opt_protocol)
  5818. opt_quiet = false;
  5819. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  5820. goto retry;
  5821. } else if (!strncasecmp(&input, "c", 1))
  5822. clear_logwin();
  5823. else if (!strncasecmp(&input, "l", 1)) {
  5824. selected = curses_int("Interval in seconds");
  5825. if (selected < 0 || selected > 9999) {
  5826. wlogprint("Invalid selection\n");
  5827. goto retry;
  5828. }
  5829. opt_log_interval = selected;
  5830. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  5831. goto retry;
  5832. } else if (!strncasecmp(&input, "s", 1)) {
  5833. opt_realquiet = true;
  5834. } else if (!strncasecmp(&input, "w", 1)) {
  5835. opt_worktime ^= true;
  5836. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  5837. goto retry;
  5838. } else if (!strncasecmp(&input, "z", 1)) {
  5839. zero_stats();
  5840. goto retry;
  5841. } else
  5842. clear_logwin();
  5843. immedok(logwin, false);
  5844. opt_loginput = false;
  5845. }
  5846. #endif
  5847. void default_save_file(char *filename)
  5848. {
  5849. #if defined(unix) || defined(__APPLE__)
  5850. if (getenv("HOME") && *getenv("HOME")) {
  5851. strcpy(filename, getenv("HOME"));
  5852. strcat(filename, "/");
  5853. }
  5854. else
  5855. strcpy(filename, "");
  5856. strcat(filename, ".bfgminer/");
  5857. mkdir(filename, 0777);
  5858. #else
  5859. strcpy(filename, "");
  5860. #endif
  5861. strcat(filename, def_conf);
  5862. }
  5863. #ifdef HAVE_CURSES
  5864. static void set_options(void)
  5865. {
  5866. int selected;
  5867. char input;
  5868. opt_loginput = true;
  5869. immedok(logwin, true);
  5870. clear_logwin();
  5871. retry:
  5872. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  5873. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  5874. "[W]rite config file\n[B]FGMiner restart\n",
  5875. opt_queue, opt_scantime, opt_expiry, opt_retries);
  5876. wlogprint("Select an option or any other key to return\n");
  5877. logwin_update();
  5878. input = getch();
  5879. if (!strncasecmp(&input, "q", 1)) {
  5880. selected = curses_int("Extra work items to queue");
  5881. if (selected < 0 || selected > 9999) {
  5882. wlogprint("Invalid selection\n");
  5883. goto retry;
  5884. }
  5885. opt_queue = selected;
  5886. goto retry;
  5887. } else if (!strncasecmp(&input, "l", 1)) {
  5888. if (want_longpoll)
  5889. stop_longpoll();
  5890. else
  5891. start_longpoll();
  5892. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  5893. goto retry;
  5894. } else if (!strncasecmp(&input, "s", 1)) {
  5895. selected = curses_int("Set scantime in seconds");
  5896. if (selected < 0 || selected > 9999) {
  5897. wlogprint("Invalid selection\n");
  5898. goto retry;
  5899. }
  5900. opt_scantime = selected;
  5901. goto retry;
  5902. } else if (!strncasecmp(&input, "e", 1)) {
  5903. selected = curses_int("Set expiry time in seconds");
  5904. if (selected < 0 || selected > 9999) {
  5905. wlogprint("Invalid selection\n");
  5906. goto retry;
  5907. }
  5908. opt_expiry = selected;
  5909. goto retry;
  5910. } else if (!strncasecmp(&input, "r", 1)) {
  5911. selected = curses_int("Retries before failing (-1 infinite)");
  5912. if (selected < -1 || selected > 9999) {
  5913. wlogprint("Invalid selection\n");
  5914. goto retry;
  5915. }
  5916. opt_retries = selected;
  5917. goto retry;
  5918. } else if (!strncasecmp(&input, "w", 1)) {
  5919. FILE *fcfg;
  5920. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  5921. default_save_file(filename);
  5922. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  5923. str = curses_input(prompt);
  5924. if (strcmp(str, "-1")) {
  5925. struct stat statbuf;
  5926. strcpy(filename, str);
  5927. free(str);
  5928. if (!stat(filename, &statbuf)) {
  5929. wlogprint("File exists, overwrite?\n");
  5930. input = getch();
  5931. if (strncasecmp(&input, "y", 1))
  5932. goto retry;
  5933. }
  5934. }
  5935. else
  5936. free(str);
  5937. fcfg = fopen(filename, "w");
  5938. if (!fcfg) {
  5939. wlogprint("Cannot open or create file\n");
  5940. goto retry;
  5941. }
  5942. write_config(fcfg);
  5943. fclose(fcfg);
  5944. goto retry;
  5945. } else if (!strncasecmp(&input, "b", 1)) {
  5946. wlogprint("Are you sure?\n");
  5947. input = getch();
  5948. if (!strncasecmp(&input, "y", 1))
  5949. app_restart();
  5950. else
  5951. clear_logwin();
  5952. } else
  5953. clear_logwin();
  5954. immedok(logwin, false);
  5955. opt_loginput = false;
  5956. }
  5957. int scan_serial(const char *);
  5958. static
  5959. void _managetui_msg(const char *repr, const char **msg)
  5960. {
  5961. if (*msg)
  5962. {
  5963. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  5964. wattron(logwin, A_BOLD);
  5965. wlogprint("%s", *msg);
  5966. wattroff(logwin, A_BOLD);
  5967. *msg = NULL;
  5968. }
  5969. logwin_update();
  5970. }
  5971. void manage_device(void)
  5972. {
  5973. char logline[256];
  5974. const char *msg = NULL;
  5975. struct cgpu_info *cgpu;
  5976. const struct device_drv *drv;
  5977. opt_loginput = true;
  5978. selecting_device = true;
  5979. immedok(logwin, true);
  5980. devchange:
  5981. if (unlikely(!total_devices))
  5982. {
  5983. clear_logwin();
  5984. wlogprint("(no devices)\n");
  5985. wlogprint("Press the plus key to add devices, or Enter when done\n");
  5986. _managetui_msg("(none)", &msg);
  5987. int input = getch();
  5988. switch (input)
  5989. {
  5990. case '+': case '=': // add new device
  5991. goto addnew;
  5992. default:
  5993. goto out;
  5994. }
  5995. }
  5996. cgpu = devices[selected_device];
  5997. drv = cgpu->drv;
  5998. refresh_devstatus();
  5999. refresh:
  6000. clear_logwin();
  6001. wlogprint("Select processor to manage using up/down arrow keys\n");
  6002. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6003. wattron(logwin, A_BOLD);
  6004. wlogprint("%s", logline);
  6005. wattroff(logwin, A_BOLD);
  6006. wlogprint("\n");
  6007. if (cgpu->dev_manufacturer)
  6008. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6009. else
  6010. if (cgpu->dev_product)
  6011. wlogprint(" %s\n", cgpu->dev_product);
  6012. if (cgpu->dev_serial)
  6013. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6014. if (cgpu->kname)
  6015. wlogprint("Kernel: %s\n", cgpu->kname);
  6016. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6017. drv->proc_wlogprint_status(cgpu);
  6018. wlogprint("\n");
  6019. // TODO: Last share at TIMESTAMP on pool N
  6020. // TODO: Custom device info/commands
  6021. if (cgpu->deven != DEV_ENABLED)
  6022. wlogprint("[E]nable ");
  6023. if (cgpu->deven != DEV_DISABLED)
  6024. wlogprint("[D]isable ");
  6025. if (drv->identify_device)
  6026. wlogprint("[I]dentify ");
  6027. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6028. drv->proc_tui_wlogprint_choices(cgpu);
  6029. wlogprint("\n");
  6030. wlogprint("Or press Enter when done or the plus key to add more devices\n");
  6031. _managetui_msg(cgpu->proc_repr, &msg);
  6032. while (true)
  6033. {
  6034. int input = getch();
  6035. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6036. switch (input) {
  6037. case 'd': case 'D':
  6038. if (cgpu->deven == DEV_DISABLED)
  6039. msg = "Processor already disabled\n";
  6040. else
  6041. {
  6042. cgpu->deven = DEV_DISABLED;
  6043. msg = "Processor being disabled\n";
  6044. }
  6045. goto refresh;
  6046. case 'e': case 'E':
  6047. if (cgpu->deven == DEV_ENABLED)
  6048. msg = "Processor already enabled\n";
  6049. else
  6050. {
  6051. proc_enable(cgpu);
  6052. msg = "Processor being enabled\n";
  6053. }
  6054. goto refresh;
  6055. case 'i': case 'I':
  6056. if (drv->identify_device && drv->identify_device(cgpu))
  6057. msg = "Identify command sent\n";
  6058. else
  6059. goto key_default;
  6060. goto refresh;
  6061. case KEY_DOWN:
  6062. if (selected_device >= total_devices - 1)
  6063. break;
  6064. ++selected_device;
  6065. goto devchange;
  6066. case KEY_UP:
  6067. if (selected_device <= 0)
  6068. break;
  6069. --selected_device;
  6070. goto devchange;
  6071. case KEY_NPAGE:
  6072. {
  6073. if (selected_device >= total_devices - 1)
  6074. break;
  6075. struct cgpu_info *mdev = devices[selected_device]->device;
  6076. do {
  6077. ++selected_device;
  6078. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6079. goto devchange;
  6080. }
  6081. case KEY_PPAGE:
  6082. {
  6083. if (selected_device <= 0)
  6084. break;
  6085. struct cgpu_info *mdev = devices[selected_device]->device;
  6086. do {
  6087. --selected_device;
  6088. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6089. goto devchange;
  6090. }
  6091. case '+': case '=': // add new device
  6092. {
  6093. addnew:
  6094. clear_logwin();
  6095. _wlogprint(
  6096. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6097. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6098. "For example: erupter:"
  6099. #ifdef WIN32
  6100. "\\\\.\\COM40"
  6101. #elif defined(__APPLE__)
  6102. "/dev/cu.SLAB_USBtoUART"
  6103. #else
  6104. "/dev/ttyUSB39"
  6105. #endif
  6106. "\n"
  6107. );
  6108. char *scanser = curses_input("Enter target");
  6109. if (scan_serial(scanser))
  6110. {
  6111. selected_device = total_devices - 1;
  6112. msg = "Device scan succeeded\n";
  6113. }
  6114. else
  6115. msg = "No new devices found\n";
  6116. goto devchange;
  6117. }
  6118. case 'Q': case 'q':
  6119. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6120. case '\x1b': // ESC
  6121. case KEY_ENTER:
  6122. case '\r': // Ctrl-M on Windows, with nonl
  6123. #ifdef PADENTER
  6124. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6125. #endif
  6126. case '\n':
  6127. goto out;
  6128. default:
  6129. ;
  6130. key_default:
  6131. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6132. {
  6133. msg = drv->proc_tui_handle_choice(cgpu, input);
  6134. if (msg)
  6135. goto refresh;
  6136. }
  6137. }
  6138. }
  6139. out:
  6140. selecting_device = false;
  6141. clear_logwin();
  6142. immedok(logwin, false);
  6143. opt_loginput = false;
  6144. }
  6145. void show_help(void)
  6146. {
  6147. opt_loginput = true;
  6148. clear_logwin();
  6149. // NOTE: wlogprint is a macro with a buffer limit
  6150. _wlogprint(
  6151. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6152. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6153. "E: # shares * diff per 2kB bw | U: shares/minute | BS: best share ever found\n"
  6154. "\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"
  6155. "devices/processors hashing (only for totals line), hottest temperature\n"
  6156. );
  6157. wlogprint(
  6158. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6159. , opt_log_interval);
  6160. _wlogprint(
  6161. "A: accepted shares | R: rejected+discarded(%% of total)\n"
  6162. "HW: hardware errors / %% nonces invalid\n"
  6163. "\n"
  6164. "Press any key to clear"
  6165. );
  6166. logwin_update();
  6167. getch();
  6168. clear_logwin();
  6169. opt_loginput = false;
  6170. }
  6171. static void *input_thread(void __maybe_unused *userdata)
  6172. {
  6173. RenameThread("input");
  6174. if (!curses_active)
  6175. return NULL;
  6176. while (1) {
  6177. int input;
  6178. input = getch();
  6179. switch (input) {
  6180. case 'h': case 'H': case '?':
  6181. show_help();
  6182. break;
  6183. case 'q': case 'Q':
  6184. kill_work();
  6185. return NULL;
  6186. case 'd': case 'D':
  6187. display_options();
  6188. break;
  6189. case 'm': case 'M':
  6190. manage_device();
  6191. break;
  6192. case 'p': case 'P':
  6193. display_pools();
  6194. break;
  6195. case 's': case 'S':
  6196. set_options();
  6197. break;
  6198. #ifdef HAVE_CURSES
  6199. case KEY_DOWN:
  6200. {
  6201. const int visible_lines = logcursor - devcursor;
  6202. const int invisible_lines = total_lines - visible_lines;
  6203. if (devsummaryYOffset <= -invisible_lines)
  6204. break;
  6205. devsummaryYOffset -= 2;
  6206. }
  6207. case KEY_UP:
  6208. if (devsummaryYOffset == 0)
  6209. break;
  6210. ++devsummaryYOffset;
  6211. refresh_devstatus();
  6212. break;
  6213. #endif
  6214. }
  6215. if (opt_realquiet) {
  6216. disable_curses();
  6217. break;
  6218. }
  6219. }
  6220. return NULL;
  6221. }
  6222. #endif
  6223. static void *api_thread(void *userdata)
  6224. {
  6225. struct thr_info *mythr = userdata;
  6226. pthread_detach(pthread_self());
  6227. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6228. RenameThread("rpc");
  6229. api(api_thr_id);
  6230. mythr->has_pth = false;
  6231. return NULL;
  6232. }
  6233. void thread_reportin(struct thr_info *thr)
  6234. {
  6235. cgtime(&thr->last);
  6236. thr->cgpu->status = LIFE_WELL;
  6237. thr->getwork = 0;
  6238. thr->cgpu->device_last_well = time(NULL);
  6239. }
  6240. void thread_reportout(struct thr_info *thr)
  6241. {
  6242. thr->getwork = time(NULL);
  6243. }
  6244. static void hashmeter(int thr_id, struct timeval *diff,
  6245. uint64_t hashes_done)
  6246. {
  6247. char logstatusline[256];
  6248. struct timeval temp_tv_end, total_diff;
  6249. double secs;
  6250. double local_secs;
  6251. static double local_mhashes_done = 0;
  6252. static double rolling = 0;
  6253. double local_mhashes = (double)hashes_done / 1000000.0;
  6254. bool showlog = false;
  6255. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  6256. char rejpcbuf[6];
  6257. char bnbuf[6];
  6258. struct thr_info *thr;
  6259. /* Update the last time this thread reported in */
  6260. if (thr_id >= 0) {
  6261. thr = get_thread(thr_id);
  6262. cgtime(&(thr->last));
  6263. thr->cgpu->device_last_well = time(NULL);
  6264. }
  6265. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  6266. /* So we can call hashmeter from a non worker thread */
  6267. if (thr_id >= 0) {
  6268. struct cgpu_info *cgpu = thr->cgpu;
  6269. int threadobj = cgpu->threads ?: 1;
  6270. double thread_rolling = 0.0;
  6271. int i;
  6272. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  6273. thr_id, hashes_done, hashes_done / 1000 / secs);
  6274. /* Rolling average for each thread and each device */
  6275. decay_time(&thr->rolling, local_mhashes / secs, secs);
  6276. for (i = 0; i < threadobj; i++)
  6277. thread_rolling += cgpu->thr[i]->rolling;
  6278. mutex_lock(&hash_lock);
  6279. decay_time(&cgpu->rolling, thread_rolling, secs);
  6280. cgpu->total_mhashes += local_mhashes;
  6281. mutex_unlock(&hash_lock);
  6282. // If needed, output detailed, per-device stats
  6283. if (want_per_device_stats) {
  6284. struct timeval now;
  6285. struct timeval elapsed;
  6286. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  6287. cgtime(&now);
  6288. timersub(&now, last_msg_tv, &elapsed);
  6289. if (opt_log_interval <= elapsed.tv_sec) {
  6290. struct cgpu_info *cgpu = thr->cgpu;
  6291. char logline[255];
  6292. *last_msg_tv = now;
  6293. get_statline(logline, sizeof(logline), cgpu);
  6294. if (!curses_active) {
  6295. printf("%s \r", logline);
  6296. fflush(stdout);
  6297. } else
  6298. applog(LOG_INFO, "%s", logline);
  6299. }
  6300. }
  6301. }
  6302. /* Totals are updated by all threads so can race without locking */
  6303. mutex_lock(&hash_lock);
  6304. cgtime(&temp_tv_end);
  6305. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  6306. total_mhashes_done += local_mhashes;
  6307. local_mhashes_done += local_mhashes;
  6308. /* Only update with opt_log_interval */
  6309. if (total_diff.tv_sec < opt_log_interval)
  6310. goto out_unlock;
  6311. showlog = true;
  6312. cgtime(&total_tv_end);
  6313. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  6314. decay_time(&rolling, local_mhashes_done / local_secs, local_secs);
  6315. global_hashrate = roundl(rolling) * 1000000;
  6316. timersub(&total_tv_end, &total_tv_start, &total_diff);
  6317. total_secs = (double)total_diff.tv_sec +
  6318. ((double)total_diff.tv_usec / 1000000.0);
  6319. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  6320. multi_format_unit_array2(
  6321. ((char*[]){cHr, aHr, uHr}),
  6322. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_SPACED]}),
  6323. true, "h/s", H2B_SHORT,
  6324. 3,
  6325. 1e6*rolling,
  6326. 1e6*total_mhashes_done / total_secs,
  6327. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  6328. #ifdef HAVE_CURSES
  6329. if (curses_active_locked()) {
  6330. float temp = 0;
  6331. struct cgpu_info *proc, *last_working_dev = NULL;
  6332. int i, working_devs = 0, working_procs = 0;
  6333. int divx;
  6334. bool bad = false;
  6335. // Find the highest temperature of all processors
  6336. for (i = 0; i < total_devices; ++i)
  6337. {
  6338. proc = get_devices(i);
  6339. if (proc->temp > temp)
  6340. temp = proc->temp;
  6341. if (unlikely(proc->deven == DEV_DISABLED))
  6342. ; // Just need to block it off from both conditions
  6343. else
  6344. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  6345. {
  6346. if (proc->rolling > .1)
  6347. {
  6348. ++working_procs;
  6349. if (proc->device != last_working_dev)
  6350. {
  6351. ++working_devs;
  6352. last_working_dev = proc->device;
  6353. }
  6354. }
  6355. }
  6356. else
  6357. bad = true;
  6358. }
  6359. if (working_devs == working_procs)
  6360. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? "\2" : "", working_devs);
  6361. else
  6362. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? "\2" : "", working_devs, working_procs);
  6363. divx = 7;
  6364. if (opt_show_procs && !opt_compact)
  6365. ++divx;
  6366. if (bad)
  6367. {
  6368. ++divx;
  6369. statusline[divx] = '\1';
  6370. ++divx;
  6371. }
  6372. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  6373. format_statline(statusline, sizeof(statusline),
  6374. cHr, aHr,
  6375. uHr,
  6376. total_accepted,
  6377. total_rejected,
  6378. total_stale,
  6379. total_diff_rejected + total_diff_stale, total_diff_accepted,
  6380. hw_errors,
  6381. total_bad_nonces, total_bad_nonces + total_diff1);
  6382. unlock_curses();
  6383. }
  6384. #endif
  6385. // Add a space
  6386. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  6387. uHr[5] = ' ';
  6388. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  6389. percentf4(bnbuf, sizeof(bnbuf), total_bad_nonces, total_diff1);
  6390. snprintf(logstatusline, sizeof(logstatusline),
  6391. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  6392. want_per_device_stats ? "ALL " : "",
  6393. opt_log_interval,
  6394. cHr, aHr,
  6395. uHr,
  6396. total_accepted,
  6397. total_rejected,
  6398. total_stale,
  6399. rejpcbuf,
  6400. hw_errors,
  6401. bnbuf
  6402. );
  6403. local_mhashes_done = 0;
  6404. out_unlock:
  6405. mutex_unlock(&hash_lock);
  6406. if (showlog) {
  6407. if (!curses_active) {
  6408. printf("%s \r", logstatusline);
  6409. fflush(stdout);
  6410. } else
  6411. applog(LOG_INFO, "%s", logstatusline);
  6412. }
  6413. }
  6414. void hashmeter2(struct thr_info *thr)
  6415. {
  6416. struct timeval tv_now, tv_elapsed;
  6417. timerclear(&thr->tv_hashes_done);
  6418. cgtime(&tv_now);
  6419. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  6420. /* Update the hashmeter at most 5 times per second */
  6421. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  6422. tv_elapsed.tv_sec >= opt_log_interval) {
  6423. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  6424. thr->hashes_done = 0;
  6425. thr->tv_lastupdate = tv_now;
  6426. }
  6427. }
  6428. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  6429. struct stratum_share *sshare)
  6430. {
  6431. struct work *work = sshare->work;
  6432. share_result(val, res_val, err_val, work, false, "");
  6433. }
  6434. /* Parses stratum json responses and tries to find the id that the request
  6435. * matched to and treat it accordingly. */
  6436. bool parse_stratum_response(struct pool *pool, char *s)
  6437. {
  6438. json_t *val = NULL, *err_val, *res_val, *id_val;
  6439. struct stratum_share *sshare;
  6440. json_error_t err;
  6441. bool ret = false;
  6442. int id;
  6443. val = JSON_LOADS(s, &err);
  6444. if (!val) {
  6445. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  6446. goto out;
  6447. }
  6448. res_val = json_object_get(val, "result");
  6449. err_val = json_object_get(val, "error");
  6450. id_val = json_object_get(val, "id");
  6451. if (json_is_null(id_val) || !id_val) {
  6452. char *ss;
  6453. if (err_val)
  6454. ss = json_dumps(err_val, JSON_INDENT(3));
  6455. else
  6456. ss = strdup("(unknown reason)");
  6457. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  6458. free(ss);
  6459. goto out;
  6460. }
  6461. if (!json_is_integer(id_val)) {
  6462. if (json_is_string(id_val)
  6463. && !strncmp(json_string_value(id_val), "txlist", 6)
  6464. && !strcmp(json_string_value(id_val) + 6, pool->swork.job_id)
  6465. && json_is_array(res_val)) {
  6466. // Check that the transactions actually hash to the merkle links
  6467. {
  6468. unsigned maxtx = 1 << pool->swork.merkles;
  6469. unsigned mintx = maxtx >> 1;
  6470. --maxtx;
  6471. unsigned acttx = (unsigned)json_array_size(res_val);
  6472. if (acttx < mintx || acttx > maxtx) {
  6473. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  6474. pool->pool_no, acttx, mintx, maxtx);
  6475. goto fishy;
  6476. }
  6477. // TODO: Check hashes match actual merkle links
  6478. }
  6479. pool_set_opaque(pool, false);
  6480. timer_unset(&pool->swork.tv_transparency);
  6481. fishy:
  6482. ret = true;
  6483. }
  6484. goto out;
  6485. }
  6486. id = json_integer_value(id_val);
  6487. mutex_lock(&sshare_lock);
  6488. HASH_FIND_INT(stratum_shares, &id, sshare);
  6489. if (sshare)
  6490. HASH_DEL(stratum_shares, sshare);
  6491. mutex_unlock(&sshare_lock);
  6492. if (!sshare) {
  6493. double pool_diff;
  6494. /* Since the share is untracked, we can only guess at what the
  6495. * work difficulty is based on the current pool diff. */
  6496. cg_rlock(&pool->data_lock);
  6497. pool_diff = pool->swork.diff;
  6498. cg_runlock(&pool->data_lock);
  6499. if (json_is_true(res_val)) {
  6500. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  6501. /* We don't know what device this came from so we can't
  6502. * attribute the work to the relevant cgpu */
  6503. mutex_lock(&stats_lock);
  6504. total_accepted++;
  6505. pool->accepted++;
  6506. total_diff_accepted += pool_diff;
  6507. pool->diff_accepted += pool_diff;
  6508. mutex_unlock(&stats_lock);
  6509. } else {
  6510. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  6511. mutex_lock(&stats_lock);
  6512. total_rejected++;
  6513. pool->rejected++;
  6514. total_diff_rejected += pool_diff;
  6515. pool->diff_rejected += pool_diff;
  6516. mutex_unlock(&stats_lock);
  6517. }
  6518. goto out;
  6519. }
  6520. else {
  6521. mutex_lock(&submitting_lock);
  6522. --total_submitting;
  6523. mutex_unlock(&submitting_lock);
  6524. }
  6525. stratum_share_result(val, res_val, err_val, sshare);
  6526. free_work(sshare->work);
  6527. free(sshare);
  6528. ret = true;
  6529. out:
  6530. if (val)
  6531. json_decref(val);
  6532. return ret;
  6533. }
  6534. static void shutdown_stratum(struct pool *pool)
  6535. {
  6536. // Shut down Stratum as if we never had it
  6537. pool->stratum_active = false;
  6538. pool->stratum_init = false;
  6539. pool->has_stratum = false;
  6540. shutdown(pool->sock, SHUT_RDWR);
  6541. free(pool->stratum_url);
  6542. if (pool->sockaddr_url == pool->stratum_url)
  6543. pool->sockaddr_url = NULL;
  6544. pool->stratum_url = NULL;
  6545. }
  6546. void clear_stratum_shares(struct pool *pool)
  6547. {
  6548. int my_mining_threads = mining_threads; // Cached outside of locking
  6549. struct stratum_share *sshare, *tmpshare;
  6550. struct work *work;
  6551. struct cgpu_info *cgpu;
  6552. double diff_cleared = 0;
  6553. double thr_diff_cleared[my_mining_threads];
  6554. int cleared = 0;
  6555. int thr_cleared[my_mining_threads];
  6556. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  6557. for (int i = 0; i < my_mining_threads; ++i)
  6558. {
  6559. thr_diff_cleared[i] = 0;
  6560. thr_cleared[i] = 0;
  6561. }
  6562. mutex_lock(&sshare_lock);
  6563. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  6564. work = sshare->work;
  6565. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  6566. HASH_DEL(stratum_shares, sshare);
  6567. sharelog("disconnect", work);
  6568. diff_cleared += sshare->work->work_difficulty;
  6569. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  6570. ++thr_cleared[work->thr_id];
  6571. free_work(sshare->work);
  6572. free(sshare);
  6573. cleared++;
  6574. }
  6575. }
  6576. mutex_unlock(&sshare_lock);
  6577. if (cleared) {
  6578. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  6579. mutex_lock(&stats_lock);
  6580. pool->stale_shares += cleared;
  6581. total_stale += cleared;
  6582. pool->diff_stale += diff_cleared;
  6583. total_diff_stale += diff_cleared;
  6584. for (int i = 0; i < my_mining_threads; ++i)
  6585. if (thr_cleared[i])
  6586. {
  6587. cgpu = get_thr_cgpu(i);
  6588. cgpu->diff_stale += thr_diff_cleared[i];
  6589. cgpu->stale += thr_cleared[i];
  6590. }
  6591. mutex_unlock(&stats_lock);
  6592. mutex_lock(&submitting_lock);
  6593. total_submitting -= cleared;
  6594. mutex_unlock(&submitting_lock);
  6595. }
  6596. }
  6597. static void resubmit_stratum_shares(struct pool *pool)
  6598. {
  6599. struct stratum_share *sshare, *tmpshare;
  6600. struct work *work;
  6601. unsigned resubmitted = 0;
  6602. mutex_lock(&sshare_lock);
  6603. mutex_lock(&submitting_lock);
  6604. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  6605. if (sshare->work->pool != pool)
  6606. continue;
  6607. HASH_DEL(stratum_shares, sshare);
  6608. work = sshare->work;
  6609. DL_APPEND(submit_waiting, work);
  6610. free(sshare);
  6611. ++resubmitted;
  6612. }
  6613. mutex_unlock(&submitting_lock);
  6614. mutex_unlock(&sshare_lock);
  6615. if (resubmitted) {
  6616. notifier_wake(submit_waiting_notifier);
  6617. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  6618. }
  6619. }
  6620. static void clear_pool_work(struct pool *pool)
  6621. {
  6622. struct work *work, *tmp;
  6623. int cleared = 0;
  6624. mutex_lock(stgd_lock);
  6625. HASH_ITER(hh, staged_work, work, tmp) {
  6626. if (work->pool == pool) {
  6627. HASH_DEL(staged_work, work);
  6628. free_work(work);
  6629. cleared++;
  6630. staged_full = false;
  6631. }
  6632. }
  6633. mutex_unlock(stgd_lock);
  6634. }
  6635. static int cp_prio(void)
  6636. {
  6637. int prio;
  6638. cg_rlock(&control_lock);
  6639. prio = currentpool->prio;
  6640. cg_runlock(&control_lock);
  6641. return prio;
  6642. }
  6643. /* We only need to maintain a secondary pool connection when we need the
  6644. * capacity to get work from the backup pools while still on the primary */
  6645. static bool cnx_needed(struct pool *pool)
  6646. {
  6647. struct pool *cp;
  6648. if (pool->enabled != POOL_ENABLED)
  6649. return false;
  6650. /* Balance strategies need all pools online */
  6651. if (pool_strategy == POOL_BALANCE)
  6652. return true;
  6653. if (pool_strategy == POOL_LOADBALANCE)
  6654. return true;
  6655. /* Idle stratum pool needs something to kick it alive again */
  6656. if (pool->has_stratum && pool->idle)
  6657. return true;
  6658. /* Getwork pools without opt_fail_only need backup pools up to be able
  6659. * to leak shares */
  6660. cp = current_pool();
  6661. if (cp == pool)
  6662. return true;
  6663. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  6664. return true;
  6665. /* Keep the connection open to allow any stray shares to be submitted
  6666. * on switching pools for 2 minutes. */
  6667. if (!timer_passed(&pool->tv_last_work_time, NULL))
  6668. return true;
  6669. /* If the pool has only just come to life and is higher priority than
  6670. * the current pool keep the connection open so we can fail back to
  6671. * it. */
  6672. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  6673. return true;
  6674. if (pool_unworkable(cp))
  6675. return true;
  6676. /* We've run out of work, bring anything back to life. */
  6677. if (no_work)
  6678. return true;
  6679. return false;
  6680. }
  6681. static void wait_lpcurrent(struct pool *pool);
  6682. static void pool_resus(struct pool *pool);
  6683. static void gen_stratum_work(struct pool *pool, struct work *work);
  6684. static void stratum_resumed(struct pool *pool)
  6685. {
  6686. if (!pool->stratum_notify)
  6687. return;
  6688. if (pool_tclear(pool, &pool->idle)) {
  6689. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  6690. pool_resus(pool);
  6691. }
  6692. }
  6693. static bool supports_resume(struct pool *pool)
  6694. {
  6695. bool ret;
  6696. cg_rlock(&pool->data_lock);
  6697. ret = (pool->sessionid != NULL);
  6698. cg_runlock(&pool->data_lock);
  6699. return ret;
  6700. }
  6701. /* One stratum thread per pool that has stratum waits on the socket checking
  6702. * for new messages and for the integrity of the socket connection. We reset
  6703. * the connection based on the integrity of the receive side only as the send
  6704. * side will eventually expire data it fails to send. */
  6705. static void *stratum_thread(void *userdata)
  6706. {
  6707. struct pool *pool = (struct pool *)userdata;
  6708. pthread_detach(pthread_self());
  6709. char threadname[20];
  6710. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  6711. RenameThread(threadname);
  6712. srand(time(NULL) + (intptr_t)userdata);
  6713. while (42) {
  6714. struct timeval timeout;
  6715. int sel_ret;
  6716. fd_set rd;
  6717. char *s;
  6718. int sock;
  6719. if (unlikely(!pool->has_stratum))
  6720. break;
  6721. sock = pool->sock;
  6722. /* Check to see whether we need to maintain this connection
  6723. * indefinitely or just bring it up when we switch to this
  6724. * pool */
  6725. if (sock == INVSOCK || (!sock_full(pool) && !cnx_needed(pool))) {
  6726. suspend_stratum(pool);
  6727. clear_stratum_shares(pool);
  6728. clear_pool_work(pool);
  6729. wait_lpcurrent(pool);
  6730. if (!restart_stratum(pool)) {
  6731. pool_died(pool);
  6732. while (!restart_stratum(pool)) {
  6733. if (pool->removed)
  6734. goto out;
  6735. cgsleep_ms(30000);
  6736. }
  6737. }
  6738. }
  6739. FD_ZERO(&rd);
  6740. FD_SET(sock, &rd);
  6741. timeout.tv_sec = 120;
  6742. timeout.tv_usec = 0;
  6743. /* If we fail to receive any notify messages for 2 minutes we
  6744. * assume the connection has been dropped and treat this pool
  6745. * as dead */
  6746. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  6747. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  6748. s = NULL;
  6749. } else
  6750. s = recv_line(pool);
  6751. if (!s) {
  6752. if (!pool->has_stratum)
  6753. break;
  6754. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  6755. pool->getfail_occasions++;
  6756. total_go++;
  6757. mutex_lock(&pool->stratum_lock);
  6758. pool->stratum_active = pool->stratum_notify = false;
  6759. pool->sock = INVSOCK;
  6760. mutex_unlock(&pool->stratum_lock);
  6761. /* If the socket to our stratum pool disconnects, all
  6762. * submissions need to be discarded or resent. */
  6763. if (!supports_resume(pool))
  6764. clear_stratum_shares(pool);
  6765. else
  6766. resubmit_stratum_shares(pool);
  6767. clear_pool_work(pool);
  6768. if (pool == current_pool())
  6769. restart_threads();
  6770. if (restart_stratum(pool))
  6771. continue;
  6772. shutdown_stratum(pool);
  6773. pool_died(pool);
  6774. break;
  6775. }
  6776. /* Check this pool hasn't died while being a backup pool and
  6777. * has not had its idle flag cleared */
  6778. stratum_resumed(pool);
  6779. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  6780. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  6781. free(s);
  6782. if (pool->swork.clean) {
  6783. struct work *work = make_work();
  6784. /* Generate a single work item to update the current
  6785. * block database */
  6786. pool->swork.clean = false;
  6787. gen_stratum_work(pool, work);
  6788. /* Try to extract block height from coinbase scriptSig */
  6789. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  6790. unsigned char cb_height_sz;
  6791. cb_height_sz = bin_height[-1];
  6792. if (cb_height_sz == 3) {
  6793. // FIXME: The block number will overflow this by AD 2173
  6794. uint32_t block_id = ((uint32_t*)work->data)[1];
  6795. uint32_t height = 0;
  6796. memcpy(&height, bin_height, 3);
  6797. height = le32toh(height);
  6798. have_block_height(block_id, height);
  6799. }
  6800. ++pool->work_restart_id;
  6801. if (test_work_current(work)) {
  6802. /* Only accept a work update if this stratum
  6803. * connection is from the current pool */
  6804. if (pool == current_pool()) {
  6805. restart_threads();
  6806. applog(
  6807. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  6808. "Stratum from pool %d requested work update", pool->pool_no);
  6809. }
  6810. } else
  6811. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  6812. free_work(work);
  6813. }
  6814. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  6815. // More than 4 timmills past since requested transactions
  6816. timer_unset(&pool->swork.tv_transparency);
  6817. pool_set_opaque(pool, true);
  6818. }
  6819. }
  6820. out:
  6821. return NULL;
  6822. }
  6823. static void init_stratum_thread(struct pool *pool)
  6824. {
  6825. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  6826. quit(1, "Failed to create stratum thread");
  6827. }
  6828. static void *longpoll_thread(void *userdata);
  6829. static bool stratum_works(struct pool *pool)
  6830. {
  6831. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  6832. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  6833. return false;
  6834. if (pool->stratum_active)
  6835. return true;
  6836. if (!initiate_stratum(pool))
  6837. return false;
  6838. return true;
  6839. }
  6840. static bool pool_active(struct pool *pool, bool pinging)
  6841. {
  6842. struct timeval tv_getwork, tv_getwork_reply;
  6843. bool ret = false;
  6844. json_t *val;
  6845. CURL *curl;
  6846. int rolltime;
  6847. char *rpc_req;
  6848. struct work *work;
  6849. enum pool_protocol proto;
  6850. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  6851. /* This is the central point we activate stratum when we can */
  6852. curl = curl_easy_init();
  6853. if (unlikely(!curl)) {
  6854. applog(LOG_ERR, "CURL initialisation failed");
  6855. return false;
  6856. }
  6857. if (!(want_gbt || want_getwork))
  6858. goto nohttp;
  6859. work = make_work();
  6860. /* Probe for GBT support on first pass */
  6861. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  6862. tryagain:
  6863. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  6864. work->pool = pool;
  6865. if (!rpc_req)
  6866. goto out;
  6867. pool->probed = false;
  6868. cgtime(&tv_getwork);
  6869. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  6870. true, false, &rolltime, pool, false);
  6871. cgtime(&tv_getwork_reply);
  6872. free(rpc_req);
  6873. /* Detect if a http getwork pool has an X-Stratum header at startup,
  6874. * and if so, switch to that in preference to getwork if it works */
  6875. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  6876. if (!pool->has_stratum) {
  6877. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  6878. if (!pool->rpc_url)
  6879. pool->rpc_url = strdup(pool->stratum_url);
  6880. pool->has_stratum = true;
  6881. }
  6882. free_work(work);
  6883. if (val)
  6884. json_decref(val);
  6885. retry_stratum:
  6886. curl_easy_cleanup(curl);
  6887. /* We create the stratum thread for each pool just after
  6888. * successful authorisation. Once the init flag has been set
  6889. * we never unset it and the stratum thread is responsible for
  6890. * setting/unsetting the active flag */
  6891. bool init = pool_tset(pool, &pool->stratum_init);
  6892. if (!init) {
  6893. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  6894. if (ret)
  6895. {
  6896. detect_algo = 2;
  6897. init_stratum_thread(pool);
  6898. }
  6899. else
  6900. pool_tclear(pool, &pool->stratum_init);
  6901. return ret;
  6902. }
  6903. return pool->stratum_active;
  6904. }
  6905. else if (pool->has_stratum)
  6906. shutdown_stratum(pool);
  6907. if (val) {
  6908. bool rc;
  6909. json_t *res;
  6910. res = json_object_get(val, "result");
  6911. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  6912. goto badwork;
  6913. work->rolltime = rolltime;
  6914. rc = work_decode(pool, work, val);
  6915. if (rc) {
  6916. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  6917. pool->pool_no, pool->rpc_url);
  6918. work->pool = pool;
  6919. copy_time(&work->tv_getwork, &tv_getwork);
  6920. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  6921. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  6922. calc_diff(work, 0);
  6923. update_last_work(work);
  6924. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  6925. tq_push(control_thr[stage_thr_id].q, work);
  6926. total_getworks++;
  6927. pool->getwork_requested++;
  6928. ret = true;
  6929. cgtime(&pool->tv_idle);
  6930. } else {
  6931. badwork:
  6932. json_decref(val);
  6933. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  6934. pool->pool_no, pool->rpc_url);
  6935. pool->proto = proto = pool_protocol_fallback(proto);
  6936. if (PLP_NONE != proto)
  6937. goto tryagain;
  6938. free_work(work);
  6939. goto out;
  6940. }
  6941. json_decref(val);
  6942. if (proto != pool->proto) {
  6943. pool->proto = proto;
  6944. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  6945. }
  6946. if (pool->lp_url)
  6947. goto out;
  6948. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  6949. const struct blktmpl_longpoll_req *lp;
  6950. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  6951. // NOTE: work_decode takes care of lp id
  6952. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  6953. if (!pool->lp_url)
  6954. {
  6955. ret = false;
  6956. goto out;
  6957. }
  6958. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  6959. }
  6960. else
  6961. if (pool->hdr_path && want_getwork) {
  6962. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  6963. if (!pool->lp_url)
  6964. {
  6965. ret = false;
  6966. goto out;
  6967. }
  6968. pool->lp_proto = PLP_GETWORK;
  6969. } else
  6970. pool->lp_url = NULL;
  6971. if (want_longpoll && !pool->lp_started) {
  6972. pool->lp_started = true;
  6973. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  6974. quit(1, "Failed to create pool longpoll thread");
  6975. }
  6976. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  6977. pool->proto = proto;
  6978. goto tryagain;
  6979. } else {
  6980. free_work(work);
  6981. nohttp:
  6982. /* If we failed to parse a getwork, this could be a stratum
  6983. * url without the prefix stratum+tcp:// so let's check it */
  6984. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  6985. pool->has_stratum = true;
  6986. goto retry_stratum;
  6987. }
  6988. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  6989. pool->pool_no, pool->rpc_url);
  6990. if (!pinging)
  6991. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  6992. }
  6993. out:
  6994. curl_easy_cleanup(curl);
  6995. return ret;
  6996. }
  6997. static void pool_resus(struct pool *pool)
  6998. {
  6999. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio()) {
  7000. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7001. switch_pools(NULL);
  7002. } else
  7003. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7004. }
  7005. static struct work *hash_pop(void)
  7006. {
  7007. struct work *work = NULL, *tmp;
  7008. int hc;
  7009. struct timespec ts;
  7010. retry:
  7011. mutex_lock(stgd_lock);
  7012. while (!HASH_COUNT(staged_work))
  7013. {
  7014. if (unlikely(staged_full))
  7015. {
  7016. if (likely(opt_queue < 10 + mining_threads))
  7017. {
  7018. ++opt_queue;
  7019. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7020. }
  7021. else
  7022. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7023. staged_full = false; // Let it fill up before triggering an underrun again
  7024. no_work = true;
  7025. }
  7026. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7027. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7028. {
  7029. run_cmd(cmd_idle);
  7030. pthread_cond_wait(&getq->cond, stgd_lock);
  7031. }
  7032. }
  7033. no_work = false;
  7034. hc = HASH_COUNT(staged_work);
  7035. /* Find clone work if possible, to allow masters to be reused */
  7036. if (hc > staged_rollable) {
  7037. HASH_ITER(hh, staged_work, work, tmp) {
  7038. if (!work_rollable(work))
  7039. break;
  7040. }
  7041. } else
  7042. work = staged_work;
  7043. if (can_roll(work) && should_roll(work))
  7044. {
  7045. // Instead of consuming it, force it to be cloned and grab the clone
  7046. mutex_unlock(stgd_lock);
  7047. clone_available();
  7048. goto retry;
  7049. }
  7050. HASH_DEL(staged_work, work);
  7051. if (work_rollable(work))
  7052. staged_rollable--;
  7053. /* Signal the getwork scheduler to look for more work */
  7054. pthread_cond_signal(&gws_cond);
  7055. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7056. pthread_cond_signal(&getq->cond);
  7057. mutex_unlock(stgd_lock);
  7058. work->pool->last_work_time = time(NULL);
  7059. cgtime(&work->pool->tv_last_work_time);
  7060. return work;
  7061. }
  7062. /* Clones work by rolling it if possible, and returning a clone instead of the
  7063. * original work item which gets staged again to possibly be rolled again in
  7064. * the future */
  7065. static struct work *clone_work(struct work *work)
  7066. {
  7067. int mrs = mining_threads + opt_queue - total_staged();
  7068. struct work *work_clone;
  7069. bool cloned;
  7070. if (mrs < 1)
  7071. return work;
  7072. cloned = false;
  7073. work_clone = make_clone(work);
  7074. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7075. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7076. stage_work(work_clone);
  7077. roll_work(work);
  7078. work_clone = make_clone(work);
  7079. /* Roll it again to prevent duplicates should this be used
  7080. * directly later on */
  7081. roll_work(work);
  7082. cloned = true;
  7083. }
  7084. if (cloned) {
  7085. stage_work(work);
  7086. return work_clone;
  7087. }
  7088. free_work(work_clone);
  7089. return work;
  7090. }
  7091. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7092. {
  7093. unsigned char hash1[32];
  7094. sha256(data, len, hash1);
  7095. sha256(hash1, 32, hash);
  7096. }
  7097. /* Diff 1 is a 256 bit unsigned integer of
  7098. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  7099. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  7100. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7101. static void bdiff_target_leadzero(unsigned char *target, double diff)
  7102. {
  7103. uint64_t *data64, h64;
  7104. double d64;
  7105. d64 = diffone;
  7106. d64 /= diff;
  7107. d64 = ceil(d64);
  7108. h64 = d64;
  7109. memset(target, 0, 32);
  7110. if (d64 < 18446744073709551616.0) {
  7111. unsigned char *rtarget = target;
  7112. memset(rtarget, 0, 32);
  7113. if (opt_scrypt)
  7114. data64 = (uint64_t *)(rtarget + 2);
  7115. else
  7116. data64 = (uint64_t *)(rtarget + 4);
  7117. *data64 = htobe64(h64);
  7118. } else {
  7119. /* Support for the classic all FFs just-below-1 diff */
  7120. if (opt_scrypt)
  7121. memset(&target[2], 0xff, 30);
  7122. else
  7123. memset(&target[4], 0xff, 28);
  7124. }
  7125. }
  7126. void set_target(unsigned char *dest_target, double diff)
  7127. {
  7128. unsigned char rtarget[32];
  7129. bdiff_target_leadzero(rtarget, diff);
  7130. swab256(dest_target, rtarget);
  7131. if (opt_debug) {
  7132. char htarget[65];
  7133. bin2hex(htarget, rtarget, 32);
  7134. applog(LOG_DEBUG, "Generated target %s", htarget);
  7135. }
  7136. }
  7137. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  7138. {
  7139. *dst = *src;
  7140. dst->job_id = strdup(src->job_id);
  7141. bytes_cpy(&dst->coinbase, &src->coinbase);
  7142. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  7143. }
  7144. void stratum_work_clean(struct stratum_work * const swork)
  7145. {
  7146. free(swork->job_id);
  7147. bytes_free(&swork->coinbase);
  7148. bytes_free(&swork->merkle_bin);
  7149. }
  7150. /* Generates stratum based work based on the most recent notify information
  7151. * from the pool. This will keep generating work while a pool is down so we use
  7152. * other means to detect when the pool has died in stratum_thread */
  7153. static void gen_stratum_work(struct pool *pool, struct work *work)
  7154. {
  7155. clean_work(work);
  7156. cg_wlock(&pool->data_lock);
  7157. pool->swork.data_lock_p = &pool->data_lock;
  7158. bytes_resize(&work->nonce2, pool->n2size);
  7159. if (pool->nonce2sz < pool->n2size)
  7160. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  7161. memcpy(bytes_buf(&work->nonce2),
  7162. #ifdef WORDS_BIGENDIAN
  7163. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  7164. &((char*)&pool->nonce2)[pool->nonce2off],
  7165. #else
  7166. &pool->nonce2,
  7167. #endif
  7168. pool->nonce2sz);
  7169. pool->nonce2++;
  7170. work->pool = pool;
  7171. work->work_restart_id = work->pool->work_restart_id;
  7172. gen_stratum_work2(work, &pool->swork, pool->nonce1);
  7173. cgtime(&work->tv_staged);
  7174. }
  7175. void gen_stratum_work2(struct work *work, struct stratum_work *swork, const char *nonce1)
  7176. {
  7177. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  7178. uint8_t *merkle_bin;
  7179. uint32_t *data32, *swap32;
  7180. int i;
  7181. /* Generate coinbase */
  7182. coinbase = bytes_buf(&swork->coinbase);
  7183. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7184. /* Downgrade to a read lock to read off the variables */
  7185. if (swork->data_lock_p)
  7186. cg_dwlock(swork->data_lock_p);
  7187. /* Generate merkle root */
  7188. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  7189. memcpy(merkle_sha, merkle_root, 32);
  7190. merkle_bin = bytes_buf(&swork->merkle_bin);
  7191. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  7192. memcpy(merkle_sha + 32, merkle_bin, 32);
  7193. gen_hash(merkle_sha, merkle_root, 64);
  7194. memcpy(merkle_sha, merkle_root, 32);
  7195. }
  7196. data32 = (uint32_t *)merkle_sha;
  7197. swap32 = (uint32_t *)merkle_root;
  7198. flip32(swap32, data32);
  7199. memcpy(&work->data[0], swork->header1, 36);
  7200. memcpy(&work->data[36], merkle_root, 32);
  7201. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  7202. memcpy(&work->data[72], swork->diffbits, 4);
  7203. memset(&work->data[76], 0, 4); // nonce
  7204. memcpy(&work->data[80], workpadding_bin, 48);
  7205. /* Store the stratum work diff to check it still matches the pool's
  7206. * stratum diff when submitting shares */
  7207. work->sdiff = swork->diff;
  7208. /* Copy parameters required for share submission */
  7209. work->job_id = strdup(swork->job_id);
  7210. work->nonce1 = strdup(nonce1);
  7211. if (swork->data_lock_p)
  7212. cg_runlock(swork->data_lock_p);
  7213. if (opt_debug)
  7214. {
  7215. char header[161];
  7216. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  7217. bin2hex(header, work->data, 80);
  7218. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7219. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7220. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  7221. }
  7222. calc_midstate(work);
  7223. set_target(work->target, work->sdiff);
  7224. local_work++;
  7225. work->stratum = true;
  7226. work->blk.nonce = 0;
  7227. work->id = total_work++;
  7228. work->longpoll = false;
  7229. work->getwork_mode = GETWORK_MODE_STRATUM;
  7230. calc_diff(work, 0);
  7231. }
  7232. void request_work(struct thr_info *thr)
  7233. {
  7234. struct cgpu_info *cgpu = thr->cgpu;
  7235. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7236. /* Tell the watchdog thread this thread is waiting on getwork and
  7237. * should not be restarted */
  7238. thread_reportout(thr);
  7239. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  7240. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7241. {
  7242. if (proc->threads)
  7243. break;
  7244. thread_reportout(proc->thr[0]);
  7245. }
  7246. cgtime(&dev_stats->_get_start);
  7247. }
  7248. // FIXME: Make this non-blocking (and remove HACK above)
  7249. struct work *get_work(struct thr_info *thr)
  7250. {
  7251. const int thr_id = thr->id;
  7252. struct cgpu_info *cgpu = thr->cgpu;
  7253. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7254. struct cgminer_stats *pool_stats;
  7255. struct timeval tv_get;
  7256. struct work *work = NULL;
  7257. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  7258. while (!work) {
  7259. work = hash_pop();
  7260. if (stale_work(work, false)) {
  7261. staged_full = false; // It wasn't really full, since it was stale :(
  7262. discard_work(work);
  7263. work = NULL;
  7264. wake_gws();
  7265. }
  7266. }
  7267. applog(LOG_DEBUG, "%"PRIpreprv": Got work from get queue to get work for thread %d", cgpu->proc_repr, thr_id);
  7268. work->thr_id = thr_id;
  7269. thread_reportin(thr);
  7270. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  7271. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7272. {
  7273. if (proc->threads)
  7274. break;
  7275. thread_reportin(proc->thr[0]);
  7276. }
  7277. work->mined = true;
  7278. work->blk.nonce = 0;
  7279. cgtime(&tv_get);
  7280. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  7281. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  7282. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  7283. dev_stats->getwork_wait_max = tv_get;
  7284. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  7285. dev_stats->getwork_wait_min = tv_get;
  7286. ++dev_stats->getwork_calls;
  7287. pool_stats = &(work->pool->cgminer_stats);
  7288. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  7289. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  7290. pool_stats->getwork_wait_max = tv_get;
  7291. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  7292. pool_stats->getwork_wait_min = tv_get;
  7293. ++pool_stats->getwork_calls;
  7294. return work;
  7295. }
  7296. static
  7297. void _submit_work_async(struct work *work)
  7298. {
  7299. applog(LOG_DEBUG, "Pushing submit work to work thread");
  7300. mutex_lock(&submitting_lock);
  7301. ++total_submitting;
  7302. DL_APPEND(submit_waiting, work);
  7303. mutex_unlock(&submitting_lock);
  7304. notifier_wake(submit_waiting_notifier);
  7305. }
  7306. static void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  7307. {
  7308. struct work *work = copy_work(work_in);
  7309. if (tv_work_found)
  7310. copy_time(&work->tv_work_found, tv_work_found);
  7311. _submit_work_async(work);
  7312. }
  7313. void inc_hw_errors2(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p)
  7314. {
  7315. struct cgpu_info * const cgpu = thr->cgpu;
  7316. if (bad_nonce_p)
  7317. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  7318. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  7319. mutex_lock(&stats_lock);
  7320. hw_errors++;
  7321. ++cgpu->hw_errors;
  7322. if (bad_nonce_p)
  7323. {
  7324. ++total_bad_nonces;
  7325. ++cgpu->bad_nonces;
  7326. }
  7327. mutex_unlock(&stats_lock);
  7328. if (thr->cgpu->drv->hw_error)
  7329. thr->cgpu->drv->hw_error(thr);
  7330. }
  7331. void inc_hw_errors(struct thr_info *thr, const struct work *work, const uint32_t bad_nonce)
  7332. {
  7333. inc_hw_errors2(thr, work, work ? &bad_nonce : NULL);
  7334. }
  7335. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  7336. {
  7337. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  7338. hash_data(work->hash, work->data);
  7339. if (hash2_32[7] != 0)
  7340. return TNR_BAD;
  7341. if (!checktarget)
  7342. return TNR_GOOD;
  7343. if (!hash_target_check_v(work->hash, work->target))
  7344. return TNR_HIGH;
  7345. return TNR_GOOD;
  7346. }
  7347. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  7348. {
  7349. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7350. *work_nonce = htole32(nonce);
  7351. #ifdef USE_SCRYPT
  7352. if (opt_scrypt)
  7353. // NOTE: Depends on scrypt_test return matching enum values
  7354. return scrypt_test(work->data, work->target, nonce);
  7355. #endif
  7356. return hashtest2(work, checktarget);
  7357. }
  7358. /* Returns true if nonce for work was a valid share */
  7359. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  7360. {
  7361. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7362. uint32_t bak_nonce = *work_nonce;
  7363. struct timeval tv_work_found;
  7364. enum test_nonce2_result res;
  7365. bool ret = true;
  7366. thread_reportout(thr);
  7367. cgtime(&tv_work_found);
  7368. *work_nonce = htole32(nonce);
  7369. work->thr_id = thr->id;
  7370. /* Do one last check before attempting to submit the work */
  7371. /* Side effect: sets work->data for us */
  7372. res = test_nonce2(work, nonce);
  7373. if (unlikely(res == TNR_BAD))
  7374. {
  7375. inc_hw_errors(thr, work, nonce);
  7376. ret = false;
  7377. goto out;
  7378. }
  7379. mutex_lock(&stats_lock);
  7380. total_diff1++;
  7381. thr->cgpu->diff1++;
  7382. work->pool->diff1++;
  7383. thr->cgpu->last_device_valid_work = time(NULL);
  7384. mutex_unlock(&stats_lock);
  7385. if (noncelog_file)
  7386. noncelog(work);
  7387. if (res == TNR_HIGH)
  7388. {
  7389. // Share above target, normal
  7390. /* Check the diff of the share, even if it didn't reach the
  7391. * target, just to set the best share value if it's higher. */
  7392. share_diff(work);
  7393. goto out;
  7394. }
  7395. submit_work_async(work, &tv_work_found);
  7396. out:
  7397. *work_nonce = bak_nonce;
  7398. thread_reportin(thr);
  7399. return ret;
  7400. }
  7401. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  7402. {
  7403. if (wdiff->tv_sec > opt_scantime ||
  7404. work->blk.nonce >= MAXTHREADS - hashes ||
  7405. hashes >= 0xfffffffe ||
  7406. stale_work(work, false))
  7407. return true;
  7408. return false;
  7409. }
  7410. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  7411. {
  7412. struct cgpu_info *proc = thr->cgpu;
  7413. if (proc->threads > 1)
  7414. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  7415. else
  7416. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  7417. }
  7418. void mt_disable_start(struct thr_info *mythr)
  7419. {
  7420. struct cgpu_info *cgpu = mythr->cgpu;
  7421. struct device_drv *drv = cgpu->drv;
  7422. if (drv->thread_disable)
  7423. drv->thread_disable(mythr);
  7424. hashmeter2(mythr);
  7425. if (mythr->prev_work)
  7426. free_work(mythr->prev_work);
  7427. mythr->prev_work = mythr->work;
  7428. mythr->work = NULL;
  7429. mythr->_job_transition_in_progress = false;
  7430. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  7431. mythr->rolling = mythr->cgpu->rolling = 0;
  7432. thread_reportout(mythr);
  7433. }
  7434. /* Create a hashtable of work items for devices with a queue. The device
  7435. * driver must have a custom queue_full function or it will default to true
  7436. * and put only one work item in the queue. Work items should not be removed
  7437. * from this hashtable until they are no longer in use anywhere. Once a work
  7438. * item is physically queued on the device itself, the work->queued flag
  7439. * should be set under cgpu->qlock write lock to prevent it being dereferenced
  7440. * while still in use. */
  7441. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  7442. {
  7443. thread_reportout(mythr);
  7444. do {
  7445. bool need_work;
  7446. rd_lock(&cgpu->qlock);
  7447. need_work = (HASH_COUNT(cgpu->queued_work) == cgpu->queued_count);
  7448. rd_unlock(&cgpu->qlock);
  7449. if (need_work) {
  7450. struct work *work = get_work(mythr);
  7451. wr_lock(&cgpu->qlock);
  7452. HASH_ADD_INT(cgpu->queued_work, id, work);
  7453. wr_unlock(&cgpu->qlock);
  7454. }
  7455. /* The queue_full function should be used by the driver to
  7456. * actually place work items on the physical device if it
  7457. * does have a queue. */
  7458. } while (drv->queue_full && !drv->queue_full(cgpu));
  7459. }
  7460. /* This function is for retrieving one work item from the queued hashtable of
  7461. * available work items that are not yet physically on a device (which is
  7462. * flagged with the work->queued bool). Code using this function must be able
  7463. * to handle NULL as a return which implies there is no work available. */
  7464. struct work *get_queued(struct cgpu_info *cgpu)
  7465. {
  7466. struct work *work, *tmp, *ret = NULL;
  7467. wr_lock(&cgpu->qlock);
  7468. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  7469. if (!work->queued) {
  7470. work->queued = true;
  7471. cgpu->queued_count++;
  7472. ret = work;
  7473. break;
  7474. }
  7475. }
  7476. wr_unlock(&cgpu->qlock);
  7477. return ret;
  7478. }
  7479. /* This function is for finding an already queued work item in the
  7480. * given que hashtable. Code using this function must be able
  7481. * to handle NULL as a return which implies there is no matching work.
  7482. * The calling function must lock access to the que if it is required.
  7483. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7484. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7485. {
  7486. struct work *work, *tmp, *ret = NULL;
  7487. HASH_ITER(hh, que, work, tmp) {
  7488. if (work->queued &&
  7489. memcmp(work->midstate, midstate, midstatelen) == 0 &&
  7490. memcmp(work->data + offset, data, datalen) == 0) {
  7491. ret = work;
  7492. break;
  7493. }
  7494. }
  7495. return ret;
  7496. }
  7497. /* This function is for finding an already queued work item in the
  7498. * device's queued_work hashtable. Code using this function must be able
  7499. * to handle NULL as a return which implies there is no matching work.
  7500. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7501. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7502. {
  7503. struct work *ret;
  7504. rd_lock(&cgpu->qlock);
  7505. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  7506. rd_unlock(&cgpu->qlock);
  7507. return ret;
  7508. }
  7509. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7510. {
  7511. struct work *work, *ret = NULL;
  7512. rd_lock(&cgpu->qlock);
  7513. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  7514. if (work)
  7515. ret = copy_work(work);
  7516. rd_unlock(&cgpu->qlock);
  7517. return ret;
  7518. }
  7519. static void __work_completed(struct cgpu_info *cgpu, struct work *work)
  7520. {
  7521. if (work->queued)
  7522. cgpu->queued_count--;
  7523. HASH_DEL(cgpu->queued_work, work);
  7524. }
  7525. /* This function should be used by queued device drivers when they're sure
  7526. * the work struct is no longer in use. */
  7527. void work_completed(struct cgpu_info *cgpu, struct work *work)
  7528. {
  7529. wr_lock(&cgpu->qlock);
  7530. __work_completed(cgpu, work);
  7531. wr_unlock(&cgpu->qlock);
  7532. free_work(work);
  7533. }
  7534. /* Combines find_queued_work_bymidstate and work_completed in one function
  7535. * withOUT destroying the work so the driver must free it. */
  7536. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7537. {
  7538. struct work *work;
  7539. wr_lock(&cgpu->qlock);
  7540. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  7541. if (work)
  7542. __work_completed(cgpu, work);
  7543. wr_unlock(&cgpu->qlock);
  7544. return work;
  7545. }
  7546. static void flush_queue(struct cgpu_info *cgpu)
  7547. {
  7548. struct work *work, *tmp;
  7549. int discarded = 0;
  7550. wr_lock(&cgpu->qlock);
  7551. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  7552. /* Can only discard the work items if they're not physically
  7553. * queued on the device. */
  7554. if (!work->queued) {
  7555. HASH_DEL(cgpu->queued_work, work);
  7556. discard_work(work);
  7557. discarded++;
  7558. }
  7559. }
  7560. wr_unlock(&cgpu->qlock);
  7561. if (discarded)
  7562. applog(LOG_DEBUG, "Discarded %d queued work items", discarded);
  7563. }
  7564. /* This version of hash work is for devices that are fast enough to always
  7565. * perform a full nonce range and need a queue to maintain the device busy.
  7566. * Work creation and destruction is not done from within this function
  7567. * directly. */
  7568. void hash_queued_work(struct thr_info *mythr)
  7569. {
  7570. const long cycle = opt_log_interval / 5 ? : 1;
  7571. struct timeval tv_start = {0, 0}, tv_end;
  7572. struct cgpu_info *cgpu = mythr->cgpu;
  7573. struct device_drv *drv = cgpu->drv;
  7574. const int thr_id = mythr->id;
  7575. int64_t hashes_done = 0;
  7576. while (likely(!cgpu->shutdown)) {
  7577. struct timeval diff;
  7578. int64_t hashes;
  7579. mythr->work_restart = false;
  7580. fill_queue(mythr, cgpu, drv, thr_id);
  7581. thread_reportin(mythr);
  7582. hashes = drv->scanwork(mythr);
  7583. if (unlikely(hashes == -1 )) {
  7584. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  7585. cgpu->deven = DEV_DISABLED;
  7586. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  7587. mt_disable(mythr);
  7588. }
  7589. hashes_done += hashes;
  7590. cgtime(&tv_end);
  7591. timersub(&tv_end, &tv_start, &diff);
  7592. if (diff.tv_sec >= cycle) {
  7593. hashmeter(thr_id, &diff, hashes_done);
  7594. hashes_done = 0;
  7595. copy_time(&tv_start, &tv_end);
  7596. }
  7597. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  7598. mt_disable(mythr);
  7599. if (unlikely(mythr->work_restart)) {
  7600. flush_queue(cgpu);
  7601. if (drv->flush_work)
  7602. drv->flush_work(cgpu);
  7603. }
  7604. }
  7605. // cgpu->deven = DEV_DISABLED; set in miner_thread
  7606. }
  7607. void mt_disable_finish(struct thr_info *mythr)
  7608. {
  7609. struct device_drv *drv = mythr->cgpu->drv;
  7610. thread_reportin(mythr);
  7611. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  7612. if (drv->thread_enable)
  7613. drv->thread_enable(mythr);
  7614. }
  7615. void mt_disable(struct thr_info *mythr)
  7616. {
  7617. mt_disable_start(mythr);
  7618. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  7619. do {
  7620. notifier_read(mythr->notifier);
  7621. } while (mythr->pause);
  7622. mt_disable_finish(mythr);
  7623. }
  7624. enum {
  7625. STAT_SLEEP_INTERVAL = 1,
  7626. STAT_CTR_INTERVAL = 10000000,
  7627. FAILURE_INTERVAL = 30,
  7628. };
  7629. /* Stage another work item from the work returned in a longpoll */
  7630. 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)
  7631. {
  7632. bool rc;
  7633. work->rolltime = rolltime;
  7634. rc = work_decode(pool, work, val);
  7635. if (unlikely(!rc)) {
  7636. applog(LOG_ERR, "Could not convert longpoll data to work");
  7637. free_work(work);
  7638. return;
  7639. }
  7640. total_getworks++;
  7641. pool->getwork_requested++;
  7642. work->pool = pool;
  7643. copy_time(&work->tv_getwork, tv_lp);
  7644. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  7645. calc_diff(work, 0);
  7646. if (pool->enabled == POOL_REJECTING)
  7647. work->mandatory = true;
  7648. work->longpoll = true;
  7649. work->getwork_mode = GETWORK_MODE_LP;
  7650. update_last_work(work);
  7651. /* We'll be checking this work item twice, but we already know it's
  7652. * from a new block so explicitly force the new block detection now
  7653. * rather than waiting for it to hit the stage thread. This also
  7654. * allows testwork to know whether LP discovered the block or not. */
  7655. test_work_current(work);
  7656. /* Don't use backup LPs as work if we have failover-only enabled. Use
  7657. * the longpoll work from a pool that has been rejecting shares as a
  7658. * way to detect when the pool has recovered.
  7659. */
  7660. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  7661. free_work(work);
  7662. return;
  7663. }
  7664. work = clone_work(work);
  7665. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  7666. stage_work(work);
  7667. applog(LOG_DEBUG, "Converted longpoll data to work");
  7668. }
  7669. /* If we want longpoll, enable it for the chosen default pool, or, if
  7670. * the pool does not support longpoll, find the first one that does
  7671. * and use its longpoll support */
  7672. static struct pool *select_longpoll_pool(struct pool *cp)
  7673. {
  7674. int i;
  7675. if (cp->lp_url)
  7676. return cp;
  7677. for (i = 0; i < total_pools; i++) {
  7678. struct pool *pool = pools[i];
  7679. if (pool->has_stratum || pool->lp_url)
  7680. return pool;
  7681. }
  7682. return NULL;
  7683. }
  7684. /* This will make the longpoll thread wait till it's the current pool, or it
  7685. * has been flagged as rejecting, before attempting to open any connections.
  7686. */
  7687. static void wait_lpcurrent(struct pool *pool)
  7688. {
  7689. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  7690. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  7691. pool_strategy != POOL_BALANCE))) {
  7692. mutex_lock(&lp_lock);
  7693. pthread_cond_wait(&lp_cond, &lp_lock);
  7694. mutex_unlock(&lp_lock);
  7695. }
  7696. }
  7697. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  7698. struct pool *pool = vpool;
  7699. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  7700. pool->lp_socket = sock;
  7701. return sock;
  7702. }
  7703. static void *longpoll_thread(void *userdata)
  7704. {
  7705. struct pool *cp = (struct pool *)userdata;
  7706. /* This *pool is the source of the actual longpoll, not the pool we've
  7707. * tied it to */
  7708. struct timeval start, reply, end;
  7709. struct pool *pool = NULL;
  7710. char threadname[20];
  7711. CURL *curl = NULL;
  7712. int failures = 0;
  7713. char *lp_url;
  7714. int rolltime;
  7715. #ifndef HAVE_PTHREAD_CANCEL
  7716. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7717. #endif
  7718. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  7719. RenameThread(threadname);
  7720. curl = curl_easy_init();
  7721. if (unlikely(!curl)) {
  7722. applog(LOG_ERR, "CURL initialisation failed");
  7723. return NULL;
  7724. }
  7725. retry_pool:
  7726. pool = select_longpoll_pool(cp);
  7727. if (!pool) {
  7728. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  7729. while (!pool) {
  7730. cgsleep_ms(60000);
  7731. pool = select_longpoll_pool(cp);
  7732. }
  7733. }
  7734. if (pool->has_stratum) {
  7735. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7736. cp->rpc_url, pool->rpc_url);
  7737. goto out;
  7738. }
  7739. /* Any longpoll from any pool is enough for this to be true */
  7740. have_longpoll = true;
  7741. wait_lpcurrent(cp);
  7742. {
  7743. lp_url = pool->lp_url;
  7744. if (cp == pool)
  7745. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  7746. else
  7747. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  7748. }
  7749. while (42) {
  7750. json_t *val, *soval;
  7751. struct work *work = make_work();
  7752. char *lpreq;
  7753. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  7754. work->pool = pool;
  7755. if (!lpreq)
  7756. {
  7757. free_work(work);
  7758. goto lpfail;
  7759. }
  7760. wait_lpcurrent(cp);
  7761. cgtime(&start);
  7762. /* Longpoll connections can be persistent for a very long time
  7763. * and any number of issues could have come up in the meantime
  7764. * so always establish a fresh connection instead of relying on
  7765. * a persistent one. */
  7766. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  7767. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  7768. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  7769. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  7770. lpreq, false, true, &rolltime, pool, false);
  7771. pool->lp_socket = CURL_SOCKET_BAD;
  7772. cgtime(&reply);
  7773. free(lpreq);
  7774. if (likely(val)) {
  7775. soval = json_object_get(json_object_get(val, "result"), "submitold");
  7776. if (soval)
  7777. pool->submit_old = json_is_true(soval);
  7778. else
  7779. pool->submit_old = false;
  7780. convert_to_work(val, rolltime, pool, work, &start, &reply);
  7781. failures = 0;
  7782. json_decref(val);
  7783. } else {
  7784. /* Some pools regularly drop the longpoll request so
  7785. * only see this as longpoll failure if it happens
  7786. * immediately and just restart it the rest of the
  7787. * time. */
  7788. cgtime(&end);
  7789. free_work(work);
  7790. if (end.tv_sec - start.tv_sec > 30)
  7791. continue;
  7792. if (failures == 1)
  7793. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7794. lpfail:
  7795. cgsleep_ms(30000);
  7796. }
  7797. if (pool != cp) {
  7798. pool = select_longpoll_pool(cp);
  7799. if (pool->has_stratum) {
  7800. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7801. cp->rpc_url, pool->rpc_url);
  7802. break;
  7803. }
  7804. if (unlikely(!pool))
  7805. goto retry_pool;
  7806. }
  7807. if (unlikely(pool->removed))
  7808. break;
  7809. }
  7810. out:
  7811. curl_easy_cleanup(curl);
  7812. return NULL;
  7813. }
  7814. static void stop_longpoll(void)
  7815. {
  7816. int i;
  7817. want_longpoll = false;
  7818. for (i = 0; i < total_pools; ++i)
  7819. {
  7820. struct pool *pool = pools[i];
  7821. if (unlikely(!pool->lp_started))
  7822. continue;
  7823. pool->lp_started = false;
  7824. pthread_cancel(pool->longpoll_thread);
  7825. }
  7826. have_longpoll = false;
  7827. }
  7828. static void start_longpoll(void)
  7829. {
  7830. int i;
  7831. want_longpoll = true;
  7832. for (i = 0; i < total_pools; ++i)
  7833. {
  7834. struct pool *pool = pools[i];
  7835. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  7836. continue;
  7837. pool->lp_started = true;
  7838. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7839. quit(1, "Failed to create pool longpoll thread");
  7840. }
  7841. }
  7842. void reinit_device(struct cgpu_info *cgpu)
  7843. {
  7844. if (cgpu->drv->reinit_device)
  7845. cgpu->drv->reinit_device(cgpu);
  7846. }
  7847. static struct timeval rotate_tv;
  7848. /* We reap curls if they are unused for over a minute */
  7849. static void reap_curl(struct pool *pool)
  7850. {
  7851. struct curl_ent *ent, *iter;
  7852. struct timeval now;
  7853. int reaped = 0;
  7854. cgtime(&now);
  7855. mutex_lock(&pool->pool_lock);
  7856. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  7857. if (pool->curls < 2)
  7858. break;
  7859. if (now.tv_sec - ent->tv.tv_sec > 300) {
  7860. reaped++;
  7861. pool->curls--;
  7862. LL_DELETE(pool->curllist, ent);
  7863. curl_easy_cleanup(ent->curl);
  7864. free(ent);
  7865. }
  7866. }
  7867. mutex_unlock(&pool->pool_lock);
  7868. if (reaped)
  7869. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  7870. }
  7871. static void *watchpool_thread(void __maybe_unused *userdata)
  7872. {
  7873. int intervals = 0;
  7874. #ifndef HAVE_PTHREAD_CANCEL
  7875. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7876. #endif
  7877. RenameThread("watchpool");
  7878. while (42) {
  7879. struct timeval now;
  7880. int i;
  7881. if (++intervals > 20)
  7882. intervals = 0;
  7883. cgtime(&now);
  7884. for (i = 0; i < total_pools; i++) {
  7885. struct pool *pool = pools[i];
  7886. if (!opt_benchmark)
  7887. reap_curl(pool);
  7888. /* Get a rolling utility per pool over 10 mins */
  7889. if (intervals > 19) {
  7890. int shares = pool->diff1 - pool->last_shares;
  7891. pool->last_shares = pool->diff1;
  7892. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  7893. pool->shares = pool->utility;
  7894. }
  7895. if (pool->enabled == POOL_DISABLED)
  7896. continue;
  7897. /* Don't start testing any pools if the test threads
  7898. * from startup are still doing their first attempt. */
  7899. if (unlikely(pool->testing)) {
  7900. pthread_join(pool->test_thread, NULL);
  7901. }
  7902. /* Test pool is idle once every minute */
  7903. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  7904. cgtime(&pool->tv_idle);
  7905. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  7906. pool_resus(pool);
  7907. }
  7908. }
  7909. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  7910. cgtime(&rotate_tv);
  7911. switch_pools(NULL);
  7912. }
  7913. cgsleep_ms(30000);
  7914. }
  7915. return NULL;
  7916. }
  7917. void mt_enable(struct thr_info *thr)
  7918. {
  7919. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  7920. notifier_wake(thr->notifier);
  7921. }
  7922. void proc_enable(struct cgpu_info *cgpu)
  7923. {
  7924. int j;
  7925. cgpu->deven = DEV_ENABLED;
  7926. for (j = cgpu->threads ?: 1; j--; )
  7927. mt_enable(cgpu->thr[j]);
  7928. }
  7929. #define device_recovered(cgpu) proc_enable(cgpu)
  7930. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  7931. * the screen at regular intervals, and restarts threads if they appear to have
  7932. * died. */
  7933. #define WATCHDOG_SICK_TIME 60
  7934. #define WATCHDOG_DEAD_TIME 600
  7935. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  7936. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  7937. static void *watchdog_thread(void __maybe_unused *userdata)
  7938. {
  7939. const unsigned int interval = WATCHDOG_INTERVAL;
  7940. struct timeval zero_tv;
  7941. #ifndef HAVE_PTHREAD_CANCEL
  7942. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7943. #endif
  7944. RenameThread("watchdog");
  7945. memset(&zero_tv, 0, sizeof(struct timeval));
  7946. cgtime(&rotate_tv);
  7947. while (1) {
  7948. int i;
  7949. struct timeval now;
  7950. sleep(interval);
  7951. discard_stale();
  7952. hashmeter(-1, &zero_tv, 0);
  7953. #ifdef HAVE_CURSES
  7954. const int ts = total_staged();
  7955. if (curses_active_locked()) {
  7956. change_logwinsize();
  7957. curses_print_status(ts);
  7958. for (i = 0; i < total_devices; i++)
  7959. curses_print_devstatus(get_devices(i));
  7960. touchwin(statuswin);
  7961. wrefresh(statuswin);
  7962. touchwin(logwin);
  7963. wrefresh(logwin);
  7964. unlock_curses();
  7965. }
  7966. #endif
  7967. cgtime(&now);
  7968. if (!sched_paused && !should_run()) {
  7969. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  7970. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7971. if (!schedstart.enable) {
  7972. quit(0, "Terminating execution as planned");
  7973. break;
  7974. }
  7975. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  7976. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7977. sched_paused = true;
  7978. rd_lock(&mining_thr_lock);
  7979. for (i = 0; i < mining_threads; i++)
  7980. mining_thr[i]->pause = true;
  7981. rd_unlock(&mining_thr_lock);
  7982. } else if (sched_paused && should_run()) {
  7983. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  7984. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7985. if (schedstop.enable)
  7986. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  7987. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7988. sched_paused = false;
  7989. for (i = 0; i < mining_threads; i++) {
  7990. struct thr_info *thr;
  7991. thr = get_thread(i);
  7992. thr->pause = false;
  7993. }
  7994. for (i = 0; i < total_devices; ++i)
  7995. {
  7996. struct cgpu_info *cgpu = get_devices(i);
  7997. /* Don't touch disabled devices */
  7998. if (cgpu->deven == DEV_DISABLED)
  7999. continue;
  8000. proc_enable(cgpu);
  8001. }
  8002. }
  8003. for (i = 0; i < total_devices; ++i) {
  8004. struct cgpu_info *cgpu = get_devices(i);
  8005. if (!cgpu->disable_watchdog)
  8006. bfg_watchdog(cgpu, &now);
  8007. }
  8008. }
  8009. return NULL;
  8010. }
  8011. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  8012. {
  8013. struct thr_info *thr = cgpu->thr[0];
  8014. enum dev_enable *denable;
  8015. char *dev_str = cgpu->proc_repr;
  8016. int gpu;
  8017. if (cgpu->drv->get_stats && likely(drv_ready(cgpu)))
  8018. cgpu->drv->get_stats(cgpu);
  8019. gpu = cgpu->device_id;
  8020. denable = &cgpu->deven;
  8021. #ifdef HAVE_ADL
  8022. if (adl_active && cgpu->has_adl)
  8023. gpu_autotune(gpu, denable);
  8024. if (opt_debug && cgpu->has_adl) {
  8025. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  8026. float temp = 0, vddc = 0;
  8027. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  8028. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMHz V: %.3fV A: %d%% P: %d%%",
  8029. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  8030. }
  8031. #endif
  8032. /* Thread is disabled */
  8033. if (*denable == DEV_DISABLED)
  8034. return;
  8035. else
  8036. if (*denable == DEV_RECOVER_ERR) {
  8037. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  8038. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  8039. dev_str);
  8040. if (cgpu->reinit_backoff < 300)
  8041. cgpu->reinit_backoff *= 2;
  8042. device_recovered(cgpu);
  8043. }
  8044. return;
  8045. }
  8046. else
  8047. if (*denable == DEV_RECOVER) {
  8048. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  8049. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  8050. dev_str);
  8051. device_recovered(cgpu);
  8052. }
  8053. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8054. return;
  8055. }
  8056. else
  8057. if (cgpu->temp > cgpu->cutofftemp)
  8058. {
  8059. applog(LOG_WARNING, "%s hit thermal cutoff limit, disabling!",
  8060. dev_str);
  8061. *denable = DEV_RECOVER;
  8062. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8063. run_cmd(cmd_idle);
  8064. }
  8065. if (thr->getwork) {
  8066. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  8067. int thrid;
  8068. bool cgpu_idle = true;
  8069. thr->rolling = 0;
  8070. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  8071. if (!cgpu->thr[thrid]->getwork)
  8072. cgpu_idle = false;
  8073. if (cgpu_idle) {
  8074. cgpu->rolling = 0;
  8075. cgpu->status = LIFE_WAIT;
  8076. }
  8077. }
  8078. return;
  8079. }
  8080. else if (cgpu->status == LIFE_WAIT)
  8081. cgpu->status = LIFE_WELL;
  8082. #ifdef WANT_CPUMINE
  8083. if (!strcmp(cgpu->drv->dname, "cpu"))
  8084. return;
  8085. #endif
  8086. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  8087. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  8088. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  8089. cgpu->status = LIFE_WELL;
  8090. cgpu->device_last_well = time(NULL);
  8091. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  8092. thr->rolling = cgpu->rolling = 0;
  8093. cgpu->status = LIFE_SICK;
  8094. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  8095. cgtime(&thr->sick);
  8096. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  8097. run_cmd(cmd_sick);
  8098. #ifdef HAVE_ADL
  8099. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8100. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  8101. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  8102. } else
  8103. #endif
  8104. if (opt_restart && cgpu->drv->reinit_device) {
  8105. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  8106. reinit_device(cgpu);
  8107. }
  8108. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  8109. cgpu->status = LIFE_DEAD;
  8110. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  8111. cgtime(&thr->sick);
  8112. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  8113. run_cmd(cmd_dead);
  8114. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  8115. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  8116. /* Attempt to restart a GPU that's sick or dead once every minute */
  8117. cgtime(&thr->sick);
  8118. #ifdef HAVE_ADL
  8119. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8120. /* Again do not attempt to restart a device that may have hard hung */
  8121. } else
  8122. #endif
  8123. if (opt_restart)
  8124. reinit_device(cgpu);
  8125. }
  8126. }
  8127. static void log_print_status(struct cgpu_info *cgpu)
  8128. {
  8129. char logline[255];
  8130. get_statline(logline, sizeof(logline), cgpu);
  8131. applog(LOG_WARNING, "%s", logline);
  8132. }
  8133. void print_summary(void)
  8134. {
  8135. struct timeval diff;
  8136. int hours, mins, secs, i;
  8137. double utility, efficiency = 0.0;
  8138. char xfer[17], bw[19];
  8139. int pool_secs;
  8140. timersub(&total_tv_end, &total_tv_start, &diff);
  8141. hours = diff.tv_sec / 3600;
  8142. mins = (diff.tv_sec % 3600) / 60;
  8143. secs = diff.tv_sec % 60;
  8144. utility = total_accepted / total_secs * 60;
  8145. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  8146. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  8147. applog(LOG_WARNING, "Started at %s", datestamp);
  8148. if (total_pools == 1)
  8149. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  8150. #ifdef WANT_CPUMINE
  8151. if (opt_n_threads)
  8152. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  8153. #endif
  8154. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  8155. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  8156. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  8157. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  8158. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  8159. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  8160. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  8161. total_rejected, total_stale,
  8162. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  8163. );
  8164. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  8165. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  8166. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  8167. applog(LOG_WARNING, "Network transfer: %s (%s)",
  8168. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8169. (float)total_bytes_rcvd,
  8170. (float)total_bytes_sent),
  8171. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8172. (float)(total_bytes_rcvd / total_secs),
  8173. (float)(total_bytes_sent / total_secs)));
  8174. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  8175. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  8176. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  8177. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  8178. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  8179. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  8180. if (total_pools > 1) {
  8181. for (i = 0; i < total_pools; i++) {
  8182. struct pool *pool = pools[i];
  8183. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  8184. if (pool->solved)
  8185. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  8186. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  8187. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  8188. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  8189. pool->rejected, pool->stale_shares,
  8190. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  8191. );
  8192. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  8193. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  8194. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  8195. applog(LOG_WARNING, " Network transfer: %s (%s)",
  8196. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8197. (float)pool->cgminer_pool_stats.net_bytes_received,
  8198. (float)pool->cgminer_pool_stats.net_bytes_sent),
  8199. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8200. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  8201. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  8202. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  8203. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  8204. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  8205. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  8206. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  8207. }
  8208. }
  8209. applog(LOG_WARNING, "Summary of per device statistics:\n");
  8210. for (i = 0; i < total_devices; ++i) {
  8211. struct cgpu_info *cgpu = get_devices(i);
  8212. if ((!cgpu->proc_id) && cgpu->procs > 1)
  8213. {
  8214. // Device summary line
  8215. opt_show_procs = false;
  8216. log_print_status(cgpu);
  8217. opt_show_procs = true;
  8218. }
  8219. log_print_status(cgpu);
  8220. }
  8221. if (opt_shares) {
  8222. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  8223. if (opt_shares > total_accepted)
  8224. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  8225. }
  8226. applog(LOG_WARNING, " ");
  8227. fflush(stderr);
  8228. fflush(stdout);
  8229. }
  8230. void _bfg_clean_up(void)
  8231. {
  8232. #ifdef HAVE_OPENCL
  8233. clear_adl(nDevs);
  8234. #endif
  8235. #ifdef HAVE_LIBUSB
  8236. if (likely(have_libusb))
  8237. libusb_exit(NULL);
  8238. #endif
  8239. cgtime(&total_tv_end);
  8240. #ifdef WIN32
  8241. timeEndPeriod(1);
  8242. #endif
  8243. #ifdef HAVE_CURSES
  8244. disable_curses();
  8245. #endif
  8246. if (!opt_realquiet && successful_connect)
  8247. print_summary();
  8248. if (opt_n_threads)
  8249. free(cpus);
  8250. curl_global_cleanup();
  8251. }
  8252. void _quit(int status)
  8253. {
  8254. if (status) {
  8255. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  8256. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  8257. int *p = NULL;
  8258. // NOTE debugger can bypass with: p = &p
  8259. *p = status; // Segfault, hopefully dumping core
  8260. }
  8261. }
  8262. #if defined(unix) || defined(__APPLE__)
  8263. if (forkpid > 0) {
  8264. kill(forkpid, SIGTERM);
  8265. forkpid = 0;
  8266. }
  8267. #endif
  8268. exit(status);
  8269. }
  8270. #ifdef HAVE_CURSES
  8271. char *curses_input(const char *query)
  8272. {
  8273. char *input;
  8274. echo();
  8275. input = malloc(255);
  8276. if (!input)
  8277. quit(1, "Failed to malloc input");
  8278. leaveok(logwin, false);
  8279. wlogprint("%s:\n", query);
  8280. wgetnstr(logwin, input, 255);
  8281. if (!strlen(input))
  8282. strcpy(input, "-1");
  8283. leaveok(logwin, true);
  8284. noecho();
  8285. return input;
  8286. }
  8287. #endif
  8288. static bool pools_active = false;
  8289. static void *test_pool_thread(void *arg)
  8290. {
  8291. struct pool *pool = (struct pool *)arg;
  8292. if (pool_active(pool, false)) {
  8293. pool_tset(pool, &pool->lagging);
  8294. pool_tclear(pool, &pool->idle);
  8295. bool first_pool = false;
  8296. cg_wlock(&control_lock);
  8297. if (!pools_active) {
  8298. currentpool = pool;
  8299. if (pool->pool_no != 0)
  8300. first_pool = true;
  8301. pools_active = true;
  8302. }
  8303. cg_wunlock(&control_lock);
  8304. if (unlikely(first_pool))
  8305. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  8306. pool_resus(pool);
  8307. } else
  8308. pool_died(pool);
  8309. pool->testing = false;
  8310. return NULL;
  8311. }
  8312. /* Always returns true that the pool details were added unless we are not
  8313. * live, implying this is the only pool being added, so if no pools are
  8314. * active it returns false. */
  8315. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  8316. {
  8317. size_t siz;
  8318. pool->rpc_url = url;
  8319. pool->rpc_user = user;
  8320. pool->rpc_pass = pass;
  8321. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8322. pool->rpc_userpass = malloc(siz);
  8323. if (!pool->rpc_userpass)
  8324. quit(1, "Failed to malloc userpass");
  8325. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8326. pool->testing = true;
  8327. pool->idle = true;
  8328. enable_pool(pool);
  8329. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8330. if (!live) {
  8331. pthread_join(pool->test_thread, NULL);
  8332. return pools_active;
  8333. }
  8334. return true;
  8335. }
  8336. #ifdef HAVE_CURSES
  8337. static bool input_pool(bool live)
  8338. {
  8339. char *url = NULL, *user = NULL, *pass = NULL;
  8340. struct pool *pool;
  8341. bool ret = false;
  8342. immedok(logwin, true);
  8343. wlogprint("Input server details.\n");
  8344. url = curses_input("URL");
  8345. if (!url)
  8346. goto out;
  8347. user = curses_input("Username");
  8348. if (!user)
  8349. goto out;
  8350. pass = curses_input("Password");
  8351. if (!pass)
  8352. goto out;
  8353. pool = add_pool();
  8354. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  8355. strncmp(url, "https://", 8)) {
  8356. char *httpinput;
  8357. httpinput = malloc(256);
  8358. if (!httpinput)
  8359. quit(1, "Failed to malloc httpinput");
  8360. strcpy(httpinput, "http://");
  8361. strncat(httpinput, url, 248);
  8362. free(url);
  8363. url = httpinput;
  8364. }
  8365. ret = add_pool_details(pool, live, url, user, pass);
  8366. out:
  8367. immedok(logwin, false);
  8368. if (!ret) {
  8369. if (url)
  8370. free(url);
  8371. if (user)
  8372. free(user);
  8373. if (pass)
  8374. free(pass);
  8375. }
  8376. return ret;
  8377. }
  8378. #endif
  8379. #if defined(unix) || defined(__APPLE__)
  8380. static void fork_monitor()
  8381. {
  8382. // Make a pipe: [readFD, writeFD]
  8383. int pfd[2];
  8384. int r = pipe(pfd);
  8385. if (r < 0) {
  8386. perror("pipe - failed to create pipe for --monitor");
  8387. exit(1);
  8388. }
  8389. // Make stderr write end of pipe
  8390. fflush(stderr);
  8391. r = dup2(pfd[1], 2);
  8392. if (r < 0) {
  8393. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  8394. exit(1);
  8395. }
  8396. r = close(pfd[1]);
  8397. if (r < 0) {
  8398. perror("close - failed to close write end of pipe for --monitor");
  8399. exit(1);
  8400. }
  8401. // Don't allow a dying monitor to kill the main process
  8402. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  8403. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  8404. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  8405. perror("signal - failed to edit signal mask for --monitor");
  8406. exit(1);
  8407. }
  8408. // Fork a child process
  8409. forkpid = fork();
  8410. if (forkpid < 0) {
  8411. perror("fork - failed to fork child process for --monitor");
  8412. exit(1);
  8413. }
  8414. // Child: launch monitor command
  8415. if (0 == forkpid) {
  8416. // Make stdin read end of pipe
  8417. r = dup2(pfd[0], 0);
  8418. if (r < 0) {
  8419. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  8420. exit(1);
  8421. }
  8422. close(pfd[0]);
  8423. if (r < 0) {
  8424. perror("close - in child, failed to close read end of pipe for --monitor");
  8425. exit(1);
  8426. }
  8427. // Launch user specified command
  8428. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  8429. perror("execl - in child failed to exec user specified command for --monitor");
  8430. exit(1);
  8431. }
  8432. // Parent: clean up unused fds and bail
  8433. r = close(pfd[0]);
  8434. if (r < 0) {
  8435. perror("close - failed to close read end of pipe for --monitor");
  8436. exit(1);
  8437. }
  8438. }
  8439. #endif // defined(unix)
  8440. #ifdef HAVE_CURSES
  8441. #ifdef USE_UNICODE
  8442. static
  8443. wchar_t select_unicode_char(const wchar_t *opt)
  8444. {
  8445. for ( ; *opt; ++opt)
  8446. if (iswprint(*opt))
  8447. return *opt;
  8448. return '?';
  8449. }
  8450. #endif
  8451. void enable_curses(void) {
  8452. int x;
  8453. __maybe_unused int y;
  8454. lock_curses();
  8455. if (curses_active) {
  8456. unlock_curses();
  8457. return;
  8458. }
  8459. #ifdef USE_UNICODE
  8460. if (use_unicode)
  8461. {
  8462. setlocale(LC_CTYPE, "");
  8463. if (iswprint(0xb0))
  8464. have_unicode_degrees = true;
  8465. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  8466. }
  8467. #endif
  8468. mainwin = initscr();
  8469. start_color();
  8470. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  8471. if (ERR != use_default_colors())
  8472. default_bgcolor = -1;
  8473. #endif
  8474. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  8475. {
  8476. menu_attr = COLOR_PAIR(1);
  8477. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  8478. attr_bad |= COLOR_PAIR(2);
  8479. }
  8480. keypad(mainwin, true);
  8481. getmaxyx(mainwin, y, x);
  8482. statuswin = newwin(logstart, x, 0, 0);
  8483. leaveok(statuswin, true);
  8484. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  8485. // We resize the window later anyway, so just start it off at 1 :)
  8486. logwin = newwin(1, 0, logcursor, 0);
  8487. idlok(logwin, true);
  8488. scrollok(logwin, true);
  8489. leaveok(logwin, true);
  8490. cbreak();
  8491. noecho();
  8492. nonl();
  8493. curses_active = true;
  8494. statusy = logstart;
  8495. unlock_curses();
  8496. }
  8497. #endif
  8498. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  8499. #ifndef WANT_CPUMINE
  8500. struct device_drv cpu_drv;
  8501. struct device_drv cpu_drv = {
  8502. .name = "CPU",
  8503. };
  8504. #endif
  8505. #ifdef USE_BITFORCE
  8506. extern struct device_drv bitforce_drv;
  8507. #endif
  8508. #ifdef USE_BIGPIC
  8509. extern struct device_drv bigpic_drv;
  8510. #endif
  8511. #ifdef USE_ICARUS
  8512. extern struct device_drv cairnsmore_drv;
  8513. extern struct device_drv erupter_drv;
  8514. extern struct device_drv icarus_drv;
  8515. #endif
  8516. #ifdef USE_AVALON
  8517. extern struct device_drv avalon_drv;
  8518. #endif
  8519. #ifdef USE_LITTLEFURY
  8520. extern struct device_drv littlefury_drv;
  8521. #endif
  8522. #ifdef USE_MODMINER
  8523. extern struct device_drv modminer_drv;
  8524. #endif
  8525. #ifdef USE_X6500
  8526. extern struct device_drv x6500_api;
  8527. #endif
  8528. #ifdef USE_ZTEX
  8529. extern struct device_drv ztex_drv;
  8530. #endif
  8531. #ifdef USE_BITFURY
  8532. extern struct device_drv bitfury_drv;
  8533. #endif
  8534. #ifdef USE_METABANK
  8535. extern struct device_drv metabank_drv;
  8536. #endif
  8537. #ifdef USE_BFSB
  8538. extern struct device_drv bfsb_drv;
  8539. #endif
  8540. static int cgminer_id_count = 0;
  8541. static int device_line_id_count;
  8542. void register_device(struct cgpu_info *cgpu)
  8543. {
  8544. cgpu->deven = DEV_ENABLED;
  8545. wr_lock(&devices_lock);
  8546. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  8547. wr_unlock(&devices_lock);
  8548. if (!cgpu->proc_id)
  8549. cgpu->device_line_id = device_line_id_count++;
  8550. mining_threads += cgpu->threads ?: 1;
  8551. #ifdef HAVE_CURSES
  8552. adj_width(mining_threads, &dev_width);
  8553. #endif
  8554. #ifdef HAVE_OPENCL
  8555. if (cgpu->drv == &opencl_api) {
  8556. gpu_threads += cgpu->threads;
  8557. }
  8558. #endif
  8559. rwlock_init(&cgpu->qlock);
  8560. cgpu->queued_work = NULL;
  8561. }
  8562. struct _cgpu_devid_counter {
  8563. char name[4];
  8564. int lastid;
  8565. UT_hash_handle hh;
  8566. };
  8567. void renumber_cgpu(struct cgpu_info *cgpu)
  8568. {
  8569. static struct _cgpu_devid_counter *devids = NULL;
  8570. struct _cgpu_devid_counter *d;
  8571. HASH_FIND_STR(devids, cgpu->drv->name, d);
  8572. if (d)
  8573. cgpu->device_id = ++d->lastid;
  8574. else {
  8575. d = malloc(sizeof(*d));
  8576. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  8577. cgpu->device_id = d->lastid = 0;
  8578. HASH_ADD_STR(devids, name, d);
  8579. }
  8580. }
  8581. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  8582. {
  8583. sha256(buffer, length, digest);
  8584. return true;
  8585. }
  8586. #ifndef HAVE_PTHREAD_CANCEL
  8587. extern void setup_pthread_cancel_workaround();
  8588. extern struct sigaction pcwm_orig_term_handler;
  8589. #endif
  8590. static
  8591. void drv_detect_all()
  8592. {
  8593. #ifdef USE_X6500
  8594. if (likely(have_libusb))
  8595. ft232r_scan();
  8596. #endif
  8597. #ifdef USE_ICARUS
  8598. if (!opt_scrypt)
  8599. {
  8600. cairnsmore_drv.drv_detect();
  8601. erupter_drv.drv_detect();
  8602. icarus_drv.drv_detect();
  8603. }
  8604. #endif
  8605. #ifdef USE_BITFORCE
  8606. if (!opt_scrypt)
  8607. bitforce_drv.drv_detect();
  8608. #endif
  8609. #ifdef USE_BIGPIC
  8610. if (!opt_scrypt)
  8611. bigpic_drv.drv_detect();
  8612. #endif
  8613. #ifdef USE_MODMINER
  8614. if (!opt_scrypt)
  8615. modminer_drv.drv_detect();
  8616. #endif
  8617. #ifdef USE_X6500
  8618. if (likely(have_libusb) && !opt_scrypt)
  8619. x6500_api.drv_detect();
  8620. #endif
  8621. #ifdef USE_ZTEX
  8622. if (likely(have_libusb) && !opt_scrypt)
  8623. ztex_drv.drv_detect();
  8624. #endif
  8625. #ifdef USE_BITFURY
  8626. if (!opt_scrypt)
  8627. {
  8628. bitfury_drv.drv_detect();
  8629. #ifdef USE_METABANK
  8630. metabank_drv.drv_detect();
  8631. #endif
  8632. #ifdef USE_BFSB
  8633. bfsb_drv.drv_detect();
  8634. #endif
  8635. }
  8636. #endif
  8637. #ifdef USE_LITTLEFURY
  8638. if (!opt_scrypt)
  8639. littlefury_drv.drv_detect();
  8640. #endif
  8641. /* Detect avalon last since it will try to claim the device regardless
  8642. * as detection is unreliable. */
  8643. #ifdef USE_AVALON
  8644. if (!opt_scrypt)
  8645. avalon_drv.drv_detect();
  8646. #endif
  8647. #ifdef WANT_CPUMINE
  8648. cpu_drv.drv_detect();
  8649. #endif
  8650. #ifdef USE_X6500
  8651. if (likely(have_libusb))
  8652. ft232r_scan_free();
  8653. #endif
  8654. #ifdef HAVE_OPENCL
  8655. if (!opt_nogpu)
  8656. opencl_api.drv_detect();
  8657. gpu_threads = 0;
  8658. #endif
  8659. }
  8660. static
  8661. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  8662. {
  8663. struct thr_info *thr;
  8664. int j;
  8665. struct device_drv *api = cgpu->drv;
  8666. if (!cgpu->devtype)
  8667. cgpu->devtype = "PGA";
  8668. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8669. int threadobj = cgpu->threads;
  8670. if (!threadobj)
  8671. // Create a fake thread object to handle hashmeter etc
  8672. threadobj = 1;
  8673. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  8674. cgpu->thr[threadobj] = NULL;
  8675. cgpu->status = LIFE_INIT;
  8676. cgpu->max_hashes = 0;
  8677. // Setup thread structs before starting any of the threads, in case they try to interact
  8678. for (j = 0; j < threadobj; ++j, ++*kp) {
  8679. thr = get_thread(*kp);
  8680. thr->id = *kp;
  8681. thr->cgpu = cgpu;
  8682. thr->device_thread = j;
  8683. thr->work_restart_notifier[1] = INVSOCK;
  8684. thr->mutex_request[1] = INVSOCK;
  8685. thr->_job_transition_in_progress = true;
  8686. timerclear(&thr->tv_morework);
  8687. thr->_last_sbr_state = true;
  8688. thr->scanhash_working = true;
  8689. thr->hashes_done = 0;
  8690. timerclear(&thr->tv_hashes_done);
  8691. cgtime(&thr->tv_lastupdate);
  8692. thr->tv_poll.tv_sec = -1;
  8693. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  8694. cgpu->thr[j] = thr;
  8695. }
  8696. if (!cgpu->device->threads)
  8697. notifier_init_invalid(cgpu->thr[0]->notifier);
  8698. else
  8699. if (!cgpu->threads)
  8700. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  8701. else
  8702. for (j = 0; j < cgpu->threads; ++j)
  8703. {
  8704. thr = cgpu->thr[j];
  8705. notifier_init(thr->notifier);
  8706. }
  8707. }
  8708. static
  8709. void start_cgpu(struct cgpu_info *cgpu)
  8710. {
  8711. struct thr_info *thr;
  8712. int j;
  8713. for (j = 0; j < cgpu->threads; ++j) {
  8714. thr = cgpu->thr[j];
  8715. /* Enable threads for devices set not to mine but disable
  8716. * their queue in case we wish to enable them later */
  8717. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  8718. continue;
  8719. thread_reportout(thr);
  8720. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  8721. quit(1, "thread %d create failed", thr->id);
  8722. }
  8723. if (cgpu->deven == DEV_ENABLED)
  8724. proc_enable(cgpu);
  8725. }
  8726. static
  8727. void _scan_serial(void *p)
  8728. {
  8729. const char *s = p;
  8730. struct string_elist *iter, *tmp;
  8731. struct string_elist *orig_scan_devices = scan_devices;
  8732. if (s)
  8733. {
  8734. // Make temporary scan_devices list
  8735. scan_devices = NULL;
  8736. string_elist_add("noauto", &scan_devices);
  8737. add_serial(s);
  8738. }
  8739. drv_detect_all();
  8740. if (s)
  8741. {
  8742. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  8743. {
  8744. string_elist_del(&scan_devices, iter);
  8745. }
  8746. scan_devices = orig_scan_devices;
  8747. }
  8748. }
  8749. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  8750. {
  8751. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  8752. int devcount, i, mining_threads_new = 0;
  8753. unsigned int k;
  8754. struct cgpu_info *cgpu;
  8755. struct thr_info *thr;
  8756. void *p;
  8757. char *dummy = "\0";
  8758. mutex_lock(&mutex);
  8759. devcount = total_devices;
  8760. addfunc(arg);
  8761. if (!total_devices_new)
  8762. goto out;
  8763. wr_lock(&devices_lock);
  8764. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  8765. if (unlikely(!p))
  8766. {
  8767. wr_unlock(&devices_lock);
  8768. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  8769. goto out;
  8770. }
  8771. devices = p;
  8772. wr_unlock(&devices_lock);
  8773. for (i = 0; i < total_devices_new; ++i)
  8774. {
  8775. cgpu = devices_new[i];
  8776. mining_threads_new += cgpu->threads ?: 1;
  8777. }
  8778. wr_lock(&mining_thr_lock);
  8779. mining_threads_new += mining_threads;
  8780. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  8781. if (unlikely(!p))
  8782. {
  8783. wr_unlock(&mining_thr_lock);
  8784. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  8785. goto out;
  8786. }
  8787. mining_thr = p;
  8788. wr_unlock(&mining_thr_lock);
  8789. for (i = mining_threads; i < mining_threads_new; ++i) {
  8790. mining_thr[i] = calloc(1, sizeof(*thr));
  8791. if (!mining_thr[i])
  8792. {
  8793. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  8794. for ( ; --i >= mining_threads; )
  8795. free(mining_thr[i]);
  8796. goto out;
  8797. }
  8798. }
  8799. k = mining_threads;
  8800. for (i = 0; i < total_devices_new; ++i)
  8801. {
  8802. cgpu = devices_new[i];
  8803. load_temp_config_cgpu(cgpu, &dummy, &dummy);
  8804. allocate_cgpu(cgpu, &k);
  8805. start_cgpu(cgpu);
  8806. register_device(cgpu);
  8807. ++total_devices;
  8808. }
  8809. #ifdef HAVE_CURSES
  8810. switch_logsize();
  8811. #endif
  8812. out:
  8813. total_devices_new = 0;
  8814. devcount = total_devices - devcount;
  8815. mutex_unlock(&mutex);
  8816. return devcount;
  8817. }
  8818. int scan_serial(const char *s)
  8819. {
  8820. return create_new_cgpus(_scan_serial, (void*)s);
  8821. }
  8822. static void probe_pools(void)
  8823. {
  8824. int i;
  8825. for (i = 0; i < total_pools; i++) {
  8826. struct pool *pool = pools[i];
  8827. pool->testing = true;
  8828. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8829. }
  8830. }
  8831. static void raise_fd_limits(void)
  8832. {
  8833. #ifdef HAVE_SETRLIMIT
  8834. struct rlimit fdlimit;
  8835. unsigned long old_soft_limit;
  8836. char frombuf[0x10] = "unlimited";
  8837. char hardbuf[0x10] = "unlimited";
  8838. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  8839. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  8840. old_soft_limit = fdlimit.rlim_cur;
  8841. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  8842. fdlimit.rlim_cur = FD_SETSIZE;
  8843. else
  8844. fdlimit.rlim_cur = fdlimit.rlim_max;
  8845. if (fdlimit.rlim_max != RLIM_INFINITY)
  8846. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  8847. if (old_soft_limit != RLIM_INFINITY)
  8848. snprintf(frombuf, sizeof(frombuf), "%lu", old_soft_limit);
  8849. if (fdlimit.rlim_cur == old_soft_limit)
  8850. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  8851. old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  8852. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  8853. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  8854. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  8855. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  8856. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  8857. #else
  8858. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  8859. #endif
  8860. }
  8861. extern void bfg_init_threadlocal();
  8862. extern void stratumsrv_start();
  8863. int main(int argc, char *argv[])
  8864. {
  8865. struct sigaction handler;
  8866. struct thr_info *thr;
  8867. struct block *block;
  8868. unsigned int k;
  8869. int i;
  8870. char *s;
  8871. #ifdef WIN32
  8872. LoadLibrary("backtrace.dll");
  8873. #endif
  8874. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  8875. bfg_init_threadlocal();
  8876. #ifndef HAVE_PTHREAD_CANCEL
  8877. setup_pthread_cancel_workaround();
  8878. #endif
  8879. /* This dangerous functions tramples random dynamically allocated
  8880. * variables so do it before anything at all */
  8881. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  8882. quit(1, "Failed to curl_global_init");
  8883. initial_args = malloc(sizeof(char *) * (argc + 1));
  8884. for (i = 0; i < argc; i++)
  8885. initial_args[i] = strdup(argv[i]);
  8886. initial_args[argc] = NULL;
  8887. mutex_init(&hash_lock);
  8888. mutex_init(&console_lock);
  8889. cglock_init(&control_lock);
  8890. mutex_init(&stats_lock);
  8891. mutex_init(&sharelog_lock);
  8892. cglock_init(&ch_lock);
  8893. mutex_init(&sshare_lock);
  8894. rwlock_init(&blk_lock);
  8895. rwlock_init(&netacc_lock);
  8896. rwlock_init(&mining_thr_lock);
  8897. rwlock_init(&devices_lock);
  8898. mutex_init(&lp_lock);
  8899. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  8900. quit(1, "Failed to pthread_cond_init lp_cond");
  8901. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  8902. quit(1, "Failed to pthread_cond_init gws_cond");
  8903. notifier_init(submit_waiting_notifier);
  8904. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  8905. #ifdef WANT_CPUMINE
  8906. init_max_name_len();
  8907. #endif
  8908. handler.sa_handler = &sighandler;
  8909. handler.sa_flags = 0;
  8910. sigemptyset(&handler.sa_mask);
  8911. #ifdef HAVE_PTHREAD_CANCEL
  8912. sigaction(SIGTERM, &handler, &termhandler);
  8913. #else
  8914. // Need to let pthread_cancel emulation handle SIGTERM first
  8915. termhandler = pcwm_orig_term_handler;
  8916. pcwm_orig_term_handler = handler;
  8917. #endif
  8918. sigaction(SIGINT, &handler, &inthandler);
  8919. #ifndef WIN32
  8920. signal(SIGPIPE, SIG_IGN);
  8921. #else
  8922. timeBeginPeriod(1);
  8923. #endif
  8924. opt_kernel_path = CGMINER_PREFIX;
  8925. cgminer_path = alloca(PATH_MAX);
  8926. s = strdup(argv[0]);
  8927. strcpy(cgminer_path, dirname(s));
  8928. free(s);
  8929. strcat(cgminer_path, "/");
  8930. #ifdef WANT_CPUMINE
  8931. // Hack to make cgminer silent when called recursively on WIN32
  8932. int skip_to_bench = 0;
  8933. #if defined(WIN32)
  8934. char buf[32];
  8935. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  8936. skip_to_bench = 1;
  8937. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  8938. skip_to_bench = 1;
  8939. #endif // defined(WIN32)
  8940. #endif
  8941. devcursor = 8;
  8942. logstart = devcursor;
  8943. logcursor = logstart;
  8944. block = calloc(sizeof(struct block), 1);
  8945. if (unlikely(!block))
  8946. quit (1, "main OOM");
  8947. for (i = 0; i < 36; i++)
  8948. strcat(block->hash, "0");
  8949. HASH_ADD_STR(blocks, hash, block);
  8950. strcpy(current_block, block->hash);
  8951. mutex_init(&submitting_lock);
  8952. #ifdef HAVE_OPENCL
  8953. memset(gpus, 0, sizeof(gpus));
  8954. for (i = 0; i < MAX_GPUDEVICES; i++)
  8955. gpus[i].dynamic = true;
  8956. #endif
  8957. schedstart.tm.tm_sec = 1;
  8958. schedstop .tm.tm_sec = 1;
  8959. /* parse command line */
  8960. opt_register_table(opt_config_table,
  8961. "Options for both config file and command line");
  8962. opt_register_table(opt_cmdline_table,
  8963. "Options for command line only");
  8964. opt_parse(&argc, argv, applog_and_exit);
  8965. if (argc != 1)
  8966. quit(1, "Unexpected extra commandline arguments");
  8967. if (!config_loaded)
  8968. load_default_config();
  8969. #ifndef HAVE_PTHREAD_CANCEL
  8970. // Can't do this any earlier, or config isn't loaded
  8971. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  8972. #endif
  8973. #ifdef HAVE_PWD_H
  8974. struct passwd *user_info = NULL;
  8975. if (opt_setuid != NULL) {
  8976. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  8977. quit(1, "Unable to find setuid user information");
  8978. }
  8979. }
  8980. #endif
  8981. #ifdef HAVE_CHROOT
  8982. if (chroot_dir != NULL) {
  8983. #ifdef HAVE_PWD_H
  8984. if (user_info == NULL && getuid() == 0) {
  8985. applog(LOG_WARNING, "Running as root inside chroot");
  8986. }
  8987. #endif
  8988. if (chroot(chroot_dir) != 0) {
  8989. quit(1, "Unable to chroot");
  8990. }
  8991. chdir("/");
  8992. }
  8993. #endif
  8994. #ifdef HAVE_PWD_H
  8995. if (user_info != NULL) {
  8996. if (setgid((*user_info).pw_gid) != 0)
  8997. quit(1, "Unable to setgid");
  8998. if (setuid((*user_info).pw_uid) != 0)
  8999. quit(1, "Unable to setuid");
  9000. }
  9001. #endif
  9002. raise_fd_limits();
  9003. if (opt_benchmark) {
  9004. struct pool *pool;
  9005. if (opt_scrypt)
  9006. quit(1, "Cannot use benchmark mode with scrypt");
  9007. want_longpoll = false;
  9008. pool = add_pool();
  9009. pool->rpc_url = malloc(255);
  9010. strcpy(pool->rpc_url, "Benchmark");
  9011. pool->rpc_user = pool->rpc_url;
  9012. pool->rpc_pass = pool->rpc_url;
  9013. enable_pool(pool);
  9014. pool->idle = false;
  9015. successful_connect = true;
  9016. }
  9017. if (opt_unittest) {
  9018. test_intrange();
  9019. test_decimal_width();
  9020. }
  9021. #ifdef HAVE_CURSES
  9022. if (opt_realquiet || opt_display_devs)
  9023. use_curses = false;
  9024. setlocale(LC_ALL, "C");
  9025. if (use_curses)
  9026. enable_curses();
  9027. #endif
  9028. #ifdef HAVE_LIBUSB
  9029. int err = libusb_init(NULL);
  9030. if (err)
  9031. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  9032. else
  9033. have_libusb = true;
  9034. #endif
  9035. applog(LOG_WARNING, "Started %s", packagename);
  9036. if (cnfbuf) {
  9037. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  9038. switch (fileconf_load) {
  9039. case 0:
  9040. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  9041. applog(LOG_WARNING, "Configuration file could not be used.");
  9042. break;
  9043. case -1:
  9044. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  9045. if (use_curses)
  9046. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  9047. break;
  9048. default:
  9049. break;
  9050. }
  9051. free(cnfbuf);
  9052. cnfbuf = NULL;
  9053. }
  9054. i = strlen(opt_kernel_path) + 2;
  9055. char __kernel_path[i];
  9056. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  9057. opt_kernel_path = __kernel_path;
  9058. if (want_per_device_stats)
  9059. opt_log_output = true;
  9060. #ifdef WANT_CPUMINE
  9061. #ifdef USE_SCRYPT
  9062. if (opt_scrypt)
  9063. set_scrypt_algo(&opt_algo);
  9064. else
  9065. #endif
  9066. if (0 <= opt_bench_algo) {
  9067. double rate = bench_algo_stage3(opt_bench_algo);
  9068. if (!skip_to_bench)
  9069. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  9070. else {
  9071. // Write result to shared memory for parent
  9072. #if defined(WIN32)
  9073. char unique_name[64];
  9074. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  9075. HANDLE map_handle = CreateFileMapping(
  9076. INVALID_HANDLE_VALUE, // use paging file
  9077. NULL, // default security attributes
  9078. PAGE_READWRITE, // read/write access
  9079. 0, // size: high 32-bits
  9080. 4096, // size: low 32-bits
  9081. unique_name // name of map object
  9082. );
  9083. if (NULL != map_handle) {
  9084. void *shared_mem = MapViewOfFile(
  9085. map_handle, // object to map view of
  9086. FILE_MAP_WRITE, // read/write access
  9087. 0, // high offset: map from
  9088. 0, // low offset: beginning
  9089. 0 // default: map entire file
  9090. );
  9091. if (NULL != shared_mem)
  9092. CopyMemory(shared_mem, &rate, sizeof(rate));
  9093. (void)UnmapViewOfFile(shared_mem);
  9094. }
  9095. (void)CloseHandle(map_handle);
  9096. }
  9097. #endif
  9098. }
  9099. exit(0);
  9100. }
  9101. #endif
  9102. drv_detect_all();
  9103. total_devices = total_devices_new;
  9104. devices = devices_new;
  9105. total_devices_new = 0;
  9106. devices_new = NULL;
  9107. if (opt_display_devs) {
  9108. applog(LOG_ERR, "Devices detected:");
  9109. for (i = 0; i < total_devices; ++i) {
  9110. struct cgpu_info *cgpu = devices[i];
  9111. if (cgpu->name)
  9112. applog(LOG_ERR, " %2d. %"PRIprepr": %s (driver: %s)", i, cgpu->proc_repr, cgpu->name, cgpu->drv->dname);
  9113. else
  9114. applog(LOG_ERR, " %2d. %"PRIprepr" (driver: %s)", i, cgpu->proc_repr, cgpu->drv->dname);
  9115. }
  9116. quit(0, "%d devices listed", total_devices);
  9117. }
  9118. mining_threads = 0;
  9119. if (opt_devs_enabled) {
  9120. for (i = 0; i < MAX_DEVICES; i++) {
  9121. if (devices_enabled[i]) {
  9122. if (i >= total_devices)
  9123. quit (1, "Command line options set a device that doesn't exist");
  9124. register_device(devices[i]);
  9125. } else if (i < total_devices) {
  9126. if (opt_removedisabled) {
  9127. if (devices[i]->drv == &cpu_drv)
  9128. --opt_n_threads;
  9129. } else {
  9130. register_device(devices[i]);
  9131. }
  9132. devices[i]->deven = DEV_DISABLED;
  9133. }
  9134. }
  9135. total_devices = cgminer_id_count;
  9136. } else {
  9137. for (i = 0; i < total_devices; ++i)
  9138. register_device(devices[i]);
  9139. }
  9140. if (!total_devices) {
  9141. const bool netdev_support =
  9142. #ifdef USE_LIBMICROHTTPD
  9143. (httpsrv_port != -1) ||
  9144. #endif
  9145. #ifdef USE_LIBEVENT
  9146. (stratumsrv_port != -1) ||
  9147. #endif
  9148. false;
  9149. if ((!netdev_support) && (!use_curses) && !opt_api_listen)
  9150. quit(1, "All devices disabled, cannot mine!");
  9151. applog(LOG_WARNING, "No devices detected!");
  9152. if (use_curses)
  9153. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  9154. else
  9155. applog(LOG_WARNING, "Waiting for %s or press Ctrl-C to quit",
  9156. netdev_support ? "network devices" : "RPC commands");
  9157. }
  9158. load_temp_config();
  9159. #ifdef HAVE_CURSES
  9160. switch_logsize();
  9161. #endif
  9162. if (!total_pools) {
  9163. applog(LOG_WARNING, "Need to specify at least one pool server.");
  9164. #ifdef HAVE_CURSES
  9165. if (!use_curses || !input_pool(false))
  9166. #endif
  9167. quit(1, "Pool setup failed");
  9168. }
  9169. for (i = 0; i < total_pools; i++) {
  9170. struct pool *pool = pools[i];
  9171. size_t siz;
  9172. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9173. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9174. if (!pool->rpc_url)
  9175. quit(1, "No URI supplied for pool %u", i);
  9176. if (!pool->rpc_userpass) {
  9177. if (!pool->rpc_user || !pool->rpc_pass)
  9178. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  9179. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9180. pool->rpc_userpass = malloc(siz);
  9181. if (!pool->rpc_userpass)
  9182. quit(1, "Failed to malloc userpass");
  9183. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9184. }
  9185. }
  9186. /* Set the currentpool to pool with priority 0 */
  9187. validate_pool_priorities();
  9188. for (i = 0; i < total_pools; i++) {
  9189. struct pool *pool = pools[i];
  9190. if (!pool->prio)
  9191. currentpool = pool;
  9192. }
  9193. #ifdef HAVE_SYSLOG_H
  9194. if (use_syslog)
  9195. openlog(PACKAGE, LOG_PID, LOG_USER);
  9196. #endif
  9197. #if defined(unix) || defined(__APPLE__)
  9198. if (opt_stderr_cmd)
  9199. fork_monitor();
  9200. #endif // defined(unix)
  9201. mining_thr = calloc(mining_threads, sizeof(thr));
  9202. if (!mining_thr)
  9203. quit(1, "Failed to calloc mining_thr");
  9204. for (i = 0; i < mining_threads; i++) {
  9205. mining_thr[i] = calloc(1, sizeof(*thr));
  9206. if (!mining_thr[i])
  9207. quit(1, "Failed to calloc mining_thr[%d]", i);
  9208. }
  9209. total_control_threads = 7;
  9210. control_thr = calloc(total_control_threads, sizeof(*thr));
  9211. if (!control_thr)
  9212. quit(1, "Failed to calloc control_thr");
  9213. gwsched_thr_id = 0;
  9214. stage_thr_id = 1;
  9215. thr = &control_thr[stage_thr_id];
  9216. thr->q = tq_new();
  9217. if (!thr->q)
  9218. quit(1, "Failed to tq_new");
  9219. /* start stage thread */
  9220. if (thr_info_create(thr, NULL, stage_thread, thr))
  9221. quit(1, "stage thread create failed");
  9222. pthread_detach(thr->pth);
  9223. /* Create a unique get work queue */
  9224. getq = tq_new();
  9225. if (!getq)
  9226. quit(1, "Failed to create getq");
  9227. /* We use the getq mutex as the staged lock */
  9228. stgd_lock = &getq->mutex;
  9229. if (opt_benchmark)
  9230. goto begin_bench;
  9231. for (i = 0; i < total_pools; i++) {
  9232. struct pool *pool = pools[i];
  9233. enable_pool(pool);
  9234. pool->idle = true;
  9235. }
  9236. applog(LOG_NOTICE, "Probing for an alive pool");
  9237. do {
  9238. bool still_testing;
  9239. int i;
  9240. /* Look for at least one active pool before starting */
  9241. probe_pools();
  9242. do {
  9243. sleep(1);
  9244. still_testing = false;
  9245. for (int i = 0; i < total_pools; ++i)
  9246. if (pools[i]->testing)
  9247. still_testing = true;
  9248. } while (still_testing);
  9249. if (!pools_active) {
  9250. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  9251. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  9252. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  9253. for (i = 0; i < total_pools; i++) {
  9254. struct pool *pool;
  9255. pool = pools[i];
  9256. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  9257. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  9258. }
  9259. #ifdef HAVE_CURSES
  9260. if (use_curses) {
  9261. halfdelay(150);
  9262. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  9263. if (getch() != ERR)
  9264. quit(0, "No servers could be used! Exiting.");
  9265. cbreak();
  9266. } else
  9267. #endif
  9268. quit(0, "No servers could be used! Exiting.");
  9269. }
  9270. } while (!pools_active);
  9271. #ifdef USE_SCRYPT
  9272. if (detect_algo == 1 && !opt_scrypt) {
  9273. applog(LOG_NOTICE, "Detected scrypt algorithm");
  9274. opt_scrypt = true;
  9275. }
  9276. #endif
  9277. detect_algo = 0;
  9278. begin_bench:
  9279. total_mhashes_done = 0;
  9280. for (i = 0; i < total_devices; i++) {
  9281. struct cgpu_info *cgpu = devices[i];
  9282. cgpu->rolling = cgpu->total_mhashes = 0;
  9283. }
  9284. cgtime(&total_tv_start);
  9285. cgtime(&total_tv_end);
  9286. miner_started = total_tv_start;
  9287. time_t miner_start_ts = time(NULL);
  9288. if (schedstart.tm.tm_sec)
  9289. localtime_r(&miner_start_ts, &schedstart.tm);
  9290. if (schedstop.tm.tm_sec)
  9291. localtime_r(&miner_start_ts, &schedstop .tm);
  9292. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  9293. // Initialise processors and threads
  9294. k = 0;
  9295. for (i = 0; i < total_devices; ++i) {
  9296. struct cgpu_info *cgpu = devices[i];
  9297. allocate_cgpu(cgpu, &k);
  9298. }
  9299. // Start threads
  9300. for (i = 0; i < total_devices; ++i) {
  9301. struct cgpu_info *cgpu = devices[i];
  9302. start_cgpu(cgpu);
  9303. }
  9304. #ifdef HAVE_OPENCL
  9305. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  9306. for (i = 0; i < nDevs; i++)
  9307. pause_dynamic_threads(i);
  9308. #endif
  9309. #ifdef WANT_CPUMINE
  9310. applog(LOG_INFO, "%d cpu miner threads started, "
  9311. "using SHA256 '%s' algorithm.",
  9312. opt_n_threads,
  9313. algo_names[opt_algo]);
  9314. #endif
  9315. cgtime(&total_tv_start);
  9316. cgtime(&total_tv_end);
  9317. {
  9318. pthread_t submit_thread;
  9319. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  9320. quit(1, "submit_work thread create failed");
  9321. }
  9322. watchpool_thr_id = 2;
  9323. thr = &control_thr[watchpool_thr_id];
  9324. /* start watchpool thread */
  9325. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  9326. quit(1, "watchpool thread create failed");
  9327. pthread_detach(thr->pth);
  9328. watchdog_thr_id = 3;
  9329. thr = &control_thr[watchdog_thr_id];
  9330. /* start watchdog thread */
  9331. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  9332. quit(1, "watchdog thread create failed");
  9333. pthread_detach(thr->pth);
  9334. #ifdef HAVE_OPENCL
  9335. /* Create reinit gpu thread */
  9336. gpur_thr_id = 4;
  9337. thr = &control_thr[gpur_thr_id];
  9338. thr->q = tq_new();
  9339. if (!thr->q)
  9340. quit(1, "tq_new failed for gpur_thr_id");
  9341. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  9342. quit(1, "reinit_gpu thread create failed");
  9343. #endif
  9344. /* Create API socket thread */
  9345. api_thr_id = 5;
  9346. thr = &control_thr[api_thr_id];
  9347. if (thr_info_create(thr, NULL, api_thread, thr))
  9348. quit(1, "API thread create failed");
  9349. #ifdef USE_LIBMICROHTTPD
  9350. if (httpsrv_port != -1)
  9351. httpsrv_start(httpsrv_port);
  9352. #endif
  9353. #ifdef USE_LIBEVENT
  9354. if (stratumsrv_port != -1)
  9355. stratumsrv_start();
  9356. #endif
  9357. #ifdef HAVE_CURSES
  9358. /* Create curses input thread for keyboard input. Create this last so
  9359. * that we know all threads are created since this can call kill_work
  9360. * to try and shut down ll previous threads. */
  9361. input_thr_id = 6;
  9362. thr = &control_thr[input_thr_id];
  9363. if (thr_info_create(thr, NULL, input_thread, thr))
  9364. quit(1, "input thread create failed");
  9365. pthread_detach(thr->pth);
  9366. #endif
  9367. /* Just to be sure */
  9368. if (total_control_threads != 7)
  9369. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  9370. /* Once everything is set up, main() becomes the getwork scheduler */
  9371. while (42) {
  9372. int ts, max_staged = opt_queue;
  9373. struct pool *pool, *cp;
  9374. bool lagging = false;
  9375. struct curl_ent *ce;
  9376. struct work *work;
  9377. cp = current_pool();
  9378. /* If the primary pool is a getwork pool and cannot roll work,
  9379. * try to stage one extra work per mining thread */
  9380. if (!pool_localgen(cp) && !staged_rollable)
  9381. max_staged += mining_threads;
  9382. mutex_lock(stgd_lock);
  9383. ts = __total_staged();
  9384. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  9385. lagging = true;
  9386. /* Wait until hash_pop tells us we need to create more work */
  9387. if (ts > max_staged) {
  9388. staged_full = true;
  9389. pthread_cond_wait(&gws_cond, stgd_lock);
  9390. ts = __total_staged();
  9391. }
  9392. mutex_unlock(stgd_lock);
  9393. if (ts > max_staged)
  9394. continue;
  9395. work = make_work();
  9396. if (lagging && !pool_tset(cp, &cp->lagging)) {
  9397. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  9398. cp->getfail_occasions++;
  9399. total_go++;
  9400. }
  9401. pool = select_pool(lagging);
  9402. retry:
  9403. if (pool->has_stratum) {
  9404. while (!pool->stratum_active || !pool->stratum_notify) {
  9405. struct pool *altpool = select_pool(true);
  9406. if (altpool == pool && pool->has_stratum)
  9407. cgsleep_ms(5000);
  9408. pool = altpool;
  9409. goto retry;
  9410. }
  9411. gen_stratum_work(pool, work);
  9412. applog(LOG_DEBUG, "Generated stratum work");
  9413. stage_work(work);
  9414. continue;
  9415. }
  9416. if (pool->last_work_copy) {
  9417. mutex_lock(&pool->last_work_lock);
  9418. struct work *last_work = pool->last_work_copy;
  9419. if (!last_work)
  9420. {}
  9421. else
  9422. if (can_roll(last_work) && should_roll(last_work)) {
  9423. struct timeval tv_now;
  9424. cgtime(&tv_now);
  9425. free_work(work);
  9426. work = make_clone(pool->last_work_copy);
  9427. mutex_unlock(&pool->last_work_lock);
  9428. roll_work(work);
  9429. 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));
  9430. stage_work(work);
  9431. continue;
  9432. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  9433. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  9434. } else {
  9435. free_work(last_work);
  9436. pool->last_work_copy = NULL;
  9437. }
  9438. mutex_unlock(&pool->last_work_lock);
  9439. }
  9440. if (clone_available()) {
  9441. applog(LOG_DEBUG, "Cloned getwork work");
  9442. free_work(work);
  9443. continue;
  9444. }
  9445. if (opt_benchmark) {
  9446. get_benchmark_work(work);
  9447. applog(LOG_DEBUG, "Generated benchmark work");
  9448. stage_work(work);
  9449. continue;
  9450. }
  9451. work->pool = pool;
  9452. ce = pop_curl_entry3(pool, 2);
  9453. /* obtain new work from bitcoin via JSON-RPC */
  9454. if (!get_upstream_work(work, ce->curl)) {
  9455. struct pool *next_pool;
  9456. /* Make sure the pool just hasn't stopped serving
  9457. * requests but is up as we'll keep hammering it */
  9458. push_curl_entry(ce, pool);
  9459. ++pool->seq_getfails;
  9460. pool_died(pool);
  9461. next_pool = select_pool(!opt_fail_only);
  9462. if (pool == next_pool) {
  9463. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  9464. cgsleep_ms(5000);
  9465. } else {
  9466. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  9467. pool = next_pool;
  9468. }
  9469. goto retry;
  9470. }
  9471. if (ts >= max_staged)
  9472. pool_tclear(pool, &pool->lagging);
  9473. if (pool_tclear(pool, &pool->idle))
  9474. pool_resus(pool);
  9475. applog(LOG_DEBUG, "Generated getwork work");
  9476. stage_work(work);
  9477. push_curl_entry(ce, pool);
  9478. }
  9479. return 0;
  9480. }