miner.c 220 KB

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