miner.c 218 KB

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