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