cgminer.c 202 KB

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