miner.c 303 KB

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