cgminer.c 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #ifdef HAVE_CURSES
  13. #include <curses.h>
  14. #endif
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <time.h>
  23. #include <math.h>
  24. #include <stdarg.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27. #ifdef USE_USBUTILS
  28. #include <semaphore.h>
  29. #endif
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #ifndef WIN32
  33. #include <sys/resource.h>
  34. #endif
  35. #include <ccan/opt/opt.h>
  36. #include <jansson.h>
  37. #include <curl/curl.h>
  38. #include <libgen.h>
  39. #include <sha2.h>
  40. #include "compat.h"
  41. #include "miner.h"
  42. #include "findnonce.h"
  43. #include "adl.h"
  44. #include "driver-opencl.h"
  45. #include "bench_block.h"
  46. #include "scrypt.h"
  47. #ifdef USE_AVALON
  48. #include "driver-avalon.h"
  49. #endif
  50. #if defined(unix)
  51. #include <errno.h>
  52. #include <fcntl.h>
  53. #include <sys/wait.h>
  54. #endif
  55. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_AVALON) || defined(USE_MODMINER)
  56. # define USE_FPGA
  57. #elif defined(USE_ZTEX)
  58. # define USE_FPGA
  59. #endif
  60. struct strategies strategies[] = {
  61. { "Failover" },
  62. { "Round Robin" },
  63. { "Rotate" },
  64. { "Load Balance" },
  65. { "Balance" },
  66. };
  67. static char packagename[256];
  68. bool opt_protocol;
  69. static bool opt_benchmark;
  70. bool have_longpoll;
  71. bool want_per_device_stats;
  72. bool use_syslog;
  73. bool opt_quiet;
  74. bool opt_realquiet;
  75. bool opt_loginput;
  76. bool opt_compact;
  77. const int opt_cutofftemp = 95;
  78. int opt_log_interval = 5;
  79. int opt_queue = 1;
  80. int opt_scantime = -1;
  81. int opt_expiry = 120;
  82. static const bool opt_time = true;
  83. unsigned long long global_hashrate;
  84. #if defined(HAVE_OPENCL) || defined(USE_USBUTILS)
  85. int nDevs;
  86. #endif
  87. #ifdef HAVE_OPENCL
  88. int opt_dynamic_interval = 7;
  89. int opt_g_threads = -1;
  90. int gpu_threads;
  91. #ifdef USE_SCRYPT
  92. bool opt_scrypt;
  93. #endif
  94. #endif
  95. bool opt_restart = true;
  96. static bool opt_nogpu;
  97. struct list_head scan_devices;
  98. static bool devices_enabled[MAX_DEVICES];
  99. static int opt_devs_enabled;
  100. static bool opt_display_devs;
  101. static bool opt_removedisabled;
  102. int total_devices;
  103. struct cgpu_info **devices;
  104. bool have_opencl;
  105. int mining_threads;
  106. int num_processors;
  107. #ifdef HAVE_CURSES
  108. bool use_curses = true;
  109. #else
  110. bool use_curses;
  111. #endif
  112. static bool opt_submit_stale = true;
  113. static int opt_shares;
  114. bool opt_fail_only;
  115. static bool opt_fix_protocol;
  116. static bool opt_lowmem;
  117. bool opt_autofan;
  118. bool opt_autoengine;
  119. bool opt_noadl;
  120. char *opt_api_allow = NULL;
  121. char *opt_api_groups;
  122. char *opt_api_description = PACKAGE_STRING;
  123. int opt_api_port = 4028;
  124. bool opt_api_listen;
  125. bool opt_api_network;
  126. bool opt_delaynet;
  127. bool opt_disable_pool;
  128. char *opt_icarus_options = NULL;
  129. char *opt_icarus_timing = NULL;
  130. bool opt_worktime;
  131. #ifdef USE_AVALON
  132. char *opt_avalon_options = NULL;
  133. #endif
  134. #ifdef USE_USBUTILS
  135. char *opt_usb_select = NULL;
  136. int opt_usbdump = -1;
  137. bool opt_usb_list_all;
  138. sem_t usb_resource_sem;
  139. #endif
  140. char *opt_kernel_path;
  141. char *cgminer_path;
  142. #if defined(USE_BITFORCE)
  143. bool opt_bfl_noncerange;
  144. #endif
  145. #define QUIET (opt_quiet || opt_realquiet)
  146. struct thr_info *control_thr;
  147. struct thr_info **mining_thr;
  148. static int gwsched_thr_id;
  149. static int stage_thr_id;
  150. static int watchpool_thr_id;
  151. static int watchdog_thr_id;
  152. #ifdef HAVE_CURSES
  153. static int input_thr_id;
  154. #endif
  155. int gpur_thr_id;
  156. static int api_thr_id;
  157. #ifdef USE_USBUTILS
  158. static int usbres_thr_id;
  159. static int hotplug_thr_id;
  160. #endif
  161. static int total_control_threads;
  162. bool hotplug_mode;
  163. static int new_devices;
  164. static int new_threads;
  165. 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. #endif
  1909. #ifdef HAVE_CURSES
  1910. bool log_curses_only(int prio, const char *f, va_list ap)
  1911. {
  1912. bool high_prio;
  1913. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  1914. if (curses_active_locked()) {
  1915. if (!opt_loginput || high_prio) {
  1916. vw_printw(logwin, f, ap);
  1917. if (high_prio) {
  1918. touchwin(logwin);
  1919. wrefresh(logwin);
  1920. }
  1921. }
  1922. unlock_curses();
  1923. return true;
  1924. }
  1925. return false;
  1926. }
  1927. void clear_logwin(void)
  1928. {
  1929. if (curses_active_locked()) {
  1930. erase();
  1931. wclear(logwin);
  1932. unlock_curses();
  1933. }
  1934. }
  1935. void logwin_update(void)
  1936. {
  1937. if (curses_active_locked()) {
  1938. touchwin(logwin);
  1939. wrefresh(logwin);
  1940. unlock_curses();
  1941. }
  1942. }
  1943. #endif
  1944. static void enable_pool(struct pool *pool)
  1945. {
  1946. if (pool->enabled != POOL_ENABLED) {
  1947. enabled_pools++;
  1948. pool->enabled = POOL_ENABLED;
  1949. }
  1950. }
  1951. #ifdef HAVE_CURSES
  1952. static void disable_pool(struct pool *pool)
  1953. {
  1954. if (pool->enabled == POOL_ENABLED)
  1955. enabled_pools--;
  1956. pool->enabled = POOL_DISABLED;
  1957. }
  1958. #endif
  1959. static void reject_pool(struct pool *pool)
  1960. {
  1961. if (pool->enabled == POOL_ENABLED)
  1962. enabled_pools--;
  1963. pool->enabled = POOL_REJECTING;
  1964. }
  1965. static void restart_threads(void);
  1966. /* Theoretically threads could race when modifying accepted and
  1967. * rejected values but the chance of two submits completing at the
  1968. * same time is zero so there is no point adding extra locking */
  1969. static void
  1970. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  1971. char *hashshow, bool resubmit, char *worktime)
  1972. {
  1973. struct pool *pool = work->pool;
  1974. struct cgpu_info *cgpu;
  1975. cgpu = get_thr_cgpu(work->thr_id);
  1976. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  1977. mutex_lock(&stats_lock);
  1978. cgpu->accepted++;
  1979. total_accepted++;
  1980. pool->accepted++;
  1981. cgpu->diff_accepted += work->work_difficulty;
  1982. total_diff_accepted += work->work_difficulty;
  1983. pool->diff_accepted += work->work_difficulty;
  1984. mutex_unlock(&stats_lock);
  1985. pool->seq_rejects = 0;
  1986. cgpu->last_share_pool = pool->pool_no;
  1987. cgpu->last_share_pool_time = time(NULL);
  1988. cgpu->last_share_diff = work->work_difficulty;
  1989. pool->last_share_time = cgpu->last_share_pool_time;
  1990. pool->last_share_diff = work->work_difficulty;
  1991. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1992. if (!QUIET) {
  1993. if (total_pools > 1)
  1994. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  1995. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  1996. else
  1997. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  1998. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  1999. }
  2000. sharelog("accept", work);
  2001. if (opt_shares && total_accepted >= opt_shares) {
  2002. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2003. kill_work();
  2004. return;
  2005. }
  2006. /* Detect if a pool that has been temporarily disabled for
  2007. * continually rejecting shares has started accepting shares.
  2008. * This will only happen with the work returned from a
  2009. * longpoll */
  2010. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2011. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2012. enable_pool(pool);
  2013. switch_pools(NULL);
  2014. }
  2015. /* If we know we found the block we know better than anyone
  2016. * that new work is needed. */
  2017. if (unlikely(work->block))
  2018. restart_threads();
  2019. } else {
  2020. mutex_lock(&stats_lock);
  2021. cgpu->rejected++;
  2022. total_rejected++;
  2023. pool->rejected++;
  2024. cgpu->diff_rejected += work->work_difficulty;
  2025. total_diff_rejected += work->work_difficulty;
  2026. pool->diff_rejected += work->work_difficulty;
  2027. pool->seq_rejects++;
  2028. mutex_unlock(&stats_lock);
  2029. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2030. if (!QUIET) {
  2031. char where[20];
  2032. char disposition[36] = "reject";
  2033. char reason[32];
  2034. strcpy(reason, "");
  2035. if (total_pools > 1)
  2036. sprintf(where, "pool %d", work->pool->pool_no);
  2037. else
  2038. strcpy(where, "");
  2039. if (!work->gbt)
  2040. res = json_object_get(val, "reject-reason");
  2041. if (res) {
  2042. const char *reasontmp = json_string_value(res);
  2043. size_t reasonLen = strlen(reasontmp);
  2044. if (reasonLen > 28)
  2045. reasonLen = 28;
  2046. reason[0] = ' '; reason[1] = '(';
  2047. memcpy(2 + reason, reasontmp, reasonLen);
  2048. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2049. memcpy(disposition + 7, reasontmp, reasonLen);
  2050. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2051. } else if (work->stratum && err && json_is_array(err)) {
  2052. json_t *reason_val = json_array_get(err, 1);
  2053. char *reason_str;
  2054. if (reason_val && json_is_string(reason_val)) {
  2055. reason_str = (char *)json_string_value(reason_val);
  2056. snprintf(reason, 31, " (%s)", reason_str);
  2057. }
  2058. }
  2059. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2060. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2061. sharelog(disposition, work);
  2062. }
  2063. /* Once we have more than a nominal amount of sequential rejects,
  2064. * at least 10 and more than 3 mins at the current utility,
  2065. * disable the pool because some pool error is likely to have
  2066. * ensued. Do not do this if we know the share just happened to
  2067. * be stale due to networking delays.
  2068. */
  2069. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2070. double utility = total_accepted / total_secs * 60;
  2071. if (pool->seq_rejects > utility * 3) {
  2072. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2073. pool->pool_no, pool->seq_rejects);
  2074. reject_pool(pool);
  2075. if (pool == current_pool())
  2076. switch_pools(NULL);
  2077. pool->seq_rejects = 0;
  2078. }
  2079. }
  2080. }
  2081. }
  2082. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2083. {
  2084. char *hexstr = NULL;
  2085. json_t *val, *res, *err;
  2086. char *s;
  2087. bool rc = false;
  2088. int thr_id = work->thr_id;
  2089. struct cgpu_info *cgpu;
  2090. struct pool *pool = work->pool;
  2091. int rolltime;
  2092. struct timeval tv_submit, tv_submit_reply;
  2093. char hashshow[64 + 4] = "";
  2094. char worktime[200] = "";
  2095. cgpu = get_thr_cgpu(thr_id);
  2096. endian_flip128(work->data, work->data);
  2097. /* build hex string */
  2098. hexstr = bin2hex(work->data, sizeof(work->data));
  2099. /* build JSON-RPC request */
  2100. if (work->gbt) {
  2101. char *gbt_block, *varint;
  2102. unsigned char data[80];
  2103. flip80(data, work->data);
  2104. gbt_block = bin2hex(data, 80);
  2105. if (work->gbt_txns < 0xfd) {
  2106. uint8_t val = work->gbt_txns;
  2107. varint = bin2hex((const unsigned char *)&val, 1);
  2108. } else if (work->gbt_txns <= 0xffff) {
  2109. uint16_t val = htole16(work->gbt_txns);
  2110. gbt_block = realloc_strcat(gbt_block, "fd");
  2111. varint = bin2hex((const unsigned char *)&val, 2);
  2112. } else {
  2113. uint32_t val = htole32(work->gbt_txns);
  2114. gbt_block = realloc_strcat(gbt_block, "fe");
  2115. varint = bin2hex((const unsigned char *)&val, 4);
  2116. }
  2117. gbt_block = realloc_strcat(gbt_block, varint);
  2118. free(varint);
  2119. gbt_block = realloc_strcat(gbt_block, work->gbt_coinbase);
  2120. s = strdup("{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"");
  2121. s = realloc_strcat(s, gbt_block);
  2122. if (work->job_id) {
  2123. s = realloc_strcat(s, "\", {\"workid\": \"");
  2124. s = realloc_strcat(s, work->job_id);
  2125. s = realloc_strcat(s, "\"}]}");
  2126. } else
  2127. s = realloc_strcat(s, "\", {}]}");
  2128. free(gbt_block);
  2129. } else {
  2130. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2131. s = realloc_strcat(s, hexstr);
  2132. s = realloc_strcat(s, "\" ], \"id\":1}");
  2133. }
  2134. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  2135. s = realloc_strcat(s, "\n");
  2136. cgtime(&tv_submit);
  2137. /* issue JSON-RPC request */
  2138. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2139. cgtime(&tv_submit_reply);
  2140. free(s);
  2141. if (unlikely(!val)) {
  2142. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2143. if (!pool_tset(pool, &pool->submit_fail)) {
  2144. total_ro++;
  2145. pool->remotefail_occasions++;
  2146. if (opt_lowmem) {
  2147. applog(LOG_WARNING, "Pool %d communication failure, discarding shares", pool->pool_no);
  2148. goto out;
  2149. }
  2150. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2151. }
  2152. nmsleep(5000);
  2153. goto out;
  2154. } else if (pool_tclear(pool, &pool->submit_fail))
  2155. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2156. res = json_object_get(val, "result");
  2157. err = json_object_get(val, "error");
  2158. if (!QUIET) {
  2159. int intdiff = floor(work->work_difficulty);
  2160. char diffdisp[16], *outhash;
  2161. unsigned char rhash[32];
  2162. swab256(rhash, work->hash);
  2163. if (opt_scrypt)
  2164. outhash = bin2hex(rhash + 2, 4);
  2165. else
  2166. outhash = bin2hex(rhash + 4, 4);
  2167. suffix_string(work->share_diff, diffdisp, 0);
  2168. sprintf(hashshow, "%s Diff %s/%d%s", outhash, diffdisp, intdiff,
  2169. work->block? " BLOCK!" : "");
  2170. free(outhash);
  2171. if (opt_worktime) {
  2172. char workclone[20];
  2173. struct tm *tm, tm_getwork, tm_submit_reply;
  2174. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2175. (struct timeval *)&(work->tv_getwork));
  2176. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2177. (struct timeval *)&(work->tv_getwork_reply));
  2178. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2179. (struct timeval *)&(work->tv_work_start));
  2180. double work_to_submit = tdiff(&tv_submit,
  2181. (struct timeval *)&(work->tv_work_found));
  2182. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  2183. int diffplaces = 3;
  2184. time_t tmp_time = work->tv_getwork.tv_sec;
  2185. tm = localtime(&tmp_time);
  2186. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2187. tmp_time = tv_submit_reply.tv_sec;
  2188. tm = localtime(&tmp_time);
  2189. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2190. if (work->clone) {
  2191. sprintf(workclone, "C:%1.3f",
  2192. tdiff((struct timeval *)&(work->tv_cloned),
  2193. (struct timeval *)&(work->tv_getwork_reply)));
  2194. }
  2195. else
  2196. strcpy(workclone, "O");
  2197. if (work->work_difficulty < 1)
  2198. diffplaces = 6;
  2199. 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",
  2200. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2201. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2202. work->getwork_mode, diffplaces, work->work_difficulty,
  2203. tm_getwork.tm_hour, tm_getwork.tm_min,
  2204. tm_getwork.tm_sec, getwork_time, workclone,
  2205. getwork_to_work, work_time, work_to_submit, submit_time,
  2206. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2207. tm_submit_reply.tm_sec);
  2208. }
  2209. }
  2210. share_result(val, res, err, work, hashshow, resubmit, worktime);
  2211. cgpu->utility = cgpu->accepted / total_secs * 60;
  2212. if (!opt_realquiet)
  2213. print_status(thr_id);
  2214. if (!want_per_device_stats) {
  2215. char logline[256];
  2216. get_statline(logline, cgpu);
  2217. applog(LOG_INFO, "%s", logline);
  2218. }
  2219. json_decref(val);
  2220. rc = true;
  2221. out:
  2222. free(hexstr);
  2223. return rc;
  2224. }
  2225. /* Specifies whether we can use this pool for work or not. */
  2226. static bool pool_unworkable(struct pool *pool)
  2227. {
  2228. if (pool->idle)
  2229. return true;
  2230. if (pool->enabled != POOL_ENABLED)
  2231. return true;
  2232. if (pool->has_stratum && !pool->stratum_active)
  2233. return true;
  2234. return false;
  2235. }
  2236. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2237. * rolling average per 10 minutes and if pools start getting more, it biases
  2238. * away from them to distribute work evenly. The share count is reset to the
  2239. * rolling average every 10 minutes to not send all work to one pool after it
  2240. * has been disabled/out for an extended period. */
  2241. static struct pool *select_balanced(struct pool *cp)
  2242. {
  2243. int i, lowest = cp->shares;
  2244. struct pool *ret = cp;
  2245. for (i = 0; i < total_pools; i++) {
  2246. struct pool *pool = pools[i];
  2247. if (pool_unworkable(pool))
  2248. continue;
  2249. if (pool->shares < lowest) {
  2250. lowest = pool->shares;
  2251. ret = pool;
  2252. }
  2253. }
  2254. ret->shares++;
  2255. return ret;
  2256. }
  2257. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2258. static inline struct pool *select_pool(bool lagging)
  2259. {
  2260. static int rotating_pool = 0;
  2261. struct pool *pool, *cp;
  2262. int tested;
  2263. cp = current_pool();
  2264. if (pool_strategy == POOL_BALANCE)
  2265. return select_balanced(cp);
  2266. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2267. pool = cp;
  2268. else
  2269. pool = NULL;
  2270. /* Try to find the first pool in the rotation that is usable */
  2271. tested = 0;
  2272. while (!pool && tested++ < total_pools) {
  2273. if (++rotating_pool >= total_pools)
  2274. rotating_pool = 0;
  2275. pool = pools[rotating_pool];
  2276. if (!pool_unworkable(pool))
  2277. break;
  2278. pool = NULL;
  2279. }
  2280. /* If still nothing is usable, use the current pool */
  2281. if (!pool)
  2282. pool = cp;
  2283. return pool;
  2284. }
  2285. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  2286. static const uint64_t diffone = 0xFFFF000000000000ull;
  2287. /*
  2288. * Calculate the work share difficulty
  2289. */
  2290. static void calc_diff(struct work *work, int known)
  2291. {
  2292. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2293. double difficulty;
  2294. if (opt_scrypt) {
  2295. uint64_t *data64, d64;
  2296. char rtarget[32];
  2297. swab256(rtarget, work->target);
  2298. data64 = (uint64_t *)(rtarget + 2);
  2299. d64 = be64toh(*data64);
  2300. if (unlikely(!d64))
  2301. d64 = 1;
  2302. work->work_difficulty = diffone / d64;
  2303. } else if (!known) {
  2304. double targ = 0;
  2305. int i;
  2306. for (i = 31; i >= 0; i--) {
  2307. targ *= 256;
  2308. targ += work->target[i];
  2309. }
  2310. work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
  2311. } else
  2312. work->work_difficulty = known;
  2313. difficulty = work->work_difficulty;
  2314. pool_stats->last_diff = difficulty;
  2315. suffix_string((uint64_t)difficulty, work->pool->diff, 0);
  2316. if (difficulty == pool_stats->min_diff)
  2317. pool_stats->min_diff_count++;
  2318. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2319. pool_stats->min_diff = difficulty;
  2320. pool_stats->min_diff_count = 1;
  2321. }
  2322. if (difficulty == pool_stats->max_diff)
  2323. pool_stats->max_diff_count++;
  2324. else if (difficulty > pool_stats->max_diff) {
  2325. pool_stats->max_diff = difficulty;
  2326. pool_stats->max_diff_count = 1;
  2327. }
  2328. }
  2329. static void get_benchmark_work(struct work *work)
  2330. {
  2331. // Use a random work block pulled from a pool
  2332. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2333. size_t bench_size = sizeof(*work);
  2334. size_t work_size = sizeof(bench_block);
  2335. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2336. memset(work, 0, sizeof(*work));
  2337. memcpy(work, &bench_block, min_size);
  2338. work->mandatory = true;
  2339. work->pool = pools[0];
  2340. cgtime(&work->tv_getwork);
  2341. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  2342. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2343. calc_diff(work, 0);
  2344. }
  2345. static bool get_upstream_work(struct work *work, CURL *curl)
  2346. {
  2347. struct pool *pool = work->pool;
  2348. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2349. struct timeval tv_elapsed;
  2350. json_t *val = NULL;
  2351. bool rc = false;
  2352. char *url;
  2353. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, pool->rpc_req);
  2354. url = pool->rpc_url;
  2355. cgtime(&work->tv_getwork);
  2356. val = json_rpc_call(curl, url, pool->rpc_userpass, pool->rpc_req, false,
  2357. false, &work->rolltime, pool, false);
  2358. pool_stats->getwork_attempts++;
  2359. if (likely(val)) {
  2360. rc = work_decode(pool, work, val);
  2361. if (unlikely(!rc))
  2362. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2363. } else
  2364. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2365. cgtime(&work->tv_getwork_reply);
  2366. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2367. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2368. pool_stats->getwork_wait_rolling /= 1.63;
  2369. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2370. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2371. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2372. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2373. }
  2374. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2375. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2376. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2377. }
  2378. pool_stats->getwork_calls++;
  2379. work->pool = pool;
  2380. work->longpoll = false;
  2381. work->getwork_mode = GETWORK_MODE_POOL;
  2382. calc_diff(work, 0);
  2383. total_getworks++;
  2384. pool->getwork_requested++;
  2385. if (likely(val))
  2386. json_decref(val);
  2387. return rc;
  2388. }
  2389. #ifdef HAVE_CURSES
  2390. static void disable_curses(void)
  2391. {
  2392. if (curses_active_locked()) {
  2393. use_curses = false;
  2394. curses_active = false;
  2395. leaveok(logwin, false);
  2396. leaveok(statuswin, false);
  2397. leaveok(mainwin, false);
  2398. nocbreak();
  2399. echo();
  2400. delwin(logwin);
  2401. delwin(statuswin);
  2402. delwin(mainwin);
  2403. endwin();
  2404. #ifdef WIN32
  2405. // Move the cursor to after curses output.
  2406. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2407. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2408. COORD coord;
  2409. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2410. coord.X = 0;
  2411. coord.Y = csbi.dwSize.Y - 1;
  2412. SetConsoleCursorPosition(hout, coord);
  2413. }
  2414. #endif
  2415. unlock_curses();
  2416. }
  2417. }
  2418. #endif
  2419. static void __kill_work(void)
  2420. {
  2421. struct thr_info *thr;
  2422. int i;
  2423. if (!successful_connect)
  2424. return;
  2425. applog(LOG_INFO, "Received kill message");
  2426. #ifdef USE_USBUTILS
  2427. /* Best to get rid of it first so it doesn't
  2428. * try to create any new devices */
  2429. if (!opt_scrypt) {
  2430. applog(LOG_DEBUG, "Killing off HotPlug thread");
  2431. thr = &control_thr[hotplug_thr_id];
  2432. thr_info_cancel(thr);
  2433. }
  2434. #endif
  2435. applog(LOG_DEBUG, "Killing off watchpool thread");
  2436. /* Kill the watchpool thread */
  2437. thr = &control_thr[watchpool_thr_id];
  2438. thr_info_cancel(thr);
  2439. applog(LOG_DEBUG, "Killing off watchdog thread");
  2440. /* Kill the watchdog thread */
  2441. thr = &control_thr[watchdog_thr_id];
  2442. thr_info_cancel(thr);
  2443. applog(LOG_DEBUG, "Shutting down mining threads");
  2444. for (i = 0; i < mining_threads; i++) {
  2445. struct cgpu_info *cgpu;
  2446. thr = get_thread(i);
  2447. if (!thr)
  2448. continue;
  2449. cgpu = thr->cgpu;
  2450. if (!cgpu)
  2451. continue;
  2452. cgpu->shutdown = true;
  2453. }
  2454. sleep(1);
  2455. applog(LOG_DEBUG, "Killing off mining threads");
  2456. /* Kill the mining threads*/
  2457. for (i = 0; i < mining_threads; i++) {
  2458. pthread_t *pth = NULL;
  2459. thr = get_thread(i);
  2460. if (thr && PTH(thr) != 0L)
  2461. pth = &thr->pth;
  2462. thr_info_cancel(thr);
  2463. #ifndef WIN32
  2464. if (pth && *pth)
  2465. pthread_join(*pth, NULL);
  2466. #else
  2467. if (pth && pth->p)
  2468. pthread_join(*pth, NULL);
  2469. #endif
  2470. }
  2471. applog(LOG_DEBUG, "Killing off stage thread");
  2472. /* Stop the others */
  2473. thr = &control_thr[stage_thr_id];
  2474. thr_info_cancel(thr);
  2475. applog(LOG_DEBUG, "Killing off API thread");
  2476. thr = &control_thr[api_thr_id];
  2477. thr_info_cancel(thr);
  2478. #ifdef USE_USBUTILS
  2479. /* Release USB resources in case it's a restart
  2480. * and not a QUIT */
  2481. if (!opt_scrypt) {
  2482. applog(LOG_DEBUG, "Releasing all USB devices");
  2483. usb_cleanup();
  2484. applog(LOG_DEBUG, "Killing off usbres thread");
  2485. thr = &control_thr[usbres_thr_id];
  2486. thr_info_cancel(thr);
  2487. }
  2488. #endif
  2489. }
  2490. /* This should be the common exit path */
  2491. void kill_work(void)
  2492. {
  2493. __kill_work();
  2494. quit(0, "Shutdown signal received.");
  2495. }
  2496. static
  2497. #ifdef WIN32
  2498. const
  2499. #endif
  2500. char **initial_args;
  2501. static void clean_up(void);
  2502. void app_restart(void)
  2503. {
  2504. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2505. __kill_work();
  2506. clean_up();
  2507. #if defined(unix)
  2508. if (forkpid > 0) {
  2509. kill(forkpid, SIGTERM);
  2510. forkpid = 0;
  2511. }
  2512. #endif
  2513. execv(initial_args[0], (EXECV_2ND_ARG_TYPE)initial_args);
  2514. applog(LOG_WARNING, "Failed to restart application");
  2515. }
  2516. static void sighandler(int __maybe_unused sig)
  2517. {
  2518. /* Restore signal handlers so we can still quit if kill_work fails */
  2519. sigaction(SIGTERM, &termhandler, NULL);
  2520. sigaction(SIGINT, &inthandler, NULL);
  2521. kill_work();
  2522. }
  2523. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2524. * this pool. */
  2525. static void recruit_curl(struct pool *pool)
  2526. {
  2527. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2528. if (unlikely(!ce))
  2529. quit(1, "Failed to calloc in recruit_curl");
  2530. ce->curl = curl_easy_init();
  2531. if (unlikely(!ce->curl))
  2532. quit(1, "Failed to init in recruit_curl");
  2533. list_add(&ce->node, &pool->curlring);
  2534. pool->curls++;
  2535. }
  2536. /* Grab an available curl if there is one. If not, then recruit extra curls
  2537. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2538. * and there are already 5 curls in circulation. Limit total number to the
  2539. * number of mining threads per pool as well to prevent blasting a pool during
  2540. * network delays/outages. */
  2541. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2542. {
  2543. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2544. bool recruited = false;
  2545. struct curl_ent *ce;
  2546. mutex_lock(&pool->pool_lock);
  2547. retry:
  2548. if (!pool->curls) {
  2549. recruit_curl(pool);
  2550. recruited = true;
  2551. } else if (list_empty(&pool->curlring)) {
  2552. if (pool->curls >= curl_limit) {
  2553. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2554. goto retry;
  2555. } else {
  2556. recruit_curl(pool);
  2557. recruited = true;
  2558. }
  2559. }
  2560. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2561. list_del(&ce->node);
  2562. mutex_unlock(&pool->pool_lock);
  2563. if (recruited)
  2564. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  2565. return ce;
  2566. }
  2567. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2568. {
  2569. mutex_lock(&pool->pool_lock);
  2570. list_add_tail(&ce->node, &pool->curlring);
  2571. cgtime(&ce->tv);
  2572. pthread_cond_broadcast(&pool->cr_cond);
  2573. mutex_unlock(&pool->pool_lock);
  2574. }
  2575. static bool stale_work(struct work *work, bool share);
  2576. static inline bool should_roll(struct work *work)
  2577. {
  2578. struct timeval now;
  2579. time_t expiry;
  2580. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  2581. return false;
  2582. if (work->rolltime > opt_scantime)
  2583. expiry = work->rolltime;
  2584. else
  2585. expiry = opt_scantime;
  2586. expiry = expiry * 2 / 3;
  2587. /* We shouldn't roll if we're unlikely to get one shares' duration
  2588. * work out of doing so */
  2589. cgtime(&now);
  2590. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  2591. return false;
  2592. return true;
  2593. }
  2594. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  2595. * reject blocks as invalid. */
  2596. static inline bool can_roll(struct work *work)
  2597. {
  2598. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  2599. work->rolls < 7000 && !stale_work(work, false));
  2600. }
  2601. static void roll_work(struct work *work)
  2602. {
  2603. uint32_t *work_ntime;
  2604. uint32_t ntime;
  2605. work_ntime = (uint32_t *)(work->data + 68);
  2606. ntime = be32toh(*work_ntime);
  2607. ntime++;
  2608. *work_ntime = htobe32(ntime);
  2609. local_work++;
  2610. work->rolls++;
  2611. work->blk.nonce = 0;
  2612. applog(LOG_DEBUG, "Successfully rolled work");
  2613. /* This is now a different work item so it needs a different ID for the
  2614. * hashtable */
  2615. work->id = total_work++;
  2616. }
  2617. /* Duplicates any dynamically allocated arrays within the work struct to
  2618. * prevent a copied work struct from freeing ram belonging to another struct */
  2619. void __copy_work(struct work *work, struct work *base_work)
  2620. {
  2621. int id = work->id;
  2622. clean_work(work);
  2623. memcpy(work, base_work, sizeof(struct work));
  2624. /* Keep the unique new id assigned during make_work to prevent copied
  2625. * work from having the same id. */
  2626. work->id = id;
  2627. if (base_work->job_id)
  2628. work->job_id = strdup(base_work->job_id);
  2629. if (base_work->nonce1)
  2630. work->nonce1 = strdup(base_work->nonce1);
  2631. if (base_work->nonce2)
  2632. work->nonce2 = strdup(base_work->nonce2);
  2633. if (base_work->ntime)
  2634. work->ntime = strdup(base_work->ntime);
  2635. if (base_work->gbt_coinbase)
  2636. work->gbt_coinbase = strdup(base_work->gbt_coinbase);
  2637. }
  2638. /* Generates a copy of an existing work struct, creating fresh heap allocations
  2639. * for all dynamically allocated arrays within the struct */
  2640. struct work *copy_work(struct work *base_work)
  2641. {
  2642. struct work *work = make_work();
  2643. __copy_work(work, base_work);
  2644. return work;
  2645. }
  2646. static struct work *make_clone(struct work *work)
  2647. {
  2648. struct work *work_clone = copy_work(work);
  2649. work_clone->clone = true;
  2650. cgtime((struct timeval *)&(work_clone->tv_cloned));
  2651. work_clone->longpoll = false;
  2652. work_clone->mandatory = false;
  2653. /* Make cloned work appear slightly older to bias towards keeping the
  2654. * master work item which can be further rolled */
  2655. work_clone->tv_staged.tv_sec -= 1;
  2656. return work_clone;
  2657. }
  2658. static void stage_work(struct work *work);
  2659. static bool clone_available(void)
  2660. {
  2661. struct work *work_clone = NULL, *work, *tmp;
  2662. bool cloned = false;
  2663. mutex_lock(stgd_lock);
  2664. if (!staged_rollable)
  2665. goto out_unlock;
  2666. HASH_ITER(hh, staged_work, work, tmp) {
  2667. if (can_roll(work) && should_roll(work)) {
  2668. roll_work(work);
  2669. work_clone = make_clone(work);
  2670. roll_work(work);
  2671. cloned = true;
  2672. break;
  2673. }
  2674. }
  2675. out_unlock:
  2676. mutex_unlock(stgd_lock);
  2677. if (cloned) {
  2678. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2679. stage_work(work_clone);
  2680. }
  2681. return cloned;
  2682. }
  2683. static void pool_died(struct pool *pool)
  2684. {
  2685. if (!pool_tset(pool, &pool->idle)) {
  2686. cgtime(&pool->tv_idle);
  2687. if (pool == current_pool()) {
  2688. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2689. switch_pools(NULL);
  2690. } else
  2691. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  2692. }
  2693. }
  2694. static bool stale_work(struct work *work, bool share)
  2695. {
  2696. struct timeval now;
  2697. time_t work_expiry;
  2698. struct pool *pool;
  2699. int getwork_delay;
  2700. if (opt_benchmark)
  2701. return false;
  2702. if (work->work_block != work_block) {
  2703. applog(LOG_DEBUG, "Work stale due to block mismatch");
  2704. return true;
  2705. }
  2706. /* Technically the rolltime should be correct but some pools
  2707. * advertise a broken expire= that is lower than a meaningful
  2708. * scantime */
  2709. if (work->rolltime > opt_scantime)
  2710. work_expiry = work->rolltime;
  2711. else
  2712. work_expiry = opt_expiry;
  2713. pool = work->pool;
  2714. if (!share && pool->has_stratum) {
  2715. bool same_job;
  2716. if (!pool->stratum_active || !pool->stratum_notify) {
  2717. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  2718. return true;
  2719. }
  2720. same_job = true;
  2721. cg_rlock(&pool->data_lock);
  2722. if (strcmp(work->job_id, pool->swork.job_id))
  2723. same_job = false;
  2724. cg_runlock(&pool->data_lock);
  2725. if (!same_job) {
  2726. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  2727. return true;
  2728. }
  2729. }
  2730. /* Factor in the average getwork delay of this pool, rounding it up to
  2731. * the nearest second */
  2732. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2733. work_expiry -= getwork_delay;
  2734. if (unlikely(work_expiry < 5))
  2735. work_expiry = 5;
  2736. cgtime(&now);
  2737. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2738. applog(LOG_DEBUG, "Work stale due to expiry");
  2739. return true;
  2740. }
  2741. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2742. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2743. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. static uint64_t share_diff(const struct work *work)
  2749. {
  2750. uint64_t *data64, d64, ret;
  2751. bool new_best = false;
  2752. char rhash[32];
  2753. swab256(rhash, work->hash);
  2754. if (opt_scrypt)
  2755. data64 = (uint64_t *)(rhash + 2);
  2756. else
  2757. data64 = (uint64_t *)(rhash + 4);
  2758. d64 = be64toh(*data64);
  2759. if (unlikely(!d64))
  2760. d64 = 1;
  2761. ret = diffone / d64;
  2762. cg_wlock(&control_lock);
  2763. if (unlikely(ret > best_diff)) {
  2764. new_best = true;
  2765. best_diff = ret;
  2766. suffix_string(best_diff, best_share, 0);
  2767. }
  2768. if (unlikely(ret > work->pool->best_diff))
  2769. work->pool->best_diff = ret;
  2770. cg_wunlock(&control_lock);
  2771. if (unlikely(new_best))
  2772. applog(LOG_INFO, "New best share: %s", best_share);
  2773. return ret;
  2774. }
  2775. static void regen_hash(struct work *work)
  2776. {
  2777. uint32_t *data32 = (uint32_t *)(work->data);
  2778. unsigned char swap[80];
  2779. uint32_t *swap32 = (uint32_t *)swap;
  2780. unsigned char hash1[32];
  2781. flip80(swap32, data32);
  2782. sha2(swap, 80, hash1);
  2783. sha2(hash1, 32, (unsigned char *)(work->hash));
  2784. }
  2785. static void rebuild_hash(struct work *work)
  2786. {
  2787. if (opt_scrypt)
  2788. scrypt_regenhash(work);
  2789. else
  2790. regen_hash(work);
  2791. work->share_diff = share_diff(work);
  2792. if (unlikely(work->share_diff >= current_diff)) {
  2793. work->block = true;
  2794. work->pool->solved++;
  2795. found_blocks++;
  2796. work->mandatory = true;
  2797. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  2798. }
  2799. }
  2800. static bool cnx_needed(struct pool *pool);
  2801. static void *submit_work_thread(void *userdata)
  2802. {
  2803. struct work *work = (struct work *)userdata;
  2804. struct pool *pool = work->pool;
  2805. bool resubmit = false;
  2806. struct curl_ent *ce;
  2807. pthread_detach(pthread_self());
  2808. RenameThread("submit_work");
  2809. applog(LOG_DEBUG, "Creating extra submit work thread");
  2810. ce = pop_curl_entry(pool);
  2811. /* submit solution to bitcoin via JSON-RPC */
  2812. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2813. if (opt_lowmem) {
  2814. applog(LOG_NOTICE, "Pool %d share being discarded to minimise memory cache", pool->pool_no);
  2815. break;
  2816. }
  2817. resubmit = true;
  2818. if (stale_work(work, true)) {
  2819. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  2820. mutex_lock(&stats_lock);
  2821. total_stale++;
  2822. pool->stale_shares++;
  2823. total_diff_stale += work->work_difficulty;
  2824. pool->diff_stale += work->work_difficulty;
  2825. mutex_unlock(&stats_lock);
  2826. free_work(work);
  2827. break;
  2828. }
  2829. /* pause, then restart work-request loop */
  2830. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2831. }
  2832. push_curl_entry(ce, pool);
  2833. return NULL;
  2834. }
  2835. /* Find the pool that currently has the highest priority */
  2836. static struct pool *priority_pool(int choice)
  2837. {
  2838. struct pool *ret = NULL;
  2839. int i;
  2840. for (i = 0; i < total_pools; i++) {
  2841. struct pool *pool = pools[i];
  2842. if (pool->prio == choice) {
  2843. ret = pool;
  2844. break;
  2845. }
  2846. }
  2847. if (unlikely(!ret)) {
  2848. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2849. return pools[choice];
  2850. }
  2851. return ret;
  2852. }
  2853. static void clear_pool_work(struct pool *pool);
  2854. /* Specifies whether we can switch to this pool or not. */
  2855. static bool pool_unusable(struct pool *pool)
  2856. {
  2857. if (pool->idle)
  2858. return true;
  2859. if (pool->enabled != POOL_ENABLED)
  2860. return true;
  2861. return false;
  2862. }
  2863. void switch_pools(struct pool *selected)
  2864. {
  2865. struct pool *pool, *last_pool;
  2866. int i, pool_no, next_pool;
  2867. cg_wlock(&control_lock);
  2868. last_pool = currentpool;
  2869. pool_no = currentpool->pool_no;
  2870. /* Switch selected to pool number 0 and move the rest down */
  2871. if (selected) {
  2872. if (selected->prio != 0) {
  2873. for (i = 0; i < total_pools; i++) {
  2874. pool = pools[i];
  2875. if (pool->prio < selected->prio)
  2876. pool->prio++;
  2877. }
  2878. selected->prio = 0;
  2879. }
  2880. }
  2881. switch (pool_strategy) {
  2882. /* Both of these set to the master pool */
  2883. case POOL_BALANCE:
  2884. case POOL_FAILOVER:
  2885. case POOL_LOADBALANCE:
  2886. for (i = 0; i < total_pools; i++) {
  2887. pool = priority_pool(i);
  2888. if (pool_unusable(pool))
  2889. continue;
  2890. pool_no = pool->pool_no;
  2891. break;
  2892. }
  2893. break;
  2894. /* Both of these simply increment and cycle */
  2895. case POOL_ROUNDROBIN:
  2896. case POOL_ROTATE:
  2897. if (selected && !selected->idle) {
  2898. pool_no = selected->pool_no;
  2899. break;
  2900. }
  2901. next_pool = pool_no;
  2902. /* Select the next alive pool */
  2903. for (i = 1; i < total_pools; i++) {
  2904. next_pool++;
  2905. if (next_pool >= total_pools)
  2906. next_pool = 0;
  2907. pool = pools[next_pool];
  2908. if (pool_unusable(pool))
  2909. continue;
  2910. pool_no = next_pool;
  2911. break;
  2912. }
  2913. break;
  2914. default:
  2915. break;
  2916. }
  2917. currentpool = pools[pool_no];
  2918. pool = currentpool;
  2919. cg_wunlock(&control_lock);
  2920. /* Set the lagging flag to avoid pool not providing work fast enough
  2921. * messages in failover only mode since we have to get all fresh work
  2922. * as in restart_threads */
  2923. if (opt_fail_only)
  2924. pool_tset(pool, &pool->lagging);
  2925. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2926. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  2927. if (pool->has_gbt || pool->has_stratum || opt_fail_only)
  2928. clear_pool_work(last_pool);
  2929. }
  2930. mutex_lock(&lp_lock);
  2931. pthread_cond_broadcast(&lp_cond);
  2932. mutex_unlock(&lp_lock);
  2933. }
  2934. void discard_work(struct work *work)
  2935. {
  2936. if (!work->clone && !work->rolls && !work->mined) {
  2937. if (work->pool)
  2938. work->pool->discarded_work++;
  2939. total_discarded++;
  2940. applog(LOG_DEBUG, "Discarded work");
  2941. } else
  2942. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2943. free_work(work);
  2944. }
  2945. static void wake_gws(void)
  2946. {
  2947. mutex_lock(stgd_lock);
  2948. pthread_cond_signal(&gws_cond);
  2949. mutex_unlock(stgd_lock);
  2950. }
  2951. static void discard_stale(void)
  2952. {
  2953. struct work *work, *tmp;
  2954. int stale = 0;
  2955. mutex_lock(stgd_lock);
  2956. HASH_ITER(hh, staged_work, work, tmp) {
  2957. if (stale_work(work, false)) {
  2958. HASH_DEL(staged_work, work);
  2959. discard_work(work);
  2960. stale++;
  2961. }
  2962. }
  2963. pthread_cond_signal(&gws_cond);
  2964. mutex_unlock(stgd_lock);
  2965. if (stale)
  2966. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2967. }
  2968. /* A generic wait function for threads that poll that will wait a specified
  2969. * time tdiff waiting on the pthread conditional that is broadcast when a
  2970. * work restart is required. Returns the value of pthread_cond_timedwait
  2971. * which is zero if the condition was met or ETIMEDOUT if not.
  2972. */
  2973. int restart_wait(unsigned int mstime)
  2974. {
  2975. struct timeval now, then, tdiff;
  2976. struct timespec abstime;
  2977. int rc;
  2978. tdiff.tv_sec = mstime / 1000;
  2979. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  2980. cgtime(&now);
  2981. timeradd(&now, &tdiff, &then);
  2982. abstime.tv_sec = then.tv_sec;
  2983. abstime.tv_nsec = then.tv_usec * 1000;
  2984. mutex_lock(&restart_lock);
  2985. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  2986. mutex_unlock(&restart_lock);
  2987. return rc;
  2988. }
  2989. static void restart_threads(void)
  2990. {
  2991. struct pool *cp = current_pool();
  2992. int i;
  2993. /* Artificially set the lagging flag to avoid pool not providing work
  2994. * fast enough messages after every long poll */
  2995. pool_tset(cp, &cp->lagging);
  2996. /* Discard staged work that is now stale */
  2997. discard_stale();
  2998. rd_lock(&mining_thr_lock);
  2999. for (i = 0; i < mining_threads; i++)
  3000. mining_thr[i]->work_restart = true;
  3001. rd_unlock(&mining_thr_lock);
  3002. mutex_lock(&restart_lock);
  3003. pthread_cond_broadcast(&restart_cond);
  3004. mutex_unlock(&restart_lock);
  3005. }
  3006. static void set_curblock(char *hexstr, unsigned char *hash)
  3007. {
  3008. unsigned char hash_swap[32];
  3009. unsigned char block_hash_swap[32];
  3010. strcpy(current_block, hexstr);
  3011. swap256(hash_swap, hash);
  3012. swap256(block_hash_swap, hash + 4);
  3013. cg_wlock(&ch_lock);
  3014. cgtime(&block_timeval);
  3015. free(current_hash);
  3016. current_hash = bin2hex(hash_swap + 2, 8);
  3017. free(current_fullhash);
  3018. current_fullhash = bin2hex(block_hash_swap, 32);
  3019. get_timestamp(blocktime, &block_timeval);
  3020. cg_wunlock(&ch_lock);
  3021. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  3022. }
  3023. /* Search to see if this string is from a block that has been seen before */
  3024. static bool block_exists(char *hexstr)
  3025. {
  3026. struct block *s;
  3027. rd_lock(&blk_lock);
  3028. HASH_FIND_STR(blocks, hexstr, s);
  3029. rd_unlock(&blk_lock);
  3030. if (s)
  3031. return true;
  3032. return false;
  3033. }
  3034. /* Tests if this work is from a block that has been seen before */
  3035. static inline bool from_existing_block(struct work *work)
  3036. {
  3037. char *hexstr = bin2hex(work->data + 8, 18);
  3038. bool ret;
  3039. ret = block_exists(hexstr);
  3040. free(hexstr);
  3041. return ret;
  3042. }
  3043. static int block_sort(struct block *blocka, struct block *blockb)
  3044. {
  3045. return blocka->block_no - blockb->block_no;
  3046. }
  3047. static void set_blockdiff(const struct work *work)
  3048. {
  3049. uint64_t *data64, d64, diff64;
  3050. double previous_diff;
  3051. uint32_t diffhash[8];
  3052. uint32_t difficulty;
  3053. uint32_t diffbytes;
  3054. uint32_t diffvalue;
  3055. char rhash[32];
  3056. int diffshift;
  3057. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  3058. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  3059. diffvalue = difficulty & 0x00ffffff;
  3060. diffshift = (diffbytes % 4) * 8;
  3061. if (diffshift == 0) {
  3062. diffshift = 32;
  3063. diffbytes--;
  3064. }
  3065. memset(diffhash, 0, 32);
  3066. diffbytes >>= 2;
  3067. if (unlikely(diffbytes > 6))
  3068. return;
  3069. diffhash[diffbytes + 1] = diffvalue >> (32 - diffshift);
  3070. diffhash[diffbytes] = diffvalue << diffshift;
  3071. swab256(rhash, diffhash);
  3072. if (opt_scrypt)
  3073. data64 = (uint64_t *)(rhash + 2);
  3074. else
  3075. data64 = (uint64_t *)(rhash + 4);
  3076. d64 = be64toh(*data64);
  3077. if (unlikely(!d64))
  3078. d64 = 1;
  3079. previous_diff = current_diff;
  3080. diff64 = diffone / d64;
  3081. suffix_string(diff64, block_diff, 0);
  3082. current_diff = (double)diffone / (double)d64;
  3083. if (unlikely(current_diff != previous_diff))
  3084. applog(LOG_NOTICE, "Network diff set to %s", block_diff);
  3085. }
  3086. static bool test_work_current(struct work *work)
  3087. {
  3088. bool ret = true;
  3089. char *hexstr;
  3090. if (work->mandatory)
  3091. return ret;
  3092. /* Hack to work around dud work sneaking into test */
  3093. hexstr = bin2hex(work->data + 8, 18);
  3094. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  3095. goto out_free;
  3096. /* Search to see if this block exists yet and if not, consider it a
  3097. * new block and set the current block details to this one */
  3098. if (!block_exists(hexstr)) {
  3099. struct block *s = calloc(sizeof(struct block), 1);
  3100. int deleted_block = 0;
  3101. ret = false;
  3102. if (unlikely(!s))
  3103. quit (1, "test_work_current OOM");
  3104. strcpy(s->hash, hexstr);
  3105. s->block_no = new_blocks++;
  3106. wr_lock(&blk_lock);
  3107. /* Only keep the last hour's worth of blocks in memory since
  3108. * work from blocks before this is virtually impossible and we
  3109. * want to prevent memory usage from continually rising */
  3110. if (HASH_COUNT(blocks) > 6) {
  3111. struct block *oldblock;
  3112. HASH_SORT(blocks, block_sort);
  3113. oldblock = blocks;
  3114. deleted_block = oldblock->block_no;
  3115. HASH_DEL(blocks, oldblock);
  3116. free(oldblock);
  3117. }
  3118. HASH_ADD_STR(blocks, hash, s);
  3119. set_blockdiff(work);
  3120. wr_unlock(&blk_lock);
  3121. if (deleted_block)
  3122. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3123. set_curblock(hexstr, work->data);
  3124. if (unlikely(new_blocks == 1))
  3125. goto out_free;
  3126. work->work_block = ++work_block;
  3127. if (!work->stratum) {
  3128. if (work->longpoll) {
  3129. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
  3130. work->gbt ? "GBT " : "", work->pool->pool_no);
  3131. } else if (have_longpoll)
  3132. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3133. else
  3134. applog(LOG_NOTICE, "New block detected on network");
  3135. }
  3136. restart_threads();
  3137. } else if (work->longpoll) {
  3138. work->work_block = ++work_block;
  3139. if (work->pool == current_pool()) {
  3140. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  3141. work->gbt ? "GBT " : "", work->pool->pool_no);
  3142. restart_threads();
  3143. }
  3144. }
  3145. work->longpoll = false;
  3146. out_free:
  3147. free(hexstr);
  3148. return ret;
  3149. }
  3150. static int tv_sort(struct work *worka, struct work *workb)
  3151. {
  3152. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3153. }
  3154. static bool work_rollable(struct work *work)
  3155. {
  3156. return (!work->clone && work->rolltime);
  3157. }
  3158. static bool hash_push(struct work *work)
  3159. {
  3160. bool rc = true;
  3161. mutex_lock(stgd_lock);
  3162. if (work_rollable(work))
  3163. staged_rollable++;
  3164. if (likely(!getq->frozen)) {
  3165. HASH_ADD_INT(staged_work, id, work);
  3166. HASH_SORT(staged_work, tv_sort);
  3167. } else
  3168. rc = false;
  3169. pthread_cond_broadcast(&getq->cond);
  3170. mutex_unlock(stgd_lock);
  3171. return rc;
  3172. }
  3173. static void *stage_thread(void *userdata)
  3174. {
  3175. struct thr_info *mythr = userdata;
  3176. bool ok = true;
  3177. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3178. RenameThread("stage");
  3179. while (ok) {
  3180. struct work *work = NULL;
  3181. applog(LOG_DEBUG, "Popping work to stage thread");
  3182. work = tq_pop(mythr->q, NULL);
  3183. if (unlikely(!work)) {
  3184. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3185. ok = false;
  3186. break;
  3187. }
  3188. work->work_block = work_block;
  3189. test_work_current(work);
  3190. applog(LOG_DEBUG, "Pushing work to getwork queue");
  3191. if (unlikely(!hash_push(work))) {
  3192. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3193. continue;
  3194. }
  3195. }
  3196. tq_freeze(mythr->q);
  3197. return NULL;
  3198. }
  3199. static void stage_work(struct work *work)
  3200. {
  3201. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  3202. work->work_block = work_block;
  3203. test_work_current(work);
  3204. hash_push(work);
  3205. }
  3206. #ifdef HAVE_CURSES
  3207. int curses_int(const char *query)
  3208. {
  3209. int ret;
  3210. char *cvar;
  3211. cvar = curses_input(query);
  3212. ret = atoi(cvar);
  3213. free(cvar);
  3214. return ret;
  3215. }
  3216. #endif
  3217. #ifdef HAVE_CURSES
  3218. static bool input_pool(bool live);
  3219. #endif
  3220. #ifdef HAVE_CURSES
  3221. static void display_pool_summary(struct pool *pool)
  3222. {
  3223. double efficiency = 0.0;
  3224. if (curses_active_locked()) {
  3225. wlog("Pool: %s\n", pool->rpc_url);
  3226. if (pool->solved)
  3227. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3228. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  3229. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3230. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3231. wlog(" Accepted shares: %d\n", pool->accepted);
  3232. wlog(" Rejected shares: %d\n", pool->rejected);
  3233. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  3234. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  3235. if (pool->accepted || pool->rejected)
  3236. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3237. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3238. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3239. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3240. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3241. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3242. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3243. unlock_curses();
  3244. }
  3245. }
  3246. #endif
  3247. /* We can't remove the memory used for this struct pool because there may
  3248. * still be work referencing it. We just remove it from the pools list */
  3249. void remove_pool(struct pool *pool)
  3250. {
  3251. int i, last_pool = total_pools - 1;
  3252. struct pool *other;
  3253. /* Boost priority of any lower prio than this one */
  3254. for (i = 0; i < total_pools; i++) {
  3255. other = pools[i];
  3256. if (other->prio > pool->prio)
  3257. other->prio--;
  3258. }
  3259. if (pool->pool_no < last_pool) {
  3260. /* Swap the last pool for this one */
  3261. (pools[last_pool])->pool_no = pool->pool_no;
  3262. pools[pool->pool_no] = pools[last_pool];
  3263. }
  3264. /* Give it an invalid number */
  3265. pool->pool_no = total_pools;
  3266. pool->removed = true;
  3267. total_pools--;
  3268. }
  3269. /* add a mutex if this needs to be thread safe in the future */
  3270. static struct JE {
  3271. char *buf;
  3272. struct JE *next;
  3273. } *jedata = NULL;
  3274. static void json_escape_free()
  3275. {
  3276. struct JE *jeptr = jedata;
  3277. struct JE *jenext;
  3278. jedata = NULL;
  3279. while (jeptr) {
  3280. jenext = jeptr->next;
  3281. free(jeptr->buf);
  3282. free(jeptr);
  3283. jeptr = jenext;
  3284. }
  3285. }
  3286. static char *json_escape(char *str)
  3287. {
  3288. struct JE *jeptr;
  3289. char *buf, *ptr;
  3290. /* 2x is the max, may as well just allocate that */
  3291. ptr = buf = malloc(strlen(str) * 2 + 1);
  3292. jeptr = malloc(sizeof(*jeptr));
  3293. jeptr->buf = buf;
  3294. jeptr->next = jedata;
  3295. jedata = jeptr;
  3296. while (*str) {
  3297. if (*str == '\\' || *str == '"')
  3298. *(ptr++) = '\\';
  3299. *(ptr++) = *(str++);
  3300. }
  3301. *ptr = '\0';
  3302. return buf;
  3303. }
  3304. void write_config(FILE *fcfg)
  3305. {
  3306. int i;
  3307. /* Write pool values */
  3308. fputs("{\n\"pools\" : [", fcfg);
  3309. for(i = 0; i < total_pools; i++) {
  3310. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  3311. pools[i]->rpc_proxy ? json_escape((char *)proxytype(pools[i]->rpc_proxytype)) : "",
  3312. pools[i]->rpc_proxy ? json_escape(pools[i]->rpc_proxy) : "",
  3313. pools[i]->rpc_proxy ? "|" : "",
  3314. json_escape(pools[i]->rpc_url));
  3315. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3316. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  3317. }
  3318. fputs("\n]\n", fcfg);
  3319. #ifdef HAVE_OPENCL
  3320. if (nDevs) {
  3321. /* Write GPU device values */
  3322. fputs(",\n\"intensity\" : \"", fcfg);
  3323. for(i = 0; i < nDevs; i++)
  3324. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3325. fputs("\",\n\"vectors\" : \"", fcfg);
  3326. for(i = 0; i < nDevs; i++)
  3327. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3328. gpus[i].vwidth);
  3329. fputs("\",\n\"worksize\" : \"", fcfg);
  3330. for(i = 0; i < nDevs; i++)
  3331. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3332. (int)gpus[i].work_size);
  3333. fputs("\",\n\"kernel\" : \"", fcfg);
  3334. for(i = 0; i < nDevs; i++) {
  3335. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3336. switch (gpus[i].kernel) {
  3337. case KL_NONE: // Shouldn't happen
  3338. break;
  3339. case KL_POCLBM:
  3340. fprintf(fcfg, "poclbm");
  3341. break;
  3342. case KL_PHATK:
  3343. fprintf(fcfg, "phatk");
  3344. break;
  3345. case KL_DIAKGCN:
  3346. fprintf(fcfg, "diakgcn");
  3347. break;
  3348. case KL_DIABLO:
  3349. fprintf(fcfg, "diablo");
  3350. break;
  3351. case KL_SCRYPT:
  3352. fprintf(fcfg, "scrypt");
  3353. break;
  3354. }
  3355. }
  3356. #ifdef USE_SCRYPT
  3357. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3358. for(i = 0; i < nDevs; i++)
  3359. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3360. (int)gpus[i].opt_lg);
  3361. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3362. for(i = 0; i < nDevs; i++)
  3363. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3364. (int)gpus[i].opt_tc);
  3365. fputs("\",\n\"shaders\" : \"", fcfg);
  3366. for(i = 0; i < nDevs; i++)
  3367. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3368. (int)gpus[i].shaders);
  3369. #endif
  3370. #ifdef HAVE_ADL
  3371. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3372. for(i = 0; i < nDevs; i++)
  3373. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3374. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3375. for(i = 0; i < nDevs; i++)
  3376. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3377. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3378. for(i = 0; i < nDevs; i++)
  3379. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3380. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3381. for(i = 0; i < nDevs; i++)
  3382. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3383. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3384. for(i = 0; i < nDevs; i++)
  3385. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3386. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3387. for(i = 0; i < nDevs; i++)
  3388. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3389. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3390. for(i = 0; i < nDevs; i++)
  3391. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3392. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3393. for(i = 0; i < nDevs; i++)
  3394. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3395. fputs("\",\n\"temp-target\" : \"", fcfg);
  3396. for(i = 0; i < nDevs; i++)
  3397. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  3398. #endif
  3399. fputs("\"", fcfg);
  3400. }
  3401. #endif
  3402. #ifdef HAVE_ADL
  3403. if (opt_reorder)
  3404. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3405. #endif
  3406. /* Simple bool and int options */
  3407. struct opt_table *opt;
  3408. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3409. char *p, *name = strdup(opt->names);
  3410. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3411. if (p[1] != '-')
  3412. continue;
  3413. if (opt->type & OPT_NOARG &&
  3414. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3415. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3416. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3417. if (opt->type & OPT_HASARG &&
  3418. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3419. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3420. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3421. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  3422. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3423. }
  3424. }
  3425. /* Special case options */
  3426. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3427. if (pool_strategy == POOL_BALANCE)
  3428. fputs(",\n\"balance\" : true", fcfg);
  3429. if (pool_strategy == POOL_LOADBALANCE)
  3430. fputs(",\n\"load-balance\" : true", fcfg);
  3431. if (pool_strategy == POOL_ROUNDROBIN)
  3432. fputs(",\n\"round-robin\" : true", fcfg);
  3433. if (pool_strategy == POOL_ROTATE)
  3434. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3435. #if defined(unix)
  3436. if (opt_stderr_cmd && *opt_stderr_cmd)
  3437. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3438. #endif // defined(unix)
  3439. if (opt_kernel_path && *opt_kernel_path) {
  3440. char *kpath = strdup(opt_kernel_path);
  3441. if (kpath[strlen(kpath)-1] == '/')
  3442. kpath[strlen(kpath)-1] = 0;
  3443. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3444. }
  3445. if (schedstart.enable)
  3446. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3447. if (schedstop.enable)
  3448. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3449. if (opt_socks_proxy && *opt_socks_proxy)
  3450. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3451. if (opt_devs_enabled) {
  3452. fprintf(fcfg, ",\n\"device\" : \"");
  3453. bool extra_devs = false;
  3454. for (i = 0; i < MAX_DEVICES; i++) {
  3455. if (devices_enabled[i]) {
  3456. int startd = i;
  3457. if (extra_devs)
  3458. fprintf(fcfg, ",");
  3459. while (i < MAX_DEVICES && devices_enabled[i + 1])
  3460. ++i;
  3461. fprintf(fcfg, "%d", startd);
  3462. if (i > startd)
  3463. fprintf(fcfg, "-%d", i);
  3464. }
  3465. }
  3466. fprintf(fcfg, "\"");
  3467. }
  3468. if (opt_removedisabled)
  3469. fprintf(fcfg, ",\n\"remove-disabled\" : true");
  3470. if (opt_api_allow)
  3471. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3472. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3473. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3474. if (opt_api_groups)
  3475. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3476. if (opt_icarus_options)
  3477. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3478. if (opt_icarus_timing)
  3479. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3480. #ifdef USE_USBUTILS
  3481. if (opt_usb_select)
  3482. fprintf(fcfg, ",\n\"usb\" : \"%s\"", json_escape(opt_usb_select));
  3483. #endif
  3484. fputs("\n}\n", fcfg);
  3485. json_escape_free();
  3486. }
  3487. void zero_bestshare(void)
  3488. {
  3489. int i;
  3490. best_diff = 0;
  3491. memset(best_share, 0, 8);
  3492. suffix_string(best_diff, best_share, 0);
  3493. for (i = 0; i < total_pools; i++) {
  3494. struct pool *pool = pools[i];
  3495. pool->best_diff = 0;
  3496. }
  3497. }
  3498. void zero_stats(void)
  3499. {
  3500. int i;
  3501. cgtime(&total_tv_start);
  3502. total_mhashes_done = 0;
  3503. total_getworks = 0;
  3504. total_accepted = 0;
  3505. total_rejected = 0;
  3506. hw_errors = 0;
  3507. total_stale = 0;
  3508. total_discarded = 0;
  3509. local_work = 0;
  3510. total_go = 0;
  3511. total_ro = 0;
  3512. total_secs = 1.0;
  3513. total_diff1 = 0;
  3514. found_blocks = 0;
  3515. total_diff_accepted = 0;
  3516. total_diff_rejected = 0;
  3517. total_diff_stale = 0;
  3518. for (i = 0; i < total_pools; i++) {
  3519. struct pool *pool = pools[i];
  3520. pool->getwork_requested = 0;
  3521. pool->accepted = 0;
  3522. pool->rejected = 0;
  3523. pool->stale_shares = 0;
  3524. pool->discarded_work = 0;
  3525. pool->getfail_occasions = 0;
  3526. pool->remotefail_occasions = 0;
  3527. pool->last_share_time = 0;
  3528. pool->diff1 = 0;
  3529. pool->diff_accepted = 0;
  3530. pool->diff_rejected = 0;
  3531. pool->diff_stale = 0;
  3532. pool->last_share_diff = 0;
  3533. }
  3534. zero_bestshare();
  3535. for (i = 0; i < total_devices; ++i) {
  3536. struct cgpu_info *cgpu = get_devices(i);
  3537. mutex_lock(&hash_lock);
  3538. cgpu->total_mhashes = 0;
  3539. cgpu->accepted = 0;
  3540. cgpu->rejected = 0;
  3541. cgpu->hw_errors = 0;
  3542. cgpu->utility = 0.0;
  3543. cgpu->last_share_pool_time = 0;
  3544. cgpu->diff1 = 0;
  3545. cgpu->diff_accepted = 0;
  3546. cgpu->diff_rejected = 0;
  3547. cgpu->last_share_diff = 0;
  3548. mutex_unlock(&hash_lock);
  3549. }
  3550. }
  3551. #ifdef HAVE_CURSES
  3552. static void display_pools(void)
  3553. {
  3554. struct pool *pool;
  3555. int selected, i;
  3556. char input;
  3557. opt_loginput = true;
  3558. immedok(logwin, true);
  3559. clear_logwin();
  3560. updated:
  3561. for (i = 0; i < total_pools; i++) {
  3562. pool = pools[i];
  3563. if (pool == current_pool())
  3564. wattron(logwin, A_BOLD);
  3565. if (pool->enabled != POOL_ENABLED)
  3566. wattron(logwin, A_DIM);
  3567. wlogprint("%d: ", pool->pool_no);
  3568. switch (pool->enabled) {
  3569. case POOL_ENABLED:
  3570. wlogprint("Enabled ");
  3571. break;
  3572. case POOL_DISABLED:
  3573. wlogprint("Disabled ");
  3574. break;
  3575. case POOL_REJECTING:
  3576. wlogprint("Rejecting ");
  3577. break;
  3578. }
  3579. wlogprint("%s Priority %d: %s User:%s\n",
  3580. pool->idle? "Dead" : "Alive",
  3581. pool->prio,
  3582. pool->rpc_url, pool->rpc_user);
  3583. wattroff(logwin, A_BOLD | A_DIM);
  3584. }
  3585. retry:
  3586. wlogprint("\nCurrent pool management strategy: %s\n",
  3587. strategies[pool_strategy]);
  3588. if (pool_strategy == POOL_ROTATE)
  3589. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3590. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3591. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3592. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3593. wlogprint("Or press any other key to continue\n");
  3594. logwin_update();
  3595. input = getch();
  3596. if (!strncasecmp(&input, "a", 1)) {
  3597. input_pool(true);
  3598. goto updated;
  3599. } else if (!strncasecmp(&input, "r", 1)) {
  3600. if (total_pools <= 1) {
  3601. wlogprint("Cannot remove last pool");
  3602. goto retry;
  3603. }
  3604. selected = curses_int("Select pool number");
  3605. if (selected < 0 || selected >= total_pools) {
  3606. wlogprint("Invalid selection\n");
  3607. goto retry;
  3608. }
  3609. pool = pools[selected];
  3610. if (pool == current_pool())
  3611. switch_pools(NULL);
  3612. if (pool == current_pool()) {
  3613. wlogprint("Unable to remove pool due to activity\n");
  3614. goto retry;
  3615. }
  3616. disable_pool(pool);
  3617. remove_pool(pool);
  3618. goto updated;
  3619. } else if (!strncasecmp(&input, "s", 1)) {
  3620. selected = curses_int("Select pool number");
  3621. if (selected < 0 || selected >= total_pools) {
  3622. wlogprint("Invalid selection\n");
  3623. goto retry;
  3624. }
  3625. pool = pools[selected];
  3626. enable_pool(pool);
  3627. switch_pools(pool);
  3628. goto updated;
  3629. } else if (!strncasecmp(&input, "d", 1)) {
  3630. if (enabled_pools <= 1) {
  3631. wlogprint("Cannot disable last pool");
  3632. goto retry;
  3633. }
  3634. selected = curses_int("Select pool number");
  3635. if (selected < 0 || selected >= total_pools) {
  3636. wlogprint("Invalid selection\n");
  3637. goto retry;
  3638. }
  3639. pool = pools[selected];
  3640. disable_pool(pool);
  3641. if (pool == current_pool())
  3642. switch_pools(NULL);
  3643. goto updated;
  3644. } else if (!strncasecmp(&input, "e", 1)) {
  3645. selected = curses_int("Select pool number");
  3646. if (selected < 0 || selected >= total_pools) {
  3647. wlogprint("Invalid selection\n");
  3648. goto retry;
  3649. }
  3650. pool = pools[selected];
  3651. enable_pool(pool);
  3652. if (pool->prio < current_pool()->prio)
  3653. switch_pools(pool);
  3654. goto updated;
  3655. } else if (!strncasecmp(&input, "c", 1)) {
  3656. for (i = 0; i <= TOP_STRATEGY; i++)
  3657. wlogprint("%d: %s\n", i, strategies[i]);
  3658. selected = curses_int("Select strategy number type");
  3659. if (selected < 0 || selected > TOP_STRATEGY) {
  3660. wlogprint("Invalid selection\n");
  3661. goto retry;
  3662. }
  3663. if (selected == POOL_ROTATE) {
  3664. opt_rotate_period = curses_int("Select interval in minutes");
  3665. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3666. opt_rotate_period = 0;
  3667. wlogprint("Invalid selection\n");
  3668. goto retry;
  3669. }
  3670. }
  3671. pool_strategy = selected;
  3672. switch_pools(NULL);
  3673. goto updated;
  3674. } else if (!strncasecmp(&input, "i", 1)) {
  3675. selected = curses_int("Select pool number");
  3676. if (selected < 0 || selected >= total_pools) {
  3677. wlogprint("Invalid selection\n");
  3678. goto retry;
  3679. }
  3680. pool = pools[selected];
  3681. display_pool_summary(pool);
  3682. goto retry;
  3683. } else if (!strncasecmp(&input, "f", 1)) {
  3684. opt_fail_only ^= true;
  3685. goto updated;
  3686. } else
  3687. clear_logwin();
  3688. immedok(logwin, false);
  3689. opt_loginput = false;
  3690. }
  3691. static void display_options(void)
  3692. {
  3693. int selected;
  3694. char input;
  3695. opt_loginput = true;
  3696. immedok(logwin, true);
  3697. clear_logwin();
  3698. retry:
  3699. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3700. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  3701. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  3702. "[L]og interval:%d\n[Z]ero statistics\n",
  3703. opt_debug ? "on" : "off",
  3704. want_per_device_stats? "on" : "off",
  3705. opt_quiet ? "on" : "off",
  3706. opt_log_output ? "on" : "off",
  3707. opt_protocol ? "on" : "off",
  3708. opt_worktime ? "on" : "off",
  3709. opt_compact ? "on" : "off",
  3710. opt_log_interval);
  3711. wlogprint("Select an option or any other key to return\n");
  3712. logwin_update();
  3713. input = getch();
  3714. if (!strncasecmp(&input, "q", 1)) {
  3715. opt_quiet ^= true;
  3716. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3717. goto retry;
  3718. } else if (!strncasecmp(&input, "v", 1)) {
  3719. opt_log_output ^= true;
  3720. if (opt_log_output)
  3721. opt_quiet = false;
  3722. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3723. goto retry;
  3724. } else if (!strncasecmp(&input, "n", 1)) {
  3725. opt_log_output = false;
  3726. opt_debug = false;
  3727. opt_quiet = false;
  3728. opt_protocol = false;
  3729. opt_compact = false;
  3730. want_per_device_stats = false;
  3731. wlogprint("Output mode reset to normal\n");
  3732. switch_logsize();
  3733. goto retry;
  3734. } else if (!strncasecmp(&input, "d", 1)) {
  3735. opt_debug ^= true;
  3736. opt_log_output = opt_debug;
  3737. if (opt_debug)
  3738. opt_quiet = false;
  3739. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  3740. goto retry;
  3741. } else if (!strncasecmp(&input, "m", 1)) {
  3742. opt_compact ^= true;
  3743. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  3744. switch_logsize();
  3745. goto retry;
  3746. } else if (!strncasecmp(&input, "p", 1)) {
  3747. want_per_device_stats ^= true;
  3748. opt_log_output = want_per_device_stats;
  3749. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3750. goto retry;
  3751. } else if (!strncasecmp(&input, "r", 1)) {
  3752. opt_protocol ^= true;
  3753. if (opt_protocol)
  3754. opt_quiet = false;
  3755. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3756. goto retry;
  3757. } else if (!strncasecmp(&input, "c", 1))
  3758. clear_logwin();
  3759. else if (!strncasecmp(&input, "l", 1)) {
  3760. selected = curses_int("Interval in seconds");
  3761. if (selected < 0 || selected > 9999) {
  3762. wlogprint("Invalid selection\n");
  3763. goto retry;
  3764. }
  3765. opt_log_interval = selected;
  3766. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3767. goto retry;
  3768. } else if (!strncasecmp(&input, "s", 1)) {
  3769. opt_realquiet = true;
  3770. } else if (!strncasecmp(&input, "w", 1)) {
  3771. opt_worktime ^= true;
  3772. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  3773. goto retry;
  3774. } else if (!strncasecmp(&input, "z", 1)) {
  3775. zero_stats();
  3776. goto retry;
  3777. } else
  3778. clear_logwin();
  3779. immedok(logwin, false);
  3780. opt_loginput = false;
  3781. }
  3782. #endif
  3783. void default_save_file(char *filename)
  3784. {
  3785. if (default_config && *default_config) {
  3786. strcpy(filename, default_config);
  3787. return;
  3788. }
  3789. #if defined(unix)
  3790. if (getenv("HOME") && *getenv("HOME")) {
  3791. strcpy(filename, getenv("HOME"));
  3792. strcat(filename, "/");
  3793. }
  3794. else
  3795. strcpy(filename, "");
  3796. strcat(filename, ".cgminer/");
  3797. mkdir(filename, 0777);
  3798. #else
  3799. strcpy(filename, "");
  3800. #endif
  3801. strcat(filename, def_conf);
  3802. }
  3803. #ifdef HAVE_CURSES
  3804. static void set_options(void)
  3805. {
  3806. int selected;
  3807. char input;
  3808. opt_loginput = true;
  3809. immedok(logwin, true);
  3810. clear_logwin();
  3811. retry:
  3812. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  3813. "[W]rite config file\n[C]gminer restart\n",
  3814. opt_queue, opt_scantime, opt_expiry);
  3815. wlogprint("Select an option or any other key to return\n");
  3816. logwin_update();
  3817. input = getch();
  3818. if (!strncasecmp(&input, "q", 1)) {
  3819. selected = curses_int("Extra work items to queue");
  3820. if (selected < 0 || selected > 9999) {
  3821. wlogprint("Invalid selection\n");
  3822. goto retry;
  3823. }
  3824. opt_queue = selected;
  3825. goto retry;
  3826. } else if (!strncasecmp(&input, "s", 1)) {
  3827. selected = curses_int("Set scantime in seconds");
  3828. if (selected < 0 || selected > 9999) {
  3829. wlogprint("Invalid selection\n");
  3830. goto retry;
  3831. }
  3832. opt_scantime = selected;
  3833. goto retry;
  3834. } else if (!strncasecmp(&input, "e", 1)) {
  3835. selected = curses_int("Set expiry time in seconds");
  3836. if (selected < 0 || selected > 9999) {
  3837. wlogprint("Invalid selection\n");
  3838. goto retry;
  3839. }
  3840. opt_expiry = selected;
  3841. goto retry;
  3842. } else if (!strncasecmp(&input, "w", 1)) {
  3843. FILE *fcfg;
  3844. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3845. default_save_file(filename);
  3846. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3847. str = curses_input(prompt);
  3848. if (strcmp(str, "-1")) {
  3849. struct stat statbuf;
  3850. strcpy(filename, str);
  3851. free(str);
  3852. if (!stat(filename, &statbuf)) {
  3853. wlogprint("File exists, overwrite?\n");
  3854. input = getch();
  3855. if (strncasecmp(&input, "y", 1))
  3856. goto retry;
  3857. }
  3858. }
  3859. else
  3860. free(str);
  3861. fcfg = fopen(filename, "w");
  3862. if (!fcfg) {
  3863. wlogprint("Cannot open or create file\n");
  3864. goto retry;
  3865. }
  3866. write_config(fcfg);
  3867. fclose(fcfg);
  3868. goto retry;
  3869. } else if (!strncasecmp(&input, "c", 1)) {
  3870. wlogprint("Are you sure?\n");
  3871. input = getch();
  3872. if (!strncasecmp(&input, "y", 1))
  3873. app_restart();
  3874. else
  3875. clear_logwin();
  3876. } else
  3877. clear_logwin();
  3878. immedok(logwin, false);
  3879. opt_loginput = false;
  3880. }
  3881. static void *input_thread(void __maybe_unused *userdata)
  3882. {
  3883. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3884. RenameThread("input");
  3885. if (!curses_active)
  3886. return NULL;
  3887. while (1) {
  3888. char input;
  3889. input = getch();
  3890. if (!strncasecmp(&input, "q", 1)) {
  3891. kill_work();
  3892. return NULL;
  3893. } else if (!strncasecmp(&input, "d", 1))
  3894. display_options();
  3895. else if (!strncasecmp(&input, "p", 1))
  3896. display_pools();
  3897. else if (!strncasecmp(&input, "s", 1))
  3898. set_options();
  3899. else if (have_opencl && !strncasecmp(&input, "g", 1))
  3900. manage_gpu();
  3901. if (opt_realquiet) {
  3902. disable_curses();
  3903. break;
  3904. }
  3905. }
  3906. return NULL;
  3907. }
  3908. #endif
  3909. static void *api_thread(void *userdata)
  3910. {
  3911. struct thr_info *mythr = userdata;
  3912. pthread_detach(pthread_self());
  3913. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3914. RenameThread("api");
  3915. api(api_thr_id);
  3916. PTH(mythr) = 0L;
  3917. return NULL;
  3918. }
  3919. void thread_reportin(struct thr_info *thr)
  3920. {
  3921. cgtime(&thr->last);
  3922. thr->cgpu->status = LIFE_WELL;
  3923. thr->getwork = false;
  3924. thr->cgpu->device_last_well = time(NULL);
  3925. }
  3926. static inline void thread_reportout(struct thr_info *thr)
  3927. {
  3928. thr->getwork = true;
  3929. }
  3930. static void hashmeter(int thr_id, struct timeval *diff,
  3931. uint64_t hashes_done)
  3932. {
  3933. struct timeval temp_tv_end, total_diff;
  3934. double secs;
  3935. double local_secs;
  3936. double utility;
  3937. static double local_mhashes_done = 0;
  3938. static double rolling = 0;
  3939. double local_mhashes;
  3940. bool showlog = false;
  3941. char displayed_hashes[16], displayed_rolling[16];
  3942. uint64_t dh64, dr64;
  3943. struct thr_info *thr;
  3944. local_mhashes = (double)hashes_done / 1000000.0;
  3945. /* Update the last time this thread reported in */
  3946. if (thr_id >= 0) {
  3947. thr = get_thread(thr_id);
  3948. cgtime(&(thr->last));
  3949. thr->cgpu->device_last_well = time(NULL);
  3950. }
  3951. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3952. /* So we can call hashmeter from a non worker thread */
  3953. if (thr_id >= 0) {
  3954. struct cgpu_info *cgpu = thr->cgpu;
  3955. double thread_rolling = 0.0;
  3956. int i;
  3957. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  3958. thr_id, hashes_done, hashes_done / 1000 / secs);
  3959. /* Rolling average for each thread and each device */
  3960. decay_time(&thr->rolling, local_mhashes / secs);
  3961. for (i = 0; i < cgpu->threads; i++)
  3962. thread_rolling += cgpu->thr[i]->rolling;
  3963. mutex_lock(&hash_lock);
  3964. decay_time(&cgpu->rolling, thread_rolling);
  3965. cgpu->total_mhashes += local_mhashes;
  3966. mutex_unlock(&hash_lock);
  3967. // If needed, output detailed, per-device stats
  3968. if (want_per_device_stats) {
  3969. struct timeval now;
  3970. struct timeval elapsed;
  3971. cgtime(&now);
  3972. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  3973. if (opt_log_interval <= elapsed.tv_sec) {
  3974. struct cgpu_info *cgpu = thr->cgpu;
  3975. char logline[255];
  3976. cgpu->last_message_tv = now;
  3977. get_statline(logline, cgpu);
  3978. if (!curses_active) {
  3979. printf("%s \r", logline);
  3980. fflush(stdout);
  3981. } else
  3982. applog(LOG_INFO, "%s", logline);
  3983. }
  3984. }
  3985. }
  3986. /* Totals are updated by all threads so can race without locking */
  3987. mutex_lock(&hash_lock);
  3988. cgtime(&temp_tv_end);
  3989. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  3990. total_mhashes_done += local_mhashes;
  3991. local_mhashes_done += local_mhashes;
  3992. /* Only update with opt_log_interval */
  3993. if (total_diff.tv_sec < opt_log_interval)
  3994. goto out_unlock;
  3995. showlog = true;
  3996. cgtime(&total_tv_end);
  3997. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3998. decay_time(&rolling, local_mhashes_done / local_secs);
  3999. global_hashrate = roundl(rolling) * 1000000;
  4000. timersub(&total_tv_end, &total_tv_start, &total_diff);
  4001. total_secs = (double)total_diff.tv_sec +
  4002. ((double)total_diff.tv_usec / 1000000.0);
  4003. utility = total_accepted / total_secs * 60;
  4004. dh64 = (double)total_mhashes_done / total_secs * 1000000ull;
  4005. dr64 = (double)rolling * 1000000ull;
  4006. suffix_string(dh64, displayed_hashes, 4);
  4007. suffix_string(dr64, displayed_rolling, 4);
  4008. sprintf(statusline, "%s(%ds):%s (avg):%sh/s | A:%d R:%d HW:%d U:%.1f/m WU:%.1f/m",
  4009. want_per_device_stats ? "ALL " : "",
  4010. opt_log_interval, displayed_rolling, displayed_hashes,
  4011. total_accepted, total_rejected, hw_errors, utility,
  4012. total_diff1 / total_secs * 60);
  4013. local_mhashes_done = 0;
  4014. out_unlock:
  4015. mutex_unlock(&hash_lock);
  4016. if (showlog) {
  4017. if (!curses_active) {
  4018. printf("%s \r", statusline);
  4019. fflush(stdout);
  4020. } else
  4021. applog(LOG_INFO, "%s", statusline);
  4022. }
  4023. }
  4024. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  4025. struct stratum_share *sshare)
  4026. {
  4027. struct work *work = sshare->work;
  4028. char hashshow[65];
  4029. uint32_t *hash32;
  4030. char diffdisp[16];
  4031. int intdiff;
  4032. hash32 = (uint32_t *)(work->hash);
  4033. intdiff = floor(work->work_difficulty);
  4034. suffix_string(work->share_diff, diffdisp, 0);
  4035. sprintf(hashshow, "%08lx Diff %s/%d%s", (unsigned long)htole32(hash32[6]), diffdisp, intdiff,
  4036. work->block? " BLOCK!" : "");
  4037. share_result(val, res_val, err_val, work, hashshow, false, "");
  4038. }
  4039. /* Parses stratum json responses and tries to find the id that the request
  4040. * matched to and treat it accordingly. */
  4041. static bool parse_stratum_response(struct pool *pool, char *s)
  4042. {
  4043. json_t *val = NULL, *err_val, *res_val, *id_val;
  4044. struct stratum_share *sshare;
  4045. json_error_t err;
  4046. bool ret = false;
  4047. int id;
  4048. val = JSON_LOADS(s, &err);
  4049. if (!val) {
  4050. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  4051. goto out;
  4052. }
  4053. res_val = json_object_get(val, "result");
  4054. err_val = json_object_get(val, "error");
  4055. id_val = json_object_get(val, "id");
  4056. if (json_is_null(id_val) || !id_val) {
  4057. char *ss;
  4058. if (err_val)
  4059. ss = json_dumps(err_val, JSON_INDENT(3));
  4060. else
  4061. ss = strdup("(unknown reason)");
  4062. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  4063. free(ss);
  4064. goto out;
  4065. }
  4066. id = json_integer_value(id_val);
  4067. mutex_lock(&sshare_lock);
  4068. HASH_FIND_INT(stratum_shares, &id, sshare);
  4069. if (sshare) {
  4070. HASH_DEL(stratum_shares, sshare);
  4071. pool->sshares--;
  4072. }
  4073. mutex_unlock(&sshare_lock);
  4074. if (!sshare) {
  4075. double pool_diff;
  4076. /* Since the share is untracked, we can only guess at what the
  4077. * work difficulty is based on the current pool diff. */
  4078. cg_rlock(&pool->data_lock);
  4079. pool_diff = pool->swork.diff;
  4080. cg_runlock(&pool->data_lock);
  4081. if (json_is_true(res_val)) {
  4082. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  4083. /* We don't know what device this came from so we can't
  4084. * attribute the work to the relevant cgpu */
  4085. mutex_lock(&stats_lock);
  4086. total_accepted++;
  4087. pool->accepted++;
  4088. total_diff_accepted += pool_diff;
  4089. pool->diff_accepted += pool_diff;
  4090. mutex_unlock(&stats_lock);
  4091. } else {
  4092. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  4093. mutex_lock(&stats_lock);
  4094. total_rejected++;
  4095. pool->rejected++;
  4096. total_diff_rejected += pool_diff;
  4097. pool->diff_rejected += pool_diff;
  4098. mutex_unlock(&stats_lock);
  4099. }
  4100. goto out;
  4101. }
  4102. stratum_share_result(val, res_val, err_val, sshare);
  4103. free_work(sshare->work);
  4104. free(sshare);
  4105. ret = true;
  4106. out:
  4107. if (val)
  4108. json_decref(val);
  4109. return ret;
  4110. }
  4111. void clear_stratum_shares(struct pool *pool)
  4112. {
  4113. struct stratum_share *sshare, *tmpshare;
  4114. double diff_cleared = 0;
  4115. int cleared = 0;
  4116. mutex_lock(&sshare_lock);
  4117. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  4118. if (sshare->work->pool == pool) {
  4119. HASH_DEL(stratum_shares, sshare);
  4120. diff_cleared += sshare->work->work_difficulty;
  4121. free_work(sshare->work);
  4122. pool->sshares--;
  4123. free(sshare);
  4124. cleared++;
  4125. }
  4126. }
  4127. mutex_unlock(&sshare_lock);
  4128. if (cleared) {
  4129. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  4130. pool->stale_shares += cleared;
  4131. total_stale += cleared;
  4132. pool->diff_stale += diff_cleared;
  4133. total_diff_stale += diff_cleared;
  4134. }
  4135. }
  4136. static void clear_pool_work(struct pool *pool)
  4137. {
  4138. struct work *work, *tmp;
  4139. int cleared = 0;
  4140. mutex_lock(stgd_lock);
  4141. HASH_ITER(hh, staged_work, work, tmp) {
  4142. if (work->pool == pool) {
  4143. HASH_DEL(staged_work, work);
  4144. free_work(work);
  4145. cleared++;
  4146. }
  4147. }
  4148. mutex_unlock(stgd_lock);
  4149. }
  4150. static int cp_prio(void)
  4151. {
  4152. int prio;
  4153. cg_rlock(&control_lock);
  4154. prio = currentpool->prio;
  4155. cg_runlock(&control_lock);
  4156. return prio;
  4157. }
  4158. /* We only need to maintain a secondary pool connection when we need the
  4159. * capacity to get work from the backup pools while still on the primary */
  4160. static bool cnx_needed(struct pool *pool)
  4161. {
  4162. struct pool *cp;
  4163. if (pool->enabled != POOL_ENABLED)
  4164. return false;
  4165. /* Balance strategies need all pools online */
  4166. if (pool_strategy == POOL_BALANCE)
  4167. return true;
  4168. if (pool_strategy == POOL_LOADBALANCE)
  4169. return true;
  4170. /* Idle stratum pool needs something to kick it alive again */
  4171. if (pool->has_stratum && pool->idle)
  4172. return true;
  4173. /* Getwork pools without opt_fail_only need backup pools up to be able
  4174. * to leak shares */
  4175. cp = current_pool();
  4176. if (cp == pool)
  4177. return true;
  4178. if (!cp->has_gbt && !cp->has_stratum && (!opt_fail_only || !cp->hdr_path))
  4179. return true;
  4180. /* If we're waiting for a response from shares submitted, keep the
  4181. * connection open. */
  4182. if (pool->sshares)
  4183. return true;
  4184. /* If the pool has only just come to life and is higher priority than
  4185. * the current pool keep the connection open so we can fail back to
  4186. * it. */
  4187. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  4188. return true;
  4189. if (pool_unworkable(cp))
  4190. return true;
  4191. return false;
  4192. }
  4193. static void wait_lpcurrent(struct pool *pool);
  4194. static void pool_resus(struct pool *pool);
  4195. static void gen_stratum_work(struct pool *pool, struct work *work);
  4196. static void stratum_resumed(struct pool *pool)
  4197. {
  4198. if (!pool->stratum_notify)
  4199. return;
  4200. if (pool_tclear(pool, &pool->idle)) {
  4201. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  4202. pool_resus(pool);
  4203. }
  4204. }
  4205. static bool supports_resume(struct pool *pool)
  4206. {
  4207. bool ret;
  4208. cg_rlock(&pool->data_lock);
  4209. ret = (pool->sessionid != NULL);
  4210. cg_runlock(&pool->data_lock);
  4211. return ret;
  4212. }
  4213. /* One stratum receive thread per pool that has stratum waits on the socket
  4214. * checking for new messages and for the integrity of the socket connection. We
  4215. * reset the connection based on the integrity of the receive side only as the
  4216. * send side will eventually expire data it fails to send. */
  4217. static void *stratum_rthread(void *userdata)
  4218. {
  4219. struct pool *pool = (struct pool *)userdata;
  4220. char threadname[16];
  4221. pthread_detach(pthread_self());
  4222. snprintf(threadname, 16, "StratumR/%d", pool->pool_no);
  4223. RenameThread(threadname);
  4224. while (42) {
  4225. struct timeval timeout;
  4226. int sel_ret;
  4227. fd_set rd;
  4228. char *s;
  4229. if (unlikely(pool->removed))
  4230. break;
  4231. /* Check to see whether we need to maintain this connection
  4232. * indefinitely or just bring it up when we switch to this
  4233. * pool */
  4234. if (!sock_full(pool) && !cnx_needed(pool)) {
  4235. suspend_stratum(pool);
  4236. clear_stratum_shares(pool);
  4237. clear_pool_work(pool);
  4238. wait_lpcurrent(pool);
  4239. if (!restart_stratum(pool)) {
  4240. pool_died(pool);
  4241. while (!restart_stratum(pool)) {
  4242. if (pool->removed)
  4243. goto out;
  4244. nmsleep(30000);
  4245. }
  4246. }
  4247. }
  4248. FD_ZERO(&rd);
  4249. FD_SET(pool->sock, &rd);
  4250. timeout.tv_sec = 90;
  4251. timeout.tv_usec = 0;
  4252. /* The protocol specifies that notify messages should be sent
  4253. * every minute so if we fail to receive any for 90 seconds we
  4254. * assume the connection has been dropped and treat this pool
  4255. * as dead */
  4256. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  4257. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  4258. s = NULL;
  4259. } else
  4260. s = recv_line(pool);
  4261. if (!s) {
  4262. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  4263. pool->getfail_occasions++;
  4264. total_go++;
  4265. /* If the socket to our stratum pool disconnects, all
  4266. * tracked submitted shares are lost and we will leak
  4267. * the memory if we don't discard their records. */
  4268. if (!supports_resume(pool) || opt_lowmem)
  4269. clear_stratum_shares(pool);
  4270. clear_pool_work(pool);
  4271. if (pool == current_pool())
  4272. restart_threads();
  4273. if (restart_stratum(pool))
  4274. continue;
  4275. pool_died(pool);
  4276. while (!restart_stratum(pool)) {
  4277. if (pool->removed)
  4278. goto out;
  4279. nmsleep(30000);
  4280. }
  4281. stratum_resumed(pool);
  4282. continue;
  4283. }
  4284. /* Check this pool hasn't died while being a backup pool and
  4285. * has not had its idle flag cleared */
  4286. stratum_resumed(pool);
  4287. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  4288. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  4289. free(s);
  4290. if (pool->swork.clean) {
  4291. struct work *work = make_work();
  4292. /* Generate a single work item to update the current
  4293. * block database */
  4294. pool->swork.clean = false;
  4295. gen_stratum_work(pool, work);
  4296. if (test_work_current(work)) {
  4297. /* Only accept a work restart if this stratum
  4298. * connection is from the current pool */
  4299. if (pool == current_pool()) {
  4300. restart_threads();
  4301. applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
  4302. }
  4303. } else
  4304. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  4305. free_work(work);
  4306. }
  4307. }
  4308. out:
  4309. return NULL;
  4310. }
  4311. /* Each pool has one stratum send thread for sending shares to avoid many
  4312. * threads being created for submission since all sends need to be serialised
  4313. * anyway. */
  4314. static void *stratum_sthread(void *userdata)
  4315. {
  4316. struct pool *pool = (struct pool *)userdata;
  4317. char threadname[16];
  4318. pthread_detach(pthread_self());
  4319. snprintf(threadname, 16, "StratumS/%d", pool->pool_no);
  4320. RenameThread(threadname);
  4321. pool->stratum_q = tq_new();
  4322. if (!pool->stratum_q)
  4323. quit(1, "Failed to create stratum_q in stratum_sthread");
  4324. while (42) {
  4325. struct stratum_share *sshare;
  4326. uint32_t *hash32, nonce;
  4327. struct work *work;
  4328. bool submitted;
  4329. char *noncehex;
  4330. char s[1024];
  4331. if (unlikely(pool->removed))
  4332. break;
  4333. work = tq_pop(pool->stratum_q, NULL);
  4334. if (unlikely(!work))
  4335. quit(1, "Stratum q returned empty work");
  4336. sshare = calloc(sizeof(struct stratum_share), 1);
  4337. hash32 = (uint32_t *)work->hash;
  4338. submitted = false;
  4339. sshare->sshare_time = time(NULL);
  4340. /* This work item is freed in parse_stratum_response */
  4341. sshare->work = work;
  4342. nonce = *((uint32_t *)(work->data + 76));
  4343. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  4344. memset(s, 0, 1024);
  4345. mutex_lock(&sshare_lock);
  4346. /* Give the stratum share a unique id */
  4347. sshare->id = swork_id++;
  4348. mutex_unlock(&sshare_lock);
  4349. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  4350. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  4351. free(noncehex);
  4352. applog(LOG_INFO, "Submitting share %08lx to pool %d",
  4353. (long unsigned int)htole32(hash32[6]), pool->pool_no);
  4354. /* Try resubmitting for up to 2 minutes if we fail to submit
  4355. * once and the stratum pool nonce1 still matches suggesting
  4356. * we may be able to resume. */
  4357. while (time(NULL) < sshare->sshare_time + 120) {
  4358. bool sessionid_match;
  4359. if (likely(stratum_send(pool, s, strlen(s)))) {
  4360. if (pool_tclear(pool, &pool->submit_fail))
  4361. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4362. mutex_lock(&sshare_lock);
  4363. HASH_ADD_INT(stratum_shares, id, sshare);
  4364. pool->sshares++;
  4365. mutex_unlock(&sshare_lock);
  4366. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  4367. submitted = true;
  4368. break;
  4369. }
  4370. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  4371. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  4372. total_ro++;
  4373. pool->remotefail_occasions++;
  4374. }
  4375. if (opt_lowmem) {
  4376. applog(LOG_DEBUG, "Lowmem option prevents resubmitting stratum share");
  4377. break;
  4378. }
  4379. cg_rlock(&pool->data_lock);
  4380. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  4381. cg_runlock(&pool->data_lock);
  4382. if (!sessionid_match) {
  4383. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4384. break;
  4385. }
  4386. /* Retry every 5 seconds */
  4387. sleep(5);
  4388. }
  4389. if (unlikely(!submitted)) {
  4390. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  4391. free_work(work);
  4392. free(sshare);
  4393. pool->stale_shares++;
  4394. total_stale++;
  4395. }
  4396. }
  4397. /* Freeze the work queue but don't free up its memory in case there is
  4398. * work still trying to be submitted to the removed pool. */
  4399. tq_freeze(pool->stratum_q);
  4400. return NULL;
  4401. }
  4402. static void init_stratum_threads(struct pool *pool)
  4403. {
  4404. if (unlikely(pthread_create(&pool->stratum_sthread, NULL, stratum_sthread, (void *)pool)))
  4405. quit(1, "Failed to create stratum sthread");
  4406. if (unlikely(pthread_create(&pool->stratum_rthread, NULL, stratum_rthread, (void *)pool)))
  4407. quit(1, "Failed to create stratum rthread");
  4408. }
  4409. static void *longpoll_thread(void *userdata);
  4410. static bool stratum_works(struct pool *pool)
  4411. {
  4412. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  4413. if (!extract_sockaddr(pool, pool->stratum_url))
  4414. return false;
  4415. if (!initiate_stratum(pool))
  4416. return false;
  4417. return true;
  4418. }
  4419. static bool pool_active(struct pool *pool, bool pinging)
  4420. {
  4421. struct timeval tv_getwork, tv_getwork_reply;
  4422. bool ret = false;
  4423. json_t *val;
  4424. CURL *curl;
  4425. int rolltime;
  4426. if (pool->has_gbt)
  4427. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  4428. else
  4429. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  4430. /* This is the central point we activate stratum when we can */
  4431. retry_stratum:
  4432. if (pool->has_stratum) {
  4433. /* We create the stratum thread for each pool just after
  4434. * successful authorisation. Once the init flag has been set
  4435. * we never unset it and the stratum thread is responsible for
  4436. * setting/unsetting the active flag */
  4437. bool init = pool_tset(pool, &pool->stratum_init);
  4438. if (!init) {
  4439. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  4440. if (ret)
  4441. init_stratum_threads(pool);
  4442. else
  4443. pool_tclear(pool, &pool->stratum_init);
  4444. return ret;
  4445. }
  4446. return pool->stratum_active;
  4447. }
  4448. curl = curl_easy_init();
  4449. if (unlikely(!curl)) {
  4450. applog(LOG_ERR, "CURL initialisation failed");
  4451. return false;
  4452. }
  4453. /* Probe for GBT support on first pass */
  4454. if (!pool->probed && !opt_fix_protocol) {
  4455. applog(LOG_DEBUG, "Probing for GBT support");
  4456. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4457. gbt_req, true, false, &rolltime, pool, false);
  4458. if (val) {
  4459. bool append = false, submit = false;
  4460. json_t *res_val, *mutables;
  4461. int i, mutsize = 0;
  4462. res_val = json_object_get(val, "result");
  4463. if (res_val) {
  4464. mutables = json_object_get(res_val, "mutable");
  4465. mutsize = json_array_size(mutables);
  4466. }
  4467. for (i = 0; i < mutsize; i++) {
  4468. json_t *arrval = json_array_get(mutables, i);
  4469. if (json_is_string(arrval)) {
  4470. const char *mutable = json_string_value(arrval);
  4471. if (!strncasecmp(mutable, "coinbase/append", 15))
  4472. append = true;
  4473. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  4474. submit = true;
  4475. }
  4476. }
  4477. json_decref(val);
  4478. /* Only use GBT if it supports coinbase append and
  4479. * submit coinbase */
  4480. if (append && submit) {
  4481. pool->has_gbt = true;
  4482. pool->rpc_req = gbt_req;
  4483. }
  4484. }
  4485. /* Reset this so we can probe fully just after this. It will be
  4486. * set to true that time.*/
  4487. pool->probed = false;
  4488. if (pool->has_gbt)
  4489. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  4490. else
  4491. applog(LOG_DEBUG, "No GBT coinbase + append support found, using getwork protocol");
  4492. }
  4493. cgtime(&tv_getwork);
  4494. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4495. pool->rpc_req, true, false, &rolltime, pool, false);
  4496. cgtime(&tv_getwork_reply);
  4497. /* Detect if a http getwork pool has an X-Stratum header at startup,
  4498. * and if so, switch to that in preference to getwork if it works */
  4499. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  4500. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  4501. if (!pool->rpc_url)
  4502. pool->rpc_url = strdup(pool->stratum_url);
  4503. pool->has_stratum = true;
  4504. curl_easy_cleanup(curl);
  4505. goto retry_stratum;
  4506. }
  4507. if (val) {
  4508. struct work *work = make_work();
  4509. bool rc;
  4510. rc = work_decode(pool, work, val);
  4511. if (rc) {
  4512. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4513. pool->pool_no, pool->rpc_url);
  4514. work->pool = pool;
  4515. work->rolltime = rolltime;
  4516. copy_time(&work->tv_getwork, &tv_getwork);
  4517. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  4518. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  4519. calc_diff(work, 0);
  4520. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4521. tq_push(control_thr[stage_thr_id].q, work);
  4522. total_getworks++;
  4523. pool->getwork_requested++;
  4524. ret = true;
  4525. cgtime(&pool->tv_idle);
  4526. } else {
  4527. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4528. pool->pool_no, pool->rpc_url);
  4529. free_work(work);
  4530. }
  4531. json_decref(val);
  4532. if (pool->lp_url)
  4533. goto out;
  4534. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4535. if (pool->hdr_path) {
  4536. char *copy_start, *hdr_path;
  4537. bool need_slash = false;
  4538. hdr_path = pool->hdr_path;
  4539. if (strstr(hdr_path, "://")) {
  4540. pool->lp_url = hdr_path;
  4541. hdr_path = NULL;
  4542. } else {
  4543. /* absolute path, on current server */
  4544. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  4545. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  4546. need_slash = true;
  4547. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  4548. if (!pool->lp_url) {
  4549. applog(LOG_ERR, "Malloc failure in pool_active");
  4550. return false;
  4551. }
  4552. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  4553. }
  4554. } else
  4555. pool->lp_url = NULL;
  4556. if (!pool->lp_started) {
  4557. pool->lp_started = true;
  4558. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4559. quit(1, "Failed to create pool longpoll thread");
  4560. }
  4561. } else {
  4562. /* If we failed to parse a getwork, this could be a stratum
  4563. * url without the prefix stratum+tcp:// so let's check it */
  4564. if (initiate_stratum(pool)) {
  4565. pool->has_stratum = true;
  4566. goto retry_stratum;
  4567. }
  4568. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4569. pool->pool_no, pool->rpc_url);
  4570. if (!pinging)
  4571. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4572. }
  4573. out:
  4574. curl_easy_cleanup(curl);
  4575. return ret;
  4576. }
  4577. static void pool_resus(struct pool *pool)
  4578. {
  4579. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio()) {
  4580. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4581. switch_pools(NULL);
  4582. } else
  4583. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4584. }
  4585. static struct work *hash_pop(void)
  4586. {
  4587. struct work *work = NULL, *tmp;
  4588. int hc;
  4589. mutex_lock(stgd_lock);
  4590. while (!getq->frozen && !HASH_COUNT(staged_work))
  4591. pthread_cond_wait(&getq->cond, stgd_lock);
  4592. hc = HASH_COUNT(staged_work);
  4593. /* Find clone work if possible, to allow masters to be reused */
  4594. if (hc > staged_rollable) {
  4595. HASH_ITER(hh, staged_work, work, tmp) {
  4596. if (!work_rollable(work))
  4597. break;
  4598. }
  4599. } else
  4600. work = staged_work;
  4601. HASH_DEL(staged_work, work);
  4602. if (work_rollable(work))
  4603. staged_rollable--;
  4604. /* Signal the getwork scheduler to look for more work */
  4605. pthread_cond_signal(&gws_cond);
  4606. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  4607. pthread_cond_signal(&getq->cond);
  4608. mutex_unlock(stgd_lock);
  4609. return work;
  4610. }
  4611. /* Clones work by rolling it if possible, and returning a clone instead of the
  4612. * original work item which gets staged again to possibly be rolled again in
  4613. * the future */
  4614. static struct work *clone_work(struct work *work)
  4615. {
  4616. int mrs = mining_threads + opt_queue - total_staged();
  4617. struct work *work_clone;
  4618. bool cloned;
  4619. if (mrs < 1)
  4620. return work;
  4621. cloned = false;
  4622. work_clone = make_clone(work);
  4623. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4624. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4625. stage_work(work_clone);
  4626. roll_work(work);
  4627. work_clone = make_clone(work);
  4628. /* Roll it again to prevent duplicates should this be used
  4629. * directly later on */
  4630. roll_work(work);
  4631. cloned = true;
  4632. }
  4633. if (cloned) {
  4634. stage_work(work);
  4635. return work_clone;
  4636. }
  4637. free_work(work_clone);
  4638. return work;
  4639. }
  4640. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  4641. {
  4642. unsigned char hash1[32];
  4643. sha2(data, len, hash1);
  4644. sha2(hash1, 32, hash);
  4645. }
  4646. /* Diff 1 is a 256 bit unsigned integer of
  4647. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  4648. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  4649. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  4650. void set_target(unsigned char *dest_target, double diff)
  4651. {
  4652. unsigned char target[32];
  4653. uint64_t *data64, h64;
  4654. double d64;
  4655. d64 = diffone;
  4656. d64 /= diff;
  4657. h64 = d64;
  4658. memset(target, 0, 32);
  4659. if (h64) {
  4660. unsigned char rtarget[32];
  4661. memset(rtarget, 0, 32);
  4662. if (opt_scrypt)
  4663. data64 = (uint64_t *)(rtarget + 2);
  4664. else
  4665. data64 = (uint64_t *)(rtarget + 4);
  4666. *data64 = htobe64(h64);
  4667. swab256(target, rtarget);
  4668. } else {
  4669. /* Support for the classic all FFs just-below-1 diff */
  4670. if (opt_scrypt)
  4671. memset(target, 0xff, 30);
  4672. else
  4673. memset(target, 0xff, 28);
  4674. }
  4675. if (opt_debug) {
  4676. char *htarget = bin2hex(target, 32);
  4677. applog(LOG_DEBUG, "Generated target %s", htarget);
  4678. free(htarget);
  4679. }
  4680. memcpy(dest_target, target, 32);
  4681. }
  4682. /* Generates stratum based work based on the most recent notify information
  4683. * from the pool. This will keep generating work while a pool is down so we use
  4684. * other means to detect when the pool has died in stratum_thread */
  4685. static void gen_stratum_work(struct pool *pool, struct work *work)
  4686. {
  4687. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  4688. char *header, *merkle_hash;
  4689. uint32_t *data32, *swap32;
  4690. size_t alloc_len;
  4691. int i;
  4692. /* Use intermediate lock to update the one pool variable */
  4693. cg_ilock(&pool->data_lock);
  4694. /* Generate coinbase */
  4695. work->nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  4696. pool->nonce2++;
  4697. /* Downgrade to a read lock to read off the pool variables */
  4698. cg_dlock(&pool->data_lock);
  4699. alloc_len = pool->swork.cb_len;
  4700. align_len(&alloc_len);
  4701. coinbase = calloc(alloc_len, 1);
  4702. if (unlikely(!coinbase))
  4703. quit(1, "Failed to calloc coinbase in gen_stratum_work");
  4704. hex2bin(coinbase, pool->swork.coinbase1, pool->swork.cb1_len);
  4705. hex2bin(coinbase + pool->swork.cb1_len, pool->nonce1, pool->n1_len);
  4706. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len, work->nonce2, pool->n2size);
  4707. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len + pool->n2size, pool->swork.coinbase2, pool->swork.cb2_len);
  4708. /* Generate merkle root */
  4709. gen_hash(coinbase, merkle_root, pool->swork.cb_len);
  4710. free(coinbase);
  4711. memcpy(merkle_sha, merkle_root, 32);
  4712. for (i = 0; i < pool->swork.merkles; i++) {
  4713. unsigned char merkle_bin[32];
  4714. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  4715. memcpy(merkle_sha + 32, merkle_bin, 32);
  4716. gen_hash(merkle_sha, merkle_root, 64);
  4717. memcpy(merkle_sha, merkle_root, 32);
  4718. }
  4719. data32 = (uint32_t *)merkle_sha;
  4720. swap32 = (uint32_t *)merkle_root;
  4721. flip32(swap32, data32);
  4722. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  4723. header = calloc(pool->swork.header_len, 1);
  4724. if (unlikely(!header))
  4725. quit(1, "Failed to calloc header in gen_stratum_work");
  4726. sprintf(header, "%s%s%s%s%s%s%s",
  4727. pool->swork.bbversion,
  4728. pool->swork.prev_hash,
  4729. merkle_hash,
  4730. pool->swork.ntime,
  4731. pool->swork.nbit,
  4732. "00000000", /* nonce */
  4733. workpadding);
  4734. /* Store the stratum work diff to check it still matches the pool's
  4735. * stratum diff when submitting shares */
  4736. work->sdiff = pool->swork.diff;
  4737. /* Copy parameters required for share submission */
  4738. work->job_id = strdup(pool->swork.job_id);
  4739. work->nonce1 = strdup(pool->nonce1);
  4740. work->ntime = strdup(pool->swork.ntime);
  4741. cg_runlock(&pool->data_lock);
  4742. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  4743. applog(LOG_DEBUG, "Generated stratum header %s", header);
  4744. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  4745. free(merkle_hash);
  4746. /* Convert hex data to binary data for work */
  4747. if (unlikely(!hex2bin(work->data, header, 128)))
  4748. quit(1, "Failed to convert header to data in gen_stratum_work");
  4749. free(header);
  4750. calc_midstate(work);
  4751. set_target(work->target, work->sdiff);
  4752. local_work++;
  4753. work->pool = pool;
  4754. work->stratum = true;
  4755. work->blk.nonce = 0;
  4756. work->id = total_work++;
  4757. work->longpoll = false;
  4758. work->getwork_mode = GETWORK_MODE_STRATUM;
  4759. work->work_block = work_block;
  4760. calc_diff(work, work->sdiff);
  4761. cgtime(&work->tv_staged);
  4762. }
  4763. static struct work *get_work(struct thr_info *thr, const int thr_id)
  4764. {
  4765. struct work *work = NULL;
  4766. /* Tell the watchdog thread this thread is waiting on getwork and
  4767. * should not be restarted */
  4768. thread_reportout(thr);
  4769. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4770. while (!work) {
  4771. work = hash_pop();
  4772. if (stale_work(work, false)) {
  4773. discard_work(work);
  4774. work = NULL;
  4775. wake_gws();
  4776. }
  4777. }
  4778. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  4779. work->thr_id = thr_id;
  4780. thread_reportin(thr);
  4781. work->mined = true;
  4782. return work;
  4783. }
  4784. static void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  4785. {
  4786. struct work *work = copy_work(work_in);
  4787. struct pool *pool = work->pool;
  4788. pthread_t submit_thread;
  4789. if (tv_work_found)
  4790. copy_time(&work->tv_work_found, tv_work_found);
  4791. if (stale_work(work, true)) {
  4792. if (opt_submit_stale)
  4793. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4794. else if (pool->submit_old)
  4795. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4796. else {
  4797. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4798. sharelog("discard", work);
  4799. mutex_lock(&stats_lock);
  4800. total_stale++;
  4801. pool->stale_shares++;
  4802. total_diff_stale += work->work_difficulty;
  4803. pool->diff_stale += work->work_difficulty;
  4804. mutex_unlock(&stats_lock);
  4805. free_work(work);
  4806. return;
  4807. }
  4808. work->stale = true;
  4809. }
  4810. if (work->stratum) {
  4811. applog(LOG_DEBUG, "Pushing pool %d work to stratum queue", pool->pool_no);
  4812. if (unlikely(!tq_push(pool->stratum_q, work))) {
  4813. applog(LOG_DEBUG, "Discarding work from removed pool");
  4814. free_work(work);
  4815. }
  4816. } else {
  4817. applog(LOG_DEBUG, "Pushing submit work to work thread");
  4818. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  4819. quit(1, "Failed to create submit_work_thread");
  4820. }
  4821. }
  4822. void inc_hw_errors(struct thr_info *thr)
  4823. {
  4824. mutex_lock(&stats_lock);
  4825. hw_errors++;
  4826. thr->cgpu->hw_errors++;
  4827. mutex_unlock(&stats_lock);
  4828. thr->cgpu->drv->hw_error(thr);
  4829. }
  4830. /* Returns true if nonce for work was a valid share */
  4831. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4832. {
  4833. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  4834. struct timeval tv_work_found;
  4835. unsigned char hash2[32];
  4836. uint32_t *hash2_32 = (uint32_t *)hash2;
  4837. uint32_t diff1targ;
  4838. bool ret = true;
  4839. thread_reportout(thr);
  4840. cgtime(&tv_work_found);
  4841. *work_nonce = htole32(nonce);
  4842. mutex_lock(&stats_lock);
  4843. total_diff1 += work->device_diff;
  4844. thr->cgpu->diff1 += work->device_diff;
  4845. work->pool->diff1 += work->device_diff;
  4846. mutex_unlock(&stats_lock);
  4847. /* Do one last check before attempting to submit the work */
  4848. rebuild_hash(work);
  4849. flip32(hash2_32, work->hash);
  4850. diff1targ = opt_scrypt ? 0x0000ffffUL : 0;
  4851. if (be32toh(hash2_32[7]) > diff1targ) {
  4852. applog(LOG_WARNING, "%s%d: invalid nonce - HW error",
  4853. thr->cgpu->drv->name, thr->cgpu->device_id);
  4854. inc_hw_errors(thr);
  4855. ret = false;
  4856. goto out;
  4857. }
  4858. mutex_lock(&stats_lock);
  4859. thr->cgpu->last_device_valid_work = time(NULL);
  4860. mutex_unlock(&stats_lock);
  4861. if (!fulltest(hash2, work->target)) {
  4862. applog(LOG_INFO, "Share below target");
  4863. goto out;
  4864. }
  4865. submit_work_async(work, &tv_work_found);
  4866. out:
  4867. thread_reportin(thr);
  4868. return ret;
  4869. }
  4870. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  4871. {
  4872. if (wdiff->tv_sec > opt_scantime ||
  4873. work->blk.nonce >= MAXTHREADS - hashes ||
  4874. hashes >= 0xfffffffe ||
  4875. stale_work(work, false))
  4876. return true;
  4877. return false;
  4878. }
  4879. static void mt_disable(struct thr_info *mythr, const int thr_id,
  4880. struct device_drv *drv)
  4881. {
  4882. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4883. mythr->rolling = mythr->cgpu->rolling = 0;
  4884. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  4885. thread_reportout(mythr);
  4886. do {
  4887. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4888. } while (mythr->pause);
  4889. thread_reportin(mythr);
  4890. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4891. drv->thread_enable(mythr);
  4892. }
  4893. /* The main hashing loop for devices that are slow enough to work on one work
  4894. * item at a time, without a queue, aborting work before the entire nonce
  4895. * range has been hashed if needed. */
  4896. static void hash_sole_work(struct thr_info *mythr)
  4897. {
  4898. const int thr_id = mythr->id;
  4899. struct cgpu_info *cgpu = mythr->cgpu;
  4900. struct device_drv *drv = cgpu->drv;
  4901. struct timeval getwork_start, tv_start, *tv_end, tv_workstart, tv_lastupdate;
  4902. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  4903. struct cgminer_stats *pool_stats;
  4904. /* Try to cycle approximately 5 times before each log update */
  4905. const long cycle = opt_log_interval / 5 ? : 1;
  4906. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  4907. struct timeval diff, sdiff, wdiff = {0, 0};
  4908. uint32_t max_nonce = drv->can_limit_work(mythr);
  4909. int64_t hashes_done = 0;
  4910. tv_end = &getwork_start;
  4911. cgtime(&getwork_start);
  4912. sdiff.tv_sec = sdiff.tv_usec = 0;
  4913. cgtime(&tv_lastupdate);
  4914. while (likely(!cgpu->shutdown)) {
  4915. struct work *work = get_work(mythr, thr_id);
  4916. int64_t hashes;
  4917. mythr->work_restart = false;
  4918. cgpu->new_work = true;
  4919. cgtime(&tv_workstart);
  4920. work->blk.nonce = 0;
  4921. cgpu->max_hashes = 0;
  4922. if (!drv->prepare_work(mythr, work)) {
  4923. applog(LOG_ERR, "work prepare failed, exiting "
  4924. "mining thread %d", thr_id);
  4925. break;
  4926. }
  4927. work->device_diff = MIN(drv->working_diff, work->work_difficulty);
  4928. #ifdef USE_SCRYPT
  4929. /* Dynamically adjust the working diff even if the target
  4930. * diff is very high to ensure we can still validate scrypt is
  4931. * returning shares. */
  4932. if (opt_scrypt) {
  4933. double wu;
  4934. wu = total_diff1 / total_secs * 60;
  4935. if (wu > 30 && drv->working_diff < drv->max_diff &&
  4936. drv->working_diff < work->work_difficulty) {
  4937. drv->working_diff++;
  4938. applog(LOG_DEBUG, "Driver %s working diff changed to %.0f",
  4939. drv->dname, drv->working_diff);
  4940. work->device_diff = MIN(drv->working_diff, work->work_difficulty);
  4941. } else if (drv->working_diff > work->work_difficulty)
  4942. drv->working_diff = work->work_difficulty;
  4943. set_target(work->device_target, work->device_diff);
  4944. }
  4945. #endif
  4946. do {
  4947. cgtime(&tv_start);
  4948. subtime(&tv_start, &getwork_start);
  4949. addtime(&getwork_start, &dev_stats->getwork_wait);
  4950. if (time_more(&getwork_start, &dev_stats->getwork_wait_max))
  4951. copy_time(&dev_stats->getwork_wait_max, &getwork_start);
  4952. if (time_less(&getwork_start, &dev_stats->getwork_wait_min))
  4953. copy_time(&dev_stats->getwork_wait_min, &getwork_start);
  4954. dev_stats->getwork_calls++;
  4955. pool_stats = &(work->pool->cgminer_stats);
  4956. addtime(&getwork_start, &pool_stats->getwork_wait);
  4957. if (time_more(&getwork_start, &pool_stats->getwork_wait_max))
  4958. copy_time(&pool_stats->getwork_wait_max, &getwork_start);
  4959. if (time_less(&getwork_start, &pool_stats->getwork_wait_min))
  4960. copy_time(&pool_stats->getwork_wait_min, &getwork_start);
  4961. pool_stats->getwork_calls++;
  4962. cgtime(&(work->tv_work_start));
  4963. thread_reportin(mythr);
  4964. /* Only allow the mining thread to be cancelled when
  4965. * it is not in the driver code. */
  4966. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  4967. hashes = drv->scanhash(mythr, work, work->blk.nonce + max_nonce);
  4968. thread_reportin(mythr);
  4969. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  4970. pthread_testcancel();
  4971. /* tv_end is == &getwork_start */
  4972. cgtime(&getwork_start);
  4973. if (unlikely(hashes == -1)) {
  4974. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  4975. cgpu->deven = DEV_DISABLED;
  4976. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  4977. mt_disable(mythr, thr_id, drv);
  4978. }
  4979. hashes_done += hashes;
  4980. if (hashes > cgpu->max_hashes)
  4981. cgpu->max_hashes = hashes;
  4982. timersub(tv_end, &tv_start, &diff);
  4983. sdiff.tv_sec += diff.tv_sec;
  4984. sdiff.tv_usec += diff.tv_usec;
  4985. if (sdiff.tv_usec > 1000000) {
  4986. ++sdiff.tv_sec;
  4987. sdiff.tv_usec -= 1000000;
  4988. }
  4989. timersub(tv_end, &tv_workstart, &wdiff);
  4990. if (unlikely((long)sdiff.tv_sec < cycle)) {
  4991. int mult;
  4992. if (likely(max_nonce == 0xffffffff))
  4993. continue;
  4994. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  4995. mult *= cycle;
  4996. if (max_nonce > (0xffffffff * 0x400) / mult)
  4997. max_nonce = 0xffffffff;
  4998. else
  4999. max_nonce = (max_nonce * mult) / 0x400;
  5000. } else if (unlikely(sdiff.tv_sec > cycle))
  5001. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  5002. else if (unlikely(sdiff.tv_usec > 100000))
  5003. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  5004. timersub(tv_end, &tv_lastupdate, &diff);
  5005. /* Update the hashmeter at most 5 times per second */
  5006. if (diff.tv_sec > 0 || diff.tv_usec > 200) {
  5007. hashmeter(thr_id, &diff, hashes_done);
  5008. hashes_done = 0;
  5009. copy_time(&tv_lastupdate, tv_end);
  5010. }
  5011. if (unlikely(mythr->work_restart)) {
  5012. /* Apart from device_thread 0, we stagger the
  5013. * starting of every next thread to try and get
  5014. * all devices busy before worrying about
  5015. * getting work for their extra threads */
  5016. if (!primary) {
  5017. struct timespec rgtp;
  5018. rgtp.tv_sec = 0;
  5019. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  5020. nanosleep(&rgtp, NULL);
  5021. }
  5022. break;
  5023. }
  5024. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  5025. mt_disable(mythr, thr_id, drv);
  5026. sdiff.tv_sec = sdiff.tv_usec = 0;
  5027. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  5028. free_work(work);
  5029. }
  5030. cgpu->deven = DEV_DISABLED;
  5031. }
  5032. /* Create a hashtable of work items for devices with a queue. The device
  5033. * driver must have a custom queue_full function or it will default to true
  5034. * and put only one work item in the queue. Work items should not be removed
  5035. * from this hashtable until they are no longer in use anywhere. Once a work
  5036. * item is physically queued on the device itself, the work->queued flag
  5037. * should be set under cgpu->qlock write lock to prevent it being dereferenced
  5038. * while still in use. */
  5039. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  5040. {
  5041. thread_reportout(mythr);
  5042. do {
  5043. bool need_work;
  5044. rd_lock(&cgpu->qlock);
  5045. need_work = (HASH_COUNT(cgpu->queued_work) == cgpu->queued_count);
  5046. rd_unlock(&cgpu->qlock);
  5047. if (need_work) {
  5048. struct work *work = get_work(mythr, thr_id);
  5049. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  5050. wr_lock(&cgpu->qlock);
  5051. HASH_ADD_INT(cgpu->queued_work, id, work);
  5052. wr_unlock(&cgpu->qlock);
  5053. }
  5054. /* The queue_full function should be used by the driver to
  5055. * actually place work items on the physical device if it
  5056. * does have a queue. */
  5057. } while (!drv->queue_full(cgpu));
  5058. }
  5059. /* This function is for retrieving one work item from the queued hashtable of
  5060. * available work items that are not yet physically on a device (which is
  5061. * flagged with the work->queued bool). Code using this function must be able
  5062. * to handle NULL as a return which implies there is no work available. */
  5063. struct work *get_queued(struct cgpu_info *cgpu)
  5064. {
  5065. struct work *work, *tmp, *ret = NULL;
  5066. wr_lock(&cgpu->qlock);
  5067. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  5068. if (!work->queued) {
  5069. work->queued = true;
  5070. cgpu->queued_count++;
  5071. ret = work;
  5072. break;
  5073. }
  5074. }
  5075. wr_unlock(&cgpu->qlock);
  5076. return ret;
  5077. }
  5078. /* This function is for finding an already queued work item in the
  5079. * given que hashtable. Code using this function must be able
  5080. * to handle NULL as a return which implies there is no matching work.
  5081. * The calling function must lock access to the que if it is required.
  5082. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  5083. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  5084. {
  5085. struct work *work, *tmp, *ret = NULL;
  5086. HASH_ITER(hh, que, work, tmp) {
  5087. if (work->queued &&
  5088. memcmp(work->midstate, midstate, midstatelen) == 0 &&
  5089. memcmp(work->data + offset, data, datalen) == 0) {
  5090. ret = work;
  5091. break;
  5092. }
  5093. }
  5094. return ret;
  5095. }
  5096. /* This function is for finding an already queued work item in the
  5097. * device's queued_work hashtable. Code using this function must be able
  5098. * to handle NULL as a return which implies there is no matching work.
  5099. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  5100. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  5101. {
  5102. struct work *ret;
  5103. rd_lock(&cgpu->qlock);
  5104. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  5105. rd_unlock(&cgpu->qlock);
  5106. return ret;
  5107. }
  5108. /* This function should be used by queued device drivers when they're sure
  5109. * the work struct is no longer in use. */
  5110. void work_completed(struct cgpu_info *cgpu, struct work *work)
  5111. {
  5112. wr_lock(&cgpu->qlock);
  5113. if (work->queued)
  5114. cgpu->queued_count--;
  5115. HASH_DEL(cgpu->queued_work, work);
  5116. wr_unlock(&cgpu->qlock);
  5117. free_work(work);
  5118. }
  5119. static void flush_queue(struct cgpu_info *cgpu)
  5120. {
  5121. struct work *work, *tmp;
  5122. int discarded = 0;
  5123. wr_lock(&cgpu->qlock);
  5124. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  5125. /* Can only discard the work items if they're not physically
  5126. * queued on the device. */
  5127. if (!work->queued) {
  5128. HASH_DEL(cgpu->queued_work, work);
  5129. discard_work(work);
  5130. discarded++;
  5131. }
  5132. }
  5133. wr_unlock(&cgpu->qlock);
  5134. if (discarded)
  5135. applog(LOG_DEBUG, "Discarded %d queued work items", discarded);
  5136. }
  5137. /* This version of hash work is for devices that are fast enough to always
  5138. * perform a full nonce range and need a queue to maintain the device busy.
  5139. * Work creation and destruction is not done from within this function
  5140. * directly. */
  5141. void hash_queued_work(struct thr_info *mythr)
  5142. {
  5143. struct timeval tv_start = {0, 0}, tv_end;
  5144. struct cgpu_info *cgpu = mythr->cgpu;
  5145. struct device_drv *drv = cgpu->drv;
  5146. const int thr_id = mythr->id;
  5147. int64_t hashes_done = 0;
  5148. while (likely(!cgpu->shutdown)) {
  5149. struct timeval diff;
  5150. int64_t hashes;
  5151. mythr->work_restart = false;
  5152. fill_queue(mythr, cgpu, drv, thr_id);
  5153. thread_reportin(mythr);
  5154. hashes = drv->scanwork(mythr);
  5155. if (unlikely(hashes == -1 )) {
  5156. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  5157. cgpu->deven = DEV_DISABLED;
  5158. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  5159. mt_disable(mythr, thr_id, drv);
  5160. }
  5161. hashes_done += hashes;
  5162. cgtime(&tv_end);
  5163. timersub(&tv_end, &tv_start, &diff);
  5164. /* Update the hashmeter at most 5 times per second */
  5165. if (diff.tv_sec > 0 || diff.tv_usec > 200) {
  5166. hashmeter(thr_id, &diff, hashes_done);
  5167. hashes_done = 0;
  5168. copy_time(&tv_start, &tv_end);
  5169. }
  5170. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  5171. mt_disable(mythr, thr_id, drv);
  5172. if (unlikely(mythr->work_restart)) {
  5173. flush_queue(cgpu);
  5174. drv->flush_work(cgpu);
  5175. }
  5176. }
  5177. cgpu->deven = DEV_DISABLED;
  5178. }
  5179. void *miner_thread(void *userdata)
  5180. {
  5181. struct thr_info *mythr = userdata;
  5182. const int thr_id = mythr->id;
  5183. struct cgpu_info *cgpu = mythr->cgpu;
  5184. struct device_drv *drv = cgpu->drv;
  5185. char threadname[24];
  5186. snprintf(threadname, 24, "miner/%d", thr_id);
  5187. RenameThread(threadname);
  5188. if (!drv->thread_init(mythr)) {
  5189. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  5190. goto out;
  5191. }
  5192. thread_reportout(mythr);
  5193. applog(LOG_DEBUG, "Popping ping in miner thread");
  5194. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  5195. drv->hash_work(mythr);
  5196. out:
  5197. drv->thread_shutdown(mythr);
  5198. thread_reportin(mythr);
  5199. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  5200. tq_freeze(mythr->q);
  5201. return NULL;
  5202. }
  5203. enum {
  5204. STAT_SLEEP_INTERVAL = 1,
  5205. STAT_CTR_INTERVAL = 10000000,
  5206. FAILURE_INTERVAL = 30,
  5207. };
  5208. /* Stage another work item from the work returned in a longpoll */
  5209. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  5210. {
  5211. struct work *work;
  5212. bool rc;
  5213. work = make_work();
  5214. rc = work_decode(pool, work, val);
  5215. if (unlikely(!rc)) {
  5216. applog(LOG_ERR, "Could not convert longpoll data to work");
  5217. free_work(work);
  5218. return;
  5219. }
  5220. total_getworks++;
  5221. pool->getwork_requested++;
  5222. work->pool = pool;
  5223. work->rolltime = rolltime;
  5224. copy_time(&work->tv_getwork, tv_lp);
  5225. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  5226. calc_diff(work, 0);
  5227. if (pool->enabled == POOL_REJECTING)
  5228. work->mandatory = true;
  5229. if (pool->has_gbt)
  5230. gen_gbt_work(pool, work);
  5231. work->longpoll = true;
  5232. work->getwork_mode = GETWORK_MODE_LP;
  5233. /* We'll be checking this work item twice, but we already know it's
  5234. * from a new block so explicitly force the new block detection now
  5235. * rather than waiting for it to hit the stage thread. This also
  5236. * allows testwork to know whether LP discovered the block or not. */
  5237. test_work_current(work);
  5238. /* Don't use backup LPs as work if we have failover-only enabled. Use
  5239. * the longpoll work from a pool that has been rejecting shares as a
  5240. * way to detect when the pool has recovered.
  5241. */
  5242. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  5243. free_work(work);
  5244. return;
  5245. }
  5246. work = clone_work(work);
  5247. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  5248. stage_work(work);
  5249. applog(LOG_DEBUG, "Converted longpoll data to work");
  5250. }
  5251. /* If we want longpoll, enable it for the chosen default pool, or, if
  5252. * the pool does not support longpoll, find the first one that does
  5253. * and use its longpoll support */
  5254. static struct pool *select_longpoll_pool(struct pool *cp)
  5255. {
  5256. int i;
  5257. if (cp->hdr_path || cp->has_gbt)
  5258. return cp;
  5259. for (i = 0; i < total_pools; i++) {
  5260. struct pool *pool = pools[i];
  5261. if (pool->has_stratum || pool->hdr_path)
  5262. return pool;
  5263. }
  5264. return NULL;
  5265. }
  5266. /* This will make the longpoll thread wait till it's the current pool, or it
  5267. * has been flagged as rejecting, before attempting to open any connections.
  5268. */
  5269. static void wait_lpcurrent(struct pool *pool)
  5270. {
  5271. if (cnx_needed(pool))
  5272. return;
  5273. while (pool->enabled == POOL_DISABLED ||
  5274. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  5275. pool_strategy != POOL_BALANCE)) {
  5276. mutex_lock(&lp_lock);
  5277. pthread_cond_wait(&lp_cond, &lp_lock);
  5278. mutex_unlock(&lp_lock);
  5279. }
  5280. }
  5281. static void *longpoll_thread(void *userdata)
  5282. {
  5283. struct pool *cp = (struct pool *)userdata;
  5284. /* This *pool is the source of the actual longpoll, not the pool we've
  5285. * tied it to */
  5286. struct timeval start, reply, end;
  5287. struct pool *pool = NULL;
  5288. char threadname[16];
  5289. CURL *curl = NULL;
  5290. int failures = 0;
  5291. char lpreq[1024];
  5292. char *lp_url;
  5293. int rolltime;
  5294. snprintf(threadname, 16, "longpoll/%d", cp->pool_no);
  5295. RenameThread(threadname);
  5296. curl = curl_easy_init();
  5297. if (unlikely(!curl)) {
  5298. applog(LOG_ERR, "CURL initialisation failed");
  5299. return NULL;
  5300. }
  5301. retry_pool:
  5302. pool = select_longpoll_pool(cp);
  5303. if (!pool) {
  5304. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  5305. while (!pool) {
  5306. nmsleep(60000);
  5307. pool = select_longpoll_pool(cp);
  5308. }
  5309. }
  5310. if (pool->has_stratum) {
  5311. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5312. cp->rpc_url, pool->rpc_url);
  5313. goto out;
  5314. }
  5315. /* Any longpoll from any pool is enough for this to be true */
  5316. have_longpoll = true;
  5317. wait_lpcurrent(cp);
  5318. if (pool->has_gbt) {
  5319. lp_url = pool->rpc_url;
  5320. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  5321. } else {
  5322. strcpy(lpreq, getwork_req);
  5323. lp_url = pool->lp_url;
  5324. if (cp == pool)
  5325. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  5326. else
  5327. applog(LOG_WARNING, "Long-polling activated for %s via %s", cp->rpc_url, lp_url);
  5328. }
  5329. while (42) {
  5330. json_t *val, *soval;
  5331. wait_lpcurrent(cp);
  5332. cgtime(&start);
  5333. /* Update the longpollid every time, but do it under lock to
  5334. * avoid races */
  5335. if (pool->has_gbt) {
  5336. cg_rlock(&pool->gbt_lock);
  5337. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  5338. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  5339. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  5340. cg_runlock(&pool->gbt_lock);
  5341. }
  5342. /* Longpoll connections can be persistent for a very long time
  5343. * and any number of issues could have come up in the meantime
  5344. * so always establish a fresh connection instead of relying on
  5345. * a persistent one. */
  5346. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  5347. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  5348. lpreq, false, true, &rolltime, pool, false);
  5349. cgtime(&reply);
  5350. if (likely(val)) {
  5351. soval = json_object_get(json_object_get(val, "result"), "submitold");
  5352. if (soval)
  5353. pool->submit_old = json_is_true(soval);
  5354. else
  5355. pool->submit_old = false;
  5356. convert_to_work(val, rolltime, pool, &start, &reply);
  5357. failures = 0;
  5358. json_decref(val);
  5359. } else {
  5360. /* Some pools regularly drop the longpoll request so
  5361. * only see this as longpoll failure if it happens
  5362. * immediately and just restart it the rest of the
  5363. * time. */
  5364. cgtime(&end);
  5365. if (end.tv_sec - start.tv_sec > 30)
  5366. continue;
  5367. if (failures == 1)
  5368. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  5369. nmsleep(30000);
  5370. }
  5371. if (pool != cp) {
  5372. pool = select_longpoll_pool(cp);
  5373. if (pool->has_stratum) {
  5374. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5375. cp->rpc_url, pool->rpc_url);
  5376. break;
  5377. }
  5378. if (unlikely(!pool))
  5379. goto retry_pool;
  5380. }
  5381. if (unlikely(pool->removed))
  5382. break;
  5383. }
  5384. out:
  5385. curl_easy_cleanup(curl);
  5386. return NULL;
  5387. }
  5388. void reinit_device(struct cgpu_info *cgpu)
  5389. {
  5390. cgpu->drv->reinit_device(cgpu);
  5391. }
  5392. static struct timeval rotate_tv;
  5393. /* We reap curls if they are unused for over a minute */
  5394. static void reap_curl(struct pool *pool)
  5395. {
  5396. struct curl_ent *ent, *iter;
  5397. struct timeval now;
  5398. int reaped = 0;
  5399. cgtime(&now);
  5400. mutex_lock(&pool->pool_lock);
  5401. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  5402. if (pool->curls < 2)
  5403. break;
  5404. if (now.tv_sec - ent->tv.tv_sec > 300) {
  5405. reaped++;
  5406. pool->curls--;
  5407. list_del(&ent->node);
  5408. curl_easy_cleanup(ent->curl);
  5409. free(ent);
  5410. }
  5411. }
  5412. mutex_unlock(&pool->pool_lock);
  5413. if (reaped)
  5414. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  5415. }
  5416. static void *watchpool_thread(void __maybe_unused *userdata)
  5417. {
  5418. int intervals = 0;
  5419. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5420. RenameThread("watchpool");
  5421. while (42) {
  5422. struct timeval now;
  5423. int i;
  5424. if (++intervals > 20)
  5425. intervals = 0;
  5426. cgtime(&now);
  5427. for (i = 0; i < total_pools; i++) {
  5428. struct pool *pool = pools[i];
  5429. if (!opt_benchmark)
  5430. reap_curl(pool);
  5431. /* Get a rolling utility per pool over 10 mins */
  5432. if (intervals > 19) {
  5433. int shares = pool->diff1 - pool->last_shares;
  5434. pool->last_shares = pool->diff1;
  5435. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  5436. pool->shares = pool->utility;
  5437. }
  5438. if (pool->enabled == POOL_DISABLED)
  5439. continue;
  5440. /* Don't start testing any pools if the test threads
  5441. * from startup are still doing their first attempt. */
  5442. if (unlikely(pool->testing)) {
  5443. pthread_join(pool->test_thread, NULL);
  5444. pool->testing = false;
  5445. }
  5446. /* Test pool is idle once every minute */
  5447. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  5448. cgtime(&pool->tv_idle);
  5449. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  5450. pool_resus(pool);
  5451. }
  5452. }
  5453. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  5454. cgtime(&rotate_tv);
  5455. switch_pools(NULL);
  5456. }
  5457. nmsleep(30000);
  5458. }
  5459. return NULL;
  5460. }
  5461. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  5462. * the screen at regular intervals, and restarts threads if they appear to have
  5463. * died. */
  5464. #define WATCHDOG_INTERVAL 2
  5465. #define WATCHDOG_SICK_TIME 60
  5466. #define WATCHDOG_DEAD_TIME 600
  5467. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  5468. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  5469. static void *watchdog_thread(void __maybe_unused *userdata)
  5470. {
  5471. const unsigned int interval = WATCHDOG_INTERVAL;
  5472. struct timeval zero_tv;
  5473. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5474. RenameThread("watchdog");
  5475. memset(&zero_tv, 0, sizeof(struct timeval));
  5476. cgtime(&rotate_tv);
  5477. while (1) {
  5478. int i;
  5479. struct timeval now;
  5480. sleep(interval);
  5481. discard_stale();
  5482. hashmeter(-1, &zero_tv, 0);
  5483. #ifdef HAVE_CURSES
  5484. if (curses_active_locked()) {
  5485. struct cgpu_info *cgpu;
  5486. int count;
  5487. change_logwinsize();
  5488. curses_print_status();
  5489. count = 0;
  5490. for (i = 0; i < total_devices; i++) {
  5491. cgpu = get_devices(i);
  5492. #ifndef USE_USBUTILS
  5493. if (cgpu)
  5494. #else
  5495. if (cgpu && !cgpu->usbinfo.nodev)
  5496. #endif
  5497. curses_print_devstatus(cgpu, count++);
  5498. }
  5499. #ifdef USE_USBUTILS
  5500. for (i = 0; i < total_devices; i++) {
  5501. cgpu = get_devices(i);
  5502. if (cgpu && cgpu->usbinfo.nodev)
  5503. curses_print_devstatus(cgpu, count++);
  5504. }
  5505. #endif
  5506. touchwin(statuswin);
  5507. wrefresh(statuswin);
  5508. touchwin(logwin);
  5509. wrefresh(logwin);
  5510. unlock_curses();
  5511. }
  5512. #endif
  5513. cgtime(&now);
  5514. if (!sched_paused && !should_run()) {
  5515. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  5516. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5517. if (!schedstart.enable) {
  5518. quit(0, "Terminating execution as planned");
  5519. break;
  5520. }
  5521. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  5522. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5523. sched_paused = true;
  5524. rd_lock(&mining_thr_lock);
  5525. for (i = 0; i < mining_threads; i++)
  5526. mining_thr[i]->pause = true;
  5527. rd_unlock(&mining_thr_lock);
  5528. } else if (sched_paused && should_run()) {
  5529. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  5530. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5531. if (schedstop.enable)
  5532. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  5533. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5534. sched_paused = false;
  5535. for (i = 0; i < mining_threads; i++) {
  5536. struct thr_info *thr;
  5537. thr = get_thread(i);
  5538. /* Don't touch disabled devices */
  5539. if (thr->cgpu->deven == DEV_DISABLED)
  5540. continue;
  5541. thr->pause = false;
  5542. tq_push(thr->q, &ping);
  5543. }
  5544. }
  5545. for (i = 0; i < total_devices; ++i) {
  5546. struct cgpu_info *cgpu = get_devices(i);
  5547. struct thr_info *thr = cgpu->thr[0];
  5548. enum dev_enable *denable;
  5549. char dev_str[8];
  5550. int gpu;
  5551. cgpu->drv->get_stats(cgpu);
  5552. gpu = cgpu->device_id;
  5553. denable = &cgpu->deven;
  5554. sprintf(dev_str, "%s%d", cgpu->drv->name, gpu);
  5555. #ifdef HAVE_ADL
  5556. if (adl_active && cgpu->has_adl)
  5557. gpu_autotune(gpu, denable);
  5558. if (opt_debug && cgpu->has_adl) {
  5559. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  5560. float temp = 0, vddc = 0;
  5561. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  5562. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  5563. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  5564. }
  5565. #endif
  5566. /* Thread is waiting on getwork or disabled */
  5567. if (thr->getwork || *denable == DEV_DISABLED)
  5568. continue;
  5569. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  5570. if (cgpu->status != LIFE_INIT)
  5571. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  5572. cgpu->status = LIFE_WELL;
  5573. cgpu->device_last_well = time(NULL);
  5574. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  5575. thr->rolling = cgpu->rolling = 0;
  5576. cgpu->status = LIFE_SICK;
  5577. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  5578. cgtime(&thr->sick);
  5579. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  5580. #ifdef HAVE_ADL
  5581. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5582. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  5583. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  5584. } else
  5585. #endif
  5586. if (opt_restart) {
  5587. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  5588. reinit_device(cgpu);
  5589. }
  5590. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  5591. cgpu->status = LIFE_DEAD;
  5592. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  5593. cgtime(&thr->sick);
  5594. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  5595. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  5596. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  5597. /* Attempt to restart a GPU that's sick or dead once every minute */
  5598. cgtime(&thr->sick);
  5599. #ifdef HAVE_ADL
  5600. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5601. /* Again do not attempt to restart a device that may have hard hung */
  5602. } else
  5603. #endif
  5604. if (opt_restart)
  5605. reinit_device(cgpu);
  5606. }
  5607. }
  5608. }
  5609. return NULL;
  5610. }
  5611. static void log_print_status(struct cgpu_info *cgpu)
  5612. {
  5613. char logline[255];
  5614. get_statline(logline, cgpu);
  5615. applog(LOG_WARNING, "%s", logline);
  5616. }
  5617. void print_summary(void)
  5618. {
  5619. struct timeval diff;
  5620. int hours, mins, secs, i;
  5621. double utility, displayed_hashes, work_util;
  5622. bool mhash_base = true;
  5623. timersub(&total_tv_end, &total_tv_start, &diff);
  5624. hours = diff.tv_sec / 3600;
  5625. mins = (diff.tv_sec % 3600) / 60;
  5626. secs = diff.tv_sec % 60;
  5627. utility = total_accepted / total_secs * 60;
  5628. work_util = total_diff1 / total_secs * 60;
  5629. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  5630. applog(LOG_WARNING, "Started at %s", datestamp);
  5631. if (total_pools == 1)
  5632. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  5633. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  5634. displayed_hashes = total_mhashes_done / total_secs;
  5635. if (displayed_hashes < 1) {
  5636. displayed_hashes *= 1000;
  5637. mhash_base = false;
  5638. }
  5639. applog(LOG_WARNING, "Average hashrate: %.1f %shash/s", displayed_hashes, mhash_base? "Mega" : "Kilo");
  5640. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  5641. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  5642. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  5643. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  5644. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  5645. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  5646. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  5647. if (total_accepted || total_rejected)
  5648. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  5649. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  5650. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  5651. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  5652. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  5653. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  5654. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  5655. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  5656. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  5657. if (total_pools > 1) {
  5658. for (i = 0; i < total_pools; i++) {
  5659. struct pool *pool = pools[i];
  5660. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  5661. if (pool->solved)
  5662. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  5663. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  5664. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  5665. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  5666. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  5667. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  5668. if (pool->accepted || pool->rejected)
  5669. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  5670. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  5671. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  5672. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  5673. }
  5674. }
  5675. applog(LOG_WARNING, "Summary of per device statistics:\n");
  5676. for (i = 0; i < total_devices; ++i) {
  5677. struct cgpu_info *cgpu = get_devices(i);
  5678. log_print_status(cgpu);
  5679. }
  5680. if (opt_shares) {
  5681. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  5682. if (opt_shares > total_accepted)
  5683. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  5684. }
  5685. applog(LOG_WARNING, " ");
  5686. fflush(stderr);
  5687. fflush(stdout);
  5688. }
  5689. static void clean_up(void)
  5690. {
  5691. #ifdef HAVE_OPENCL
  5692. clear_adl(nDevs);
  5693. #endif
  5694. #ifdef HAVE_LIBUSB
  5695. libusb_exit(NULL);
  5696. #endif
  5697. cgtime(&total_tv_end);
  5698. #ifdef HAVE_CURSES
  5699. disable_curses();
  5700. #endif
  5701. if (!opt_realquiet && successful_connect)
  5702. print_summary();
  5703. curl_global_cleanup();
  5704. }
  5705. void quit(int status, const char *format, ...)
  5706. {
  5707. if (format) {
  5708. va_list ap;
  5709. va_start(ap, format);
  5710. vapplog(LOG_ERR, format, ap);
  5711. va_end(ap);
  5712. }
  5713. clean_up();
  5714. #if defined(unix)
  5715. if (forkpid > 0) {
  5716. kill(forkpid, SIGTERM);
  5717. forkpid = 0;
  5718. }
  5719. #endif
  5720. exit(status);
  5721. }
  5722. #ifdef HAVE_CURSES
  5723. char *curses_input(const char *query)
  5724. {
  5725. char *input;
  5726. echo();
  5727. input = malloc(255);
  5728. if (!input)
  5729. quit(1, "Failed to malloc input");
  5730. leaveok(logwin, false);
  5731. wlogprint("%s:\n", query);
  5732. wgetnstr(logwin, input, 255);
  5733. if (!strlen(input))
  5734. strcpy(input, "-1");
  5735. leaveok(logwin, true);
  5736. noecho();
  5737. return input;
  5738. }
  5739. #endif
  5740. static bool pools_active = false;
  5741. static void *test_pool_thread(void *arg)
  5742. {
  5743. struct pool *pool = (struct pool *)arg;
  5744. if (pool_active(pool, false)) {
  5745. pool_tset(pool, &pool->lagging);
  5746. pool_tclear(pool, &pool->idle);
  5747. bool first_pool = false;
  5748. cg_wlock(&control_lock);
  5749. if (!pools_active) {
  5750. currentpool = pool;
  5751. if (pool->pool_no != 0)
  5752. first_pool = true;
  5753. pools_active = true;
  5754. }
  5755. cg_wunlock(&control_lock);
  5756. if (unlikely(first_pool))
  5757. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  5758. pool_resus(pool);
  5759. } else
  5760. pool_died(pool);
  5761. return NULL;
  5762. }
  5763. /* Always returns true that the pool details were added unless we are not
  5764. * live, implying this is the only pool being added, so if no pools are
  5765. * active it returns false. */
  5766. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  5767. {
  5768. url = get_proxy(url, pool);
  5769. pool->rpc_url = url;
  5770. pool->rpc_user = user;
  5771. pool->rpc_pass = pass;
  5772. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5773. if (!pool->rpc_userpass)
  5774. quit(1, "Failed to malloc userpass");
  5775. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5776. pool->testing = true;
  5777. pool->idle = true;
  5778. enable_pool(pool);
  5779. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  5780. if (!live) {
  5781. pthread_join(pool->test_thread, NULL);
  5782. pool->testing = false;
  5783. return pools_active;
  5784. }
  5785. return true;
  5786. }
  5787. #ifdef HAVE_CURSES
  5788. static bool input_pool(bool live)
  5789. {
  5790. char *url = NULL, *user = NULL, *pass = NULL;
  5791. struct pool *pool;
  5792. bool ret = false;
  5793. immedok(logwin, true);
  5794. wlogprint("Input server details.\n");
  5795. url = curses_input("URL");
  5796. if (!url)
  5797. goto out;
  5798. user = curses_input("Username");
  5799. if (!user)
  5800. goto out;
  5801. pass = curses_input("Password");
  5802. if (!pass)
  5803. goto out;
  5804. pool = add_pool();
  5805. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  5806. strncmp(url, "https://", 8)) {
  5807. char *httpinput;
  5808. httpinput = malloc(256);
  5809. if (!httpinput)
  5810. quit(1, "Failed to malloc httpinput");
  5811. strcpy(httpinput, "http://");
  5812. strncat(httpinput, url, 248);
  5813. free(url);
  5814. url = httpinput;
  5815. }
  5816. ret = add_pool_details(pool, live, url, user, pass);
  5817. out:
  5818. immedok(logwin, false);
  5819. if (!ret) {
  5820. if (url)
  5821. free(url);
  5822. if (user)
  5823. free(user);
  5824. if (pass)
  5825. free(pass);
  5826. }
  5827. return ret;
  5828. }
  5829. #endif
  5830. #if defined(unix)
  5831. static void fork_monitor()
  5832. {
  5833. // Make a pipe: [readFD, writeFD]
  5834. int pfd[2];
  5835. int r = pipe(pfd);
  5836. if (r < 0) {
  5837. perror("pipe - failed to create pipe for --monitor");
  5838. exit(1);
  5839. }
  5840. // Make stderr write end of pipe
  5841. fflush(stderr);
  5842. r = dup2(pfd[1], 2);
  5843. if (r < 0) {
  5844. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  5845. exit(1);
  5846. }
  5847. r = close(pfd[1]);
  5848. if (r < 0) {
  5849. perror("close - failed to close write end of pipe for --monitor");
  5850. exit(1);
  5851. }
  5852. // Don't allow a dying monitor to kill the main process
  5853. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  5854. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  5855. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  5856. perror("signal - failed to edit signal mask for --monitor");
  5857. exit(1);
  5858. }
  5859. // Fork a child process
  5860. forkpid = fork();
  5861. if (forkpid < 0) {
  5862. perror("fork - failed to fork child process for --monitor");
  5863. exit(1);
  5864. }
  5865. // Child: launch monitor command
  5866. if (0 == forkpid) {
  5867. // Make stdin read end of pipe
  5868. r = dup2(pfd[0], 0);
  5869. if (r < 0) {
  5870. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  5871. exit(1);
  5872. }
  5873. close(pfd[0]);
  5874. if (r < 0) {
  5875. perror("close - in child, failed to close read end of pipe for --monitor");
  5876. exit(1);
  5877. }
  5878. // Launch user specified command
  5879. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  5880. perror("execl - in child failed to exec user specified command for --monitor");
  5881. exit(1);
  5882. }
  5883. // Parent: clean up unused fds and bail
  5884. r = close(pfd[0]);
  5885. if (r < 0) {
  5886. perror("close - failed to close read end of pipe for --monitor");
  5887. exit(1);
  5888. }
  5889. }
  5890. #endif // defined(unix)
  5891. #ifdef HAVE_CURSES
  5892. void enable_curses(void) {
  5893. int x,y;
  5894. lock_curses();
  5895. if (curses_active) {
  5896. unlock_curses();
  5897. return;
  5898. }
  5899. mainwin = initscr();
  5900. getmaxyx(mainwin, y, x);
  5901. statuswin = newwin(logstart, x, 0, 0);
  5902. leaveok(statuswin, true);
  5903. logwin = newwin(y - logcursor, 0, logcursor, 0);
  5904. idlok(logwin, true);
  5905. scrollok(logwin, true);
  5906. leaveok(logwin, true);
  5907. cbreak();
  5908. noecho();
  5909. curses_active = true;
  5910. statusy = logstart;
  5911. unlock_curses();
  5912. }
  5913. #endif
  5914. #ifdef USE_BFLSC
  5915. extern struct device_drv bflsc_drv;
  5916. #endif
  5917. #ifdef USE_BITFORCE
  5918. extern struct device_drv bitforce_drv;
  5919. #endif
  5920. #ifdef USE_ICARUS
  5921. extern struct device_drv icarus_drv;
  5922. #endif
  5923. #ifdef USE_AVALON
  5924. extern struct device_drv avalon_drv;
  5925. #endif
  5926. #ifdef USE_MODMINER
  5927. extern struct device_drv modminer_drv;
  5928. #endif
  5929. #ifdef USE_ZTEX
  5930. extern struct device_drv ztex_drv;
  5931. #endif
  5932. static int cgminer_id_count = 0;
  5933. /* Various noop functions for drivers that don't support or need their
  5934. * variants. */
  5935. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  5936. {
  5937. }
  5938. void blank_get_statline_before(char *buf, struct cgpu_info __maybe_unused *cgpu)
  5939. {
  5940. tailsprintf(buf, " | ");
  5941. }
  5942. static void noop_get_statline(char __maybe_unused *buf, struct cgpu_info __maybe_unused *cgpu)
  5943. {
  5944. }
  5945. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  5946. {
  5947. return true;
  5948. }
  5949. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  5950. {
  5951. return true;
  5952. }
  5953. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  5954. {
  5955. return 0xffffffff;
  5956. }
  5957. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  5958. {
  5959. return true;
  5960. }
  5961. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  5962. {
  5963. return true;
  5964. }
  5965. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  5966. {
  5967. }
  5968. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  5969. {
  5970. }
  5971. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  5972. {
  5973. }
  5974. #define noop_flush_work noop_reinit_device
  5975. #define noop_queue_full noop_get_stats
  5976. /* Fill missing driver drv functions with noops */
  5977. void fill_device_drv(struct cgpu_info *cgpu)
  5978. {
  5979. struct device_drv *drv = cgpu->drv;
  5980. if (!drv->reinit_device)
  5981. drv->reinit_device = &noop_reinit_device;
  5982. if (!drv->get_statline_before)
  5983. drv->get_statline_before = &blank_get_statline_before;
  5984. if (!drv->get_statline)
  5985. drv->get_statline = &noop_get_statline;
  5986. if (!drv->get_stats)
  5987. drv->get_stats = &noop_get_stats;
  5988. if (!drv->thread_prepare)
  5989. drv->thread_prepare = &noop_thread_prepare;
  5990. if (!drv->can_limit_work)
  5991. drv->can_limit_work = &noop_can_limit_work;
  5992. if (!drv->thread_init)
  5993. drv->thread_init = &noop_thread_init;
  5994. if (!drv->prepare_work)
  5995. drv->prepare_work = &noop_prepare_work;
  5996. if (!drv->hw_error)
  5997. drv->hw_error = &noop_hw_error;
  5998. if (!drv->thread_shutdown)
  5999. drv->thread_shutdown = &noop_thread_shutdown;
  6000. if (!drv->thread_enable)
  6001. drv->thread_enable = &noop_thread_enable;
  6002. if (!drv->hash_work)
  6003. drv->hash_work = &hash_sole_work;
  6004. if (!drv->flush_work)
  6005. drv->flush_work = &noop_flush_work;
  6006. if (!drv->queue_full)
  6007. drv->queue_full = &noop_queue_full;
  6008. if (!drv->max_diff)
  6009. drv->max_diff = 1;
  6010. if (!drv->working_diff)
  6011. drv->working_diff = 1;
  6012. }
  6013. void enable_device(struct cgpu_info *cgpu)
  6014. {
  6015. cgpu->deven = DEV_ENABLED;
  6016. wr_lock(&devices_lock);
  6017. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  6018. wr_unlock(&devices_lock);
  6019. if (hotplug_mode) {
  6020. new_threads += cgpu->threads;
  6021. #ifdef HAVE_CURSES
  6022. adj_width(mining_threads + new_threads, &dev_width);
  6023. #endif
  6024. } else {
  6025. mining_threads += cgpu->threads;
  6026. #ifdef HAVE_CURSES
  6027. adj_width(mining_threads, &dev_width);
  6028. #endif
  6029. }
  6030. #ifdef HAVE_OPENCL
  6031. if (cgpu->drv->drv_id == DRIVER_OPENCL) {
  6032. gpu_threads += cgpu->threads;
  6033. }
  6034. #endif
  6035. fill_device_drv(cgpu);
  6036. rwlock_init(&cgpu->qlock);
  6037. cgpu->queued_work = NULL;
  6038. }
  6039. struct _cgpu_devid_counter {
  6040. char name[4];
  6041. int lastid;
  6042. UT_hash_handle hh;
  6043. };
  6044. bool add_cgpu(struct cgpu_info *cgpu)
  6045. {
  6046. static struct _cgpu_devid_counter *devids = NULL;
  6047. struct _cgpu_devid_counter *d;
  6048. HASH_FIND_STR(devids, cgpu->drv->name, d);
  6049. if (d)
  6050. cgpu->device_id = ++d->lastid;
  6051. else {
  6052. d = malloc(sizeof(*d));
  6053. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  6054. cgpu->device_id = d->lastid = 0;
  6055. HASH_ADD_STR(devids, name, d);
  6056. }
  6057. wr_lock(&devices_lock);
  6058. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + new_devices + 2));
  6059. wr_unlock(&devices_lock);
  6060. mutex_lock(&stats_lock);
  6061. cgpu->last_device_valid_work = time(NULL);
  6062. mutex_unlock(&stats_lock);
  6063. if (hotplug_mode)
  6064. devices[total_devices + new_devices++] = cgpu;
  6065. else
  6066. devices[total_devices++] = cgpu;
  6067. return true;
  6068. }
  6069. struct device_drv *copy_drv(struct device_drv *drv)
  6070. {
  6071. struct device_drv *copy;
  6072. char buf[100];
  6073. if (unlikely(!(copy = malloc(sizeof(*copy))))) {
  6074. sprintf(buf, "Failed to allocate device_drv copy of %s (%s)",
  6075. drv->name, drv->copy ? "copy" : "original");
  6076. quit(1, buf);
  6077. }
  6078. memcpy(copy, drv, sizeof(*copy));
  6079. copy->copy = true;
  6080. return copy;
  6081. }
  6082. #ifdef USE_USBUTILS
  6083. static void hotplug_process()
  6084. {
  6085. struct thr_info *thr;
  6086. int i, j;
  6087. for (i = 0; i < new_devices; i++) {
  6088. struct cgpu_info *cgpu;
  6089. int dev_no = total_devices + i;
  6090. cgpu = devices[dev_no];
  6091. if (!opt_devs_enabled || (opt_devs_enabled && devices_enabled[dev_no]))
  6092. enable_device(cgpu);
  6093. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6094. cgpu->rolling = cgpu->total_mhashes = 0;
  6095. }
  6096. wr_lock(&mining_thr_lock);
  6097. mining_thr = realloc(mining_thr, sizeof(thr) * (mining_threads + new_threads + 1));
  6098. wr_unlock(&mining_thr_lock);
  6099. if (!mining_thr)
  6100. quit(1, "Failed to hotplug realloc mining_thr");
  6101. for (i = 0; i < new_threads; i++) {
  6102. mining_thr[mining_threads + i] = calloc(1, sizeof(*thr));
  6103. if (!mining_thr[mining_threads + i])
  6104. quit(1, "Failed to hotplug calloc mining_thr[%d]", i);
  6105. }
  6106. // Start threads
  6107. for (i = 0; i < new_devices; ++i) {
  6108. struct cgpu_info *cgpu = devices[total_devices];
  6109. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  6110. cgpu->thr[cgpu->threads] = NULL;
  6111. cgpu->status = LIFE_INIT;
  6112. for (j = 0; j < cgpu->threads; ++j) {
  6113. thr = get_thread(mining_threads);
  6114. thr->id = mining_threads;
  6115. thr->cgpu = cgpu;
  6116. thr->device_thread = j;
  6117. thr->q = tq_new();
  6118. if (!thr->q)
  6119. quit(1, "tq_new hotplug failed in starting %s%d mining thread (#%d)", cgpu->drv->name, cgpu->device_id, total_devices);
  6120. /* Enable threads for devices set not to mine but disable
  6121. * their queue in case we wish to enable them later */
  6122. if (cgpu->deven != DEV_DISABLED) {
  6123. applog(LOG_DEBUG, "Pushing hotplug ping to thread %d", thr->id);
  6124. tq_push(thr->q, &ping);
  6125. }
  6126. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  6127. continue;
  6128. thread_reportout(thr);
  6129. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  6130. quit(1, "hotplug thread %d create failed", thr->id);
  6131. cgpu->thr[j] = thr;
  6132. mining_threads++;
  6133. }
  6134. total_devices++;
  6135. applog(LOG_WARNING, "Hotplug: %s added %s %i", cgpu->drv->dname, cgpu->drv->name, cgpu->device_id);
  6136. }
  6137. switch_logsize();
  6138. }
  6139. static void *hotplug_thread(void __maybe_unused *userdata)
  6140. {
  6141. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6142. RenameThread("hotplug");
  6143. hotplug_mode = true;
  6144. nmsleep(5000);
  6145. while (0x2a) {
  6146. // Version 0.1 just add the devices on - worry about using nodev later
  6147. if (hotplug_time == 0)
  6148. nmsleep(5000);
  6149. else {
  6150. new_devices = 0;
  6151. new_threads = 0;
  6152. #ifdef USE_ICARUS
  6153. icarus_drv.drv_detect();
  6154. #endif
  6155. #ifdef USE_BFLSC
  6156. bflsc_drv.drv_detect();
  6157. #endif
  6158. #ifdef USE_BITFORCE
  6159. bitforce_drv.drv_detect();
  6160. #endif
  6161. #ifdef USE_MODMINER
  6162. modminer_drv.drv_detect();
  6163. #endif
  6164. #ifdef USE_AVALON
  6165. avalon_drv.drv_detect();
  6166. #endif
  6167. if (new_devices)
  6168. hotplug_process();
  6169. // hotplug_time >0 && <=9999
  6170. nmsleep(hotplug_time * 1000);
  6171. }
  6172. }
  6173. return NULL;
  6174. }
  6175. #endif
  6176. static void probe_pools(void)
  6177. {
  6178. int i;
  6179. for (i = 0; i < total_pools; i++) {
  6180. struct pool *pool = pools[i];
  6181. pool->testing = true;
  6182. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  6183. }
  6184. }
  6185. int main(int argc, char *argv[])
  6186. {
  6187. struct sigaction handler;
  6188. struct thr_info *thr;
  6189. struct block *block;
  6190. unsigned int k;
  6191. int i, j;
  6192. char *s;
  6193. /* This dangerous functions tramples random dynamically allocated
  6194. * variables so do it before anything at all */
  6195. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  6196. quit(1, "Failed to curl_global_init");
  6197. initial_args = malloc(sizeof(char *) * (argc + 1));
  6198. for (i = 0; i < argc; i++)
  6199. initial_args[i] = strdup(argv[i]);
  6200. initial_args[argc] = NULL;
  6201. #ifdef HAVE_LIBUSB
  6202. int err = libusb_init(NULL);
  6203. if (err) {
  6204. fprintf(stderr, "libusb_init() failed err %d", err);
  6205. fflush(stderr);
  6206. quit(1, "libusb_init() failed");
  6207. }
  6208. #ifdef USE_USBUTILS
  6209. mutex_init(&cgusb_lock);
  6210. mutex_init(&cgusbres_lock);
  6211. #endif
  6212. #endif
  6213. mutex_init(&hash_lock);
  6214. mutex_init(&console_lock);
  6215. cglock_init(&control_lock);
  6216. mutex_init(&stats_lock);
  6217. mutex_init(&sharelog_lock);
  6218. cglock_init(&ch_lock);
  6219. mutex_init(&sshare_lock);
  6220. rwlock_init(&blk_lock);
  6221. rwlock_init(&netacc_lock);
  6222. rwlock_init(&mining_thr_lock);
  6223. rwlock_init(&devices_lock);
  6224. mutex_init(&lp_lock);
  6225. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  6226. quit(1, "Failed to pthread_cond_init lp_cond");
  6227. mutex_init(&restart_lock);
  6228. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  6229. quit(1, "Failed to pthread_cond_init restart_cond");
  6230. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  6231. quit(1, "Failed to pthread_cond_init gws_cond");
  6232. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  6233. handler.sa_handler = &sighandler;
  6234. handler.sa_flags = 0;
  6235. sigemptyset(&handler.sa_mask);
  6236. sigaction(SIGTERM, &handler, &termhandler);
  6237. sigaction(SIGINT, &handler, &inthandler);
  6238. #ifndef WIN32
  6239. signal(SIGPIPE, SIG_IGN);
  6240. #endif
  6241. opt_kernel_path = alloca(PATH_MAX);
  6242. strcpy(opt_kernel_path, CGMINER_PREFIX);
  6243. cgminer_path = alloca(PATH_MAX);
  6244. s = strdup(argv[0]);
  6245. strcpy(cgminer_path, dirname(s));
  6246. free(s);
  6247. strcat(cgminer_path, "/");
  6248. devcursor = 8;
  6249. logstart = devcursor + 1;
  6250. logcursor = logstart + 1;
  6251. block = calloc(sizeof(struct block), 1);
  6252. if (unlikely(!block))
  6253. quit (1, "main OOM");
  6254. for (i = 0; i < 36; i++)
  6255. strcat(block->hash, "0");
  6256. HASH_ADD_STR(blocks, hash, block);
  6257. strcpy(current_block, block->hash);
  6258. INIT_LIST_HEAD(&scan_devices);
  6259. #ifdef HAVE_OPENCL
  6260. memset(gpus, 0, sizeof(gpus));
  6261. for (i = 0; i < MAX_GPUDEVICES; i++)
  6262. gpus[i].dynamic = true;
  6263. #endif
  6264. /* parse command line */
  6265. opt_register_table(opt_config_table,
  6266. "Options for both config file and command line");
  6267. opt_register_table(opt_cmdline_table,
  6268. "Options for command line only");
  6269. opt_parse(&argc, argv, applog_and_exit);
  6270. if (argc != 1)
  6271. quit(1, "Unexpected extra commandline arguments");
  6272. if (!config_loaded)
  6273. load_default_config();
  6274. if (opt_benchmark) {
  6275. struct pool *pool;
  6276. pool = add_pool();
  6277. pool->rpc_url = malloc(255);
  6278. strcpy(pool->rpc_url, "Benchmark");
  6279. pool->rpc_user = pool->rpc_url;
  6280. pool->rpc_pass = pool->rpc_url;
  6281. enable_pool(pool);
  6282. pool->idle = false;
  6283. successful_connect = true;
  6284. }
  6285. #ifdef HAVE_CURSES
  6286. if (opt_realquiet || opt_display_devs)
  6287. use_curses = false;
  6288. if (use_curses)
  6289. enable_curses();
  6290. #endif
  6291. applog(LOG_WARNING, "Started %s", packagename);
  6292. if (cnfbuf) {
  6293. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  6294. switch (fileconf_load) {
  6295. case 0:
  6296. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  6297. applog(LOG_WARNING, "Configuration file could not be used.");
  6298. break;
  6299. case -1:
  6300. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  6301. if (use_curses)
  6302. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  6303. break;
  6304. default:
  6305. break;
  6306. }
  6307. free(cnfbuf);
  6308. cnfbuf = NULL;
  6309. }
  6310. strcat(opt_kernel_path, "/");
  6311. if (want_per_device_stats)
  6312. opt_log_output = true;
  6313. /* Use a shorter scantime for scrypt */
  6314. if (opt_scantime < 0)
  6315. opt_scantime = opt_scrypt ? 30 : 60;
  6316. total_control_threads = 9;
  6317. control_thr = calloc(total_control_threads, sizeof(*thr));
  6318. if (!control_thr)
  6319. quit(1, "Failed to calloc control_thr");
  6320. gwsched_thr_id = 0;
  6321. #ifdef USE_USBUTILS
  6322. usb_initialise();
  6323. // before device detection
  6324. if (!opt_scrypt) {
  6325. if (sem_init(&usb_resource_sem, 0, 0))
  6326. quit(1, "Failed to sem_init usb_resource_sem");
  6327. usbres_thr_id = 1;
  6328. thr = &control_thr[usbres_thr_id];
  6329. if (thr_info_create(thr, NULL, usb_resource_thread, thr))
  6330. quit(1, "usb resource thread create failed");
  6331. pthread_detach(thr->pth);
  6332. }
  6333. #endif
  6334. #ifdef HAVE_OPENCL
  6335. if (!opt_nogpu)
  6336. opencl_drv.drv_detect();
  6337. gpu_threads = 0;
  6338. #endif
  6339. #ifdef USE_ICARUS
  6340. if (!opt_scrypt)
  6341. icarus_drv.drv_detect();
  6342. #endif
  6343. #ifdef USE_BFLSC
  6344. if (!opt_scrypt)
  6345. bflsc_drv.drv_detect();
  6346. #endif
  6347. #ifdef USE_BITFORCE
  6348. if (!opt_scrypt)
  6349. bitforce_drv.drv_detect();
  6350. #endif
  6351. #ifdef USE_MODMINER
  6352. if (!opt_scrypt)
  6353. modminer_drv.drv_detect();
  6354. #endif
  6355. #ifdef USE_ZTEX
  6356. if (!opt_scrypt)
  6357. ztex_drv.drv_detect();
  6358. #endif
  6359. /* Detect avalon last since it will try to claim the device regardless
  6360. * as detection is unreliable. */
  6361. #ifdef USE_AVALON
  6362. if (!opt_scrypt)
  6363. avalon_drv.drv_detect();
  6364. #endif
  6365. if (opt_display_devs) {
  6366. applog(LOG_ERR, "Devices detected:");
  6367. for (i = 0; i < total_devices; ++i) {
  6368. struct cgpu_info *cgpu = devices[i];
  6369. if (cgpu->name)
  6370. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->name, cgpu->drv->dname);
  6371. else
  6372. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->drv->dname);
  6373. }
  6374. quit(0, "%d devices listed", total_devices);
  6375. }
  6376. mining_threads = 0;
  6377. if (opt_devs_enabled) {
  6378. for (i = 0; i < MAX_DEVICES; i++) {
  6379. if (devices_enabled[i]) {
  6380. if (i >= total_devices)
  6381. quit (1, "Command line options set a device that doesn't exist");
  6382. enable_device(devices[i]);
  6383. } else if (i < total_devices) {
  6384. if (!opt_removedisabled)
  6385. enable_device(devices[i]);
  6386. devices[i]->deven = DEV_DISABLED;
  6387. }
  6388. }
  6389. total_devices = cgminer_id_count;
  6390. } else {
  6391. for (i = 0; i < total_devices; ++i)
  6392. enable_device(devices[i]);
  6393. }
  6394. #ifdef USE_USBUTILS
  6395. if (!total_devices) {
  6396. applog(LOG_WARNING, "No devices detected!");
  6397. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  6398. }
  6399. #else
  6400. if (!total_devices)
  6401. quit(1, "All devices disabled, cannot mine!");
  6402. #endif
  6403. load_temp_cutoffs();
  6404. for (i = 0; i < total_devices; ++i)
  6405. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6406. if (!opt_compact) {
  6407. logstart += total_devices;
  6408. logcursor = logstart + 1;
  6409. #ifdef HAVE_CURSES
  6410. check_winsizes();
  6411. #endif
  6412. }
  6413. if (!total_pools) {
  6414. applog(LOG_WARNING, "Need to specify at least one pool server.");
  6415. #ifdef HAVE_CURSES
  6416. if (!use_curses || !input_pool(false))
  6417. #endif
  6418. quit(1, "Pool setup failed");
  6419. }
  6420. for (i = 0; i < total_pools; i++) {
  6421. struct pool *pool = pools[i];
  6422. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6423. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6424. if (!pool->rpc_userpass) {
  6425. if (!pool->rpc_user || !pool->rpc_pass)
  6426. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  6427. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6428. if (!pool->rpc_userpass)
  6429. quit(1, "Failed to malloc userpass");
  6430. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6431. }
  6432. }
  6433. /* Set the currentpool to pool 0 */
  6434. currentpool = pools[0];
  6435. #ifdef HAVE_SYSLOG_H
  6436. if (use_syslog)
  6437. openlog(PACKAGE, LOG_PID, LOG_USER);
  6438. #endif
  6439. #if defined(unix)
  6440. if (opt_stderr_cmd)
  6441. fork_monitor();
  6442. #endif // defined(unix)
  6443. mining_thr = calloc(mining_threads, sizeof(thr));
  6444. if (!mining_thr)
  6445. quit(1, "Failed to calloc mining_thr");
  6446. for (i = 0; i < mining_threads; i++) {
  6447. mining_thr[i] = calloc(1, sizeof(*thr));
  6448. if (!mining_thr[i])
  6449. quit(1, "Failed to calloc mining_thr[%d]", i);
  6450. }
  6451. stage_thr_id = 2;
  6452. thr = &control_thr[stage_thr_id];
  6453. thr->q = tq_new();
  6454. if (!thr->q)
  6455. quit(1, "Failed to tq_new");
  6456. /* start stage thread */
  6457. if (thr_info_create(thr, NULL, stage_thread, thr))
  6458. quit(1, "stage thread create failed");
  6459. pthread_detach(thr->pth);
  6460. /* Create a unique get work queue */
  6461. getq = tq_new();
  6462. if (!getq)
  6463. quit(1, "Failed to create getq");
  6464. /* We use the getq mutex as the staged lock */
  6465. stgd_lock = &getq->mutex;
  6466. if (opt_benchmark)
  6467. goto begin_bench;
  6468. for (i = 0; i < total_pools; i++) {
  6469. struct pool *pool = pools[i];
  6470. enable_pool(pool);
  6471. pool->idle = true;
  6472. }
  6473. applog(LOG_NOTICE, "Probing for an alive pool");
  6474. do {
  6475. int slept = 0;
  6476. /* Look for at least one active pool before starting */
  6477. probe_pools();
  6478. do {
  6479. sleep(1);
  6480. slept++;
  6481. } while (!pools_active && slept < 60);
  6482. if (!pools_active) {
  6483. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  6484. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  6485. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  6486. for (i = 0; i < total_pools; i++) {
  6487. struct pool *pool;
  6488. pool = pools[i];
  6489. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  6490. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  6491. }
  6492. #ifdef HAVE_CURSES
  6493. if (use_curses) {
  6494. halfdelay(150);
  6495. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  6496. if (getch() != ERR)
  6497. quit(0, "No servers could be used! Exiting.");
  6498. cbreak();
  6499. } else
  6500. #endif
  6501. quit(0, "No servers could be used! Exiting.");
  6502. }
  6503. } while (!pools_active);
  6504. begin_bench:
  6505. total_mhashes_done = 0;
  6506. for (i = 0; i < total_devices; i++) {
  6507. struct cgpu_info *cgpu = devices[i];
  6508. cgpu->rolling = cgpu->total_mhashes = 0;
  6509. }
  6510. cgtime(&total_tv_start);
  6511. cgtime(&total_tv_end);
  6512. get_datestamp(datestamp, &total_tv_start);
  6513. // Start threads
  6514. k = 0;
  6515. for (i = 0; i < total_devices; ++i) {
  6516. struct cgpu_info *cgpu = devices[i];
  6517. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  6518. cgpu->thr[cgpu->threads] = NULL;
  6519. cgpu->status = LIFE_INIT;
  6520. for (j = 0; j < cgpu->threads; ++j, ++k) {
  6521. thr = get_thread(k);
  6522. thr->id = k;
  6523. thr->cgpu = cgpu;
  6524. thr->device_thread = j;
  6525. thr->q = tq_new();
  6526. if (!thr->q)
  6527. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->drv->name, cgpu->device_id, i);
  6528. /* Enable threads for devices set not to mine but disable
  6529. * their queue in case we wish to enable them later */
  6530. if (cgpu->deven != DEV_DISABLED) {
  6531. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  6532. tq_push(thr->q, &ping);
  6533. }
  6534. if (!cgpu->drv->thread_prepare(thr))
  6535. continue;
  6536. thread_reportout(thr);
  6537. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  6538. quit(1, "thread %d create failed", thr->id);
  6539. cgpu->thr[j] = thr;
  6540. }
  6541. }
  6542. #ifdef HAVE_OPENCL
  6543. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  6544. for (i = 0; i < nDevs; i++)
  6545. pause_dynamic_threads(i);
  6546. #endif
  6547. cgtime(&total_tv_start);
  6548. cgtime(&total_tv_end);
  6549. watchpool_thr_id = 3;
  6550. thr = &control_thr[watchpool_thr_id];
  6551. /* start watchpool thread */
  6552. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  6553. quit(1, "watchpool thread create failed");
  6554. pthread_detach(thr->pth);
  6555. watchdog_thr_id = 4;
  6556. thr = &control_thr[watchdog_thr_id];
  6557. /* start watchdog thread */
  6558. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  6559. quit(1, "watchdog thread create failed");
  6560. pthread_detach(thr->pth);
  6561. #ifdef HAVE_OPENCL
  6562. /* Create reinit gpu thread */
  6563. gpur_thr_id = 5;
  6564. thr = &control_thr[gpur_thr_id];
  6565. thr->q = tq_new();
  6566. if (!thr->q)
  6567. quit(1, "tq_new failed for gpur_thr_id");
  6568. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  6569. quit(1, "reinit_gpu thread create failed");
  6570. #endif
  6571. /* Create API socket thread */
  6572. api_thr_id = 6;
  6573. thr = &control_thr[api_thr_id];
  6574. if (thr_info_create(thr, NULL, api_thread, thr))
  6575. quit(1, "API thread create failed");
  6576. #ifdef USE_USBUTILS
  6577. if (!opt_scrypt) {
  6578. hotplug_thr_id = 7;
  6579. thr = &control_thr[hotplug_thr_id];
  6580. if (thr_info_create(thr, NULL, hotplug_thread, thr))
  6581. quit(1, "hotplug thread create failed");
  6582. pthread_detach(thr->pth);
  6583. }
  6584. #endif
  6585. #ifdef HAVE_CURSES
  6586. /* Create curses input thread for keyboard input. Create this last so
  6587. * that we know all threads are created since this can call kill_work
  6588. * to try and shut down all previous threads. */
  6589. input_thr_id = 8;
  6590. thr = &control_thr[input_thr_id];
  6591. if (thr_info_create(thr, NULL, input_thread, thr))
  6592. quit(1, "input thread create failed");
  6593. pthread_detach(thr->pth);
  6594. #endif
  6595. /* Just to be sure */
  6596. if (total_control_threads != 9)
  6597. quit(1, "incorrect total_control_threads (%d) should be 9", total_control_threads);
  6598. /* Once everything is set up, main() becomes the getwork scheduler */
  6599. while (42) {
  6600. int ts, max_staged = opt_queue;
  6601. struct pool *pool, *cp;
  6602. bool lagging = false;
  6603. struct curl_ent *ce;
  6604. struct work *work;
  6605. cp = current_pool();
  6606. /* If the primary pool is a getwork pool and cannot roll work,
  6607. * try to stage one extra work per mining thread */
  6608. if (!cp->has_stratum && !cp->has_gbt && !staged_rollable)
  6609. max_staged += mining_threads;
  6610. mutex_lock(stgd_lock);
  6611. ts = __total_staged();
  6612. if (!cp->has_stratum && !cp->has_gbt && !ts && !opt_fail_only)
  6613. lagging = true;
  6614. /* Wait until hash_pop tells us we need to create more work */
  6615. if (ts > max_staged) {
  6616. pthread_cond_wait(&gws_cond, stgd_lock);
  6617. ts = __total_staged();
  6618. }
  6619. mutex_unlock(stgd_lock);
  6620. if (ts > max_staged)
  6621. continue;
  6622. work = make_work();
  6623. if (lagging && !pool_tset(cp, &cp->lagging)) {
  6624. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  6625. cp->getfail_occasions++;
  6626. total_go++;
  6627. }
  6628. pool = select_pool(lagging);
  6629. retry:
  6630. if (pool->has_stratum) {
  6631. while (!pool->stratum_active || !pool->stratum_notify) {
  6632. struct pool *altpool = select_pool(true);
  6633. nmsleep(5000);
  6634. if (altpool != pool) {
  6635. pool = altpool;
  6636. goto retry;
  6637. }
  6638. }
  6639. gen_stratum_work(pool, work);
  6640. applog(LOG_DEBUG, "Generated stratum work");
  6641. stage_work(work);
  6642. continue;
  6643. }
  6644. if (pool->has_gbt) {
  6645. while (pool->idle) {
  6646. struct pool *altpool = select_pool(true);
  6647. nmsleep(5000);
  6648. if (altpool != pool) {
  6649. pool = altpool;
  6650. goto retry;
  6651. }
  6652. }
  6653. gen_gbt_work(pool, work);
  6654. applog(LOG_DEBUG, "Generated GBT work");
  6655. stage_work(work);
  6656. continue;
  6657. }
  6658. if (clone_available()) {
  6659. applog(LOG_DEBUG, "Cloned getwork work");
  6660. free_work(work);
  6661. continue;
  6662. }
  6663. if (opt_benchmark) {
  6664. get_benchmark_work(work);
  6665. applog(LOG_DEBUG, "Generated benchmark work");
  6666. stage_work(work);
  6667. continue;
  6668. }
  6669. work->pool = pool;
  6670. ce = pop_curl_entry(pool);
  6671. /* obtain new work from bitcoin via JSON-RPC */
  6672. if (!get_upstream_work(work, ce->curl)) {
  6673. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  6674. /* Make sure the pool just hasn't stopped serving
  6675. * requests but is up as we'll keep hammering it */
  6676. if (++pool->seq_getfails > mining_threads + opt_queue)
  6677. pool_died(pool);
  6678. nmsleep(5000);
  6679. push_curl_entry(ce, pool);
  6680. pool = select_pool(!opt_fail_only);
  6681. goto retry;
  6682. }
  6683. if (ts >= max_staged)
  6684. pool_tclear(pool, &pool->lagging);
  6685. if (pool_tclear(pool, &pool->idle))
  6686. pool_resus(pool);
  6687. applog(LOG_DEBUG, "Generated getwork work");
  6688. stage_work(work);
  6689. push_curl_entry(ce, pool);
  6690. }
  6691. return 0;
  6692. }