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