miner.c 285 KB

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