cgminer.c 266 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086
  1. /*
  2. * Copyright 2011-2014 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. #include <limits.h>
  28. #ifdef USE_USBUTILS
  29. #include <semaphore.h>
  30. #endif
  31. #include <sys/stat.h>
  32. #include <sys/types.h>
  33. #ifndef WIN32
  34. #include <sys/resource.h>
  35. #else
  36. #include <windows.h>
  37. #endif
  38. #include <ccan/opt/opt.h>
  39. #include <jansson.h>
  40. #ifdef HAVE_LIBCURL
  41. #include <curl/curl.h>
  42. #else
  43. char *curly = ":D";
  44. #endif
  45. #include <libgen.h>
  46. #include <sha2.h>
  47. #include "compat.h"
  48. #include "miner.h"
  49. #include "bench_block.h"
  50. #include "scrypt.h"
  51. #ifdef USE_USBUTILS
  52. #include "usbutils.h"
  53. #endif
  54. #if defined(unix) || defined(__APPLE__)
  55. #include <errno.h>
  56. #include <fcntl.h>
  57. #include <sys/wait.h>
  58. #endif
  59. #ifdef USE_AVALON
  60. #include "driver-avalon.h"
  61. #endif
  62. #ifdef USE_AVALON2
  63. #include "driver-avalon2.h"
  64. #endif
  65. #ifdef USE_BFLSC
  66. #include "driver-bflsc.h"
  67. #endif
  68. #ifdef USE_SP10
  69. #include "driver-spondoolies-sp10.h"
  70. #endif
  71. #ifdef USE_SP30
  72. #include "driver-spondoolies-sp30.h"
  73. #endif
  74. #ifdef USE_BLOCK_ERUPTER
  75. #include "driver-blockerupter.h"
  76. #endif
  77. #ifdef USE_BITFURY
  78. #include "driver-bitfury.h"
  79. #endif
  80. #ifdef USE_COINTERRA
  81. #include "driver-cointerra.h"
  82. #endif
  83. #ifdef USE_HASHFAST
  84. #include "driver-hashfast.h"
  85. #endif
  86. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  87. #include "driver-bitmain.h"
  88. #endif
  89. #ifdef USE_GRIDSEED
  90. #include "driver-gridseed.h"
  91. #endif
  92. #ifdef USE_ZEUS
  93. #include "driver-zeus.h"
  94. #endif
  95. #ifdef USE_LKETC
  96. #include "driver-lketc.h"
  97. #endif
  98. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_AVALON) || defined(USE_AVALON2) || defined(USE_MODMINER)
  99. # define USE_FPGA
  100. #endif
  101. struct strategies strategies[] = {
  102. { "Failover" },
  103. { "Round Robin" },
  104. { "Rotate" },
  105. { "Load Balance" },
  106. { "Balance" },
  107. };
  108. static char packagename[256];
  109. bool opt_work_update;
  110. bool opt_protocol;
  111. static struct benchfile_layout {
  112. int length;
  113. char *name;
  114. } benchfile_data[] = {
  115. { 1, "Version" },
  116. { 64, "MerkleRoot" },
  117. { 64, "PrevHash" },
  118. { 8, "DifficultyBits" },
  119. { 10, "NonceTime" } // 10 digits
  120. };
  121. enum benchwork {
  122. BENCHWORK_VERSION = 0,
  123. BENCHWORK_MERKLEROOT,
  124. BENCHWORK_PREVHASH,
  125. BENCHWORK_DIFFBITS,
  126. BENCHWORK_NONCETIME,
  127. BENCHWORK_COUNT
  128. };
  129. #ifdef HAVE_LIBCURL
  130. static char *opt_btc_address;
  131. static char *opt_btc_sig;
  132. #endif
  133. static char *opt_benchfile;
  134. static bool opt_benchfile_display;
  135. static FILE *benchfile_in;
  136. static int benchfile_line;
  137. static int benchfile_work;
  138. static bool opt_benchmark;
  139. bool have_longpoll;
  140. bool want_per_device_stats;
  141. bool use_syslog;
  142. bool opt_quiet;
  143. bool opt_realquiet;
  144. bool opt_loginput;
  145. bool opt_compact;
  146. const int opt_cutofftemp = 95;
  147. int opt_log_interval = 5;
  148. int opt_queue = 1;
  149. static int max_queue = 1;
  150. int opt_scantime = -1;
  151. int opt_expiry = 120;
  152. static const bool opt_time = true;
  153. unsigned long long global_hashrate;
  154. unsigned long global_quota_gcd = 1;
  155. time_t last_getwork;
  156. #if defined(USE_USBUTILS)
  157. int nDevs;
  158. #endif
  159. bool opt_sha256;
  160. #ifdef USE_SCRYPT
  161. bool opt_scrypt;
  162. #endif
  163. bool opt_restart = true;
  164. bool opt_nogpu;
  165. struct list_head scan_devices;
  166. static bool opt_display_devs;
  167. int total_devices;
  168. int zombie_devs;
  169. static int most_devices;
  170. struct cgpu_info **devices;
  171. int mining_threads;
  172. int num_processors;
  173. #ifdef HAVE_CURSES
  174. bool use_curses = true;
  175. #else
  176. bool use_curses;
  177. #endif
  178. static bool opt_widescreen;
  179. static bool alt_status;
  180. static bool switch_status;
  181. static bool opt_submit_stale = true;
  182. static int opt_shares;
  183. bool opt_fail_only;
  184. static bool opt_fix_protocol;
  185. bool opt_lowmem;
  186. bool opt_autofan;
  187. bool opt_autoengine;
  188. bool opt_noadl;
  189. char *opt_api_allow = NULL;
  190. char *opt_api_groups;
  191. char *opt_api_description = PACKAGE_STRING;
  192. int opt_api_port = 4028;
  193. char *opt_api_host = API_LISTEN_ADDR;
  194. bool opt_api_listen;
  195. bool opt_api_mcast;
  196. char *opt_api_mcast_addr = API_MCAST_ADDR;
  197. char *opt_api_mcast_code = API_MCAST_CODE;
  198. char *opt_api_mcast_des = "";
  199. int opt_api_mcast_port = 4028;
  200. bool opt_api_network;
  201. bool opt_delaynet;
  202. bool opt_disable_pool;
  203. static bool no_work;
  204. #ifdef USE_ICARUS
  205. char *opt_icarus_options = NULL;
  206. char *opt_icarus_timing = NULL;
  207. float opt_anu_freq = 200;
  208. float opt_rock_freq = 270;
  209. #endif
  210. bool opt_worktime;
  211. #ifdef USE_AVALON
  212. char *opt_avalon_options;
  213. char *opt_bitburner_fury_options;
  214. static char *opt_set_avalon_fan;
  215. static char *opt_set_avalon_freq;
  216. #endif
  217. #ifdef USE_AVALON2
  218. static char *opt_set_avalon2_freq;
  219. static char *opt_set_avalon2_fan;
  220. static char *opt_set_avalon2_voltage;
  221. #endif
  222. #ifdef USE_BLOCKERUPTER
  223. int opt_bet_clk = 0;
  224. #endif
  225. #ifdef USE_HASHRATIO
  226. #include "driver-hashratio.h"
  227. #endif
  228. #ifdef USE_KLONDIKE
  229. char *opt_klondike_options = NULL;
  230. #endif
  231. #ifdef USE_DRILLBIT
  232. char *opt_drillbit_options = NULL;
  233. char *opt_drillbit_auto = NULL;
  234. #endif
  235. char *opt_bab_options = NULL;
  236. #ifdef USE_BITMINE_A1
  237. char *opt_bitmine_a1_options = NULL;
  238. #endif
  239. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  240. char *opt_bitmain_options;
  241. static char *opt_set_bitmain_fan;
  242. static char *opt_set_bitmain_freq;
  243. #endif
  244. #ifdef USE_ANT_S2
  245. char *opt_bitmain_dev;
  246. #endif
  247. #ifdef USE_HASHFAST
  248. static char *opt_set_hfa_fan;
  249. #endif
  250. #ifdef USE_GRIDSEED
  251. char *opt_gridseed_options = NULL;
  252. char *opt_gridseed_freq = NULL;
  253. char *opt_gridseed_override = NULL;
  254. #endif
  255. #ifdef USE_LKETC
  256. bool opt_lketc_debug;
  257. int opt_lketc_chips_count;
  258. int opt_lketc_chip_clk;
  259. bool opt_lketc_nocheck_golden;
  260. char *opt_lketc_options;
  261. #endif
  262. #ifdef USE_ZEUS
  263. bool opt_zeus_debug;
  264. int opt_zeus_chips_count;
  265. int opt_zeus_chip_clk;
  266. bool opt_zeus_nocheck_golden;
  267. char *opt_zeus_options;
  268. #endif
  269. static char *opt_set_null;
  270. #ifdef USE_MINION
  271. int opt_minion_chipreport;
  272. char *opt_minion_cores;
  273. bool opt_minion_extra;
  274. char *opt_minion_freq;
  275. int opt_minion_freqchange = 1000;
  276. int opt_minion_freqpercent = 70;
  277. bool opt_minion_idlecount;
  278. int opt_minion_ledcount;
  279. int opt_minion_ledlimit = 98;
  280. bool opt_minion_noautofreq;
  281. bool opt_minion_overheat;
  282. int opt_minion_spidelay;
  283. char *opt_minion_spireset;
  284. int opt_minion_spisleep = 200;
  285. int opt_minion_spiusec;
  286. char *opt_minion_temp;
  287. #endif
  288. #ifdef USE_USBUTILS
  289. char *opt_usb_select = NULL;
  290. int opt_usbdump = -1;
  291. bool opt_usb_list_all;
  292. cgsem_t usb_resource_sem;
  293. static pthread_t usb_poll_thread;
  294. static bool usb_polling;
  295. #endif
  296. char *opt_kernel_path;
  297. char *cgminer_path;
  298. #if defined(USE_BITFORCE)
  299. bool opt_bfl_noncerange;
  300. #endif
  301. #define QUIET (opt_quiet || opt_realquiet)
  302. struct thr_info *control_thr;
  303. struct thr_info **mining_thr;
  304. static int gwsched_thr_id;
  305. static int watchpool_thr_id;
  306. static int watchdog_thr_id;
  307. #ifdef HAVE_CURSES
  308. static int input_thr_id;
  309. #endif
  310. int gpur_thr_id;
  311. static int api_thr_id;
  312. #ifdef USE_USBUTILS
  313. static int usbres_thr_id;
  314. static int hotplug_thr_id;
  315. #endif
  316. static int total_control_threads;
  317. bool hotplug_mode;
  318. static int new_devices;
  319. static int new_threads;
  320. int hotplug_time = 5;
  321. #if LOCK_TRACKING
  322. pthread_mutex_t lockstat_lock;
  323. #endif
  324. pthread_mutex_t hash_lock;
  325. static pthread_mutex_t *stgd_lock;
  326. pthread_mutex_t console_lock;
  327. cglock_t ch_lock;
  328. static pthread_rwlock_t blk_lock;
  329. static pthread_mutex_t sshare_lock;
  330. pthread_rwlock_t netacc_lock;
  331. pthread_rwlock_t mining_thr_lock;
  332. pthread_rwlock_t devices_lock;
  333. static pthread_mutex_t lp_lock;
  334. static pthread_cond_t lp_cond;
  335. pthread_mutex_t restart_lock;
  336. pthread_cond_t restart_cond;
  337. pthread_cond_t gws_cond;
  338. double rolling1, rolling5, rolling15;
  339. double total_rolling;
  340. double total_mhashes_done;
  341. static struct timeval total_tv_start, total_tv_end;
  342. static struct timeval restart_tv_start, update_tv_start;
  343. cglock_t control_lock;
  344. pthread_mutex_t stats_lock;
  345. int hw_errors;
  346. int64_t total_accepted, total_rejected, total_diff1;
  347. int64_t total_getworks, total_stale, total_discarded;
  348. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  349. static int staged_rollable;
  350. unsigned int new_blocks;
  351. static unsigned int work_block;
  352. unsigned int found_blocks;
  353. unsigned int local_work;
  354. unsigned int total_go, total_ro;
  355. struct pool **pools;
  356. static struct pool *currentpool = NULL;
  357. int total_pools, enabled_pools;
  358. enum pool_strategy pool_strategy = POOL_FAILOVER;
  359. int opt_rotate_period;
  360. static int total_urls, total_users, total_passes, total_userpasses, total_extranonce;
  361. static
  362. #ifndef HAVE_CURSES
  363. const
  364. #endif
  365. bool curses_active;
  366. /* Protected by ch_lock */
  367. char current_hash[68];
  368. static char prev_block[12];
  369. static char current_block[32];
  370. static char datestamp[40];
  371. static char blocktime[32];
  372. struct timeval block_timeval;
  373. static char best_share[8] = "0";
  374. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  375. static char block_diff[8];
  376. uint64_t best_diff = 0;
  377. struct block {
  378. char hash[68];
  379. UT_hash_handle hh;
  380. int block_no;
  381. };
  382. static struct block *blocks = NULL;
  383. int swork_id;
  384. /* For creating a hash database of stratum shares submitted that have not had
  385. * a response yet */
  386. struct stratum_share {
  387. UT_hash_handle hh;
  388. bool block;
  389. struct work *work;
  390. int id;
  391. time_t sshare_time;
  392. time_t sshare_sent;
  393. };
  394. static struct stratum_share *stratum_shares = NULL;
  395. char *opt_socks_proxy = NULL;
  396. int opt_suggest_diff;
  397. static const char def_conf[] = "cgminer.conf";
  398. static char *default_config;
  399. static bool config_loaded;
  400. static int include_count;
  401. #define JSON_INCLUDE_CONF "include"
  402. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  403. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  404. #define JSON_MAX_DEPTH 10
  405. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  406. #define JSON_WEB_ERROR "WEB config err"
  407. #if defined(unix) || defined(__APPLE__)
  408. static char *opt_stderr_cmd = NULL;
  409. static int forkpid;
  410. #endif // defined(unix)
  411. struct sigaction termhandler, inthandler;
  412. struct thread_q *getq;
  413. static uint32_t total_work;
  414. struct work *staged_work = NULL;
  415. struct schedtime {
  416. bool enable;
  417. struct tm tm;
  418. };
  419. struct schedtime schedstart;
  420. struct schedtime schedstop;
  421. bool sched_paused;
  422. static bool time_before(struct tm *tm1, struct tm *tm2)
  423. {
  424. if (tm1->tm_hour < tm2->tm_hour)
  425. return true;
  426. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  427. return true;
  428. return false;
  429. }
  430. static bool should_run(void)
  431. {
  432. struct timeval tv;
  433. struct tm *tm;
  434. if (!schedstart.enable && !schedstop.enable)
  435. return true;
  436. cgtime(&tv);
  437. const time_t tmp_time = tv.tv_sec;
  438. tm = localtime(&tmp_time);
  439. if (schedstart.enable) {
  440. if (!schedstop.enable) {
  441. if (time_before(tm, &schedstart.tm))
  442. return false;
  443. /* This is a once off event with no stop time set */
  444. schedstart.enable = false;
  445. return true;
  446. }
  447. if (time_before(&schedstart.tm, &schedstop.tm)) {
  448. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  449. return true;
  450. return false;
  451. } /* Times are reversed */
  452. if (time_before(tm, &schedstart.tm)) {
  453. if (time_before(tm, &schedstop.tm))
  454. return true;
  455. return false;
  456. }
  457. return true;
  458. }
  459. /* only schedstop.enable == true */
  460. if (!time_before(tm, &schedstop.tm))
  461. return false;
  462. return true;
  463. }
  464. void get_datestamp(char *f, size_t fsiz, struct timeval *tv)
  465. {
  466. struct tm *tm;
  467. const time_t tmp_time = tv->tv_sec;
  468. tm = localtime(&tmp_time);
  469. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  470. tm->tm_year + 1900,
  471. tm->tm_mon + 1,
  472. tm->tm_mday,
  473. tm->tm_hour,
  474. tm->tm_min,
  475. tm->tm_sec);
  476. }
  477. static void get_timestamp(char *f, size_t fsiz, struct timeval *tv)
  478. {
  479. struct tm *tm;
  480. const time_t tmp_time = tv->tv_sec;
  481. tm = localtime(&tmp_time);
  482. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  483. tm->tm_hour,
  484. tm->tm_min,
  485. tm->tm_sec);
  486. }
  487. static char exit_buf[512];
  488. static void applog_and_exit(const char *fmt, ...)
  489. {
  490. va_list ap;
  491. va_start(ap, fmt);
  492. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  493. va_end(ap);
  494. _applog(LOG_ERR, exit_buf, true);
  495. exit(1);
  496. }
  497. static pthread_mutex_t sharelog_lock;
  498. static FILE *sharelog_file = NULL;
  499. static struct thr_info *__get_thread(int thr_id)
  500. {
  501. return mining_thr[thr_id];
  502. }
  503. struct thr_info *get_thread(int thr_id)
  504. {
  505. struct thr_info *thr;
  506. rd_lock(&mining_thr_lock);
  507. thr = __get_thread(thr_id);
  508. rd_unlock(&mining_thr_lock);
  509. return thr;
  510. }
  511. static struct cgpu_info *get_thr_cgpu(int thr_id)
  512. {
  513. struct thr_info *thr = get_thread(thr_id);
  514. return thr->cgpu;
  515. }
  516. struct cgpu_info *get_devices(int id)
  517. {
  518. struct cgpu_info *cgpu;
  519. rd_lock(&devices_lock);
  520. cgpu = devices[id];
  521. rd_unlock(&devices_lock);
  522. return cgpu;
  523. }
  524. static void sharelog(const char*disposition, const struct work*work)
  525. {
  526. char *target, *hash, *data;
  527. struct cgpu_info *cgpu;
  528. unsigned long int t;
  529. struct pool *pool;
  530. int thr_id, rv;
  531. char s[1024];
  532. size_t ret;
  533. if (!sharelog_file)
  534. return;
  535. thr_id = work->thr_id;
  536. cgpu = get_thr_cgpu(thr_id);
  537. pool = work->pool;
  538. t = (unsigned long int)(work->tv_work_found.tv_sec);
  539. target = bin2hex(work->target, sizeof(work->target));
  540. hash = bin2hex(work->hash, sizeof(work->hash));
  541. data = bin2hex(work->data, sizeof(work->data));
  542. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  543. 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);
  544. free(target);
  545. free(hash);
  546. free(data);
  547. if (rv >= (int)(sizeof(s)))
  548. s[sizeof(s) - 1] = '\0';
  549. else if (rv < 0) {
  550. applog(LOG_ERR, "sharelog printf error");
  551. return;
  552. }
  553. mutex_lock(&sharelog_lock);
  554. ret = fwrite(s, rv, 1, sharelog_file);
  555. fflush(sharelog_file);
  556. mutex_unlock(&sharelog_lock);
  557. if (ret != 1)
  558. applog(LOG_ERR, "sharelog fwrite error");
  559. }
  560. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  561. static char *gbt_req = "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"]}]}\n";
  562. static char *gbt_solo_req = "{\"id\": 0, \"method\": \"getblocktemplate\"}\n";
  563. /* Adjust all the pools' quota to the greatest common denominator after a pool
  564. * has been added or the quotas changed. */
  565. void adjust_quota_gcd(void)
  566. {
  567. unsigned long gcd, lowest_quota = ~0UL, quota;
  568. struct pool *pool;
  569. int i;
  570. for (i = 0; i < total_pools; i++) {
  571. pool = pools[i];
  572. quota = pool->quota;
  573. if (!quota)
  574. continue;
  575. if (quota < lowest_quota)
  576. lowest_quota = quota;
  577. }
  578. if (likely(lowest_quota < ~0UL)) {
  579. gcd = lowest_quota;
  580. for (i = 0; i < total_pools; i++) {
  581. pool = pools[i];
  582. quota = pool->quota;
  583. if (!quota)
  584. continue;
  585. while (quota % gcd)
  586. gcd--;
  587. }
  588. } else
  589. gcd = 1;
  590. for (i = 0; i < total_pools; i++) {
  591. pool = pools[i];
  592. pool->quota_used *= global_quota_gcd;
  593. pool->quota_used /= gcd;
  594. pool->quota_gcd = pool->quota / gcd;
  595. }
  596. global_quota_gcd = gcd;
  597. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  598. }
  599. /* Return value is ignored if not called from add_pool_details */
  600. struct pool *add_pool(void)
  601. {
  602. struct pool *pool;
  603. pool = calloc(sizeof(struct pool), 1);
  604. if (!pool)
  605. quit(1, "Failed to malloc pool in add_pool");
  606. pool->pool_no = pool->prio = total_pools;
  607. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  608. pools[total_pools++] = pool;
  609. mutex_init(&pool->pool_lock);
  610. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  611. quit(1, "Failed to pthread_cond_init in add_pool");
  612. cglock_init(&pool->data_lock);
  613. mutex_init(&pool->stratum_lock);
  614. cglock_init(&pool->gbt_lock);
  615. INIT_LIST_HEAD(&pool->curlring);
  616. /* Make sure the pool doesn't think we've been idle since time 0 */
  617. pool->tv_idle.tv_sec = ~0UL;
  618. pool->rpc_req = getwork_req;
  619. pool->rpc_proxy = NULL;
  620. pool->quota = 1;
  621. adjust_quota_gcd();
  622. pool->extranonce_subscribe = false;
  623. return pool;
  624. }
  625. /* Pool variant of test and set */
  626. static bool pool_tset(struct pool *pool, bool *var)
  627. {
  628. bool ret;
  629. mutex_lock(&pool->pool_lock);
  630. ret = *var;
  631. *var = true;
  632. mutex_unlock(&pool->pool_lock);
  633. return ret;
  634. }
  635. bool pool_tclear(struct pool *pool, bool *var)
  636. {
  637. bool ret;
  638. mutex_lock(&pool->pool_lock);
  639. ret = *var;
  640. *var = false;
  641. mutex_unlock(&pool->pool_lock);
  642. return ret;
  643. }
  644. struct pool *current_pool(void)
  645. {
  646. struct pool *pool;
  647. cg_rlock(&control_lock);
  648. pool = currentpool;
  649. cg_runlock(&control_lock);
  650. return pool;
  651. }
  652. char *set_int_range(const char *arg, int *i, int min, int max)
  653. {
  654. char *err = opt_set_intval(arg, i);
  655. if (err)
  656. return err;
  657. if (*i < min || *i > max)
  658. return "Value out of range";
  659. return NULL;
  660. }
  661. static char *set_int_0_to_9999(const char *arg, int *i)
  662. {
  663. return set_int_range(arg, i, 0, 9999);
  664. }
  665. static char *set_int_1_to_65535(const char *arg, int *i)
  666. {
  667. return set_int_range(arg, i, 1, 65535);
  668. }
  669. static char *set_int_0_to_10(const char *arg, int *i)
  670. {
  671. return set_int_range(arg, i, 0, 10);
  672. }
  673. static char *set_int_0_to_100(const char *arg, int *i)
  674. {
  675. return set_int_range(arg, i, 0, 100);
  676. }
  677. static char *set_int_0_to_255(const char *arg, int *i)
  678. {
  679. return set_int_range(arg, i, 0, 255);
  680. }
  681. static char *set_int_0_to_200(const char *arg, int *i)
  682. {
  683. return set_int_range(arg, i, 0, 200);
  684. }
  685. static char *set_int_32_to_63(const char *arg, int *i)
  686. {
  687. return set_int_range(arg, i, 32, 63);
  688. }
  689. static char *set_int_1_to_10(const char *arg, int *i)
  690. {
  691. return set_int_range(arg, i, 1, 10);
  692. }
  693. static char __maybe_unused *set_int_0_to_4(const char *arg, int *i)
  694. {
  695. return set_int_range(arg, i, 0, 4);
  696. }
  697. static char *set_int_1_to_1024(const char *arg, int *i)
  698. {
  699. return set_int_range(arg, i, 1, 1024);
  700. }
  701. #ifdef USE_FPGA_SERIAL
  702. static char *opt_add_serial;
  703. static char *add_serial(char *arg)
  704. {
  705. string_elist_add(arg, &scan_devices);
  706. return NULL;
  707. }
  708. #endif
  709. void get_intrange(char *arg, int *val1, int *val2)
  710. {
  711. if (sscanf(arg, "%d-%d", val1, val2) == 1)
  712. *val2 = *val1;
  713. }
  714. static char *set_balance(enum pool_strategy *strategy)
  715. {
  716. *strategy = POOL_BALANCE;
  717. return NULL;
  718. }
  719. static char *set_loadbalance(enum pool_strategy *strategy)
  720. {
  721. *strategy = POOL_LOADBALANCE;
  722. return NULL;
  723. }
  724. static char *set_rotate(const char *arg, char __maybe_unused *i)
  725. {
  726. pool_strategy = POOL_ROTATE;
  727. return set_int_range(arg, &opt_rotate_period, 0, 9999);
  728. }
  729. static char *set_rr(enum pool_strategy *strategy)
  730. {
  731. *strategy = POOL_ROUNDROBIN;
  732. return NULL;
  733. }
  734. /* Detect that url is for a stratum protocol either via the presence of
  735. * stratum+tcp or by detecting a stratum server response */
  736. bool detect_stratum(struct pool *pool, char *url)
  737. {
  738. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  739. return false;
  740. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  741. pool->rpc_url = strdup(url);
  742. pool->has_stratum = true;
  743. pool->stratum_url = pool->sockaddr_url;
  744. return true;
  745. }
  746. return false;
  747. }
  748. static struct pool *add_url(void)
  749. {
  750. total_urls++;
  751. if (total_urls > total_pools)
  752. add_pool();
  753. return pools[total_urls - 1];
  754. }
  755. static void setup_url(struct pool *pool, char *arg)
  756. {
  757. arg = get_proxy(arg, pool);
  758. if (detect_stratum(pool, arg))
  759. return;
  760. opt_set_charp(arg, &pool->rpc_url);
  761. if (strncmp(arg, "http://", 7) &&
  762. strncmp(arg, "https://", 8)) {
  763. char *httpinput;
  764. httpinput = malloc(256);
  765. if (!httpinput)
  766. quit(1, "Failed to malloc httpinput");
  767. strcpy(httpinput, "stratum+tcp://");
  768. strncat(httpinput, arg, 242);
  769. detect_stratum(pool, httpinput);
  770. }
  771. }
  772. static char *set_url(char *arg)
  773. {
  774. struct pool *pool = add_url();
  775. setup_url(pool, arg);
  776. if (strstr(pool->rpc_url, ".nicehash.com") || strstr(pool->rpc_url, "#xnsub")) {
  777. pool->extranonce_subscribe = true;
  778. applog(LOG_DEBUG, "Pool %d extranonce subscribing enabled.", pool->pool_no);
  779. }
  780. return NULL;
  781. }
  782. static char *set_quota(char *arg)
  783. {
  784. char *semicolon = strchr(arg, ';'), *url;
  785. int len, qlen, quota;
  786. struct pool *pool;
  787. if (!semicolon)
  788. return "No semicolon separated quota;URL pair found";
  789. len = strlen(arg);
  790. *semicolon = '\0';
  791. qlen = strlen(arg);
  792. if (!qlen)
  793. return "No parameter for quota found";
  794. len -= qlen + 1;
  795. if (len < 1)
  796. return "No parameter for URL found";
  797. quota = atoi(arg);
  798. if (quota < 0)
  799. return "Invalid negative parameter for quota set";
  800. url = arg + qlen + 1;
  801. pool = add_url();
  802. setup_url(pool, url);
  803. pool->quota = quota;
  804. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  805. adjust_quota_gcd();
  806. return NULL;
  807. }
  808. static char *set_user(const char *arg)
  809. {
  810. struct pool *pool;
  811. if (total_userpasses)
  812. return "Use only user + pass or userpass, but not both";
  813. total_users++;
  814. if (total_users > total_pools)
  815. add_pool();
  816. pool = pools[total_users - 1];
  817. opt_set_charp(arg, &pool->rpc_user);
  818. return NULL;
  819. }
  820. static char *set_pass(const char *arg)
  821. {
  822. struct pool *pool;
  823. if (total_userpasses)
  824. return "Use only user + pass or userpass, but not both";
  825. total_passes++;
  826. if (total_passes > total_pools)
  827. add_pool();
  828. pool = pools[total_passes - 1];
  829. opt_set_charp(arg, &pool->rpc_pass);
  830. return NULL;
  831. }
  832. static char *set_userpass(const char *arg)
  833. {
  834. struct pool *pool;
  835. char *updup;
  836. if (total_users || total_passes)
  837. return "Use only user + pass or userpass, but not both";
  838. total_userpasses++;
  839. if (total_userpasses > total_pools)
  840. add_pool();
  841. pool = pools[total_userpasses - 1];
  842. updup = strdup(arg);
  843. opt_set_charp(arg, &pool->rpc_userpass);
  844. pool->rpc_user = strtok(updup, ":");
  845. if (!pool->rpc_user)
  846. return "Failed to find : delimited user info";
  847. pool->rpc_pass = strtok(NULL, ":");
  848. if (!pool->rpc_pass)
  849. pool->rpc_pass = strdup("");
  850. return NULL;
  851. }
  852. static char *set_extranonce_subscribe(char *arg)
  853. {
  854. struct pool *pool;
  855. total_extranonce++;
  856. if (total_extranonce > total_pools)
  857. add_pool();
  858. pool = pools[total_extranonce - 1];
  859. applog(LOG_DEBUG, "Enable extranonce subscribe on %d", pool->pool_no);
  860. opt_set_bool(&pool->extranonce_subscribe);
  861. return NULL;
  862. }
  863. static char *enable_debug(bool *flag)
  864. {
  865. *flag = true;
  866. /* Turn on verbose output, too. */
  867. opt_log_output = true;
  868. return NULL;
  869. }
  870. static char *opt_set_sched_start;
  871. static char *opt_set_sched_stop;
  872. static char *set_schedtime(const char *arg, struct schedtime *st)
  873. {
  874. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  875. return "Invalid time set, should be HH:MM";
  876. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  877. return "Invalid time set.";
  878. st->enable = true;
  879. return NULL;
  880. }
  881. static char *set_sched_start(const char *arg)
  882. {
  883. return set_schedtime(arg, &schedstart);
  884. }
  885. static char *set_sched_stop(const char *arg)
  886. {
  887. return set_schedtime(arg, &schedstop);
  888. }
  889. static char *opt_set_sharelog;
  890. static char* set_sharelog(char *arg)
  891. {
  892. char *r = "";
  893. long int i = strtol(arg, &r, 10);
  894. if ((!*r) && i >= 0 && i <= INT_MAX) {
  895. sharelog_file = fdopen((int)i, "a");
  896. if (!sharelog_file)
  897. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  898. } else if (!strcmp(arg, "-")) {
  899. sharelog_file = stdout;
  900. if (!sharelog_file)
  901. applog(LOG_ERR, "Standard output missing for share log");
  902. } else {
  903. sharelog_file = fopen(arg, "a");
  904. if (!sharelog_file)
  905. applog(LOG_ERR, "Failed to open %s for share log", arg);
  906. }
  907. return NULL;
  908. }
  909. static char *temp_cutoff_str = NULL;
  910. static char __maybe_unused *opt_set_temp_cutoff;
  911. char *set_temp_cutoff(char *arg)
  912. {
  913. int val;
  914. if (!(arg && arg[0]))
  915. return "Invalid parameters for set temp cutoff";
  916. val = atoi(arg);
  917. if (val < 0 || val > 200)
  918. return "Invalid value passed to set temp cutoff";
  919. temp_cutoff_str = arg;
  920. return NULL;
  921. }
  922. static void load_temp_cutoffs()
  923. {
  924. int i, val = 0, device = 0;
  925. char *nextptr;
  926. if (temp_cutoff_str) {
  927. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  928. if (device >= total_devices)
  929. quit(1, "Too many values passed to set temp cutoff");
  930. val = atoi(nextptr);
  931. if (val < 0 || val > 200)
  932. quit(1, "Invalid value passed to set temp cutoff");
  933. rd_lock(&devices_lock);
  934. devices[device]->cutofftemp = val;
  935. rd_unlock(&devices_lock);
  936. }
  937. } else {
  938. rd_lock(&devices_lock);
  939. for (i = device; i < total_devices; ++i) {
  940. if (!devices[i]->cutofftemp)
  941. devices[i]->cutofftemp = opt_cutofftemp;
  942. }
  943. rd_unlock(&devices_lock);
  944. return;
  945. }
  946. if (device <= 1) {
  947. rd_lock(&devices_lock);
  948. for (i = device; i < total_devices; ++i)
  949. devices[i]->cutofftemp = val;
  950. rd_unlock(&devices_lock);
  951. }
  952. }
  953. static char *set_float_125_to_500(const char *arg, float *i)
  954. {
  955. char *err = opt_set_floatval(arg, i);
  956. if (err)
  957. return err;
  958. if (*i < 125 || *i > 500)
  959. return "Value out of range";
  960. return NULL;
  961. }
  962. static char *set_null(const char __maybe_unused *arg)
  963. {
  964. return NULL;
  965. }
  966. /* These options are available from config file or commandline */
  967. static struct opt_table opt_config_table[] = {
  968. #ifdef USE_ICARUS
  969. OPT_WITH_ARG("--anu-freq",
  970. set_float_125_to_500, &opt_show_floatval, &opt_anu_freq,
  971. "Set AntminerU1 frequency in MHz, range 125-500"),
  972. #endif
  973. OPT_WITH_ARG("--api-allow",
  974. opt_set_charp, NULL, &opt_api_allow,
  975. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  976. OPT_WITH_ARG("--api-description",
  977. opt_set_charp, NULL, &opt_api_description,
  978. "Description placed in the API status header, default: cgminer version"),
  979. OPT_WITH_ARG("--api-groups",
  980. opt_set_charp, NULL, &opt_api_groups,
  981. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  982. OPT_WITHOUT_ARG("--api-listen",
  983. opt_set_bool, &opt_api_listen,
  984. "Enable API, default: disabled"),
  985. OPT_WITHOUT_ARG("--api-mcast",
  986. opt_set_bool, &opt_api_mcast,
  987. "Enable API Multicast listener, default: disabled"),
  988. OPT_WITH_ARG("--api-mcast-addr",
  989. opt_set_charp, NULL, &opt_api_mcast_addr,
  990. "API Multicast listen address"),
  991. OPT_WITH_ARG("--api-mcast-code",
  992. opt_set_charp, NULL, &opt_api_mcast_code,
  993. "Code expected in the API Multicast message, don't use '-'"),
  994. OPT_WITH_ARG("--api-mcast-des",
  995. opt_set_charp, NULL, &opt_api_mcast_des,
  996. "Description appended to the API Multicast reply, default: ''"),
  997. OPT_WITH_ARG("--api-mcast-port",
  998. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  999. "API Multicast listen port"),
  1000. OPT_WITHOUT_ARG("--api-network",
  1001. opt_set_bool, &opt_api_network,
  1002. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1003. OPT_WITH_ARG("--api-port",
  1004. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1005. "Port number of miner API"),
  1006. OPT_WITH_ARG("--api-host",
  1007. opt_set_charp, NULL, &opt_api_host,
  1008. "Specify API listen address, default: 0.0.0.0"),
  1009. #ifdef USE_AVALON
  1010. OPT_WITHOUT_ARG("--avalon-auto",
  1011. opt_set_bool, &opt_avalon_auto,
  1012. "Adjust avalon overclock frequency dynamically for best hashrate"),
  1013. OPT_WITH_ARG("--avalon-cutoff",
  1014. set_int_0_to_100, opt_show_intval, &opt_avalon_overheat,
  1015. "Set avalon overheat cut off temperature"),
  1016. OPT_WITH_CBARG("--avalon-fan",
  1017. set_avalon_fan, NULL, &opt_set_avalon_fan,
  1018. "Set fanspeed percentage for avalon, single value or range (default: 20-100)"),
  1019. OPT_WITH_CBARG("--avalon-freq",
  1020. set_avalon_freq, NULL, &opt_set_avalon_freq,
  1021. "Set frequency range for avalon-auto, single value or range"),
  1022. OPT_WITH_ARG("--avalon-options",
  1023. opt_set_charp, NULL, &opt_avalon_options,
  1024. "Set avalon options baud:miners:asic:timeout:freq:tech"),
  1025. OPT_WITH_ARG("--avalon-temp",
  1026. set_int_0_to_100, opt_show_intval, &opt_avalon_temp,
  1027. "Set avalon target temperature"),
  1028. #endif
  1029. #ifdef USE_AVALON2
  1030. OPT_WITH_CBARG("--avalon2-freq",
  1031. set_avalon2_freq, NULL, &opt_set_avalon2_freq,
  1032. "Set frequency range for Avalon2, single value or range, step: 25"),
  1033. OPT_WITH_CBARG("--avalon2-voltage",
  1034. set_avalon2_voltage, NULL, &opt_set_avalon2_voltage,
  1035. "Set Avalon2 core voltage, in millivolts, step: 125"),
  1036. OPT_WITH_CBARG("--avalon2-fan",
  1037. set_avalon2_fan, NULL, &opt_set_avalon2_fan,
  1038. "Set Avalon2 target fan speed"),
  1039. OPT_WITH_ARG("--avalon2-cutoff",
  1040. set_int_0_to_100, opt_show_intval, &opt_avalon2_overheat,
  1041. "Set Avalon2 overheat cut off temperature"),
  1042. OPT_WITHOUT_ARG("--avalon2-fixed-speed",
  1043. set_avalon2_fixed_speed, &opt_avalon2_fan_fixed,
  1044. "Set Avalon2 fan to fixed speed"),
  1045. OPT_WITH_ARG("--avalon2-polling-delay",
  1046. set_int_1_to_65535, opt_show_intval, &opt_avalon2_polling_delay,
  1047. "Set Avalon2 polling delay value (ms)"),
  1048. #endif
  1049. #ifdef USE_BAB
  1050. OPT_WITH_ARG("--bab-options",
  1051. opt_set_charp, NULL, &opt_bab_options,
  1052. "Set bab options max:def:min:up:down:hz:delay:trf"),
  1053. #endif
  1054. OPT_WITHOUT_ARG("--balance",
  1055. set_balance, &pool_strategy,
  1056. "Change multipool strategy from failover to even share balance"),
  1057. OPT_WITH_ARG("--benchfile",
  1058. opt_set_charp, NULL, &opt_benchfile,
  1059. "Run cgminer in benchmark mode using a work file - produces no shares"),
  1060. OPT_WITHOUT_ARG("--benchfile-display",
  1061. opt_set_bool, &opt_benchfile_display,
  1062. "Display each benchfile nonce found"),
  1063. OPT_WITHOUT_ARG("--benchmark",
  1064. opt_set_bool, &opt_benchmark,
  1065. "Run cgminer in benchmark mode - produces no shares"),
  1066. #if defined(USE_BITFORCE)
  1067. OPT_WITHOUT_ARG("--bfl-range",
  1068. opt_set_bool, &opt_bfl_noncerange,
  1069. "Use nonce range on bitforce devices if supported"),
  1070. #endif
  1071. #ifdef USE_BFLSC
  1072. OPT_WITH_ARG("--bflsc-overheat",
  1073. set_int_0_to_200, opt_show_intval, &opt_bflsc_overheat,
  1074. "Set overheat temperature where BFLSC devices throttle, 0 to disable"),
  1075. #endif
  1076. #ifdef USE_AVALON
  1077. OPT_WITH_ARG("--bitburner-voltage",
  1078. opt_set_intval, NULL, &opt_bitburner_core_voltage,
  1079. "Set BitBurner (Avalon) core voltage, in millivolts"),
  1080. OPT_WITH_ARG("--bitburner-fury-voltage",
  1081. opt_set_intval, NULL, &opt_bitburner_fury_core_voltage,
  1082. "Set BitBurner Fury core voltage, in millivolts"),
  1083. OPT_WITH_ARG("--bitburner-fury-options",
  1084. opt_set_charp, NULL, &opt_bitburner_fury_options,
  1085. "Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq"),
  1086. #endif
  1087. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  1088. OPT_WITHOUT_ARG("--bitmain-auto",
  1089. opt_set_bool, &opt_bitmain_auto,
  1090. "Adjust bitmain overclock frequency dynamically for best hashrate"),
  1091. OPT_WITH_ARG("--bitmain-cutoff",
  1092. set_int_0_to_100, opt_show_intval, &opt_bitmain_overheat,
  1093. "Set bitmain overheat cut off temperature"),
  1094. OPT_WITH_CBARG("--bitmain-fan",
  1095. set_bitmain_fan, NULL, &opt_set_bitmain_fan,
  1096. "Set fanspeed percentage for bitmain, single value or range (default: 20-100)"),
  1097. OPT_WITH_CBARG("--bitmain-freq",
  1098. set_bitmain_freq, NULL, &opt_set_bitmain_freq,
  1099. "Set frequency range for bitmain-auto, single value or range"),
  1100. OPT_WITHOUT_ARG("--bitmain-hwerror",
  1101. opt_set_bool, &opt_bitmain_hwerror,
  1102. "Set bitmain device detect hardware error"),
  1103. OPT_WITH_ARG("--bitmain-options",
  1104. opt_set_charp, NULL, &opt_bitmain_options,
  1105. "Set bitmain options baud:miners:asic:timeout:freq"),
  1106. OPT_WITH_ARG("--bitmain-temp",
  1107. set_int_0_to_100, opt_show_intval, &opt_bitmain_temp,
  1108. "Set bitmain target temperature"),
  1109. #endif
  1110. #ifdef USE_ANT_S2
  1111. OPT_WITH_ARG("--bitmain-dev",
  1112. opt_set_charp, NULL, &opt_bitmain_dev,
  1113. "Set bitmain device"),
  1114. OPT_WITHOUT_ARG("--bitmainbeeper",
  1115. opt_set_bool, &opt_bitmain_beeper,
  1116. "Set bitmain beeper ringing"),
  1117. OPT_WITHOUT_ARG("--bitmain-checkall",
  1118. opt_set_bool, &opt_bitmain_checkall,
  1119. opt_hidden),
  1120. OPT_WITHOUT_ARG("--bitmain-checkn2diff",
  1121. opt_set_bool, &opt_bitmain_checkn2diff,
  1122. opt_hidden),
  1123. OPT_WITHOUT_ARG("--bitmaintempoverctrl",
  1124. opt_set_bool, &opt_bitmain_tempoverctrl,
  1125. "Set bitmain stop runing when temprerature is over 80 degree Celsius"),
  1126. #endif
  1127. #ifdef USE_BITMINE_A1
  1128. OPT_WITH_ARG("--bitmine-a1-options",
  1129. opt_set_charp, NULL, &opt_bitmine_a1_options,
  1130. "Bitmine A1 options ref_clk_khz:sys_clk_khz:spi_clk_khz:override_chip_num"),
  1131. #endif
  1132. #ifdef USE_BITFURY
  1133. OPT_WITH_ARG("--bxf-bits",
  1134. set_int_32_to_63, opt_show_intval, &opt_bxf_bits,
  1135. "Set max BXF/HXF bits for overclocking"),
  1136. OPT_WITH_ARG("--bxf-debug",
  1137. set_int_0_to_4, opt_show_intval, &opt_bxf_debug,
  1138. "BXF: Debug all USB I/O, > is to the board(s), < is from the board(s)"),
  1139. OPT_WITH_ARG("--bxf-temp-target",
  1140. set_int_0_to_200, opt_show_intval, &opt_bxf_temp_target,
  1141. "Set target temperature for BXF/HXF devices"),
  1142. OPT_WITH_ARG("--bxm-bits",
  1143. set_int_0_to_100, opt_show_intval, &opt_bxm_bits,
  1144. "Set BXM bits for overclocking"),
  1145. #endif
  1146. #ifdef USE_BLOCKERUPTER
  1147. OPT_WITH_ARG("--bet-clk",
  1148. opt_set_intval, opt_show_intval, &opt_bet_clk,
  1149. "Set Block Erupter clock"),
  1150. #endif
  1151. #ifdef HAVE_LIBCURL
  1152. OPT_WITH_ARG("--btc-address",
  1153. opt_set_charp, NULL, &opt_btc_address,
  1154. "Set bitcoin target address when solo mining to bitcoind (mandatory)"),
  1155. OPT_WITH_ARG("--btc-sig",
  1156. opt_set_charp, NULL, &opt_btc_sig,
  1157. "Set signature to add to coinbase when solo mining (optional)"),
  1158. #endif
  1159. #ifdef HAVE_CURSES
  1160. OPT_WITHOUT_ARG("--compact",
  1161. opt_set_bool, &opt_compact,
  1162. "Use compact display without per device statistics"),
  1163. #endif
  1164. #ifdef USE_COINTERRA
  1165. OPT_WITH_ARG("--cta-load",
  1166. set_int_0_to_255, opt_show_intval, &opt_cta_load,
  1167. "Set load for CTA devices, 0-255 range"),
  1168. OPT_WITH_ARG("--ps-load",
  1169. set_int_0_to_100, opt_show_intval, &opt_ps_load,
  1170. "Set power supply load for CTA devices, 0-100 range"),
  1171. #endif
  1172. OPT_WITHOUT_ARG("--debug|-D",
  1173. enable_debug, &opt_debug,
  1174. "Enable debug output"),
  1175. OPT_WITHOUT_ARG("--disable-rejecting",
  1176. opt_set_bool, &opt_disable_pool,
  1177. "Automatically disable pools that continually reject shares"),
  1178. #ifdef USE_DRILLBIT
  1179. OPT_WITH_ARG("--drillbit-options",
  1180. opt_set_charp, NULL, &opt_drillbit_options,
  1181. "Set drillbit options <int|ext>:clock[:clock_divider][:voltage]"),
  1182. OPT_WITH_ARG("--drillbit-auto",
  1183. opt_set_charp, NULL, &opt_drillbit_auto,
  1184. "Enable drillbit automatic tuning <every>:[<gooderr>:<baderr>:<maxerr>]"),
  1185. #endif
  1186. OPT_WITH_ARG("--expiry|-E",
  1187. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1188. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  1189. OPT_WITHOUT_ARG("--failover-only",
  1190. opt_set_bool, &opt_fail_only,
  1191. "Don't leak work to backup pools when primary pool is lagging"),
  1192. OPT_WITHOUT_ARG("--fix-protocol",
  1193. opt_set_bool, &opt_fix_protocol,
  1194. "Do not redirect to a different getwork protocol (eg. stratum)"),
  1195. #ifdef USE_GRIDSEED
  1196. OPT_WITH_ARG("--gridseed-options",
  1197. opt_set_charp, NULL, &opt_gridseed_options,
  1198. "Set gridseed options: freq=N[,voltage=1][,led_off=1]"),
  1199. OPT_WITH_ARG("--gridseed-freq",
  1200. opt_set_charp, NULL, &opt_gridseed_freq,
  1201. "Set gridseed frequency per-device: serial=freq[,...]"),
  1202. OPT_WITH_ARG("--gridseed-override",
  1203. opt_set_charp, NULL, &opt_gridseed_override,
  1204. "Set any gridseed option per-device: serial:opt1=val1[,...][;serial=...]"),
  1205. #endif
  1206. #ifdef USE_HASHFAST
  1207. OPT_WITHOUT_ARG("--hfa-dfu-boot",
  1208. opt_set_bool, &opt_hfa_dfu_boot,
  1209. opt_hidden),
  1210. OPT_WITH_ARG("--hfa-hash-clock",
  1211. set_int_0_to_9999, opt_show_intval, &opt_hfa_hash_clock,
  1212. "Set hashfast clock speed"),
  1213. OPT_WITH_ARG("--hfa-fail-drop",
  1214. set_int_0_to_100, opt_show_intval, &opt_hfa_fail_drop,
  1215. "Set how many MHz to drop clockspeed each failure on an overlocked hashfast device"),
  1216. OPT_WITH_CBARG("--hfa-fan",
  1217. set_hfa_fan, NULL, &opt_set_hfa_fan,
  1218. "Set fanspeed percentage for hashfast, single value or range (default: 10-85)"),
  1219. OPT_WITH_ARG("--hfa-name",
  1220. opt_set_charp, NULL, &opt_hfa_name,
  1221. "Set a unique name for a single hashfast device specified with --usb or the first device found"),
  1222. OPT_WITHOUT_ARG("--hfa-noshed",
  1223. opt_set_bool, &opt_hfa_noshed,
  1224. "Disable hashfast dynamic core disabling feature"),
  1225. OPT_WITH_ARG("--hfa-ntime-roll",
  1226. opt_set_intval, NULL, &opt_hfa_ntime_roll,
  1227. opt_hidden),
  1228. OPT_WITH_ARG("--hfa-options",
  1229. opt_set_charp, NULL, &opt_hfa_options,
  1230. "Set hashfast options name:clock (comma separated)"),
  1231. OPT_WITHOUT_ARG("--hfa-pll-bypass",
  1232. opt_set_bool, &opt_hfa_pll_bypass,
  1233. opt_hidden),
  1234. OPT_WITH_ARG("--hfa-temp-overheat",
  1235. set_int_0_to_200, opt_show_intval, &opt_hfa_overheat,
  1236. "Set the hashfast overheat throttling temperature"),
  1237. OPT_WITH_ARG("--hfa-temp-target",
  1238. set_int_0_to_200, opt_show_intval, &opt_hfa_target,
  1239. "Set the hashfast target temperature (0 to disable)"),
  1240. #endif
  1241. #ifdef USE_HASHRATIO
  1242. OPT_WITH_CBARG("--hro-freq",
  1243. set_hashratio_freq, NULL, &opt_hashratio_freq,
  1244. "Set the hashratio clock frequency"),
  1245. #endif
  1246. OPT_WITH_ARG("--hotplug",
  1247. set_int_0_to_9999, NULL, &hotplug_time,
  1248. #ifdef USE_USBUTILS
  1249. "Seconds between hotplug checks (0 means never check)"
  1250. #else
  1251. opt_hidden
  1252. #endif
  1253. ),
  1254. #ifdef USE_ICARUS
  1255. OPT_WITH_ARG("--icarus-options",
  1256. opt_set_charp, NULL, &opt_icarus_options,
  1257. opt_hidden),
  1258. OPT_WITH_ARG("--icarus-timing",
  1259. opt_set_charp, NULL, &opt_icarus_timing,
  1260. opt_hidden),
  1261. #endif
  1262. #if defined(HAVE_MODMINER)
  1263. OPT_WITH_ARG("--kernel-path|-K",
  1264. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1265. "Specify a path to where bitstream files are"),
  1266. #endif
  1267. #ifdef USE_KLONDIKE
  1268. OPT_WITH_ARG("--klondike-options",
  1269. opt_set_charp, NULL, &opt_klondike_options,
  1270. "Set klondike options clock:temptarget"),
  1271. #endif
  1272. OPT_WITHOUT_ARG("--load-balance",
  1273. set_loadbalance, &pool_strategy,
  1274. "Change multipool strategy from failover to quota based balance"),
  1275. OPT_WITH_ARG("--log|-l",
  1276. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1277. "Interval in seconds between log output"),
  1278. OPT_WITHOUT_ARG("--lowmem",
  1279. opt_set_bool, &opt_lowmem,
  1280. "Minimise caching of shares for low memory applications"),
  1281. #ifdef USE_MINION
  1282. OPT_WITH_ARG("--minion-chipreport",
  1283. set_int_0_to_100, opt_show_intval, &opt_minion_chipreport,
  1284. "Seconds to report chip 5min hashrate, range 0-100 (default: 0=disabled)"),
  1285. OPT_WITH_ARG("--minion-cores",
  1286. opt_set_charp, NULL, &opt_minion_cores,
  1287. opt_hidden),
  1288. OPT_WITHOUT_ARG("--minion-extra",
  1289. opt_set_bool, &opt_minion_extra,
  1290. opt_hidden),
  1291. OPT_WITH_ARG("--minion-freq",
  1292. opt_set_charp, NULL, &opt_minion_freq,
  1293. "Set minion chip frequencies in MHz, single value or comma list, range 100-1400 (default: 1200)"),
  1294. OPT_WITH_ARG("--minion-freqchange",
  1295. set_int_0_to_9999, opt_show_intval, &opt_minion_freqchange,
  1296. "Millisecond total time to do frequency changes (default: 1000)"),
  1297. OPT_WITH_ARG("--minion-freqpercent",
  1298. set_int_0_to_100, opt_show_intval, &opt_minion_freqpercent,
  1299. "Percentage to use when starting up a chip (default: 70%)"),
  1300. OPT_WITHOUT_ARG("--minion-idlecount",
  1301. opt_set_bool, &opt_minion_idlecount,
  1302. "Report when IdleCount is >0 or changes"),
  1303. OPT_WITH_ARG("--minion-ledcount",
  1304. set_int_0_to_100, opt_show_intval, &opt_minion_ledcount,
  1305. "Turn off led when more than this many chips below the ledlimit (default: 0)"),
  1306. OPT_WITH_ARG("--minion-ledlimit",
  1307. set_int_0_to_200, opt_show_intval, &opt_minion_ledlimit,
  1308. "Turn off led when chips GHs are below this (default: 90)"),
  1309. OPT_WITHOUT_ARG("--minion-noautofreq",
  1310. opt_set_bool, &opt_minion_noautofreq,
  1311. "Disable automatic frequency adjustment"),
  1312. OPT_WITHOUT_ARG("--minion-overheat",
  1313. opt_set_bool, &opt_minion_overheat,
  1314. "Enable directly halting any chip when the status exceeds 100C"),
  1315. OPT_WITH_ARG("--minion-spidelay",
  1316. set_int_0_to_9999, opt_show_intval, &opt_minion_spidelay,
  1317. "Add a delay in microseconds after each SPI I/O"),
  1318. OPT_WITH_ARG("--minion-spireset",
  1319. opt_set_charp, NULL, &opt_minion_spireset,
  1320. "SPI regular reset: iNNN for I/O count or sNNN for seconds - 0 means none"),
  1321. OPT_WITH_ARG("--minion-spisleep",
  1322. set_int_0_to_9999, opt_show_intval, &opt_minion_spisleep,
  1323. "Sleep time in milliseconds when doing an SPI reset"),
  1324. OPT_WITH_ARG("--minion-spiusec",
  1325. set_int_0_to_9999, NULL, &opt_minion_spiusec,
  1326. opt_hidden),
  1327. OPT_WITH_ARG("--minion-temp",
  1328. opt_set_charp, NULL, &opt_minion_temp,
  1329. "Set minion chip temperature threshold, single value or comma list, range 120-160 (default: 135C)"),
  1330. #endif
  1331. #if defined(unix) || defined(__APPLE__)
  1332. OPT_WITH_ARG("--monitor|-m",
  1333. opt_set_charp, NULL, &opt_stderr_cmd,
  1334. "Use custom pipe cmd for output messages"),
  1335. #endif // defined(unix)
  1336. #ifdef USE_BITFURY
  1337. OPT_WITH_ARG("--nfu-bits",
  1338. set_int_32_to_63, opt_show_intval, &opt_nfu_bits,
  1339. "Set nanofury bits for overclocking, range 32-63"),
  1340. #endif
  1341. OPT_WITHOUT_ARG("--net-delay",
  1342. opt_set_bool, &opt_delaynet,
  1343. "Impose small delays in networking to not overload slow routers"),
  1344. OPT_WITHOUT_ARG("--no-pool-disable",
  1345. opt_set_invbool, &opt_disable_pool,
  1346. opt_hidden),
  1347. OPT_WITHOUT_ARG("--no-submit-stale",
  1348. opt_set_invbool, &opt_submit_stale,
  1349. "Don't submit shares if they are detected as stale"),
  1350. #ifdef USE_BITFURY
  1351. OPT_WITH_ARG("--osm-led-mode",
  1352. set_int_0_to_4, opt_show_intval, &opt_osm_led_mode,
  1353. "Set LED mode for OneStringMiner devices"),
  1354. #endif
  1355. OPT_WITH_ARG("--pass|-p",
  1356. set_pass, NULL, &opt_set_null,
  1357. "Password for bitcoin JSON-RPC server"),
  1358. OPT_WITHOUT_ARG("--per-device-stats",
  1359. opt_set_bool, &want_per_device_stats,
  1360. "Force verbose mode and output per-device statistics"),
  1361. OPT_WITH_ARG("--pools",
  1362. opt_set_bool, NULL, &opt_set_null, opt_hidden),
  1363. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1364. opt_set_bool, &opt_protocol,
  1365. "Verbose dump of protocol-level activities"),
  1366. OPT_WITH_ARG("--queue|-Q",
  1367. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1368. "Maximum number of work items to have queued"),
  1369. OPT_WITHOUT_ARG("--quiet|-q",
  1370. opt_set_bool, &opt_quiet,
  1371. "Disable logging output, display status and errors"),
  1372. OPT_WITH_ARG("--quota|-U",
  1373. set_quota, NULL, &opt_set_null,
  1374. "quota;URL combination for server with load-balance strategy quotas"),
  1375. OPT_WITHOUT_ARG("--real-quiet",
  1376. opt_set_bool, &opt_realquiet,
  1377. "Disable all output"),
  1378. OPT_WITH_ARG("--retries",
  1379. set_null, NULL, &opt_set_null,
  1380. opt_hidden),
  1381. OPT_WITH_ARG("--retry-pause",
  1382. set_null, NULL, &opt_set_null,
  1383. opt_hidden),
  1384. #ifdef USE_ICARUS
  1385. OPT_WITH_ARG("--rock-freq",
  1386. set_float_125_to_500, &opt_show_floatval, &opt_rock_freq,
  1387. "Set RockMiner frequency in MHz, range 125-500"),
  1388. #endif
  1389. OPT_WITH_ARG("--rotate",
  1390. set_rotate, NULL, &opt_set_null,
  1391. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1392. OPT_WITHOUT_ARG("--round-robin",
  1393. set_rr, &pool_strategy,
  1394. "Change multipool strategy from failover to round robin on failure"),
  1395. #ifdef USE_FPGA_SERIAL
  1396. OPT_WITH_CBARG("--scan-serial|-S",
  1397. add_serial, NULL, &opt_add_serial,
  1398. "Serial port to probe for Serial FPGA Mining device"),
  1399. #endif
  1400. OPT_WITH_ARG("--scan-time|-s",
  1401. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1402. "Upper bound on time spent scanning current work, in seconds"),
  1403. OPT_WITH_CBARG("--sched-start",
  1404. set_sched_start, NULL, &opt_set_sched_start,
  1405. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1406. OPT_WITH_CBARG("--sched-stop",
  1407. set_sched_stop, NULL, &opt_set_sched_stop,
  1408. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1409. OPT_WITHOUT_ARG("--sha256",
  1410. opt_set_bool, &opt_sha256,
  1411. "Use the SHA-256 algorithm for mining"),
  1412. #ifdef USE_SCRYPT
  1413. OPT_WITHOUT_ARG("--scrypt",
  1414. opt_set_bool, &opt_scrypt,
  1415. "Use the scrypt algorithm for mining"),
  1416. #endif
  1417. OPT_WITH_CBARG("--sharelog",
  1418. set_sharelog, NULL, &opt_set_sharelog,
  1419. "Append share log to file"),
  1420. OPT_WITH_ARG("--shares",
  1421. opt_set_intval, NULL, &opt_shares,
  1422. "Quit after mining N shares (default: unlimited)"),
  1423. OPT_WITH_ARG("--socks-proxy",
  1424. opt_set_charp, NULL, &opt_socks_proxy,
  1425. "Set socks4 proxy (host:port)"),
  1426. OPT_WITH_ARG("--suggest-diff",
  1427. opt_set_intval, NULL, &opt_suggest_diff,
  1428. "Suggest miner difficulty for pool to user (default: none)"),
  1429. #ifdef HAVE_SYSLOG_H
  1430. OPT_WITHOUT_ARG("--syslog",
  1431. opt_set_bool, &use_syslog,
  1432. "Use system log for output messages (default: standard error)"),
  1433. #endif
  1434. #if defined(USE_BITFORCE) || defined(USE_MODMINER) || defined(USE_BFLSC)
  1435. OPT_WITH_CBARG("--temp-cutoff",
  1436. set_temp_cutoff, opt_show_intval, &opt_set_temp_cutoff,
  1437. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  1438. #endif
  1439. OPT_WITHOUT_ARG("--text-only|-T",
  1440. opt_set_invbool, &use_curses,
  1441. #ifdef HAVE_CURSES
  1442. "Disable ncurses formatted screen output"
  1443. #else
  1444. opt_hidden
  1445. #endif
  1446. ),
  1447. OPT_WITH_ARG("--url|-o",
  1448. set_url, NULL, &opt_set_null,
  1449. "URL for bitcoin JSON-RPC server"),
  1450. #ifdef USE_USBUTILS
  1451. OPT_WITH_ARG("--usb",
  1452. opt_set_charp, NULL, &opt_usb_select,
  1453. "USB device selection"),
  1454. OPT_WITH_ARG("--usb-dump",
  1455. set_int_0_to_10, opt_show_intval, &opt_usbdump,
  1456. opt_hidden),
  1457. OPT_WITHOUT_ARG("--usb-list-all",
  1458. opt_set_bool, &opt_usb_list_all,
  1459. opt_hidden),
  1460. #endif
  1461. OPT_WITH_ARG("--user|-u",
  1462. set_user, NULL, &opt_set_null,
  1463. "Username for bitcoin JSON-RPC server"),
  1464. OPT_WITH_ARG("--userpass|-O",
  1465. set_userpass, NULL, &opt_set_null,
  1466. "Username:Password pair for bitcoin JSON-RPC server"),
  1467. OPT_WITHOUT_ARG("--verbose",
  1468. opt_set_bool, &opt_log_output,
  1469. "Log verbose output to stderr as well as status output"),
  1470. OPT_WITHOUT_ARG("--widescreen",
  1471. opt_set_bool, &opt_widescreen,
  1472. "Use extra wide display without toggling"),
  1473. OPT_WITHOUT_ARG("--worktime",
  1474. opt_set_bool, &opt_worktime,
  1475. "Display extra work time debug information"),
  1476. #ifdef USE_ZEUS
  1477. OPT_WITH_ARG("--zeus-chips",
  1478. set_int_1_to_1024, NULL, &opt_zeus_chips_count,
  1479. "Number of Zeus chips per device"),
  1480. OPT_WITH_ARG("--zeus-clock",
  1481. opt_set_intval, NULL, &opt_zeus_chip_clk,
  1482. "Zeus chip clock speed (MHz)"),
  1483. OPT_WITHOUT_ARG("--zeus-debug",
  1484. opt_set_bool, &opt_zeus_debug,
  1485. "Enable extra Zeus driver debugging output in verbose mode"),
  1486. OPT_WITHOUT_ARG("--zeus-nocheck-golden",
  1487. opt_set_bool, &opt_zeus_nocheck_golden,
  1488. "Skip golden nonce verification during initialization"),
  1489. OPT_WITH_ARG("--zeus-options",
  1490. opt_set_charp, NULL, &opt_zeus_options,
  1491. "Set individual Zeus device options: ID,chips,clock[;ID,chips,clock...]"),
  1492. #endif
  1493. #ifdef USE_LKETC
  1494. OPT_WITH_ARG("--lketc-chips",
  1495. set_int_1_to_1024, NULL, &opt_lketc_chips_count,
  1496. "Number of LKETC chips per device"),
  1497. OPT_WITH_ARG("--lketc-clock",
  1498. opt_set_intval, NULL, &opt_lketc_chip_clk,
  1499. "LKETC chip clock speed (MHz)"),
  1500. OPT_WITHOUT_ARG("--lketc-debug",
  1501. opt_set_bool, &opt_lketc_debug,
  1502. "Enable extra LKETC driver debugging output in verbose mode"),
  1503. OPT_WITHOUT_ARG("--lketc-nocheck-golden",
  1504. opt_set_bool, &opt_lketc_nocheck_golden,
  1505. "Skip golden nonce verification during initialization"),
  1506. OPT_WITH_ARG("--lketc-options",
  1507. opt_set_charp, NULL, &opt_lketc_options,
  1508. "Set individual LKETC device options: ID,chips,clock[;ID,chips,clock...]"),
  1509. #endif
  1510. OPT_ENDTABLE
  1511. };
  1512. static char *load_config(const char *arg, void __maybe_unused *unused);
  1513. static int fileconf_load;
  1514. static char *parse_config(json_t *config, bool fileconf)
  1515. {
  1516. static char err_buf[200];
  1517. struct opt_table *opt;
  1518. const char *str;
  1519. json_t *val;
  1520. if (fileconf && !fileconf_load)
  1521. fileconf_load = 1;
  1522. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1523. char *p, *name;
  1524. /* We don't handle subtables. */
  1525. assert(!(opt->type & OPT_SUBTABLE));
  1526. if (!opt->names)
  1527. continue;
  1528. /* Pull apart the option name(s). */
  1529. name = strdup(opt->names);
  1530. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1531. char *err = NULL;
  1532. /* Ignore short options. */
  1533. if (p[1] != '-')
  1534. continue;
  1535. val = json_object_get(config, p+2);
  1536. if (!val)
  1537. continue;
  1538. if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_string(val)) {
  1539. str = json_string_value(val);
  1540. err = opt->cb_arg(str, opt->u.arg);
  1541. if (opt->type == OPT_PROCESSARG)
  1542. opt_set_charp(str, opt->u.arg);
  1543. } else if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_array(val)) {
  1544. json_t *arr_val;
  1545. size_t index;
  1546. json_array_foreach(val, index, arr_val) {
  1547. if (json_is_string(arr_val)) {
  1548. str = json_string_value(arr_val);
  1549. err = opt->cb_arg(str, opt->u.arg);
  1550. if (opt->type == OPT_PROCESSARG)
  1551. opt_set_charp(str, opt->u.arg);
  1552. } else if (json_is_object(arr_val))
  1553. err = parse_config(arr_val, false);
  1554. if (err)
  1555. break;
  1556. }
  1557. } else if ((opt->type & OPT_NOARG) && json_is_true(val))
  1558. err = opt->cb(opt->u.arg);
  1559. else
  1560. err = "Invalid value";
  1561. if (err) {
  1562. /* Allow invalid values to be in configuration
  1563. * file, just skipping over them provided the
  1564. * JSON is still valid after that. */
  1565. if (fileconf) {
  1566. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1567. fileconf_load = -1;
  1568. } else {
  1569. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  1570. p, err);
  1571. return err_buf;
  1572. }
  1573. }
  1574. }
  1575. free(name);
  1576. }
  1577. val = json_object_get(config, JSON_INCLUDE_CONF);
  1578. if (val && json_is_string(val))
  1579. return load_config(json_string_value(val), NULL);
  1580. return NULL;
  1581. }
  1582. char *cnfbuf = NULL;
  1583. #ifdef HAVE_LIBCURL
  1584. char conf_web1[] = "http://";
  1585. char conf_web2[] = "https://";
  1586. static char *load_web_config(const char *arg)
  1587. {
  1588. json_t *val = json_web_config(arg);
  1589. if (!val || !json_is_object(val))
  1590. return JSON_WEB_ERROR;
  1591. if (!cnfbuf)
  1592. cnfbuf = strdup(arg);
  1593. config_loaded = true;
  1594. return parse_config(val, true);
  1595. }
  1596. #endif
  1597. static char *load_config(const char *arg, void __maybe_unused *unused)
  1598. {
  1599. json_error_t err;
  1600. json_t *config;
  1601. char *json_error;
  1602. size_t siz;
  1603. #ifdef HAVE_LIBCURL
  1604. if (strncasecmp(arg, conf_web1, sizeof(conf_web1)-1) == 0 ||
  1605. strncasecmp(arg, conf_web2, sizeof(conf_web2)-1) == 0)
  1606. return load_web_config(arg);
  1607. #endif
  1608. if (!cnfbuf)
  1609. cnfbuf = strdup(arg);
  1610. if (++include_count > JSON_MAX_DEPTH)
  1611. return JSON_MAX_DEPTH_ERR;
  1612. config = json_load_file(arg, 0, &err);
  1613. if (!json_is_object(config)) {
  1614. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  1615. json_error = malloc(siz);
  1616. if (!json_error)
  1617. quit(1, "Malloc failure in json error");
  1618. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  1619. return json_error;
  1620. }
  1621. config_loaded = true;
  1622. /* Parse the config now, so we can override it. That can keep pointers
  1623. * so don't free config object. */
  1624. return parse_config(config, true);
  1625. }
  1626. static char *set_default_config(const char *arg)
  1627. {
  1628. opt_set_charp(arg, &default_config);
  1629. return NULL;
  1630. }
  1631. void default_save_file(char *filename);
  1632. static void load_default_config(void)
  1633. {
  1634. cnfbuf = malloc(PATH_MAX);
  1635. default_save_file(cnfbuf);
  1636. if (!access(cnfbuf, R_OK))
  1637. load_config(cnfbuf, NULL);
  1638. else {
  1639. free(cnfbuf);
  1640. cnfbuf = NULL;
  1641. }
  1642. }
  1643. extern const char *opt_argv0;
  1644. static char *opt_verusage_and_exit(const char *extra)
  1645. {
  1646. printf("%s\nBuilt with "
  1647. #ifdef USE_ANT_S1
  1648. "ant.S1 "
  1649. #endif
  1650. #ifdef USE_ANT_S2
  1651. "ant.S2 "
  1652. #endif
  1653. #ifdef USE_AVALON
  1654. "avalon "
  1655. #endif
  1656. #ifdef USE_AVALON2
  1657. "avalon2 "
  1658. #endif
  1659. #ifdef USE_BFLSC
  1660. "bflsc "
  1661. #endif
  1662. #ifdef USE_BITFORCE
  1663. "bitforce "
  1664. #endif
  1665. #ifdef USE_BITFURY
  1666. "bitfury "
  1667. #endif
  1668. #ifdef USE_COINTERRA
  1669. "cointerra "
  1670. #endif
  1671. #ifdef USE_DRILLBIT
  1672. "drillbit "
  1673. #endif
  1674. #ifdef USE_HASHFAST
  1675. "hashfast "
  1676. #endif
  1677. #ifdef USE_ICARUS
  1678. "icarus "
  1679. #endif
  1680. #ifdef USE_KLONDIKE
  1681. "klondike "
  1682. #endif
  1683. #ifdef USE_KNC
  1684. "KnC "
  1685. #endif
  1686. #ifdef USE_BAB
  1687. "BaB "
  1688. #endif
  1689. #ifdef USE_MINION
  1690. "minion "
  1691. #endif
  1692. #ifdef USE_MODMINER
  1693. "modminer "
  1694. #endif
  1695. #ifdef USE_BITMINE_A1
  1696. "Bitmine.A1 "
  1697. #endif
  1698. #ifdef USE_SP10
  1699. "spondoolies "
  1700. #endif
  1701. #ifdef USE_SP30
  1702. "sp30 "
  1703. #endif
  1704. #ifdef USE_GRIDSEED
  1705. "GridSeed "
  1706. #endif
  1707. #ifdef USE_ZEUS
  1708. "Zeus "
  1709. #endif
  1710. #ifdef USE_LKETC
  1711. "Lketc "
  1712. #endif
  1713. #ifdef USE_SCRYPT
  1714. "scrypt "
  1715. #endif
  1716. "mining support.\n"
  1717. , packagename);
  1718. printf("%s", opt_usage(opt_argv0, extra));
  1719. fflush(stdout);
  1720. exit(0);
  1721. }
  1722. #if defined(USE_USBUTILS)
  1723. char *display_devs(int *ndevs)
  1724. {
  1725. *ndevs = 0;
  1726. usb_all(0);
  1727. exit(*ndevs);
  1728. }
  1729. #endif
  1730. /* These options are available from commandline only */
  1731. static struct opt_table opt_cmdline_table[] = {
  1732. OPT_WITH_ARG("--config|-c",
  1733. load_config, NULL, &opt_set_null,
  1734. "Load a JSON-format configuration file\n"
  1735. "See example.conf for an example configuration."),
  1736. OPT_WITH_ARG("--default-config",
  1737. set_default_config, NULL, &opt_set_null,
  1738. "Specify the filename of the default config file\n"
  1739. "Loaded at start and used when saving without a name."),
  1740. OPT_WITHOUT_ARG("--help|-h",
  1741. opt_verusage_and_exit, NULL,
  1742. "Print this message"),
  1743. #if defined(USE_USBUTILS)
  1744. OPT_WITHOUT_ARG("--ndevs|-n",
  1745. display_devs, &nDevs,
  1746. "Display all USB devices and exit"),
  1747. #endif
  1748. OPT_WITHOUT_ARG("--version|-V",
  1749. opt_version_and_exit, packagename,
  1750. "Display version and exit"),
  1751. OPT_ENDTABLE
  1752. };
  1753. #ifdef HAVE_LIBCURL
  1754. static bool jobj_binary(const json_t *obj, const char *key,
  1755. void *buf, size_t buflen, bool required)
  1756. {
  1757. const char *hexstr;
  1758. json_t *tmp;
  1759. tmp = json_object_get(obj, key);
  1760. if (unlikely(!tmp)) {
  1761. if (unlikely(required))
  1762. applog(LOG_ERR, "JSON key '%s' not found", key);
  1763. return false;
  1764. }
  1765. hexstr = json_string_value(tmp);
  1766. if (unlikely(!hexstr)) {
  1767. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1768. return false;
  1769. }
  1770. if (!hex2bin(buf, hexstr, buflen))
  1771. return false;
  1772. return true;
  1773. }
  1774. #endif
  1775. static void calc_midstate(struct work *work)
  1776. {
  1777. unsigned char data[64];
  1778. uint32_t *data32 = (uint32_t *)data;
  1779. sha256_ctx ctx;
  1780. flip64(data32, work->data);
  1781. sha256_init(&ctx);
  1782. sha256_update(&ctx, data, 64);
  1783. memcpy(work->midstate, ctx.h, 32);
  1784. endian_flip32(work->midstate, work->midstate);
  1785. }
  1786. /* Returns the current value of total_work and increments it */
  1787. static int total_work_inc(void)
  1788. {
  1789. int ret;
  1790. cg_wlock(&control_lock);
  1791. ret = total_work++;
  1792. cg_wunlock(&control_lock);
  1793. return ret;
  1794. }
  1795. static struct work *make_work(void)
  1796. {
  1797. struct work *work = calloc(1, sizeof(struct work));
  1798. if (unlikely(!work))
  1799. quit(1, "Failed to calloc work in make_work");
  1800. work->id = total_work_inc();
  1801. return work;
  1802. }
  1803. /* This is the central place all work that is about to be retired should be
  1804. * cleaned to remove any dynamically allocated arrays within the struct */
  1805. void clean_work(struct work *work)
  1806. {
  1807. free(work->job_id);
  1808. free(work->ntime);
  1809. free(work->coinbase);
  1810. free(work->nonce1);
  1811. memset(work, 0, sizeof(struct work));
  1812. }
  1813. /* All dynamically allocated work structs should be freed here to not leak any
  1814. * ram from arrays allocated within the work struct */
  1815. void _free_work(struct work *work)
  1816. {
  1817. clean_work(work);
  1818. free(work);
  1819. }
  1820. static void gen_hash(unsigned char *data, unsigned char *hash, int len);
  1821. static void calc_diff(struct work *work, double known);
  1822. char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
  1823. #ifdef HAVE_LIBCURL
  1824. /* Process transactions with GBT by storing the binary value of the first
  1825. * transaction, and the hashes of the remaining transactions since these
  1826. * remain constant with an altered coinbase when generating work. Must be
  1827. * entered under gbt_lock */
  1828. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr);
  1829. static void __build_gbt_txns(struct pool *pool, json_t *res_val)
  1830. {
  1831. json_t *txn_array;
  1832. txn_array = json_object_get(res_val, "transactions");
  1833. gbt_merkle_bins(pool, txn_array);
  1834. }
  1835. static void __gbt_merkleroot(struct pool *pool, unsigned char *merkle_root)
  1836. {
  1837. unsigned char merkle_sha[64];
  1838. int i;
  1839. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  1840. memcpy(merkle_sha, merkle_root, 32);
  1841. for (i = 0; i < pool->merkles; i++) {
  1842. memcpy(merkle_sha + 32, pool->merklebin + i * 32, 32);
  1843. gen_hash(merkle_sha, merkle_root, 64);
  1844. memcpy(merkle_sha, merkle_root, 32);
  1845. }
  1846. }
  1847. static bool work_decode(struct pool *pool, struct work *work, json_t *val);
  1848. static void update_gbt(struct pool *pool)
  1849. {
  1850. int rolltime;
  1851. json_t *val;
  1852. CURL *curl;
  1853. curl = curl_easy_init();
  1854. if (unlikely(!curl))
  1855. quit (1, "CURL initialisation failed in update_gbt");
  1856. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  1857. pool->rpc_req, true, false, &rolltime, pool, false);
  1858. if (val) {
  1859. struct work *work = make_work();
  1860. bool rc = work_decode(pool, work, val);
  1861. total_getworks++;
  1862. pool->getwork_requested++;
  1863. if (rc) {
  1864. applog(LOG_DEBUG, "Successfully retrieved and updated GBT from pool %u %s",
  1865. pool->pool_no, pool->rpc_url);
  1866. if (pool == current_pool())
  1867. opt_work_update = true;
  1868. } else {
  1869. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher GBT from pool %u %s",
  1870. pool->pool_no, pool->rpc_url);
  1871. }
  1872. json_decref(val);
  1873. free_work(work);
  1874. } else {
  1875. applog(LOG_DEBUG, "FAILED to update GBT from pool %u %s",
  1876. pool->pool_no, pool->rpc_url);
  1877. }
  1878. curl_easy_cleanup(curl);
  1879. }
  1880. static void gen_gbt_work(struct pool *pool, struct work *work)
  1881. {
  1882. unsigned char merkleroot[32];
  1883. struct timeval now;
  1884. uint64_t nonce2le;
  1885. cgtime(&now);
  1886. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  1887. update_gbt(pool);
  1888. cg_wlock(&pool->gbt_lock);
  1889. nonce2le = htole64(pool->nonce2);
  1890. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  1891. pool->nonce2++;
  1892. cg_dwlock(&pool->gbt_lock);
  1893. __gbt_merkleroot(pool, merkleroot);
  1894. memcpy(work->data, &pool->gbt_version, 4);
  1895. memcpy(work->data + 4, pool->previousblockhash, 32);
  1896. memcpy(work->data + 4 + 32 + 32, &pool->curtime, 4);
  1897. memcpy(work->data + 4 + 32 + 32 + 4, &pool->gbt_bits, 4);
  1898. memcpy(work->target, pool->gbt_target, 32);
  1899. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  1900. /* For encoding the block data on submission */
  1901. work->gbt_txns = pool->gbt_txns + 1;
  1902. if (pool->gbt_workid)
  1903. work->job_id = strdup(pool->gbt_workid);
  1904. cg_runlock(&pool->gbt_lock);
  1905. flip32(work->data + 4 + 32, merkleroot);
  1906. memset(work->data + 4 + 32 + 32 + 4 + 4, 0, 4); /* nonce */
  1907. hex2bin(work->data + 4 + 32 + 32 + 4 + 4 + 4, workpadding, 48);
  1908. if (opt_debug) {
  1909. char *header = bin2hex(work->data, 128);
  1910. applog(LOG_DEBUG, "Generated GBT header %s", header);
  1911. applog(LOG_DEBUG, "Work coinbase %s", work->coinbase);
  1912. free(header);
  1913. }
  1914. calc_midstate(work);
  1915. local_work++;
  1916. work->pool = pool;
  1917. work->gbt = true;
  1918. work->longpoll = false;
  1919. work->getwork_mode = GETWORK_MODE_GBT;
  1920. work->work_block = work_block;
  1921. /* Nominally allow a driver to ntime roll 60 seconds */
  1922. work->drv_rolllimit = 60;
  1923. calc_diff(work, 0);
  1924. cgtime(&work->tv_staged);
  1925. }
  1926. static bool gbt_decode(struct pool *pool, json_t *res_val)
  1927. {
  1928. const char *previousblockhash;
  1929. const char *target;
  1930. const char *coinbasetxn;
  1931. const char *longpollid;
  1932. unsigned char hash_swap[32];
  1933. int expires;
  1934. int version;
  1935. int curtime;
  1936. bool submitold;
  1937. const char *bits;
  1938. const char *workid;
  1939. int cbt_len, orig_len;
  1940. uint8_t *extra_len;
  1941. size_t cal_len;
  1942. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  1943. target = json_string_value(json_object_get(res_val, "target"));
  1944. coinbasetxn = json_string_value(json_object_get(json_object_get(res_val, "coinbasetxn"), "data"));
  1945. longpollid = json_string_value(json_object_get(res_val, "longpollid"));
  1946. expires = json_integer_value(json_object_get(res_val, "expires"));
  1947. version = json_integer_value(json_object_get(res_val, "version"));
  1948. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  1949. submitold = json_is_true(json_object_get(res_val, "submitold"));
  1950. bits = json_string_value(json_object_get(res_val, "bits"));
  1951. workid = json_string_value(json_object_get(res_val, "workid"));
  1952. if (!previousblockhash || !target || !coinbasetxn || !longpollid ||
  1953. !expires || !version || !curtime || !bits) {
  1954. applog(LOG_ERR, "JSON failed to decode GBT");
  1955. return false;
  1956. }
  1957. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  1958. applog(LOG_DEBUG, "target: %s", target);
  1959. applog(LOG_DEBUG, "coinbasetxn: %s", coinbasetxn);
  1960. applog(LOG_DEBUG, "longpollid: %s", longpollid);
  1961. applog(LOG_DEBUG, "expires: %d", expires);
  1962. applog(LOG_DEBUG, "version: %d", version);
  1963. applog(LOG_DEBUG, "curtime: %d", curtime);
  1964. applog(LOG_DEBUG, "submitold: %s", submitold ? "true" : "false");
  1965. applog(LOG_DEBUG, "bits: %s", bits);
  1966. if (workid)
  1967. applog(LOG_DEBUG, "workid: %s", workid);
  1968. cg_wlock(&pool->gbt_lock);
  1969. free(pool->coinbasetxn);
  1970. pool->coinbasetxn = strdup(coinbasetxn);
  1971. cbt_len = strlen(pool->coinbasetxn) / 2;
  1972. /* We add 8 bytes of extra data corresponding to nonce2 */
  1973. pool->n2size = 8;
  1974. pool->coinbase_len = cbt_len + pool->n2size;
  1975. cal_len = pool->coinbase_len + 1;
  1976. align_len(&cal_len);
  1977. free(pool->coinbase);
  1978. pool->coinbase = calloc(cal_len, 1);
  1979. if (unlikely(!pool->coinbase))
  1980. quit(1, "Failed to calloc pool coinbase in gbt_decode");
  1981. hex2bin(pool->coinbase, pool->coinbasetxn, 42);
  1982. extra_len = (uint8_t *)(pool->coinbase + 41);
  1983. orig_len = *extra_len;
  1984. hex2bin(pool->coinbase + 42, pool->coinbasetxn + 84, orig_len);
  1985. *extra_len += pool->n2size;
  1986. hex2bin(pool->coinbase + 42 + *extra_len, pool->coinbasetxn + 84 + (orig_len * 2),
  1987. cbt_len - orig_len - 42);
  1988. pool->nonce2_offset = orig_len + 42;
  1989. free(pool->longpollid);
  1990. pool->longpollid = strdup(longpollid);
  1991. free(pool->gbt_workid);
  1992. if (workid)
  1993. pool->gbt_workid = strdup(workid);
  1994. else
  1995. pool->gbt_workid = NULL;
  1996. hex2bin(hash_swap, previousblockhash, 32);
  1997. swap256(pool->previousblockhash, hash_swap);
  1998. hex2bin(hash_swap, target, 32);
  1999. swab256(pool->gbt_target, hash_swap);
  2000. pool->gbt_expires = expires;
  2001. pool->gbt_version = htobe32(version);
  2002. pool->curtime = htobe32(curtime);
  2003. pool->submit_old = submitold;
  2004. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  2005. __build_gbt_txns(pool, res_val);
  2006. cg_wunlock(&pool->gbt_lock);
  2007. return true;
  2008. }
  2009. static bool getwork_decode(json_t *res_val, struct work *work)
  2010. {
  2011. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2012. applog(LOG_ERR, "JSON inval data");
  2013. return false;
  2014. }
  2015. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2016. // Calculate it ourselves
  2017. applog(LOG_DEBUG, "Calculating midstate locally");
  2018. calc_midstate(work);
  2019. }
  2020. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2021. applog(LOG_ERR, "JSON inval target");
  2022. return false;
  2023. }
  2024. return true;
  2025. }
  2026. /* Returns whether the pool supports local work generation or not. */
  2027. static bool pool_localgen(struct pool *pool)
  2028. {
  2029. return (pool->has_stratum || pool->has_gbt || pool->gbt_solo);
  2030. }
  2031. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr)
  2032. {
  2033. unsigned char *hashbin;
  2034. json_t *arr_val;
  2035. int i, j, binleft, binlen;
  2036. free(pool->txn_data);
  2037. pool->txn_data = NULL;
  2038. pool->transactions = 0;
  2039. pool->merkles = 0;
  2040. pool->transactions = json_array_size(transaction_arr);
  2041. binlen = pool->transactions * 32 + 32;
  2042. hashbin = alloca(binlen + 32);
  2043. memset(hashbin, 0, 32);
  2044. binleft = binlen / 32;
  2045. if (pool->transactions) {
  2046. int len = 0, ofs = 0;
  2047. const char *txn;
  2048. for (i = 0; i < pool->transactions; i++) {
  2049. arr_val = json_array_get(transaction_arr, i);
  2050. txn = json_string_value(json_object_get(arr_val, "data"));
  2051. if (!txn) {
  2052. applog(LOG_ERR, "Pool %d json_string_value fail - cannot find transaction data",
  2053. pool->pool_no);
  2054. return;
  2055. }
  2056. len += strlen(txn);
  2057. }
  2058. pool->txn_data = malloc(len + 1);
  2059. if (unlikely(!pool->txn_data))
  2060. quit(1, "Failed to calloc txn_data in gbt_merkle_bins");
  2061. pool->txn_data[len] = '\0';
  2062. for (i = 0; i < pool->transactions; i++) {
  2063. unsigned char binswap[32];
  2064. const char *hash;
  2065. arr_val = json_array_get(transaction_arr, i);
  2066. hash = json_string_value(json_object_get(arr_val, "hash"));
  2067. txn = json_string_value(json_object_get(arr_val, "data"));
  2068. len = strlen(txn);
  2069. memcpy(pool->txn_data + ofs, txn, len);
  2070. ofs += len;
  2071. if (!hash) {
  2072. unsigned char *txn_bin;
  2073. int txn_len;
  2074. txn_len = len / 2;
  2075. txn_bin = malloc(txn_len);
  2076. if (!txn_bin)
  2077. quit(1, "Failed to malloc txn_bin in gbt_merkle_bins");
  2078. hex2bin(txn_bin, txn, txn_len);
  2079. /* This is needed for pooled mining since only
  2080. * transaction data and not hashes are sent */
  2081. gen_hash(txn_bin, hashbin + 32 + 32 * i, txn_len);
  2082. continue;
  2083. }
  2084. if (!hex2bin(binswap, hash, 32)) {
  2085. applog(LOG_ERR, "Failed to hex2bin hash in gbt_merkle_bins");
  2086. return;
  2087. }
  2088. swab256(hashbin + 32 + 32 * i, binswap);
  2089. }
  2090. }
  2091. if (binleft > 1) {
  2092. while (42) {
  2093. if (binleft == 1)
  2094. break;
  2095. memcpy(pool->merklebin + (pool->merkles * 32), hashbin + 32, 32);
  2096. pool->merkles++;
  2097. if (binleft % 2) {
  2098. memcpy(hashbin + binlen, hashbin + binlen - 32, 32);
  2099. binlen += 32;
  2100. binleft++;
  2101. }
  2102. for (i = 32, j = 64; j < binlen; i += 32, j += 64) {
  2103. gen_hash(hashbin + j, hashbin + i, 64);
  2104. }
  2105. binleft /= 2;
  2106. binlen = binleft * 32;
  2107. }
  2108. }
  2109. if (opt_debug) {
  2110. char hashhex[68];
  2111. for (i = 0; i < pool->merkles; i++) {
  2112. __bin2hex(hashhex, pool->merklebin + i * 32, 32);
  2113. applog(LOG_DEBUG, "MH%d %s",i, hashhex);
  2114. }
  2115. }
  2116. applog(LOG_INFO, "Stored %d transactions from pool %d", pool->transactions,
  2117. pool->pool_no);
  2118. }
  2119. static double diff_from_target(void *target);
  2120. static const char scriptsig_header[] = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff";
  2121. static unsigned char scriptsig_header_bin[41];
  2122. static bool gbt_solo_decode(struct pool *pool, json_t *res_val)
  2123. {
  2124. json_t *transaction_arr, *coinbase_aux;
  2125. const char *previousblockhash;
  2126. unsigned char hash_swap[32];
  2127. struct timeval now;
  2128. const char *target;
  2129. uint64_t coinbasevalue;
  2130. const char *flags;
  2131. const char *bits;
  2132. char header[228];
  2133. int ofs = 0, len;
  2134. uint64_t *u64;
  2135. uint32_t *u32;
  2136. int version;
  2137. int curtime;
  2138. int height;
  2139. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  2140. target = json_string_value(json_object_get(res_val, "target"));
  2141. transaction_arr = json_object_get(res_val, "transactions");
  2142. version = json_integer_value(json_object_get(res_val, "version"));
  2143. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  2144. bits = json_string_value(json_object_get(res_val, "bits"));
  2145. height = json_integer_value(json_object_get(res_val, "height"));
  2146. coinbasevalue = json_integer_value(json_object_get(res_val, "coinbasevalue"));
  2147. coinbase_aux = json_object_get(res_val, "coinbaseaux");
  2148. flags = json_string_value(json_object_get(coinbase_aux, "flags"));
  2149. if (!previousblockhash || !target || !version || !curtime || !bits || !coinbase_aux || !flags) {
  2150. applog(LOG_ERR, "Pool %d JSON failed to decode GBT", pool->pool_no);
  2151. return false;
  2152. }
  2153. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  2154. applog(LOG_DEBUG, "target: %s", target);
  2155. applog(LOG_DEBUG, "version: %d", version);
  2156. applog(LOG_DEBUG, "curtime: %d", curtime);
  2157. applog(LOG_DEBUG, "bits: %s", bits);
  2158. applog(LOG_DEBUG, "height: %d", height);
  2159. applog(LOG_DEBUG, "flags: %s", flags);
  2160. cg_wlock(&pool->gbt_lock);
  2161. hex2bin(hash_swap, previousblockhash, 32);
  2162. swap256(pool->previousblockhash, hash_swap);
  2163. __bin2hex(pool->prev_hash, pool->previousblockhash, 32);
  2164. hex2bin(hash_swap, target, 32);
  2165. swab256(pool->gbt_target, hash_swap);
  2166. pool->sdiff = diff_from_target(pool->gbt_target);
  2167. pool->gbt_version = htobe32(version);
  2168. pool->curtime = htobe32(curtime);
  2169. snprintf(pool->ntime, 9, "%08x", curtime);
  2170. snprintf(pool->bbversion, 9, "%08x", version);
  2171. snprintf(pool->nbit, 9, "%s", bits);
  2172. pool->nValue = coinbasevalue;
  2173. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  2174. gbt_merkle_bins(pool, transaction_arr);
  2175. pool->height = height;
  2176. memset(pool->scriptsig_base, 0, 42);
  2177. ofs++; // Leave room for template length
  2178. /* Put block height at start of template. */
  2179. ofs += ser_number(pool->scriptsig_base + ofs, height); // max 5
  2180. /* Followed by flags */
  2181. len = strlen(flags) / 2;
  2182. pool->scriptsig_base[ofs++] = len;
  2183. hex2bin(pool->scriptsig_base + ofs, flags, len);
  2184. ofs += len;
  2185. /* Followed by timestamp */
  2186. cgtime(&now);
  2187. pool->scriptsig_base[ofs++] = 0xfe; // Encode seconds as u32
  2188. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  2189. *u32 = htole32(now.tv_sec);
  2190. ofs += 4; // sizeof uint32_t
  2191. pool->scriptsig_base[ofs++] = 0xfe; // Encode usecs as u32
  2192. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  2193. *u32 = htole32(now.tv_usec);
  2194. ofs += 4; // sizeof uint32_t
  2195. memcpy(pool->scriptsig_base + ofs, "\x09\x63\x67\x6d\x69\x6e\x65\x72\x34\x32", 10);
  2196. ofs += 10;
  2197. /* Followed by extranonce size, fixed at 8 */
  2198. pool->scriptsig_base[ofs++] = 8;
  2199. pool->nonce2_offset = 41 + ofs;
  2200. ofs += 8;
  2201. if (opt_btc_sig) {
  2202. len = strlen(opt_btc_sig);
  2203. if (len > 32)
  2204. len = 32;
  2205. pool->scriptsig_base[ofs++] = len;
  2206. memcpy(pool->scriptsig_base + ofs, opt_btc_sig, len);
  2207. ofs += len;
  2208. }
  2209. pool->scriptsig_base[0] = ofs++; // Template length
  2210. pool->n1_len = ofs;
  2211. len = 41 // prefix
  2212. + ofs // Template length
  2213. + 4 // txin sequence no
  2214. + 1 // transactions
  2215. + 8 // value
  2216. + 1 + 25 // txout
  2217. + 4; // lock
  2218. free(pool->coinbase);
  2219. pool->coinbase = calloc(len, 1);
  2220. if (unlikely(!pool->coinbase))
  2221. quit(1, "Failed to calloc coinbase in gbt_solo_decode");
  2222. memcpy(pool->coinbase + 41, pool->scriptsig_base, ofs);
  2223. memcpy(pool->coinbase + 41 + ofs, "\xff\xff\xff\xff", 4);
  2224. pool->coinbase[41 + ofs + 4] = 1;
  2225. u64 = (uint64_t *)&(pool->coinbase[41 + ofs + 4 + 1]);
  2226. *u64 = htole64(coinbasevalue);
  2227. pool->nonce2 = 0;
  2228. pool->n2size = 4;
  2229. pool->coinbase_len = 41 + ofs + 4 + 1 + 8 + 1 + 25 + 4;
  2230. cg_wunlock(&pool->gbt_lock);
  2231. snprintf(header, 225, "%s%s%s%s%s%s%s",
  2232. pool->bbversion,
  2233. pool->prev_hash,
  2234. "0000000000000000000000000000000000000000000000000000000000000000",
  2235. pool->ntime,
  2236. pool->nbit,
  2237. "00000000", /* nonce */
  2238. workpadding);
  2239. if (unlikely(!hex2bin(pool->header_bin, header, 112)))
  2240. quit(1, "Failed to hex2bin header in gbt_solo_decode");
  2241. return true;
  2242. }
  2243. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2244. {
  2245. json_t *res_val = json_object_get(val, "result");
  2246. bool ret = false;
  2247. cgtime(&pool->tv_lastwork);
  2248. if (!res_val || json_is_null(res_val)) {
  2249. applog(LOG_ERR, "JSON Failed to decode result");
  2250. goto out;
  2251. }
  2252. if (pool->gbt_solo) {
  2253. if (unlikely(!gbt_solo_decode(pool, res_val)))
  2254. goto out;
  2255. ret = true;
  2256. goto out;
  2257. } else if (pool->has_gbt) {
  2258. if (unlikely(!gbt_decode(pool, res_val)))
  2259. goto out;
  2260. work->gbt = true;
  2261. ret = true;
  2262. goto out;
  2263. } else if (unlikely(!getwork_decode(res_val, work)))
  2264. goto out;
  2265. memset(work->hash, 0, sizeof(work->hash));
  2266. cgtime(&work->tv_staged);
  2267. ret = true;
  2268. out:
  2269. return ret;
  2270. }
  2271. #else /* HAVE_LIBCURL */
  2272. /* Always true with stratum */
  2273. #define pool_localgen(pool) (true)
  2274. #define json_rpc_call(curl, url, userpass, rpc_req, probe, longpoll, rolltime, pool, share) (NULL)
  2275. #define work_decode(pool, work, val) (false)
  2276. #define gen_gbt_work(pool, work) {}
  2277. #endif /* HAVE_LIBCURL */
  2278. int dev_from_id(int thr_id)
  2279. {
  2280. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2281. return cgpu->device_id;
  2282. }
  2283. /* Create an exponentially decaying average over the opt_log_interval */
  2284. void decay_time(double *f, double fadd, double fsecs, double interval)
  2285. {
  2286. double ftotal, fprop;
  2287. if (fsecs <= 0)
  2288. return;
  2289. fprop = 1.0 - 1 / (exp(fsecs / interval));
  2290. ftotal = 1.0 + fprop;
  2291. *f += (fadd / fsecs * fprop);
  2292. *f /= ftotal;
  2293. }
  2294. static int __total_staged(void)
  2295. {
  2296. return HASH_COUNT(staged_work);
  2297. }
  2298. static int total_staged(void)
  2299. {
  2300. int ret;
  2301. mutex_lock(stgd_lock);
  2302. ret = __total_staged();
  2303. mutex_unlock(stgd_lock);
  2304. return ret;
  2305. }
  2306. #ifdef HAVE_CURSES
  2307. WINDOW *mainwin, *statuswin, *logwin;
  2308. #endif
  2309. double total_secs = 1.0;
  2310. static char statusline[256];
  2311. /* logstart is where the log window should start */
  2312. static int devcursor, logstart, logcursor;
  2313. #ifdef HAVE_CURSES
  2314. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2315. static int statusy;
  2316. #endif
  2317. #ifdef HAVE_CURSES
  2318. static inline void unlock_curses(void)
  2319. {
  2320. mutex_unlock(&console_lock);
  2321. }
  2322. static inline void lock_curses(void)
  2323. {
  2324. mutex_lock(&console_lock);
  2325. }
  2326. static bool curses_active_locked(void)
  2327. {
  2328. bool ret;
  2329. lock_curses();
  2330. ret = curses_active;
  2331. if (!ret)
  2332. unlock_curses();
  2333. return ret;
  2334. }
  2335. #endif
  2336. /* Convert a uint64_t value into a truncated string for displaying with its
  2337. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  2338. static void suffix_string(uint64_t val, char *buf, size_t bufsiz, int sigdigits)
  2339. {
  2340. const double dkilo = 1000.0;
  2341. const uint64_t kilo = 1000ull;
  2342. const uint64_t mega = 1000000ull;
  2343. const uint64_t giga = 1000000000ull;
  2344. const uint64_t tera = 1000000000000ull;
  2345. const uint64_t peta = 1000000000000000ull;
  2346. const uint64_t exa = 1000000000000000000ull;
  2347. char suffix[2] = "";
  2348. bool decimal = true;
  2349. double dval;
  2350. if (val >= exa) {
  2351. val /= peta;
  2352. dval = (double)val / dkilo;
  2353. strcpy(suffix, "E");
  2354. } else if (val >= peta) {
  2355. val /= tera;
  2356. dval = (double)val / dkilo;
  2357. strcpy(suffix, "P");
  2358. } else if (val >= tera) {
  2359. val /= giga;
  2360. dval = (double)val / dkilo;
  2361. strcpy(suffix, "T");
  2362. } else if (val >= giga) {
  2363. val /= mega;
  2364. dval = (double)val / dkilo;
  2365. strcpy(suffix, "G");
  2366. } else if (val >= mega) {
  2367. val /= kilo;
  2368. dval = (double)val / dkilo;
  2369. strcpy(suffix, "M");
  2370. } else if (val >= kilo) {
  2371. dval = (double)val / dkilo;
  2372. strcpy(suffix, "K");
  2373. } else {
  2374. dval = val;
  2375. decimal = false;
  2376. }
  2377. if (!sigdigits) {
  2378. if (decimal)
  2379. snprintf(buf, bufsiz, "%.3g%s", dval, suffix);
  2380. else
  2381. snprintf(buf, bufsiz, "%d%s", (unsigned int)dval, suffix);
  2382. } else {
  2383. /* Always show sigdigits + 1, padded on right with zeroes
  2384. * followed by suffix */
  2385. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  2386. snprintf(buf, bufsiz, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  2387. }
  2388. }
  2389. double cgpu_runtime(struct cgpu_info *cgpu)
  2390. {
  2391. struct timeval now;
  2392. double dev_runtime;
  2393. if (cgpu->dev_start_tv.tv_sec == 0)
  2394. dev_runtime = total_secs;
  2395. else {
  2396. cgtime(&now);
  2397. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  2398. }
  2399. if (dev_runtime < 1.0)
  2400. dev_runtime = 1.0;
  2401. return dev_runtime;
  2402. }
  2403. double tsince_restart(void)
  2404. {
  2405. struct timeval now;
  2406. cgtime(&now);
  2407. return tdiff(&now, &restart_tv_start);
  2408. }
  2409. double tsince_update(void)
  2410. {
  2411. struct timeval now;
  2412. cgtime(&now);
  2413. return tdiff(&now, &update_tv_start);
  2414. }
  2415. static void get_statline(char *buf, size_t bufsiz, struct cgpu_info *cgpu)
  2416. {
  2417. char displayed_hashes[16], displayed_rolling[16];
  2418. double dev_runtime, wu;
  2419. uint64_t dh64, dr64;
  2420. dev_runtime = cgpu_runtime(cgpu);
  2421. wu = cgpu->diff1 / dev_runtime * 60.0;
  2422. dh64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2423. dr64 = (double)cgpu->rolling * 1000000ull;
  2424. suffix_string(dh64, displayed_hashes, sizeof(displayed_hashes), 4);
  2425. suffix_string(dr64, displayed_rolling, sizeof(displayed_rolling), 4);
  2426. snprintf(buf, bufsiz, "%s%d ", cgpu->drv->name, cgpu->device_id);
  2427. cgpu->drv->get_statline_before(buf, bufsiz, cgpu);
  2428. tailsprintf(buf, bufsiz, "(%ds):%s (avg):%sh/s | A:%.0f R:%.0f HW:%d WU:%.1f/m",
  2429. opt_log_interval,
  2430. displayed_rolling,
  2431. displayed_hashes,
  2432. cgpu->diff_accepted,
  2433. cgpu->diff_rejected,
  2434. cgpu->hw_errors,
  2435. wu);
  2436. cgpu->drv->get_statline(buf, bufsiz, cgpu);
  2437. }
  2438. static bool shared_strategy(void)
  2439. {
  2440. return (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE);
  2441. }
  2442. #ifdef HAVE_CURSES
  2443. #define CURBUFSIZ 256
  2444. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  2445. char tmp42[CURBUFSIZ]; \
  2446. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  2447. mvwprintw(win, y, x, "%s", tmp42); \
  2448. } while (0)
  2449. #define cg_wprintw(win, fmt, ...) do { \
  2450. char tmp42[CURBUFSIZ]; \
  2451. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  2452. wprintw(win, "%s", tmp42); \
  2453. } while (0)
  2454. /* Must be called with curses mutex lock held and curses_active */
  2455. static void curses_print_status(void)
  2456. {
  2457. struct pool *pool = current_pool();
  2458. int linewidth = opt_widescreen ? 100 : 80;
  2459. wattron(statuswin, A_BOLD);
  2460. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  2461. wattroff(statuswin, A_BOLD);
  2462. mvwhline(statuswin, 1, 0, '-', linewidth);
  2463. cg_mvwprintw(statuswin, 2, 0, " %s", statusline);
  2464. wclrtoeol(statuswin);
  2465. if (opt_widescreen) {
  2466. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m |"
  2467. " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  2468. total_diff_accepted, total_diff_rejected, hw_errors,
  2469. total_diff1 / total_secs * 60,
  2470. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  2471. } else if (alt_status) {
  2472. cg_mvwprintw(statuswin, 3, 0, " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  2473. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  2474. } else {
  2475. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m",
  2476. total_diff_accepted, total_diff_rejected, hw_errors,
  2477. total_diff1 / total_secs * 60);
  2478. }
  2479. wclrtoeol(statuswin);
  2480. if (shared_strategy() && total_pools > 1) {
  2481. cg_mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s block change notify",
  2482. have_longpoll ? "": "out");
  2483. } else if (pool->has_stratum) {
  2484. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  2485. pool->sockaddr_url, pool->diff, pool->rpc_user);
  2486. } else {
  2487. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s %s as user %s",
  2488. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out",
  2489. pool->has_gbt ? "GBT" : "LP", pool->rpc_user);
  2490. }
  2491. wclrtoeol(statuswin);
  2492. cg_mvwprintw(statuswin, 5, 0, " Block: %s... Diff:%s Started: %s Best share: %s ",
  2493. prev_block, block_diff, blocktime, best_share);
  2494. mvwhline(statuswin, 6, 0, '-', linewidth);
  2495. mvwhline(statuswin, statusy - 1, 0, '-', linewidth);
  2496. #ifdef USE_USBUTILS
  2497. cg_mvwprintw(statuswin, devcursor - 1, 1, "[U]SB management [P]ool management [S]ettings [D]isplay options [Q]uit");
  2498. #else
  2499. cg_mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management [S]ettings [D]isplay options [Q]uit");
  2500. #endif
  2501. }
  2502. static void adj_width(int var, int *length)
  2503. {
  2504. if ((int)(log10(var) + 1) > *length)
  2505. (*length)++;
  2506. }
  2507. static void adj_fwidth(float var, int *length)
  2508. {
  2509. if ((int)(log10(var) + 1) > *length)
  2510. (*length)++;
  2511. }
  2512. #define STATBEFORELEN 23
  2513. const char blanks[] = " ";
  2514. static void curses_print_devstatus(struct cgpu_info *cgpu, int devno, int count)
  2515. {
  2516. static int devno_width = 1, uid_width = 4, dawidth = 1, drwidth = 1, hwwidth = 1, wuwidth = 1;
  2517. char logline[256], unique_id[16];
  2518. struct timeval now;
  2519. double dev_runtime, wu;
  2520. unsigned int devstatlen;
  2521. if (opt_compact)
  2522. return;
  2523. if (devcursor + count > LINES - 2)
  2524. return;
  2525. if (count >= most_devices)
  2526. return;
  2527. if (cgpu->dev_start_tv.tv_sec == 0)
  2528. dev_runtime = total_secs;
  2529. else {
  2530. cgtime(&now);
  2531. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  2532. }
  2533. if (dev_runtime < 1.0)
  2534. dev_runtime = 1.0;
  2535. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2536. wu = cgpu->diff1 / dev_runtime * 60;
  2537. wmove(statuswin,devcursor + count, 0);
  2538. adj_width(devno, &devno_width);
  2539. if (cgpu->unique_id) {
  2540. if (uid_width < 12 && (int)strlen(cgpu->unique_id) > uid_width)
  2541. uid_width = MIN(strlen(cgpu->unique_id), 12); // maximum length 12
  2542. unique_id[4] = '\0';
  2543. memcpy(unique_id, blanks, 4); // minimum length 4
  2544. strncpy(unique_id, cgpu->unique_id, uid_width);
  2545. unique_id[uid_width] = '\0';
  2546. } else {
  2547. adj_width(cgpu->device_id, &uid_width);
  2548. if (uid_width < 4)
  2549. uid_width = 4;
  2550. if (uid_width > 12)
  2551. uid_width = 12;
  2552. sprintf(unique_id, "%-*d", uid_width, cgpu->device_id);
  2553. }
  2554. cg_wprintw(statuswin, " %*d: %s %-*s: ", devno_width, devno, cgpu->drv->name,
  2555. uid_width, unique_id);
  2556. logline[0] = '\0';
  2557. cgpu->drv->get_statline_before(logline, sizeof(logline), cgpu);
  2558. devstatlen = strlen(logline);
  2559. if (devstatlen < STATBEFORELEN)
  2560. strncat(logline, blanks, STATBEFORELEN - devstatlen);
  2561. cg_wprintw(statuswin, "%s | ", logline);
  2562. #ifdef USE_USBUTILS
  2563. if (cgpu->usbinfo.nodev)
  2564. cg_wprintw(statuswin, "ZOMBIE");
  2565. else
  2566. #endif
  2567. if (cgpu->status == LIFE_DEAD)
  2568. cg_wprintw(statuswin, "DEAD ");
  2569. else if (cgpu->status == LIFE_SICK)
  2570. cg_wprintw(statuswin, "SICK ");
  2571. else if (cgpu->deven == DEV_DISABLED)
  2572. cg_wprintw(statuswin, "OFF ");
  2573. else if (cgpu->deven == DEV_RECOVER)
  2574. cg_wprintw(statuswin, "REST ");
  2575. else if (opt_widescreen) {
  2576. char displayed_hashes[16], displayed_rolling[16];
  2577. uint64_t d64;
  2578. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2579. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  2580. d64 = (double)cgpu->rolling * 1000000ull;
  2581. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  2582. adj_width(wu, &wuwidth);
  2583. adj_fwidth(cgpu->diff_accepted, &dawidth);
  2584. adj_fwidth(cgpu->diff_rejected, &drwidth);
  2585. adj_width(cgpu->hw_errors, &hwwidth);
  2586. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m "
  2587. "A:%*.0f R:%*.0f HW:%*d",
  2588. displayed_rolling,
  2589. displayed_hashes, wuwidth + 2, wu,
  2590. dawidth, cgpu->diff_accepted,
  2591. drwidth, cgpu->diff_rejected,
  2592. hwwidth, cgpu->hw_errors);
  2593. } else if (!alt_status) {
  2594. char displayed_hashes[16], displayed_rolling[16];
  2595. uint64_t d64;
  2596. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2597. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  2598. d64 = (double)cgpu->rolling * 1000000ull;
  2599. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  2600. adj_width(wu, &wuwidth);
  2601. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m", displayed_rolling,
  2602. displayed_hashes, wuwidth + 2, wu);
  2603. } else {
  2604. adj_fwidth(cgpu->diff_accepted, &dawidth);
  2605. adj_fwidth(cgpu->diff_rejected, &drwidth);
  2606. adj_width(cgpu->hw_errors, &hwwidth);
  2607. cg_wprintw(statuswin, "A:%*.0f R:%*.0f HW:%*d",
  2608. dawidth, cgpu->diff_accepted,
  2609. drwidth, cgpu->diff_rejected,
  2610. hwwidth, cgpu->hw_errors);
  2611. }
  2612. logline[0] = '\0';
  2613. cgpu->drv->get_statline(logline, sizeof(logline), cgpu);
  2614. cg_wprintw(statuswin, "%s", logline);
  2615. wclrtoeol(statuswin);
  2616. }
  2617. #endif
  2618. #ifdef HAVE_CURSES
  2619. /* Check for window resize. Called with curses mutex locked */
  2620. static inline void change_logwinsize(void)
  2621. {
  2622. int x, y, logx, logy;
  2623. getmaxyx(mainwin, y, x);
  2624. if (x < 80 || y < 25)
  2625. return;
  2626. if (y > statusy + 2 && statusy < logstart) {
  2627. if (y - 2 < logstart)
  2628. statusy = y - 2;
  2629. else
  2630. statusy = logstart;
  2631. logcursor = statusy + 1;
  2632. mvwin(logwin, logcursor, 0);
  2633. wresize(statuswin, statusy, x);
  2634. }
  2635. y -= logcursor;
  2636. getmaxyx(logwin, logy, logx);
  2637. /* Detect screen size change */
  2638. if (x != logx || y != logy)
  2639. wresize(logwin, y, x);
  2640. }
  2641. static void check_winsizes(void)
  2642. {
  2643. if (!use_curses)
  2644. return;
  2645. if (curses_active_locked()) {
  2646. int y, x;
  2647. erase();
  2648. x = getmaxx(statuswin);
  2649. if (logstart > LINES - 2)
  2650. statusy = LINES - 2;
  2651. else
  2652. statusy = logstart;
  2653. logcursor = statusy;
  2654. wresize(statuswin, statusy, x);
  2655. getmaxyx(mainwin, y, x);
  2656. y -= logcursor;
  2657. wresize(logwin, y, x);
  2658. mvwin(logwin, logcursor, 0);
  2659. unlock_curses();
  2660. }
  2661. }
  2662. static void disable_curses_windows(void);
  2663. static void enable_curses_windows(void);
  2664. static void switch_logsize(bool __maybe_unused newdevs)
  2665. {
  2666. if (curses_active_locked()) {
  2667. #ifdef WIN32
  2668. if (newdevs)
  2669. disable_curses_windows();
  2670. #endif
  2671. if (opt_compact) {
  2672. logstart = devcursor + 1;
  2673. logcursor = logstart + 1;
  2674. } else {
  2675. logstart = devcursor + most_devices + 1;
  2676. logcursor = logstart + 1;
  2677. }
  2678. #ifdef WIN32
  2679. if (newdevs)
  2680. enable_curses_windows();
  2681. #endif
  2682. unlock_curses();
  2683. check_winsizes();
  2684. }
  2685. }
  2686. /* For mandatory printing when mutex is already locked */
  2687. void _wlog(const char *str)
  2688. {
  2689. wprintw(logwin, "%s", str);
  2690. }
  2691. /* Mandatory printing */
  2692. void _wlogprint(const char *str)
  2693. {
  2694. if (curses_active_locked()) {
  2695. wprintw(logwin, "%s", str);
  2696. unlock_curses();
  2697. }
  2698. }
  2699. #endif
  2700. #ifdef HAVE_CURSES
  2701. bool log_curses_only(int prio, const char *datetime, const char *str)
  2702. {
  2703. bool high_prio;
  2704. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  2705. if (curses_active_locked()) {
  2706. if (!opt_loginput || high_prio) {
  2707. wprintw(logwin, "%s%s\n", datetime, str);
  2708. if (high_prio) {
  2709. touchwin(logwin);
  2710. wrefresh(logwin);
  2711. }
  2712. }
  2713. unlock_curses();
  2714. return true;
  2715. }
  2716. return false;
  2717. }
  2718. void clear_logwin(void)
  2719. {
  2720. if (curses_active_locked()) {
  2721. erase();
  2722. wclear(logwin);
  2723. unlock_curses();
  2724. }
  2725. }
  2726. void logwin_update(void)
  2727. {
  2728. if (curses_active_locked()) {
  2729. touchwin(logwin);
  2730. wrefresh(logwin);
  2731. unlock_curses();
  2732. }
  2733. }
  2734. #endif
  2735. static void enable_pool(struct pool *pool)
  2736. {
  2737. if (pool->enabled != POOL_ENABLED) {
  2738. enabled_pools++;
  2739. pool->enabled = POOL_ENABLED;
  2740. }
  2741. }
  2742. #ifdef HAVE_CURSES
  2743. static void disable_pool(struct pool *pool)
  2744. {
  2745. if (pool->enabled == POOL_ENABLED)
  2746. enabled_pools--;
  2747. pool->enabled = POOL_DISABLED;
  2748. }
  2749. #endif
  2750. static void reject_pool(struct pool *pool)
  2751. {
  2752. if (pool->enabled == POOL_ENABLED)
  2753. enabled_pools--;
  2754. pool->enabled = POOL_REJECTING;
  2755. }
  2756. static void restart_threads(void);
  2757. /* Theoretically threads could race when modifying accepted and
  2758. * rejected values but the chance of two submits completing at the
  2759. * same time is zero so there is no point adding extra locking */
  2760. static void
  2761. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2762. char *hashshow, bool resubmit, char *worktime)
  2763. {
  2764. struct pool *pool = work->pool;
  2765. struct cgpu_info *cgpu;
  2766. cgpu = get_thr_cgpu(work->thr_id);
  2767. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  2768. mutex_lock(&stats_lock);
  2769. cgpu->accepted++;
  2770. total_accepted++;
  2771. pool->accepted++;
  2772. cgpu->diff_accepted += work->work_difficulty;
  2773. total_diff_accepted += work->work_difficulty;
  2774. pool->diff_accepted += work->work_difficulty;
  2775. mutex_unlock(&stats_lock);
  2776. pool->seq_rejects = 0;
  2777. cgpu->last_share_pool = pool->pool_no;
  2778. cgpu->last_share_pool_time = time(NULL);
  2779. cgpu->last_share_diff = work->work_difficulty;
  2780. pool->last_share_time = cgpu->last_share_pool_time;
  2781. pool->last_share_diff = work->work_difficulty;
  2782. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2783. if (!QUIET) {
  2784. if (total_pools > 1)
  2785. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  2786. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  2787. else
  2788. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  2789. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  2790. }
  2791. sharelog("accept", work);
  2792. if (opt_shares && total_diff_accepted >= opt_shares) {
  2793. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2794. kill_work();
  2795. return;
  2796. }
  2797. /* Detect if a pool that has been temporarily disabled for
  2798. * continually rejecting shares has started accepting shares.
  2799. * This will only happen with the work returned from a
  2800. * longpoll */
  2801. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2802. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2803. enable_pool(pool);
  2804. switch_pools(NULL);
  2805. }
  2806. /* If we know we found the block we know better than anyone
  2807. * that new work is needed. */
  2808. if (unlikely(work->block))
  2809. restart_threads();
  2810. } else {
  2811. mutex_lock(&stats_lock);
  2812. cgpu->rejected++;
  2813. total_rejected++;
  2814. pool->rejected++;
  2815. cgpu->diff_rejected += work->work_difficulty;
  2816. total_diff_rejected += work->work_difficulty;
  2817. pool->diff_rejected += work->work_difficulty;
  2818. pool->seq_rejects++;
  2819. mutex_unlock(&stats_lock);
  2820. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2821. if (!QUIET) {
  2822. char where[20];
  2823. char disposition[36] = "reject";
  2824. char reason[32];
  2825. strcpy(reason, "");
  2826. if (total_pools > 1)
  2827. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  2828. else
  2829. strcpy(where, "");
  2830. if (!work->gbt)
  2831. res = json_object_get(val, "reject-reason");
  2832. if (res) {
  2833. const char *reasontmp = json_string_value(res);
  2834. size_t reasonLen = strlen(reasontmp);
  2835. if (reasonLen > 28)
  2836. reasonLen = 28;
  2837. reason[0] = ' '; reason[1] = '(';
  2838. memcpy(2 + reason, reasontmp, reasonLen);
  2839. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2840. memcpy(disposition + 7, reasontmp, reasonLen);
  2841. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2842. } else if (work->stratum && err) {
  2843. if (json_is_array(err)) {
  2844. json_t *reason_val = json_array_get(err, 1);
  2845. char *reason_str;
  2846. if (reason_val && json_is_string(reason_val)) {
  2847. reason_str = (char *)json_string_value(reason_val);
  2848. snprintf(reason, 31, " (%s)", reason_str);
  2849. }
  2850. } else if (json_is_string(err)) {
  2851. const char *s = json_string_value(err);
  2852. snprintf(reason, 31, " (%s)", s);
  2853. }
  2854. }
  2855. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2856. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2857. sharelog(disposition, work);
  2858. }
  2859. /* Once we have more than a nominal amount of sequential rejects,
  2860. * at least 10 and more than 3 mins at the current utility,
  2861. * disable the pool because some pool error is likely to have
  2862. * ensued. Do not do this if we know the share just happened to
  2863. * be stale due to networking delays.
  2864. */
  2865. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2866. double utility = total_accepted / total_secs * 60;
  2867. if (pool->seq_rejects > utility * 3 && enabled_pools > 1) {
  2868. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2869. pool->pool_no, pool->seq_rejects);
  2870. reject_pool(pool);
  2871. if (pool == current_pool())
  2872. switch_pools(NULL);
  2873. pool->seq_rejects = 0;
  2874. }
  2875. }
  2876. }
  2877. }
  2878. static void show_hash(struct work *work, char *hashshow)
  2879. {
  2880. unsigned char rhash[32];
  2881. char diffdisp[16];
  2882. unsigned long h32;
  2883. uint32_t *hash32;
  2884. uint64_t uintdiff;
  2885. int ofs;
  2886. swab256(rhash, work->hash);
  2887. for (ofs = 0; ofs <= 28; ofs ++) {
  2888. if (rhash[ofs])
  2889. break;
  2890. }
  2891. hash32 = (uint32_t *)(rhash + ofs);
  2892. h32 = be32toh(*hash32);
  2893. uintdiff = round(work->work_difficulty);
  2894. suffix_string(work->share_diff, diffdisp, sizeof (diffdisp), 0);
  2895. snprintf(hashshow, 64, "%08lx Diff %s/%"PRIu64"%s", h32, diffdisp, uintdiff,
  2896. work->block? " BLOCK!" : "");
  2897. }
  2898. #ifdef HAVE_LIBCURL
  2899. static void text_print_status(int thr_id)
  2900. {
  2901. struct cgpu_info *cgpu;
  2902. char logline[256];
  2903. cgpu = get_thr_cgpu(thr_id);
  2904. if (cgpu) {
  2905. get_statline(logline, sizeof(logline), cgpu);
  2906. printf("%s\n", logline);
  2907. }
  2908. }
  2909. static void print_status(int thr_id)
  2910. {
  2911. if (!curses_active)
  2912. text_print_status(thr_id);
  2913. }
  2914. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2915. {
  2916. json_t *val, *res, *err;
  2917. char *s;
  2918. bool rc = false;
  2919. int thr_id = work->thr_id;
  2920. struct cgpu_info *cgpu;
  2921. struct pool *pool = work->pool;
  2922. int rolltime;
  2923. struct timeval tv_submit, tv_submit_reply;
  2924. char hashshow[64 + 4] = "";
  2925. char worktime[200] = "";
  2926. struct timeval now;
  2927. double dev_runtime;
  2928. cgpu = get_thr_cgpu(thr_id);
  2929. /* build JSON-RPC request */
  2930. if (work->gbt) {
  2931. char gbt_block[1024], varint[12];
  2932. unsigned char data[80];
  2933. flip80(data, work->data);
  2934. __bin2hex(gbt_block, data, 80); // 160 length
  2935. if (work->gbt_txns < 0xfd) {
  2936. uint8_t val8 = work->gbt_txns;
  2937. __bin2hex(varint, (const unsigned char *)&val8, 1);
  2938. } else if (work->gbt_txns <= 0xffff) {
  2939. uint16_t val16 = htole16(work->gbt_txns);
  2940. strcat(gbt_block, "fd"); // +2
  2941. __bin2hex(varint, (const unsigned char *)&val16, 2);
  2942. } else {
  2943. uint32_t val32 = htole32(work->gbt_txns);
  2944. strcat(gbt_block, "fe"); // +2
  2945. __bin2hex(varint, (const unsigned char *)&val32, 4);
  2946. }
  2947. strcat(gbt_block, varint); // +8 max
  2948. strcat(gbt_block, work->coinbase);
  2949. s = malloc(1024);
  2950. if (unlikely(!s))
  2951. quit(1, "Failed to malloc s in submit_upstream_work");
  2952. sprintf(s, "{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"%s", gbt_block);
  2953. /* Has submit/coinbase support */
  2954. if (!pool->has_gbt) {
  2955. cg_rlock(&pool->gbt_lock);
  2956. if (pool->txn_data)
  2957. s = realloc_strcat(s, pool->txn_data);
  2958. cg_runlock(&pool->gbt_lock);
  2959. }
  2960. if (work->job_id) {
  2961. s = realloc_strcat(s, "\", {\"workid\": \"");
  2962. s = realloc_strcat(s, work->job_id);
  2963. s = realloc_strcat(s, "\"}]}");
  2964. } else
  2965. s = realloc_strcat(s, "\"]}");
  2966. } else {
  2967. char *hexstr;
  2968. endian_flip128(work->data, work->data);
  2969. /* build hex string */
  2970. hexstr = bin2hex(work->data, 118);
  2971. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2972. s = realloc_strcat(s, hexstr);
  2973. s = realloc_strcat(s, "\" ], \"id\":1}");
  2974. free(hexstr);
  2975. }
  2976. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  2977. s = realloc_strcat(s, "\n");
  2978. cgtime(&tv_submit);
  2979. /* issue JSON-RPC request */
  2980. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2981. cgtime(&tv_submit_reply);
  2982. free(s);
  2983. if (unlikely(!val)) {
  2984. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2985. if (!pool_tset(pool, &pool->submit_fail)) {
  2986. total_ro++;
  2987. pool->remotefail_occasions++;
  2988. if (opt_lowmem) {
  2989. applog(LOG_WARNING, "Pool %d communication failure, discarding shares", pool->pool_no);
  2990. goto out;
  2991. }
  2992. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2993. }
  2994. cgsleep_ms(5000);
  2995. goto out;
  2996. } else if (pool_tclear(pool, &pool->submit_fail))
  2997. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2998. res = json_object_get(val, "result");
  2999. err = json_object_get(val, "error");
  3000. if (!QUIET) {
  3001. show_hash(work, hashshow);
  3002. if (opt_worktime) {
  3003. char workclone[20];
  3004. struct tm *tm, tm_getwork, tm_submit_reply;
  3005. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  3006. (struct timeval *)&(work->tv_getwork));
  3007. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  3008. (struct timeval *)&(work->tv_getwork_reply));
  3009. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  3010. (struct timeval *)&(work->tv_work_start));
  3011. double work_to_submit = tdiff(&tv_submit,
  3012. (struct timeval *)&(work->tv_work_found));
  3013. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  3014. int diffplaces = 3;
  3015. time_t tmp_time = work->tv_getwork.tv_sec;
  3016. tm = localtime(&tmp_time);
  3017. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3018. tmp_time = tv_submit_reply.tv_sec;
  3019. tm = localtime(&tmp_time);
  3020. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3021. if (work->clone) {
  3022. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  3023. tdiff((struct timeval *)&(work->tv_cloned),
  3024. (struct timeval *)&(work->tv_getwork_reply)));
  3025. }
  3026. else
  3027. strcpy(workclone, "O");
  3028. if (work->work_difficulty < 1)
  3029. diffplaces = 6;
  3030. snprintf(worktime, sizeof(worktime),
  3031. " <-%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",
  3032. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3033. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3034. work->getwork_mode, diffplaces, work->work_difficulty,
  3035. tm_getwork.tm_hour, tm_getwork.tm_min,
  3036. tm_getwork.tm_sec, getwork_time, workclone,
  3037. getwork_to_work, work_time, work_to_submit, submit_time,
  3038. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3039. tm_submit_reply.tm_sec);
  3040. }
  3041. }
  3042. share_result(val, res, err, work, hashshow, resubmit, worktime);
  3043. if (cgpu->dev_start_tv.tv_sec == 0)
  3044. dev_runtime = total_secs;
  3045. else {
  3046. cgtime(&now);
  3047. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  3048. }
  3049. if (dev_runtime < 1.0)
  3050. dev_runtime = 1.0;
  3051. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3052. if (!opt_realquiet)
  3053. print_status(thr_id);
  3054. if (!want_per_device_stats) {
  3055. char logline[256];
  3056. get_statline(logline, sizeof(logline), cgpu);
  3057. applog(LOG_INFO, "%s", logline);
  3058. }
  3059. json_decref(val);
  3060. rc = true;
  3061. out:
  3062. return rc;
  3063. }
  3064. static bool get_upstream_work(struct work *work, CURL *curl)
  3065. {
  3066. struct pool *pool = work->pool;
  3067. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  3068. struct timeval tv_elapsed;
  3069. json_t *val = NULL;
  3070. bool rc = false;
  3071. char *url;
  3072. url = pool->rpc_url;
  3073. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", url, pool->rpc_req);
  3074. cgtime(&work->tv_getwork);
  3075. val = json_rpc_call(curl, url, pool->rpc_userpass, pool->rpc_req, false,
  3076. false, &work->rolltime, pool, false);
  3077. pool_stats->getwork_attempts++;
  3078. if (likely(val)) {
  3079. rc = work_decode(pool, work, val);
  3080. if (unlikely(!rc))
  3081. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  3082. } else
  3083. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  3084. cgtime(&work->tv_getwork_reply);
  3085. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  3086. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  3087. pool_stats->getwork_wait_rolling /= 1.63;
  3088. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  3089. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  3090. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  3091. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  3092. }
  3093. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  3094. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  3095. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  3096. }
  3097. pool_stats->getwork_calls++;
  3098. work->pool = pool;
  3099. work->longpoll = false;
  3100. work->getwork_mode = GETWORK_MODE_POOL;
  3101. calc_diff(work, 0);
  3102. total_getworks++;
  3103. pool->getwork_requested++;
  3104. if (likely(val))
  3105. json_decref(val);
  3106. return rc;
  3107. }
  3108. #endif /* HAVE_LIBCURL */
  3109. /* Specifies whether we can use this pool for work or not. */
  3110. static bool pool_unworkable(struct pool *pool)
  3111. {
  3112. if (pool->idle)
  3113. return true;
  3114. if (pool->enabled != POOL_ENABLED)
  3115. return true;
  3116. if (pool->has_stratum && !pool->stratum_active)
  3117. return true;
  3118. return false;
  3119. }
  3120. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3121. * rolling average per 10 minutes and if pools start getting more, it biases
  3122. * away from them to distribute work evenly. The share count is reset to the
  3123. * rolling average every 10 minutes to not send all work to one pool after it
  3124. * has been disabled/out for an extended period. */
  3125. static struct pool *select_balanced(struct pool *cp)
  3126. {
  3127. int i, lowest = cp->shares;
  3128. struct pool *ret = cp;
  3129. for (i = 0; i < total_pools; i++) {
  3130. struct pool *pool = pools[i];
  3131. if (pool_unworkable(pool))
  3132. continue;
  3133. if (pool->shares < lowest) {
  3134. lowest = pool->shares;
  3135. ret = pool;
  3136. }
  3137. }
  3138. ret->shares++;
  3139. return ret;
  3140. }
  3141. static struct pool *priority_pool(int choice);
  3142. static bool pool_unusable(struct pool *pool);
  3143. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  3144. * it has any quota left. */
  3145. static inline struct pool *select_pool(bool lagging)
  3146. {
  3147. static int rotating_pool = 0;
  3148. struct pool *pool, *cp;
  3149. bool avail = false;
  3150. int tested, i;
  3151. cp = current_pool();
  3152. if (pool_strategy == POOL_BALANCE) {
  3153. pool = select_balanced(cp);
  3154. goto out;
  3155. }
  3156. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  3157. pool = cp;
  3158. goto out;
  3159. } else
  3160. pool = NULL;
  3161. for (i = 0; i < total_pools; i++) {
  3162. struct pool *tp = pools[i];
  3163. if (tp->quota_used < tp->quota_gcd) {
  3164. avail = true;
  3165. break;
  3166. }
  3167. }
  3168. /* There are no pools with quota, so reset them. */
  3169. if (!avail) {
  3170. for (i = 0; i < total_pools; i++)
  3171. pools[i]->quota_used = 0;
  3172. if (++rotating_pool >= total_pools)
  3173. rotating_pool = 0;
  3174. }
  3175. /* Try to find the first pool in the rotation that is usable */
  3176. tested = 0;
  3177. while (!pool && tested++ < total_pools) {
  3178. pool = pools[rotating_pool];
  3179. if (pool->quota_used++ < pool->quota_gcd) {
  3180. if (!pool_unworkable(pool))
  3181. break;
  3182. /* Failover-only flag for load-balance means distribute
  3183. * unused quota to priority pool 0. */
  3184. if (opt_fail_only)
  3185. priority_pool(0)->quota_used--;
  3186. }
  3187. pool = NULL;
  3188. if (++rotating_pool >= total_pools)
  3189. rotating_pool = 0;
  3190. }
  3191. /* If there are no alive pools with quota, choose according to
  3192. * priority. */
  3193. if (!pool) {
  3194. for (i = 0; i < total_pools; i++) {
  3195. struct pool *tp = priority_pool(i);
  3196. if (!pool_unusable(tp)) {
  3197. pool = tp;
  3198. break;
  3199. }
  3200. }
  3201. }
  3202. /* If still nothing is usable, use the current pool */
  3203. if (!pool)
  3204. pool = cp;
  3205. out:
  3206. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  3207. return pool;
  3208. }
  3209. /* truediffone == 0x00000000FFFF0000000000000000000000000000000000000000000000000000
  3210. * Generate a 256 bit binary LE target by cutting up diff into 64 bit sized
  3211. * portions or vice versa. */
  3212. static const double truediffone = 26959535291011309493156476344723991336010898738574164086137773096960.0;
  3213. static const double bits192 = 6277101735386680763835789423207666416102355444464034512896.0;
  3214. static const double bits128 = 340282366920938463463374607431768211456.0;
  3215. static const double bits64 = 18446744073709551616.0;
  3216. /* Converts a little endian 256 bit value to a double */
  3217. static double le256todouble(const void *target)
  3218. {
  3219. uint64_t *data64;
  3220. double dcut64;
  3221. data64 = (uint64_t *)(target + 24);
  3222. dcut64 = le64toh(*data64) * bits192;
  3223. data64 = (uint64_t *)(target + 16);
  3224. dcut64 += le64toh(*data64) * bits128;
  3225. data64 = (uint64_t *)(target + 8);
  3226. dcut64 += le64toh(*data64) * bits64;
  3227. data64 = (uint64_t *)(target);
  3228. dcut64 += le64toh(*data64);
  3229. return dcut64;
  3230. }
  3231. static double diff_from_target(void *target)
  3232. {
  3233. double d64, dcut64;
  3234. d64 = truediffone;
  3235. if (opt_scrypt)
  3236. d64 *= (double)65536;
  3237. dcut64 = le256todouble(target);
  3238. if (unlikely(!dcut64))
  3239. dcut64 = 1;
  3240. return d64 / dcut64;
  3241. }
  3242. /*
  3243. * Calculate the work->work_difficulty based on the work->target
  3244. */
  3245. static void calc_diff(struct work *work, double known)
  3246. {
  3247. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3248. double difficulty;
  3249. uint64_t uintdiff;
  3250. if (known)
  3251. work->work_difficulty = known;
  3252. else
  3253. work->work_difficulty = diff_from_target(work->target);
  3254. difficulty = work->work_difficulty;
  3255. pool_stats->last_diff = difficulty;
  3256. uintdiff = round(difficulty);
  3257. suffix_string(uintdiff, work->pool->diff, sizeof(work->pool->diff), 0);
  3258. if (difficulty == pool_stats->min_diff)
  3259. pool_stats->min_diff_count++;
  3260. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3261. pool_stats->min_diff = difficulty;
  3262. pool_stats->min_diff_count = 1;
  3263. }
  3264. if (difficulty == pool_stats->max_diff)
  3265. pool_stats->max_diff_count++;
  3266. else if (difficulty > pool_stats->max_diff) {
  3267. pool_stats->max_diff = difficulty;
  3268. pool_stats->max_diff_count = 1;
  3269. }
  3270. }
  3271. static unsigned char bench_hidiff_bins[16][160];
  3272. static unsigned char bench_lodiff_bins[16][160];
  3273. static unsigned char bench_target[32];
  3274. /* Iterate over the lo and hi diff benchmark work items such that we find one
  3275. * diff 32+ share every 32 work items. */
  3276. static void get_benchmark_work(struct work *work)
  3277. {
  3278. work->work_difficulty = 32;
  3279. memcpy(work->target, bench_target, 32);
  3280. work->drv_rolllimit = 0;
  3281. work->mandatory = true;
  3282. work->pool = pools[0];
  3283. cgtime(&work->tv_getwork);
  3284. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3285. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3286. }
  3287. static void benchfile_dspwork(struct work *work, uint32_t nonce)
  3288. {
  3289. char buf[1024];
  3290. uint32_t dn;
  3291. int i;
  3292. dn = 0;
  3293. for (i = 0; i < 4; i++) {
  3294. dn *= 0x100;
  3295. dn += nonce & 0xff;
  3296. nonce /= 0x100;
  3297. }
  3298. if ((sizeof(work->data) * 2 + 1) > sizeof(buf))
  3299. quithere(1, "BENCHFILE Invalid buf size");
  3300. __bin2hex(buf, work->data, sizeof(work->data));
  3301. applog(LOG_ERR, "BENCHFILE nonce %u=0x%08x for work=%s",
  3302. (unsigned int)dn, (unsigned int)dn, buf);
  3303. }
  3304. static bool benchfile_get_work(struct work *work)
  3305. {
  3306. char buf[1024];
  3307. char item[1024];
  3308. bool got = false;
  3309. if (!benchfile_in) {
  3310. if (opt_benchfile)
  3311. benchfile_in = fopen(opt_benchfile, "r");
  3312. else
  3313. quit(1, "BENCHFILE Invalid benchfile NULL");
  3314. if (!benchfile_in)
  3315. quit(1, "BENCHFILE Failed to open benchfile '%s'", opt_benchfile);
  3316. benchfile_line = 0;
  3317. if (!fgets(buf, 1024, benchfile_in))
  3318. quit(1, "BENCHFILE Failed to read benchfile '%s'", opt_benchfile);
  3319. got = true;
  3320. benchfile_work = 0;
  3321. }
  3322. if (!got) {
  3323. if (!fgets(buf, 1024, benchfile_in)) {
  3324. if (benchfile_work == 0)
  3325. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  3326. fclose(benchfile_in);
  3327. benchfile_in = NULL;
  3328. return benchfile_get_work(work);
  3329. }
  3330. }
  3331. do {
  3332. benchfile_line++;
  3333. // Empty lines and lines starting with '#' or '/' are ignored
  3334. if (*buf != '\0' && *buf != '#' && *buf != '/') {
  3335. char *commas[BENCHWORK_COUNT];
  3336. int i, j, len;
  3337. long nonce_time;
  3338. commas[0] = buf;
  3339. for (i = 1; i < BENCHWORK_COUNT; i++) {
  3340. commas[i] = strchr(commas[i-1], ',');
  3341. if (!commas[i]) {
  3342. quit(1, "BENCHFILE Invalid input file line %d"
  3343. " - field count is %d but should be %d",
  3344. benchfile_line, i, BENCHWORK_COUNT);
  3345. }
  3346. len = commas[i] - commas[i-1];
  3347. if (benchfile_data[i-1].length &&
  3348. (len != benchfile_data[i-1].length)) {
  3349. quit(1, "BENCHFILE Invalid input file line %d "
  3350. "field %d (%s) length is %d but should be %d",
  3351. benchfile_line, i,
  3352. benchfile_data[i-1].name,
  3353. len, benchfile_data[i-1].length);
  3354. }
  3355. *(commas[i]++) = '\0';
  3356. }
  3357. // NonceTime may have LF's etc
  3358. len = strlen(commas[BENCHWORK_NONCETIME]);
  3359. if (len < benchfile_data[BENCHWORK_NONCETIME].length) {
  3360. quit(1, "BENCHFILE Invalid input file line %d field %d"
  3361. " (%s) length is %d but should be least %d",
  3362. benchfile_line, BENCHWORK_NONCETIME+1,
  3363. benchfile_data[BENCHWORK_NONCETIME].name, len,
  3364. benchfile_data[BENCHWORK_NONCETIME].length);
  3365. }
  3366. sprintf(item, "0000000%c", commas[BENCHWORK_VERSION][0]);
  3367. j = strlen(item);
  3368. for (i = benchfile_data[BENCHWORK_PREVHASH].length-8; i >= 0; i -= 8) {
  3369. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_PREVHASH][i]);
  3370. j += 8;
  3371. }
  3372. for (i = benchfile_data[BENCHWORK_MERKLEROOT].length-8; i >= 0; i -= 8) {
  3373. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_MERKLEROOT][i]);
  3374. j += 8;
  3375. }
  3376. nonce_time = atol(commas[BENCHWORK_NONCETIME]);
  3377. sprintf(&(item[j]), "%08lx", nonce_time);
  3378. j += 8;
  3379. strcpy(&(item[j]), commas[BENCHWORK_DIFFBITS]);
  3380. j += benchfile_data[BENCHWORK_DIFFBITS].length;
  3381. memset(work, 0, sizeof(*work));
  3382. hex2bin(work->data, item, j >> 1);
  3383. calc_midstate(work);
  3384. benchfile_work++;
  3385. return true;
  3386. }
  3387. } while (fgets(buf, 1024, benchfile_in));
  3388. if (benchfile_work == 0)
  3389. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  3390. fclose(benchfile_in);
  3391. benchfile_in = NULL;
  3392. return benchfile_get_work(work);
  3393. }
  3394. static void get_benchfile_work(struct work *work)
  3395. {
  3396. benchfile_get_work(work);
  3397. work->mandatory = true;
  3398. work->pool = pools[0];
  3399. cgtime(&work->tv_getwork);
  3400. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3401. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3402. calc_diff(work, 0);
  3403. }
  3404. #ifdef HAVE_CURSES
  3405. static void disable_curses_windows(void)
  3406. {
  3407. leaveok(logwin, false);
  3408. leaveok(statuswin, false);
  3409. leaveok(mainwin, false);
  3410. nocbreak();
  3411. echo();
  3412. delwin(logwin);
  3413. delwin(statuswin);
  3414. }
  3415. /* Force locking of curses console_lock on shutdown since a dead thread might
  3416. * have grabbed the lock. */
  3417. static bool curses_active_forcelocked(void)
  3418. {
  3419. bool ret;
  3420. mutex_trylock(&console_lock);
  3421. ret = curses_active;
  3422. if (!ret)
  3423. unlock_curses();
  3424. return ret;
  3425. }
  3426. static void disable_curses(void)
  3427. {
  3428. if (curses_active_forcelocked()) {
  3429. use_curses = false;
  3430. curses_active = false;
  3431. disable_curses_windows();
  3432. delwin(mainwin);
  3433. endwin();
  3434. #ifdef WIN32
  3435. // Move the cursor to after curses output.
  3436. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  3437. CONSOLE_SCREEN_BUFFER_INFO csbi;
  3438. COORD coord;
  3439. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  3440. coord.X = 0;
  3441. coord.Y = csbi.dwSize.Y - 1;
  3442. SetConsoleCursorPosition(hout, coord);
  3443. }
  3444. #endif
  3445. unlock_curses();
  3446. }
  3447. }
  3448. #endif
  3449. static void kill_timeout(struct thr_info *thr)
  3450. {
  3451. cg_completion_timeout(&thr_info_cancel, thr, 1000);
  3452. }
  3453. static void kill_mining(void)
  3454. {
  3455. struct thr_info *thr;
  3456. int i;
  3457. forcelog(LOG_DEBUG, "Killing off mining threads");
  3458. /* Kill the mining threads*/
  3459. for (i = 0; i < mining_threads; i++) {
  3460. pthread_t *pth = NULL;
  3461. thr = get_thread(i);
  3462. if (thr && PTH(thr) != 0L)
  3463. pth = &thr->pth;
  3464. thr_info_cancel(thr);
  3465. #ifndef WIN32
  3466. if (pth && *pth)
  3467. pthread_join(*pth, NULL);
  3468. #else
  3469. if (pth && pth->p)
  3470. pthread_join(*pth, NULL);
  3471. #endif
  3472. }
  3473. }
  3474. static void __kill_work(void)
  3475. {
  3476. struct thr_info *thr;
  3477. int i;
  3478. if (!successful_connect)
  3479. return;
  3480. forcelog(LOG_INFO, "Received kill message");
  3481. #ifdef USE_USBUTILS
  3482. /* Best to get rid of it first so it doesn't
  3483. * try to create any new devices */
  3484. forcelog(LOG_DEBUG, "Killing off HotPlug thread");
  3485. thr = &control_thr[hotplug_thr_id];
  3486. kill_timeout(thr);
  3487. #endif
  3488. forcelog(LOG_DEBUG, "Killing off watchpool thread");
  3489. /* Kill the watchpool thread */
  3490. thr = &control_thr[watchpool_thr_id];
  3491. kill_timeout(thr);
  3492. forcelog(LOG_DEBUG, "Killing off watchdog thread");
  3493. /* Kill the watchdog thread */
  3494. thr = &control_thr[watchdog_thr_id];
  3495. kill_timeout(thr);
  3496. forcelog(LOG_DEBUG, "Shutting down mining threads");
  3497. for (i = 0; i < mining_threads; i++) {
  3498. struct cgpu_info *cgpu;
  3499. thr = get_thread(i);
  3500. if (!thr)
  3501. continue;
  3502. cgpu = thr->cgpu;
  3503. if (!cgpu)
  3504. continue;
  3505. cgpu->shutdown = true;
  3506. }
  3507. sleep(1);
  3508. cg_completion_timeout(&kill_mining, NULL, 3000);
  3509. /* Stop the others */
  3510. forcelog(LOG_DEBUG, "Killing off API thread");
  3511. thr = &control_thr[api_thr_id];
  3512. kill_timeout(thr);
  3513. #ifdef USE_USBUTILS
  3514. /* Release USB resources in case it's a restart
  3515. * and not a QUIT */
  3516. forcelog(LOG_DEBUG, "Releasing all USB devices");
  3517. cg_completion_timeout(&usb_cleanup, NULL, 1000);
  3518. forcelog(LOG_DEBUG, "Killing off usbres thread");
  3519. thr = &control_thr[usbres_thr_id];
  3520. kill_timeout(thr);
  3521. #endif
  3522. }
  3523. /* This should be the common exit path */
  3524. void kill_work(void)
  3525. {
  3526. cg_completion_timeout(&__kill_work, NULL, 5000);
  3527. quit(0, "Shutdown signal received.");
  3528. }
  3529. static
  3530. #ifdef WIN32
  3531. const
  3532. #endif
  3533. char **initial_args;
  3534. static void clean_up(bool restarting);
  3535. void app_restart(void)
  3536. {
  3537. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  3538. cg_completion_timeout(&__kill_work, NULL, 5000);
  3539. clean_up(true);
  3540. #if defined(unix) || defined(__APPLE__)
  3541. if (forkpid > 0) {
  3542. kill(forkpid, SIGTERM);
  3543. forkpid = 0;
  3544. }
  3545. #endif
  3546. execv(initial_args[0], (EXECV_2ND_ARG_TYPE)initial_args);
  3547. applog(LOG_WARNING, "Failed to restart application");
  3548. }
  3549. static void sighandler(int __maybe_unused sig)
  3550. {
  3551. /* Restore signal handlers so we can still quit if kill_work fails */
  3552. sigaction(SIGTERM, &termhandler, NULL);
  3553. sigaction(SIGINT, &inthandler, NULL);
  3554. kill_work();
  3555. }
  3556. static void _stage_work(struct work *work);
  3557. #define stage_work(WORK) do { \
  3558. _stage_work(WORK); \
  3559. WORK = NULL; \
  3560. } while (0)
  3561. /* Adjust an existing char ntime field with a relative noffset */
  3562. static void modify_ntime(char *ntime, int noffset)
  3563. {
  3564. unsigned char bin[4];
  3565. uint32_t h32, *be32 = (uint32_t *)bin;
  3566. hex2bin(bin, ntime, 4);
  3567. h32 = be32toh(*be32) + noffset;
  3568. *be32 = htobe32(h32);
  3569. __bin2hex(ntime, bin, 4);
  3570. }
  3571. void roll_work(struct work *work)
  3572. {
  3573. uint32_t *work_ntime;
  3574. uint32_t ntime;
  3575. work_ntime = (uint32_t *)(work->data + 68);
  3576. ntime = be32toh(*work_ntime);
  3577. ntime++;
  3578. *work_ntime = htobe32(ntime);
  3579. local_work++;
  3580. work->rolls++;
  3581. work->nonce = 0;
  3582. applog(LOG_DEBUG, "Successfully rolled work");
  3583. /* Change the ntime field if this is stratum work */
  3584. if (work->ntime)
  3585. modify_ntime(work->ntime, 1);
  3586. /* This is now a different work item so it needs a different ID for the
  3587. * hashtable */
  3588. work->id = total_work_inc();
  3589. }
  3590. struct work *make_clone(struct work *work)
  3591. {
  3592. struct work *work_clone = copy_work(work);
  3593. work_clone->clone = true;
  3594. cgtime((struct timeval *)&(work_clone->tv_cloned));
  3595. work_clone->longpoll = false;
  3596. work_clone->mandatory = false;
  3597. /* Make cloned work appear slightly older to bias towards keeping the
  3598. * master work item which can be further rolled */
  3599. work_clone->tv_staged.tv_sec -= 1;
  3600. return work_clone;
  3601. }
  3602. #ifdef HAVE_LIBCURL
  3603. /* Called with pool_lock held. Recruit an extra curl if none are available for
  3604. * this pool. */
  3605. static void recruit_curl(struct pool *pool)
  3606. {
  3607. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  3608. if (unlikely(!ce))
  3609. quit(1, "Failed to calloc in recruit_curl");
  3610. ce->curl = curl_easy_init();
  3611. if (unlikely(!ce->curl))
  3612. quit(1, "Failed to init in recruit_curl");
  3613. list_add(&ce->node, &pool->curlring);
  3614. pool->curls++;
  3615. }
  3616. /* Grab an available curl if there is one. If not, then recruit extra curls
  3617. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  3618. * and there are already 5 curls in circulation. Limit total number to the
  3619. * number of mining threads per pool as well to prevent blasting a pool during
  3620. * network delays/outages. */
  3621. static struct curl_ent *pop_curl_entry(struct pool *pool)
  3622. {
  3623. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  3624. bool recruited = false;
  3625. struct curl_ent *ce;
  3626. mutex_lock(&pool->pool_lock);
  3627. retry:
  3628. if (!pool->curls) {
  3629. recruit_curl(pool);
  3630. recruited = true;
  3631. } else if (list_empty(&pool->curlring)) {
  3632. if (pool->curls >= curl_limit) {
  3633. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  3634. goto retry;
  3635. } else {
  3636. recruit_curl(pool);
  3637. recruited = true;
  3638. }
  3639. }
  3640. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  3641. list_del(&ce->node);
  3642. mutex_unlock(&pool->pool_lock);
  3643. if (recruited)
  3644. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  3645. return ce;
  3646. }
  3647. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  3648. {
  3649. mutex_lock(&pool->pool_lock);
  3650. list_add_tail(&ce->node, &pool->curlring);
  3651. cgtime(&ce->tv);
  3652. pthread_cond_broadcast(&pool->cr_cond);
  3653. mutex_unlock(&pool->pool_lock);
  3654. }
  3655. static bool stale_work(struct work *work, bool share);
  3656. static inline bool should_roll(struct work *work)
  3657. {
  3658. struct timeval now;
  3659. time_t expiry;
  3660. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  3661. return false;
  3662. if (work->rolltime > opt_scantime)
  3663. expiry = work->rolltime;
  3664. else
  3665. expiry = opt_scantime;
  3666. expiry = expiry * 2 / 3;
  3667. /* We shouldn't roll if we're unlikely to get one shares' duration
  3668. * work out of doing so */
  3669. cgtime(&now);
  3670. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  3671. return false;
  3672. return true;
  3673. }
  3674. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3675. * reject blocks as invalid. */
  3676. static inline bool can_roll(struct work *work)
  3677. {
  3678. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  3679. work->rolls < 7000 && !stale_work(work, false));
  3680. }
  3681. static void *submit_work_thread(void *userdata)
  3682. {
  3683. struct work *work = (struct work *)userdata;
  3684. struct pool *pool = work->pool;
  3685. bool resubmit = false;
  3686. struct curl_ent *ce;
  3687. pthread_detach(pthread_self());
  3688. RenameThread("SubmitWork");
  3689. applog(LOG_DEBUG, "Creating extra submit work thread");
  3690. ce = pop_curl_entry(pool);
  3691. /* submit solution to bitcoin via JSON-RPC */
  3692. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  3693. if (opt_lowmem) {
  3694. applog(LOG_NOTICE, "Pool %d share being discarded to minimise memory cache", pool->pool_no);
  3695. break;
  3696. }
  3697. resubmit = true;
  3698. if (stale_work(work, true)) {
  3699. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  3700. mutex_lock(&stats_lock);
  3701. total_stale++;
  3702. pool->stale_shares++;
  3703. total_diff_stale += work->work_difficulty;
  3704. pool->diff_stale += work->work_difficulty;
  3705. mutex_unlock(&stats_lock);
  3706. free_work(work);
  3707. break;
  3708. }
  3709. /* pause, then restart work-request loop */
  3710. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3711. }
  3712. push_curl_entry(ce, pool);
  3713. return NULL;
  3714. }
  3715. static bool clone_available(void)
  3716. {
  3717. struct work *work_clone = NULL, *work, *tmp;
  3718. bool cloned = false;
  3719. mutex_lock(stgd_lock);
  3720. if (!staged_rollable)
  3721. goto out_unlock;
  3722. HASH_ITER(hh, staged_work, work, tmp) {
  3723. if (can_roll(work) && should_roll(work)) {
  3724. roll_work(work);
  3725. work_clone = make_clone(work);
  3726. roll_work(work);
  3727. cloned = true;
  3728. break;
  3729. }
  3730. }
  3731. out_unlock:
  3732. mutex_unlock(stgd_lock);
  3733. if (cloned) {
  3734. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  3735. stage_work(work_clone);
  3736. }
  3737. return cloned;
  3738. }
  3739. /* Clones work by rolling it if possible, and returning a clone instead of the
  3740. * original work item which gets staged again to possibly be rolled again in
  3741. * the future */
  3742. static struct work *clone_work(struct work *work)
  3743. {
  3744. int mrs = mining_threads + opt_queue - total_staged();
  3745. struct work *work_clone;
  3746. bool cloned;
  3747. if (mrs < 1)
  3748. return work;
  3749. cloned = false;
  3750. work_clone = make_clone(work);
  3751. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  3752. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  3753. stage_work(work_clone);
  3754. roll_work(work);
  3755. work_clone = make_clone(work);
  3756. /* Roll it again to prevent duplicates should this be used
  3757. * directly later on */
  3758. roll_work(work);
  3759. cloned = true;
  3760. }
  3761. if (cloned) {
  3762. stage_work(work);
  3763. return work_clone;
  3764. }
  3765. free_work(work_clone);
  3766. return work;
  3767. }
  3768. #else /* HAVE_LIBCURL */
  3769. static void *submit_work_thread(void __maybe_unused *userdata)
  3770. {
  3771. pthread_detach(pthread_self());
  3772. return NULL;
  3773. }
  3774. #endif /* HAVE_LIBCURL */
  3775. /* Return an adjusted ntime if we're submitting work that a device has
  3776. * internally offset the ntime. */
  3777. static char *offset_ntime(const char *ntime, int noffset)
  3778. {
  3779. unsigned char bin[4];
  3780. uint32_t h32, *be32 = (uint32_t *)bin;
  3781. hex2bin(bin, ntime, 4);
  3782. h32 = be32toh(*be32) + noffset;
  3783. *be32 = htobe32(h32);
  3784. return bin2hex(bin, 4);
  3785. }
  3786. /* Duplicates any dynamically allocated arrays within the work struct to
  3787. * prevent a copied work struct from freeing ram belonging to another struct */
  3788. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  3789. {
  3790. uint32_t id = work->id;
  3791. clean_work(work);
  3792. memcpy(work, base_work, sizeof(struct work));
  3793. /* Keep the unique new id assigned during make_work to prevent copied
  3794. * work from having the same id. */
  3795. work->id = id;
  3796. if (base_work->job_id)
  3797. work->job_id = strdup(base_work->job_id);
  3798. if (base_work->nonce1)
  3799. work->nonce1 = strdup(base_work->nonce1);
  3800. if (base_work->ntime) {
  3801. /* If we are passed an noffset the binary work->data ntime and
  3802. * the work->ntime hex string need to be adjusted. */
  3803. if (noffset) {
  3804. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3805. uint32_t ntime = be32toh(*work_ntime);
  3806. ntime += noffset;
  3807. *work_ntime = htobe32(ntime);
  3808. work->ntime = offset_ntime(base_work->ntime, noffset);
  3809. } else
  3810. work->ntime = strdup(base_work->ntime);
  3811. } else if (noffset) {
  3812. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3813. uint32_t ntime = be32toh(*work_ntime);
  3814. ntime += noffset;
  3815. *work_ntime = htobe32(ntime);
  3816. }
  3817. if (base_work->coinbase)
  3818. work->coinbase = strdup(base_work->coinbase);
  3819. }
  3820. void set_work_ntime(struct work *work, int ntime)
  3821. {
  3822. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3823. *work_ntime = htobe32(ntime);
  3824. if (work->ntime) {
  3825. free(work->ntime);
  3826. work->ntime = bin2hex((unsigned char *)work_ntime, 4);
  3827. }
  3828. }
  3829. /* Generates a copy of an existing work struct, creating fresh heap allocations
  3830. * for all dynamically allocated arrays within the struct. noffset is used for
  3831. * when a driver has internally rolled the ntime, noffset is a relative value.
  3832. * The macro copy_work() calls this function with an noffset of 0. */
  3833. struct work *copy_work_noffset(struct work *base_work, int noffset)
  3834. {
  3835. struct work *work = make_work();
  3836. _copy_work(work, base_work, noffset);
  3837. return work;
  3838. }
  3839. void pool_died(struct pool *pool)
  3840. {
  3841. if (!pool_tset(pool, &pool->idle)) {
  3842. cgtime(&pool->tv_idle);
  3843. if (pool == current_pool()) {
  3844. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3845. switch_pools(NULL);
  3846. } else
  3847. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  3848. }
  3849. }
  3850. static bool stale_work(struct work *work, bool share)
  3851. {
  3852. struct timeval now;
  3853. time_t work_expiry;
  3854. struct pool *pool;
  3855. int getwork_delay;
  3856. if (opt_benchmark || opt_benchfile)
  3857. return false;
  3858. if (work->work_block != work_block) {
  3859. applog(LOG_DEBUG, "Work stale due to block mismatch");
  3860. return true;
  3861. }
  3862. /* Technically the rolltime should be correct but some pools
  3863. * advertise a broken expire= that is lower than a meaningful
  3864. * scantime */
  3865. if (work->rolltime > opt_scantime)
  3866. work_expiry = work->rolltime;
  3867. else
  3868. work_expiry = opt_expiry;
  3869. pool = work->pool;
  3870. if (!share && pool->has_stratum) {
  3871. bool same_job;
  3872. if (!pool->stratum_active || !pool->stratum_notify) {
  3873. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  3874. return true;
  3875. }
  3876. same_job = true;
  3877. cg_rlock(&pool->data_lock);
  3878. if (strcmp(work->job_id, pool->swork.job_id))
  3879. same_job = false;
  3880. cg_runlock(&pool->data_lock);
  3881. if (!same_job) {
  3882. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  3883. return true;
  3884. }
  3885. }
  3886. /* Factor in the average getwork delay of this pool, rounding it up to
  3887. * the nearest second */
  3888. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  3889. work_expiry -= getwork_delay;
  3890. if (unlikely(work_expiry < 5))
  3891. work_expiry = 5;
  3892. cgtime(&now);
  3893. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  3894. applog(LOG_DEBUG, "Work stale due to expiry");
  3895. return true;
  3896. }
  3897. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  3898. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3899. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  3900. return true;
  3901. }
  3902. return false;
  3903. }
  3904. uint64_t share_diff(const struct work *work)
  3905. {
  3906. bool new_best = false;
  3907. double d64, s64;
  3908. uint64_t ret;
  3909. d64 = truediffone;
  3910. if (opt_scrypt)
  3911. d64 *= (double)65536;
  3912. s64 = le256todouble(work->hash);
  3913. if (unlikely(!s64))
  3914. s64 = 0;
  3915. ret = round(d64 / s64);
  3916. cg_wlock(&control_lock);
  3917. if (unlikely(ret > best_diff)) {
  3918. new_best = true;
  3919. best_diff = ret;
  3920. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  3921. }
  3922. if (unlikely(ret > work->pool->best_diff))
  3923. work->pool->best_diff = ret;
  3924. cg_wunlock(&control_lock);
  3925. if (unlikely(new_best))
  3926. applog(LOG_INFO, "New best share: %s", best_share);
  3927. return ret;
  3928. }
  3929. static void regen_hash(struct work *work)
  3930. {
  3931. uint32_t *data32 = (uint32_t *)(work->data);
  3932. unsigned char swap[80];
  3933. uint32_t *swap32 = (uint32_t *)swap;
  3934. unsigned char hash1[32];
  3935. flip80(swap32, data32);
  3936. sha256(swap, 80, hash1);
  3937. sha256(hash1, 32, (unsigned char *)(work->hash));
  3938. }
  3939. static void rebuild_hash(struct work *work)
  3940. {
  3941. if (opt_scrypt)
  3942. scrypt_regenhash(work);
  3943. else
  3944. regen_hash(work);
  3945. }
  3946. static bool cnx_needed(struct pool *pool);
  3947. /* Find the pool that currently has the highest priority */
  3948. static struct pool *priority_pool(int choice)
  3949. {
  3950. struct pool *ret = NULL;
  3951. int i;
  3952. for (i = 0; i < total_pools; i++) {
  3953. struct pool *pool = pools[i];
  3954. if (pool->prio == choice) {
  3955. ret = pool;
  3956. break;
  3957. }
  3958. }
  3959. if (unlikely(!ret)) {
  3960. applog(LOG_ERR, "WTF No pool %d found!", choice);
  3961. return pools[choice];
  3962. }
  3963. return ret;
  3964. }
  3965. /* Specifies whether we can switch to this pool or not. */
  3966. static bool pool_unusable(struct pool *pool)
  3967. {
  3968. if (pool->idle)
  3969. return true;
  3970. if (pool->enabled != POOL_ENABLED)
  3971. return true;
  3972. return false;
  3973. }
  3974. void switch_pools(struct pool *selected)
  3975. {
  3976. struct pool *pool, *last_pool;
  3977. int i, pool_no, next_pool;
  3978. cg_wlock(&control_lock);
  3979. last_pool = currentpool;
  3980. pool_no = currentpool->pool_no;
  3981. /* Switch selected to pool number 0 and move the rest down */
  3982. if (selected) {
  3983. if (selected->prio != 0) {
  3984. for (i = 0; i < total_pools; i++) {
  3985. pool = pools[i];
  3986. if (pool->prio < selected->prio)
  3987. pool->prio++;
  3988. }
  3989. selected->prio = 0;
  3990. }
  3991. }
  3992. switch (pool_strategy) {
  3993. /* All of these set to the master pool */
  3994. case POOL_BALANCE:
  3995. case POOL_FAILOVER:
  3996. case POOL_LOADBALANCE:
  3997. for (i = 0; i < total_pools; i++) {
  3998. pool = priority_pool(i);
  3999. if (pool_unusable(pool))
  4000. continue;
  4001. pool_no = pool->pool_no;
  4002. break;
  4003. }
  4004. break;
  4005. /* Both of these simply increment and cycle */
  4006. case POOL_ROUNDROBIN:
  4007. case POOL_ROTATE:
  4008. if (selected && !selected->idle) {
  4009. pool_no = selected->pool_no;
  4010. break;
  4011. }
  4012. next_pool = pool_no;
  4013. /* Select the next alive pool */
  4014. for (i = 1; i < total_pools; i++) {
  4015. next_pool++;
  4016. if (next_pool >= total_pools)
  4017. next_pool = 0;
  4018. pool = pools[next_pool];
  4019. if (pool_unusable(pool))
  4020. continue;
  4021. pool_no = next_pool;
  4022. break;
  4023. }
  4024. break;
  4025. default:
  4026. break;
  4027. }
  4028. currentpool = pools[pool_no];
  4029. pool = currentpool;
  4030. cg_wunlock(&control_lock);
  4031. /* Set the lagging flag to avoid pool not providing work fast enough
  4032. * messages in failover only mode since we have to get all fresh work
  4033. * as in restart_threads */
  4034. if (opt_fail_only)
  4035. pool_tset(pool, &pool->lagging);
  4036. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4037. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  4038. if (pool_localgen(pool) || opt_fail_only)
  4039. clear_pool_work(last_pool);
  4040. }
  4041. mutex_lock(&lp_lock);
  4042. pthread_cond_broadcast(&lp_cond);
  4043. mutex_unlock(&lp_lock);
  4044. }
  4045. void _discard_work(struct work *work)
  4046. {
  4047. if (!work->clone && !work->rolls && !work->mined) {
  4048. if (work->pool) {
  4049. work->pool->discarded_work++;
  4050. work->pool->quota_used--;
  4051. work->pool->works--;
  4052. }
  4053. total_discarded++;
  4054. applog(LOG_DEBUG, "Discarded work");
  4055. } else
  4056. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  4057. free_work(work);
  4058. }
  4059. static void wake_gws(void)
  4060. {
  4061. mutex_lock(stgd_lock);
  4062. pthread_cond_signal(&gws_cond);
  4063. mutex_unlock(stgd_lock);
  4064. }
  4065. static void discard_stale(void)
  4066. {
  4067. struct work *work, *tmp;
  4068. int stale = 0;
  4069. mutex_lock(stgd_lock);
  4070. HASH_ITER(hh, staged_work, work, tmp) {
  4071. if (stale_work(work, false)) {
  4072. HASH_DEL(staged_work, work);
  4073. discard_work(work);
  4074. stale++;
  4075. }
  4076. }
  4077. pthread_cond_signal(&gws_cond);
  4078. mutex_unlock(stgd_lock);
  4079. if (stale)
  4080. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  4081. }
  4082. /* A generic wait function for threads that poll that will wait a specified
  4083. * time tdiff waiting on the pthread conditional that is broadcast when a
  4084. * work restart is required. Returns the value of pthread_cond_timedwait
  4085. * which is zero if the condition was met or ETIMEDOUT if not.
  4086. */
  4087. int restart_wait(struct thr_info *thr, unsigned int mstime)
  4088. {
  4089. struct timeval now, then, tdiff;
  4090. struct timespec abstime;
  4091. int rc;
  4092. tdiff.tv_sec = mstime / 1000;
  4093. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  4094. cgtime(&now);
  4095. timeradd(&now, &tdiff, &then);
  4096. abstime.tv_sec = then.tv_sec;
  4097. abstime.tv_nsec = then.tv_usec * 1000;
  4098. mutex_lock(&restart_lock);
  4099. if (thr->work_restart)
  4100. rc = 0;
  4101. else
  4102. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  4103. mutex_unlock(&restart_lock);
  4104. return rc;
  4105. }
  4106. static void *restart_thread(void __maybe_unused *arg)
  4107. {
  4108. struct pool *cp = current_pool();
  4109. struct cgpu_info *cgpu;
  4110. int i, mt;
  4111. pthread_detach(pthread_self());
  4112. /* Artificially set the lagging flag to avoid pool not providing work
  4113. * fast enough messages after every long poll */
  4114. pool_tset(cp, &cp->lagging);
  4115. /* Discard staged work that is now stale */
  4116. discard_stale();
  4117. rd_lock(&mining_thr_lock);
  4118. mt = mining_threads;
  4119. rd_unlock(&mining_thr_lock);
  4120. for (i = 0; i < mt; i++) {
  4121. cgpu = mining_thr[i]->cgpu;
  4122. if (unlikely(!cgpu))
  4123. continue;
  4124. if (cgpu->deven != DEV_ENABLED)
  4125. continue;
  4126. mining_thr[i]->work_restart = true;
  4127. flush_queue(cgpu);
  4128. cgpu->drv->flush_work(cgpu);
  4129. }
  4130. mutex_lock(&restart_lock);
  4131. pthread_cond_broadcast(&restart_cond);
  4132. mutex_unlock(&restart_lock);
  4133. #ifdef USE_USBUTILS
  4134. /* Cancels any cancellable usb transfers. Flagged as such it means they
  4135. * are usualy waiting on a read result and it's safe to abort the read
  4136. * early. */
  4137. cancel_usb_transfers();
  4138. #endif
  4139. return NULL;
  4140. }
  4141. /* In order to prevent a deadlock via the various drv->flush_work
  4142. * implementations we send the restart messages via a separate thread. */
  4143. static void restart_threads(void)
  4144. {
  4145. pthread_t rthread;
  4146. cgtime(&restart_tv_start);
  4147. if (unlikely(pthread_create(&rthread, NULL, restart_thread, NULL)))
  4148. quit(1, "Failed to create restart thread");
  4149. }
  4150. static void signal_work_update(void)
  4151. {
  4152. int i;
  4153. applog(LOG_INFO, "Work update message received");
  4154. cgtime(&update_tv_start);
  4155. rd_lock(&mining_thr_lock);
  4156. for (i = 0; i < mining_threads; i++)
  4157. mining_thr[i]->work_update = true;
  4158. rd_unlock(&mining_thr_lock);
  4159. }
  4160. static void set_curblock(char *hexstr, unsigned char *bedata)
  4161. {
  4162. int ofs;
  4163. cg_wlock(&ch_lock);
  4164. cgtime(&block_timeval);
  4165. strcpy(current_hash, hexstr);
  4166. memcpy(current_block, bedata, 32);
  4167. get_timestamp(blocktime, sizeof(blocktime), &block_timeval);
  4168. cg_wunlock(&ch_lock);
  4169. for (ofs = 0; ofs <= 56; ofs++) {
  4170. if (memcmp(&current_hash[ofs], "0", 1))
  4171. break;
  4172. }
  4173. strncpy(prev_block, &current_hash[ofs], 8);
  4174. prev_block[8] = '\0';
  4175. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  4176. }
  4177. /* Search to see if this string is from a block that has been seen before */
  4178. static bool block_exists(char *hexstr)
  4179. {
  4180. struct block *s;
  4181. rd_lock(&blk_lock);
  4182. HASH_FIND_STR(blocks, hexstr, s);
  4183. rd_unlock(&blk_lock);
  4184. if (s)
  4185. return true;
  4186. return false;
  4187. }
  4188. /* Tests if this work is from a block that has been seen before */
  4189. static inline bool from_existing_block(struct work *work)
  4190. {
  4191. char *hexstr = bin2hex(work->data + 8, 18);
  4192. bool ret;
  4193. ret = block_exists(hexstr);
  4194. free(hexstr);
  4195. return ret;
  4196. }
  4197. static int block_sort(struct block *blocka, struct block *blockb)
  4198. {
  4199. return blocka->block_no - blockb->block_no;
  4200. }
  4201. /* Decode the current block difficulty which is in packed form */
  4202. static void set_blockdiff(const struct work *work)
  4203. {
  4204. uint8_t pow = work->data[72];
  4205. int powdiff = (8 * (0x1d - 3)) - (8 * (pow - 3));
  4206. uint32_t diff32 = be32toh(*((uint32_t *)(work->data + 72))) & 0x00FFFFFF;
  4207. double numerator = 0xFFFFULL << powdiff;
  4208. double ddiff = numerator / (double)diff32;
  4209. if (unlikely(current_diff != ddiff)) {
  4210. suffix_string(ddiff, block_diff, sizeof(block_diff), 0);
  4211. current_diff = ddiff;
  4212. applog(LOG_NOTICE, "Network diff set to %s", block_diff);
  4213. }
  4214. }
  4215. static bool test_work_current(struct work *work)
  4216. {
  4217. struct pool *pool = work->pool;
  4218. unsigned char bedata[32];
  4219. char hexstr[68];
  4220. bool ret = true;
  4221. if (work->mandatory)
  4222. return ret;
  4223. swap256(bedata, work->data + 4);
  4224. __bin2hex(hexstr, bedata, 32);
  4225. /* Search to see if this block exists yet and if not, consider it a
  4226. * new block and set the current block details to this one */
  4227. if (!block_exists(hexstr)) {
  4228. struct block *s = calloc(sizeof(struct block), 1);
  4229. int deleted_block = 0;
  4230. if (unlikely(!s))
  4231. quit (1, "test_work_current OOM");
  4232. strcpy(s->hash, hexstr);
  4233. s->block_no = new_blocks++;
  4234. wr_lock(&blk_lock);
  4235. /* Only keep the last hour's worth of blocks in memory since
  4236. * work from blocks before this is virtually impossible and we
  4237. * want to prevent memory usage from continually rising */
  4238. if (HASH_COUNT(blocks) > 6) {
  4239. struct block *oldblock;
  4240. HASH_SORT(blocks, block_sort);
  4241. oldblock = blocks;
  4242. deleted_block = oldblock->block_no;
  4243. HASH_DEL(blocks, oldblock);
  4244. free(oldblock);
  4245. }
  4246. HASH_ADD_STR(blocks, hash, s);
  4247. set_blockdiff(work);
  4248. wr_unlock(&blk_lock);
  4249. if (deleted_block)
  4250. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  4251. set_curblock(hexstr, bedata);
  4252. /* Copy the information to this pool's prev_block since it
  4253. * knows the new block exists. */
  4254. memcpy(pool->prev_block, bedata, 32);
  4255. if (unlikely(new_blocks == 1)) {
  4256. ret = false;
  4257. goto out;
  4258. }
  4259. work->work_block = ++work_block;
  4260. if (work->longpoll) {
  4261. if (work->stratum) {
  4262. applog(LOG_NOTICE, "Stratum from pool %d detected new block",
  4263. pool->pool_no);
  4264. } else {
  4265. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
  4266. work->gbt ? "GBT " : "", work->pool->pool_no);
  4267. }
  4268. } else if (have_longpoll && !pool->gbt_solo)
  4269. applog(LOG_NOTICE, "New block detected on network before pool notification");
  4270. else if (!pool->gbt_solo)
  4271. applog(LOG_NOTICE, "New block detected on network");
  4272. restart_threads();
  4273. } else {
  4274. if (memcmp(pool->prev_block, bedata, 32)) {
  4275. /* Work doesn't match what this pool has stored as
  4276. * prev_block. Let's see if the work is from an old
  4277. * block or the pool is just learning about a new
  4278. * block. */
  4279. if (memcmp(bedata, current_block, 32)) {
  4280. /* Doesn't match current block. It's stale */
  4281. applog(LOG_DEBUG, "Stale data from pool %d", pool->pool_no);
  4282. ret = false;
  4283. } else {
  4284. /* Work is from new block and pool is up now
  4285. * current. */
  4286. applog(LOG_INFO, "Pool %d now up to date", pool->pool_no);
  4287. memcpy(pool->prev_block, bedata, 32);
  4288. }
  4289. }
  4290. #if 0
  4291. /* This isn't ideal, this pool is still on an old block but
  4292. * accepting shares from it. To maintain fair work distribution
  4293. * we work on it anyway. */
  4294. if (memcmp(bedata, current_block, 32))
  4295. applog(LOG_DEBUG, "Pool %d still on old block", pool->pool_no);
  4296. #endif
  4297. if (work->longpoll) {
  4298. work->work_block = ++work_block;
  4299. if (shared_strategy() || work->pool == current_pool()) {
  4300. if (work->stratum) {
  4301. applog(LOG_NOTICE, "Stratum from pool %d requested work restart",
  4302. pool->pool_no);
  4303. } else {
  4304. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  4305. work->gbt ? "GBT " : "", work->pool->pool_no);
  4306. }
  4307. restart_threads();
  4308. }
  4309. }
  4310. }
  4311. out:
  4312. work->longpoll = false;
  4313. return ret;
  4314. }
  4315. static int tv_sort(struct work *worka, struct work *workb)
  4316. {
  4317. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  4318. }
  4319. static bool work_rollable(struct work *work)
  4320. {
  4321. return (!work->clone && work->rolltime);
  4322. }
  4323. static bool hash_push(struct work *work)
  4324. {
  4325. bool rc = true;
  4326. mutex_lock(stgd_lock);
  4327. if (work_rollable(work))
  4328. staged_rollable++;
  4329. if (likely(!getq->frozen)) {
  4330. HASH_ADD_INT(staged_work, id, work);
  4331. HASH_SORT(staged_work, tv_sort);
  4332. } else
  4333. rc = false;
  4334. pthread_cond_broadcast(&getq->cond);
  4335. mutex_unlock(stgd_lock);
  4336. return rc;
  4337. }
  4338. static void _stage_work(struct work *work)
  4339. {
  4340. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  4341. work->work_block = work_block;
  4342. test_work_current(work);
  4343. work->pool->works++;
  4344. hash_push(work);
  4345. }
  4346. #ifdef HAVE_CURSES
  4347. int curses_int(const char *query)
  4348. {
  4349. int ret;
  4350. char *cvar;
  4351. cvar = curses_input(query);
  4352. ret = atoi(cvar);
  4353. free(cvar);
  4354. return ret;
  4355. }
  4356. #endif
  4357. #ifdef HAVE_CURSES
  4358. static bool input_pool(bool live);
  4359. #endif
  4360. #ifdef HAVE_CURSES
  4361. static void display_pool_summary(struct pool *pool)
  4362. {
  4363. double efficiency = 0.0;
  4364. if (curses_active_locked()) {
  4365. wlog("Pool: %s\n", pool->rpc_url);
  4366. if (pool->solved)
  4367. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  4368. if (!pool->has_stratum)
  4369. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  4370. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  4371. wlog(" Share submissions: %"PRId64"\n", pool->accepted + pool->rejected);
  4372. wlog(" Accepted shares: %"PRId64"\n", pool->accepted);
  4373. wlog(" Rejected shares: %"PRId64"\n", pool->rejected);
  4374. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  4375. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  4376. if (pool->accepted || pool->rejected)
  4377. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4378. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4379. if (!pool_localgen(pool))
  4380. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  4381. wlog(" Items worked on: %d\n", pool->works);
  4382. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  4383. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  4384. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  4385. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  4386. unlock_curses();
  4387. }
  4388. }
  4389. #endif
  4390. /* We can't remove the memory used for this struct pool because there may
  4391. * still be work referencing it. We just remove it from the pools list */
  4392. void remove_pool(struct pool *pool)
  4393. {
  4394. int i, last_pool = total_pools - 1;
  4395. struct pool *other;
  4396. /* Boost priority of any lower prio than this one */
  4397. for (i = 0; i < total_pools; i++) {
  4398. other = pools[i];
  4399. if (other->prio > pool->prio)
  4400. other->prio--;
  4401. }
  4402. if (pool->pool_no < last_pool) {
  4403. /* Swap the last pool for this one */
  4404. (pools[last_pool])->pool_no = pool->pool_no;
  4405. pools[pool->pool_no] = pools[last_pool];
  4406. }
  4407. /* Give it an invalid number */
  4408. pool->pool_no = total_pools;
  4409. pool->removed = true;
  4410. total_pools--;
  4411. }
  4412. /* add a mutex if this needs to be thread safe in the future */
  4413. static struct JE {
  4414. char *buf;
  4415. struct JE *next;
  4416. } *jedata = NULL;
  4417. static void json_escape_free()
  4418. {
  4419. struct JE *jeptr = jedata;
  4420. struct JE *jenext;
  4421. jedata = NULL;
  4422. while (jeptr) {
  4423. jenext = jeptr->next;
  4424. free(jeptr->buf);
  4425. free(jeptr);
  4426. jeptr = jenext;
  4427. }
  4428. }
  4429. static char *json_escape(char *str)
  4430. {
  4431. struct JE *jeptr;
  4432. char *buf, *ptr;
  4433. /* 2x is the max, may as well just allocate that */
  4434. ptr = buf = malloc(strlen(str) * 2 + 1);
  4435. jeptr = malloc(sizeof(*jeptr));
  4436. jeptr->buf = buf;
  4437. jeptr->next = jedata;
  4438. jedata = jeptr;
  4439. while (*str) {
  4440. if (*str == '\\' || *str == '"')
  4441. *(ptr++) = '\\';
  4442. *(ptr++) = *(str++);
  4443. }
  4444. *ptr = '\0';
  4445. return buf;
  4446. }
  4447. void write_config(FILE *fcfg)
  4448. {
  4449. struct opt_table *opt;
  4450. int i;
  4451. /* Write pool values */
  4452. fputs("{\n\"pools\" : [", fcfg);
  4453. for(i = 0; i < total_pools; i++) {
  4454. struct pool *pool = priority_pool(i);
  4455. if (pool->quota != 1) {
  4456. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%s%s%s%d;%s\",", i > 0 ? "," : "",
  4457. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  4458. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  4459. pool->rpc_proxy ? "|" : "",
  4460. pool->quota,
  4461. json_escape(pool->rpc_url));
  4462. } else {
  4463. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  4464. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  4465. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  4466. pool->rpc_proxy ? "|" : "",
  4467. json_escape(pool->rpc_url));
  4468. }
  4469. if (pool->extranonce_subscribe)
  4470. fputs("\n\t\t\"extranonce-subscribe\" : true,", fcfg);
  4471. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  4472. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pool->rpc_pass));
  4473. }
  4474. fputs("\n]\n", fcfg);
  4475. /* Simple bool,int and char options */
  4476. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  4477. char *p, *name = strdup(opt->names);
  4478. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  4479. if (p[1] != '-')
  4480. continue;
  4481. if (opt->desc == opt_hidden)
  4482. continue;
  4483. if (opt->type & OPT_NOARG &&
  4484. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  4485. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool))) {
  4486. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  4487. continue;
  4488. }
  4489. if (opt->type & OPT_HASARG &&
  4490. ((void *)opt->cb_arg == (void *)opt_set_intval ||
  4491. (void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  4492. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  4493. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  4494. (void *)opt->cb_arg == (void *)set_int_1_to_10 ||
  4495. (void *)opt->cb_arg == (void *)set_int_0_to_100 ||
  4496. (void *)opt->cb_arg == (void *)set_int_0_to_255 ||
  4497. (void *)opt->cb_arg == (void *)set_int_0_to_200 ||
  4498. (void *)opt->cb_arg == (void *)set_int_0_to_4 ||
  4499. (void *)opt->cb_arg == (void *)set_int_32_to_63 ||
  4500. (void *)opt->cb_arg == (void *)set_int_1_to_1024)) {
  4501. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  4502. continue;
  4503. }
  4504. if (opt->type & OPT_HASARG &&
  4505. ((void *)opt->cb_arg == (void *)set_float_125_to_500)) {
  4506. fprintf(fcfg, ",\n\"%s\" : \"%.1f\"", p+2, *(float *)opt->u.arg);
  4507. continue;
  4508. }
  4509. if (opt->type & (OPT_HASARG | OPT_PROCESSARG) &&
  4510. (opt->u.arg != &opt_set_null)) {
  4511. char *carg = *(char **)opt->u.arg;
  4512. if (carg)
  4513. fprintf(fcfg, ",\n\"%s\" : \"%s\"", p+2, json_escape(carg));
  4514. continue;
  4515. }
  4516. }
  4517. free(name);
  4518. }
  4519. /* Special case options */
  4520. if (pool_strategy == POOL_BALANCE)
  4521. fputs(",\n\"balance\" : true", fcfg);
  4522. if (pool_strategy == POOL_LOADBALANCE)
  4523. fputs(",\n\"load-balance\" : true", fcfg);
  4524. if (pool_strategy == POOL_ROUNDROBIN)
  4525. fputs(",\n\"round-robin\" : true", fcfg);
  4526. if (pool_strategy == POOL_ROTATE)
  4527. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  4528. fputs("\n}\n", fcfg);
  4529. json_escape_free();
  4530. }
  4531. void zero_bestshare(void)
  4532. {
  4533. int i;
  4534. best_diff = 0;
  4535. memset(best_share, 0, 8);
  4536. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4537. for (i = 0; i < total_pools; i++) {
  4538. struct pool *pool = pools[i];
  4539. pool->best_diff = 0;
  4540. }
  4541. }
  4542. static struct timeval tv_hashmeter;
  4543. static time_t hashdisplay_t;
  4544. void zero_stats(void)
  4545. {
  4546. int i;
  4547. cgtime(&total_tv_start);
  4548. copy_time(&tv_hashmeter, &total_tv_start);
  4549. total_rolling = 0;
  4550. rolling1 = 0;
  4551. rolling5 = 0;
  4552. rolling15 = 0;
  4553. total_mhashes_done = 0;
  4554. total_getworks = 0;
  4555. total_accepted = 0;
  4556. total_rejected = 0;
  4557. hw_errors = 0;
  4558. total_stale = 0;
  4559. total_discarded = 0;
  4560. local_work = 0;
  4561. total_go = 0;
  4562. total_ro = 0;
  4563. total_secs = 1.0;
  4564. total_diff1 = 0;
  4565. found_blocks = 0;
  4566. total_diff_accepted = 0;
  4567. total_diff_rejected = 0;
  4568. total_diff_stale = 0;
  4569. for (i = 0; i < total_pools; i++) {
  4570. struct pool *pool = pools[i];
  4571. pool->getwork_requested = 0;
  4572. pool->accepted = 0;
  4573. pool->rejected = 0;
  4574. pool->stale_shares = 0;
  4575. pool->discarded_work = 0;
  4576. pool->getfail_occasions = 0;
  4577. pool->remotefail_occasions = 0;
  4578. pool->last_share_time = 0;
  4579. pool->diff1 = 0;
  4580. pool->diff_accepted = 0;
  4581. pool->diff_rejected = 0;
  4582. pool->diff_stale = 0;
  4583. pool->last_share_diff = 0;
  4584. }
  4585. zero_bestshare();
  4586. for (i = 0; i < total_devices; ++i) {
  4587. struct cgpu_info *cgpu = get_devices(i);
  4588. copy_time(&cgpu->dev_start_tv, &total_tv_start);
  4589. mutex_lock(&hash_lock);
  4590. cgpu->total_mhashes = 0;
  4591. cgpu->accepted = 0;
  4592. cgpu->rejected = 0;
  4593. cgpu->hw_errors = 0;
  4594. cgpu->utility = 0.0;
  4595. cgpu->last_share_pool_time = 0;
  4596. cgpu->diff1 = 0;
  4597. cgpu->diff_accepted = 0;
  4598. cgpu->diff_rejected = 0;
  4599. cgpu->last_share_diff = 0;
  4600. mutex_unlock(&hash_lock);
  4601. /* Don't take any locks in the driver zero stats function, as
  4602. * it's called async from everything else and we don't want to
  4603. * deadlock. */
  4604. cgpu->drv->zero_stats(cgpu);
  4605. }
  4606. }
  4607. static void set_highprio(void)
  4608. {
  4609. #ifndef WIN32
  4610. int ret = nice(-10);
  4611. if (!ret)
  4612. applog(LOG_DEBUG, "Unable to set thread to high priority");
  4613. #else
  4614. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
  4615. #endif
  4616. }
  4617. static void set_lowprio(void)
  4618. {
  4619. #ifndef WIN32
  4620. int ret = nice(10);
  4621. if (!ret)
  4622. applog(LOG_INFO, "Unable to set thread to low priority");
  4623. #else
  4624. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
  4625. #endif
  4626. }
  4627. #ifdef HAVE_CURSES
  4628. static void display_pools(void)
  4629. {
  4630. struct pool *pool;
  4631. int selected, i;
  4632. char input;
  4633. opt_loginput = true;
  4634. immedok(logwin, true);
  4635. clear_logwin();
  4636. updated:
  4637. for (i = 0; i < total_pools; i++) {
  4638. pool = pools[i];
  4639. if (pool == current_pool())
  4640. wattron(logwin, A_BOLD);
  4641. if (pool->enabled != POOL_ENABLED)
  4642. wattron(logwin, A_DIM);
  4643. wlogprint("%d: ", pool->pool_no);
  4644. switch (pool->enabled) {
  4645. case POOL_ENABLED:
  4646. wlogprint("Enabled ");
  4647. break;
  4648. case POOL_DISABLED:
  4649. wlogprint("Disabled ");
  4650. break;
  4651. case POOL_REJECTING:
  4652. wlogprint("Rejecting ");
  4653. break;
  4654. }
  4655. wlogprint("%s Quota %d Prio %d: %s User:%s\n",
  4656. pool->idle? "Dead" : "Alive",
  4657. pool->quota,
  4658. pool->prio,
  4659. pool->rpc_url, pool->rpc_user);
  4660. wattroff(logwin, A_BOLD | A_DIM);
  4661. }
  4662. retry:
  4663. wlogprint("\nCurrent pool management strategy: %s\n",
  4664. strategies[pool_strategy].s);
  4665. if (pool_strategy == POOL_ROTATE)
  4666. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  4667. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  4668. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [Q]uota change\n");
  4669. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  4670. wlogprint("Or press any other key to continue\n");
  4671. logwin_update();
  4672. input = getch();
  4673. if (!strncasecmp(&input, "a", 1)) {
  4674. input_pool(true);
  4675. goto updated;
  4676. } else if (!strncasecmp(&input, "r", 1)) {
  4677. if (total_pools <= 1) {
  4678. wlogprint("Cannot remove last pool");
  4679. goto retry;
  4680. }
  4681. selected = curses_int("Select pool number");
  4682. if (selected < 0 || selected >= total_pools) {
  4683. wlogprint("Invalid selection\n");
  4684. goto retry;
  4685. }
  4686. pool = pools[selected];
  4687. if (pool == current_pool())
  4688. switch_pools(NULL);
  4689. if (pool == current_pool()) {
  4690. wlogprint("Unable to remove pool due to activity\n");
  4691. goto retry;
  4692. }
  4693. disable_pool(pool);
  4694. remove_pool(pool);
  4695. goto updated;
  4696. } else if (!strncasecmp(&input, "s", 1)) {
  4697. selected = curses_int("Select pool number");
  4698. if (selected < 0 || selected >= total_pools) {
  4699. wlogprint("Invalid selection\n");
  4700. goto retry;
  4701. }
  4702. pool = pools[selected];
  4703. enable_pool(pool);
  4704. switch_pools(pool);
  4705. goto updated;
  4706. } else if (!strncasecmp(&input, "d", 1)) {
  4707. if (enabled_pools <= 1) {
  4708. wlogprint("Cannot disable last pool");
  4709. goto retry;
  4710. }
  4711. selected = curses_int("Select pool number");
  4712. if (selected < 0 || selected >= total_pools) {
  4713. wlogprint("Invalid selection\n");
  4714. goto retry;
  4715. }
  4716. pool = pools[selected];
  4717. disable_pool(pool);
  4718. if (pool == current_pool())
  4719. switch_pools(NULL);
  4720. goto updated;
  4721. } else if (!strncasecmp(&input, "e", 1)) {
  4722. selected = curses_int("Select pool number");
  4723. if (selected < 0 || selected >= total_pools) {
  4724. wlogprint("Invalid selection\n");
  4725. goto retry;
  4726. }
  4727. pool = pools[selected];
  4728. enable_pool(pool);
  4729. if (pool->prio < current_pool()->prio)
  4730. switch_pools(pool);
  4731. goto updated;
  4732. } else if (!strncasecmp(&input, "c", 1)) {
  4733. for (i = 0; i <= TOP_STRATEGY; i++)
  4734. wlogprint("%d: %s\n", i, strategies[i].s);
  4735. selected = curses_int("Select strategy number type");
  4736. if (selected < 0 || selected > TOP_STRATEGY) {
  4737. wlogprint("Invalid selection\n");
  4738. goto retry;
  4739. }
  4740. if (selected == POOL_ROTATE) {
  4741. opt_rotate_period = curses_int("Select interval in minutes");
  4742. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  4743. opt_rotate_period = 0;
  4744. wlogprint("Invalid selection\n");
  4745. goto retry;
  4746. }
  4747. }
  4748. pool_strategy = selected;
  4749. switch_pools(NULL);
  4750. goto updated;
  4751. } else if (!strncasecmp(&input, "i", 1)) {
  4752. selected = curses_int("Select pool number");
  4753. if (selected < 0 || selected >= total_pools) {
  4754. wlogprint("Invalid selection\n");
  4755. goto retry;
  4756. }
  4757. pool = pools[selected];
  4758. display_pool_summary(pool);
  4759. goto retry;
  4760. } else if (!strncasecmp(&input, "q", 1)) {
  4761. selected = curses_int("Select pool number");
  4762. if (selected < 0 || selected >= total_pools) {
  4763. wlogprint("Invalid selection\n");
  4764. goto retry;
  4765. }
  4766. pool = pools[selected];
  4767. selected = curses_int("Set quota");
  4768. if (selected < 0) {
  4769. wlogprint("Invalid negative quota\n");
  4770. goto retry;
  4771. }
  4772. pool->quota = selected;
  4773. adjust_quota_gcd();
  4774. goto updated;
  4775. } else if (!strncasecmp(&input, "f", 1)) {
  4776. opt_fail_only ^= true;
  4777. goto updated;
  4778. } else
  4779. clear_logwin();
  4780. immedok(logwin, false);
  4781. opt_loginput = false;
  4782. }
  4783. static void display_options(void)
  4784. {
  4785. int selected;
  4786. char input;
  4787. opt_loginput = true;
  4788. immedok(logwin, true);
  4789. clear_logwin();
  4790. retry:
  4791. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  4792. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  4793. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  4794. "[T]oggle status switching:%s\n"
  4795. "w[I]descreen:%s\n"
  4796. "[Z]ero statistics\n"
  4797. "[L]og interval:%d\n",
  4798. opt_debug ? "on" : "off",
  4799. want_per_device_stats? "on" : "off",
  4800. opt_quiet ? "on" : "off",
  4801. opt_log_output ? "on" : "off",
  4802. opt_protocol ? "on" : "off",
  4803. opt_worktime ? "on" : "off",
  4804. opt_compact ? "on" : "off",
  4805. switch_status ? "enabled" : "disabled",
  4806. opt_widescreen ? "enabled" : "disabled",
  4807. opt_log_interval);
  4808. wlogprint("Select an option or any other key to return\n");
  4809. logwin_update();
  4810. input = getch();
  4811. if (!strncasecmp(&input, "q", 1)) {
  4812. opt_quiet ^= true;
  4813. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  4814. goto retry;
  4815. } else if (!strncasecmp(&input, "v", 1)) {
  4816. opt_log_output ^= true;
  4817. if (opt_log_output)
  4818. opt_quiet = false;
  4819. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  4820. goto retry;
  4821. } else if (!strncasecmp(&input, "n", 1)) {
  4822. opt_log_output = false;
  4823. opt_debug = false;
  4824. opt_quiet = false;
  4825. opt_protocol = false;
  4826. opt_compact = false;
  4827. want_per_device_stats = false;
  4828. wlogprint("Output mode reset to normal\n");
  4829. switch_logsize(false);
  4830. goto retry;
  4831. } else if (!strncasecmp(&input, "d", 1)) {
  4832. opt_debug ^= true;
  4833. opt_log_output = opt_debug;
  4834. if (opt_debug)
  4835. opt_quiet = false;
  4836. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  4837. goto retry;
  4838. } else if (!strncasecmp(&input, "m", 1)) {
  4839. opt_compact ^= true;
  4840. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  4841. switch_logsize(false);
  4842. goto retry;
  4843. } else if (!strncasecmp(&input, "p", 1)) {
  4844. want_per_device_stats ^= true;
  4845. opt_log_output = want_per_device_stats;
  4846. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  4847. goto retry;
  4848. } else if (!strncasecmp(&input, "r", 1)) {
  4849. opt_protocol ^= true;
  4850. if (opt_protocol)
  4851. opt_quiet = false;
  4852. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  4853. goto retry;
  4854. } else if (!strncasecmp(&input, "c", 1))
  4855. clear_logwin();
  4856. else if (!strncasecmp(&input, "l", 1)) {
  4857. selected = curses_int("Interval in seconds");
  4858. if (selected < 0 || selected > 9999) {
  4859. wlogprint("Invalid selection\n");
  4860. goto retry;
  4861. }
  4862. opt_log_interval = selected;
  4863. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  4864. goto retry;
  4865. } else if (!strncasecmp(&input, "s", 1)) {
  4866. opt_realquiet = true;
  4867. } else if (!strncasecmp(&input, "w", 1)) {
  4868. opt_worktime ^= true;
  4869. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  4870. goto retry;
  4871. } else if (!strncasecmp(&input, "t", 1)) {
  4872. switch_status ^= true;
  4873. goto retry;
  4874. } else if (!strncasecmp(&input, "i", 1)) {
  4875. opt_widescreen ^= true;
  4876. goto retry;
  4877. } else if (!strncasecmp(&input, "z", 1)) {
  4878. zero_stats();
  4879. goto retry;
  4880. } else
  4881. clear_logwin();
  4882. immedok(logwin, false);
  4883. opt_loginput = false;
  4884. }
  4885. #endif
  4886. void default_save_file(char *filename)
  4887. {
  4888. if (default_config && *default_config) {
  4889. strcpy(filename, default_config);
  4890. return;
  4891. }
  4892. #if defined(unix) || defined(__APPLE__)
  4893. if (getenv("HOME") && *getenv("HOME")) {
  4894. strcpy(filename, getenv("HOME"));
  4895. strcat(filename, "/");
  4896. }
  4897. else
  4898. strcpy(filename, "");
  4899. strcat(filename, ".cgminer/");
  4900. mkdir(filename, 0777);
  4901. #else
  4902. strcpy(filename, "");
  4903. #endif
  4904. strcat(filename, def_conf);
  4905. }
  4906. #ifdef HAVE_CURSES
  4907. static void set_options(void)
  4908. {
  4909. int selected;
  4910. char input;
  4911. opt_loginput = true;
  4912. immedok(logwin, true);
  4913. clear_logwin();
  4914. retry:
  4915. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  4916. "[W]rite config file\n[C]gminer restart\n",
  4917. opt_queue, opt_scantime, opt_expiry);
  4918. wlogprint("Select an option or any other key to return\n");
  4919. logwin_update();
  4920. input = getch();
  4921. if (!strncasecmp(&input, "q", 1)) {
  4922. selected = curses_int("Extra work items to queue");
  4923. if (selected < 0 || selected > 9999) {
  4924. wlogprint("Invalid selection\n");
  4925. goto retry;
  4926. }
  4927. opt_queue = selected;
  4928. if (opt_queue < max_queue)
  4929. max_queue = opt_queue;
  4930. goto retry;
  4931. } else if (!strncasecmp(&input, "s", 1)) {
  4932. selected = curses_int("Set scantime in seconds");
  4933. if (selected < 0 || selected > 9999) {
  4934. wlogprint("Invalid selection\n");
  4935. goto retry;
  4936. }
  4937. opt_scantime = selected;
  4938. goto retry;
  4939. } else if (!strncasecmp(&input, "e", 1)) {
  4940. selected = curses_int("Set expiry time in seconds");
  4941. if (selected < 0 || selected > 9999) {
  4942. wlogprint("Invalid selection\n");
  4943. goto retry;
  4944. }
  4945. opt_expiry = selected;
  4946. goto retry;
  4947. } else if (!strncasecmp(&input, "w", 1)) {
  4948. FILE *fcfg;
  4949. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  4950. default_save_file(filename);
  4951. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  4952. str = curses_input(prompt);
  4953. if (strcmp(str, "-1")) {
  4954. struct stat statbuf;
  4955. strcpy(filename, str);
  4956. free(str);
  4957. if (!stat(filename, &statbuf)) {
  4958. wlogprint("File exists, overwrite?\n");
  4959. input = getch();
  4960. if (strncasecmp(&input, "y", 1))
  4961. goto retry;
  4962. }
  4963. }
  4964. else
  4965. free(str);
  4966. fcfg = fopen(filename, "w");
  4967. if (!fcfg) {
  4968. wlogprint("Cannot open or create file\n");
  4969. goto retry;
  4970. }
  4971. write_config(fcfg);
  4972. fclose(fcfg);
  4973. goto retry;
  4974. } else if (!strncasecmp(&input, "c", 1)) {
  4975. wlogprint("Are you sure?\n");
  4976. input = getch();
  4977. if (!strncasecmp(&input, "y", 1))
  4978. app_restart();
  4979. else
  4980. clear_logwin();
  4981. } else
  4982. clear_logwin();
  4983. immedok(logwin, false);
  4984. opt_loginput = false;
  4985. }
  4986. #ifdef USE_USBUTILS
  4987. static void mt_enable(struct thr_info *mythr)
  4988. {
  4989. cgsem_post(&mythr->sem);
  4990. }
  4991. static void set_usb(void)
  4992. {
  4993. int selected, i, mt, enabled, disabled, zombie, total, blacklisted;
  4994. struct cgpu_info *cgpu;
  4995. struct thr_info *thr;
  4996. double val;
  4997. char input;
  4998. opt_loginput = true;
  4999. immedok(logwin, true);
  5000. clear_logwin();
  5001. retry:
  5002. enabled = 0;
  5003. disabled = 0;
  5004. zombie = 0;
  5005. total = 0;
  5006. blacklisted = 0;
  5007. rd_lock(&mining_thr_lock);
  5008. mt = mining_threads;
  5009. rd_unlock(&mining_thr_lock);
  5010. for (i = 0; i < mt; i++) {
  5011. cgpu = mining_thr[i]->cgpu;
  5012. if (unlikely(!cgpu))
  5013. continue;
  5014. if (cgpu->usbinfo.nodev)
  5015. zombie++;
  5016. else if (cgpu->deven == DEV_DISABLED)
  5017. disabled++;
  5018. else
  5019. enabled++;
  5020. if (cgpu->blacklisted)
  5021. blacklisted++;
  5022. total++;
  5023. }
  5024. wlogprint("Hotplug interval:%d\n", hotplug_time);
  5025. wlogprint("%d USB devices, %d enabled, %d disabled, %d zombie\n",
  5026. total, enabled, disabled, zombie);
  5027. wlogprint("[S]ummary of device information\n");
  5028. wlogprint("[E]nable device\n");
  5029. wlogprint("[D]isable device\n");
  5030. wlogprint("[U]nplug to allow hotplug restart\n");
  5031. wlogprint("[R]eset device USB\n");
  5032. wlogprint("[L]ist all known devices\n");
  5033. wlogprint("[B]lacklist current device from current instance of cgminer\n");
  5034. wlogprint("[W]hitelist previously blacklisted device\n");
  5035. wlogprint("[H]otplug interval (0 to disable)\n");
  5036. wlogprint("Select an option or any other key to return\n");
  5037. logwin_update();
  5038. input = getch();
  5039. if (!strncasecmp(&input, "s", 1)) {
  5040. selected = curses_int("Select device number");
  5041. if (selected < 0 || selected >= mt) {
  5042. wlogprint("Invalid selection\n");
  5043. goto retry;
  5044. }
  5045. cgpu = mining_thr[selected]->cgpu;
  5046. wlogprint("Device %03u:%03u\n", cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  5047. wlogprint("Name %s\n", cgpu->drv->name);
  5048. wlogprint("ID %d\n", cgpu->device_id);
  5049. wlogprint("Enabled: %s\n", cgpu->deven != DEV_DISABLED ? "Yes" : "No");
  5050. wlogprint("Temperature %.1f\n", cgpu->temp);
  5051. wlogprint("MHS av %.0f\n", cgpu->total_mhashes / cgpu_runtime(cgpu));
  5052. wlogprint("Accepted %d\n", cgpu->accepted);
  5053. wlogprint("Rejected %d\n", cgpu->rejected);
  5054. wlogprint("Hardware Errors %d\n", cgpu->hw_errors);
  5055. wlogprint("Last Share Pool %d\n", cgpu->last_share_pool_time > 0 ? cgpu->last_share_pool : -1);
  5056. wlogprint("Total MH %.1f\n", cgpu->total_mhashes);
  5057. wlogprint("Diff1 Work %"PRId64"\n", cgpu->diff1);
  5058. wlogprint("Difficulty Accepted %.1f\n", cgpu->diff_accepted);
  5059. wlogprint("Difficulty Rejected %.1f\n", cgpu->diff_rejected);
  5060. wlogprint("Last Share Difficulty %.1f\n", cgpu->last_share_diff);
  5061. wlogprint("No Device: %s\n", cgpu->usbinfo.nodev ? "True" : "False");
  5062. wlogprint("Last Valid Work %"PRIu64"\n", (uint64_t)cgpu->last_device_valid_work);
  5063. val = 0;
  5064. if (cgpu->hw_errors + cgpu->diff1)
  5065. val = cgpu->hw_errors / (cgpu->hw_errors + cgpu->diff1);
  5066. wlogprint("Device Hardware %.1f%%\n", val);
  5067. val = 0;
  5068. if (cgpu->diff1)
  5069. val = cgpu->diff_rejected / cgpu->diff1;
  5070. wlogprint("Device Rejected %.1f%%\n", val);
  5071. goto retry;
  5072. } else if (!strncasecmp(&input, "e", 1)) {
  5073. selected = curses_int("Select device number");
  5074. if (selected < 0 || selected >= mt) {
  5075. wlogprint("Invalid selection\n");
  5076. goto retry;
  5077. }
  5078. cgpu = mining_thr[selected]->cgpu;
  5079. if (cgpu->usbinfo.nodev) {
  5080. wlogprint("Device removed, unable to re-enable!\n");
  5081. goto retry;
  5082. }
  5083. thr = get_thread(selected);
  5084. cgpu->deven = DEV_ENABLED;
  5085. mt_enable(thr);
  5086. goto retry;
  5087. } else if (!strncasecmp(&input, "d", 1)) {
  5088. selected = curses_int("Select device number");
  5089. if (selected < 0 || selected >= mt) {
  5090. wlogprint("Invalid selection\n");
  5091. goto retry;
  5092. }
  5093. cgpu = mining_thr[selected]->cgpu;
  5094. cgpu->deven = DEV_DISABLED;
  5095. goto retry;
  5096. } else if (!strncasecmp(&input, "u", 1)) {
  5097. selected = curses_int("Select device number");
  5098. if (selected < 0 || selected >= mt) {
  5099. wlogprint("Invalid selection\n");
  5100. goto retry;
  5101. }
  5102. cgpu = mining_thr[selected]->cgpu;
  5103. if (cgpu->usbinfo.nodev) {
  5104. wlogprint("Device already removed, unable to unplug!\n");
  5105. goto retry;
  5106. }
  5107. usb_nodev(cgpu);
  5108. goto retry;
  5109. } else if (!strncasecmp(&input, "r", 1)) {
  5110. selected = curses_int("Select device number");
  5111. if (selected < 0 || selected >= mt) {
  5112. wlogprint("Invalid selection\n");
  5113. goto retry;
  5114. }
  5115. cgpu = mining_thr[selected]->cgpu;
  5116. if (cgpu->usbinfo.nodev) {
  5117. wlogprint("Device already removed, unable to reset!\n");
  5118. goto retry;
  5119. }
  5120. usb_reset(cgpu);
  5121. goto retry;
  5122. } else if (!strncasecmp(&input, "b", 1)) {
  5123. selected = curses_int("Select device number");
  5124. if (selected < 0 || selected >= mt) {
  5125. wlogprint("Invalid selection\n");
  5126. goto retry;
  5127. }
  5128. cgpu = mining_thr[selected]->cgpu;
  5129. if (cgpu->usbinfo.nodev) {
  5130. wlogprint("Device already removed, unable to blacklist!\n");
  5131. goto retry;
  5132. }
  5133. blacklist_cgpu(cgpu);
  5134. goto retry;
  5135. } else if (!strncasecmp(&input, "w", 1)) {
  5136. if (!blacklisted) {
  5137. wlogprint("No blacklisted devices!\n");
  5138. goto retry;
  5139. }
  5140. wlogprint("Blacklisted devices:\n");
  5141. for (i = 0; i < mt; i++) {
  5142. cgpu = mining_thr[i]->cgpu;
  5143. if (unlikely(!cgpu))
  5144. continue;
  5145. if (cgpu->blacklisted) {
  5146. wlogprint("%d: %s %d %03u:%03u\n", i, cgpu->drv->name,
  5147. cgpu->device_id, cgpu->usbinfo.bus_number,
  5148. cgpu->usbinfo.device_address);
  5149. }
  5150. }
  5151. selected = curses_int("Select device number");
  5152. if (selected < 0 || selected >= mt) {
  5153. wlogprint("Invalid selection\n");
  5154. goto retry;
  5155. }
  5156. cgpu = mining_thr[selected]->cgpu;
  5157. if (!cgpu->blacklisted) {
  5158. wlogprint("Device not blacklisted, unable to whitelist\n");
  5159. goto retry;
  5160. }
  5161. whitelist_cgpu(cgpu);
  5162. goto retry;
  5163. } else if (!strncasecmp(&input, "h", 1)) {
  5164. selected = curses_int("Select hotplug interval in seconds (0 to disable)");
  5165. if (selected < 0 || selected > 9999) {
  5166. wlogprint("Invalid value\n");
  5167. goto retry;
  5168. }
  5169. hotplug_time = selected;
  5170. goto retry;
  5171. } else if (!strncasecmp(&input, "l", 1)) {
  5172. usb_list();
  5173. goto retry;
  5174. } else
  5175. clear_logwin();
  5176. immedok(logwin, false);
  5177. opt_loginput = false;
  5178. }
  5179. #endif
  5180. static void *input_thread(void __maybe_unused *userdata)
  5181. {
  5182. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5183. RenameThread("Input");
  5184. if (!curses_active)
  5185. return NULL;
  5186. while (1) {
  5187. char input;
  5188. input = getch();
  5189. if (!strncasecmp(&input, "q", 1)) {
  5190. kill_work();
  5191. return NULL;
  5192. } else if (!strncasecmp(&input, "d", 1))
  5193. display_options();
  5194. else if (!strncasecmp(&input, "p", 1))
  5195. display_pools();
  5196. else if (!strncasecmp(&input, "s", 1))
  5197. set_options();
  5198. #ifdef USE_USBUTILS
  5199. else if (!strncasecmp(&input, "u", 1))
  5200. set_usb();
  5201. #endif
  5202. if (opt_realquiet) {
  5203. disable_curses();
  5204. break;
  5205. }
  5206. }
  5207. return NULL;
  5208. }
  5209. #endif
  5210. static void *api_thread(void *userdata)
  5211. {
  5212. struct thr_info *mythr = userdata;
  5213. pthread_detach(pthread_self());
  5214. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5215. RenameThread("API");
  5216. set_lowprio();
  5217. api(api_thr_id);
  5218. PTH(mythr) = 0L;
  5219. return NULL;
  5220. }
  5221. /* Sole work devices are serialised wrt calling get_work so they report in on
  5222. * each pass through their scanhash function as well as in get_work whereas
  5223. * queued work devices work asynchronously so get them to report in and out
  5224. * only across get_work. */
  5225. static void thread_reportin(struct thr_info *thr)
  5226. {
  5227. thr->getwork = false;
  5228. cgtime(&thr->last);
  5229. thr->cgpu->status = LIFE_WELL;
  5230. thr->cgpu->device_last_well = time(NULL);
  5231. }
  5232. /* Tell the watchdog thread this thread is waiting on get work and should not
  5233. * be restarted */
  5234. static void thread_reportout(struct thr_info *thr)
  5235. {
  5236. thr->getwork = true;
  5237. cgtime(&thr->last);
  5238. thr->cgpu->status = LIFE_WELL;
  5239. thr->cgpu->device_last_well = time(NULL);
  5240. }
  5241. static void hashmeter(int thr_id, uint64_t hashes_done)
  5242. {
  5243. bool showlog = false;
  5244. double tv_tdiff, mhashes_done = 0.0;
  5245. time_t now_t;
  5246. int diff_t;
  5247. cgtime(&total_tv_end);
  5248. tv_tdiff = tdiff(&total_tv_end, &tv_hashmeter);
  5249. now_t = total_tv_end.tv_sec;
  5250. diff_t = now_t - hashdisplay_t;
  5251. if (diff_t >= opt_log_interval) {
  5252. alt_status ^= switch_status;
  5253. hashdisplay_t = now_t;
  5254. showlog = true;
  5255. } else if (thr_id < 0) {
  5256. /* hashmeter is called by non-mining threads in case nothing
  5257. * has reported in to allow hashrate to converge to zero , but
  5258. * we only update if it has been more than opt_log_interval */
  5259. return;
  5260. }
  5261. copy_time(&tv_hashmeter, &total_tv_end);
  5262. if (thr_id >= 0) {
  5263. struct thr_info *thr = get_thread(thr_id);
  5264. struct cgpu_info *cgpu = thr->cgpu;
  5265. double device_tdiff, thr_mhs;
  5266. /* Update the last time this thread reported in */
  5267. copy_time(&thr->last, &total_tv_end);
  5268. cgpu->device_last_well = now_t;
  5269. device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  5270. copy_time(&cgpu->last_message_tv, &total_tv_end);
  5271. thr_mhs = (double)hashes_done / device_tdiff / 1000000;
  5272. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f mhash/sec]",
  5273. thr_id, hashes_done, thr_mhs);
  5274. mhashes_done = hashes_done / 1000000.0;
  5275. mutex_lock(&hash_lock);
  5276. cgpu->total_mhashes += mhashes_done;
  5277. decay_time(&cgpu->rolling, mhashes_done, device_tdiff, opt_log_interval);
  5278. decay_time(&cgpu->rolling1, mhashes_done, device_tdiff, 60.0);
  5279. decay_time(&cgpu->rolling5, mhashes_done, device_tdiff, 300.0);
  5280. decay_time(&cgpu->rolling15, mhashes_done, device_tdiff, 900.0);
  5281. mutex_unlock(&hash_lock);
  5282. if (want_per_device_stats && showlog) {
  5283. char logline[256];
  5284. get_statline(logline, sizeof(logline), cgpu);
  5285. if (!curses_active) {
  5286. printf("%s \r", logline);
  5287. fflush(stdout);
  5288. } else
  5289. applog(LOG_INFO, "%s", logline);
  5290. }
  5291. } else {
  5292. /* No device has reported in, we have been called from the
  5293. * watchdog thread so decay all the hashrates */
  5294. mutex_lock(&hash_lock);
  5295. for (thr_id = 0; thr_id < mining_threads; thr_id++) {
  5296. struct thr_info *thr = get_thread(thr_id);
  5297. struct cgpu_info *cgpu = thr->cgpu;
  5298. double device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  5299. copy_time(&cgpu->last_message_tv, &total_tv_end);
  5300. decay_time(&cgpu->rolling, 0, device_tdiff, opt_log_interval);
  5301. decay_time(&cgpu->rolling1, 0, device_tdiff, 60.0);
  5302. decay_time(&cgpu->rolling5, 0, device_tdiff, 300.0);
  5303. decay_time(&cgpu->rolling15, 0, device_tdiff, 900.0);
  5304. }
  5305. mutex_unlock(&hash_lock);
  5306. }
  5307. mutex_lock(&hash_lock);
  5308. total_mhashes_done += mhashes_done;
  5309. decay_time(&total_rolling, mhashes_done, tv_tdiff, opt_log_interval);
  5310. decay_time(&rolling1, mhashes_done, tv_tdiff, 60.0);
  5311. decay_time(&rolling5, mhashes_done, tv_tdiff, 300.0);
  5312. decay_time(&rolling15, mhashes_done, tv_tdiff, 900.0);
  5313. global_hashrate = llround(total_rolling) * 1000000;
  5314. total_secs = tdiff(&total_tv_end, &total_tv_start);
  5315. if (showlog) {
  5316. char displayed_hashes[16], displayed_rolling[16];
  5317. char displayed_r1[16], displayed_r5[16], displayed_r15[16];
  5318. uint64_t d64;
  5319. d64 = (double)total_mhashes_done / total_secs * 1000000ull;
  5320. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  5321. d64 = (double)total_rolling * 1000000ull;
  5322. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  5323. d64 = (double)rolling1 * 1000000ull;
  5324. suffix_string(d64, displayed_r1, sizeof(displayed_rolling), 4);
  5325. d64 = (double)rolling5 * 1000000ull;
  5326. suffix_string(d64, displayed_r5, sizeof(displayed_rolling), 4);
  5327. d64 = (double)rolling15 * 1000000ull;
  5328. suffix_string(d64, displayed_r15, sizeof(displayed_rolling), 4);
  5329. snprintf(statusline, sizeof(statusline),
  5330. "(%ds):%s (1m):%s (5m):%s (15m):%s (avg):%sh/s",
  5331. opt_log_interval, displayed_rolling, displayed_r1, displayed_r5,
  5332. displayed_r15, displayed_hashes);
  5333. }
  5334. mutex_unlock(&hash_lock);
  5335. if (showlog) {
  5336. if (!curses_active) {
  5337. printf("%s \r", statusline);
  5338. fflush(stdout);
  5339. } else
  5340. applog(LOG_INFO, "%s", statusline);
  5341. }
  5342. }
  5343. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  5344. struct stratum_share *sshare)
  5345. {
  5346. struct work *work = sshare->work;
  5347. time_t now_t = time(NULL);
  5348. char hashshow[64];
  5349. int srdiff;
  5350. srdiff = now_t - sshare->sshare_sent;
  5351. if (opt_debug || srdiff > 0) {
  5352. applog(LOG_INFO, "Pool %d stratum share result lag time %d seconds",
  5353. work->pool->pool_no, srdiff);
  5354. }
  5355. show_hash(work, hashshow);
  5356. share_result(val, res_val, err_val, work, hashshow, false, "");
  5357. }
  5358. /* Parses stratum json responses and tries to find the id that the request
  5359. * matched to and treat it accordingly. */
  5360. static bool parse_stratum_response(struct pool *pool, char *s)
  5361. {
  5362. json_t *val = NULL, *err_val, *res_val, *id_val;
  5363. struct stratum_share *sshare;
  5364. json_error_t err;
  5365. bool ret = false;
  5366. int id;
  5367. val = JSON_LOADS(s, &err);
  5368. if (!val) {
  5369. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  5370. goto out;
  5371. }
  5372. res_val = json_object_get(val, "result");
  5373. if (!res_val)
  5374. goto out;
  5375. err_val = json_object_get(val, "error");
  5376. id_val = json_object_get(val, "id");
  5377. if (json_is_null(id_val) || !id_val) {
  5378. char *ss;
  5379. if (err_val)
  5380. ss = json_dumps(err_val, JSON_INDENT(3));
  5381. else
  5382. ss = strdup("(unknown reason)");
  5383. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  5384. free(ss);
  5385. goto out;
  5386. }
  5387. id = json_integer_value(id_val);
  5388. mutex_lock(&sshare_lock);
  5389. HASH_FIND_INT(stratum_shares, &id, sshare);
  5390. if (sshare) {
  5391. HASH_DEL(stratum_shares, sshare);
  5392. pool->sshares--;
  5393. }
  5394. mutex_unlock(&sshare_lock);
  5395. if (!sshare) {
  5396. double pool_diff;
  5397. /* Since the share is untracked, we can only guess at what the
  5398. * work difficulty is based on the current pool diff. */
  5399. cg_rlock(&pool->data_lock);
  5400. pool_diff = pool->sdiff;
  5401. cg_runlock(&pool->data_lock);
  5402. if (json_is_true(res_val)) {
  5403. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  5404. /* We don't know what device this came from so we can't
  5405. * attribute the work to the relevant cgpu */
  5406. mutex_lock(&stats_lock);
  5407. total_accepted++;
  5408. pool->accepted++;
  5409. total_diff_accepted += pool_diff;
  5410. pool->diff_accepted += pool_diff;
  5411. mutex_unlock(&stats_lock);
  5412. } else {
  5413. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  5414. mutex_lock(&stats_lock);
  5415. total_rejected++;
  5416. pool->rejected++;
  5417. total_diff_rejected += pool_diff;
  5418. pool->diff_rejected += pool_diff;
  5419. mutex_unlock(&stats_lock);
  5420. }
  5421. goto out;
  5422. }
  5423. stratum_share_result(val, res_val, err_val, sshare);
  5424. free_work(sshare->work);
  5425. free(sshare);
  5426. ret = true;
  5427. out:
  5428. if (val)
  5429. json_decref(val);
  5430. return ret;
  5431. }
  5432. void clear_stratum_shares(struct pool *pool)
  5433. {
  5434. struct stratum_share *sshare, *tmpshare;
  5435. double diff_cleared = 0;
  5436. int cleared = 0;
  5437. mutex_lock(&sshare_lock);
  5438. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  5439. if (sshare->work->pool == pool) {
  5440. HASH_DEL(stratum_shares, sshare);
  5441. diff_cleared += sshare->work->work_difficulty;
  5442. free_work(sshare->work);
  5443. pool->sshares--;
  5444. free(sshare);
  5445. cleared++;
  5446. }
  5447. }
  5448. mutex_unlock(&sshare_lock);
  5449. if (cleared) {
  5450. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5451. pool->stale_shares += cleared;
  5452. total_stale += cleared;
  5453. pool->diff_stale += diff_cleared;
  5454. total_diff_stale += diff_cleared;
  5455. }
  5456. }
  5457. void clear_pool_work(struct pool *pool)
  5458. {
  5459. struct work *work, *tmp;
  5460. int cleared = 0;
  5461. mutex_lock(stgd_lock);
  5462. HASH_ITER(hh, staged_work, work, tmp) {
  5463. if (work->pool == pool) {
  5464. HASH_DEL(staged_work, work);
  5465. free_work(work);
  5466. cleared++;
  5467. }
  5468. }
  5469. mutex_unlock(stgd_lock);
  5470. if (cleared)
  5471. applog(LOG_INFO, "Cleared %d work items due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5472. }
  5473. static int cp_prio(void)
  5474. {
  5475. int prio;
  5476. cg_rlock(&control_lock);
  5477. prio = currentpool->prio;
  5478. cg_runlock(&control_lock);
  5479. return prio;
  5480. }
  5481. /* We only need to maintain a secondary pool connection when we need the
  5482. * capacity to get work from the backup pools while still on the primary */
  5483. static bool cnx_needed(struct pool *pool)
  5484. {
  5485. struct pool *cp;
  5486. if (pool->enabled != POOL_ENABLED)
  5487. return false;
  5488. /* Balance strategies need all pools online */
  5489. if (pool_strategy == POOL_BALANCE)
  5490. return true;
  5491. if (pool_strategy == POOL_LOADBALANCE)
  5492. return true;
  5493. /* Idle stratum pool needs something to kick it alive again */
  5494. if (pool->has_stratum && pool->idle)
  5495. return true;
  5496. /* Getwork pools without opt_fail_only need backup pools up to be able
  5497. * to leak shares */
  5498. cp = current_pool();
  5499. if (cp == pool)
  5500. return true;
  5501. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  5502. return true;
  5503. /* If we're waiting for a response from shares submitted, keep the
  5504. * connection open. */
  5505. if (pool->sshares)
  5506. return true;
  5507. /* If the pool has only just come to life and is higher priority than
  5508. * the current pool keep the connection open so we can fail back to
  5509. * it. */
  5510. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  5511. return true;
  5512. /* We've run out of work, bring anything back to life. */
  5513. if (no_work)
  5514. return true;
  5515. return false;
  5516. }
  5517. static void wait_lpcurrent(struct pool *pool);
  5518. static void pool_resus(struct pool *pool);
  5519. static void gen_stratum_work(struct pool *pool, struct work *work);
  5520. void stratum_resumed(struct pool *pool)
  5521. {
  5522. if (pool_tclear(pool, &pool->idle)) {
  5523. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  5524. pool_resus(pool);
  5525. }
  5526. }
  5527. static bool supports_resume(struct pool *pool)
  5528. {
  5529. bool ret;
  5530. cg_rlock(&pool->data_lock);
  5531. ret = (pool->sessionid != NULL);
  5532. cg_runlock(&pool->data_lock);
  5533. return ret;
  5534. }
  5535. /* One stratum receive thread per pool that has stratum waits on the socket
  5536. * checking for new messages and for the integrity of the socket connection. We
  5537. * reset the connection based on the integrity of the receive side only as the
  5538. * send side will eventually expire data it fails to send. */
  5539. static void *stratum_rthread(void *userdata)
  5540. {
  5541. struct pool *pool = (struct pool *)userdata;
  5542. char threadname[16];
  5543. pthread_detach(pthread_self());
  5544. snprintf(threadname, sizeof(threadname), "%d/RStratum", pool->pool_no);
  5545. RenameThread(threadname);
  5546. while (42) {
  5547. struct timeval timeout;
  5548. int sel_ret;
  5549. fd_set rd;
  5550. char *s;
  5551. if (unlikely(pool->removed)) {
  5552. suspend_stratum(pool);
  5553. break;
  5554. }
  5555. /* Check to see whether we need to maintain this connection
  5556. * indefinitely or just bring it up when we switch to this
  5557. * pool */
  5558. if (!sock_full(pool) && !cnx_needed(pool)) {
  5559. suspend_stratum(pool);
  5560. clear_stratum_shares(pool);
  5561. clear_pool_work(pool);
  5562. wait_lpcurrent(pool);
  5563. while (!restart_stratum(pool)) {
  5564. if (pool->removed)
  5565. goto out;
  5566. if (enabled_pools > 1)
  5567. cgsleep_ms(30000);
  5568. else
  5569. cgsleep_ms(3000);
  5570. }
  5571. }
  5572. FD_ZERO(&rd);
  5573. FD_SET(pool->sock, &rd);
  5574. timeout.tv_sec = 90;
  5575. timeout.tv_usec = 0;
  5576. /* The protocol specifies that notify messages should be sent
  5577. * every minute so if we fail to receive any for 90 seconds we
  5578. * assume the connection has been dropped and treat this pool
  5579. * as dead */
  5580. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  5581. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  5582. s = NULL;
  5583. } else
  5584. s = recv_line(pool);
  5585. if (!s) {
  5586. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  5587. pool->getfail_occasions++;
  5588. total_go++;
  5589. /* If the socket to our stratum pool disconnects, all
  5590. * tracked submitted shares are lost and we will leak
  5591. * the memory if we don't discard their records. */
  5592. if (!supports_resume(pool) || opt_lowmem)
  5593. clear_stratum_shares(pool);
  5594. clear_pool_work(pool);
  5595. if (pool == current_pool())
  5596. restart_threads();
  5597. while (!restart_stratum(pool)) {
  5598. if (pool->removed)
  5599. goto out;
  5600. cgsleep_ms(30000);
  5601. }
  5602. continue;
  5603. }
  5604. /* Check this pool hasn't died while being a backup pool and
  5605. * has not had its idle flag cleared */
  5606. stratum_resumed(pool);
  5607. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  5608. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  5609. else if (pool->swork.clean) {
  5610. struct work *work = make_work();
  5611. /* Generate a single work item to update the current
  5612. * block database */
  5613. pool->swork.clean = false;
  5614. gen_stratum_work(pool, work);
  5615. work->longpoll = true;
  5616. /* Return value doesn't matter. We're just informing
  5617. * that we may need to restart. */
  5618. test_work_current(work);
  5619. free_work(work);
  5620. }
  5621. free(s);
  5622. }
  5623. out:
  5624. return NULL;
  5625. }
  5626. /* Each pool has one stratum send thread for sending shares to avoid many
  5627. * threads being created for submission since all sends need to be serialised
  5628. * anyway. */
  5629. static void *stratum_sthread(void *userdata)
  5630. {
  5631. struct pool *pool = (struct pool *)userdata;
  5632. char threadname[16];
  5633. pthread_detach(pthread_self());
  5634. snprintf(threadname, sizeof(threadname), "%d/SStratum", pool->pool_no);
  5635. RenameThread(threadname);
  5636. pool->stratum_q = tq_new();
  5637. if (!pool->stratum_q)
  5638. quit(1, "Failed to create stratum_q in stratum_sthread");
  5639. while (42) {
  5640. char noncehex[12], nonce2hex[20], s[1024];
  5641. struct stratum_share *sshare;
  5642. uint32_t *hash32, nonce;
  5643. unsigned char nonce2[8];
  5644. uint64_t *nonce2_64;
  5645. struct work *work;
  5646. bool submitted;
  5647. if (unlikely(pool->removed))
  5648. break;
  5649. work = tq_pop(pool->stratum_q, NULL);
  5650. if (unlikely(!work))
  5651. quit(1, "Stratum q returned empty work");
  5652. if (unlikely(work->nonce2_len > 8)) {
  5653. applog(LOG_ERR, "Pool %d asking for inappropriately long nonce2 length %d",
  5654. pool->pool_no, (int)work->nonce2_len);
  5655. applog(LOG_ERR, "Not attempting to submit shares");
  5656. free_work(work);
  5657. continue;
  5658. }
  5659. sshare = calloc(sizeof(struct stratum_share), 1);
  5660. hash32 = (uint32_t *)work->hash;
  5661. submitted = false;
  5662. sshare->sshare_time = time(NULL);
  5663. /* This work item is freed in parse_stratum_response */
  5664. sshare->work = work;
  5665. nonce = *((uint32_t *)(work->data + 76));
  5666. __bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5667. memset(s, 0, 1024);
  5668. mutex_lock(&sshare_lock);
  5669. /* Give the stratum share a unique id */
  5670. sshare->id = swork_id++;
  5671. mutex_unlock(&sshare_lock);
  5672. nonce2_64 = (uint64_t *)nonce2;
  5673. *nonce2_64 = htole64(work->nonce2);
  5674. __bin2hex(nonce2hex, nonce2, work->nonce2_len);
  5675. snprintf(s, sizeof(s),
  5676. "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5677. pool->rpc_user, work->job_id, nonce2hex, work->ntime, noncehex, sshare->id);
  5678. applog(LOG_INFO, "Submitting share %08lx to pool %d",
  5679. (long unsigned int)htole32(hash32[6]), pool->pool_no);
  5680. /* Try resubmitting for up to 2 minutes if we fail to submit
  5681. * once and the stratum pool nonce1 still matches suggesting
  5682. * we may be able to resume. */
  5683. while (time(NULL) < sshare->sshare_time + 120) {
  5684. bool sessionid_match;
  5685. if (likely(stratum_send(pool, s, strlen(s)))) {
  5686. mutex_lock(&sshare_lock);
  5687. HASH_ADD_INT(stratum_shares, id, sshare);
  5688. pool->sshares++;
  5689. mutex_unlock(&sshare_lock);
  5690. if (pool_tclear(pool, &pool->submit_fail))
  5691. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5692. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5693. submitted = true;
  5694. break;
  5695. }
  5696. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  5697. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5698. total_ro++;
  5699. pool->remotefail_occasions++;
  5700. }
  5701. if (opt_lowmem) {
  5702. applog(LOG_DEBUG, "Lowmem option prevents resubmitting stratum share");
  5703. break;
  5704. }
  5705. cg_rlock(&pool->data_lock);
  5706. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  5707. cg_runlock(&pool->data_lock);
  5708. if (!sessionid_match) {
  5709. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5710. break;
  5711. }
  5712. /* Retry every 5 seconds */
  5713. sleep(5);
  5714. }
  5715. if (unlikely(!submitted)) {
  5716. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  5717. free_work(work);
  5718. free(sshare);
  5719. pool->stale_shares++;
  5720. total_stale++;
  5721. } else {
  5722. int ssdiff;
  5723. sshare->sshare_sent = time(NULL);
  5724. ssdiff = sshare->sshare_sent - sshare->sshare_time;
  5725. if (opt_debug || ssdiff > 0) {
  5726. applog(LOG_INFO, "Pool %d stratum share submission lag time %d seconds",
  5727. pool->pool_no, ssdiff);
  5728. }
  5729. }
  5730. }
  5731. /* Freeze the work queue but don't free up its memory in case there is
  5732. * work still trying to be submitted to the removed pool. */
  5733. tq_freeze(pool->stratum_q);
  5734. return NULL;
  5735. }
  5736. static void init_stratum_threads(struct pool *pool)
  5737. {
  5738. have_longpoll = true;
  5739. if (unlikely(pthread_create(&pool->stratum_sthread, NULL, stratum_sthread, (void *)pool)))
  5740. quit(1, "Failed to create stratum sthread");
  5741. if (unlikely(pthread_create(&pool->stratum_rthread, NULL, stratum_rthread, (void *)pool)))
  5742. quit(1, "Failed to create stratum rthread");
  5743. }
  5744. static void *longpoll_thread(void *userdata);
  5745. static bool stratum_works(struct pool *pool)
  5746. {
  5747. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  5748. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  5749. return false;
  5750. if (!initiate_stratum(pool))
  5751. return false;
  5752. return true;
  5753. }
  5754. #ifdef HAVE_LIBCURL
  5755. static void __setup_gbt_solo(struct pool *pool)
  5756. {
  5757. cg_wlock(&pool->gbt_lock);
  5758. memcpy(pool->coinbase, scriptsig_header_bin, 41);
  5759. pool->coinbase[41 + pool->n1_len + 4 + 1 + 8] = 25;
  5760. memcpy(pool->coinbase + 41 + pool->n1_len + 4 + 1 + 8 + 1, pool->script_pubkey, 25);
  5761. cg_wunlock(&pool->gbt_lock);
  5762. }
  5763. static bool setup_gbt_solo(CURL *curl, struct pool *pool)
  5764. {
  5765. char s[256];
  5766. int uninitialised_var(rolltime);
  5767. bool ret = false;
  5768. json_t *val = NULL, *res_val, *valid_val;
  5769. if (!opt_btc_address) {
  5770. applog(LOG_ERR, "No BTC address specified, unable to mine solo on %s",
  5771. pool->rpc_url);
  5772. goto out;
  5773. }
  5774. snprintf(s, 256, "{\"method\": \"validateaddress\", \"params\": [\"%s\"]}\n", opt_btc_address);
  5775. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, true,
  5776. false, &rolltime, pool, false);
  5777. if (!val)
  5778. goto out;
  5779. res_val = json_object_get(val, "result");
  5780. if (!res_val)
  5781. goto out;
  5782. valid_val = json_object_get(res_val, "isvalid");
  5783. if (!valid_val)
  5784. goto out;
  5785. if (!json_is_true(valid_val)) {
  5786. applog(LOG_ERR, "Bitcoin address %s is NOT valid", opt_btc_address);
  5787. goto out;
  5788. }
  5789. applog(LOG_NOTICE, "Solo mining to valid address: %s", opt_btc_address);
  5790. ret = true;
  5791. address_to_pubkeyhash(pool->script_pubkey, opt_btc_address);
  5792. hex2bin(scriptsig_header_bin, scriptsig_header, 41);
  5793. __setup_gbt_solo(pool);
  5794. if (opt_debug) {
  5795. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  5796. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  5797. free(cb);
  5798. }
  5799. pool->gbt_curl = curl_easy_init();
  5800. if (unlikely(!pool->gbt_curl))
  5801. quit(1, "GBT CURL initialisation failed");
  5802. out:
  5803. if (val)
  5804. json_decref(val);
  5805. return ret;
  5806. }
  5807. #else
  5808. static bool setup_gbt_solo(CURL __maybe_unused *curl, struct pool __maybe_unused *pool)
  5809. {
  5810. return false;
  5811. }
  5812. #endif
  5813. static void pool_start_lp(struct pool *pool)
  5814. {
  5815. if (!pool->lp_started) {
  5816. pool->lp_started = true;
  5817. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  5818. quit(1, "Failed to create pool longpoll thread");
  5819. }
  5820. }
  5821. static bool pool_active(struct pool *pool, bool pinging)
  5822. {
  5823. struct timeval tv_getwork, tv_getwork_reply;
  5824. json_t *val = NULL;
  5825. bool ret = false;
  5826. CURL *curl;
  5827. int uninitialised_var(rolltime);
  5828. if (pool->has_gbt)
  5829. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  5830. else
  5831. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  5832. /* This is the central point we activate stratum when we can */
  5833. retry_stratum:
  5834. if (pool->has_stratum) {
  5835. /* We create the stratum thread for each pool just after
  5836. * successful authorisation. Once the init flag has been set
  5837. * we never unset it and the stratum thread is responsible for
  5838. * setting/unsetting the active flag */
  5839. bool init = pool_tset(pool, &pool->stratum_init);
  5840. if (!init) {
  5841. bool ret = initiate_stratum(pool) && (!pool->extranonce_subscribe || subscribe_extranonce(pool)) && auth_stratum(pool);
  5842. if (ret)
  5843. init_stratum_threads(pool);
  5844. else
  5845. pool_tclear(pool, &pool->stratum_init);
  5846. return ret;
  5847. }
  5848. return pool->stratum_active;
  5849. }
  5850. curl = curl_easy_init();
  5851. if (unlikely(!curl)) {
  5852. applog(LOG_ERR, "CURL initialisation failed");
  5853. return false;
  5854. }
  5855. /* Probe for GBT support on first pass */
  5856. if (!pool->probed) {
  5857. applog(LOG_DEBUG, "Probing for GBT support");
  5858. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  5859. gbt_req, true, false, &rolltime, pool, false);
  5860. if (val) {
  5861. bool append = false, submit = false, transactions = false;
  5862. json_t *res_val, *mutables;
  5863. int i, mutsize = 0;
  5864. res_val = json_object_get(val, "result");
  5865. if (res_val) {
  5866. mutables = json_object_get(res_val, "mutable");
  5867. mutsize = json_array_size(mutables);
  5868. }
  5869. for (i = 0; i < mutsize; i++) {
  5870. json_t *arrval = json_array_get(mutables, i);
  5871. if (json_is_string(arrval)) {
  5872. const char *mutable = json_string_value(arrval);
  5873. if (!strncasecmp(mutable, "coinbase/append", 15))
  5874. append = true;
  5875. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  5876. submit = true;
  5877. else if (!strncasecmp(mutable, "transactions", 12))
  5878. transactions = true;
  5879. }
  5880. }
  5881. json_decref(val);
  5882. /* Only use GBT if it supports coinbase append and
  5883. * submit coinbase */
  5884. if (append && submit) {
  5885. pool->has_gbt = true;
  5886. pool->rpc_req = gbt_req;
  5887. } else if (transactions) {
  5888. pool->gbt_solo = true;
  5889. pool->rpc_req = gbt_solo_req;
  5890. }
  5891. }
  5892. /* Reset this so we can probe fully just after this. It will be
  5893. * set to true that time.*/
  5894. pool->probed = false;
  5895. if (pool->has_gbt)
  5896. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  5897. else if (pool->gbt_solo)
  5898. applog(LOG_DEBUG, "GBT coinbase without append found, switching to GBT solo protocol");
  5899. else
  5900. applog(LOG_DEBUG, "No GBT coinbase + append support found, using getwork protocol");
  5901. }
  5902. cgtime(&tv_getwork);
  5903. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  5904. pool->rpc_req, true, false, &rolltime, pool, false);
  5905. cgtime(&tv_getwork_reply);
  5906. /* Detect if a http getwork pool has an X-Stratum header at startup,
  5907. * and if so, switch to that in preference to getwork if it works */
  5908. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  5909. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  5910. if (!pool->rpc_url)
  5911. pool->rpc_url = strdup(pool->stratum_url);
  5912. pool->has_stratum = true;
  5913. curl_easy_cleanup(curl);
  5914. goto retry_stratum;
  5915. }
  5916. if (val) {
  5917. struct work *work = make_work();
  5918. bool rc;
  5919. rc = work_decode(pool, work, val);
  5920. if (rc) {
  5921. if (pool->gbt_solo) {
  5922. ret = setup_gbt_solo(curl, pool);
  5923. if (ret)
  5924. pool_start_lp(pool);
  5925. free_work(work);
  5926. goto out;
  5927. }
  5928. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  5929. pool->pool_no, pool->rpc_url);
  5930. work->pool = pool;
  5931. work->rolltime = rolltime;
  5932. copy_time(&work->tv_getwork, &tv_getwork);
  5933. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  5934. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  5935. calc_diff(work, 0);
  5936. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  5937. stage_work(work);
  5938. total_getworks++;
  5939. pool->getwork_requested++;
  5940. ret = true;
  5941. } else {
  5942. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  5943. pool->pool_no, pool->rpc_url);
  5944. free_work(work);
  5945. }
  5946. if (pool->lp_url)
  5947. goto out;
  5948. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  5949. if (pool->hdr_path) {
  5950. char *copy_start, *hdr_path;
  5951. bool need_slash = false;
  5952. size_t siz;
  5953. hdr_path = pool->hdr_path;
  5954. if (strstr(hdr_path, "://")) {
  5955. pool->lp_url = hdr_path;
  5956. hdr_path = NULL;
  5957. } else {
  5958. /* absolute path, on current server */
  5959. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  5960. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  5961. need_slash = true;
  5962. siz = strlen(pool->rpc_url) + strlen(copy_start) + 2;
  5963. pool->lp_url = malloc(siz);
  5964. if (!pool->lp_url) {
  5965. applog(LOG_ERR, "Malloc failure in pool_active");
  5966. return false;
  5967. }
  5968. snprintf(pool->lp_url, siz, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  5969. }
  5970. } else
  5971. pool->lp_url = NULL;
  5972. pool_start_lp(pool);
  5973. } else {
  5974. /* If we failed to parse a getwork, this could be a stratum
  5975. * url without the prefix stratum+tcp:// so let's check it */
  5976. if (initiate_stratum(pool)) {
  5977. pool->has_stratum = true;
  5978. goto retry_stratum;
  5979. }
  5980. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  5981. pool->pool_no, pool->rpc_url);
  5982. if (!pinging && !pool->idle)
  5983. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  5984. }
  5985. out:
  5986. if (val)
  5987. json_decref(val);
  5988. curl_easy_cleanup(curl);
  5989. return ret;
  5990. }
  5991. static void pool_resus(struct pool *pool)
  5992. {
  5993. pool->seq_getfails = 0;
  5994. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  5995. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  5996. else
  5997. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  5998. }
  5999. static bool work_filled;
  6000. static bool work_emptied;
  6001. /* If this is called non_blocking, it will return NULL for work so that must
  6002. * be handled. */
  6003. static struct work *hash_pop(bool blocking)
  6004. {
  6005. struct work *work = NULL, *tmp;
  6006. int hc;
  6007. mutex_lock(stgd_lock);
  6008. if (!HASH_COUNT(staged_work)) {
  6009. /* Increase the queue if we reach zero and we know we can reach
  6010. * the maximum we're asking for. */
  6011. if (work_filled && max_queue < opt_queue) {
  6012. max_queue++;
  6013. work_filled = false;
  6014. }
  6015. work_emptied = true;
  6016. if (!blocking)
  6017. goto out_unlock;
  6018. do {
  6019. struct timespec then;
  6020. struct timeval now;
  6021. int rc;
  6022. cgtime(&now);
  6023. then.tv_sec = now.tv_sec + 10;
  6024. then.tv_nsec = now.tv_usec * 1000;
  6025. pthread_cond_signal(&gws_cond);
  6026. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, &then);
  6027. /* Check again for !no_work as multiple threads may be
  6028. * waiting on this condition and another may set the
  6029. * bool separately. */
  6030. if (rc && !no_work) {
  6031. no_work = true;
  6032. applog(LOG_WARNING, "Waiting for work to be available from pools.");
  6033. }
  6034. } while (!HASH_COUNT(staged_work));
  6035. }
  6036. if (no_work) {
  6037. applog(LOG_WARNING, "Work available from pools, resuming.");
  6038. no_work = false;
  6039. }
  6040. hc = HASH_COUNT(staged_work);
  6041. /* Find clone work if possible, to allow masters to be reused */
  6042. if (hc > staged_rollable) {
  6043. HASH_ITER(hh, staged_work, work, tmp) {
  6044. if (!work_rollable(work))
  6045. break;
  6046. }
  6047. } else
  6048. work = staged_work;
  6049. HASH_DEL(staged_work, work);
  6050. if (work_rollable(work))
  6051. staged_rollable--;
  6052. /* Signal the getwork scheduler to look for more work */
  6053. pthread_cond_signal(&gws_cond);
  6054. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  6055. pthread_cond_signal(&getq->cond);
  6056. /* Keep track of last getwork grabbed */
  6057. last_getwork = time(NULL);
  6058. out_unlock:
  6059. mutex_unlock(stgd_lock);
  6060. return work;
  6061. }
  6062. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  6063. {
  6064. unsigned char hash1[32];
  6065. sha256(data, len, hash1);
  6066. sha256(hash1, 32, hash);
  6067. }
  6068. void set_target(unsigned char *dest_target, double diff)
  6069. {
  6070. unsigned char target[32];
  6071. uint64_t *data64, h64;
  6072. double d64, dcut64;
  6073. if (unlikely(diff == 0.0)) {
  6074. /* This shouldn't happen but best we check to prevent a crash */
  6075. applog(LOG_ERR, "Diff zero passed to set_target");
  6076. diff = 1.0;
  6077. }
  6078. d64 = truediffone;
  6079. if (opt_scrypt)
  6080. d64 *= (double)65536;
  6081. d64 /= diff;
  6082. dcut64 = d64 / bits192;
  6083. h64 = dcut64;
  6084. data64 = (uint64_t *)(target + 24);
  6085. *data64 = htole64(h64);
  6086. dcut64 = h64;
  6087. dcut64 *= bits192;
  6088. d64 -= dcut64;
  6089. dcut64 = d64 / bits128;
  6090. h64 = dcut64;
  6091. data64 = (uint64_t *)(target + 16);
  6092. *data64 = htole64(h64);
  6093. dcut64 = h64;
  6094. dcut64 *= bits128;
  6095. d64 -= dcut64;
  6096. dcut64 = d64 / bits64;
  6097. h64 = dcut64;
  6098. data64 = (uint64_t *)(target + 8);
  6099. *data64 = htole64(h64);
  6100. dcut64 = h64;
  6101. dcut64 *= bits64;
  6102. d64 -= dcut64;
  6103. h64 = d64;
  6104. data64 = (uint64_t *)(target);
  6105. *data64 = htole64(h64);
  6106. if (opt_debug) {
  6107. char *htarget = bin2hex(target, 32);
  6108. applog(LOG_DEBUG, "Generated target %s", htarget);
  6109. free(htarget);
  6110. }
  6111. memcpy(dest_target, target, 32);
  6112. }
  6113. #if defined (USE_AVALON2) || defined (USE_HASHRATIO)
  6114. bool submit_nonce2_nonce(struct thr_info *thr, struct pool *pool, struct pool *real_pool,
  6115. uint32_t nonce2, uint32_t nonce)
  6116. {
  6117. const int thr_id = thr->id;
  6118. struct cgpu_info *cgpu = thr->cgpu;
  6119. struct device_drv *drv = cgpu->drv;
  6120. struct work *work = make_work();
  6121. bool ret;
  6122. cg_wlock(&pool->data_lock);
  6123. pool->nonce2 = nonce2;
  6124. cg_wunlock(&pool->data_lock);
  6125. gen_stratum_work(pool, work);
  6126. work->pool = real_pool;
  6127. work->thr_id = thr_id;
  6128. work->work_block = work_block;
  6129. work->pool->works++;
  6130. work->mined = true;
  6131. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  6132. work->device_diff = MAX(drv->min_diff, work->device_diff);
  6133. ret = submit_nonce(thr, work, nonce);
  6134. free_work(work);
  6135. return ret;
  6136. }
  6137. #endif
  6138. /* Generates stratum based work based on the most recent notify information
  6139. * from the pool. This will keep generating work while a pool is down so we use
  6140. * other means to detect when the pool has died in stratum_thread */
  6141. static void gen_stratum_work(struct pool *pool, struct work *work)
  6142. {
  6143. unsigned char merkle_root[32], merkle_sha[64];
  6144. uint32_t *data32, *swap32;
  6145. uint64_t nonce2le;
  6146. int i;
  6147. cg_wlock(&pool->data_lock);
  6148. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  6149. * from left to right and prevent overflow errors with small n2sizes */
  6150. nonce2le = htole64(pool->nonce2);
  6151. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  6152. work->nonce2 = pool->nonce2++;
  6153. work->nonce2_len = pool->n2size;
  6154. /* Downgrade to a read lock to read off the pool variables */
  6155. cg_dwlock(&pool->data_lock);
  6156. /* Generate merkle root */
  6157. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  6158. memcpy(merkle_sha, merkle_root, 32);
  6159. for (i = 0; i < pool->merkles; i++) {
  6160. memcpy(merkle_sha + 32, pool->swork.merkle_bin[i], 32);
  6161. gen_hash(merkle_sha, merkle_root, 64);
  6162. memcpy(merkle_sha, merkle_root, 32);
  6163. }
  6164. data32 = (uint32_t *)merkle_sha;
  6165. swap32 = (uint32_t *)merkle_root;
  6166. flip32(swap32, data32);
  6167. /* Copy the data template from header_bin */
  6168. memcpy(work->data, pool->header_bin, 112);
  6169. memcpy(work->data + 36, merkle_root, 32);
  6170. /* Store the stratum work diff to check it still matches the pool's
  6171. * stratum diff when submitting shares */
  6172. work->sdiff = pool->sdiff;
  6173. /* Copy parameters required for share submission */
  6174. work->job_id = strdup(pool->swork.job_id);
  6175. work->nonce1 = strdup(pool->nonce1);
  6176. work->ntime = strdup(pool->ntime);
  6177. cg_runlock(&pool->data_lock);
  6178. if (opt_debug) {
  6179. char *header, *merkle_hash;
  6180. header = bin2hex(work->data, 112);
  6181. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  6182. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  6183. applog(LOG_DEBUG, "Generated stratum header %s", header);
  6184. applog(LOG_DEBUG, "Work job_id %s nonce2 %"PRIu64" ntime %s", work->job_id,
  6185. work->nonce2, work->ntime);
  6186. free(header);
  6187. free(merkle_hash);
  6188. }
  6189. calc_midstate(work);
  6190. set_target(work->target, work->sdiff);
  6191. local_work++;
  6192. work->pool = pool;
  6193. work->stratum = true;
  6194. work->nonce = 0;
  6195. work->longpoll = false;
  6196. work->getwork_mode = GETWORK_MODE_STRATUM;
  6197. work->work_block = work_block;
  6198. /* Nominally allow a driver to ntime roll 60 seconds */
  6199. work->drv_rolllimit = 60;
  6200. calc_diff(work, work->sdiff);
  6201. cgtime(&work->tv_staged);
  6202. }
  6203. #ifdef HAVE_LIBCURL
  6204. static void gen_solo_work(struct pool *pool, struct work *work);
  6205. /* Use the one instance of gbt_curl, protecting the bool with the gbt_lock but
  6206. * avoiding holding the lock once we've set the bool. */
  6207. static void get_gbt_curl(struct pool *pool, int poll)
  6208. {
  6209. cg_ilock(&pool->gbt_lock);
  6210. while (pool->gbt_curl_inuse) {
  6211. cg_uilock(&pool->gbt_lock);
  6212. cgsleep_ms(poll);
  6213. cg_ilock(&pool->gbt_lock);
  6214. }
  6215. cg_ulock(&pool->gbt_lock);
  6216. pool->gbt_curl_inuse = true;
  6217. cg_wunlock(&pool->gbt_lock);
  6218. }
  6219. /* No need for locking here */
  6220. static inline void release_gbt_curl(struct pool *pool)
  6221. {
  6222. pool->gbt_curl_inuse = false;
  6223. }
  6224. static void update_gbt_solo(struct pool *pool)
  6225. {
  6226. struct work *work = make_work();
  6227. int rolltime;
  6228. json_t *val;
  6229. get_gbt_curl(pool, 10);
  6230. retry:
  6231. /* Bitcoind doesn't like many open RPC connections. */
  6232. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  6233. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, pool->rpc_req,
  6234. true, false, &rolltime, pool, false);
  6235. if (likely(val)) {
  6236. bool rc = work_decode(pool, work, val);
  6237. if (rc) {
  6238. __setup_gbt_solo(pool);
  6239. gen_solo_work(pool, work);
  6240. stage_work(work);
  6241. } else
  6242. free_work(work);
  6243. json_decref(val);
  6244. } else {
  6245. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get gbt, retrying in 5s",
  6246. pool->pool_no);
  6247. if (++pool->seq_getfails > 5) {
  6248. pool_died(pool);
  6249. goto out;
  6250. }
  6251. cgsleep_ms(5000);
  6252. goto retry;
  6253. }
  6254. out:
  6255. release_gbt_curl(pool);
  6256. }
  6257. static void gen_solo_work(struct pool *pool, struct work *work)
  6258. {
  6259. unsigned char merkle_root[32], merkle_sha[64];
  6260. uint32_t *data32, *swap32;
  6261. struct timeval now;
  6262. uint64_t nonce2le;
  6263. int i;
  6264. cgtime(&now);
  6265. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  6266. update_gbt_solo(pool);
  6267. cg_wlock(&pool->gbt_lock);
  6268. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  6269. * from left to right and prevent overflow errors with small n2sizes */
  6270. nonce2le = htole64(pool->nonce2);
  6271. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  6272. work->nonce2 = pool->nonce2++;
  6273. work->nonce2_len = pool->n2size;
  6274. work->gbt_txns = pool->transactions + 1;
  6275. /* Downgrade to a read lock to read off the pool variables */
  6276. cg_dwlock(&pool->gbt_lock);
  6277. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  6278. /* Generate merkle root */
  6279. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  6280. memcpy(merkle_sha, merkle_root, 32);
  6281. for (i = 0; i < pool->merkles; i++) {
  6282. unsigned char *merkle_bin;
  6283. merkle_bin = pool->merklebin + (i * 32);
  6284. memcpy(merkle_sha + 32, merkle_bin, 32);
  6285. gen_hash(merkle_sha, merkle_root, 64);
  6286. memcpy(merkle_sha, merkle_root, 32);
  6287. }
  6288. data32 = (uint32_t *)merkle_sha;
  6289. swap32 = (uint32_t *)merkle_root;
  6290. flip32(swap32, data32);
  6291. /* Copy the data template from header_bin */
  6292. memcpy(work->data, pool->header_bin, 112);
  6293. memcpy(work->data + 36, merkle_root, 32);
  6294. work->sdiff = pool->sdiff;
  6295. /* Copy parameters required for share submission */
  6296. work->ntime = strdup(pool->ntime);
  6297. memcpy(work->target, pool->gbt_target, 32);
  6298. cg_runlock(&pool->gbt_lock);
  6299. if (opt_debug) {
  6300. char *header, *merkle_hash;
  6301. header = bin2hex(work->data, 112);
  6302. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  6303. applog(LOG_DEBUG, "Generated GBT solo merkle %s", merkle_hash);
  6304. applog(LOG_DEBUG, "Generated GBT solo header %s", header);
  6305. applog(LOG_DEBUG, "Work nonce2 %"PRIu64" ntime %s", work->nonce2,
  6306. work->ntime);
  6307. free(header);
  6308. free(merkle_hash);
  6309. }
  6310. calc_midstate(work);
  6311. local_work++;
  6312. work->gbt = true;
  6313. work->pool = pool;
  6314. work->nonce = 0;
  6315. work->longpoll = false;
  6316. work->getwork_mode = GETWORK_MODE_SOLO;
  6317. work->work_block = work_block;
  6318. /* Nominally allow a driver to ntime roll 60 seconds */
  6319. work->drv_rolllimit = 60;
  6320. calc_diff(work, work->sdiff);
  6321. cgtime(&work->tv_staged);
  6322. }
  6323. #endif
  6324. /* The time difference in seconds between when this device last got work via
  6325. * get_work() and generated a valid share. */
  6326. int share_work_tdiff(struct cgpu_info *cgpu)
  6327. {
  6328. return last_getwork - cgpu->last_device_valid_work;
  6329. }
  6330. static void set_benchmark_work(struct cgpu_info *cgpu, struct work *work)
  6331. {
  6332. cgpu->lodiff += cgpu->direction;
  6333. if (cgpu->lodiff < 1)
  6334. cgpu->direction = 1;
  6335. if (cgpu->lodiff > 15) {
  6336. cgpu->direction = -1;
  6337. if (++cgpu->hidiff > 15)
  6338. cgpu->hidiff = 0;
  6339. memcpy(work, &bench_hidiff_bins[cgpu->hidiff][0], 160);
  6340. } else
  6341. memcpy(work, &bench_lodiff_bins[cgpu->lodiff][0], 160);
  6342. }
  6343. struct work *get_work(struct thr_info *thr, const int thr_id)
  6344. {
  6345. struct cgpu_info *cgpu = thr->cgpu;
  6346. struct work *work = NULL;
  6347. time_t diff_t;
  6348. thread_reportout(thr);
  6349. applog(LOG_DEBUG, "Popping work from get queue to get work");
  6350. diff_t = time(NULL);
  6351. while (!work) {
  6352. work = hash_pop(true);
  6353. if (stale_work(work, false)) {
  6354. discard_work(work);
  6355. wake_gws();
  6356. }
  6357. }
  6358. diff_t = time(NULL) - diff_t;
  6359. /* Since this is a blocking function, we need to add grace time to
  6360. * the device's last valid work to not make outages appear to be
  6361. * device failures. */
  6362. if (diff_t > 0) {
  6363. applog(LOG_DEBUG, "Get work blocked for %d seconds", (int)diff_t);
  6364. cgpu->last_device_valid_work += diff_t;
  6365. }
  6366. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  6367. work->thr_id = thr_id;
  6368. if (opt_benchmark)
  6369. set_benchmark_work(cgpu, work);
  6370. thread_reportin(thr);
  6371. work->mined = true;
  6372. work->device_diff = MIN(cgpu->drv->max_diff, work->work_difficulty);
  6373. work->device_diff = MAX(cgpu->drv->min_diff, work->device_diff);
  6374. return work;
  6375. }
  6376. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  6377. static void submit_work_async(struct work *work)
  6378. {
  6379. struct pool *pool = work->pool;
  6380. pthread_t submit_thread;
  6381. cgtime(&work->tv_work_found);
  6382. if (opt_benchmark) {
  6383. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  6384. mutex_lock(&stats_lock);
  6385. cgpu->accepted++;
  6386. total_accepted++;
  6387. pool->accepted++;
  6388. cgpu->diff_accepted += work->work_difficulty;
  6389. total_diff_accepted += work->work_difficulty;
  6390. pool->diff_accepted += work->work_difficulty;
  6391. mutex_unlock(&stats_lock);
  6392. applog(LOG_NOTICE, "Accepted %s %d benchmark share nonce %08x",
  6393. cgpu->drv->name, cgpu->device_id, *(uint32_t *)(work->data + 64 + 12));
  6394. return;
  6395. }
  6396. if (stale_work(work, true)) {
  6397. if (opt_submit_stale)
  6398. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  6399. else if (pool->submit_old)
  6400. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  6401. else {
  6402. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  6403. sharelog("discard", work);
  6404. mutex_lock(&stats_lock);
  6405. total_stale++;
  6406. pool->stale_shares++;
  6407. total_diff_stale += work->work_difficulty;
  6408. pool->diff_stale += work->work_difficulty;
  6409. mutex_unlock(&stats_lock);
  6410. free_work(work);
  6411. return;
  6412. }
  6413. work->stale = true;
  6414. }
  6415. if (work->stratum) {
  6416. applog(LOG_DEBUG, "Pushing pool %d work to stratum queue", pool->pool_no);
  6417. if (unlikely(!tq_push(pool->stratum_q, work))) {
  6418. applog(LOG_DEBUG, "Discarding work from removed pool");
  6419. free_work(work);
  6420. }
  6421. } else {
  6422. applog(LOG_DEBUG, "Pushing submit work to work thread");
  6423. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  6424. quit(1, "Failed to create submit_work_thread");
  6425. }
  6426. }
  6427. void inc_hw_errors(struct thr_info *thr)
  6428. {
  6429. applog(LOG_INFO, "%s%d: invalid nonce - HW error", thr->cgpu->drv->name,
  6430. thr->cgpu->device_id);
  6431. mutex_lock(&stats_lock);
  6432. hw_errors++;
  6433. thr->cgpu->hw_errors++;
  6434. mutex_unlock(&stats_lock);
  6435. thr->cgpu->drv->hw_error(thr);
  6436. }
  6437. /* Fills in the work nonce and builds the output data in work->hash */
  6438. static void rebuild_nonce(struct work *work, uint32_t nonce)
  6439. {
  6440. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  6441. *work_nonce = htole32(nonce);
  6442. rebuild_hash(work);
  6443. }
  6444. /* For testing a nonce against diff 1 */
  6445. bool test_nonce(struct work *work, uint32_t nonce)
  6446. {
  6447. uint32_t *hash_32 = (uint32_t *)(work->hash + 28);
  6448. rebuild_nonce(work, nonce);
  6449. return (*hash_32 <= (opt_scrypt ? 0x0000ffffUL : 0));
  6450. }
  6451. /* For testing a nonce against an arbitrary diff */
  6452. bool test_nonce_diff(struct work *work, uint32_t nonce, double diff)
  6453. {
  6454. uint64_t *hash64 = (uint64_t *)(work->hash + 24), diff64;
  6455. rebuild_nonce(work, nonce);
  6456. diff64 = opt_scrypt ? 0x0000ffff00000000ULL : 0x00000000ffff0000ULL;
  6457. diff64 /= diff;
  6458. return (le64toh(*hash64) <= diff64);
  6459. }
  6460. static void update_work_stats(struct thr_info *thr, struct work *work)
  6461. {
  6462. double test_diff = current_diff;
  6463. work->share_diff = share_diff(work);
  6464. if (opt_scrypt)
  6465. test_diff *= (double)65536;
  6466. if (unlikely(work->share_diff >= test_diff)) {
  6467. work->block = true;
  6468. work->pool->solved++;
  6469. found_blocks++;
  6470. work->mandatory = true;
  6471. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  6472. }
  6473. mutex_lock(&stats_lock);
  6474. total_diff1 += work->device_diff;
  6475. thr->cgpu->diff1 += work->device_diff;
  6476. work->pool->diff1 += work->device_diff;
  6477. thr->cgpu->last_device_valid_work = time(NULL);
  6478. mutex_unlock(&stats_lock);
  6479. }
  6480. /* To be used once the work has been tested to be meet diff1 and has had its
  6481. * nonce adjusted. Returns true if the work target is met. */
  6482. bool submit_tested_work(struct thr_info *thr, struct work *work)
  6483. {
  6484. struct work *work_out;
  6485. update_work_stats(thr, work);
  6486. if (!fulltest(work->hash, work->target)) {
  6487. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  6488. thr->cgpu->device_id);
  6489. return false;
  6490. }
  6491. work_out = copy_work(work);
  6492. submit_work_async(work_out);
  6493. return true;
  6494. }
  6495. /* Returns true if nonce for work was a valid share */
  6496. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  6497. {
  6498. if (test_nonce(work, nonce))
  6499. submit_tested_work(thr, work);
  6500. else {
  6501. inc_hw_errors(thr);
  6502. return false;
  6503. }
  6504. if (opt_benchfile && opt_benchfile_display)
  6505. benchfile_dspwork(work, nonce);
  6506. return true;
  6507. }
  6508. /* Allows drivers to submit work items where the driver has changed the ntime
  6509. * value by noffset. Must be only used with a work protocol that does not ntime
  6510. * roll itself intrinsically to generate work (eg stratum). We do not touch
  6511. * the original work struct, but the copy of it only. */
  6512. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  6513. int noffset)
  6514. {
  6515. struct work *work = make_work();
  6516. bool ret = false;
  6517. _copy_work(work, work_in, noffset);
  6518. if (!test_nonce(work, nonce)) {
  6519. free_work(work);
  6520. inc_hw_errors(thr);
  6521. goto out;
  6522. }
  6523. update_work_stats(thr, work);
  6524. if (opt_benchfile && opt_benchfile_display)
  6525. benchfile_dspwork(work, nonce);
  6526. ret = true;
  6527. if (!fulltest(work->hash, work->target)) {
  6528. free_work(work);
  6529. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  6530. thr->cgpu->device_id);
  6531. goto out;
  6532. }
  6533. submit_work_async(work);
  6534. out:
  6535. return ret;
  6536. }
  6537. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  6538. {
  6539. if (wdiff->tv_sec > opt_scantime || hashes >= 0xfffffffe ||
  6540. stale_work(work, false))
  6541. return true;
  6542. return false;
  6543. }
  6544. static void mt_disable(struct thr_info *mythr, const int thr_id,
  6545. struct device_drv *drv)
  6546. {
  6547. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  6548. mythr->cgpu->rolling = 0;
  6549. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  6550. cgsem_wait(&mythr->sem);
  6551. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  6552. drv->thread_enable(mythr);
  6553. }
  6554. /* The main hashing loop for devices that are slow enough to work on one work
  6555. * item at a time, without a queue, aborting work before the entire nonce
  6556. * range has been hashed if needed. */
  6557. static void hash_sole_work(struct thr_info *mythr)
  6558. {
  6559. const int thr_id = mythr->id;
  6560. struct cgpu_info *cgpu = mythr->cgpu;
  6561. struct device_drv *drv = cgpu->drv;
  6562. struct timeval getwork_start, tv_start, *tv_end, tv_workstart, tv_lastupdate;
  6563. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  6564. struct cgminer_stats *pool_stats;
  6565. /* Try to cycle approximately 5 times before each log update */
  6566. const long cycle = opt_log_interval / 5 ? : 1;
  6567. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  6568. struct timeval diff, sdiff, wdiff = {0, 0};
  6569. uint32_t max_nonce = drv->can_limit_work(mythr);
  6570. int64_t hashes_done = 0;
  6571. tv_end = &getwork_start;
  6572. cgtime(&getwork_start);
  6573. sdiff.tv_sec = sdiff.tv_usec = 0;
  6574. cgtime(&tv_lastupdate);
  6575. while (likely(!cgpu->shutdown)) {
  6576. struct work *work = get_work(mythr, thr_id);
  6577. int64_t hashes;
  6578. mythr->work_restart = false;
  6579. cgpu->new_work = true;
  6580. cgtime(&tv_workstart);
  6581. work->nonce = 0;
  6582. cgpu->max_hashes = 0;
  6583. if (!drv->prepare_work(mythr, work)) {
  6584. applog(LOG_ERR, "work prepare failed, exiting "
  6585. "mining thread %d", thr_id);
  6586. break;
  6587. }
  6588. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  6589. work->device_diff = MAX(drv->min_diff, work->device_diff);
  6590. do {
  6591. cgtime(&tv_start);
  6592. subtime(&tv_start, &getwork_start);
  6593. addtime(&getwork_start, &dev_stats->getwork_wait);
  6594. if (time_more(&getwork_start, &dev_stats->getwork_wait_max))
  6595. copy_time(&dev_stats->getwork_wait_max, &getwork_start);
  6596. if (time_less(&getwork_start, &dev_stats->getwork_wait_min))
  6597. copy_time(&dev_stats->getwork_wait_min, &getwork_start);
  6598. dev_stats->getwork_calls++;
  6599. pool_stats = &(work->pool->cgminer_stats);
  6600. addtime(&getwork_start, &pool_stats->getwork_wait);
  6601. if (time_more(&getwork_start, &pool_stats->getwork_wait_max))
  6602. copy_time(&pool_stats->getwork_wait_max, &getwork_start);
  6603. if (time_less(&getwork_start, &pool_stats->getwork_wait_min))
  6604. copy_time(&pool_stats->getwork_wait_min, &getwork_start);
  6605. pool_stats->getwork_calls++;
  6606. cgtime(&(work->tv_work_start));
  6607. /* Only allow the mining thread to be cancelled when
  6608. * it is not in the driver code. */
  6609. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  6610. thread_reportin(mythr);
  6611. hashes = drv->scanhash(mythr, work, work->nonce + max_nonce);
  6612. thread_reportout(mythr);
  6613. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  6614. pthread_testcancel();
  6615. /* tv_end is == &getwork_start */
  6616. cgtime(&getwork_start);
  6617. if (unlikely(hashes == -1)) {
  6618. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6619. cgpu->deven = DEV_DISABLED;
  6620. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6621. cgpu->shutdown = true;
  6622. break;
  6623. }
  6624. hashes_done += hashes;
  6625. if (hashes > cgpu->max_hashes)
  6626. cgpu->max_hashes = hashes;
  6627. timersub(tv_end, &tv_start, &diff);
  6628. sdiff.tv_sec += diff.tv_sec;
  6629. sdiff.tv_usec += diff.tv_usec;
  6630. if (sdiff.tv_usec > 1000000) {
  6631. ++sdiff.tv_sec;
  6632. sdiff.tv_usec -= 1000000;
  6633. }
  6634. timersub(tv_end, &tv_workstart, &wdiff);
  6635. if (unlikely((long)sdiff.tv_sec < cycle)) {
  6636. int mult;
  6637. if (likely(max_nonce == 0xffffffff))
  6638. continue;
  6639. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  6640. mult *= cycle;
  6641. if (max_nonce > (0xffffffff * 0x400) / mult)
  6642. max_nonce = 0xffffffff;
  6643. else
  6644. max_nonce = (max_nonce * mult) / 0x400;
  6645. } else if (unlikely(sdiff.tv_sec > cycle))
  6646. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  6647. else if (unlikely(sdiff.tv_usec > 100000))
  6648. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  6649. timersub(tv_end, &tv_lastupdate, &diff);
  6650. /* Update the hashmeter at most 5 times per second */
  6651. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6652. diff.tv_sec >= opt_log_interval) {
  6653. hashmeter(thr_id, hashes_done);
  6654. hashes_done = 0;
  6655. copy_time(&tv_lastupdate, tv_end);
  6656. }
  6657. if (unlikely(mythr->work_restart)) {
  6658. /* Apart from device_thread 0, we stagger the
  6659. * starting of every next thread to try and get
  6660. * all devices busy before worrying about
  6661. * getting work for their extra threads */
  6662. if (!primary) {
  6663. struct timespec rgtp;
  6664. rgtp.tv_sec = 0;
  6665. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  6666. nanosleep(&rgtp, NULL);
  6667. }
  6668. break;
  6669. }
  6670. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6671. mt_disable(mythr, thr_id, drv);
  6672. sdiff.tv_sec = sdiff.tv_usec = 0;
  6673. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  6674. free_work(work);
  6675. }
  6676. cgpu->deven = DEV_DISABLED;
  6677. }
  6678. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  6679. * the driver tells us it's full so that it may extract the work item using
  6680. * the get_queued() function which adds it to the hashtable on
  6681. * cgpu->queued_work. */
  6682. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  6683. {
  6684. do {
  6685. bool need_work;
  6686. /* Do this lockless just to know if we need more unqueued work. */
  6687. need_work = (!cgpu->unqueued_work);
  6688. /* get_work is a blocking function so do it outside of lock
  6689. * to prevent deadlocks with other locks. */
  6690. if (need_work) {
  6691. struct work *work = get_work(mythr, thr_id);
  6692. wr_lock(&cgpu->qlock);
  6693. /* Check we haven't grabbed work somehow between
  6694. * checking and picking up the lock. */
  6695. if (likely(!cgpu->unqueued_work))
  6696. cgpu->unqueued_work = work;
  6697. else
  6698. need_work = false;
  6699. wr_unlock(&cgpu->qlock);
  6700. if (unlikely(!need_work))
  6701. discard_work(work);
  6702. }
  6703. /* The queue_full function should be used by the driver to
  6704. * actually place work items on the physical device if it
  6705. * does have a queue. */
  6706. } while (!drv->queue_full(cgpu));
  6707. }
  6708. /* Add a work item to a cgpu's queued hashlist */
  6709. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  6710. {
  6711. cgpu->queued_count++;
  6712. HASH_ADD_INT(cgpu->queued_work, id, work);
  6713. }
  6714. struct work *__get_queued(struct cgpu_info *cgpu)
  6715. {
  6716. struct work *work = NULL;
  6717. if (cgpu->unqueued_work) {
  6718. work = cgpu->unqueued_work;
  6719. if (unlikely(stale_work(work, false))) {
  6720. discard_work(work);
  6721. } else
  6722. __add_queued(cgpu, work);
  6723. cgpu->unqueued_work = NULL;
  6724. wake_gws();
  6725. }
  6726. return work;
  6727. }
  6728. /* This function is for retrieving one work item from the unqueued pointer and
  6729. * adding it to the hashtable of queued work. Code using this function must be
  6730. * able to handle NULL as a return which implies there is no work available. */
  6731. struct work *get_queued(struct cgpu_info *cgpu)
  6732. {
  6733. struct work *work;
  6734. wr_lock(&cgpu->qlock);
  6735. work = __get_queued(cgpu);
  6736. wr_unlock(&cgpu->qlock);
  6737. return work;
  6738. }
  6739. void add_queued(struct cgpu_info *cgpu, struct work *work)
  6740. {
  6741. wr_lock(&cgpu->qlock);
  6742. __add_queued(cgpu, work);
  6743. wr_unlock(&cgpu->qlock);
  6744. }
  6745. /* Get fresh work and add it to cgpu's queued hashlist */
  6746. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  6747. {
  6748. struct work *work = get_work(thr, thr_id);
  6749. add_queued(cgpu, work);
  6750. return work;
  6751. }
  6752. /* This function is for finding an already queued work item in the
  6753. * given que hashtable. Code using this function must be able
  6754. * to handle NULL as a return which implies there is no matching work.
  6755. * The calling function must lock access to the que if it is required.
  6756. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6757. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6758. {
  6759. struct work *work, *tmp, *ret = NULL;
  6760. HASH_ITER(hh, que, work, tmp) {
  6761. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  6762. memcmp(work->data + offset, data, datalen) == 0) {
  6763. ret = work;
  6764. break;
  6765. }
  6766. }
  6767. return ret;
  6768. }
  6769. /* This function is for finding an already queued work item in the
  6770. * device's queued_work hashtable. Code using this function must be able
  6771. * to handle NULL as a return which implies there is no matching work.
  6772. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6773. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6774. {
  6775. struct work *ret;
  6776. rd_lock(&cgpu->qlock);
  6777. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6778. rd_unlock(&cgpu->qlock);
  6779. return ret;
  6780. }
  6781. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6782. {
  6783. struct work *work, *ret = NULL;
  6784. rd_lock(&cgpu->qlock);
  6785. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6786. if (work)
  6787. ret = copy_work(work);
  6788. rd_unlock(&cgpu->qlock);
  6789. return ret;
  6790. }
  6791. /* This function is for finding an already queued work item in the
  6792. * given que hashtable. Code using this function must be able
  6793. * to handle NULL as a return which implies there is no matching work.
  6794. * The calling function must lock access to the que if it is required. */
  6795. struct work *__find_work_byid(struct work *que, uint32_t id)
  6796. {
  6797. struct work *work, *tmp, *ret = NULL;
  6798. HASH_ITER(hh, que, work, tmp) {
  6799. if (work->id == id) {
  6800. ret = work;
  6801. break;
  6802. }
  6803. }
  6804. return ret;
  6805. }
  6806. struct work *find_queued_work_byid(struct cgpu_info *cgpu, uint32_t id)
  6807. {
  6808. struct work *ret;
  6809. rd_lock(&cgpu->qlock);
  6810. ret = __find_work_byid(cgpu->queued_work, id);
  6811. rd_unlock(&cgpu->qlock);
  6812. return ret;
  6813. }
  6814. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  6815. {
  6816. cgpu->queued_count--;
  6817. HASH_DEL(cgpu->queued_work, work);
  6818. }
  6819. /* This iterates over a queued hashlist finding work started more than secs
  6820. * seconds ago and discards the work as completed. The driver must set the
  6821. * work->tv_work_start value appropriately. Returns the number of items aged. */
  6822. int age_queued_work(struct cgpu_info *cgpu, double secs)
  6823. {
  6824. struct work *work, *tmp;
  6825. struct timeval tv_now;
  6826. int aged = 0;
  6827. cgtime(&tv_now);
  6828. wr_lock(&cgpu->qlock);
  6829. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  6830. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  6831. __work_completed(cgpu, work);
  6832. free_work(work);
  6833. aged++;
  6834. }
  6835. }
  6836. wr_unlock(&cgpu->qlock);
  6837. return aged;
  6838. }
  6839. /* This function should be used by queued device drivers when they're sure
  6840. * the work struct is no longer in use. */
  6841. void work_completed(struct cgpu_info *cgpu, struct work *work)
  6842. {
  6843. wr_lock(&cgpu->qlock);
  6844. __work_completed(cgpu, work);
  6845. wr_unlock(&cgpu->qlock);
  6846. free_work(work);
  6847. }
  6848. /* Combines find_queued_work_bymidstate and work_completed in one function
  6849. * withOUT destroying the work so the driver must free it. */
  6850. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6851. {
  6852. struct work *work;
  6853. wr_lock(&cgpu->qlock);
  6854. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6855. if (work)
  6856. __work_completed(cgpu, work);
  6857. wr_unlock(&cgpu->qlock);
  6858. return work;
  6859. }
  6860. void flush_queue(struct cgpu_info *cgpu)
  6861. {
  6862. struct work *work = NULL;
  6863. if (unlikely(!cgpu))
  6864. return;
  6865. /* Use only a trylock in case we get into a deadlock with a queueing
  6866. * function holding the read lock when we're called. */
  6867. if (wr_trylock(&cgpu->qlock))
  6868. return;
  6869. work = cgpu->unqueued_work;
  6870. cgpu->unqueued_work = NULL;
  6871. wr_unlock(&cgpu->qlock);
  6872. if (work) {
  6873. free_work(work);
  6874. applog(LOG_DEBUG, "Discarded queued work item");
  6875. }
  6876. }
  6877. /* This version of hash work is for devices that are fast enough to always
  6878. * perform a full nonce range and need a queue to maintain the device busy.
  6879. * Work creation and destruction is not done from within this function
  6880. * directly. */
  6881. void hash_queued_work(struct thr_info *mythr)
  6882. {
  6883. struct timeval tv_start = {0, 0}, tv_end;
  6884. struct cgpu_info *cgpu = mythr->cgpu;
  6885. struct device_drv *drv = cgpu->drv;
  6886. const int thr_id = mythr->id;
  6887. int64_t hashes_done = 0;
  6888. while (likely(!cgpu->shutdown)) {
  6889. struct timeval diff;
  6890. int64_t hashes;
  6891. mythr->work_update = false;
  6892. fill_queue(mythr, cgpu, drv, thr_id);
  6893. hashes = drv->scanwork(mythr);
  6894. /* Reset the bool here in case the driver looks for it
  6895. * synchronously in the scanwork loop. */
  6896. mythr->work_restart = false;
  6897. if (unlikely(hashes == -1 )) {
  6898. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6899. cgpu->deven = DEV_DISABLED;
  6900. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6901. break;
  6902. }
  6903. hashes_done += hashes;
  6904. cgtime(&tv_end);
  6905. timersub(&tv_end, &tv_start, &diff);
  6906. /* Update the hashmeter at most 5 times per second */
  6907. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6908. diff.tv_sec >= opt_log_interval) {
  6909. hashmeter(thr_id, hashes_done);
  6910. hashes_done = 0;
  6911. copy_time(&tv_start, &tv_end);
  6912. }
  6913. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6914. mt_disable(mythr, thr_id, drv);
  6915. if (mythr->work_update)
  6916. drv->update_work(cgpu);
  6917. }
  6918. cgpu->deven = DEV_DISABLED;
  6919. }
  6920. /* This version of hash_work is for devices drivers that want to do their own
  6921. * work management entirely, usually by using get_work(). Note that get_work
  6922. * is a blocking function and will wait indefinitely if no work is available
  6923. * so this must be taken into consideration in the driver. */
  6924. void hash_driver_work(struct thr_info *mythr)
  6925. {
  6926. struct timeval tv_start = {0, 0}, tv_end;
  6927. struct cgpu_info *cgpu = mythr->cgpu;
  6928. struct device_drv *drv = cgpu->drv;
  6929. const int thr_id = mythr->id;
  6930. int64_t hashes_done = 0;
  6931. while (likely(!cgpu->shutdown)) {
  6932. struct timeval diff;
  6933. int64_t hashes;
  6934. mythr->work_update = false;
  6935. hashes = drv->scanwork(mythr);
  6936. /* Reset the bool here in case the driver looks for it
  6937. * synchronously in the scanwork loop. */
  6938. mythr->work_restart = false;
  6939. if (unlikely(hashes == -1 )) {
  6940. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6941. cgpu->deven = DEV_DISABLED;
  6942. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6943. break;
  6944. }
  6945. hashes_done += hashes;
  6946. cgtime(&tv_end);
  6947. timersub(&tv_end, &tv_start, &diff);
  6948. /* Update the hashmeter at most 5 times per second */
  6949. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6950. diff.tv_sec >= opt_log_interval) {
  6951. hashmeter(thr_id, hashes_done);
  6952. hashes_done = 0;
  6953. copy_time(&tv_start, &tv_end);
  6954. }
  6955. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6956. mt_disable(mythr, thr_id, drv);
  6957. if (mythr->work_update)
  6958. drv->update_work(cgpu);
  6959. }
  6960. cgpu->deven = DEV_DISABLED;
  6961. }
  6962. void *miner_thread(void *userdata)
  6963. {
  6964. struct thr_info *mythr = userdata;
  6965. const int thr_id = mythr->id;
  6966. struct cgpu_info *cgpu = mythr->cgpu;
  6967. struct device_drv *drv = cgpu->drv;
  6968. char threadname[16];
  6969. snprintf(threadname, sizeof(threadname), "%d/Miner", thr_id);
  6970. RenameThread(threadname);
  6971. thread_reportout(mythr);
  6972. if (!drv->thread_init(mythr)) {
  6973. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  6974. goto out;
  6975. }
  6976. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  6977. cgsem_wait(&mythr->sem);
  6978. cgpu->last_device_valid_work = time(NULL);
  6979. drv->hash_work(mythr);
  6980. drv->thread_shutdown(mythr);
  6981. out:
  6982. return NULL;
  6983. }
  6984. enum {
  6985. STAT_SLEEP_INTERVAL = 1,
  6986. STAT_CTR_INTERVAL = 10000000,
  6987. FAILURE_INTERVAL = 30,
  6988. };
  6989. #ifdef HAVE_LIBCURL
  6990. /* Stage another work item from the work returned in a longpoll */
  6991. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  6992. {
  6993. struct work *work;
  6994. bool rc;
  6995. work = make_work();
  6996. rc = work_decode(pool, work, val);
  6997. if (unlikely(!rc)) {
  6998. applog(LOG_ERR, "Could not convert longpoll data to work");
  6999. free_work(work);
  7000. return;
  7001. }
  7002. total_getworks++;
  7003. pool->getwork_requested++;
  7004. work->pool = pool;
  7005. work->rolltime = rolltime;
  7006. copy_time(&work->tv_getwork, tv_lp);
  7007. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  7008. calc_diff(work, 0);
  7009. if (pool->enabled == POOL_REJECTING)
  7010. work->mandatory = true;
  7011. if (pool->has_gbt)
  7012. gen_gbt_work(pool, work);
  7013. work->longpoll = true;
  7014. work->getwork_mode = GETWORK_MODE_LP;
  7015. /* We'll be checking this work item twice, but we already know it's
  7016. * from a new block so explicitly force the new block detection now
  7017. * rather than waiting for it to hit the stage thread. This also
  7018. * allows testwork to know whether LP discovered the block or not. */
  7019. test_work_current(work);
  7020. /* Don't use backup LPs as work if we have failover-only enabled. Use
  7021. * the longpoll work from a pool that has been rejecting shares as a
  7022. * way to detect when the pool has recovered.
  7023. */
  7024. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  7025. free_work(work);
  7026. return;
  7027. }
  7028. work = clone_work(work);
  7029. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  7030. stage_work(work);
  7031. applog(LOG_DEBUG, "Converted longpoll data to work");
  7032. }
  7033. /* If we want longpoll, enable it for the chosen default pool, or, if
  7034. * the pool does not support longpoll, find the first one that does
  7035. * and use its longpoll support */
  7036. static struct pool *select_longpoll_pool(struct pool *cp)
  7037. {
  7038. int i;
  7039. if (cp->hdr_path || cp->has_gbt || cp->gbt_solo)
  7040. return cp;
  7041. for (i = 0; i < total_pools; i++) {
  7042. struct pool *pool = pools[i];
  7043. if (pool->has_stratum || pool->hdr_path)
  7044. return pool;
  7045. }
  7046. return NULL;
  7047. }
  7048. #endif /* HAVE_LIBCURL */
  7049. /* This will make the longpoll thread wait till it's the current pool, or it
  7050. * has been flagged as rejecting, before attempting to open any connections.
  7051. */
  7052. static void wait_lpcurrent(struct pool *pool)
  7053. {
  7054. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  7055. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  7056. pool_strategy != POOL_BALANCE))) {
  7057. mutex_lock(&lp_lock);
  7058. pthread_cond_wait(&lp_cond, &lp_lock);
  7059. mutex_unlock(&lp_lock);
  7060. }
  7061. }
  7062. #ifdef HAVE_LIBCURL
  7063. static void *longpoll_thread(void *userdata)
  7064. {
  7065. struct pool *cp = (struct pool *)userdata;
  7066. /* This *pool is the source of the actual longpoll, not the pool we've
  7067. * tied it to */
  7068. struct timeval start, reply, end;
  7069. struct pool *pool = NULL;
  7070. char threadname[16];
  7071. CURL *curl = NULL;
  7072. int failures = 0;
  7073. char lpreq[1024];
  7074. char *lp_url;
  7075. int rolltime;
  7076. snprintf(threadname, sizeof(threadname), "%d/Longpoll", cp->pool_no);
  7077. RenameThread(threadname);
  7078. retry_pool:
  7079. pool = select_longpoll_pool(cp);
  7080. if (!pool) {
  7081. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  7082. while (!pool) {
  7083. cgsleep_ms(60000);
  7084. pool = select_longpoll_pool(cp);
  7085. }
  7086. }
  7087. if (pool->has_stratum) {
  7088. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7089. cp->rpc_url, pool->rpc_url);
  7090. goto out;
  7091. }
  7092. if (pool->gbt_solo) {
  7093. applog(LOG_WARNING, "Block change for %s detection via getblockcount polling",
  7094. cp->rpc_url);
  7095. while (42) {
  7096. json_t *val, *res_val = NULL;
  7097. if (unlikely(pool->removed))
  7098. return NULL;
  7099. cgtime(&start);
  7100. wait_lpcurrent(cp);
  7101. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockcount\"}\n");
  7102. /* We will be making another call immediately after this
  7103. * one to get the height so allow this curl to be reused.*/
  7104. get_gbt_curl(pool, 500);
  7105. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 0);
  7106. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, lpreq, true,
  7107. false, &rolltime, pool, false);
  7108. release_gbt_curl(pool);
  7109. if (likely(val))
  7110. res_val = json_object_get(val, "result");
  7111. if (likely(res_val)) {
  7112. int height = json_integer_value(res_val);
  7113. const char *prev_hash;
  7114. failures = 0;
  7115. json_decref(val);
  7116. if (height >= cp->height) {
  7117. applog(LOG_WARNING, "Block height change to %d detected on pool %d",
  7118. height, cp->pool_no);
  7119. update_gbt_solo(pool);
  7120. continue;
  7121. }
  7122. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockhash\", \"params\": [%d]}\n", height);
  7123. get_gbt_curl(pool, 500);
  7124. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  7125. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass,
  7126. lpreq, true, false, &rolltime, pool, false);
  7127. release_gbt_curl(pool);
  7128. if (val) {
  7129. /* Do a comparison on a short stretch of
  7130. * the hash to make sure it hasn't changed
  7131. * due to mining on an orphan branch. */
  7132. prev_hash = json_string_value(json_object_get(val, "result"));
  7133. if (unlikely(prev_hash && strncasecmp(prev_hash + 56, pool->prev_hash, 8))) {
  7134. applog(LOG_WARNING, "Mining on orphan branch detected, switching!");
  7135. update_gbt_solo(pool);
  7136. }
  7137. json_decref(val);
  7138. }
  7139. cgsleep_ms(500);
  7140. } else {
  7141. if (val)
  7142. json_decref(val);
  7143. cgtime(&end);
  7144. if (end.tv_sec - start.tv_sec > 30)
  7145. continue;
  7146. if (failures == 1)
  7147. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7148. cgsleep_ms(30000);
  7149. }
  7150. }
  7151. }
  7152. curl = curl_easy_init();
  7153. if (unlikely(!curl))
  7154. quit (1, "Longpoll CURL initialisation failed");
  7155. /* Any longpoll from any pool is enough for this to be true */
  7156. have_longpoll = true;
  7157. wait_lpcurrent(cp);
  7158. if (pool->has_gbt) {
  7159. lp_url = pool->rpc_url;
  7160. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  7161. } else {
  7162. strcpy(lpreq, getwork_req);
  7163. lp_url = pool->lp_url;
  7164. if (cp == pool)
  7165. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  7166. else
  7167. applog(LOG_WARNING, "Long-polling activated for %s via %s", cp->rpc_url, lp_url);
  7168. }
  7169. while (42) {
  7170. json_t *val, *soval;
  7171. wait_lpcurrent(cp);
  7172. cgtime(&start);
  7173. /* Update the longpollid every time, but do it under lock to
  7174. * avoid races */
  7175. if (pool->has_gbt) {
  7176. cg_rlock(&pool->gbt_lock);
  7177. snprintf(lpreq, sizeof(lpreq),
  7178. "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  7179. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  7180. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  7181. cg_runlock(&pool->gbt_lock);
  7182. }
  7183. /* Longpoll connections can be persistent for a very long time
  7184. * and any number of issues could have come up in the meantime
  7185. * so always establish a fresh connection instead of relying on
  7186. * a persistent one. */
  7187. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  7188. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  7189. lpreq, false, true, &rolltime, pool, false);
  7190. cgtime(&reply);
  7191. if (likely(val)) {
  7192. soval = json_object_get(json_object_get(val, "result"), "submitold");
  7193. if (soval)
  7194. pool->submit_old = json_is_true(soval);
  7195. else
  7196. pool->submit_old = false;
  7197. convert_to_work(val, rolltime, pool, &start, &reply);
  7198. failures = 0;
  7199. json_decref(val);
  7200. } else {
  7201. /* Some pools regularly drop the longpoll request so
  7202. * only see this as longpoll failure if it happens
  7203. * immediately and just restart it the rest of the
  7204. * time. */
  7205. cgtime(&end);
  7206. if (end.tv_sec - start.tv_sec > 30)
  7207. continue;
  7208. if (failures == 1)
  7209. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7210. cgsleep_ms(30000);
  7211. }
  7212. if (pool != cp) {
  7213. pool = select_longpoll_pool(cp);
  7214. if (pool->has_stratum) {
  7215. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7216. cp->rpc_url, pool->rpc_url);
  7217. break;
  7218. }
  7219. if (unlikely(!pool))
  7220. goto retry_pool;
  7221. }
  7222. if (unlikely(pool->removed))
  7223. break;
  7224. }
  7225. out:
  7226. curl_easy_cleanup(curl);
  7227. return NULL;
  7228. }
  7229. #else /* HAVE_LIBCURL */
  7230. static void *longpoll_thread(void __maybe_unused *userdata)
  7231. {
  7232. pthread_detach(pthread_self());
  7233. return NULL;
  7234. }
  7235. #endif /* HAVE_LIBCURL */
  7236. void reinit_device(struct cgpu_info *cgpu)
  7237. {
  7238. if (cgpu->deven == DEV_DISABLED)
  7239. return;
  7240. #ifdef USE_USBUTILS
  7241. /* Attempt a usb device reset if the device has gone sick */
  7242. if (cgpu->usbdev && cgpu->usbdev->handle)
  7243. libusb_reset_device(cgpu->usbdev->handle);
  7244. #endif
  7245. cgpu->drv->reinit_device(cgpu);
  7246. }
  7247. static struct timeval rotate_tv;
  7248. /* We reap curls if they are unused for over a minute */
  7249. static void reap_curl(struct pool *pool)
  7250. {
  7251. struct curl_ent *ent, *iter;
  7252. struct timeval now;
  7253. int reaped = 0;
  7254. cgtime(&now);
  7255. mutex_lock(&pool->pool_lock);
  7256. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  7257. if (pool->curls < 2)
  7258. break;
  7259. if (now.tv_sec - ent->tv.tv_sec > 300) {
  7260. reaped++;
  7261. pool->curls--;
  7262. list_del(&ent->node);
  7263. curl_easy_cleanup(ent->curl);
  7264. free(ent);
  7265. }
  7266. }
  7267. mutex_unlock(&pool->pool_lock);
  7268. if (reaped)
  7269. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  7270. }
  7271. /* Prune old shares we haven't had a response about for over 2 minutes in case
  7272. * the pool never plans to respond and we're just leaking memory. If we get a
  7273. * response beyond that time they will be seen as untracked shares. */
  7274. static void prune_stratum_shares(struct pool *pool)
  7275. {
  7276. struct stratum_share *sshare, *tmpshare;
  7277. time_t current_time = time(NULL);
  7278. int cleared = 0;
  7279. mutex_lock(&sshare_lock);
  7280. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7281. if (sshare->work->pool == pool && current_time > sshare->sshare_time + 120) {
  7282. HASH_DEL(stratum_shares, sshare);
  7283. free_work(sshare->work);
  7284. free(sshare);
  7285. cleared++;
  7286. }
  7287. }
  7288. mutex_unlock(&sshare_lock);
  7289. if (cleared) {
  7290. applog(LOG_WARNING, "Lost %d shares due to no stratum share response from pool %d",
  7291. cleared, pool->pool_no);
  7292. pool->stale_shares += cleared;
  7293. total_stale += cleared;
  7294. }
  7295. }
  7296. static void *watchpool_thread(void __maybe_unused *userdata)
  7297. {
  7298. int intervals = 0;
  7299. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7300. RenameThread("Watchpool");
  7301. set_lowprio();
  7302. while (42) {
  7303. struct timeval now;
  7304. int i;
  7305. if (++intervals > 20)
  7306. intervals = 0;
  7307. cgtime(&now);
  7308. for (i = 0; i < total_pools; i++) {
  7309. struct pool *pool = pools[i];
  7310. if (!opt_benchmark && !opt_benchfile) {
  7311. reap_curl(pool);
  7312. prune_stratum_shares(pool);
  7313. }
  7314. /* Get a rolling utility per pool over 10 mins */
  7315. if (intervals > 19) {
  7316. double shares = pool->diff1 - pool->last_shares;
  7317. pool->last_shares = pool->diff1;
  7318. pool->utility = (pool->utility + shares * 0.63) / 1.63;
  7319. pool->shares = pool->utility;
  7320. }
  7321. if (pool->enabled == POOL_DISABLED)
  7322. continue;
  7323. /* Don't start testing a pool if its test thread
  7324. * from startup is still doing its first attempt. */
  7325. if (unlikely(pool->testing))
  7326. continue;
  7327. /* Test pool is idle once every minute */
  7328. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  7329. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  7330. pool_resus(pool);
  7331. else
  7332. cgtime(&pool->tv_idle);
  7333. }
  7334. /* Only switch pools if the failback pool has been
  7335. * alive for more than 5 minutes to prevent
  7336. * intermittently failing pools from being used. */
  7337. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  7338. now.tv_sec - pool->tv_idle.tv_sec > 300) {
  7339. applog(LOG_WARNING, "Pool %d %s stable for 5 mins",
  7340. pool->pool_no, pool->rpc_url);
  7341. switch_pools(NULL);
  7342. }
  7343. }
  7344. if (current_pool()->idle)
  7345. switch_pools(NULL);
  7346. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  7347. cgtime(&rotate_tv);
  7348. switch_pools(NULL);
  7349. }
  7350. cgsleep_ms(30000);
  7351. }
  7352. return NULL;
  7353. }
  7354. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  7355. * the screen at regular intervals, and restarts threads if they appear to have
  7356. * died. */
  7357. #define WATCHDOG_INTERVAL 2
  7358. #define WATCHDOG_SICK_TIME 120
  7359. #define WATCHDOG_DEAD_TIME 600
  7360. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  7361. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  7362. static void *watchdog_thread(void __maybe_unused *userdata)
  7363. {
  7364. const unsigned int interval = WATCHDOG_INTERVAL;
  7365. struct timeval zero_tv;
  7366. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7367. RenameThread("Watchdog");
  7368. set_lowprio();
  7369. memset(&zero_tv, 0, sizeof(struct timeval));
  7370. cgtime(&rotate_tv);
  7371. while (1) {
  7372. int i;
  7373. struct timeval now;
  7374. sleep(interval);
  7375. discard_stale();
  7376. hashmeter(-1, 0);
  7377. #ifdef HAVE_CURSES
  7378. if (curses_active_locked()) {
  7379. struct cgpu_info *cgpu;
  7380. int count;
  7381. change_logwinsize();
  7382. curses_print_status();
  7383. count = 0;
  7384. for (i = 0; i < total_devices; i++) {
  7385. cgpu = get_devices(i);
  7386. #ifndef USE_USBUTILS
  7387. if (cgpu)
  7388. #else
  7389. if (cgpu && !cgpu->usbinfo.nodev)
  7390. #endif
  7391. curses_print_devstatus(cgpu, i, count++);
  7392. }
  7393. #ifdef USE_USBUTILS
  7394. for (i = 0; i < total_devices; i++) {
  7395. cgpu = get_devices(i);
  7396. if (cgpu && cgpu->usbinfo.nodev)
  7397. curses_print_devstatus(cgpu, i, count++);
  7398. }
  7399. #endif
  7400. touchwin(statuswin);
  7401. wrefresh(statuswin);
  7402. touchwin(logwin);
  7403. wrefresh(logwin);
  7404. unlock_curses();
  7405. }
  7406. #endif
  7407. cgtime(&now);
  7408. if (!sched_paused && !should_run()) {
  7409. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  7410. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7411. if (!schedstart.enable) {
  7412. quit(0, "Terminating execution as planned");
  7413. break;
  7414. }
  7415. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  7416. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7417. sched_paused = true;
  7418. rd_lock(&mining_thr_lock);
  7419. for (i = 0; i < mining_threads; i++)
  7420. mining_thr[i]->pause = true;
  7421. rd_unlock(&mining_thr_lock);
  7422. } else if (sched_paused && should_run()) {
  7423. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  7424. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7425. if (schedstop.enable)
  7426. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  7427. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7428. sched_paused = false;
  7429. for (i = 0; i < mining_threads; i++) {
  7430. struct thr_info *thr;
  7431. thr = get_thread(i);
  7432. /* Don't touch disabled devices */
  7433. if (thr->cgpu->deven == DEV_DISABLED)
  7434. continue;
  7435. thr->pause = false;
  7436. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  7437. cgsem_post(&thr->sem);
  7438. }
  7439. }
  7440. for (i = 0; i < total_devices; ++i) {
  7441. struct cgpu_info *cgpu = get_devices(i);
  7442. struct thr_info *thr = cgpu->thr[0];
  7443. enum dev_enable *denable;
  7444. char dev_str[8];
  7445. int gpu;
  7446. if (!thr)
  7447. continue;
  7448. cgpu->drv->get_stats(cgpu);
  7449. gpu = cgpu->device_id;
  7450. denable = &cgpu->deven;
  7451. snprintf(dev_str, sizeof(dev_str), "%s%d", cgpu->drv->name, gpu);
  7452. /* Thread is waiting on getwork or disabled */
  7453. if (thr->getwork || *denable == DEV_DISABLED)
  7454. continue;
  7455. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  7456. if (cgpu->status != LIFE_INIT)
  7457. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  7458. cgpu->status = LIFE_WELL;
  7459. cgpu->device_last_well = time(NULL);
  7460. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  7461. cgpu->rolling = 0;
  7462. cgpu->status = LIFE_SICK;
  7463. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  7464. cgtime(&thr->sick);
  7465. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  7466. if (opt_restart) {
  7467. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  7468. reinit_device(cgpu);
  7469. }
  7470. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  7471. cgpu->status = LIFE_DEAD;
  7472. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  7473. cgtime(&thr->sick);
  7474. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  7475. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  7476. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  7477. /* Attempt to restart a GPU that's sick or dead once every minute */
  7478. cgtime(&thr->sick);
  7479. if (opt_restart)
  7480. reinit_device(cgpu);
  7481. }
  7482. }
  7483. }
  7484. return NULL;
  7485. }
  7486. static void log_print_status(struct cgpu_info *cgpu)
  7487. {
  7488. char logline[255];
  7489. get_statline(logline, sizeof(logline), cgpu);
  7490. applog(LOG_WARNING, "%s", logline);
  7491. }
  7492. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu);
  7493. void blank_get_statline_before(char *buf, size_t bufsiz, struct cgpu_info __maybe_unused *cgpu);
  7494. void print_summary(void)
  7495. {
  7496. struct timeval diff;
  7497. int hours, mins, secs, i;
  7498. double utility, displayed_hashes, work_util;
  7499. timersub(&total_tv_end, &total_tv_start, &diff);
  7500. hours = diff.tv_sec / 3600;
  7501. mins = (diff.tv_sec % 3600) / 60;
  7502. secs = diff.tv_sec % 60;
  7503. utility = total_accepted / total_secs * 60;
  7504. work_util = total_diff1 / total_secs * 60;
  7505. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  7506. applog(LOG_WARNING, "Started at %s", datestamp);
  7507. if (total_pools == 1)
  7508. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  7509. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  7510. displayed_hashes = total_mhashes_done / total_secs;
  7511. applog(LOG_WARNING, "Average hashrate: %.1f Mhash/s", displayed_hashes);
  7512. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  7513. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  7514. applog(LOG_WARNING, "Share submissions: %"PRId64, total_accepted + total_rejected);
  7515. applog(LOG_WARNING, "Accepted shares: %"PRId64, total_accepted);
  7516. applog(LOG_WARNING, "Rejected shares: %"PRId64, total_rejected);
  7517. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  7518. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  7519. if (total_accepted || total_rejected)
  7520. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  7521. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  7522. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  7523. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  7524. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %"PRId64, total_stale);
  7525. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  7526. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  7527. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  7528. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  7529. if (total_pools > 1) {
  7530. for (i = 0; i < total_pools; i++) {
  7531. struct pool *pool = pools[i];
  7532. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  7533. if (pool->solved)
  7534. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  7535. applog(LOG_WARNING, " Share submissions: %"PRId64, pool->accepted + pool->rejected);
  7536. applog(LOG_WARNING, " Accepted shares: %"PRId64, pool->accepted);
  7537. applog(LOG_WARNING, " Rejected shares: %"PRId64, pool->rejected);
  7538. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  7539. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  7540. if (pool->accepted || pool->rejected)
  7541. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  7542. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  7543. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  7544. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  7545. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  7546. }
  7547. }
  7548. applog(LOG_WARNING, "Summary of per device statistics:\n");
  7549. for (i = 0; i < total_devices; ++i) {
  7550. struct cgpu_info *cgpu = get_devices(i);
  7551. cgpu->drv->get_statline_before = &blank_get_statline_before;
  7552. cgpu->drv->get_statline = &noop_get_statline;
  7553. log_print_status(cgpu);
  7554. }
  7555. if (opt_shares) {
  7556. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  7557. if (opt_shares > total_diff_accepted)
  7558. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  7559. }
  7560. applog(LOG_WARNING, " ");
  7561. fflush(stderr);
  7562. fflush(stdout);
  7563. }
  7564. static void clean_up(bool restarting)
  7565. {
  7566. #ifdef USE_USBUTILS
  7567. usb_polling = false;
  7568. pthread_join(usb_poll_thread, NULL);
  7569. libusb_exit(NULL);
  7570. #endif
  7571. cgtime(&total_tv_end);
  7572. #ifdef WIN32
  7573. timeEndPeriod(1);
  7574. #endif
  7575. #ifdef HAVE_CURSES
  7576. disable_curses();
  7577. #endif
  7578. if (!restarting && !opt_realquiet && successful_connect)
  7579. print_summary();
  7580. curl_global_cleanup();
  7581. }
  7582. /* Should all else fail and we're unable to clean up threads due to locking
  7583. * issues etc, just silently exit. */
  7584. static void *killall_thread(void __maybe_unused *arg)
  7585. {
  7586. pthread_detach(pthread_self());
  7587. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7588. sleep(5);
  7589. exit(1);
  7590. return NULL;
  7591. }
  7592. void __quit(int status, bool clean)
  7593. {
  7594. pthread_t killall_t;
  7595. if (unlikely(pthread_create(&killall_t, NULL, killall_thread, NULL)))
  7596. exit(1);
  7597. if (clean)
  7598. clean_up(false);
  7599. #ifdef HAVE_CURSES
  7600. else
  7601. disable_curses();
  7602. #endif
  7603. #if defined(unix) || defined(__APPLE__)
  7604. if (forkpid > 0) {
  7605. kill(forkpid, SIGTERM);
  7606. forkpid = 0;
  7607. }
  7608. #endif
  7609. pthread_cancel(killall_t);
  7610. exit(status);
  7611. }
  7612. void _quit(int status)
  7613. {
  7614. __quit(status, true);
  7615. }
  7616. #ifdef HAVE_CURSES
  7617. char *curses_input(const char *query)
  7618. {
  7619. char *input;
  7620. echo();
  7621. input = malloc(255);
  7622. if (!input)
  7623. quit(1, "Failed to malloc input");
  7624. leaveok(logwin, false);
  7625. wlogprint("%s:\n", query);
  7626. wgetnstr(logwin, input, 255);
  7627. if (!strlen(input))
  7628. strcpy(input, "-1");
  7629. leaveok(logwin, true);
  7630. noecho();
  7631. return input;
  7632. }
  7633. #endif
  7634. static bool pools_active = false;
  7635. static void *test_pool_thread(void *arg)
  7636. {
  7637. struct pool *pool = (struct pool *)arg;
  7638. if (!pool->blocking)
  7639. pthread_detach(pthread_self());
  7640. retry:
  7641. if (pool_active(pool, false)) {
  7642. pool_tset(pool, &pool->lagging);
  7643. pool_tclear(pool, &pool->idle);
  7644. bool first_pool = false;
  7645. cg_wlock(&control_lock);
  7646. if (!pools_active) {
  7647. currentpool = pool;
  7648. if (pool->pool_no != 0)
  7649. first_pool = true;
  7650. pools_active = true;
  7651. }
  7652. cg_wunlock(&control_lock);
  7653. if (unlikely(first_pool))
  7654. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  7655. pool_resus(pool);
  7656. switch_pools(NULL);
  7657. } else {
  7658. pool_died(pool);
  7659. sleep(5);
  7660. goto retry;
  7661. }
  7662. pool->testing = false;
  7663. return NULL;
  7664. }
  7665. /* Always returns true that the pool details were added unless we are not
  7666. * live, implying this is the only pool being added, so if no pools are
  7667. * active it returns false. */
  7668. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  7669. {
  7670. size_t siz;
  7671. url = get_proxy(url, pool);
  7672. pool->rpc_url = url;
  7673. pool->rpc_user = user;
  7674. pool->rpc_pass = pass;
  7675. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  7676. pool->rpc_userpass = malloc(siz);
  7677. if (!pool->rpc_userpass)
  7678. quit(1, "Failed to malloc userpass");
  7679. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  7680. pool->testing = true;
  7681. pool->idle = true;
  7682. pool->blocking = !live;
  7683. enable_pool(pool);
  7684. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  7685. if (!live) {
  7686. pthread_join(pool->test_thread, NULL);
  7687. return pools_active;
  7688. }
  7689. return true;
  7690. }
  7691. #ifdef HAVE_CURSES
  7692. static bool input_pool(bool live)
  7693. {
  7694. char *url = NULL, *user = NULL, *pass = NULL;
  7695. struct pool *pool;
  7696. bool ret = false;
  7697. immedok(logwin, true);
  7698. wlogprint("Input server details.\n");
  7699. url = curses_input("URL");
  7700. if (!strcmp(url, "-1"))
  7701. goto out;
  7702. user = curses_input("Username");
  7703. if (!strcmp(user, "-1"))
  7704. goto out;
  7705. pass = curses_input("Password");
  7706. if (!strcmp(pass, "-1")) {
  7707. free(pass);
  7708. pass = strdup("");
  7709. }
  7710. pool = add_pool();
  7711. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  7712. strncmp(url, "https://", 8)) {
  7713. char *httpinput;
  7714. httpinput = malloc(256);
  7715. if (!httpinput)
  7716. quit(1, "Failed to malloc httpinput");
  7717. strcpy(httpinput, "http://");
  7718. strncat(httpinput, url, 248);
  7719. free(url);
  7720. url = httpinput;
  7721. }
  7722. ret = add_pool_details(pool, live, url, user, pass);
  7723. out:
  7724. immedok(logwin, false);
  7725. if (!ret) {
  7726. free(url);
  7727. free(user);
  7728. free(pass);
  7729. }
  7730. return ret;
  7731. }
  7732. #endif
  7733. #if defined(unix) || defined(__APPLE__)
  7734. static void fork_monitor()
  7735. {
  7736. // Make a pipe: [readFD, writeFD]
  7737. int pfd[2];
  7738. int r = pipe(pfd);
  7739. if (r < 0) {
  7740. perror("pipe - failed to create pipe for --monitor");
  7741. exit(1);
  7742. }
  7743. // Make stderr write end of pipe
  7744. fflush(stderr);
  7745. r = dup2(pfd[1], 2);
  7746. if (r < 0) {
  7747. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  7748. exit(1);
  7749. }
  7750. r = close(pfd[1]);
  7751. if (r < 0) {
  7752. perror("close - failed to close write end of pipe for --monitor");
  7753. exit(1);
  7754. }
  7755. // Don't allow a dying monitor to kill the main process
  7756. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  7757. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  7758. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  7759. perror("signal - failed to edit signal mask for --monitor");
  7760. exit(1);
  7761. }
  7762. // Fork a child process
  7763. forkpid = fork();
  7764. if (forkpid < 0) {
  7765. perror("fork - failed to fork child process for --monitor");
  7766. exit(1);
  7767. }
  7768. // Child: launch monitor command
  7769. if (0 == forkpid) {
  7770. // Make stdin read end of pipe
  7771. r = dup2(pfd[0], 0);
  7772. if (r < 0) {
  7773. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  7774. exit(1);
  7775. }
  7776. close(pfd[0]);
  7777. if (r < 0) {
  7778. perror("close - in child, failed to close read end of pipe for --monitor");
  7779. exit(1);
  7780. }
  7781. // Launch user specified command
  7782. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  7783. perror("execl - in child failed to exec user specified command for --monitor");
  7784. exit(1);
  7785. }
  7786. // Parent: clean up unused fds and bail
  7787. r = close(pfd[0]);
  7788. if (r < 0) {
  7789. perror("close - failed to close read end of pipe for --monitor");
  7790. exit(1);
  7791. }
  7792. }
  7793. #endif // defined(unix)
  7794. #ifdef HAVE_CURSES
  7795. static void enable_curses_windows(void)
  7796. {
  7797. int x,y;
  7798. getmaxyx(mainwin, y, x);
  7799. statuswin = newwin(logstart, x, 0, 0);
  7800. leaveok(statuswin, true);
  7801. logwin = newwin(y - logcursor, 0, logcursor, 0);
  7802. idlok(logwin, true);
  7803. scrollok(logwin, true);
  7804. leaveok(logwin, true);
  7805. cbreak();
  7806. noecho();
  7807. }
  7808. void enable_curses(void) {
  7809. lock_curses();
  7810. if (curses_active) {
  7811. unlock_curses();
  7812. return;
  7813. }
  7814. mainwin = initscr();
  7815. enable_curses_windows();
  7816. curses_active = true;
  7817. statusy = logstart;
  7818. unlock_curses();
  7819. }
  7820. #endif
  7821. static int cgminer_id_count = 0;
  7822. /* Various noop functions for drivers that don't support or need their
  7823. * variants. */
  7824. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  7825. {
  7826. }
  7827. void blank_get_statline_before(char __maybe_unused *buf,size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  7828. {
  7829. }
  7830. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  7831. {
  7832. }
  7833. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  7834. {
  7835. return true;
  7836. }
  7837. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  7838. {
  7839. return true;
  7840. }
  7841. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  7842. {
  7843. return 0xffffffff;
  7844. }
  7845. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  7846. {
  7847. return true;
  7848. }
  7849. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  7850. {
  7851. return true;
  7852. }
  7853. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  7854. {
  7855. }
  7856. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  7857. {
  7858. }
  7859. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  7860. {
  7861. }
  7862. static void noop_detect(bool __maybe_unused hotplug)
  7863. {
  7864. }
  7865. static struct api_data *noop_get_api_stats(struct cgpu_info __maybe_unused *cgpu)
  7866. {
  7867. return NULL;
  7868. }
  7869. static void noop_hash_work(struct thr_info __maybe_unused *thr)
  7870. {
  7871. }
  7872. #define noop_flush_work noop_reinit_device
  7873. #define noop_update_work noop_reinit_device
  7874. #define noop_queue_full noop_get_stats
  7875. #define noop_zero_stats noop_reinit_device
  7876. #define noop_identify_device noop_reinit_device
  7877. /* Fill missing driver drv functions with noops */
  7878. void fill_device_drv(struct device_drv *drv)
  7879. {
  7880. if (!drv->drv_detect)
  7881. drv->drv_detect = &noop_detect;
  7882. if (!drv->reinit_device)
  7883. drv->reinit_device = &noop_reinit_device;
  7884. if (!drv->get_statline_before)
  7885. drv->get_statline_before = &blank_get_statline_before;
  7886. if (!drv->get_statline)
  7887. drv->get_statline = &noop_get_statline;
  7888. if (!drv->get_stats)
  7889. drv->get_stats = &noop_get_stats;
  7890. if (!drv->thread_prepare)
  7891. drv->thread_prepare = &noop_thread_prepare;
  7892. if (!drv->can_limit_work)
  7893. drv->can_limit_work = &noop_can_limit_work;
  7894. if (!drv->thread_init)
  7895. drv->thread_init = &noop_thread_init;
  7896. if (!drv->prepare_work)
  7897. drv->prepare_work = &noop_prepare_work;
  7898. if (!drv->hw_error)
  7899. drv->hw_error = &noop_hw_error;
  7900. if (!drv->thread_shutdown)
  7901. drv->thread_shutdown = &noop_thread_shutdown;
  7902. if (!drv->thread_enable)
  7903. drv->thread_enable = &noop_thread_enable;
  7904. if (!drv->hash_work)
  7905. drv->hash_work = &hash_sole_work;
  7906. if (!drv->flush_work)
  7907. drv->flush_work = &noop_flush_work;
  7908. if (!drv->update_work)
  7909. drv->update_work = &noop_update_work;
  7910. if (!drv->queue_full)
  7911. drv->queue_full = &noop_queue_full;
  7912. if (!drv->zero_stats)
  7913. drv->zero_stats = &noop_zero_stats;
  7914. /* If drivers support internal diff they should set a max_diff or
  7915. * we will assume they don't and set max to 1. */
  7916. if (!drv->max_diff)
  7917. drv->max_diff = 1;
  7918. }
  7919. void null_device_drv(struct device_drv *drv)
  7920. {
  7921. drv->drv_detect = &noop_detect;
  7922. drv->reinit_device = &noop_reinit_device;
  7923. drv->get_statline_before = &blank_get_statline_before;
  7924. drv->get_statline = &noop_get_statline;
  7925. drv->get_api_stats = &noop_get_api_stats;
  7926. drv->get_stats = &noop_get_stats;
  7927. drv->identify_device = &noop_identify_device;
  7928. drv->set_device = NULL;
  7929. drv->thread_prepare = &noop_thread_prepare;
  7930. drv->can_limit_work = &noop_can_limit_work;
  7931. drv->thread_init = &noop_thread_init;
  7932. drv->prepare_work = &noop_prepare_work;
  7933. /* This should make the miner thread just exit */
  7934. drv->hash_work = &noop_hash_work;
  7935. drv->hw_error = &noop_hw_error;
  7936. drv->thread_shutdown = &noop_thread_shutdown;
  7937. drv->thread_enable = &noop_thread_enable;
  7938. drv->zero_stats = &noop_zero_stats;
  7939. drv->hash_work = &noop_hash_work;
  7940. drv->queue_full = &noop_queue_full;
  7941. drv->flush_work = &noop_flush_work;
  7942. drv->update_work = &noop_update_work;
  7943. drv->zero_stats = &noop_zero_stats;
  7944. drv->max_diff = 1;
  7945. drv->min_diff = 1;
  7946. }
  7947. void enable_device(struct cgpu_info *cgpu)
  7948. {
  7949. cgpu->deven = DEV_ENABLED;
  7950. wr_lock(&devices_lock);
  7951. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  7952. wr_unlock(&devices_lock);
  7953. if (hotplug_mode)
  7954. new_threads += cgpu->threads;
  7955. else
  7956. mining_threads += cgpu->threads;
  7957. rwlock_init(&cgpu->qlock);
  7958. cgpu->queued_work = NULL;
  7959. }
  7960. struct _cgpu_devid_counter {
  7961. char name[4];
  7962. int lastid;
  7963. UT_hash_handle hh;
  7964. };
  7965. static void adjust_mostdevs(void)
  7966. {
  7967. if (total_devices - zombie_devs > most_devices)
  7968. most_devices = total_devices - zombie_devs;
  7969. }
  7970. #ifdef USE_ICARUS
  7971. bool icarus_get_device_id(struct cgpu_info *cgpu)
  7972. {
  7973. static struct _cgpu_devid_counter *devids = NULL;
  7974. struct _cgpu_devid_counter *d;
  7975. HASH_FIND_STR(devids, cgpu->drv->name, d);
  7976. if (d)
  7977. return (d->lastid + 1);
  7978. else
  7979. return 0;
  7980. }
  7981. #endif
  7982. bool add_cgpu(struct cgpu_info *cgpu)
  7983. {
  7984. static struct _cgpu_devid_counter *devids = NULL;
  7985. struct _cgpu_devid_counter *d;
  7986. HASH_FIND_STR(devids, cgpu->drv->name, d);
  7987. if (d)
  7988. cgpu->device_id = ++d->lastid;
  7989. else {
  7990. d = malloc(sizeof(*d));
  7991. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  7992. cgpu->device_id = d->lastid = 0;
  7993. HASH_ADD_STR(devids, name, d);
  7994. }
  7995. wr_lock(&devices_lock);
  7996. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + new_devices + 2));
  7997. wr_unlock(&devices_lock);
  7998. mutex_lock(&stats_lock);
  7999. cgpu->last_device_valid_work = time(NULL);
  8000. mutex_unlock(&stats_lock);
  8001. if (hotplug_mode)
  8002. devices[total_devices + new_devices++] = cgpu;
  8003. else
  8004. devices[total_devices++] = cgpu;
  8005. adjust_mostdevs();
  8006. #ifdef USE_USBUTILS
  8007. if (cgpu->usbdev && !cgpu->unique_id && cgpu->usbdev->serial_string &&
  8008. strlen(cgpu->usbdev->serial_string) > 4)
  8009. cgpu->unique_id = str_text(cgpu->usbdev->serial_string);
  8010. #endif
  8011. return true;
  8012. }
  8013. struct device_drv *copy_drv(struct device_drv *drv)
  8014. {
  8015. struct device_drv *copy;
  8016. if (unlikely(!(copy = malloc(sizeof(*copy))))) {
  8017. quit(1, "Failed to allocate device_drv copy of %s (%s)",
  8018. drv->name, drv->copy ? "copy" : "original");
  8019. }
  8020. memcpy(copy, drv, sizeof(*copy));
  8021. copy->copy = true;
  8022. return copy;
  8023. }
  8024. #ifdef USE_USBUTILS
  8025. static void hotplug_process(void)
  8026. {
  8027. struct thr_info *thr;
  8028. int i, j;
  8029. for (i = 0; i < new_devices; i++) {
  8030. struct cgpu_info *cgpu;
  8031. int dev_no = total_devices + i;
  8032. cgpu = devices[dev_no];
  8033. enable_device(cgpu);
  8034. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8035. cgpu->rolling = cgpu->total_mhashes = 0;
  8036. }
  8037. wr_lock(&mining_thr_lock);
  8038. mining_thr = realloc(mining_thr, sizeof(thr) * (mining_threads + new_threads + 1));
  8039. if (!mining_thr)
  8040. quit(1, "Failed to hotplug realloc mining_thr");
  8041. for (i = 0; i < new_threads; i++) {
  8042. mining_thr[mining_threads + i] = calloc(1, sizeof(*thr));
  8043. if (!mining_thr[mining_threads + i])
  8044. quit(1, "Failed to hotplug calloc mining_thr[%d]", i);
  8045. }
  8046. // Start threads
  8047. for (i = 0; i < new_devices; ++i) {
  8048. struct cgpu_info *cgpu = devices[total_devices];
  8049. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  8050. cgpu->thr[cgpu->threads] = NULL;
  8051. cgpu->status = LIFE_INIT;
  8052. cgtime(&(cgpu->dev_start_tv));
  8053. for (j = 0; j < cgpu->threads; ++j) {
  8054. thr = __get_thread(mining_threads);
  8055. thr->id = mining_threads;
  8056. thr->cgpu = cgpu;
  8057. thr->device_thread = j;
  8058. if (!cgpu->drv->thread_prepare(thr)) {
  8059. null_device_drv(cgpu->drv);
  8060. cgpu->deven = DEV_DISABLED;
  8061. continue;
  8062. }
  8063. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  8064. quit(1, "hotplug thread %d create failed", thr->id);
  8065. cgpu->thr[j] = thr;
  8066. /* Enable threads for devices set not to mine but disable
  8067. * their queue in case we wish to enable them later */
  8068. if (cgpu->deven != DEV_DISABLED) {
  8069. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  8070. cgsem_post(&thr->sem);
  8071. }
  8072. mining_threads++;
  8073. }
  8074. total_devices++;
  8075. applog(LOG_WARNING, "Hotplug: %s added %s %i", cgpu->drv->dname, cgpu->drv->name, cgpu->device_id);
  8076. }
  8077. wr_unlock(&mining_thr_lock);
  8078. adjust_mostdevs();
  8079. #ifdef HAVE_CURSES
  8080. switch_logsize(true);
  8081. #endif
  8082. }
  8083. #define DRIVER_DRV_DETECT_HOTPLUG(X) X##_drv.drv_detect(true);
  8084. static void *hotplug_thread(void __maybe_unused *userdata)
  8085. {
  8086. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8087. RenameThread("Hotplug");
  8088. hotplug_mode = true;
  8089. cgsleep_ms(5000);
  8090. while (0x2a) {
  8091. // Version 0.1 just add the devices on - worry about using nodev later
  8092. if (hotplug_time == 0)
  8093. cgsleep_ms(5000);
  8094. else {
  8095. new_devices = 0;
  8096. new_threads = 0;
  8097. /* Use the DRIVER_PARSE_COMMANDS macro to detect all
  8098. * devices */
  8099. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_HOTPLUG)
  8100. if (new_devices)
  8101. hotplug_process();
  8102. // hotplug_time >0 && <=9999
  8103. cgsleep_ms(hotplug_time * 1000);
  8104. }
  8105. }
  8106. return NULL;
  8107. }
  8108. #endif
  8109. static void probe_pools(void)
  8110. {
  8111. int i;
  8112. for (i = 0; i < total_pools; i++) {
  8113. struct pool *pool = pools[i];
  8114. pool->testing = true;
  8115. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8116. }
  8117. }
  8118. #define DRIVER_FILL_DEVICE_DRV(X) fill_device_drv(&X##_drv);
  8119. #define DRIVER_DRV_DETECT_ALL(X) X##_drv.drv_detect(false);
  8120. #ifdef USE_USBUTILS
  8121. static void *libusb_poll_thread(void __maybe_unused *arg)
  8122. {
  8123. struct timeval tv_end = {1, 0};
  8124. RenameThread("USBPoll");
  8125. while (usb_polling)
  8126. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  8127. /* Cancel any cancellable usb transfers */
  8128. cancel_usb_transfers();
  8129. /* Keep event handling going until there are no async transfers in
  8130. * flight. */
  8131. do {
  8132. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  8133. } while (async_usb_transfers());
  8134. return NULL;
  8135. }
  8136. static void initialise_usb(void) {
  8137. int err = libusb_init(NULL);
  8138. if (err) {
  8139. fprintf(stderr, "libusb_init() failed err %d", err);
  8140. fflush(stderr);
  8141. quit(1, "libusb_init() failed");
  8142. }
  8143. initialise_usblocks();
  8144. usb_polling = true;
  8145. pthread_create(&usb_poll_thread, NULL, libusb_poll_thread, NULL);
  8146. }
  8147. #else
  8148. #define initialise_usb() {}
  8149. #endif
  8150. int main(int argc, char *argv[])
  8151. {
  8152. struct sigaction handler;
  8153. struct work *work = NULL;
  8154. bool pool_msg = false;
  8155. struct thr_info *thr;
  8156. struct block *block;
  8157. int i, j, slept = 0;
  8158. unsigned int k;
  8159. char *s;
  8160. /* This dangerous functions tramples random dynamically allocated
  8161. * variables so do it before anything at all */
  8162. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  8163. early_quit(1, "Failed to curl_global_init");
  8164. # ifdef __linux
  8165. /* If we're on a small lowspec platform with only one CPU, we should
  8166. * yield after dropping a lock to allow a thread waiting for it to be
  8167. * able to get CPU time to grab the lock. */
  8168. if (sysconf(_SC_NPROCESSORS_ONLN) == 1)
  8169. selective_yield = &sched_yield;
  8170. #endif
  8171. #if LOCK_TRACKING
  8172. // Must be first
  8173. if (unlikely(pthread_mutex_init(&lockstat_lock, NULL)))
  8174. quithere(1, "Failed to pthread_mutex_init lockstat_lock errno=%d", errno);
  8175. #endif
  8176. initial_args = malloc(sizeof(char *) * (argc + 1));
  8177. for (i = 0; i < argc; i++)
  8178. initial_args[i] = strdup(argv[i]);
  8179. initial_args[argc] = NULL;
  8180. mutex_init(&hash_lock);
  8181. mutex_init(&console_lock);
  8182. cglock_init(&control_lock);
  8183. mutex_init(&stats_lock);
  8184. mutex_init(&sharelog_lock);
  8185. cglock_init(&ch_lock);
  8186. mutex_init(&sshare_lock);
  8187. rwlock_init(&blk_lock);
  8188. rwlock_init(&netacc_lock);
  8189. rwlock_init(&mining_thr_lock);
  8190. rwlock_init(&devices_lock);
  8191. mutex_init(&lp_lock);
  8192. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  8193. early_quit(1, "Failed to pthread_cond_init lp_cond");
  8194. mutex_init(&restart_lock);
  8195. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  8196. early_quit(1, "Failed to pthread_cond_init restart_cond");
  8197. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  8198. early_quit(1, "Failed to pthread_cond_init gws_cond");
  8199. /* Create a unique get work queue */
  8200. getq = tq_new();
  8201. if (!getq)
  8202. early_quit(1, "Failed to create getq");
  8203. /* We use the getq mutex as the staged lock */
  8204. stgd_lock = &getq->mutex;
  8205. initialise_usb();
  8206. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  8207. handler.sa_handler = &sighandler;
  8208. handler.sa_flags = 0;
  8209. sigemptyset(&handler.sa_mask);
  8210. sigaction(SIGTERM, &handler, &termhandler);
  8211. sigaction(SIGINT, &handler, &inthandler);
  8212. #ifndef WIN32
  8213. signal(SIGPIPE, SIG_IGN);
  8214. #else
  8215. timeBeginPeriod(1);
  8216. #endif
  8217. opt_kernel_path = alloca(PATH_MAX);
  8218. strcpy(opt_kernel_path, CGMINER_PREFIX);
  8219. cgminer_path = alloca(PATH_MAX);
  8220. s = strdup(argv[0]);
  8221. strcpy(cgminer_path, dirname(s));
  8222. free(s);
  8223. strcat(cgminer_path, "/");
  8224. devcursor = 8;
  8225. logstart = devcursor + 1;
  8226. logcursor = logstart + 1;
  8227. block = calloc(sizeof(struct block), 1);
  8228. if (unlikely(!block))
  8229. quit (1, "main OOM");
  8230. for (i = 0; i < 36; i++)
  8231. strcat(block->hash, "0");
  8232. HASH_ADD_STR(blocks, hash, block);
  8233. strcpy(current_hash, block->hash);
  8234. INIT_LIST_HEAD(&scan_devices);
  8235. /* parse command line */
  8236. opt_register_table(opt_config_table,
  8237. "Options for both config file and command line");
  8238. opt_register_table(opt_cmdline_table,
  8239. "Options for command line only");
  8240. opt_parse(&argc, argv, applog_and_exit);
  8241. if (argc != 1)
  8242. early_quit(1, "Unexpected extra commandline arguments");
  8243. if (!config_loaded)
  8244. load_default_config();
  8245. if (!opt_sha256 && !opt_scrypt)
  8246. early_quit(1, "Must explicitly specify mining algorithm (--sha256 or --scrypt)");
  8247. if (opt_benchmark || opt_benchfile) {
  8248. struct pool *pool;
  8249. if (opt_scrypt)
  8250. early_quit(1, "Cannot use benchmark mode with scrypt");
  8251. pool = add_pool();
  8252. pool->rpc_url = malloc(255);
  8253. if (opt_benchfile)
  8254. strcpy(pool->rpc_url, "Benchfile");
  8255. else
  8256. strcpy(pool->rpc_url, "Benchmark");
  8257. pool->rpc_user = pool->rpc_url;
  8258. pool->rpc_pass = pool->rpc_url;
  8259. pool->rpc_userpass = pool->rpc_url;
  8260. pool->sockaddr_url = pool->rpc_url;
  8261. strncpy(pool->diff, "?", sizeof(pool->diff)-1);
  8262. pool->diff[sizeof(pool->diff)-1] = '\0';
  8263. enable_pool(pool);
  8264. pool->idle = false;
  8265. successful_connect = true;
  8266. for (i = 0; i < 16; i++) {
  8267. hex2bin(&bench_hidiff_bins[i][0], &bench_hidiffs[i][0], 160);
  8268. hex2bin(&bench_lodiff_bins[i][0], &bench_lodiffs[i][0], 160);
  8269. }
  8270. set_target(bench_target, 32);
  8271. }
  8272. #ifdef HAVE_CURSES
  8273. if (opt_realquiet || opt_display_devs)
  8274. use_curses = false;
  8275. if (use_curses)
  8276. enable_curses();
  8277. #endif
  8278. applog(LOG_WARNING, "Started %s", packagename);
  8279. if (cnfbuf) {
  8280. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  8281. switch (fileconf_load) {
  8282. case 0:
  8283. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  8284. applog(LOG_WARNING, "Configuration file could not be used.");
  8285. break;
  8286. case -1:
  8287. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  8288. if (use_curses)
  8289. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  8290. break;
  8291. default:
  8292. break;
  8293. }
  8294. free(cnfbuf);
  8295. cnfbuf = NULL;
  8296. }
  8297. strcat(opt_kernel_path, "/");
  8298. if (want_per_device_stats)
  8299. opt_log_output = true;
  8300. /* Use a shorter scantime for scrypt */
  8301. if (opt_scantime < 0)
  8302. opt_scantime = opt_scrypt ? 30 : 60;
  8303. total_control_threads = 8;
  8304. control_thr = calloc(total_control_threads, sizeof(*thr));
  8305. if (!control_thr)
  8306. early_quit(1, "Failed to calloc control_thr");
  8307. gwsched_thr_id = 0;
  8308. #ifdef USE_USBUTILS
  8309. usb_initialise();
  8310. // before device detection
  8311. cgsem_init(&usb_resource_sem);
  8312. usbres_thr_id = 1;
  8313. thr = &control_thr[usbres_thr_id];
  8314. if (thr_info_create(thr, NULL, usb_resource_thread, thr))
  8315. early_quit(1, "usb resource thread create failed");
  8316. pthread_detach(thr->pth);
  8317. #endif
  8318. /* Use the DRIVER_PARSE_COMMANDS macro to fill all the device_drvs */
  8319. DRIVER_PARSE_COMMANDS(DRIVER_FILL_DEVICE_DRV)
  8320. /* Use the DRIVER_PARSE_COMMANDS macro to detect all devices */
  8321. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_ALL)
  8322. if (opt_display_devs) {
  8323. applog(LOG_ERR, "Devices detected:");
  8324. for (i = 0; i < total_devices; ++i) {
  8325. struct cgpu_info *cgpu = devices[i];
  8326. if (cgpu->name)
  8327. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->name, cgpu->drv->dname);
  8328. else
  8329. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->drv->dname);
  8330. }
  8331. early_quit(0, "%d devices listed", total_devices);
  8332. }
  8333. mining_threads = 0;
  8334. for (i = 0; i < total_devices; ++i)
  8335. enable_device(devices[i]);
  8336. #ifdef USE_USBUTILS
  8337. if (!total_devices) {
  8338. applog(LOG_WARNING, "No devices detected!");
  8339. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  8340. }
  8341. #else
  8342. if (!total_devices)
  8343. early_quit(1, "All devices disabled, cannot mine!");
  8344. #endif
  8345. if (opt_queue == -1)
  8346. opt_queue = (opt_scrypt) ? total_devices : 9999;
  8347. most_devices = total_devices;
  8348. load_temp_cutoffs();
  8349. for (i = 0; i < total_devices; ++i)
  8350. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8351. if (!opt_compact) {
  8352. logstart += most_devices;
  8353. logcursor = logstart + 1;
  8354. #ifdef HAVE_CURSES
  8355. check_winsizes();
  8356. #endif
  8357. }
  8358. if (!total_pools) {
  8359. applog(LOG_WARNING, "Need to specify at least one pool server.");
  8360. #ifdef HAVE_CURSES
  8361. if (!use_curses || !input_pool(false))
  8362. #endif
  8363. early_quit(1, "Pool setup failed");
  8364. }
  8365. for (i = 0; i < total_pools; i++) {
  8366. struct pool *pool = pools[i];
  8367. size_t siz;
  8368. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8369. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8370. if (!pool->rpc_userpass) {
  8371. if (!pool->rpc_pass)
  8372. pool->rpc_pass = strdup("");
  8373. if (!pool->rpc_user)
  8374. early_quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  8375. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8376. pool->rpc_userpass = malloc(siz);
  8377. if (!pool->rpc_userpass)
  8378. early_quit(1, "Failed to malloc userpass");
  8379. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8380. }
  8381. }
  8382. /* Set the currentpool to pool 0 */
  8383. currentpool = pools[0];
  8384. #ifdef HAVE_SYSLOG_H
  8385. if (use_syslog)
  8386. openlog(PACKAGE, LOG_PID, LOG_USER);
  8387. #endif
  8388. #if defined(unix) || defined(__APPLE__)
  8389. if (opt_stderr_cmd)
  8390. fork_monitor();
  8391. #endif // defined(unix)
  8392. mining_thr = calloc(mining_threads, sizeof(thr));
  8393. if (!mining_thr)
  8394. early_quit(1, "Failed to calloc mining_thr");
  8395. for (i = 0; i < mining_threads; i++) {
  8396. mining_thr[i] = calloc(1, sizeof(*thr));
  8397. if (!mining_thr[i])
  8398. early_quit(1, "Failed to calloc mining_thr[%d]", i);
  8399. }
  8400. // Start threads
  8401. k = 0;
  8402. for (i = 0; i < total_devices; ++i) {
  8403. struct cgpu_info *cgpu = devices[i];
  8404. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  8405. cgpu->thr[cgpu->threads] = NULL;
  8406. cgpu->status = LIFE_INIT;
  8407. for (j = 0; j < cgpu->threads; ++j, ++k) {
  8408. thr = get_thread(k);
  8409. thr->id = k;
  8410. thr->cgpu = cgpu;
  8411. thr->device_thread = j;
  8412. if (!cgpu->drv->thread_prepare(thr))
  8413. continue;
  8414. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  8415. early_quit(1, "thread %d create failed", thr->id);
  8416. cgpu->thr[j] = thr;
  8417. /* Enable threads for devices set not to mine but disable
  8418. * their queue in case we wish to enable them later */
  8419. if (cgpu->deven != DEV_DISABLED) {
  8420. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  8421. cgsem_post(&thr->sem);
  8422. }
  8423. }
  8424. }
  8425. if (opt_benchmark || opt_benchfile)
  8426. goto begin_bench;
  8427. for (i = 0; i < total_pools; i++) {
  8428. struct pool *pool = pools[i];
  8429. enable_pool(pool);
  8430. pool->idle = true;
  8431. }
  8432. /* Look for at least one active pool before starting */
  8433. applog(LOG_NOTICE, "Probing for an alive pool");
  8434. probe_pools();
  8435. do {
  8436. sleep(1);
  8437. slept++;
  8438. } while (!pools_active && slept < 60);
  8439. while (!pools_active) {
  8440. if (!pool_msg) {
  8441. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  8442. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  8443. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  8444. for (i = 0; i < total_pools; i++) {
  8445. struct pool *pool = pools[i];
  8446. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  8447. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  8448. }
  8449. pool_msg = true;
  8450. if (use_curses)
  8451. applog(LOG_ERR, "Press any key to exit, or cgminer will wait indefinitely for an alive pool.");
  8452. }
  8453. if (!use_curses)
  8454. early_quit(0, "No servers could be used! Exiting.");
  8455. #ifdef HAVE_CURSES
  8456. touchwin(logwin);
  8457. wrefresh(logwin);
  8458. halfdelay(10);
  8459. if (getch() != ERR)
  8460. early_quit(0, "No servers could be used! Exiting.");
  8461. cbreak();
  8462. #endif
  8463. };
  8464. begin_bench:
  8465. total_mhashes_done = 0;
  8466. for (i = 0; i < total_devices; i++) {
  8467. struct cgpu_info *cgpu = devices[i];
  8468. cgpu->rolling = cgpu->total_mhashes = 0;
  8469. }
  8470. cgtime(&total_tv_start);
  8471. cgtime(&total_tv_end);
  8472. cgtime(&tv_hashmeter);
  8473. get_datestamp(datestamp, sizeof(datestamp), &total_tv_start);
  8474. watchpool_thr_id = 2;
  8475. thr = &control_thr[watchpool_thr_id];
  8476. /* start watchpool thread */
  8477. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  8478. early_quit(1, "watchpool thread create failed");
  8479. pthread_detach(thr->pth);
  8480. watchdog_thr_id = 3;
  8481. thr = &control_thr[watchdog_thr_id];
  8482. /* start watchdog thread */
  8483. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  8484. early_quit(1, "watchdog thread create failed");
  8485. pthread_detach(thr->pth);
  8486. /* Create API socket thread */
  8487. api_thr_id = 5;
  8488. thr = &control_thr[api_thr_id];
  8489. if (thr_info_create(thr, NULL, api_thread, thr))
  8490. early_quit(1, "API thread create failed");
  8491. #ifdef USE_USBUTILS
  8492. hotplug_thr_id = 6;
  8493. thr = &control_thr[hotplug_thr_id];
  8494. if (thr_info_create(thr, NULL, hotplug_thread, thr))
  8495. early_quit(1, "hotplug thread create failed");
  8496. pthread_detach(thr->pth);
  8497. #endif
  8498. #ifdef HAVE_CURSES
  8499. /* Create curses input thread for keyboard input. Create this last so
  8500. * that we know all threads are created since this can call kill_work
  8501. * to try and shut down all previous threads. */
  8502. input_thr_id = 7;
  8503. thr = &control_thr[input_thr_id];
  8504. if (thr_info_create(thr, NULL, input_thread, thr))
  8505. early_quit(1, "input thread create failed");
  8506. pthread_detach(thr->pth);
  8507. #endif
  8508. /* Just to be sure */
  8509. if (total_control_threads != 8)
  8510. early_quit(1, "incorrect total_control_threads (%d) should be 8", total_control_threads);
  8511. set_highprio();
  8512. /* Once everything is set up, main() becomes the getwork scheduler */
  8513. while (42) {
  8514. int ts, max_staged = max_queue;
  8515. struct pool *pool, *cp;
  8516. bool lagging = false;
  8517. if (opt_work_update)
  8518. signal_work_update();
  8519. opt_work_update = false;
  8520. cp = current_pool();
  8521. /* If the primary pool is a getwork pool and cannot roll work,
  8522. * try to stage one extra work per mining thread */
  8523. if (!pool_localgen(cp) && !staged_rollable)
  8524. max_staged += mining_threads;
  8525. mutex_lock(stgd_lock);
  8526. ts = __total_staged();
  8527. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  8528. lagging = true;
  8529. /* Wait until hash_pop tells us we need to create more work */
  8530. if (ts > max_staged) {
  8531. if (work_emptied && max_queue < opt_queue) {
  8532. max_queue++;
  8533. work_emptied = false;
  8534. }
  8535. work_filled = true;
  8536. pthread_cond_wait(&gws_cond, stgd_lock);
  8537. ts = __total_staged();
  8538. }
  8539. mutex_unlock(stgd_lock);
  8540. if (ts > max_staged) {
  8541. /* Keeps slowly generating work even if it's not being
  8542. * used to keep last_getwork incrementing and to see
  8543. * if pools are still alive. */
  8544. if (work_emptied && max_queue < opt_queue) {
  8545. max_queue++;
  8546. work_emptied = false;
  8547. }
  8548. work_filled = true;
  8549. work = hash_pop(false);
  8550. if (work)
  8551. discard_work(work);
  8552. continue;
  8553. }
  8554. if (work)
  8555. discard_work(work);
  8556. work = make_work();
  8557. if (lagging && !pool_tset(cp, &cp->lagging)) {
  8558. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  8559. cp->getfail_occasions++;
  8560. total_go++;
  8561. if (!pool_localgen(cp) && max_queue < opt_queue)
  8562. applog(LOG_INFO, "Increasing queue to %d", ++max_queue);
  8563. }
  8564. pool = select_pool(lagging);
  8565. retry:
  8566. if (pool->has_stratum) {
  8567. while (!pool->stratum_active || !pool->stratum_notify) {
  8568. struct pool *altpool = select_pool(true);
  8569. cgsleep_ms(5000);
  8570. if (altpool != pool) {
  8571. pool = altpool;
  8572. goto retry;
  8573. }
  8574. }
  8575. gen_stratum_work(pool, work);
  8576. applog(LOG_DEBUG, "Generated stratum work");
  8577. stage_work(work);
  8578. continue;
  8579. }
  8580. if (opt_benchfile) {
  8581. get_benchfile_work(work);
  8582. applog(LOG_DEBUG, "Generated benchfile work");
  8583. stage_work(work);
  8584. continue;
  8585. } else if (opt_benchmark) {
  8586. get_benchmark_work(work);
  8587. applog(LOG_DEBUG, "Generated benchmark work");
  8588. stage_work(work);
  8589. continue;
  8590. }
  8591. #ifdef HAVE_LIBCURL
  8592. struct curl_ent *ce;
  8593. if (pool->gbt_solo) {
  8594. while (pool->idle) {
  8595. struct pool *altpool = select_pool(true);
  8596. cgsleep_ms(5000);
  8597. if (altpool != pool) {
  8598. pool = altpool;
  8599. goto retry;
  8600. }
  8601. }
  8602. gen_solo_work(pool, work);
  8603. applog(LOG_DEBUG, "Generated GBT SOLO work");
  8604. stage_work(work);
  8605. continue;
  8606. }
  8607. if (pool->has_gbt) {
  8608. while (pool->idle) {
  8609. struct pool *altpool = select_pool(true);
  8610. cgsleep_ms(5000);
  8611. if (altpool != pool) {
  8612. pool = altpool;
  8613. goto retry;
  8614. }
  8615. }
  8616. gen_gbt_work(pool, work);
  8617. applog(LOG_DEBUG, "Generated GBT work");
  8618. stage_work(work);
  8619. continue;
  8620. }
  8621. if (clone_available()) {
  8622. applog(LOG_DEBUG, "Cloned getwork work");
  8623. free_work(work);
  8624. continue;
  8625. }
  8626. work->pool = pool;
  8627. ce = pop_curl_entry(pool);
  8628. /* obtain new work from bitcoin via JSON-RPC */
  8629. if (!get_upstream_work(work, ce->curl)) {
  8630. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  8631. /* Make sure the pool just hasn't stopped serving
  8632. * requests but is up as we'll keep hammering it */
  8633. if (++pool->seq_getfails > mining_threads + opt_queue)
  8634. pool_died(pool);
  8635. cgsleep_ms(5000);
  8636. push_curl_entry(ce, pool);
  8637. pool = select_pool(!opt_fail_only);
  8638. free_work(work);
  8639. goto retry;
  8640. }
  8641. if (ts >= max_staged)
  8642. pool_tclear(pool, &pool->lagging);
  8643. if (pool_tclear(pool, &pool->idle))
  8644. pool_resus(pool);
  8645. applog(LOG_DEBUG, "Generated getwork work");
  8646. stage_work(work);
  8647. push_curl_entry(ce, pool);
  8648. #endif
  8649. }
  8650. return 0;
  8651. }