miner.c 218 KB

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