cgminer.c 202 KB

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