cgminer.c 202 KB

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