cgminer.c 308 KB

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