miner.c 233 KB

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