cgminer.c 275 KB

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