miner.c 233 KB

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