cgminer.c 321 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652
  1. /*
  2. * Copyright 2011-2022 Andrew Smith
  3. * Copyright 2011-2018 Con Kolivas
  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 __GNUC__
  14. #if __GNUC__ >= 7
  15. #pragma GCC diagnostic ignored "-Wcast-function-type"
  16. #pragma GCC diagnostic ignored "-Wstringop-truncation"
  17. #endif
  18. #endif
  19. #ifdef HAVE_CURSES
  20. #include <curses.h>
  21. #endif
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <stdbool.h>
  26. #include <stdint.h>
  27. #include <unistd.h>
  28. #include <sys/time.h>
  29. #include <time.h>
  30. #include <math.h>
  31. #include <stdarg.h>
  32. #include <assert.h>
  33. #include <signal.h>
  34. #include <limits.h>
  35. #ifdef USE_USBUTILS
  36. #include <semaphore.h>
  37. #endif
  38. #ifdef USE_LIBSYSTEMD
  39. #include <systemd/sd-daemon.h>
  40. #endif
  41. #include <sys/stat.h>
  42. #include <sys/types.h>
  43. #ifndef WIN32
  44. #include <sys/resource.h>
  45. #else
  46. #include <winsock2.h>
  47. #include <windows.h>
  48. #endif
  49. #include <ccan/opt/opt.h>
  50. #include <jansson.h>
  51. #ifdef HAVE_LIBCURL
  52. #include <curl/curl.h>
  53. #else
  54. char *curly = ":D";
  55. #endif
  56. #include <libgen.h>
  57. #include <sha2.h>
  58. #include "compat.h"
  59. #include "miner.h"
  60. #include "bench_block.h"
  61. #ifdef USE_USBUTILS
  62. #include "usbutils.h"
  63. #endif
  64. #if defined(unix) || defined(__APPLE__)
  65. #include <errno.h>
  66. #include <fcntl.h>
  67. #include <sys/wait.h>
  68. #endif
  69. #ifdef USE_AVALON
  70. #include "driver-avalon.h"
  71. #endif
  72. #ifdef USE_AVALON2
  73. #include "driver-avalon2.h"
  74. #endif
  75. #ifdef USE_AVALON4
  76. #include "driver-avalon4.h"
  77. #endif
  78. #ifdef USE_AVALON7
  79. #include "driver-avalon7.h"
  80. #include "libssplus.h"
  81. #endif
  82. #ifdef USE_AVALON8
  83. #include "driver-avalon8.h"
  84. #endif
  85. #ifdef USE_AVALON9
  86. #include "driver-avalon9.h"
  87. #endif
  88. #ifdef USE_AVALONLC3
  89. #include "driver-avalonlc3.h"
  90. #endif
  91. #ifdef USE_AVALON_MINER
  92. #include "driver-avalon-miner.h"
  93. #endif
  94. #ifdef USE_BFLSC
  95. #include "driver-bflsc.h"
  96. #endif
  97. #ifdef USE_SP10
  98. #include "driver-spondoolies-sp10.h"
  99. #endif
  100. #ifdef USE_SP30
  101. #include "driver-spondoolies-sp30.h"
  102. #endif
  103. #ifdef USE_BLOCK_ERUPTER
  104. #include "driver-blockerupter.h"
  105. #endif
  106. #ifdef USE_BITFURY
  107. #include "driver-bitfury.h"
  108. #endif
  109. #ifdef USE_BITFURY16
  110. #include "driver-bitfury16.h"
  111. #endif
  112. #ifdef USE_BITMAIN_SOC
  113. #include <sys/sysinfo.h>
  114. #include "driver-btm-soc.h"
  115. #endif
  116. #ifdef USE_COINTERRA
  117. #include "driver-cointerra.h"
  118. #endif
  119. #ifdef USE_GEKKO
  120. #include "driver-gekko.h"
  121. #endif
  122. #ifdef USE_HASHFAST
  123. #include "driver-hashfast.h"
  124. #endif
  125. #if defined(USE_ANT_S1) || defined(USE_ANT_S2) || defined(USE_ANT_S3)
  126. #include "driver-bitmain.h"
  127. #endif
  128. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_AVALON) || defined(USE_AVALON2) || defined(USE_MODMINER)
  129. # define USE_FPGA
  130. #endif
  131. struct strategies strategies[] = {
  132. { "Failover" },
  133. { "Round Robin" },
  134. { "Rotate" },
  135. { "Load Balance" },
  136. { "Balance" },
  137. };
  138. static char packagename[256];
  139. bool opt_work_update;
  140. #if defined(USE_AVALON7) || defined(USE_AVALON8) || defined(USE_AVALON9) || defined(USE_AVALONLC3)
  141. bool opt_clean_jobs = false;
  142. #endif
  143. bool opt_protocol;
  144. static struct benchfile_layout {
  145. int length;
  146. char *name;
  147. } benchfile_data[] = {
  148. { 1, "Version" },
  149. { 64, "MerkleRoot" },
  150. { 64, "PrevHash" },
  151. { 8, "DifficultyBits" },
  152. { 10, "NonceTime" } // 10 digits
  153. };
  154. enum benchwork {
  155. BENCHWORK_VERSION = 0,
  156. BENCHWORK_MERKLEROOT,
  157. BENCHWORK_PREVHASH,
  158. BENCHWORK_DIFFBITS,
  159. BENCHWORK_NONCETIME,
  160. BENCHWORK_COUNT
  161. };
  162. #ifdef HAVE_LIBCURL
  163. static char *opt_btc_address;
  164. static char *opt_btc_sig;
  165. #endif
  166. struct pool *opt_btcd;
  167. static char *opt_benchfile;
  168. static bool opt_benchfile_display;
  169. static FILE *benchfile_in;
  170. static int benchfile_line;
  171. static int benchfile_work;
  172. static bool opt_benchmark;
  173. static bool opt_blockcheck;
  174. bool have_longpoll;
  175. bool want_per_device_stats;
  176. bool use_syslog;
  177. bool opt_quiet;
  178. bool opt_realquiet;
  179. bool opt_loginput;
  180. bool opt_compact;
  181. bool opt_decode;
  182. const int opt_cutofftemp = 95;
  183. int opt_log_interval = 5;
  184. static const int max_queue = 1;
  185. const int max_scantime = 60;
  186. const int max_expiry = 600;
  187. uint64_t global_hashrate;
  188. unsigned long global_quota_gcd = 1;
  189. time_t last_getwork;
  190. int opt_pool_fallback = 120;
  191. #if defined(USE_USBUTILS)
  192. int nDevs;
  193. #endif
  194. bool opt_restart = true;
  195. bool opt_nogpu;
  196. struct list_head scan_devices;
  197. static bool opt_display_devs;
  198. int total_devices;
  199. int zombie_devs;
  200. static int most_devices;
  201. struct cgpu_info **devices;
  202. int mining_threads;
  203. int num_processors;
  204. #ifdef HAVE_CURSES
  205. bool use_curses = true;
  206. #else
  207. bool use_curses;
  208. #endif
  209. bool opt_mac_yield;
  210. bool opt_widescreen;
  211. static bool alt_status;
  212. static bool switch_status;
  213. static bool opt_submit_stale = true;
  214. static int opt_shares;
  215. static bool opt_fix_protocol;
  216. bool opt_lowmem;
  217. bool opt_autofan;
  218. bool opt_autoengine;
  219. bool opt_noadl;
  220. char *opt_api_allow = NULL;
  221. char *opt_api_groups;
  222. char *opt_api_description = PACKAGE_STRING;
  223. int opt_api_port = 4028;
  224. char *opt_api_host = API_LISTEN_ADDR;
  225. bool opt_api_listen;
  226. bool opt_api_mcast;
  227. char *opt_api_mcast_addr = API_MCAST_ADDR;
  228. char *opt_api_mcast_code = API_MCAST_CODE;
  229. char *opt_api_mcast_des = "";
  230. int opt_api_mcast_port = 4028;
  231. bool opt_api_network;
  232. bool opt_delaynet;
  233. bool opt_disable_pool;
  234. static bool no_work;
  235. #ifdef USE_ICARUS
  236. char *opt_icarus_options = NULL;
  237. char *opt_icarus_timing = NULL;
  238. float opt_anu_freq = 250;
  239. float opt_au3_freq = 225;
  240. int opt_au3_volt = 775;
  241. float opt_rock_freq = 270;
  242. #endif
  243. bool opt_worktime;
  244. #ifdef USE_AVALON
  245. char *opt_avalon_options;
  246. char *opt_bitburner_fury_options;
  247. static char *opt_set_avalon_fan;
  248. static char *opt_set_avalon_freq;
  249. #endif
  250. #ifdef USE_AVALON2
  251. static char *opt_set_avalon2_freq;
  252. static char *opt_set_avalon2_fan;
  253. static char *opt_set_avalon2_voltage;
  254. #endif
  255. #ifdef USE_AVALON4
  256. static char *opt_set_avalon4_fan;
  257. static char *opt_set_avalon4_voltage;
  258. static char *opt_set_avalon4_freq;
  259. #endif
  260. #ifdef USE_AVALON7
  261. static char *opt_set_avalon7_fan;
  262. static char *opt_set_avalon7_voltage;
  263. static char *opt_set_avalon7_voltage_level;
  264. static char *opt_set_avalon7_voltage_offset;
  265. static char *opt_set_avalon7_freq;
  266. #endif
  267. #ifdef USE_AVALON8
  268. static char *opt_set_avalon8_fan;
  269. static char *opt_set_avalon8_voltage_level;
  270. static char *opt_set_avalon8_voltage_level_offset;
  271. static char *opt_set_avalon8_freq;
  272. static char *opt_set_avalon8_asic_otp;
  273. #endif
  274. #ifdef USE_AVALON9
  275. static char *opt_set_avalon9_fan;
  276. static char *opt_set_avalon9_voltage_level;
  277. static char *opt_set_avalon9_voltage_level_offset;
  278. static char *opt_set_avalon9_freq;
  279. static char *opt_set_avalon9_adjust_volt_info;
  280. #endif
  281. #ifdef USE_AVALONLC3
  282. static char *opt_set_avalonlc3_fan;
  283. static char *opt_set_avalonlc3_voltage_level;
  284. static char *opt_set_avalonlc3_voltage_level_offset;
  285. static char *opt_set_avalonlc3_freq;
  286. static char *opt_set_avalonlc3_asic_otp;
  287. #endif
  288. #ifdef USE_AVALON_MINER
  289. static char *opt_set_avalonm_voltage;
  290. static char *opt_set_avalonm_freq;
  291. #endif
  292. #ifdef USE_BLOCKERUPTER
  293. int opt_bet_clk = 0;
  294. #endif
  295. #ifdef USE_GEKKO
  296. char *opt_gekko_serial = NULL;
  297. bool opt_gekko_noboost = 0;
  298. bool opt_gekko_lowboost = 0;
  299. bool opt_gekko_gsc_detect = 0;
  300. bool opt_gekko_gsd_detect = 0;
  301. bool opt_gekko_gse_detect = 0;
  302. bool opt_gekko_gsh_detect = 0;
  303. bool opt_gekko_gsi_detect = 0;
  304. bool opt_gekko_gsf_detect = 0;
  305. bool opt_gekko_r909_detect = 0;
  306. float opt_gekko_gsc_freq = 150;
  307. float opt_gekko_gsd_freq = 100;
  308. float opt_gekko_gse_freq = 150;
  309. float opt_gekko_tune_up = 97;
  310. float opt_gekko_tune_down = 95;
  311. #if defined(__APPLE__)
  312. float opt_gekko_wait_factor = 0.3;
  313. #elif defined (WIN32)
  314. float opt_gekko_wait_factor = 0.4;
  315. #else
  316. float opt_gekko_wait_factor = 0.5;
  317. #endif
  318. float opt_gekko_step_freq = 6.25;
  319. int opt_gekko_gsh_freq = 100;
  320. int opt_gekko_gsi_freq = 550;
  321. int opt_gekko_gsf_freq = 200;
  322. int opt_gekko_r909_freq = 450;
  323. int opt_gekko_bauddiv = 0;
  324. int opt_gekko_gsh_vcore = 400;
  325. int opt_gekko_start_freq = 100;
  326. int opt_gekko_step_delay = 15;
  327. bool opt_gekko_mine2 = false; // gekko code ignores it
  328. int opt_gekko_tune2 = 0;
  329. #endif
  330. #ifdef USE_HASHRATIO
  331. #include "driver-hashratio.h"
  332. #endif
  333. #ifdef USE_KLONDIKE
  334. char *opt_klondike_options = NULL;
  335. #endif
  336. #ifdef USE_DRILLBIT
  337. char *opt_drillbit_options = NULL;
  338. char *opt_drillbit_auto = NULL;
  339. #endif
  340. char *opt_bab_options = NULL;
  341. #ifdef USE_BITMINE_A1
  342. char *opt_bitmine_a1_options = NULL;
  343. #endif
  344. #ifdef USE_DRAGONMINT_T1
  345. #include "dragonmint_t1.h"
  346. char *opt_dragonmint_t1_options = NULL;
  347. int opt_T1Pll[MCOMPAT_CONFIG_MAX_CHAIN_NUM] = {
  348. DEFAULT_PLL, DEFAULT_PLL, DEFAULT_PLL, DEFAULT_PLL,
  349. DEFAULT_PLL, DEFAULT_PLL, DEFAULT_PLL, DEFAULT_PLL
  350. };
  351. int opt_T1Vol[MCOMPAT_CONFIG_MAX_CHAIN_NUM] = {
  352. DEFAULT_VOLT, DEFAULT_VOLT, DEFAULT_VOLT, DEFAULT_VOLT,
  353. DEFAULT_VOLT, DEFAULT_VOLT, DEFAULT_VOLT, DEFAULT_VOLT
  354. };
  355. int opt_T1VID[MCOMPAT_CONFIG_MAX_CHAIN_NUM] = {};
  356. bool opt_T1auto = true;
  357. bool opt_T1_efficient;
  358. bool opt_T1_performance;
  359. int opt_T1_target = 100;
  360. #endif
  361. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  362. char *opt_bitmain_options;
  363. char *opt_set_bitmain_fan;
  364. char *opt_bitmain_freq;
  365. // Ignored
  366. bool opt_bitmain_nobeeper;
  367. bool opt_bitmain_notempoverctrl;
  368. bool opt_bitmain_homemode;
  369. #endif
  370. #ifdef USE_ANT_S2
  371. #ifndef USE_ANT_S3
  372. char *opt_bitmain_dev;
  373. #endif
  374. char *opt_bitmain_voltage = BITMAIN_VOLTAGE_DEF;
  375. #endif
  376. #ifdef USE_HASHFAST
  377. static char *opt_set_hfa_fan;
  378. #endif
  379. static char *opt_set_null;
  380. #ifdef USE_MINION
  381. int opt_minion_chipreport;
  382. char *opt_minion_cores;
  383. bool opt_minion_extra;
  384. char *opt_minion_freq;
  385. int opt_minion_freqchange = 1000;
  386. int opt_minion_freqpercent = 70;
  387. bool opt_minion_idlecount;
  388. int opt_minion_ledcount;
  389. int opt_minion_ledlimit = 98;
  390. bool opt_minion_noautofreq;
  391. bool opt_minion_overheat;
  392. int opt_minion_spidelay;
  393. char *opt_minion_spireset;
  394. int opt_minion_spisleep = 200;
  395. int opt_minion_spiusec;
  396. char *opt_minion_temp;
  397. #endif
  398. #ifdef USE_USBUTILS
  399. char *opt_usb_select = NULL;
  400. int opt_usbdump = -1;
  401. bool opt_usb_list_all;
  402. cgsem_t usb_resource_sem;
  403. static pthread_t usb_poll_thread;
  404. static bool usb_polling;
  405. static bool polling_usb;
  406. static bool usb_reinit;
  407. #endif
  408. char *opt_kernel_path;
  409. char *cgminer_path;
  410. bool opt_gen_stratum_work;
  411. #if defined(USE_BITFORCE)
  412. bool opt_bfl_noncerange;
  413. #endif
  414. #define QUIET (opt_quiet || opt_realquiet)
  415. struct thr_info *control_thr;
  416. struct thr_info **mining_thr;
  417. static int gwsched_thr_id;
  418. static int watchpool_thr_id;
  419. static int watchdog_thr_id;
  420. #ifdef HAVE_CURSES
  421. static int input_thr_id;
  422. #endif
  423. int gpur_thr_id;
  424. static int api_thr_id;
  425. #ifdef USE_USBUTILS
  426. static int usbres_thr_id;
  427. static int hotplug_thr_id;
  428. #endif
  429. static int total_control_threads;
  430. bool hotplug_mode;
  431. static int new_devices;
  432. static int new_threads;
  433. int hotplug_time = 5;
  434. #if LOCK_TRACKING
  435. pthread_mutex_t lockstat_lock;
  436. #endif
  437. pthread_mutex_t hash_lock;
  438. static pthread_mutex_t *stgd_lock;
  439. pthread_mutex_t console_lock;
  440. cglock_t ch_lock;
  441. static pthread_rwlock_t blk_lock;
  442. static pthread_mutex_t sshare_lock;
  443. pthread_rwlock_t netacc_lock;
  444. pthread_rwlock_t mining_thr_lock;
  445. pthread_rwlock_t devices_lock;
  446. static pthread_mutex_t lp_lock;
  447. static pthread_cond_t lp_cond;
  448. pthread_mutex_t restart_lock;
  449. pthread_cond_t restart_cond;
  450. pthread_cond_t gws_cond;
  451. double rolling1, rolling5, rolling15;
  452. double total_rolling;
  453. double total_mhashes_done;
  454. #ifdef USE_BITMAIN_SOC
  455. char *opt_version_path = NULL;
  456. char displayed_hash_rate[16] = {0};
  457. char nonce_num10_string[NONCE_BUFF];
  458. char nonce_num30_string[NONCE_BUFF];
  459. char nonce_num60_string[NONCE_BUFF];
  460. char g_miner_version[256] = {0};
  461. char g_miner_compiletime[256] = {0};
  462. char g_miner_type[256] = {0};
  463. double new_total_mhashes_done;
  464. double new_total_secs = 1.0;
  465. // only used for total_secs, because we need use system info time, instead of real data time.
  466. time_t total_tv_start_sys;
  467. time_t total_tv_end_sys;
  468. #endif
  469. static struct timeval total_tv_start, total_tv_end;
  470. static struct timeval restart_tv_start, update_tv_start;
  471. cglock_t control_lock;
  472. pthread_mutex_t stats_lock;
  473. int hw_errors;
  474. int64_t total_accepted, total_rejected, total_diff1;
  475. int64_t total_getworks, total_stale, total_discarded;
  476. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  477. static int staged_rollable;
  478. unsigned int new_blocks;
  479. static unsigned int work_block;
  480. unsigned int found_blocks;
  481. unsigned int local_work;
  482. unsigned int total_go, total_ro;
  483. struct pool **pools;
  484. static struct pool *currentpool = NULL;
  485. int total_pools, enabled_pools;
  486. enum pool_strategy pool_strategy = POOL_FAILOVER;
  487. int opt_rotate_period;
  488. #ifdef USE_XTRANONCE
  489. static int total_urls, total_users, total_passes, total_userpasses, total_extranonce;
  490. #else
  491. static int total_urls, total_users, total_passes, total_userpasses;
  492. #endif
  493. static
  494. #ifndef HAVE_CURSES
  495. const
  496. #endif
  497. bool curses_active;
  498. /* Protected by ch_lock */
  499. char current_hash[68];
  500. static char prev_block[12];
  501. static char current_block[32];
  502. static char datestamp[40];
  503. static char blocktime[32];
  504. struct timeval block_timeval;
  505. static char best_share[8] = "0";
  506. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  507. static char block_diff[8];
  508. uint64_t best_diff = 0;
  509. struct block {
  510. char hash[68];
  511. UT_hash_handle hh;
  512. int block_no;
  513. };
  514. static struct block *blocks = NULL;
  515. int swork_id;
  516. /* For creating a hash database of stratum shares submitted that have not had
  517. * a response yet */
  518. struct stratum_share {
  519. UT_hash_handle hh;
  520. bool block;
  521. struct work *work;
  522. int id;
  523. time_t sshare_time;
  524. time_t sshare_sent;
  525. };
  526. static struct stratum_share *stratum_shares = NULL;
  527. char *opt_socks_proxy = NULL;
  528. int opt_suggest_diff;
  529. #if defined(USE_AVALON7) || defined (USE_AVALON8) || defined(USE_AVALON9) ||defined(USE_AVALONLC3)
  530. int opt_force_clean_jobs = 20;
  531. #endif
  532. static const char def_conf[] = "cgminer.conf";
  533. static char *default_config;
  534. static bool config_loaded;
  535. static int include_count;
  536. #define JSON_INCLUDE_CONF "include"
  537. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  538. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  539. #define JSON_MAX_DEPTH 10
  540. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  541. #define JSON_WEB_ERROR "WEB config err"
  542. #if defined(unix) || defined(__APPLE__)
  543. static char *opt_stderr_cmd = NULL;
  544. static int forkpid;
  545. #endif // defined(unix)
  546. struct sigaction termhandler, inthandler, abrthandler;
  547. struct thread_q *getq;
  548. static uint32_t total_work;
  549. struct work *staged_work = NULL;
  550. struct schedtime {
  551. bool enable;
  552. struct tm tm;
  553. };
  554. struct schedtime schedstart;
  555. struct schedtime schedstop;
  556. bool sched_paused;
  557. static bool time_before(struct tm *tm1, struct tm *tm2)
  558. {
  559. if (tm1->tm_hour < tm2->tm_hour)
  560. return true;
  561. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  562. return true;
  563. return false;
  564. }
  565. static bool should_run(void)
  566. {
  567. struct timeval tv;
  568. struct tm *tm;
  569. if (!schedstart.enable && !schedstop.enable)
  570. return true;
  571. cgtime(&tv);
  572. const time_t tmp_time = tv.tv_sec;
  573. tm = localtime(&tmp_time);
  574. if (schedstart.enable) {
  575. if (!schedstop.enable) {
  576. if (time_before(tm, &schedstart.tm))
  577. return false;
  578. /* This is a once off event with no stop time set */
  579. schedstart.enable = false;
  580. return true;
  581. }
  582. if (time_before(&schedstart.tm, &schedstop.tm)) {
  583. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  584. return true;
  585. return false;
  586. } /* Times are reversed */
  587. if (time_before(tm, &schedstart.tm)) {
  588. if (time_before(tm, &schedstop.tm))
  589. return true;
  590. return false;
  591. }
  592. return true;
  593. }
  594. /* only schedstop.enable == true */
  595. if (!time_before(tm, &schedstop.tm))
  596. return false;
  597. return true;
  598. }
  599. void get_datestamp(char *f, size_t fsiz, struct timeval *tv)
  600. {
  601. struct tm *tm;
  602. const time_t tmp_time = tv->tv_sec;
  603. int ms = (int)(tv->tv_usec / 1000);
  604. tm = localtime(&tmp_time);
  605. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d.%03d]",
  606. tm->tm_year + 1900,
  607. tm->tm_mon + 1,
  608. tm->tm_mday,
  609. tm->tm_hour,
  610. tm->tm_min,
  611. tm->tm_sec, ms);
  612. }
  613. static void get_timestamp(char *f, size_t fsiz, struct timeval *tv)
  614. {
  615. struct tm *tm;
  616. const time_t tmp_time = tv->tv_sec;
  617. int ms = (int)(tv->tv_usec / 1000);
  618. tm = localtime(&tmp_time);
  619. snprintf(f, fsiz, "[%02d:%02d:%02d.%03d]",
  620. tm->tm_hour,
  621. tm->tm_min,
  622. tm->tm_sec, ms);
  623. }
  624. static char exit_buf[512];
  625. static void applog_and_exit(const char *fmt, ...)
  626. {
  627. va_list ap;
  628. va_start(ap, fmt);
  629. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  630. va_end(ap);
  631. _applog(LOG_ERR, exit_buf, true);
  632. exit(1);
  633. }
  634. static pthread_mutex_t sharelog_lock;
  635. static FILE *sharelog_file = NULL;
  636. static struct thr_info *__get_thread(int thr_id)
  637. {
  638. return mining_thr[thr_id];
  639. }
  640. struct thr_info *get_thread(int thr_id)
  641. {
  642. struct thr_info *thr;
  643. rd_lock(&mining_thr_lock);
  644. thr = __get_thread(thr_id);
  645. rd_unlock(&mining_thr_lock);
  646. return thr;
  647. }
  648. static struct cgpu_info *get_thr_cgpu(int thr_id)
  649. {
  650. struct thr_info *thr = get_thread(thr_id);
  651. return thr->cgpu;
  652. }
  653. struct cgpu_info *get_devices(int id)
  654. {
  655. struct cgpu_info *cgpu;
  656. rd_lock(&devices_lock);
  657. cgpu = devices[id];
  658. rd_unlock(&devices_lock);
  659. return cgpu;
  660. }
  661. static void sharelog(const char*disposition, const struct work*work)
  662. {
  663. char *target, *hash, *data;
  664. struct cgpu_info *cgpu;
  665. unsigned long int t;
  666. struct pool *pool;
  667. int thr_id, rv;
  668. char s[1024];
  669. size_t ret;
  670. if (!sharelog_file)
  671. return;
  672. thr_id = work->thr_id;
  673. cgpu = get_thr_cgpu(thr_id);
  674. pool = work->pool;
  675. t = (unsigned long int)(work->tv_work_found.tv_sec);
  676. target = bin2hex(work->target, sizeof(work->target));
  677. hash = bin2hex(work->hash, sizeof(work->hash));
  678. data = bin2hex(work->data, sizeof(work->data));
  679. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  680. 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);
  681. free(target);
  682. free(hash);
  683. free(data);
  684. if (rv >= (int)(sizeof(s)))
  685. s[sizeof(s) - 1] = '\0';
  686. else if (rv < 0) {
  687. applog(LOG_ERR, "sharelog printf error");
  688. return;
  689. }
  690. mutex_lock(&sharelog_lock);
  691. ret = fwrite(s, rv, 1, sharelog_file);
  692. fflush(sharelog_file);
  693. mutex_unlock(&sharelog_lock);
  694. if (ret != 1)
  695. applog(LOG_ERR, "sharelog fwrite error");
  696. }
  697. static char *gbt_req = "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"]}]}\n";
  698. static char *gbt_solo_req = "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": [{\"rules\" : [\"segwit\"]}]}\n";
  699. static const char *gbt_understood_rules[1] = { NULL };
  700. static const char *gbt_solo_understood_rules[2] = {"segwit", NULL};
  701. static bool gbt_check_required_rule(const char* rule, const char** understood_rules)
  702. {
  703. const char *understood_rule;
  704. if (!understood_rules || !rule)
  705. return false;
  706. while ((understood_rule = *understood_rules++)) {
  707. if (strcmp(understood_rule, rule) == 0)
  708. return true;
  709. }
  710. return false;
  711. }
  712. static bool gbt_check_rules(json_t* rules_arr, const char** understood_rules)
  713. {
  714. int i, rule_count;
  715. const char *rule;
  716. if (!rules_arr)
  717. return true;
  718. rule_count = json_array_size(rules_arr);
  719. for (i = 0; i < rule_count; i++) {
  720. rule = json_string_value(json_array_get(rules_arr, i));
  721. if (rule && *rule++ == '!' && !gbt_check_required_rule(rule, understood_rules))
  722. return false;
  723. }
  724. return true;
  725. }
  726. /* Adjust all the pools' quota to the greatest common denominator after a pool
  727. * has been added or the quotas changed. */
  728. void adjust_quota_gcd(void)
  729. {
  730. unsigned long gcd, lowest_quota = ~0UL, quota;
  731. struct pool *pool;
  732. int i;
  733. for (i = 0; i < total_pools; i++) {
  734. pool = pools[i];
  735. quota = pool->quota;
  736. if (!quota)
  737. continue;
  738. if (quota < lowest_quota)
  739. lowest_quota = quota;
  740. }
  741. if (likely(lowest_quota < ~0UL)) {
  742. gcd = lowest_quota;
  743. for (i = 0; i < total_pools; i++) {
  744. pool = pools[i];
  745. quota = pool->quota;
  746. if (!quota)
  747. continue;
  748. while (quota % gcd)
  749. gcd--;
  750. }
  751. } else
  752. gcd = 1;
  753. for (i = 0; i < total_pools; i++) {
  754. pool = pools[i];
  755. pool->quota_used *= global_quota_gcd;
  756. pool->quota_used /= gcd;
  757. pool->quota_gcd = pool->quota / gcd;
  758. }
  759. global_quota_gcd = gcd;
  760. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  761. }
  762. /* Return value is ignored if not called from input_pool */
  763. struct pool *add_pool(void)
  764. {
  765. struct pool *pool;
  766. pool = cgcalloc(sizeof(struct pool), 1);
  767. pool->pool_no = pool->prio = total_pools;
  768. pools = cgrealloc(pools, sizeof(struct pool *) * (total_pools + 2));
  769. pools[total_pools++] = pool;
  770. mutex_init(&pool->pool_lock);
  771. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  772. quit(1, "Failed to pthread_cond_init in add_pool");
  773. cglock_init(&pool->data_lock);
  774. mutex_init(&pool->stratum_lock);
  775. cglock_init(&pool->gbt_lock);
  776. INIT_LIST_HEAD(&pool->curlring);
  777. /* Make sure the pool doesn't think we've been idle since time 0 */
  778. pool->tv_idle.tv_sec = ~0UL;
  779. pool->rpc_req = gbt_req;
  780. pool->rpc_proxy = NULL;
  781. pool->quota = 1;
  782. adjust_quota_gcd();
  783. #ifdef USE_XTRANONCE
  784. pool->extranonce_subscribe = false;
  785. #endif
  786. return pool;
  787. }
  788. /* Pool variant of test and set */
  789. static bool pool_tset(struct pool *pool, bool *var)
  790. {
  791. bool ret;
  792. mutex_lock(&pool->pool_lock);
  793. ret = *var;
  794. *var = true;
  795. mutex_unlock(&pool->pool_lock);
  796. return ret;
  797. }
  798. bool pool_tclear(struct pool *pool, bool *var)
  799. {
  800. bool ret;
  801. mutex_lock(&pool->pool_lock);
  802. ret = *var;
  803. *var = false;
  804. mutex_unlock(&pool->pool_lock);
  805. return ret;
  806. }
  807. struct pool *current_pool(void)
  808. {
  809. struct pool *pool;
  810. cg_rlock(&control_lock);
  811. pool = currentpool;
  812. cg_runlock(&control_lock);
  813. return pool;
  814. }
  815. char *set_int_range(const char *arg, int *i, int min, int max)
  816. {
  817. char *err = opt_set_intval(arg, i);
  818. if (err)
  819. return err;
  820. if (*i < min || *i > max)
  821. return "Value out of range";
  822. return NULL;
  823. }
  824. static char *set_int_0_to_65535(const char *arg, int *i)
  825. {
  826. return set_int_range(arg, i, 0, 65535);
  827. }
  828. static char *set_int_0_to_9999(const char *arg, int *i)
  829. {
  830. return set_int_range(arg, i, 0, 9999);
  831. }
  832. static char *set_int_1_to_65535(const char *arg, int *i)
  833. {
  834. return set_int_range(arg, i, 1, 65535);
  835. }
  836. #if defined(USE_AVALON7) || defined(USE_AVALON8) || defined(USE_AVALON9) || defined (USE_AVALONLC3)
  837. static char *set_int_0_to_1(const char *arg, int *i)
  838. {
  839. return set_int_range(arg, i, 0, 1);
  840. }
  841. static char *set_int_0_to_7(const char *arg, int *i)
  842. {
  843. return set_int_range(arg, i, 0, 7);
  844. }
  845. static char *set_int_0_to_32767(const char *arg, int *i)
  846. {
  847. return set_int_range(arg, i, 0, 32767);
  848. }
  849. #endif
  850. static char *set_int_0_to_5(const char *arg, int *i)
  851. {
  852. return set_int_range(arg, i, 0, 5);
  853. }
  854. static char *set_int_0_to_10(const char *arg, int *i)
  855. {
  856. return set_int_range(arg, i, 0, 10);
  857. }
  858. #ifdef USE_DRAGONMINT_T1
  859. static char *set_int_voltage(const char *arg, int *i)
  860. {
  861. return set_int_range(arg, i, CHIP_VOLT_MIN, CHIP_VOLT_MAX);
  862. }
  863. /* Intentionally does NOT accept zero so that zero means the value is NOT set
  864. * and has no effect. */
  865. static char *set_int_1_to_31(const char *arg, int *i)
  866. {
  867. return set_int_range(arg, i, 1, 31);
  868. }
  869. #endif
  870. static char *set_int_0_to_100(const char *arg, int *i)
  871. {
  872. return set_int_range(arg, i, 0, 100);
  873. }
  874. static char *set_int_0_to_255(const char *arg, int *i)
  875. {
  876. return set_int_range(arg, i, 0, 255);
  877. }
  878. static char *set_int_1_to_255(const char *arg, int *i)
  879. {
  880. return set_int_range(arg, i, 1, 255);
  881. }
  882. static char *set_int_0_to_7680(const char *arg, int *i)
  883. {
  884. return set_int_range(arg, i, 0, 7680);
  885. }
  886. #if defined(USE_AVALON4)
  887. static char *set_int_1_to_60(const char *arg, int *i)
  888. {
  889. return set_int_range(arg, i, 1, 60);
  890. }
  891. #endif
  892. static char *set_int_0_to_200(const char *arg, int *i)
  893. {
  894. return set_int_range(arg, i, 0, 200);
  895. }
  896. static char *set_int_32_to_63(const char *arg, int *i)
  897. {
  898. return set_int_range(arg, i, 32, 63);
  899. }
  900. static char *set_int_22_to_75(const char *arg, int *i)
  901. {
  902. return set_int_range(arg, i, 22, 75);
  903. }
  904. static char *set_int_42_to_85(const char *arg, int *i)
  905. {
  906. return set_int_range(arg, i, 42, 85);
  907. }
  908. static char *set_int_1_to_10(const char *arg, int *i)
  909. {
  910. return set_int_range(arg, i, 1, 10);
  911. }
  912. static char *set_int_24_to_32(const char *arg, int *i)
  913. {
  914. return set_int_range(arg, i, 24, 32);
  915. }
  916. static char __maybe_unused *set_int_0_to_2(const char *arg, int *i)
  917. {
  918. return set_int_range(arg, i, 0, 2);
  919. }
  920. static char __maybe_unused *set_int_0_to_3(const char *arg, int *i)
  921. {
  922. return set_int_range(arg, i, 0, 3);
  923. }
  924. static char __maybe_unused *set_int_0_to_4(const char *arg, int *i)
  925. {
  926. return set_int_range(arg, i, 0, 4);
  927. }
  928. #ifdef USE_FPGA_SERIAL
  929. static char *opt_add_serial;
  930. static char *add_serial(char *arg)
  931. {
  932. string_elist_add(arg, &scan_devices);
  933. return NULL;
  934. }
  935. #endif
  936. void get_intrange(char *arg, int *val1, int *val2)
  937. {
  938. if (sscanf(arg, "%d-%d", val1, val2) == 1)
  939. *val2 = *val1;
  940. }
  941. static char *set_balance(enum pool_strategy *strategy)
  942. {
  943. *strategy = POOL_BALANCE;
  944. return NULL;
  945. }
  946. static char *set_loadbalance(enum pool_strategy *strategy)
  947. {
  948. *strategy = POOL_LOADBALANCE;
  949. return NULL;
  950. }
  951. static char *set_rotate(const char *arg, char __maybe_unused *i)
  952. {
  953. pool_strategy = POOL_ROTATE;
  954. return set_int_range(arg, &opt_rotate_period, 0, 9999);
  955. }
  956. static char *set_rr(enum pool_strategy *strategy)
  957. {
  958. *strategy = POOL_ROUNDROBIN;
  959. return NULL;
  960. }
  961. /* Detect that url is for a stratum protocol either via the presence of
  962. * stratum+tcp or by detecting a stratum server response */
  963. bool detect_stratum(struct pool *pool, char *url)
  964. {
  965. bool ret = false;
  966. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  967. goto out;
  968. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  969. pool->rpc_url = strdup(url);
  970. pool->has_stratum = true;
  971. pool->stratum_url = pool->sockaddr_url;
  972. ret = true;
  973. }
  974. out:
  975. if (!ret) {
  976. free(pool->sockaddr_url);
  977. free(pool->stratum_port);
  978. pool->stratum_port = pool->sockaddr_url = NULL;
  979. }
  980. return ret;
  981. }
  982. static struct pool *add_url(void)
  983. {
  984. total_urls++;
  985. if (total_urls > total_pools)
  986. add_pool();
  987. return pools[total_urls - 1];
  988. }
  989. static char *setup_url(struct pool *pool, char *arg)
  990. {
  991. arg = get_proxy(arg, pool);
  992. if (detect_stratum(pool, arg))
  993. goto out;
  994. opt_set_charp(arg, &pool->rpc_url);
  995. if (strncmp(arg, "http://", 7) &&
  996. strncmp(arg, "https://", 8)) {
  997. char httpinput[256];
  998. strcpy(httpinput, "stratum+tcp://");
  999. strncat(httpinput, arg, 242);
  1000. detect_stratum(pool, httpinput);
  1001. }
  1002. out:
  1003. return pool->rpc_url;
  1004. }
  1005. static char *set_url(char *arg)
  1006. {
  1007. struct pool *pool = add_url();
  1008. setup_url(pool, arg);
  1009. #ifdef USE_XTRANONCE
  1010. if (strstr(pool->rpc_url, ".nicehash.com") || strstr(pool->rpc_url, "#xnsub")) {
  1011. pool->extranonce_subscribe = true;
  1012. applog(LOG_DEBUG, "Pool %d extranonce subscribing enabled.", pool->pool_no);
  1013. }
  1014. #endif
  1015. return NULL;
  1016. }
  1017. static char *set_quota(char *arg)
  1018. {
  1019. char *semicolon = strchr(arg, ';'), *url;
  1020. int len, qlen, quota;
  1021. struct pool *pool;
  1022. if (!semicolon)
  1023. return "No semicolon separated quota;URL pair found";
  1024. len = strlen(arg);
  1025. *semicolon = '\0';
  1026. qlen = strlen(arg);
  1027. if (!qlen)
  1028. return "No parameter for quota found";
  1029. len -= qlen + 1;
  1030. if (len < 1)
  1031. return "No parameter for URL found";
  1032. quota = atoi(arg);
  1033. if (quota < 0)
  1034. return "Invalid negative parameter for quota set";
  1035. url = arg + qlen + 1;
  1036. pool = add_url();
  1037. setup_url(pool, url);
  1038. pool->quota = quota;
  1039. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1040. adjust_quota_gcd();
  1041. return NULL;
  1042. }
  1043. static char *set_user(const char *arg)
  1044. {
  1045. struct pool *pool;
  1046. if (total_userpasses)
  1047. return "Use only user + pass or userpass, but not both";
  1048. total_users++;
  1049. if (total_users > total_pools)
  1050. add_pool();
  1051. pool = pools[total_users - 1];
  1052. opt_set_charp(arg, &pool->rpc_user);
  1053. return NULL;
  1054. }
  1055. static char *set_pass(const char *arg)
  1056. {
  1057. struct pool *pool;
  1058. if (total_userpasses)
  1059. return "Use only user + pass or userpass, but not both";
  1060. total_passes++;
  1061. if (total_passes > total_pools)
  1062. add_pool();
  1063. pool = pools[total_passes - 1];
  1064. opt_set_charp(arg, &pool->rpc_pass);
  1065. return NULL;
  1066. }
  1067. static char *set_userpass(const char *arg)
  1068. {
  1069. struct pool *pool;
  1070. char *updup;
  1071. if (total_users || total_passes)
  1072. return "Use only user + pass or userpass, but not both";
  1073. total_userpasses++;
  1074. if (total_userpasses > total_pools)
  1075. add_pool();
  1076. pool = pools[total_userpasses - 1];
  1077. updup = strdup(arg);
  1078. opt_set_charp(arg, &pool->rpc_userpass);
  1079. pool->rpc_user = strtok(updup, ":");
  1080. if (!pool->rpc_user)
  1081. return "Failed to find : delimited user info";
  1082. pool->rpc_pass = strtok(NULL, ":");
  1083. if (!pool->rpc_pass)
  1084. pool->rpc_pass = strdup("");
  1085. return NULL;
  1086. }
  1087. #ifdef USE_XTRANONCE
  1088. static char *set_extranonce_subscribe(char *arg)
  1089. {
  1090. struct pool *pool;
  1091. total_extranonce++;
  1092. if (total_extranonce > total_pools)
  1093. add_pool();
  1094. pool = pools[total_extranonce - 1];
  1095. applog(LOG_DEBUG, "Enable extranonce subscribe on %d", pool->pool_no);
  1096. opt_set_bool(&pool->extranonce_subscribe);
  1097. return NULL;
  1098. }
  1099. #endif
  1100. static char *enable_debug(bool *flag)
  1101. {
  1102. *flag = true;
  1103. /* Turn on verbose output, too. */
  1104. opt_log_output = true;
  1105. return NULL;
  1106. }
  1107. static char *opt_set_sched_start;
  1108. static char *opt_set_sched_stop;
  1109. static char *set_schedtime(const char *arg, struct schedtime *st)
  1110. {
  1111. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1112. return "Invalid time set, should be HH:MM";
  1113. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1114. return "Invalid time set.";
  1115. st->enable = true;
  1116. return NULL;
  1117. }
  1118. static char *set_sched_start(const char *arg)
  1119. {
  1120. return set_schedtime(arg, &schedstart);
  1121. }
  1122. static char *set_sched_stop(const char *arg)
  1123. {
  1124. return set_schedtime(arg, &schedstop);
  1125. }
  1126. static char *opt_set_sharelog;
  1127. static char* set_sharelog(char *arg)
  1128. {
  1129. char *r = "";
  1130. long int i = strtol(arg, &r, 10);
  1131. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1132. sharelog_file = fdopen((int)i, "a");
  1133. if (!sharelog_file)
  1134. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  1135. } else if (!strcmp(arg, "-")) {
  1136. sharelog_file = stdout;
  1137. if (!sharelog_file)
  1138. applog(LOG_ERR, "Standard output missing for share log");
  1139. } else {
  1140. sharelog_file = fopen(arg, "a");
  1141. if (!sharelog_file)
  1142. applog(LOG_ERR, "Failed to open %s for share log", arg);
  1143. }
  1144. return NULL;
  1145. }
  1146. static char *temp_cutoff_str = NULL;
  1147. static char __maybe_unused *opt_set_temp_cutoff;
  1148. char *set_temp_cutoff(char *arg)
  1149. {
  1150. int val;
  1151. if (!(arg && arg[0]))
  1152. return "Invalid parameters for set temp cutoff";
  1153. val = atoi(arg);
  1154. if (val < 0 || val > 200)
  1155. return "Invalid value passed to set temp cutoff";
  1156. temp_cutoff_str = arg;
  1157. return NULL;
  1158. }
  1159. static void load_temp_cutoffs()
  1160. {
  1161. int i, val = 0, device = 0;
  1162. char *nextptr;
  1163. if (temp_cutoff_str) {
  1164. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  1165. if (device >= total_devices)
  1166. quit(1, "Too many values passed to set temp cutoff");
  1167. val = atoi(nextptr);
  1168. if (val < 0 || val > 200)
  1169. quit(1, "Invalid value passed to set temp cutoff");
  1170. rd_lock(&devices_lock);
  1171. devices[device]->cutofftemp = val;
  1172. rd_unlock(&devices_lock);
  1173. }
  1174. } else {
  1175. rd_lock(&devices_lock);
  1176. for (i = device; i < total_devices; ++i) {
  1177. if (!devices[i]->cutofftemp)
  1178. devices[i]->cutofftemp = opt_cutofftemp;
  1179. }
  1180. rd_unlock(&devices_lock);
  1181. return;
  1182. }
  1183. if (device <= 1) {
  1184. rd_lock(&devices_lock);
  1185. for (i = device; i < total_devices; ++i)
  1186. devices[i]->cutofftemp = val;
  1187. rd_unlock(&devices_lock);
  1188. }
  1189. }
  1190. static char *set_float_0_to_500(const char *arg, float *i)
  1191. {
  1192. char *err = opt_set_floatval(arg, i);
  1193. if (err)
  1194. return err;
  1195. if (*i < 0 || *i > 500)
  1196. return "Value out of range";
  1197. return NULL;
  1198. }
  1199. static char *set_float_100_to_500(const char *arg, float *i)
  1200. {
  1201. char *err = opt_set_floatval(arg, i);
  1202. if (err)
  1203. return err;
  1204. if (*i < 100 || *i > 500)
  1205. return "Value out of range";
  1206. return NULL;
  1207. }
  1208. static char *set_float_125_to_500(const char *arg, float *i)
  1209. {
  1210. char *err = opt_set_floatval(arg, i);
  1211. if (err)
  1212. return err;
  1213. if (*i < 125 || *i > 500)
  1214. return "Value out of range";
  1215. return NULL;
  1216. }
  1217. static char *set_float_100_to_250(const char *arg, float *i)
  1218. {
  1219. char *err = opt_set_floatval(arg, i);
  1220. if (err)
  1221. return err;
  1222. if (*i < 100 || *i > 250)
  1223. return "Value out of range";
  1224. return NULL;
  1225. }
  1226. static char *set_null(const char __maybe_unused *arg)
  1227. {
  1228. return NULL;
  1229. }
  1230. #ifdef USE_BITMAIN_SOC
  1231. static char *set_version_path(const char *arg)
  1232. {
  1233. opt_set_charp(arg, &opt_version_path);
  1234. return NULL;
  1235. }
  1236. #endif
  1237. /* These options are available from config file or commandline */
  1238. static struct opt_table opt_config_table[] = {
  1239. #ifdef USE_ICARUS
  1240. OPT_WITH_ARG("--anu-freq",
  1241. set_float_125_to_500, &opt_show_floatval, &opt_anu_freq,
  1242. "Set AntminerU1/2 frequency in MHz, range 125-500"),
  1243. #endif
  1244. OPT_WITH_ARG("--api-allow",
  1245. opt_set_charp, NULL, &opt_api_allow,
  1246. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1247. OPT_WITH_ARG("--api-description",
  1248. opt_set_charp, NULL, &opt_api_description,
  1249. "Description placed in the API status header, default: cgminer version"),
  1250. OPT_WITH_ARG("--api-groups",
  1251. opt_set_charp, NULL, &opt_api_groups,
  1252. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1253. OPT_WITHOUT_ARG("--api-listen",
  1254. opt_set_bool, &opt_api_listen,
  1255. "Enable API, default: disabled"),
  1256. OPT_WITHOUT_ARG("--api-mcast",
  1257. opt_set_bool, &opt_api_mcast,
  1258. "Enable API Multicast listener, default: disabled"),
  1259. OPT_WITH_ARG("--api-mcast-addr",
  1260. opt_set_charp, NULL, &opt_api_mcast_addr,
  1261. "API Multicast listen address"),
  1262. OPT_WITH_ARG("--api-mcast-code",
  1263. opt_set_charp, NULL, &opt_api_mcast_code,
  1264. "Code expected in the API Multicast message, don't use '-'"),
  1265. OPT_WITH_ARG("--api-mcast-des",
  1266. opt_set_charp, NULL, &opt_api_mcast_des,
  1267. "Description appended to the API Multicast reply, default: ''"),
  1268. OPT_WITH_ARG("--api-mcast-port",
  1269. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1270. "API Multicast listen port"),
  1271. OPT_WITHOUT_ARG("--api-network",
  1272. opt_set_bool, &opt_api_network,
  1273. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1274. OPT_WITH_ARG("--api-port",
  1275. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1276. "Port number of miner API"),
  1277. OPT_WITH_ARG("--api-host",
  1278. opt_set_charp, NULL, &opt_api_host,
  1279. "Specify API listen address, default: 0.0.0.0"),
  1280. #ifdef USE_ICARUS
  1281. OPT_WITH_ARG("--au3-freq",
  1282. set_float_100_to_250, &opt_show_floatval, &opt_au3_freq,
  1283. "Set AntminerU3 frequency in MHz, range 100-250"),
  1284. OPT_WITH_ARG("--au3-volt",
  1285. set_int_0_to_9999, &opt_show_intval, &opt_au3_volt,
  1286. "Set AntminerU3 voltage in mv, range 725-850, 0 to not set"),
  1287. #endif
  1288. #ifdef USE_AVALON
  1289. OPT_WITHOUT_ARG("--avalon-auto",
  1290. opt_set_bool, &opt_avalon_auto,
  1291. "Adjust avalon overclock frequency dynamically for best hashrate"),
  1292. OPT_WITH_ARG("--avalon-cutoff",
  1293. set_int_0_to_100, opt_show_intval, &opt_avalon_overheat,
  1294. "Set avalon overheat cut off temperature"),
  1295. OPT_WITH_CBARG("--avalon-fan",
  1296. set_avalon_fan, NULL, &opt_set_avalon_fan,
  1297. "Set fanspeed percentage for avalon, single value or range (default: 20-100)"),
  1298. OPT_WITH_CBARG("--avalon-freq",
  1299. set_avalon_freq, NULL, &opt_set_avalon_freq,
  1300. "Set frequency range for avalon-auto, single value or range"),
  1301. OPT_WITH_ARG("--avalon-options",
  1302. opt_set_charp, NULL, &opt_avalon_options,
  1303. "Set avalon options baud:miners:asic:timeout:freq:tech"),
  1304. OPT_WITH_ARG("--avalon-temp",
  1305. set_int_0_to_100, opt_show_intval, &opt_avalon_temp,
  1306. "Set avalon target temperature"),
  1307. #endif
  1308. #ifdef USE_AVALON2
  1309. OPT_WITH_CBARG("--avalon2-freq",
  1310. set_avalon2_freq, NULL, &opt_set_avalon2_freq,
  1311. "Set frequency range for Avalon2, single value or range, step: 25"),
  1312. OPT_WITH_CBARG("--avalon2-voltage",
  1313. set_avalon2_voltage, NULL, &opt_set_avalon2_voltage,
  1314. "Set Avalon2 core voltage, in millivolts, step: 125"),
  1315. OPT_WITH_CBARG("--avalon2-fan",
  1316. set_avalon2_fan, NULL, &opt_set_avalon2_fan,
  1317. "Set Avalon2 target fan speed"),
  1318. OPT_WITH_ARG("--avalon2-cutoff",
  1319. set_int_0_to_100, opt_show_intval, &opt_avalon2_overheat,
  1320. "Set Avalon2 overheat cut off temperature"),
  1321. OPT_WITHOUT_ARG("--avalon2-fixed-speed",
  1322. set_avalon2_fixed_speed, &opt_avalon2_fan_fixed,
  1323. "Set Avalon2 fan to fixed speed"),
  1324. OPT_WITH_ARG("--avalon2-polling-delay",
  1325. set_int_1_to_65535, opt_show_intval, &opt_avalon2_polling_delay,
  1326. "Set Avalon2 polling delay value (ms)"),
  1327. #endif
  1328. #ifdef USE_AVALON4
  1329. OPT_WITHOUT_ARG("--avalon4-automatic-voltage",
  1330. opt_set_bool, &opt_avalon4_autov,
  1331. "Automatic adjust voltage base on module DH"),
  1332. OPT_WITH_CBARG("--avalon4-voltage",
  1333. set_avalon4_voltage, NULL, &opt_set_avalon4_voltage,
  1334. "Set Avalon4 core voltage, in millivolts, step: 125"),
  1335. OPT_WITH_CBARG("--avalon4-freq",
  1336. set_avalon4_freq, NULL, &opt_set_avalon4_freq,
  1337. "Set frequency for Avalon4, 1 to 3 values, example: 445:385:370"),
  1338. OPT_WITH_CBARG("--avalon4-fan",
  1339. set_avalon4_fan, NULL, &opt_set_avalon4_fan,
  1340. "Set Avalon4 target fan speed range"),
  1341. OPT_WITH_ARG("--avalon4-temp",
  1342. set_int_22_to_75, opt_show_intval, &opt_avalon4_temp_target,
  1343. "Set Avalon4 target temperature"),
  1344. OPT_WITH_ARG("--avalon4-cutoff",
  1345. set_int_42_to_85, opt_show_intval, &opt_avalon4_overheat,
  1346. "Set Avalon4 overheat cut off temperature"),
  1347. OPT_WITH_ARG("--avalon4-polling-delay",
  1348. set_int_1_to_65535, opt_show_intval, &opt_avalon4_polling_delay,
  1349. "Set Avalon4 polling delay value (ms)"),
  1350. OPT_WITH_ARG("--avalon4-ntime-offset",
  1351. opt_set_intval, opt_show_intval, &opt_avalon4_ntime_offset,
  1352. "Set Avalon4 MM ntime rolling max offset"),
  1353. OPT_WITH_ARG("--avalon4-aucspeed",
  1354. opt_set_intval, opt_show_intval, &opt_avalon4_aucspeed,
  1355. "Set Avalon4 AUC IIC bus speed"),
  1356. OPT_WITH_ARG("--avalon4-aucxdelay",
  1357. opt_set_intval, opt_show_intval, &opt_avalon4_aucxdelay,
  1358. "Set Avalon4 AUC IIC xfer read delay, 4800 ~= 1ms"),
  1359. OPT_WITH_ARG("--avalon4-miningmode",
  1360. opt_set_intval, opt_show_intval, &opt_avalon4_miningmode,
  1361. "Set Avalon4 mining mode(0:custom, 1:eco, 2:normal, 3:turbo"),
  1362. OPT_WITHOUT_ARG("--avalon4-freezesafe",
  1363. opt_set_bool, &opt_avalon4_freezesafe,
  1364. "Make Avalon4 running as a radiator when stratum server failed"),
  1365. OPT_WITH_ARG("--avalon4-ntcb",
  1366. opt_set_intval, opt_show_intval, &opt_avalon4_ntcb,
  1367. "Set Avalon4 MM NTC B value"),
  1368. OPT_WITH_ARG("--avalon4-freq-min",
  1369. opt_set_intval, opt_show_intval, &opt_avalon4_freq_min,
  1370. "Set minimum frequency for Avalon4"),
  1371. OPT_WITH_ARG("--avalon4-freq-max",
  1372. opt_set_intval, opt_show_intval, &opt_avalon4_freq_max,
  1373. "Set maximum frequency for Avalon4"),
  1374. OPT_WITHOUT_ARG("--avalon4-noncecheck-off",
  1375. opt_set_invbool, &opt_avalon4_noncecheck,
  1376. "Disable A3218 inside nonce check function"),
  1377. OPT_WITH_ARG("--avalon4-smart-speed",
  1378. opt_set_intval, opt_show_intval, &opt_avalon4_smart_speed,
  1379. "Set smart speed, range 0-3. 0 means Disable"),
  1380. OPT_WITH_ARG("--avalon4-speed-bingo",
  1381. set_int_1_to_255, opt_show_intval, &opt_avalon4_speed_bingo,
  1382. "Set A3218 speed bingo for smart speed mode 1"),
  1383. OPT_WITH_ARG("--avalon4-speed-error",
  1384. set_int_1_to_255, opt_show_intval, &opt_avalon4_speed_error,
  1385. "Set A3218 speed error for smart speed mode 1"),
  1386. OPT_WITH_ARG("--avalon4-least-pll",
  1387. set_int_0_to_7680, opt_show_intval, &opt_avalon4_least_pll_check,
  1388. "Set least pll check threshold for smart speed mode 2"),
  1389. OPT_WITH_ARG("--avalon4-most-pll",
  1390. set_int_0_to_7680, opt_show_intval, &opt_avalon4_most_pll_check,
  1391. "Set most pll check threshold for smart speed mode 2"),
  1392. OPT_WITHOUT_ARG("--avalon4-iic-detect",
  1393. opt_set_bool, &opt_avalon4_iic_detect,
  1394. "Enable miner detect through iic controller"),
  1395. OPT_WITH_ARG("--avalon4-freqadj-time",
  1396. set_int_1_to_60, opt_show_intval, &opt_avalon4_freqadj_time,
  1397. "Set Avalon4 check interval when run in AVA4_FREQ_TEMPADJ_MODE"),
  1398. OPT_WITH_ARG("--avalon4-delta-temp",
  1399. opt_set_intval, opt_show_intval, &opt_avalon4_delta_temp,
  1400. "Set Avalon4 delta temperature when reset freq in AVA4_FREQ_TEMPADJ_MODE"),
  1401. OPT_WITH_ARG("--avalon4-delta-freq",
  1402. opt_set_intval, opt_show_intval, &opt_avalon4_delta_freq,
  1403. "Set Avalon4 delta freq when adjust freq in AVA4_FREQ_TEMPADJ_MODE"),
  1404. OPT_WITH_ARG("--avalon4-freqadj-temp",
  1405. opt_set_intval, opt_show_intval, &opt_avalon4_freqadj_temp,
  1406. "Set Avalon4 check temperature when run into AVA4_FREQ_TEMPADJ_MODE"),
  1407. #endif
  1408. #ifdef USE_AVALON7
  1409. OPT_WITH_CBARG("--avalon7-voltage",
  1410. set_avalon7_voltage, NULL, &opt_set_avalon7_voltage,
  1411. "Set Avalon7 default core voltage, in millivolts, step: 78"),
  1412. OPT_WITH_CBARG("--avalon7-voltage-level",
  1413. set_avalon7_voltage_level, NULL, &opt_set_avalon7_voltage_level,
  1414. "Set Avalon7 default level of core voltage, range:[0, 15], step: 1"),
  1415. OPT_WITH_CBARG("--avalon7-voltage-offset",
  1416. set_avalon7_voltage_offset, NULL, &opt_set_avalon7_voltage_offset,
  1417. "Set Avalon7 default offset of core voltage, range:[-2, 1], step: 1"),
  1418. OPT_WITH_CBARG("--avalon7-freq",
  1419. set_avalon7_freq, NULL, &opt_set_avalon7_freq,
  1420. "Set Avalon7 default frequency, range:[24, 1404], step: 12, example: 500"),
  1421. OPT_WITH_ARG("--avalon7-freq-sel",
  1422. set_int_0_to_5, opt_show_intval, &opt_avalon7_freq_sel,
  1423. "Set Avalon7 default frequency select, range:[0, 5], step: 1, example: 3"),
  1424. OPT_WITH_CBARG("--avalon7-fan",
  1425. set_avalon7_fan, NULL, &opt_set_avalon7_fan,
  1426. "Set Avalon7 target fan speed, range:[0, 100], step: 1, example: 0-100"),
  1427. OPT_WITH_ARG("--avalon7-temp",
  1428. set_int_0_to_100, opt_show_intval, &opt_avalon7_temp_target,
  1429. "Set Avalon7 target temperature, range:[0, 100]"),
  1430. OPT_WITH_ARG("--avalon7-polling-delay",
  1431. set_int_1_to_65535, opt_show_intval, &opt_avalon7_polling_delay,
  1432. "Set Avalon7 polling delay value (ms)"),
  1433. OPT_WITH_ARG("--avalon7-aucspeed",
  1434. opt_set_intval, opt_show_intval, &opt_avalon7_aucspeed,
  1435. "Set AUC3 IIC bus speed"),
  1436. OPT_WITH_ARG("--avalon7-aucxdelay",
  1437. opt_set_intval, opt_show_intval, &opt_avalon7_aucxdelay,
  1438. "Set AUC3 IIC xfer read delay, 4800 ~= 1ms"),
  1439. OPT_WITH_ARG("--avalon7-smart-speed",
  1440. opt_set_intval, opt_show_intval, &opt_avalon7_smart_speed,
  1441. "Set Avalon7 smart speed, range 0-1. 0 means Disable"),
  1442. OPT_WITH_ARG("--avalon7-th-pass",
  1443. set_int_0_to_65535, opt_show_intval, &opt_avalon7_th_pass,
  1444. "Set A3212 th pass value"),
  1445. OPT_WITH_ARG("--avalon7-th-fail",
  1446. set_int_0_to_65535, opt_show_intval, &opt_avalon7_th_fail,
  1447. "Set A3212 th fail value"),
  1448. OPT_WITH_ARG("--avalon7-th-init",
  1449. set_int_0_to_65535, opt_show_intval, &opt_avalon7_th_init,
  1450. "Set A3212 th init value"),
  1451. OPT_WITH_ARG("--avalon7-th-ms",
  1452. set_int_0_to_65535, opt_show_intval, &opt_avalon7_th_ms,
  1453. "Set A3212 th ms value"),
  1454. OPT_WITH_ARG("--avalon7-th-timeout",
  1455. opt_set_uintval, opt_show_uintval, &opt_avalon7_th_timeout,
  1456. "Set A3212 th timeout value"),
  1457. OPT_WITHOUT_ARG("--avalon7-iic-detect",
  1458. opt_set_bool, &opt_avalon7_iic_detect,
  1459. "Enable Avalon7 detect through iic controller"),
  1460. OPT_WITH_ARG("--avalon7-nonce-mask",
  1461. set_int_24_to_32, opt_show_intval, &opt_avalon7_nonce_mask,
  1462. "Set A3212 nonce mask, range 24-32."),
  1463. OPT_WITHOUT_ARG("--no-avalon7-asic-debug",
  1464. opt_set_invbool, &opt_avalon7_asic_debug,
  1465. "Disable A3212 debug."),
  1466. OPT_WITHOUT_ARG("--avalon7-ssplus-enable",
  1467. opt_set_bool, &opt_avalon7_ssplus_enable,
  1468. "Enable avalon7 smart speed plus."),
  1469. #endif
  1470. #ifdef USE_AVALON8
  1471. OPT_WITH_CBARG("--avalon8-voltage-level",
  1472. set_avalon8_voltage_level, NULL, &opt_set_avalon8_voltage_level,
  1473. "Set Avalon8 default level of core voltage, range:[0, 15], step: 1"),
  1474. OPT_WITH_CBARG("--avalon8-voltage-level-offset",
  1475. set_avalon8_voltage_level_offset, NULL, &opt_set_avalon8_voltage_level_offset,
  1476. "Set Avalon8 default offset of core voltage level, range:[-2, 1], step: 1"),
  1477. OPT_WITH_CBARG("--avalon8-freq",
  1478. set_avalon8_freq, NULL, &opt_set_avalon8_freq,
  1479. "Set Avalon8 default frequency, range:[25, 1200], step: 25, example: 800"),
  1480. OPT_WITH_ARG("--avalon8-freq-sel",
  1481. set_int_0_to_7, opt_show_intval, &opt_avalon8_freq_sel,
  1482. "Set Avalon8 default frequency select, range:[0, 7], step: 1, example: 7"),
  1483. OPT_WITH_CBARG("--avalon8-fan",
  1484. set_avalon8_fan, NULL, &opt_set_avalon8_fan,
  1485. "Set Avalon8 target fan speed, range:[0, 100], step: 1, example: 0-100"),
  1486. OPT_WITH_ARG("--avalon8-temp",
  1487. set_int_0_to_100, opt_show_intval, &opt_avalon8_temp_target,
  1488. "Set Avalon8 target temperature, range:[0, 100]"),
  1489. OPT_WITH_ARG("--avalon8-polling-delay",
  1490. set_int_1_to_65535, opt_show_intval, &opt_avalon8_polling_delay,
  1491. "Set Avalon8 polling delay value (ms)"),
  1492. OPT_WITH_ARG("--avalon8-aucspeed",
  1493. opt_set_intval, opt_show_intval, &opt_avalon8_aucspeed,
  1494. "Set AUC3 IIC bus speed"),
  1495. OPT_WITH_ARG("--avalon8-aucxdelay",
  1496. opt_set_intval, opt_show_intval, &opt_avalon8_aucxdelay,
  1497. "Set AUC3 IIC xfer read delay, 4800 ~= 1ms"),
  1498. OPT_WITH_ARG("--avalon8-smart-speed",
  1499. opt_set_intval, opt_show_intval, &opt_avalon8_smart_speed,
  1500. "Set Avalon8 smart speed, range 0-1. 0 means Disable"),
  1501. OPT_WITH_ARG("--avalon8-th-pass",
  1502. set_int_0_to_65535, opt_show_intval, &opt_avalon8_th_pass,
  1503. "Set A3210 th pass value"),
  1504. OPT_WITH_ARG("--avalon8-th-fail",
  1505. set_int_0_to_65535, opt_show_intval, &opt_avalon8_th_fail,
  1506. "Set A3210 th fail value"),
  1507. OPT_WITH_ARG("--avalon8-th-init",
  1508. set_int_0_to_65535, opt_show_intval, &opt_avalon8_th_init,
  1509. "Set A3210 th init value"),
  1510. OPT_WITH_ARG("--avalon8-th-ms",
  1511. set_int_0_to_65535, opt_show_intval, &opt_avalon8_th_ms,
  1512. "Set A3210 th ms value"),
  1513. OPT_WITH_ARG("--avalon8-th-timeout",
  1514. opt_set_uintval, opt_show_uintval, &opt_avalon8_th_timeout,
  1515. "Set A3210 th timeout value"),
  1516. OPT_WITH_ARG("--avalon8-th-add",
  1517. set_int_0_to_1, opt_show_intval, &opt_avalon8_th_add,
  1518. "Set A3210 th add value"),
  1519. OPT_WITH_ARG("--avalon8-th-mssel",
  1520. set_int_0_to_1, opt_show_intval, &opt_avalon8_th_mssel,
  1521. "Set A3210 th mssel value"),
  1522. OPT_WITH_ARG("--avalon8-lv2-th-add",
  1523. set_int_0_to_1, opt_show_intval, &opt_avalon8_lv2_th_add,
  1524. "Set A3210 lv2 th add value"),
  1525. OPT_WITH_ARG("--avalon8-lv2-th-ms",
  1526. set_int_0_to_32767, opt_show_intval, &opt_avalon8_lv2_th_ms,
  1527. "Set A3210 lv2 th ms value"),
  1528. OPT_WITH_ARG("--avalon8-lv3-th-add",
  1529. set_int_0_to_1, opt_show_intval, &opt_avalon8_lv3_th_add,
  1530. "Set A3210 lv3 th add value"),
  1531. OPT_WITH_ARG("--avalon8-lv3-th-ms",
  1532. set_int_0_to_32767, opt_show_intval, &opt_avalon8_lv3_th_ms,
  1533. "Set A3210 lv3 th ms value"),
  1534. OPT_WITH_ARG("--avalon8-lv4-th-add",
  1535. set_int_0_to_1, opt_show_intval, &opt_avalon8_lv4_th_add,
  1536. "Set A3210 lv4 th add value"),
  1537. OPT_WITH_ARG("--avalon8-lv4-th-ms",
  1538. set_int_0_to_32767, opt_show_intval, &opt_avalon8_lv4_th_ms,
  1539. "Set A3210 lv4 th ms value"),
  1540. OPT_WITH_ARG("--avalon8-lv5-th-add",
  1541. set_int_0_to_1, opt_show_intval, &opt_avalon8_lv5_th_add,
  1542. "Set A3210 lv5 th add value"),
  1543. OPT_WITH_ARG("--avalon8-lv5-th-ms",
  1544. set_int_0_to_32767, opt_show_intval, &opt_avalon8_lv5_th_ms,
  1545. "Set A3210 lv5 th ms value"),
  1546. OPT_WITH_ARG("--avalon8-lv6-th-add",
  1547. set_int_0_to_1, opt_show_intval, &opt_avalon8_lv6_th_add,
  1548. "Set A3210 lv6 th add value"),
  1549. OPT_WITH_ARG("--avalon8-lv6-th-ms",
  1550. set_int_0_to_32767, opt_show_intval, &opt_avalon8_lv6_th_ms,
  1551. "Set A3210 lv6 th ms value"),
  1552. OPT_WITH_ARG("--avalon8-lv7-th-add",
  1553. set_int_0_to_1, opt_show_intval, &opt_avalon8_lv7_th_add,
  1554. "Set A3210 lv7 th add value"),
  1555. OPT_WITH_ARG("--avalon8-lv7-th-ms",
  1556. set_int_0_to_32767, opt_show_intval, &opt_avalon8_lv7_th_ms,
  1557. "Set A3210 lv7 th ms value"),
  1558. OPT_WITHOUT_ARG("--avalon8-iic-detect",
  1559. opt_set_bool, &opt_avalon8_iic_detect,
  1560. "Enable Avalon8 detect through iic controller"),
  1561. OPT_WITH_ARG("--avalon8-nonce-mask",
  1562. set_int_24_to_32, opt_show_intval, &opt_avalon8_nonce_mask,
  1563. "Set A3210 nonce mask, range 24-32."),
  1564. OPT_WITH_ARG("--avalon8-nonce-check",
  1565. set_int_0_to_1, opt_show_intval, &opt_avalon8_nonce_check,
  1566. "Set A3210 nonce check, range 0-1."),
  1567. OPT_WITH_ARG("--avalon8-roll-enable",
  1568. set_int_0_to_1, opt_show_intval, &opt_avalon8_roll_enable,
  1569. "Set A3210 roll enable, range 0-1."),
  1570. OPT_WITH_ARG("--avalon8-mux-l2h",
  1571. set_int_0_to_2, opt_show_intval, &opt_avalon8_mux_l2h,
  1572. "Set Avalon8 mux l2h, range 0-2."),
  1573. OPT_WITH_ARG("--avalon8-mux-h2l",
  1574. set_int_0_to_1, opt_show_intval, &opt_avalon8_mux_h2l,
  1575. "Set Avalon8 mux h2l, range 0-1."),
  1576. OPT_WITH_ARG("--avalon8-h2ltime0-spd",
  1577. set_int_0_to_255, opt_show_intval, &opt_avalon8_h2ltime0_spd,
  1578. "Set Avalon8 h2ltime0 spd, range 0-255."),
  1579. #endif
  1580. #ifdef USE_AVALON9
  1581. OPT_WITH_CBARG("--avalon9-voltage-level",
  1582. set_avalon9_voltage_level, NULL, &opt_set_avalon9_voltage_level,
  1583. "Set Avalon9 default level of core voltage, range:[0, 15], step: 1"),
  1584. OPT_WITH_CBARG("--avalon9-voltage-level-offset",
  1585. set_avalon9_voltage_level_offset, NULL, &opt_set_avalon9_voltage_level_offset,
  1586. "Set Avalon9 default offset of core voltage level, range:[-2, 1], step: 1"),
  1587. OPT_WITH_CBARG("--avalon9-freq",
  1588. set_avalon9_freq, NULL, &opt_set_avalon9_freq,
  1589. "Set Avalon9 default frequency, range:[25, 1200], step: 25, example: 800"),
  1590. OPT_WITH_ARG("--avalon9-freq-sel",
  1591. set_int_0_to_7, opt_show_intval, &opt_avalon9_freq_sel,
  1592. "Set Avalon9 default frequency select, range:[0, 7], step: 1, example: 7"),
  1593. OPT_WITH_CBARG("--avalon9-fan",
  1594. set_avalon9_fan, NULL, &opt_set_avalon9_fan,
  1595. "Set Avalon9 target fan speed, range:[0, 100], step: 1, example: 0-100"),
  1596. OPT_WITH_ARG("--avalon9-temp",
  1597. set_int_0_to_100, opt_show_intval, &opt_avalon9_temp_target,
  1598. "Set Avalon9 target temperature, range:[0, 100]"),
  1599. OPT_WITH_ARG("--avalon9-polling-delay",
  1600. set_int_1_to_65535, opt_show_intval, &opt_avalon9_polling_delay,
  1601. "Set Avalon9 polling delay value (ms)"),
  1602. OPT_WITH_ARG("--avalon9-aucspeed",
  1603. opt_set_intval, opt_show_intval, &opt_avalon9_aucspeed,
  1604. "Set AUC3 IIC bus speed"),
  1605. OPT_WITH_ARG("--avalon9-aucxdelay",
  1606. opt_set_intval, opt_show_intval, &opt_avalon9_aucxdelay,
  1607. "Set AUC3 IIC xfer read delay, 4800 ~= 1ms"),
  1608. OPT_WITH_ARG("--avalon9-smart-speed",
  1609. opt_set_intval, opt_show_intval, &opt_avalon9_smart_speed,
  1610. "Set Avalon9 smart speed, range 0-1. 0 means Disable"),
  1611. OPT_WITH_ARG("--avalon9-th-pass",
  1612. set_int_0_to_65535, opt_show_intval, &opt_avalon9_th_pass,
  1613. "Set A3206 th pass value"),
  1614. OPT_WITH_ARG("--avalon9-th-fail",
  1615. set_int_0_to_65535, opt_show_intval, &opt_avalon9_th_fail,
  1616. "Set A3206 th fail value"),
  1617. OPT_WITH_ARG("--avalon9-th-init",
  1618. set_int_0_to_65535, opt_show_intval, &opt_avalon9_th_init,
  1619. "Set A3206 th init value"),
  1620. OPT_WITH_ARG("--avalon9-th-ms",
  1621. set_int_0_to_32767, opt_show_intval, &opt_avalon9_th_ms,
  1622. "Set A3206 th ms value"),
  1623. OPT_WITH_ARG("--avalon9-th-timeout",
  1624. opt_set_uintval, opt_show_uintval, &opt_avalon9_th_timeout,
  1625. "Set A3206 th timeout value"),
  1626. OPT_WITH_ARG("--avalon9-th-add",
  1627. set_int_0_to_1, opt_show_intval, &opt_avalon9_th_add,
  1628. "Set A3206 th add value"),
  1629. OPT_WITH_ARG("--avalon9-th-mssel",
  1630. set_int_0_to_1, opt_show_intval, &opt_avalon9_th_mssel,
  1631. "Set A3206 th mssel value"),
  1632. OPT_WITH_ARG("--avalon9-lv2-th-add",
  1633. set_int_0_to_1, opt_show_intval, &opt_avalon9_lv2_th_add,
  1634. "Set A3206 lv2 th add value"),
  1635. OPT_WITH_ARG("--avalon9-lv2-th-ms",
  1636. set_int_0_to_32767, opt_show_intval, &opt_avalon9_lv2_th_ms,
  1637. "Set A3206 lv2 th ms value"),
  1638. OPT_WITH_ARG("--avalon9-lv3-th-add",
  1639. set_int_0_to_1, opt_show_intval, &opt_avalon9_lv3_th_add,
  1640. "Set A3206 lv3 th add value"),
  1641. OPT_WITH_ARG("--avalon9-lv3-th-ms",
  1642. set_int_0_to_32767, opt_show_intval, &opt_avalon9_lv3_th_ms,
  1643. "Set A3206 lv3 th ms value"),
  1644. OPT_WITH_ARG("--avalon9-lv4-th-add",
  1645. set_int_0_to_1, opt_show_intval, &opt_avalon9_lv4_th_add,
  1646. "Set A3206 lv4 th add value"),
  1647. OPT_WITH_ARG("--avalon9-lv4-th-ms",
  1648. set_int_0_to_32767, opt_show_intval, &opt_avalon9_lv4_th_ms,
  1649. "Set A3206 lv4 th ms value"),
  1650. OPT_WITH_ARG("--avalon9-lv5-th-add",
  1651. set_int_0_to_1, opt_show_intval, &opt_avalon9_lv5_th_add,
  1652. "Set A3206 lv5 th add value"),
  1653. OPT_WITH_ARG("--avalon9-lv5-th-ms",
  1654. set_int_0_to_32767, opt_show_intval, &opt_avalon9_lv5_th_ms,
  1655. "Set A3206 lv5 th ms value"),
  1656. OPT_WITH_ARG("--avalon9-lv6-th-add",
  1657. set_int_0_to_1, opt_show_intval, &opt_avalon9_lv6_th_add,
  1658. "Set A3206 lv6 th add value"),
  1659. OPT_WITH_ARG("--avalon9-lv6-th-ms",
  1660. set_int_0_to_32767, opt_show_intval, &opt_avalon9_lv6_th_ms,
  1661. "Set A3206 lv6 th ms value"),
  1662. OPT_WITH_ARG("--avalon9-lv7-th-add",
  1663. set_int_0_to_1, opt_show_intval, &opt_avalon9_lv7_th_add,
  1664. "Set A3206 lv7 th add value"),
  1665. OPT_WITH_ARG("--avalon9-lv7-th-ms",
  1666. set_int_0_to_32767, opt_show_intval, &opt_avalon9_lv7_th_ms,
  1667. "Set A3206 lv7 th ms value"),
  1668. OPT_WITHOUT_ARG("--avalon9-iic-detect",
  1669. opt_set_bool, &opt_avalon9_iic_detect,
  1670. "Enable Avalon9 detect through iic controller"),
  1671. OPT_WITH_ARG("--avalon9-nonce-mask",
  1672. set_int_24_to_32, opt_show_intval, &opt_avalon9_nonce_mask,
  1673. "Set A3206 nonce mask, range 24-32."),
  1674. OPT_WITH_ARG("--avalon9-nonce-check",
  1675. set_int_0_to_1, opt_show_intval, &opt_avalon9_nonce_check,
  1676. "Set A3206 nonce check, range 0-1."),
  1677. OPT_WITH_ARG("--avalon9-roll-enable",
  1678. set_int_0_to_1, opt_show_intval, &opt_avalon9_roll_enable,
  1679. "Set A3206 roll enable, range 0-1."),
  1680. OPT_WITH_ARG("--avalon9-mux-l2h",
  1681. set_int_0_to_2, opt_show_intval, &opt_avalon9_mux_l2h,
  1682. "Set Avalon9 mux l2h, range 0-2."),
  1683. OPT_WITH_ARG("--avalon9-mux-h2l",
  1684. set_int_0_to_1, opt_show_intval, &opt_avalon9_mux_h2l,
  1685. "Set Avalon9 mux h2l, range 0-1."),
  1686. OPT_WITH_ARG("--avalon9-h2ltime0-spd",
  1687. set_int_0_to_255, opt_show_intval, &opt_avalon9_h2ltime0_spd,
  1688. "Set Avalon9 h2ltime0 spd, range 0-255."),
  1689. OPT_WITH_ARG("--avalon9-spdlow",
  1690. set_int_0_to_7, opt_show_intval, &opt_avalon9_spdlow,
  1691. "Set Avalon9 spdlow, range 0-7."),
  1692. OPT_WITH_ARG("--avalon9-spdhigh",
  1693. set_int_0_to_7, opt_show_intval, &opt_avalon9_spdhigh,
  1694. "Set Avalon9 spdhigh, range 0-7."),
  1695. OPT_WITH_ARG("--avalon9-tbase",
  1696. set_int_0_to_255, opt_show_intval, &opt_avalon9_tbase,
  1697. "Set Avalon9 tbase and use (0-8) bits, range 0-255."),
  1698. OPT_WITH_ARG("--avalon9-pid-p",
  1699. set_int_0_to_9999, opt_show_intval, &opt_avalon9_pid_p,
  1700. "Set Avalon9 pid-p, range 0-9999."),
  1701. OPT_WITH_ARG("--avalon9-pid-i",
  1702. set_int_0_to_9999, opt_show_intval, &opt_avalon9_pid_i,
  1703. "Set Avalon9 pid-i, range 0-9999."),
  1704. OPT_WITH_ARG("--avalon9-pid-d",
  1705. set_int_0_to_9999, opt_show_intval, &opt_avalon9_pid_d,
  1706. "Set Avalon9 pid-d, range 0-9999."),
  1707. OPT_WITH_CBARG("--avalon9-adjust-volt-info",
  1708. set_avalon9_adjust_volt_info, NULL, &opt_set_avalon9_adjust_volt_info,
  1709. "Set Avalon9 adjust volt info, range 0-9999"),
  1710. #endif
  1711. #ifdef USE_AVALONLC3
  1712. OPT_WITH_CBARG("--avalonlc3-voltage-level",
  1713. set_avalonlc3_voltage_level, NULL, &opt_set_avalonlc3_voltage_level,
  1714. "Set Avalonlc3 default level of core voltage, range:[0, 31], step: 1"),
  1715. OPT_WITH_CBARG("--avalonlc3-voltage-level-offset",
  1716. set_avalonlc3_voltage_level_offset, NULL, &opt_set_avalonlc3_voltage_level_offset,
  1717. "Set Avalonlc3 default offset of core voltage level, range:[-2, 1], step: 1"),
  1718. OPT_WITH_CBARG("--avalonlc3-freq",
  1719. set_avalonlc3_freq, NULL, &opt_set_avalonlc3_freq,
  1720. "Set Avalonlc3 default frequency, range:[25, 1200], step: 25, example: 800"),
  1721. OPT_WITH_ARG("--avalonlc3-freq-sel",
  1722. set_int_0_to_4, opt_show_intval, &opt_avalonlc3_freq_sel,
  1723. "Set Avalonlc3 default frequency select, range:[0, 4], step: 1, example: 3"),
  1724. OPT_WITH_CBARG("--avalonlc3-fan",
  1725. set_avalonlc3_fan, NULL, &opt_set_avalonlc3_fan,
  1726. "Set Avalonlc3 target fan speed, range:[0, 100], step: 1, example: 0-100"),
  1727. OPT_WITH_ARG("--avalonlc3-temp",
  1728. set_int_0_to_100, opt_show_intval, &opt_avalonlc3_temp_target,
  1729. "Set Avalonlc3 target temperature, range:[0, 100]"),
  1730. OPT_WITH_ARG("--avalonlc3-polling-delay",
  1731. set_int_1_to_65535, opt_show_intval, &opt_avalonlc3_polling_delay,
  1732. "Set Avalonlc3 polling delay value (ms)"),
  1733. OPT_WITH_ARG("--avalonlc3-aucspeed",
  1734. opt_set_intval, opt_show_intval, &opt_avalonlc3_aucspeed,
  1735. "Set AUC3 IIC bus speed"),
  1736. OPT_WITH_ARG("--avalonlc3-aucxdelay",
  1737. opt_set_intval, opt_show_intval, &opt_avalonlc3_aucxdelay,
  1738. "Set AUC3 IIC xfer read delay, 4800 ~= 1ms"),
  1739. OPT_WITH_ARG("--avalonlc3-smart-speed",
  1740. opt_set_intval, opt_show_intval, &opt_avalonlc3_smart_speed,
  1741. "Set Avalonlc3 smart speed, range 0-1. 0 means Disable"),
  1742. OPT_WITH_ARG("--avalonlc3-th-pass",
  1743. set_int_0_to_65535, opt_show_intval, &opt_avalonlc3_th_pass,
  1744. "Set A3210M th pass value"),
  1745. OPT_WITH_ARG("--avalonlc3-th-fail",
  1746. set_int_0_to_65535, opt_show_intval, &opt_avalonlc3_th_fail,
  1747. "Set A3210M th fail value"),
  1748. OPT_WITH_ARG("--avalonlc3-th-init",
  1749. set_int_0_to_65535, opt_show_intval, &opt_avalonlc3_th_init,
  1750. "Set A3210M th init value"),
  1751. OPT_WITH_ARG("--avalonlc3-th-ms",
  1752. set_int_0_to_65535, opt_show_intval, &opt_avalonlc3_th_ms,
  1753. "Set A3210M th ms value"),
  1754. OPT_WITH_ARG("--avalonlc3-th-timeout",
  1755. opt_set_uintval, opt_show_uintval, &opt_avalonlc3_th_timeout,
  1756. "Set A3210M th timeout value"),
  1757. OPT_WITH_ARG("--avalonlc3-th-add",
  1758. set_int_0_to_1, opt_show_intval, &opt_avalonlc3_th_add,
  1759. "Set A3210M th add value"),
  1760. OPT_WITHOUT_ARG("--avalonlc3-iic-detect",
  1761. opt_set_bool, &opt_avalonlc3_iic_detect,
  1762. "Enable Avalonlc3 detect through iic controller"),
  1763. OPT_WITH_ARG("--avalonlc3-nonce-mask",
  1764. set_int_24_to_32, opt_show_intval, &opt_avalonlc3_nonce_mask,
  1765. "Set A3210M nonce mask, range 24-32."),
  1766. OPT_WITH_ARG("--avalonlc3-nonce-check",
  1767. set_int_0_to_1, opt_show_intval, &opt_avalonlc3_nonce_check,
  1768. "Set A3210M nonce check, range 0-1."),
  1769. OPT_WITH_ARG("--avalonlc3-roll-enable",
  1770. set_int_0_to_1, opt_show_intval, &opt_avalonlc3_roll_enable,
  1771. "Set A3210M roll enable, range 0-1."),
  1772. OPT_WITH_ARG("--avalonlc3-mux-l2h",
  1773. set_int_0_to_2, opt_show_intval, &opt_avalonlc3_mux_l2h,
  1774. "Set Avalonlc3 mux l2h, range 0-2."),
  1775. OPT_WITH_ARG("--avalonlc3-mux-h2l",
  1776. set_int_0_to_1, opt_show_intval, &opt_avalonlc3_mux_h2l,
  1777. "Set Avalonlc3 mux h2l, range 0-1."),
  1778. OPT_WITH_ARG("--avalonlc3-h2ltime0-spd",
  1779. set_int_0_to_255, opt_show_intval, &opt_avalonlc3_h2ltime0_spd,
  1780. "Set Avalonlc3 h2ltime0 spd, range 0-255."),
  1781. OPT_WITH_ARG("--avalonlc3-spdlow",
  1782. set_int_0_to_3, opt_show_intval, &opt_avalonlc3_spdlow,
  1783. "Set Avalonlc3 spdlow, range 0-3."),
  1784. OPT_WITH_ARG("--avalonlc3-spdhigh",
  1785. set_int_0_to_3, opt_show_intval, &opt_avalonlc3_spdhigh,
  1786. "Set Avalonlc3 spdhigh, range 0-3."),
  1787. OPT_WITH_ARG("--avalonlc3-tbase",
  1788. set_int_0_to_255, opt_show_intval, &opt_avalonlc3_tbase,
  1789. "Set Avalonlc3 tbase and use (0-8) bits, range 0-255."),
  1790. OPT_WITH_CBARG("--avalonlc3-cinfo-asic",
  1791. set_avalonlc3_asic_otp, NULL, &opt_set_avalonlc3_asic_otp,
  1792. "Set Avalonlc3 cinfo asic index, range:[0, 25], step: 1"),
  1793. OPT_WITH_ARG("--avalonlc3-pid-p",
  1794. set_int_0_to_9999, opt_show_intval, &opt_avalonlc3_pid_p,
  1795. "Set Avalonlc3 pid-p, range 0-9999."),
  1796. OPT_WITH_ARG("--avalonlc3-pid-i",
  1797. set_int_0_to_9999, opt_show_intval, &opt_avalonlc3_pid_i,
  1798. "Set Avalonlc3 pid-i, range 0-9999."),
  1799. OPT_WITH_ARG("--avalonlc3-pid-d",
  1800. set_int_0_to_9999, opt_show_intval, &opt_avalonlc3_pid_d,
  1801. "Set Avalonlc3 pid-d, range 0-9999."),
  1802. #endif
  1803. #ifdef USE_AVALON_MINER
  1804. OPT_WITH_CBARG("--avalonm-voltage",
  1805. set_avalonm_voltage, NULL, &opt_set_avalonm_voltage,
  1806. "Set Avalon miner core voltage, in millivolts, step: 125"),
  1807. OPT_WITH_CBARG("--avalonm-freq",
  1808. set_avalonm_freq, NULL, &opt_set_avalonm_freq,
  1809. "Set frequency for Avalon miner, 1 to 3 values, example: 275:250:200"),
  1810. OPT_WITH_ARG("--avalonm-ntime-offset",
  1811. opt_set_intval, opt_show_intval, &opt_avalonm_ntime_offset,
  1812. "Set Avalon miner ntime rolling max offset, range 0-4"),
  1813. OPT_WITH_ARG("--avalonm-spispeed",
  1814. opt_set_intval, opt_show_intval, &opt_avalonm_spispeed,
  1815. "Set spi speed for Avalon miner"),
  1816. OPT_WITHOUT_ARG("--avalonm-automatic-freq",
  1817. opt_set_bool, &opt_avalonm_autof,
  1818. "Automatic adjust frequency base on chip HW"),
  1819. #endif
  1820. #ifdef USE_BAB
  1821. OPT_WITH_ARG("--bab-options",
  1822. opt_set_charp, NULL, &opt_bab_options,
  1823. "Set bab options max:def:min:up:down:hz:delay:trf"),
  1824. #endif
  1825. OPT_WITHOUT_ARG("--balance",
  1826. set_balance, &pool_strategy,
  1827. "Change multipool strategy from failover to even share balance"),
  1828. OPT_WITH_ARG("--benchfile",
  1829. opt_set_charp, NULL, &opt_benchfile,
  1830. "Run cgminer in benchmark mode using a work file - produces no shares"),
  1831. OPT_WITHOUT_ARG("--benchfile-display",
  1832. opt_set_bool, &opt_benchfile_display,
  1833. "Display each benchfile nonce found"),
  1834. OPT_WITHOUT_ARG("--benchmark",
  1835. opt_set_bool, &opt_benchmark,
  1836. "Run cgminer in benchmark mode - produces no shares"),
  1837. #if defined(USE_BITFORCE)
  1838. OPT_WITHOUT_ARG("--bfl-range",
  1839. opt_set_bool, &opt_bfl_noncerange,
  1840. "Use nonce range on bitforce devices if supported"),
  1841. #endif
  1842. #ifdef USE_BFLSC
  1843. OPT_WITH_ARG("--bflsc-overheat",
  1844. set_int_0_to_200, opt_show_intval, &opt_bflsc_overheat,
  1845. "Set overheat temperature where BFLSC devices throttle, 0 to disable"),
  1846. #endif
  1847. #ifdef USE_AVALON
  1848. OPT_WITH_ARG("--bitburner-voltage",
  1849. opt_set_intval, NULL, &opt_bitburner_core_voltage,
  1850. "Set BitBurner (Avalon) core voltage, in millivolts"),
  1851. OPT_WITH_ARG("--bitburner-fury-voltage",
  1852. opt_set_intval, NULL, &opt_bitburner_fury_core_voltage,
  1853. "Set BitBurner Fury core voltage, in millivolts"),
  1854. OPT_WITH_ARG("--bitburner-fury-options",
  1855. opt_set_charp, NULL, &opt_bitburner_fury_options,
  1856. "Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq"),
  1857. #endif
  1858. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  1859. OPT_WITH_ARG("--bitmain-cutoff",
  1860. set_int_0_to_100, opt_show_intval, &opt_bitmain_overheat,
  1861. "Set bitmain overheat cut off temperature"),
  1862. OPT_WITH_CBARG("--bitmain-fan",
  1863. set_bitmain_fan, NULL, &opt_set_bitmain_fan,
  1864. "Set fanspeed percentage for bitmain, single value or range (default: 20-100)"),
  1865. OPT_WITH_CBARG("--bitmain-freq",
  1866. opt_set_charp, NULL, &opt_bitmain_freq,
  1867. "Set bitmain freq options timeout:freq:regdata"),
  1868. OPT_WITHOUT_ARG("--bitmain-hwerror",
  1869. opt_set_bool, &opt_bitmain_hwerror,
  1870. "Set bitmain device detect hardware error"),
  1871. OPT_WITH_ARG("--bitmain-options",
  1872. opt_set_charp, NULL, &opt_bitmain_options,
  1873. #ifdef USE_ANT_S1
  1874. "Set bitmain options baud:miners:asic:timeout:freq:regdata"
  1875. #else
  1876. "Set bitmain options baud:miners:asic:ignored..."
  1877. #endif
  1878. ),
  1879. OPT_WITH_ARG("--bitmain-temp",
  1880. set_int_0_to_100, opt_show_intval, &opt_bitmain_temp,
  1881. "Set bitmain target temperature"),
  1882. OPT_WITH_ARG("--bitmain-workdelay",
  1883. set_int_0_to_100, opt_show_intval, &opt_bitmain_workdelay,
  1884. "Set bitmain work delay (ms) 0-100"),
  1885. // Ignored
  1886. OPT_WITHOUT_ARG("--bitmain-auto",
  1887. opt_set_bool, &opt_bitmain_auto,
  1888. opt_hidden),
  1889. OPT_WITHOUT_ARG("--bitmain-nobeeper",
  1890. opt_set_bool, &opt_bitmain_nobeeper,
  1891. opt_hidden),
  1892. OPT_WITHOUT_ARG("--bitmain-notempoverctrl",
  1893. opt_set_bool, &opt_bitmain_notempoverctrl,
  1894. opt_hidden),
  1895. #ifdef USE_ANT_S1
  1896. // S1 has no effect
  1897. OPT_WITHOUT_ARG("--bitmainbeeper",
  1898. opt_set_bool, &opt_bitmain_beeper,
  1899. opt_hidden),
  1900. OPT_WITHOUT_ARG("--bitmaintempoverctrl",
  1901. opt_set_bool, &opt_bitmain_tempoverctrl,
  1902. opt_hidden),
  1903. OPT_WITHOUT_ARG("--bitmain-homemode",
  1904. opt_set_bool, &opt_bitmain_homemode,
  1905. opt_hidden),
  1906. #endif
  1907. #endif
  1908. #ifdef USE_ANT_S2
  1909. OPT_WITH_ARG("--bitmain-voltage",
  1910. opt_set_charp, NULL, &opt_bitmain_voltage,
  1911. "Set bitmain voltage (default: "BITMAIN_VOLTAGE_DEF")"),
  1912. #ifndef USE_ANT_S3
  1913. OPT_WITH_ARG("--bitmain-dev",
  1914. opt_set_charp, NULL, &opt_bitmain_dev,
  1915. "Set bitmain device"),
  1916. #endif
  1917. OPT_WITHOUT_ARG("--bitmainbeeper",
  1918. opt_set_bool, &opt_bitmain_beeper,
  1919. "Set bitmain beeper ringing"),
  1920. OPT_WITHOUT_ARG("--bitmain-checkall",
  1921. opt_set_bool, &opt_bitmain_checkall,
  1922. opt_hidden),
  1923. OPT_WITHOUT_ARG("--bitmain-checkn2diff",
  1924. opt_set_bool, &opt_bitmain_checkn2diff,
  1925. opt_hidden),
  1926. OPT_WITHOUT_ARG("--bitmaintempoverctrl",
  1927. opt_set_bool, &opt_bitmain_tempoverctrl,
  1928. "Set bitmain stop runing when temprerature is over 80 degree Celsius"),
  1929. OPT_WITHOUT_ARG("--bitmain-homemode",
  1930. opt_set_bool, &opt_bitmain_homemode,
  1931. "Set bitmain miner to home mode"),
  1932. #endif
  1933. #ifdef USE_BITMINE_A1
  1934. OPT_WITH_ARG("--bitmine-a1-options",
  1935. opt_set_charp, NULL, &opt_bitmine_a1_options,
  1936. "Bitmine A1 options ref_clk_khz:sys_clk_khz:spi_clk_khz:override_chip_num"),
  1937. #endif
  1938. OPT_WITHOUT_ARG("--block-check",
  1939. opt_set_bool, &opt_blockcheck,
  1940. "Run a block diff check of the binary then exit"),
  1941. #ifdef USE_BITFURY
  1942. OPT_WITH_ARG("--bxf-bits",
  1943. set_int_32_to_63, opt_show_intval, &opt_bxf_bits,
  1944. "Set max BXF/HXF bits for overclocking"),
  1945. OPT_WITH_ARG("--bxf-debug",
  1946. set_int_0_to_4, opt_show_intval, &opt_bxf_debug,
  1947. "BXF: Debug all USB I/O, > is to the board(s), < is from the board(s)"),
  1948. OPT_WITH_ARG("--bxf-temp-target",
  1949. set_int_0_to_200, opt_show_intval, &opt_bxf_temp_target,
  1950. "Set target temperature for BXF/HXF devices"),
  1951. OPT_WITH_ARG("--bxm-bits",
  1952. set_int_0_to_100, opt_show_intval, &opt_bxm_bits,
  1953. "Set BXM bits for overclocking"),
  1954. #endif
  1955. #ifdef USE_BITFURY16
  1956. OPT_WITHOUT_ARG("--bf16-set-clock",
  1957. opt_set_bool, &opt_bf16_set_clock,
  1958. "Set clock to all chips"),
  1959. OPT_WITH_ARG("--bf16-test-chip",
  1960. opt_set_charp, NULL, &opt_bf16_test_chip,
  1961. "Test BF16 chip communication: [board_id:bcm250_id:chip_id]"),
  1962. OPT_WITH_ARG("--bf16-clock",
  1963. opt_set_charp, NULL, &opt_bf16_clock,
  1964. "BF16 chips clock value"),
  1965. OPT_WITH_ARG("--bf16-renonce-clock",
  1966. opt_set_charp, NULL, &opt_bf16_renonce_clock,
  1967. "BF16 renonce chip clock value"),
  1968. OPT_WITHOUT_ARG("--bf16-enable-stats",
  1969. opt_set_bool, &opt_bf16_stats_enabled,
  1970. "Enable statistics thread"),
  1971. OPT_WITHOUT_ARG("--bf16-disable-power-management",
  1972. opt_set_bool, &opt_bf16_power_management_disabled,
  1973. "Disable automatic power management"),
  1974. OPT_WITH_ARG("--bf16-renonce",
  1975. set_int_0_to_2, NULL, &opt_bf16_renonce,
  1976. "Renonce functionality: 0 - disabled, 1 - one chip, 2 - chip per board"),
  1977. #ifdef MINER_X5
  1978. OPT_WITHOUT_ARG("--bf16-manual-pid-enable",
  1979. opt_set_bool, &opt_bf16_manual_pid_enabled,
  1980. "Enable manual PID regulator"),
  1981. #endif
  1982. #ifdef MINER_X6
  1983. OPT_WITHOUT_ARG("--bf16-manual-pid-disable",
  1984. opt_set_bool, &opt_bf16_manual_pid_disabled,
  1985. "Disable manual PID regulator"),
  1986. #endif
  1987. OPT_WITH_ARG("--bf16-fan-speed",
  1988. set_int_0_to_100, NULL, &opt_bf16_fan_speed,
  1989. "Set fan speed in '%' range (0 - 100)"),
  1990. OPT_WITH_ARG("--bf16-target-temp",
  1991. set_int_0_to_100, NULL, &opt_bf16_target_temp,
  1992. "Set control board target temperature range (0 - 100)"),
  1993. OPT_WITH_ARG("--bf16-alarm-temp",
  1994. set_int_0_to_100, NULL, &opt_bf16_alarm_temp,
  1995. "Set control board alarm temperature range (0 - 100)"),
  1996. #endif
  1997. #ifdef USE_BITMAIN_SOC
  1998. OPT_WITH_ARG("--version-file",
  1999. set_version_path, NULL, opt_hidden,
  2000. "Set miner version file"),
  2001. OPT_WITHOUT_ARG("--bitmain-fan-ctrl",
  2002. opt_set_bool, &opt_bitmain_fan_ctrl,
  2003. "Enable bitmain miner fan controlling"),
  2004. OPT_WITH_ARG("--bitmain-fan-pwm",
  2005. set_int_0_to_100, opt_show_intval, &opt_bitmain_fan_pwm,
  2006. "Set bitmain fan pwm percentage 0~100"),
  2007. OPT_WITH_ARG("--bitmain-freq",
  2008. set_int_0_to_9999,opt_show_intval, &opt_bitmain_soc_freq,
  2009. "Set frequency"),
  2010. OPT_WITH_ARG("--bitmain-voltage",
  2011. set_int_0_to_9999,opt_show_intval, &opt_bitmain_soc_voltage,
  2012. "Set voltage"),
  2013. OPT_WITHOUT_ARG("--fixed-freq",
  2014. opt_set_bool, &opt_fixed_freq,
  2015. "Set bitmain miner use fixed freq"),
  2016. OPT_WITHOUT_ARG("--no-pre-heat",
  2017. opt_set_false, &opt_pre_heat,
  2018. "Set bitmain miner doesn't pre heat"),
  2019. OPT_WITH_ARG("--multi-version",
  2020. opt_set_intval, NULL, &opt_multi_version,
  2021. "Multi version mining!"),
  2022. #endif
  2023. #ifdef USE_BLOCKERUPTER
  2024. OPT_WITH_ARG("--bet-clk",
  2025. opt_set_intval, opt_show_intval, &opt_bet_clk,
  2026. "Set Block Erupter clock"),
  2027. #endif
  2028. #ifdef USE_GEKKO
  2029. OPT_WITH_ARG("--gekko-serial",
  2030. opt_set_charp, NULL, &opt_gekko_serial,
  2031. "Detect GekkoScience Device by Serial Number"),
  2032. OPT_WITHOUT_ARG("--gekko-compac-detect",
  2033. opt_set_bool, &opt_gekko_gsc_detect,
  2034. "Detect GekkoScience Compac BM1384"),
  2035. OPT_WITHOUT_ARG("--gekko-2pac-detect",
  2036. opt_set_bool, &opt_gekko_gsd_detect,
  2037. "Detect GekkoScience 2Pac BM1384"),
  2038. OPT_WITHOUT_ARG("--gekko-terminus-detect",
  2039. opt_set_bool, &opt_gekko_gse_detect,
  2040. "Detect GekkoScience Terminus BM1384"),
  2041. OPT_WITHOUT_ARG("--gekko-newpac-detect",
  2042. opt_set_bool, &opt_gekko_gsh_detect,
  2043. "Detect GekkoScience NewPac BM1387"),
  2044. OPT_WITHOUT_ARG("--gekko-r606-detect",
  2045. opt_set_bool, &opt_gekko_gsi_detect,
  2046. "Detect GekkoScience Terminus BM1387"),
  2047. OPT_WITHOUT_ARG("--gekko-compacf-detect",
  2048. opt_set_bool, &opt_gekko_gsf_detect,
  2049. "Detect GekkoScience CompacF BM1397"),
  2050. OPT_WITHOUT_ARG("--gekko-r909-detect",
  2051. opt_set_bool, &opt_gekko_r909_detect,
  2052. "Detect GekkoScience Terminus R909 BM1397"),
  2053. OPT_WITHOUT_ARG("--gekko-noboost",
  2054. opt_set_bool, &opt_gekko_noboost,
  2055. "Disable GekkoScience NewPac/R606/CompacF AsicBoost"),
  2056. OPT_WITHOUT_ARG("--gekko-lowboost",
  2057. opt_set_bool, &opt_gekko_lowboost,
  2058. "GekkoScience NewPac/R606 AsicBoost - 2 midstate"),
  2059. OPT_WITH_ARG("--gekko-terminus-freq",
  2060. set_float_0_to_500, opt_show_floatval, &opt_gekko_gse_freq,
  2061. "Set GekkoScience Terminus BM1384 frequency in MHz, range 6.25-500"),
  2062. OPT_WITH_ARG("--gekko-2pac-freq",
  2063. set_float_0_to_500, opt_show_floatval, &opt_gekko_gsd_freq,
  2064. "Set GekkoScience 2Pac BM1384 frequency in MHz, range 6.25-500"),
  2065. OPT_WITH_ARG("--gekko-compac-freq",
  2066. set_float_0_to_500, opt_show_floatval, &opt_gekko_gsc_freq,
  2067. "Set GekkoScience Compac BM1384 frequency in MHz, range 6.25-500"),
  2068. OPT_WITH_ARG("--gekko-tune-down",
  2069. set_float_0_to_500, opt_show_floatval, &opt_gekko_tune_down,
  2070. "Set GekkoScience miner minimum hash quality, range 0-100"),
  2071. OPT_WITH_ARG("--gekko-tune-up",
  2072. set_float_0_to_500, opt_show_floatval, &opt_gekko_tune_up,
  2073. "Set GekkoScience miner ramping hash threshold, rante 0-99"),
  2074. OPT_WITH_ARG("--gekko-wait-factor",
  2075. set_float_0_to_500, opt_show_floatval, &opt_gekko_wait_factor,
  2076. "Set GekkoScience miner task send wait factor, range 0.01-2.00"),
  2077. OPT_WITH_ARG("--gekko-bauddiv",
  2078. set_int_0_to_9999, opt_show_intval, &opt_gekko_bauddiv,
  2079. "Set GekkoScience BM1387 baud divider {0: auto, 1: 1.5M, 7: 375K, 13: 214K, 25: 115K}"),
  2080. OPT_WITH_ARG("--gekko-newpac-freq",
  2081. set_int_0_to_9999, opt_show_intval, &opt_gekko_gsh_freq,
  2082. "Set GekkoScience NewPac BM1387 frequency in MHz, range 50-900"),
  2083. OPT_WITH_ARG("--gekko-r606-freq",
  2084. set_int_0_to_9999, opt_show_intval, &opt_gekko_gsi_freq,
  2085. "Set GekkoScience Terminus R606 frequency in MHz, range 50-900"),
  2086. OPT_WITH_ARG("--gekko-compacf-freq",
  2087. set_int_0_to_9999, opt_show_intval, &opt_gekko_gsf_freq,
  2088. "Set GekkoScience CompacF BM1397 frequency in MHz, range 100-800"),
  2089. OPT_WITH_ARG("--gekko-r909-freq",
  2090. set_int_0_to_9999, opt_show_intval, &opt_gekko_r909_freq,
  2091. "Set GekkoScience Terminus R909 BM1397 frequency in MHz, range 100-800"),
  2092. OPT_WITH_ARG("--gekko-start-freq",
  2093. set_int_0_to_9999, opt_show_intval, &opt_gekko_start_freq,
  2094. "Ramp start frequency MHz 25-500"),
  2095. OPT_WITH_ARG("--gekko-step-freq",
  2096. set_float_0_to_500, opt_show_intval, &opt_gekko_step_freq,
  2097. "Ramp frequency step MHz 1-100"),
  2098. OPT_WITH_ARG("--gekko-step-delay",
  2099. set_int_0_to_9999, opt_show_intval, &opt_gekko_step_delay,
  2100. "Ramp step interval range 1-600"),
  2101. OPT_WITHOUT_ARG("--gekko-mine2",
  2102. opt_set_bool, &opt_gekko_mine2, opt_hidden), // ignored
  2103. OPT_WITH_ARG("--gekko-tune2",
  2104. set_int_0_to_9999, opt_show_intval, &opt_gekko_tune2,
  2105. "Tune up mine2 mins 30-9999, default 0=never"),
  2106. #endif
  2107. #ifdef HAVE_LIBCURL
  2108. OPT_WITH_ARG("--btc-address",
  2109. opt_set_charp, NULL, &opt_btc_address,
  2110. "Set bitcoin target address when solo mining to bitcoind (mandatory)"),
  2111. OPT_WITH_ARG("--btc-sig",
  2112. opt_set_charp, NULL, &opt_btc_sig,
  2113. "Set signature to add to coinbase when solo mining (optional)"),
  2114. #endif
  2115. #ifdef HAVE_CURSES
  2116. OPT_WITHOUT_ARG("--compact",
  2117. opt_set_bool, &opt_compact,
  2118. "Use compact display without per device statistics"),
  2119. #endif
  2120. #ifdef USE_COINTERRA
  2121. OPT_WITH_ARG("--cta-load",
  2122. set_int_0_to_255, opt_show_intval, &opt_cta_load,
  2123. "Set load for CTA devices, 0-255 range"),
  2124. OPT_WITH_ARG("--ps-load",
  2125. set_int_0_to_100, opt_show_intval, &opt_ps_load,
  2126. "Set power supply load for CTA devices, 0-100 range"),
  2127. #endif
  2128. OPT_WITHOUT_ARG("--debug|-D",
  2129. enable_debug, &opt_debug,
  2130. "Enable debug output"),
  2131. #ifdef HAVE_CURSES
  2132. OPT_WITHOUT_ARG("--decode",
  2133. opt_set_bool, &opt_decode,
  2134. "Decode 2nd pool stratum coinbase transactions (1st must be bitcoind) and exit"),
  2135. #endif
  2136. OPT_WITHOUT_ARG("--disable-rejecting",
  2137. opt_set_bool, &opt_disable_pool,
  2138. "Automatically disable pools that continually reject shares"),
  2139. #ifdef USE_DRAGONMINT_T1
  2140. OPT_WITH_ARG("--dragonmint-t1-options",
  2141. opt_set_charp, NULL, &opt_dragonmint_t1_options,
  2142. "Dragonmint T1 options ref_clk_khz:sys_clk_khz:spi_clk_khz:override_chip_num"),
  2143. OPT_WITHOUT_ARG("--T1efficient",
  2144. opt_set_bool, &opt_T1_efficient,
  2145. "Tune Dragonmint T1 per chain voltage and frequency for optimal efficiency"),
  2146. OPT_WITHOUT_ARG("--T1factory",
  2147. opt_set_invbool, &opt_T1auto,
  2148. opt_hidden),
  2149. OPT_WITHOUT_ARG("--T1noauto",
  2150. opt_set_invbool, &opt_T1auto,
  2151. "Disable Dragonmint T1 per chain auto voltage and frequency tuning"),
  2152. OPT_WITHOUT_ARG("--T1performance",
  2153. opt_set_bool, &opt_T1_performance,
  2154. "Tune Dragonmint T1 per chain voltage and frequency for maximum performance"),
  2155. OPT_WITH_ARG("--T1fantarget",
  2156. opt_set_intval, opt_show_intval, &opt_T1_target,
  2157. "Throttle T1 frequency to keep fan less than target fan speed"),
  2158. OPT_WITH_ARG("--T1Pll1",
  2159. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[0],
  2160. "Set PLL Clock 1 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2161. OPT_WITH_ARG("--T1Pll2",
  2162. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[1],
  2163. "Set PLL Clock 2 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2164. OPT_WITH_ARG("--T1Pll3",
  2165. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[2],
  2166. "Set PLL Clock 3 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2167. OPT_WITH_ARG("--T1Pll4",
  2168. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[3],
  2169. "Set PLL Clock 4 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2170. OPT_WITH_ARG("--T1Pll5",
  2171. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[4],
  2172. "Set PLL Clock 5 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2173. OPT_WITH_ARG("--T1Pll6",
  2174. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[5],
  2175. "Set PLL Clock 6 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2176. OPT_WITH_ARG("--T1Pll7",
  2177. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[6],
  2178. "Set PLL Clock 7 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2179. OPT_WITH_ARG("--T1Pll8",
  2180. set_int_0_to_9999, opt_show_intval, &opt_T1Pll[7],
  2181. "Set PLL Clock 8 in Dragonmint T1 broad 1 chip (-1: 1000MHz, >0:Lookup PLL table)"),
  2182. OPT_WITH_ARG("--T1Volt1",
  2183. set_int_voltage, opt_show_intval, &opt_T1Vol[0],
  2184. "Dragonmint T1 set voltage 1 - VID overrides if set (390-425)"),
  2185. OPT_WITH_ARG("--T1Volt2",
  2186. set_int_voltage, opt_show_intval, &opt_T1Vol[1],
  2187. "Dragonmint T1 set voltage 2 - VID overrides if set (390-425)"),
  2188. OPT_WITH_ARG("--T1Volt3",
  2189. set_int_voltage, opt_show_intval, &opt_T1Vol[2],
  2190. "Dragonmint T1 set voltage 3 - VID overrides if set (390-425)"),
  2191. OPT_WITH_ARG("--T1Volt4",
  2192. set_int_voltage, opt_show_intval, &opt_T1Vol[3],
  2193. "Dragonmint T1 set voltage 4 - VID overrides if set (390-425)"),
  2194. OPT_WITH_ARG("--T1Volt5",
  2195. set_int_voltage, opt_show_intval, &opt_T1Vol[4],
  2196. "Dragonmint T1 set voltage 5 - VID overrides if set (390-425)"),
  2197. OPT_WITH_ARG("--T1Volt6",
  2198. set_int_voltage, opt_show_intval, &opt_T1Vol[5],
  2199. "Dragonmint T1 set voltage 6 - VID overrides if set (390-425)"),
  2200. OPT_WITH_ARG("--T1Volt7",
  2201. set_int_voltage, opt_show_intval, &opt_T1Vol[6],
  2202. "Dragonmint T1 set voltage 7 - VID overrides if set (390-425)"),
  2203. OPT_WITH_ARG("--T1Volt8",
  2204. set_int_voltage, opt_show_intval, &opt_T1Vol[7],
  2205. "Dragonmint T1 set voltage 8 - VID overrides if set (390-425)"),
  2206. OPT_WITH_ARG("--T1VID1",
  2207. set_int_1_to_31, opt_show_intval, &opt_T1VID[0],
  2208. "Dragonmint T1 set VID 1 in noauto - Overrides voltage if set (1-31)"),
  2209. OPT_WITH_ARG("--T1VID2",
  2210. set_int_1_to_31, opt_show_intval, &opt_T1VID[1],
  2211. "Dragonmint T1 set VID 2 in noauto - Overrides voltage if set (1-31)"),
  2212. OPT_WITH_ARG("--T1VID3",
  2213. set_int_1_to_31, opt_show_intval, &opt_T1VID[2],
  2214. "Dragonmint T1 set VID 3 in noauto - Overrides voltage if set (1-31)"),
  2215. OPT_WITH_ARG("--T1VID4",
  2216. set_int_1_to_31, opt_show_intval, &opt_T1VID[3],
  2217. "Dragonmint T1 set VID 4 in noauto - Overrides voltage if set (1-31)"),
  2218. OPT_WITH_ARG("--T1VID5",
  2219. set_int_1_to_31, opt_show_intval, &opt_T1VID[4],
  2220. "Dragonmint T1 set VID 5 in noauto - Overrides voltage if set (1-31)"),
  2221. OPT_WITH_ARG("--T1VID6",
  2222. set_int_1_to_31, opt_show_intval, &opt_T1VID[5],
  2223. "Dragonmint T1 set VID 6 in noauto - Overrides voltage if set (1-31)"),
  2224. OPT_WITH_ARG("--T1VID7",
  2225. set_int_1_to_31, opt_show_intval, &opt_T1VID[6],
  2226. "Dragonmint T1 set VID 7 in noauto - Overrides voltage if set (1-31)"),
  2227. OPT_WITH_ARG("--T1VID8",
  2228. set_int_1_to_31, opt_show_intval, &opt_T1VID[7],
  2229. "Dragonmint T1 set VID 8 in noauto - Overrides voltage if set (1-31)"),
  2230. #endif
  2231. #ifdef USE_DRILLBIT
  2232. OPT_WITH_ARG("--drillbit-options",
  2233. opt_set_charp, NULL, &opt_drillbit_options,
  2234. "Set drillbit options <int|ext>:clock[:clock_divider][:voltage]"),
  2235. OPT_WITH_ARG("--drillbit-auto",
  2236. opt_set_charp, NULL, &opt_drillbit_auto,
  2237. "Enable drillbit automatic tuning <every>:[<gooderr>:<baderr>:<maxerr>]"),
  2238. #endif
  2239. OPT_WITH_ARG("--expiry|-E",
  2240. set_null, NULL, &opt_set_null,
  2241. opt_hidden),
  2242. #ifdef USE_XTRANONCE
  2243. OPT_WITHOUT_ARG("--extranonce-subscribe",
  2244. set_extranonce_subscribe, NULL,
  2245. "Enable 'extranonce' stratum subscribe"),
  2246. #endif
  2247. OPT_WITHOUT_ARG("--failover-only",
  2248. set_null, &opt_set_null,
  2249. opt_hidden),
  2250. OPT_WITH_ARG("--fallback-time",
  2251. opt_set_intval, opt_show_intval, &opt_pool_fallback,
  2252. "Set time in seconds to fall back to a higher priority pool after period of instability"),
  2253. OPT_WITHOUT_ARG("--fix-protocol",
  2254. opt_set_bool, &opt_fix_protocol,
  2255. "Do not redirect to stratum protocol from GBT"),
  2256. #ifdef USE_HASHFAST
  2257. OPT_WITHOUT_ARG("--hfa-dfu-boot",
  2258. opt_set_bool, &opt_hfa_dfu_boot,
  2259. opt_hidden),
  2260. OPT_WITH_ARG("--hfa-hash-clock",
  2261. set_int_0_to_9999, opt_show_intval, &opt_hfa_hash_clock,
  2262. "Set hashfast clock speed"),
  2263. OPT_WITH_ARG("--hfa-fail-drop",
  2264. set_int_0_to_100, opt_show_intval, &opt_hfa_fail_drop,
  2265. "Set how many MHz to drop clockspeed each failure on an overlocked hashfast device"),
  2266. OPT_WITH_CBARG("--hfa-fan",
  2267. set_hfa_fan, NULL, &opt_set_hfa_fan,
  2268. "Set fanspeed percentage for hashfast, single value or range (default: 10-85)"),
  2269. OPT_WITH_ARG("--hfa-name",
  2270. opt_set_charp, NULL, &opt_hfa_name,
  2271. "Set a unique name for a single hashfast device specified with --usb or the first device found"),
  2272. OPT_WITHOUT_ARG("--hfa-noshed",
  2273. opt_set_bool, &opt_hfa_noshed,
  2274. "Disable hashfast dynamic core disabling feature"),
  2275. OPT_WITH_ARG("--hfa-ntime-roll",
  2276. opt_set_intval, NULL, &opt_hfa_ntime_roll,
  2277. opt_hidden),
  2278. OPT_WITH_ARG("--hfa-options",
  2279. opt_set_charp, NULL, &opt_hfa_options,
  2280. "Set hashfast options name:clock (comma separated)"),
  2281. OPT_WITHOUT_ARG("--hfa-pll-bypass",
  2282. opt_set_bool, &opt_hfa_pll_bypass,
  2283. opt_hidden),
  2284. OPT_WITH_ARG("--hfa-temp-overheat",
  2285. set_int_0_to_200, opt_show_intval, &opt_hfa_overheat,
  2286. "Set the hashfast overheat throttling temperature"),
  2287. OPT_WITH_ARG("--hfa-temp-target",
  2288. set_int_0_to_200, opt_show_intval, &opt_hfa_target,
  2289. "Set the hashfast target temperature (0 to disable)"),
  2290. #endif
  2291. #ifdef USE_HASHRATIO
  2292. OPT_WITH_CBARG("--hro-freq",
  2293. set_hashratio_freq, NULL, &opt_hashratio_freq,
  2294. "Set the hashratio clock frequency"),
  2295. #endif
  2296. OPT_WITH_ARG("--hotplug",
  2297. set_int_0_to_9999, NULL, &hotplug_time,
  2298. #ifdef USE_USBUTILS
  2299. "Seconds between hotplug checks (0 means never check)"
  2300. #else
  2301. opt_hidden
  2302. #endif
  2303. ),
  2304. #ifdef USE_ICARUS
  2305. OPT_WITH_ARG("--icarus-options",
  2306. opt_set_charp, NULL, &opt_icarus_options,
  2307. opt_hidden),
  2308. OPT_WITH_ARG("--icarus-timing",
  2309. opt_set_charp, NULL, &opt_icarus_timing,
  2310. opt_hidden),
  2311. #endif
  2312. #if defined(HAVE_MODMINER)
  2313. OPT_WITH_ARG("--kernel-path|-K",
  2314. opt_set_charp, opt_show_charp, &opt_kernel_path,
  2315. "Specify a path to where bitstream files are"),
  2316. #endif
  2317. #ifdef USE_KLONDIKE
  2318. OPT_WITH_ARG("--klondike-options",
  2319. opt_set_charp, NULL, &opt_klondike_options,
  2320. "Set klondike options clock:temptarget"),
  2321. #endif
  2322. OPT_WITHOUT_ARG("--load-balance",
  2323. set_loadbalance, &pool_strategy,
  2324. "Change multipool strategy from failover to quota based balance"),
  2325. OPT_WITH_ARG("--log|-l",
  2326. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  2327. "Interval in seconds between log output"),
  2328. OPT_WITHOUT_ARG("--lowmem",
  2329. opt_set_bool, &opt_lowmem,
  2330. "Minimise caching of shares for low memory applications"),
  2331. OPT_WITHOUT_ARG("--mac-yield",
  2332. opt_set_bool, &opt_mac_yield,
  2333. "Allow yield on old macs (default dont)"),
  2334. #ifdef USE_MINION
  2335. OPT_WITH_ARG("--minion-chipreport",
  2336. set_int_0_to_100, opt_show_intval, &opt_minion_chipreport,
  2337. "Seconds to report chip 5min hashrate, range 0-100 (default: 0=disabled)"),
  2338. OPT_WITH_ARG("--minion-cores",
  2339. opt_set_charp, NULL, &opt_minion_cores,
  2340. opt_hidden),
  2341. OPT_WITHOUT_ARG("--minion-extra",
  2342. opt_set_bool, &opt_minion_extra,
  2343. opt_hidden),
  2344. OPT_WITH_ARG("--minion-freq",
  2345. opt_set_charp, NULL, &opt_minion_freq,
  2346. "Set minion chip frequencies in MHz, single value or comma list, range 100-1400 (default: 1200)"),
  2347. OPT_WITH_ARG("--minion-freqchange",
  2348. set_int_0_to_9999, opt_show_intval, &opt_minion_freqchange,
  2349. "Millisecond total time to do frequency changes (default: 1000)"),
  2350. OPT_WITH_ARG("--minion-freqpercent",
  2351. set_int_0_to_100, opt_show_intval, &opt_minion_freqpercent,
  2352. "Percentage to use when starting up a chip (default: 70%)"),
  2353. OPT_WITHOUT_ARG("--minion-idlecount",
  2354. opt_set_bool, &opt_minion_idlecount,
  2355. "Report when IdleCount is >0 or changes"),
  2356. OPT_WITH_ARG("--minion-ledcount",
  2357. set_int_0_to_100, opt_show_intval, &opt_minion_ledcount,
  2358. "Turn off led when more than this many chips below the ledlimit (default: 0)"),
  2359. OPT_WITH_ARG("--minion-ledlimit",
  2360. set_int_0_to_200, opt_show_intval, &opt_minion_ledlimit,
  2361. "Turn off led when chips GHs are below this (default: 90)"),
  2362. OPT_WITHOUT_ARG("--minion-noautofreq",
  2363. opt_set_bool, &opt_minion_noautofreq,
  2364. "Disable automatic frequency adjustment"),
  2365. OPT_WITHOUT_ARG("--minion-overheat",
  2366. opt_set_bool, &opt_minion_overheat,
  2367. "Enable directly halting any chip when the status exceeds 100C"),
  2368. OPT_WITH_ARG("--minion-spidelay",
  2369. set_int_0_to_9999, opt_show_intval, &opt_minion_spidelay,
  2370. "Add a delay in microseconds after each SPI I/O"),
  2371. OPT_WITH_ARG("--minion-spireset",
  2372. opt_set_charp, NULL, &opt_minion_spireset,
  2373. "SPI regular reset: iNNN for I/O count or sNNN for seconds - 0 means none"),
  2374. OPT_WITH_ARG("--minion-spisleep",
  2375. set_int_0_to_9999, opt_show_intval, &opt_minion_spisleep,
  2376. "Sleep time in milliseconds when doing an SPI reset"),
  2377. OPT_WITH_ARG("--minion-spiusec",
  2378. set_int_0_to_9999, NULL, &opt_minion_spiusec,
  2379. opt_hidden),
  2380. OPT_WITH_ARG("--minion-temp",
  2381. opt_set_charp, NULL, &opt_minion_temp,
  2382. "Set minion chip temperature threshold, single value or comma list, range 120-160 (default: 135C)"),
  2383. #endif
  2384. #if defined(unix) || defined(__APPLE__)
  2385. OPT_WITH_ARG("--monitor|-m",
  2386. opt_set_charp, NULL, &opt_stderr_cmd,
  2387. "Use custom pipe cmd for output messages"),
  2388. #endif // defined(unix)
  2389. #ifdef USE_BITFURY
  2390. OPT_WITH_ARG("--nfu-bits",
  2391. set_int_32_to_63, opt_show_intval, &opt_nfu_bits,
  2392. "Set nanofury bits for overclocking, range 32-63"),
  2393. #endif
  2394. OPT_WITHOUT_ARG("--net-delay",
  2395. opt_set_bool, &opt_delaynet,
  2396. "Impose small delays in networking to not overload slow routers"),
  2397. OPT_WITHOUT_ARG("--no-pool-disable",
  2398. opt_set_invbool, &opt_disable_pool,
  2399. opt_hidden),
  2400. OPT_WITHOUT_ARG("--no-submit-stale",
  2401. opt_set_invbool, &opt_submit_stale,
  2402. "Don't submit shares if they are detected as stale"),
  2403. #ifdef USE_BITFURY
  2404. OPT_WITH_ARG("--osm-led-mode",
  2405. set_int_0_to_4, opt_show_intval, &opt_osm_led_mode,
  2406. "Set LED mode for OneStringMiner devices"),
  2407. #endif
  2408. OPT_WITH_ARG("--pass|-p",
  2409. set_pass, NULL, &opt_set_null,
  2410. "Password for bitcoin JSON-RPC server"),
  2411. OPT_WITHOUT_ARG("--per-device-stats",
  2412. opt_set_bool, &want_per_device_stats,
  2413. "Force verbose mode and output per-device statistics"),
  2414. OPT_WITH_ARG("--pools",
  2415. opt_set_bool, NULL, &opt_set_null, opt_hidden),
  2416. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2417. opt_set_bool, &opt_protocol,
  2418. "Verbose dump of protocol-level activities"),
  2419. OPT_WITH_ARG("--queue|-Q",
  2420. set_null, NULL, &opt_set_null,
  2421. opt_hidden),
  2422. OPT_WITHOUT_ARG("--quiet|-q",
  2423. opt_set_bool, &opt_quiet,
  2424. "Disable logging output, display status and errors"),
  2425. OPT_WITH_ARG("--quota|-U",
  2426. set_quota, NULL, &opt_set_null,
  2427. "quota;URL combination for server with load-balance strategy quotas"),
  2428. OPT_WITHOUT_ARG("--real-quiet",
  2429. opt_set_bool, &opt_realquiet,
  2430. "Disable all output"),
  2431. OPT_WITH_ARG("--retries",
  2432. set_null, NULL, &opt_set_null,
  2433. opt_hidden),
  2434. OPT_WITH_ARG("--retry-pause",
  2435. set_null, NULL, &opt_set_null,
  2436. opt_hidden),
  2437. #ifdef USE_ICARUS
  2438. OPT_WITH_ARG("--rock-freq",
  2439. set_float_125_to_500, &opt_show_floatval, &opt_rock_freq,
  2440. "Set RockMiner frequency in MHz, range 125-500"),
  2441. #endif
  2442. OPT_WITH_ARG("--rotate",
  2443. set_rotate, NULL, &opt_set_null,
  2444. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2445. OPT_WITHOUT_ARG("--round-robin",
  2446. set_rr, &pool_strategy,
  2447. "Change multipool strategy from failover to round robin on failure"),
  2448. #ifdef USE_FPGA_SERIAL
  2449. OPT_WITH_CBARG("--scan-serial|-S",
  2450. add_serial, NULL, &opt_add_serial,
  2451. "Serial port to probe for Serial FPGA Mining device"),
  2452. #endif
  2453. OPT_WITH_ARG("--scan-time|-s",
  2454. set_null, NULL, &opt_set_null,
  2455. opt_hidden),
  2456. OPT_WITH_CBARG("--sched-start",
  2457. set_sched_start, NULL, &opt_set_sched_start,
  2458. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2459. OPT_WITH_CBARG("--sched-stop",
  2460. set_sched_stop, NULL, &opt_set_sched_stop,
  2461. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2462. OPT_WITH_CBARG("--sharelog",
  2463. set_sharelog, NULL, &opt_set_sharelog,
  2464. "Append share log to file"),
  2465. OPT_WITH_ARG("--shares",
  2466. opt_set_intval, NULL, &opt_shares,
  2467. "Quit after mining N shares (default: unlimited)"),
  2468. OPT_WITH_ARG("--socks-proxy",
  2469. opt_set_charp, NULL, &opt_socks_proxy,
  2470. "Set socks4 proxy (host:port)"),
  2471. OPT_WITH_ARG("--suggest-diff",
  2472. opt_set_intval, NULL, &opt_suggest_diff,
  2473. "Suggest miner difficulty for pool to user (default: none)"),
  2474. #ifdef HAVE_SYSLOG_H
  2475. OPT_WITHOUT_ARG("--syslog",
  2476. opt_set_bool, &use_syslog,
  2477. "Use system log for output messages (default: standard error)"),
  2478. #endif
  2479. #if defined(USE_BITFORCE) || defined(USE_MODMINER) || defined(USE_BFLSC)
  2480. OPT_WITH_CBARG("--temp-cutoff",
  2481. set_temp_cutoff, opt_show_intval, &opt_set_temp_cutoff,
  2482. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  2483. #endif
  2484. OPT_WITHOUT_ARG("--text-only|-T",
  2485. opt_set_invbool, &use_curses,
  2486. #ifdef HAVE_CURSES
  2487. "Disable ncurses formatted screen output"
  2488. #else
  2489. opt_hidden
  2490. #endif
  2491. ),
  2492. OPT_WITH_ARG("--url|-o",
  2493. set_url, NULL, &opt_set_null,
  2494. "URL for bitcoin JSON-RPC server"),
  2495. #ifdef USE_USBUTILS
  2496. OPT_WITH_ARG("--usb",
  2497. opt_set_charp, NULL, &opt_usb_select,
  2498. "USB device selection"),
  2499. OPT_WITH_ARG("--usb-dump",
  2500. set_int_0_to_10, opt_show_intval, &opt_usbdump,
  2501. opt_hidden),
  2502. OPT_WITHOUT_ARG("--usb-list-all",
  2503. opt_set_bool, &opt_usb_list_all,
  2504. opt_hidden),
  2505. #endif
  2506. OPT_WITH_ARG("--user|-u",
  2507. set_user, NULL, &opt_set_null,
  2508. "Username for bitcoin JSON-RPC server"),
  2509. OPT_WITH_ARG("--userpass|-O",
  2510. set_userpass, NULL, &opt_set_null,
  2511. "Username:Password pair for bitcoin JSON-RPC server"),
  2512. OPT_WITHOUT_ARG("--verbose",
  2513. opt_set_bool, &opt_log_output,
  2514. "Log verbose output to stderr as well as status output"),
  2515. OPT_WITHOUT_ARG("--widescreen",
  2516. opt_set_bool, &opt_widescreen,
  2517. "Use extra wide display without toggling"),
  2518. OPT_WITHOUT_ARG("--worktime",
  2519. opt_set_bool, &opt_worktime,
  2520. "Display extra work time debug information"),
  2521. #if defined(USE_AVALON7) || defined(USE_AVALON8) || defined(USE_AVALON9) || defined(USE_AVALONLC3)
  2522. OPT_WITH_ARG("--force-clean-jobs",
  2523. opt_set_intval, NULL, &opt_force_clean_jobs,
  2524. "Force clean jobs to miners (default: 20)"),
  2525. #endif
  2526. OPT_ENDTABLE
  2527. };
  2528. static char *load_config(const char *arg, void __maybe_unused *unused);
  2529. static int fileconf_load;
  2530. static char *parse_config(json_t *config, bool fileconf)
  2531. {
  2532. static char err_buf[200];
  2533. struct opt_table *opt;
  2534. const char *str;
  2535. json_t *val;
  2536. if (fileconf && !fileconf_load)
  2537. fileconf_load = 1;
  2538. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2539. char *p, *saved, *name;
  2540. /* We don't handle subtables. */
  2541. assert(!(opt->type & OPT_SUBTABLE));
  2542. if (!opt->names || !strlen(opt->names))
  2543. continue;
  2544. /* Pull apart the option name(s). */
  2545. name = strdup(opt->names);
  2546. for (p = strtok_r(name, "|", &saved); p != NULL; p = strtok_r(NULL, "|", &saved)) {
  2547. char *err = NULL;
  2548. if (strlen(p) < 3)
  2549. continue;
  2550. /* Ignore short options. */
  2551. if (p[1] != '-')
  2552. continue;
  2553. val = json_object_get(config, p+2);
  2554. if (!val)
  2555. continue;
  2556. if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_string(val)) {
  2557. str = json_string_value(val);
  2558. err = opt->cb_arg(str, opt->u.arg);
  2559. if (opt->type == OPT_PROCESSARG)
  2560. opt_set_charp(str, opt->u.arg);
  2561. } else if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_array(val)) {
  2562. json_t *arr_val;
  2563. size_t index;
  2564. json_array_foreach(val, index, arr_val) {
  2565. if (json_is_string(arr_val)) {
  2566. str = json_string_value(arr_val);
  2567. err = opt->cb_arg(str, opt->u.arg);
  2568. if (opt->type == OPT_PROCESSARG)
  2569. opt_set_charp(str, opt->u.arg);
  2570. } else if (json_is_object(arr_val))
  2571. err = parse_config(arr_val, false);
  2572. if (err)
  2573. break;
  2574. }
  2575. } else if ((opt->type & OPT_NOARG) && json_is_true(val))
  2576. err = opt->cb(opt->u.arg);
  2577. else
  2578. err = "Invalid value";
  2579. if (err) {
  2580. /* Allow invalid values to be in configuration
  2581. * file, just skipping over them provided the
  2582. * JSON is still valid after that. */
  2583. if (fileconf) {
  2584. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2585. fileconf_load = -1;
  2586. } else {
  2587. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2588. p, err);
  2589. return err_buf;
  2590. }
  2591. }
  2592. }
  2593. free(name);
  2594. }
  2595. val = json_object_get(config, JSON_INCLUDE_CONF);
  2596. if (val && json_is_string(val))
  2597. return load_config(json_string_value(val), NULL);
  2598. return NULL;
  2599. }
  2600. char *cnfbuf = NULL;
  2601. #ifdef HAVE_LIBCURL
  2602. char conf_web1[] = "http://";
  2603. char conf_web2[] = "https://";
  2604. static char *load_web_config(const char *arg)
  2605. {
  2606. json_t *val = json_web_config(arg);
  2607. if (!val || !json_is_object(val))
  2608. return JSON_WEB_ERROR;
  2609. if (!cnfbuf)
  2610. cnfbuf = strdup(arg);
  2611. config_loaded = true;
  2612. return parse_config(val, true);
  2613. }
  2614. #endif
  2615. static char *load_config(const char *arg, void __maybe_unused *unused)
  2616. {
  2617. json_error_t err;
  2618. json_t *config;
  2619. char *json_error;
  2620. size_t siz;
  2621. #ifdef HAVE_LIBCURL
  2622. if (strncasecmp(arg, conf_web1, sizeof(conf_web1)-1) == 0 ||
  2623. strncasecmp(arg, conf_web2, sizeof(conf_web2)-1) == 0)
  2624. return load_web_config(arg);
  2625. #endif
  2626. if (!cnfbuf)
  2627. cnfbuf = strdup(arg);
  2628. if (++include_count > JSON_MAX_DEPTH)
  2629. return JSON_MAX_DEPTH_ERR;
  2630. config = json_load_file(arg, 0, &err);
  2631. if (!json_is_object(config)) {
  2632. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2633. json_error = cgmalloc(siz);
  2634. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2635. return json_error;
  2636. }
  2637. config_loaded = true;
  2638. /* Parse the config now, so we can override it. That can keep pointers
  2639. * so don't free config object. */
  2640. return parse_config(config, true);
  2641. }
  2642. static char *set_default_config(const char *arg)
  2643. {
  2644. opt_set_charp(arg, &default_config);
  2645. return NULL;
  2646. }
  2647. void default_save_file(char *filename);
  2648. static void load_default_config(void)
  2649. {
  2650. cnfbuf = cgmalloc(PATH_MAX);
  2651. default_save_file(cnfbuf);
  2652. if (!access(cnfbuf, R_OK))
  2653. load_config(cnfbuf, NULL);
  2654. else {
  2655. free(cnfbuf);
  2656. cnfbuf = NULL;
  2657. }
  2658. }
  2659. extern const char *opt_argv0;
  2660. static char *opt_verusage_and_exit(const char *extra)
  2661. {
  2662. printf("%s\nBuilt with "
  2663. #ifdef USE_ANT_S1
  2664. "ant.S1 "
  2665. #endif
  2666. #ifdef USE_ANT_S2
  2667. #ifdef USE_ANT_S3
  2668. "ant.S3 "
  2669. #else
  2670. "ant.S2 "
  2671. #endif
  2672. #endif
  2673. #ifdef USE_AVALON
  2674. "avalon "
  2675. #endif
  2676. #ifdef USE_AVALON2
  2677. "avalon2 "
  2678. #endif
  2679. #ifdef USE_AVALON4
  2680. "avalon4 "
  2681. #endif
  2682. #ifdef USE_AVALON7
  2683. "avalon7 "
  2684. #endif
  2685. #ifdef USE_AVALON8
  2686. "avalon8 "
  2687. #endif
  2688. #ifdef USE_AVALON9
  2689. "avalon9 "
  2690. #endif
  2691. #ifdef USE_AVALONLC3
  2692. "avalonlc3 "
  2693. #endif
  2694. #ifdef USE_AVALON_MINER
  2695. "avalon miner"
  2696. #endif
  2697. #ifdef USE_BAB
  2698. "BaB "
  2699. #endif
  2700. #ifdef USE_BFLSC
  2701. "bflsc "
  2702. #endif
  2703. #ifdef USE_BITFORCE
  2704. "bitforce "
  2705. #endif
  2706. #ifdef USE_BITFURY
  2707. "bitfury "
  2708. #endif
  2709. #ifdef USE_BITFURY16
  2710. "bitfury16 "
  2711. #endif
  2712. #ifdef USE_BITMINE_A1
  2713. "Bitmine.A1 "
  2714. #endif
  2715. #ifdef USE_BLOCKERUPTER
  2716. "Blockerupter "
  2717. #endif
  2718. #ifdef USE_COINTERRA
  2719. "cointerra "
  2720. #endif
  2721. #ifdef USE_DRILLBIT
  2722. "drillbit "
  2723. #endif
  2724. #ifdef USE_DRAGONMINT_T1
  2725. "dragonmint_t1 "
  2726. #endif
  2727. #ifdef USE_GEKKO
  2728. "gekko "
  2729. #endif
  2730. #ifdef USE_HASHFAST
  2731. "hashfast "
  2732. #endif
  2733. #ifdef USE_ICARUS
  2734. "icarus "
  2735. #endif
  2736. #ifdef USE_KLONDIKE
  2737. "klondike "
  2738. #endif
  2739. #ifdef USE_KNC
  2740. "KnC "
  2741. #endif
  2742. #ifdef USE_MINION
  2743. "minion "
  2744. #endif
  2745. #ifdef USE_MODMINER
  2746. "modminer "
  2747. #endif
  2748. #ifdef USE_BITMINE_A1
  2749. "Bitmine.A1 "
  2750. #endif
  2751. #ifdef USE_SP10
  2752. "spondoolies "
  2753. #endif
  2754. #ifdef USE_SP30
  2755. "sp30 "
  2756. #endif
  2757. #ifdef USE_XTRANONCE
  2758. "xnsub "
  2759. #endif
  2760. "mining support.\n"
  2761. , packagename);
  2762. printf("%s", opt_usage(opt_argv0, extra));
  2763. fflush(stdout);
  2764. exit(0);
  2765. }
  2766. #if defined(USE_USBUTILS)
  2767. char *display_devs(int *ndevs)
  2768. {
  2769. *ndevs = 0;
  2770. usb_all(0);
  2771. exit(*ndevs);
  2772. }
  2773. #endif
  2774. /* These options are available from commandline only */
  2775. static struct opt_table opt_cmdline_table[] = {
  2776. OPT_WITH_ARG("--config|-c",
  2777. load_config, NULL, &opt_set_null,
  2778. "Load a JSON-format configuration file\n"
  2779. "See example.conf for an example configuration."),
  2780. OPT_WITH_ARG("--default-config",
  2781. set_default_config, NULL, &opt_set_null,
  2782. "Specify the filename of the default config file\n"
  2783. "Loaded at start and used when saving without a name."),
  2784. OPT_WITHOUT_ARG("--help|-h",
  2785. opt_verusage_and_exit, NULL,
  2786. "Print this message"),
  2787. #if defined(USE_USBUTILS)
  2788. OPT_WITHOUT_ARG("--ndevs|-n",
  2789. display_devs, &nDevs,
  2790. "Display all USB devices and exit"),
  2791. #endif
  2792. OPT_WITHOUT_ARG("--version|-V",
  2793. opt_version_and_exit, packagename,
  2794. "Display version and exit"),
  2795. OPT_ENDTABLE
  2796. };
  2797. static void calc_midstate(struct pool *pool, struct work *work)
  2798. {
  2799. unsigned char data[64];
  2800. uint32_t *data32 = (uint32_t *)data;
  2801. sha256_ctx ctx;
  2802. if (pool->vmask) {
  2803. /* This would only be set if the driver requested a vmask and
  2804. * the pool has a valid version mask. */
  2805. memcpy(work->data, &(pool->vmask_001[2]), 4);
  2806. flip64(data32, work->data);
  2807. sha256_init(&ctx);
  2808. sha256_update(&ctx, data, 64);
  2809. cg_memcpy(work->midstate1, ctx.h, 32);
  2810. endian_flip32(work->midstate1, work->midstate1);
  2811. memcpy(work->data, &(pool->vmask_001[4]), 4);
  2812. flip64(data32, work->data);
  2813. sha256_init(&ctx);
  2814. sha256_update(&ctx, data, 64);
  2815. cg_memcpy(work->midstate2, ctx.h, 32);
  2816. endian_flip32(work->midstate2, work->midstate2);
  2817. memcpy(work->data, &(pool->vmask_001[8]), 4);
  2818. flip64(data32, work->data);
  2819. sha256_init(&ctx);
  2820. sha256_update(&ctx, data, 64);
  2821. cg_memcpy(work->midstate3, ctx.h, 32);
  2822. endian_flip32(work->midstate3, work->midstate3);
  2823. memcpy(work->data, &(pool->vmask_001[0]), 4);
  2824. }
  2825. flip64(data32, work->data);
  2826. sha256_init(&ctx);
  2827. sha256_update(&ctx, data, 64);
  2828. cg_memcpy(work->midstate, ctx.h, 32);
  2829. endian_flip32(work->midstate, work->midstate);
  2830. }
  2831. /* Returns the current value of total_work and increments it */
  2832. static int total_work_inc(void)
  2833. {
  2834. int ret;
  2835. cg_wlock(&control_lock);
  2836. ret = total_work++;
  2837. cg_wunlock(&control_lock);
  2838. return ret;
  2839. }
  2840. static struct work *make_work(void)
  2841. {
  2842. struct work *work = cgcalloc(1, sizeof(struct work));
  2843. work->id = total_work_inc();
  2844. return work;
  2845. }
  2846. /* This is the central place all work that is about to be retired should be
  2847. * cleaned to remove any dynamically allocated arrays within the struct */
  2848. void clean_work(struct work *work)
  2849. {
  2850. free(work->job_id);
  2851. free(work->ntime);
  2852. free(work->coinbase);
  2853. free(work->nonce1);
  2854. memset(work, 0, sizeof(struct work));
  2855. }
  2856. /* All dynamically allocated work structs should be freed here to not leak any
  2857. * ram from arrays allocated within the work struct. Null the actual pointer
  2858. * used to call free_work. */
  2859. void _free_work(struct work **workptr, const char *file, const char *func, const int line)
  2860. {
  2861. struct work *work = *workptr;
  2862. if (unlikely(!work)) {
  2863. applog(LOG_ERR, "Free work called with null work from %s %s:%d",
  2864. file, func, line);
  2865. return;
  2866. }
  2867. clean_work(work);
  2868. free(work);
  2869. *workptr = NULL;
  2870. }
  2871. static void gen_hash(unsigned char *data, unsigned char *hash, int len);
  2872. static void calc_diff(struct work *work, double known);
  2873. char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
  2874. #ifdef HAVE_LIBCURL
  2875. /* Process transactions with GBT by storing the binary value of the first
  2876. * transaction, and the hashes of the remaining transactions since these
  2877. * remain constant with an altered coinbase when generating work. Must be
  2878. * entered under gbt_lock */
  2879. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr);
  2880. static void __build_gbt_txns(struct pool *pool, json_t *res_val)
  2881. {
  2882. json_t *txn_array;
  2883. txn_array = json_object_get(res_val, "transactions");
  2884. gbt_merkle_bins(pool, txn_array);
  2885. }
  2886. static void __gbt_merkleroot(struct pool *pool, unsigned char *merkle_root)
  2887. {
  2888. unsigned char merkle_sha[64];
  2889. int i;
  2890. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  2891. cg_memcpy(merkle_sha, merkle_root, 32);
  2892. for (i = 0; i < pool->merkles; i++) {
  2893. cg_memcpy(merkle_sha + 32, pool->merklebin + i * 32, 32);
  2894. gen_hash(merkle_sha, merkle_root, 64);
  2895. cg_memcpy(merkle_sha, merkle_root, 32);
  2896. }
  2897. }
  2898. static bool work_decode(struct pool *pool, struct work *work, json_t *val);
  2899. static void update_gbt(struct pool *pool)
  2900. {
  2901. int rolltime;
  2902. json_t *val;
  2903. CURL *curl;
  2904. curl = curl_easy_init();
  2905. if (unlikely(!curl))
  2906. quit (1, "CURL initialisation failed in update_gbt");
  2907. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  2908. pool->rpc_req, true, false, &rolltime, pool, false);
  2909. if (val) {
  2910. struct work *work = make_work();
  2911. bool rc = work_decode(pool, work, val);
  2912. total_getworks++;
  2913. pool->getwork_requested++;
  2914. if (rc) {
  2915. applog(LOG_DEBUG, "Successfully retrieved and updated GBT from pool %u %s",
  2916. pool->pool_no, pool->rpc_url);
  2917. if (pool == current_pool())
  2918. opt_work_update = true;
  2919. } else {
  2920. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher GBT from pool %u %s",
  2921. pool->pool_no, pool->rpc_url);
  2922. }
  2923. json_decref(val);
  2924. free_work(work);
  2925. } else {
  2926. applog(LOG_DEBUG, "FAILED to update GBT from pool %u %s",
  2927. pool->pool_no, pool->rpc_url);
  2928. }
  2929. curl_easy_cleanup(curl);
  2930. }
  2931. static void gen_gbt_work(struct pool *pool, struct work *work)
  2932. {
  2933. unsigned char merkleroot[32];
  2934. struct timeval now;
  2935. uint64_t nonce2le;
  2936. cgtime(&now);
  2937. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  2938. update_gbt(pool);
  2939. cg_wlock(&pool->gbt_lock);
  2940. nonce2le = htole64(pool->nonce2);
  2941. cg_memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  2942. pool->nonce2++;
  2943. cg_dwlock(&pool->gbt_lock);
  2944. __gbt_merkleroot(pool, merkleroot);
  2945. cg_memcpy(work->data, &pool->gbt_version, 4);
  2946. cg_memcpy(work->data + 4, pool->previousblockhash, 32);
  2947. cg_memcpy(work->data + 4 + 32 + 32, &pool->curtime, 4);
  2948. cg_memcpy(work->data + 4 + 32 + 32 + 4, &pool->gbt_bits, 4);
  2949. cg_memcpy(work->target, pool->gbt_target, 32);
  2950. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  2951. /* For encoding the block data on submission */
  2952. work->gbt_txns = pool->gbt_txns + 1;
  2953. if (pool->gbt_workid)
  2954. work->job_id = strdup(pool->gbt_workid);
  2955. cg_runlock(&pool->gbt_lock);
  2956. flip32(work->data + 4 + 32, merkleroot);
  2957. memset(work->data + 4 + 32 + 32 + 4 + 4, 0, 4); /* nonce */
  2958. hex2bin(work->data + 4 + 32 + 32 + 4 + 4 + 4, workpadding, 48);
  2959. if (opt_debug) {
  2960. char *header = bin2hex(work->data, 128);
  2961. applog(LOG_DEBUG, "Generated GBT header %s", header);
  2962. applog(LOG_DEBUG, "Work coinbase %s", work->coinbase);
  2963. free(header);
  2964. }
  2965. calc_midstate(pool, work);
  2966. local_work++;
  2967. work->pool = pool;
  2968. work->gbt = true;
  2969. work->longpoll = false;
  2970. work->getwork_mode = GETWORK_MODE_GBT;
  2971. work->work_block = work_block;
  2972. /* Nominally allow a driver to ntime roll 60 seconds */
  2973. work->drv_rolllimit = 60;
  2974. calc_diff(work, 0);
  2975. cgtime(&work->tv_staged);
  2976. }
  2977. static bool gbt_decode(struct pool *pool, json_t *res_val)
  2978. {
  2979. const char *previousblockhash;
  2980. const char *target;
  2981. const char *coinbasetxn;
  2982. const char *longpollid;
  2983. unsigned char hash_swap[32];
  2984. int expires;
  2985. int version;
  2986. int curtime;
  2987. bool submitold;
  2988. const char *bits;
  2989. const char *workid;
  2990. int cbt_len, orig_len;
  2991. uint8_t *extra_len;
  2992. size_t cal_len;
  2993. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  2994. target = json_string_value(json_object_get(res_val, "target"));
  2995. coinbasetxn = json_string_value(json_object_get(json_object_get(res_val, "coinbasetxn"), "data"));
  2996. longpollid = json_string_value(json_object_get(res_val, "longpollid"));
  2997. expires = json_integer_value(json_object_get(res_val, "expires"));
  2998. version = json_integer_value(json_object_get(res_val, "version"));
  2999. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  3000. submitold = json_is_true(json_object_get(res_val, "submitold"));
  3001. bits = json_string_value(json_object_get(res_val, "bits"));
  3002. workid = json_string_value(json_object_get(res_val, "workid"));
  3003. if (!previousblockhash || !target || !coinbasetxn || !longpollid ||
  3004. !expires || !version || !curtime || !bits) {
  3005. applog(LOG_ERR, "JSON failed to decode GBT");
  3006. return false;
  3007. }
  3008. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  3009. applog(LOG_DEBUG, "target: %s", target);
  3010. applog(LOG_DEBUG, "coinbasetxn: %s", coinbasetxn);
  3011. applog(LOG_DEBUG, "longpollid: %s", longpollid);
  3012. applog(LOG_DEBUG, "expires: %d", expires);
  3013. applog(LOG_DEBUG, "version: %d", version);
  3014. applog(LOG_DEBUG, "curtime: %d", curtime);
  3015. applog(LOG_DEBUG, "submitold: %s", submitold ? "true" : "false");
  3016. applog(LOG_DEBUG, "bits: %s", bits);
  3017. if (workid)
  3018. applog(LOG_DEBUG, "workid: %s", workid);
  3019. cg_wlock(&pool->gbt_lock);
  3020. free(pool->coinbasetxn);
  3021. pool->coinbasetxn = strdup(coinbasetxn);
  3022. cbt_len = strlen(pool->coinbasetxn) / 2;
  3023. /* We add 8 bytes of extra data corresponding to nonce2 */
  3024. pool->n2size = 8;
  3025. pool->coinbase_len = cbt_len + pool->n2size;
  3026. cal_len = pool->coinbase_len + 1;
  3027. free(pool->coinbase);
  3028. pool->coinbase = cgcalloc(cal_len, 1);
  3029. hex2bin(pool->coinbase, pool->coinbasetxn, 42);
  3030. extra_len = (uint8_t *)(pool->coinbase + 41);
  3031. orig_len = *extra_len;
  3032. hex2bin(pool->coinbase + 42, pool->coinbasetxn + 84, orig_len);
  3033. *extra_len += pool->n2size;
  3034. hex2bin(pool->coinbase + 42 + *extra_len, pool->coinbasetxn + 84 + (orig_len * 2),
  3035. cbt_len - orig_len - 42);
  3036. pool->nonce2_offset = orig_len + 42;
  3037. free(pool->longpollid);
  3038. pool->longpollid = strdup(longpollid);
  3039. free(pool->gbt_workid);
  3040. if (workid)
  3041. pool->gbt_workid = strdup(workid);
  3042. else
  3043. pool->gbt_workid = NULL;
  3044. hex2bin(hash_swap, previousblockhash, 32);
  3045. swap256(pool->previousblockhash, hash_swap);
  3046. hex2bin(hash_swap, target, 32);
  3047. swab256(pool->gbt_target, hash_swap);
  3048. pool->gbt_expires = expires;
  3049. pool->gbt_version = htobe32(version);
  3050. pool->curtime = htobe32(curtime);
  3051. pool->submit_old = submitold;
  3052. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  3053. __build_gbt_txns(pool, res_val);
  3054. if (pool->transactions < 3)
  3055. pool->bad_work++;
  3056. cg_wunlock(&pool->gbt_lock);
  3057. return true;
  3058. }
  3059. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr)
  3060. {
  3061. unsigned char *hashbin;
  3062. json_t *arr_val;
  3063. int i, j, binleft, binlen;
  3064. free(pool->txn_data);
  3065. pool->txn_data = NULL;
  3066. pool->transactions = 0;
  3067. pool->merkles = 0;
  3068. pool->transactions = json_array_size(transaction_arr);
  3069. binlen = pool->transactions * 32 + 32;
  3070. hashbin = alloca(binlen + 32);
  3071. memset(hashbin, 0, 32);
  3072. binleft = binlen / 32;
  3073. if (pool->transactions) {
  3074. int len = 0, ofs = 0;
  3075. const char *txn;
  3076. for (i = 0; i < pool->transactions; i++) {
  3077. arr_val = json_array_get(transaction_arr, i);
  3078. txn = json_string_value(json_object_get(arr_val, "data"));
  3079. if (!txn) {
  3080. applog(LOG_ERR, "Pool %d json_string_value fail - cannot find transaction data",
  3081. pool->pool_no);
  3082. return;
  3083. }
  3084. len += strlen(txn);
  3085. }
  3086. pool->txn_data = cgmalloc(len + 1);
  3087. pool->txn_data[len] = '\0';
  3088. for (i = 0; i < pool->transactions; i++) {
  3089. unsigned char binswap[32];
  3090. const char *hash;
  3091. const char *txid;
  3092. arr_val = json_array_get(transaction_arr, i);
  3093. txid = json_string_value(json_object_get(arr_val, "txid"));
  3094. hash = json_string_value(json_object_get(arr_val, "hash"));
  3095. if(!txid)
  3096. txid = hash;
  3097. txn = json_string_value(json_object_get(arr_val, "data"));
  3098. len = strlen(txn);
  3099. cg_memcpy(pool->txn_data + ofs, txn, len);
  3100. ofs += len;
  3101. #if 0
  3102. // This logic no longer works post-segwit. The txids will always need to be sent,
  3103. // as the full txns will also contain witness data that must be omitted in these
  3104. // hashes.
  3105. if (!hash) {
  3106. unsigned char *txn_bin;
  3107. int txn_len;
  3108. txn_len = len / 2;
  3109. txn_bin = cgmalloc(txn_len);
  3110. hex2bin(txn_bin, txn, txn_len);
  3111. /* This is needed for pooled mining since only
  3112. * transaction data and not hashes are sent */
  3113. gen_hash(txn_bin, hashbin + 32 + 32 * i, txn_len);
  3114. continue;
  3115. }
  3116. #endif
  3117. if (!txid) {
  3118. applog(LOG_ERR, "missing txid in gbt_merkle_bins");
  3119. return;
  3120. }
  3121. if (!hex2bin(binswap, txid, 32)) {
  3122. applog(LOG_ERR, "Failed to hex2bin txid in gbt_merkle_bins");
  3123. return;
  3124. }
  3125. swab256(hashbin + 32 + 32 * i, binswap);
  3126. }
  3127. }
  3128. if (binleft > 1) {
  3129. while (42) {
  3130. if (binleft == 1)
  3131. break;
  3132. cg_memcpy(pool->merklebin + (pool->merkles * 32), hashbin + 32, 32);
  3133. pool->merkles++;
  3134. if (binleft % 2) {
  3135. cg_memcpy(hashbin + binlen, hashbin + binlen - 32, 32);
  3136. binlen += 32;
  3137. binleft++;
  3138. }
  3139. for (i = 32, j = 64; j < binlen; i += 32, j += 64) {
  3140. gen_hash(hashbin + j, hashbin + i, 64);
  3141. }
  3142. binleft /= 2;
  3143. binlen = binleft * 32;
  3144. }
  3145. }
  3146. if (opt_debug) {
  3147. char hashhex[68];
  3148. for (i = 0; i < pool->merkles; i++) {
  3149. __bin2hex(hashhex, pool->merklebin + i * 32, 32);
  3150. applog(LOG_DEBUG, "MH%d %s",i, hashhex);
  3151. }
  3152. }
  3153. applog(LOG_INFO, "Stored %d transactions from pool %d", pool->transactions,
  3154. pool->pool_no);
  3155. }
  3156. static const unsigned char witness_nonce[32] = {0};
  3157. static const int witness_nonce_size = sizeof(witness_nonce);
  3158. static const unsigned char witness_header[] = {0xaa, 0x21, 0xa9, 0xed};
  3159. static const int witness_header_size = sizeof(witness_header);
  3160. static bool gbt_witness_data(json_t *transaction_arr, unsigned char* witnessdata, int avail_size)
  3161. {
  3162. int i, binlen, txncount = json_array_size(transaction_arr);
  3163. unsigned char *hashbin;
  3164. const char *hash;
  3165. json_t *arr_val;
  3166. binlen = txncount * 32 + 32;
  3167. hashbin = alloca(binlen + 32);
  3168. memset(hashbin, 0, 32);
  3169. if (avail_size < witness_header_size + 32)
  3170. return false;
  3171. for (i = 0; i < txncount; i++) {
  3172. unsigned char binswap[32];
  3173. arr_val = json_array_get(transaction_arr, i);
  3174. hash = json_string_value(json_object_get(arr_val, "hash"));
  3175. if (unlikely(!hash)) {
  3176. applog(LOG_ERR, "Hash missing for transaction");
  3177. return false;
  3178. }
  3179. if (!hex2bin(binswap, hash, 32)) {
  3180. applog(LOG_ERR, "Failed to hex2bin hash in gbt_witness_data");
  3181. return false;
  3182. }
  3183. swab256(hashbin + 32 + 32 * i, binswap);
  3184. }
  3185. // Build merkle root (copied from libblkmaker)
  3186. for (txncount++ ; txncount > 1 ; txncount /= 2) {
  3187. if (txncount % 2) {
  3188. // Odd number, duplicate the last
  3189. memcpy(hashbin + 32 * txncount, hashbin + 32 * (txncount - 1), 32);
  3190. txncount++;
  3191. }
  3192. for (i = 0; i < txncount; i += 2) {
  3193. // We overlap input and output here, on the first pair
  3194. gen_hash(hashbin + 32 * i, hashbin + 32 * (i / 2), 64);
  3195. }
  3196. }
  3197. memcpy(witnessdata, witness_header, witness_header_size);
  3198. memcpy(hashbin + 32, &witness_nonce, witness_nonce_size);
  3199. gen_hash(hashbin, witnessdata + witness_header_size, 32 + witness_nonce_size);
  3200. return true;
  3201. }
  3202. static double diff_from_target(void *target);
  3203. static const char scriptsig_header[] = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff";
  3204. static unsigned char scriptsig_header_bin[41];
  3205. static bool gbt_solo_decode(struct pool *pool, json_t *res_val)
  3206. {
  3207. json_t *transaction_arr, *rules_arr, *coinbase_aux;
  3208. const char *previousblockhash;
  3209. unsigned char hash_swap[32];
  3210. struct timeval now;
  3211. const char *target;
  3212. uint64_t coinbasevalue;
  3213. const char *flags;
  3214. const char *bits;
  3215. char header[260];
  3216. int ofs = 0, len;
  3217. uint64_t *u64;
  3218. uint32_t *u32;
  3219. int version;
  3220. int curtime;
  3221. int height;
  3222. int witness_txout_len = 0;
  3223. int witnessdata_size = 0;
  3224. bool insert_witness = false;
  3225. unsigned char witnessdata[36] = {};
  3226. const char *default_witness_commitment;
  3227. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  3228. target = json_string_value(json_object_get(res_val, "target"));
  3229. transaction_arr = json_object_get(res_val, "transactions");
  3230. rules_arr = json_object_get(res_val, "rules");
  3231. version = json_integer_value(json_object_get(res_val, "version"));
  3232. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  3233. bits = json_string_value(json_object_get(res_val, "bits"));
  3234. height = json_integer_value(json_object_get(res_val, "height"));
  3235. coinbasevalue = json_integer_value(json_object_get(res_val, "coinbasevalue"));
  3236. coinbase_aux = json_object_get(res_val, "coinbaseaux");
  3237. flags = json_string_value(json_object_get(coinbase_aux, "flags"));
  3238. default_witness_commitment = json_string_value(json_object_get(res_val, "default_witness_commitment"));
  3239. if (!previousblockhash || !target || !version || !curtime || !bits || !coinbase_aux || !flags) {
  3240. applog(LOG_ERR, "Pool %d JSON failed to decode GBT", pool->pool_no);
  3241. return false;
  3242. }
  3243. if (rules_arr) {
  3244. int i;
  3245. int rule_count = json_array_size(rules_arr);
  3246. const char *rule;
  3247. for (i = 0; i < rule_count; i++) {
  3248. rule = json_string_value(json_array_get(rules_arr, i));
  3249. if (!rule)
  3250. continue;
  3251. if (*rule == '!')
  3252. rule++;
  3253. if (strncmp(rule, "segwit", 6)) {
  3254. insert_witness = true;
  3255. break;
  3256. }
  3257. }
  3258. }
  3259. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  3260. applog(LOG_DEBUG, "target: %s", target);
  3261. applog(LOG_DEBUG, "version: %d", version);
  3262. applog(LOG_DEBUG, "curtime: %d", curtime);
  3263. applog(LOG_DEBUG, "bits: %s", bits);
  3264. applog(LOG_DEBUG, "height: %d", height);
  3265. applog(LOG_DEBUG, "flags: %s", flags);
  3266. cg_wlock(&pool->gbt_lock);
  3267. hex2bin(hash_swap, previousblockhash, 32);
  3268. swap256(pool->previousblockhash, hash_swap);
  3269. __bin2hex(pool->prev_hash, pool->previousblockhash, 32);
  3270. hex2bin(hash_swap, target, 32);
  3271. swab256(pool->gbt_target, hash_swap);
  3272. pool->sdiff = diff_from_target(pool->gbt_target);
  3273. pool->gbt_version = htobe32(version);
  3274. pool->curtime = htobe32(curtime);
  3275. snprintf(pool->ntime, 9, "%08x", curtime);
  3276. snprintf(pool->bbversion, 9, "%08x", version);
  3277. snprintf(pool->nbit, 9, "%s", bits);
  3278. pool->nValue = coinbasevalue;
  3279. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  3280. gbt_merkle_bins(pool, transaction_arr);
  3281. if (insert_witness) {
  3282. char witness_str[sizeof(witnessdata) * 2];
  3283. witnessdata_size = sizeof(witnessdata);
  3284. if (!gbt_witness_data(transaction_arr, witnessdata, witnessdata_size)) {
  3285. applog(LOG_ERR, "error calculating witness data");
  3286. return false;
  3287. }
  3288. __bin2hex(witness_str, witnessdata, witnessdata_size);
  3289. applog(LOG_DEBUG, "calculated witness data: %s", witness_str);
  3290. if (default_witness_commitment) {
  3291. if (strncmp(witness_str, default_witness_commitment + 4, witnessdata_size * 2) != 0) {
  3292. applog(LOG_ERR, "bad witness data. %s != %s", default_witness_commitment + 4, witness_str);
  3293. return false;
  3294. }
  3295. }
  3296. }
  3297. if (pool->transactions < 3)
  3298. pool->bad_work++;
  3299. pool->height = height;
  3300. memset(pool->scriptsig_base, 0, 42);
  3301. ofs++; // Leave room for template length
  3302. /* Put block height at start of template. */
  3303. ofs += ser_number(pool->scriptsig_base + ofs, height); // max 5
  3304. /* Followed by flags */
  3305. if (flags) {
  3306. len = strlen(flags) / 2;
  3307. pool->scriptsig_base[ofs++] = len;
  3308. hex2bin(pool->scriptsig_base + ofs, flags, len);
  3309. ofs += len;
  3310. }
  3311. /* Followed by timestamp */
  3312. cgtime(&now);
  3313. pool->scriptsig_base[ofs++] = 0xfe; // Encode seconds as u32
  3314. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  3315. *u32 = htole32(now.tv_sec);
  3316. ofs += 4; // sizeof uint32_t
  3317. pool->scriptsig_base[ofs++] = 0xfe; // Encode usecs as u32
  3318. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  3319. *u32 = htole32(now.tv_usec);
  3320. ofs += 4; // sizeof uint32_t
  3321. cg_memcpy(pool->scriptsig_base + ofs, "\x09\x63\x67\x6d\x69\x6e\x65\x72\x34\x32", 10);
  3322. ofs += 10;
  3323. /* Followed by extranonce size, fixed at 8 */
  3324. pool->scriptsig_base[ofs++] = 8;
  3325. pool->nonce2_offset = 41 + ofs;
  3326. ofs += 8;
  3327. if (opt_btc_sig) {
  3328. len = strlen(opt_btc_sig);
  3329. if (len > 32)
  3330. len = 32;
  3331. pool->scriptsig_base[ofs++] = len;
  3332. cg_memcpy(pool->scriptsig_base + ofs, opt_btc_sig, len);
  3333. ofs += len;
  3334. }
  3335. pool->scriptsig_base[0] = ofs++; // Template length
  3336. pool->n1_len = ofs;
  3337. len = 41 // prefix
  3338. + ofs // Template length
  3339. + 4 // txin sequence no
  3340. + 1 // txouts
  3341. + 8 // value
  3342. + 1 + 25 // txout
  3343. + 4; // lock
  3344. if (insert_witness) {
  3345. len += 8 //value
  3346. + 1 + 2 + witnessdata_size; // total scriptPubKey size + OP_RETURN + push size + data
  3347. }
  3348. free(pool->coinbase);
  3349. pool->coinbase = cgcalloc(len, 1);
  3350. cg_memcpy(pool->coinbase + 41, pool->scriptsig_base, ofs);
  3351. cg_memcpy(pool->coinbase + 41 + ofs, "\xff\xff\xff\xff", 4);
  3352. pool->coinbase[41 + ofs + 4] = insert_witness ? 2 : 1;
  3353. u64 = (uint64_t *)&(pool->coinbase[41 + ofs + 4 + 1]);
  3354. *u64 = htole64(coinbasevalue);
  3355. if (insert_witness) {
  3356. unsigned char *witness = &pool->coinbase[41 + ofs + 4 + 1 + 8 + 1 + 25];
  3357. memset(witness, 0, 8);
  3358. witness_txout_len += 8;
  3359. witness[witness_txout_len++] = witnessdata_size + 2; // total scriptPubKey size
  3360. witness[witness_txout_len++] = 0x6a; // OP_RETURN
  3361. witness[witness_txout_len++] = witnessdata_size;
  3362. memcpy(&witness[witness_txout_len], witnessdata, witnessdata_size);
  3363. witness_txout_len += witnessdata_size;
  3364. }
  3365. pool->nonce2 = 0;
  3366. pool->n2size = 4;
  3367. pool->coinbase_len = 41 + ofs + 4 + 1 + 8 + 1 + 25 + witness_txout_len + 4;
  3368. cg_wunlock(&pool->gbt_lock);
  3369. snprintf(header, 257, "%s%s%s%s%s%s%s",
  3370. pool->bbversion,
  3371. pool->prev_hash,
  3372. "0000000000000000000000000000000000000000000000000000000000000000",
  3373. pool->ntime,
  3374. pool->nbit,
  3375. "00000000", /* nonce */
  3376. workpadding);
  3377. if (unlikely(!hex2bin(pool->header_bin, header, 128)))
  3378. quit(1, "Failed to hex2bin header in gbt_solo_decode");
  3379. return true;
  3380. }
  3381. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  3382. {
  3383. json_t *res_val = json_object_get(val, "result");
  3384. bool ret = false;
  3385. cgtime(&pool->tv_lastwork);
  3386. if (!res_val || json_is_null(res_val)) {
  3387. applog(LOG_ERR, "JSON Failed to decode result");
  3388. goto out;
  3389. }
  3390. if (pool->gbt_solo) {
  3391. if (unlikely(!gbt_solo_decode(pool, res_val)))
  3392. goto out;
  3393. goto out_true;
  3394. }
  3395. if (unlikely(!gbt_decode(pool, res_val)))
  3396. goto out;
  3397. work->gbt = true;
  3398. memset(work->hash, 0, sizeof(work->hash));
  3399. cgtime(&work->tv_staged);
  3400. out_true:
  3401. ret = true;
  3402. out:
  3403. return ret;
  3404. }
  3405. #else /* HAVE_LIBCURL */
  3406. #define json_rpc_call(curl, url, userpass, rpc_req, probe, longpoll, rolltime, pool, share) (NULL)
  3407. #define work_decode(pool, work, val) (false)
  3408. #define gen_gbt_work(pool, work) {}
  3409. #endif /* HAVE_LIBCURL */
  3410. int dev_from_id(int thr_id)
  3411. {
  3412. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  3413. return cgpu->device_id;
  3414. }
  3415. /* Create an exponentially decaying average over the opt_log_interval */
  3416. void decay_time(double *f, double fadd, double fsecs, double interval)
  3417. {
  3418. double ftotal, fprop;
  3419. if (fsecs <= 0)
  3420. return;
  3421. fprop = 1.0 - 1 / (exp(fsecs / interval));
  3422. ftotal = 1.0 + fprop;
  3423. *f += (fadd / fsecs * fprop);
  3424. *f /= ftotal;
  3425. }
  3426. static int __total_staged(void)
  3427. {
  3428. return HASH_COUNT(staged_work);
  3429. }
  3430. #if defined(HAVE_LIBCURL) || defined(HAVE_CURSES)
  3431. static int total_staged(void)
  3432. {
  3433. int ret;
  3434. mutex_lock(stgd_lock);
  3435. ret = __total_staged();
  3436. mutex_unlock(stgd_lock);
  3437. return ret;
  3438. }
  3439. #endif
  3440. #ifdef HAVE_CURSES
  3441. WINDOW *mainwin, *statuswin, *logwin;
  3442. #endif
  3443. double total_secs = 1.0;
  3444. static char statusline[256];
  3445. /* logstart is where the log window should start */
  3446. static int devcursor, logstart, logcursor;
  3447. #ifdef HAVE_CURSES
  3448. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  3449. static int statusy;
  3450. #endif
  3451. #ifdef HAVE_CURSES
  3452. static inline void unlock_curses(void)
  3453. {
  3454. mutex_unlock(&console_lock);
  3455. }
  3456. static inline void lock_curses(void)
  3457. {
  3458. mutex_lock(&console_lock);
  3459. }
  3460. static bool curses_active_locked(void)
  3461. {
  3462. bool ret;
  3463. lock_curses();
  3464. ret = curses_active;
  3465. if (!ret)
  3466. unlock_curses();
  3467. return ret;
  3468. }
  3469. #endif
  3470. /* Convert a uint64_t value into a truncated string for displaying with its
  3471. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  3472. static void suffix_string(uint64_t val, char *buf, size_t bufsiz, int sigdigits)
  3473. {
  3474. const double dkilo = 1000.0;
  3475. const uint64_t kilo = 1000ull;
  3476. const uint64_t mega = 1000000ull;
  3477. const uint64_t giga = 1000000000ull;
  3478. const uint64_t tera = 1000000000000ull;
  3479. const uint64_t peta = 1000000000000000ull;
  3480. const uint64_t exa = 1000000000000000000ull;
  3481. char suffix[2] = "";
  3482. bool decimal = true;
  3483. double dval;
  3484. if (val >= exa) {
  3485. val /= peta;
  3486. dval = (double)val / dkilo;
  3487. strcpy(suffix, "E");
  3488. } else if (val >= peta) {
  3489. val /= tera;
  3490. dval = (double)val / dkilo;
  3491. strcpy(suffix, "P");
  3492. } else if (val >= tera) {
  3493. val /= giga;
  3494. dval = (double)val / dkilo;
  3495. strcpy(suffix, "T");
  3496. } else if (val >= giga) {
  3497. val /= mega;
  3498. dval = (double)val / dkilo;
  3499. strcpy(suffix, "G");
  3500. } else if (val >= mega) {
  3501. val /= kilo;
  3502. dval = (double)val / dkilo;
  3503. strcpy(suffix, "M");
  3504. } else if (val >= kilo) {
  3505. dval = (double)val / dkilo;
  3506. strcpy(suffix, "K");
  3507. } else {
  3508. dval = val;
  3509. decimal = false;
  3510. }
  3511. if (!sigdigits) {
  3512. if (decimal)
  3513. snprintf(buf, bufsiz, "%.3g%s", dval, suffix);
  3514. else
  3515. snprintf(buf, bufsiz, "%d%s", (unsigned int)dval, suffix);
  3516. } else {
  3517. /* Always show sigdigits + 1, padded on right with zeroes
  3518. * followed by suffix */
  3519. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  3520. snprintf(buf, bufsiz, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  3521. }
  3522. }
  3523. double cgpu_runtime(struct cgpu_info *cgpu)
  3524. {
  3525. struct timeval now;
  3526. double dev_runtime;
  3527. if (cgpu->dev_start_tv.tv_sec == 0)
  3528. dev_runtime = total_secs;
  3529. else {
  3530. cgtime(&now);
  3531. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  3532. }
  3533. if (dev_runtime < 1.0)
  3534. dev_runtime = 1.0;
  3535. return dev_runtime;
  3536. }
  3537. double tsince_restart(void)
  3538. {
  3539. struct timeval now;
  3540. cgtime(&now);
  3541. return tdiff(&now, &restart_tv_start);
  3542. }
  3543. double tsince_update(void)
  3544. {
  3545. struct timeval now;
  3546. cgtime(&now);
  3547. return tdiff(&now, &update_tv_start);
  3548. }
  3549. static void get_statline(char *buf, size_t bufsiz, struct cgpu_info *cgpu)
  3550. {
  3551. char displayed_hashes[16], displayed_rolling[16];
  3552. double dev_runtime, wu;
  3553. uint64_t dh64, dr64;
  3554. dev_runtime = cgpu_runtime(cgpu);
  3555. wu = cgpu->diff1 / dev_runtime * 60.0;
  3556. dh64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  3557. dr64 = (double)cgpu->rolling * 1000000ull;
  3558. suffix_string(dh64, displayed_hashes, sizeof(displayed_hashes), 4);
  3559. suffix_string(dr64, displayed_rolling, sizeof(displayed_rolling), 4);
  3560. snprintf(buf, bufsiz, "%s %d ", cgpu->drv->name, cgpu->device_id);
  3561. cgpu->drv->get_statline_before(buf, bufsiz, cgpu);
  3562. tailsprintf(buf, bufsiz, "(%ds):%s (avg):%sh/s | A:%.0f R:%.0f HW:%d WU:%.1f/m",
  3563. opt_log_interval,
  3564. displayed_rolling,
  3565. displayed_hashes,
  3566. cgpu->diff_accepted,
  3567. cgpu->diff_rejected,
  3568. cgpu->hw_errors,
  3569. wu);
  3570. cgpu->drv->get_statline(buf, bufsiz, cgpu);
  3571. }
  3572. static bool shared_strategy(void)
  3573. {
  3574. return (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE);
  3575. }
  3576. #ifdef HAVE_CURSES
  3577. #define CURBUFSIZ 256
  3578. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3579. char tmp42[CURBUFSIZ]; \
  3580. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3581. mvwprintw(win, y, x, "%s", tmp42); \
  3582. } while (0)
  3583. #define cg_wprintw(win, fmt, ...) do { \
  3584. char tmp42[CURBUFSIZ]; \
  3585. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3586. wprintw(win, "%s", tmp42); \
  3587. } while (0)
  3588. /* Must be called with curses mutex lock held and curses_active */
  3589. static void curses_print_status(void)
  3590. {
  3591. struct pool *pool = current_pool();
  3592. int linewidth = opt_widescreen ? 100 : 80;
  3593. wattron(statuswin, A_BOLD);
  3594. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3595. wattroff(statuswin, A_BOLD);
  3596. mvwhline(statuswin, 1, 0, '-', linewidth);
  3597. cg_mvwprintw(statuswin, 2, 0, " %s", statusline);
  3598. wclrtoeol(statuswin);
  3599. if (opt_widescreen) {
  3600. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m |"
  3601. " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  3602. total_diff_accepted, total_diff_rejected, hw_errors,
  3603. total_diff1 / total_secs * 60,
  3604. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  3605. } else if (alt_status) {
  3606. cg_mvwprintw(statuswin, 3, 0, " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  3607. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  3608. } else {
  3609. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m",
  3610. total_diff_accepted, total_diff_rejected, hw_errors,
  3611. total_diff1 / total_secs * 60);
  3612. }
  3613. wclrtoeol(statuswin);
  3614. if (shared_strategy() && total_pools > 1) {
  3615. cg_mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s block change notify",
  3616. have_longpoll ? "": "out");
  3617. } else if (pool->has_stratum) {
  3618. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  3619. pool->sockaddr_url, pool->diff, pool->rpc_user);
  3620. } else {
  3621. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s %s as user %s",
  3622. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out",
  3623. pool->has_gbt ? "GBT" : "LP", pool->rpc_user);
  3624. }
  3625. wclrtoeol(statuswin);
  3626. cg_mvwprintw(statuswin, 5, 0, " Block: %s... Diff:%s Started: %s Best share: %s ",
  3627. prev_block, block_diff, blocktime, best_share);
  3628. mvwhline(statuswin, 6, 0, '-', linewidth);
  3629. mvwhline(statuswin, statusy - 1, 0, '-', linewidth);
  3630. #ifdef USE_USBUTILS
  3631. cg_mvwprintw(statuswin, devcursor - 1, 1, "[U]SB management [P]ool management [S]ettings [D]isplay options [Q]uit");
  3632. #else
  3633. cg_mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management [S]ettings [D]isplay options [Q]uit");
  3634. #endif
  3635. }
  3636. static void adj_width(int var, int *length)
  3637. {
  3638. if ((int)(log10(var) + 1) > *length)
  3639. (*length)++;
  3640. }
  3641. static void adj_fwidth(float var, int *length)
  3642. {
  3643. if ((int)(log10(var) + 1) > *length)
  3644. (*length)++;
  3645. }
  3646. #define STATBEFORELEN 23
  3647. const char blanks[] = " ";
  3648. static void curses_print_devstatus(struct cgpu_info *cgpu, int devno, int count)
  3649. {
  3650. static int devno_width = 1, dawidth = 1, drwidth = 1, hwwidth = 1, wuwidth = 1;
  3651. char logline[256], unique_id[12];
  3652. struct timeval now;
  3653. double dev_runtime, wu;
  3654. unsigned int devstatlen;
  3655. if (opt_compact)
  3656. return;
  3657. if (devcursor + count > LINES - 2)
  3658. return;
  3659. if (count >= most_devices)
  3660. return;
  3661. if (cgpu->dev_start_tv.tv_sec == 0)
  3662. dev_runtime = total_secs;
  3663. else {
  3664. cgtime(&now);
  3665. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  3666. }
  3667. if (dev_runtime < 1.0)
  3668. dev_runtime = 1.0;
  3669. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3670. wu = cgpu->diff1 / dev_runtime * 60;
  3671. wmove(statuswin,devcursor + count, 0);
  3672. adj_width(devno, &devno_width);
  3673. if (cgpu->unique_id) {
  3674. unique_id[8] = '\0';
  3675. cg_memcpy(unique_id, blanks, 8);
  3676. strncpy(unique_id, cgpu->unique_id, 8);
  3677. } else
  3678. sprintf(unique_id, "%-8d", cgpu->device_id);
  3679. cg_wprintw(statuswin, " %*d: %s %-8s: ", devno_width, devno, cgpu->drv->name,
  3680. unique_id);
  3681. logline[0] = '\0';
  3682. cgpu->drv->get_statline_before(logline, sizeof(logline), cgpu);
  3683. devstatlen = strlen(logline);
  3684. if (devstatlen < STATBEFORELEN)
  3685. strncat(logline, blanks, STATBEFORELEN - devstatlen);
  3686. cg_wprintw(statuswin, "%s | ", logline);
  3687. #ifdef USE_USBUTILS
  3688. if (cgpu->usbinfo.nodev)
  3689. cg_wprintw(statuswin, "ZOMBIE");
  3690. else
  3691. #endif
  3692. if (cgpu->status == LIFE_DEAD)
  3693. cg_wprintw(statuswin, "DEAD ");
  3694. else if (cgpu->status == LIFE_SICK)
  3695. cg_wprintw(statuswin, "SICK ");
  3696. else if (cgpu->deven == DEV_DISABLED)
  3697. cg_wprintw(statuswin, "OFF ");
  3698. else if (cgpu->deven == DEV_RECOVER)
  3699. cg_wprintw(statuswin, "REST ");
  3700. else if (opt_widescreen) {
  3701. char displayed_hashes[16], displayed_rolling[16];
  3702. uint64_t d64;
  3703. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  3704. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  3705. d64 = (double)cgpu->rolling * 1000000ull;
  3706. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  3707. adj_width(wu, &wuwidth);
  3708. adj_fwidth(cgpu->diff_accepted, &dawidth);
  3709. adj_fwidth(cgpu->diff_rejected, &drwidth);
  3710. adj_width(cgpu->hw_errors, &hwwidth);
  3711. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m "
  3712. "A:%*.0f R:%*.0f HW:%*d",
  3713. displayed_rolling,
  3714. displayed_hashes, wuwidth + 2, wu,
  3715. dawidth, cgpu->diff_accepted,
  3716. drwidth, cgpu->diff_rejected,
  3717. hwwidth, cgpu->hw_errors);
  3718. } else if (!alt_status) {
  3719. char displayed_hashes[16], displayed_rolling[16];
  3720. uint64_t d64;
  3721. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  3722. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  3723. d64 = (double)cgpu->rolling * 1000000ull;
  3724. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  3725. adj_width(wu, &wuwidth);
  3726. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m", displayed_rolling,
  3727. displayed_hashes, wuwidth + 2, wu);
  3728. } else {
  3729. adj_fwidth(cgpu->diff_accepted, &dawidth);
  3730. adj_fwidth(cgpu->diff_rejected, &drwidth);
  3731. adj_width(cgpu->hw_errors, &hwwidth);
  3732. cg_wprintw(statuswin, "A:%*.0f R:%*.0f HW:%*d",
  3733. dawidth, cgpu->diff_accepted,
  3734. drwidth, cgpu->diff_rejected,
  3735. hwwidth, cgpu->hw_errors);
  3736. }
  3737. logline[0] = '\0';
  3738. cgpu->drv->get_statline(logline, sizeof(logline), cgpu);
  3739. cg_wprintw(statuswin, "%s", logline);
  3740. wclrtoeol(statuswin);
  3741. }
  3742. #endif
  3743. #ifdef HAVE_CURSES
  3744. /* Check for window resize. Called with curses mutex locked */
  3745. static inline void change_logwinsize(void)
  3746. {
  3747. int x, y, logx, logy;
  3748. getmaxyx(mainwin, y, x);
  3749. if (x < 80 || y < 25)
  3750. return;
  3751. if (y > statusy + 2 && statusy < logstart) {
  3752. if (y - 2 < logstart)
  3753. statusy = y - 2;
  3754. else
  3755. statusy = logstart;
  3756. logcursor = statusy + 1;
  3757. mvwin(logwin, logcursor, 0);
  3758. wresize(statuswin, statusy, x);
  3759. }
  3760. y -= logcursor;
  3761. getmaxyx(logwin, logy, logx);
  3762. /* Detect screen size change */
  3763. if (x != logx || y != logy)
  3764. wresize(logwin, y, x);
  3765. }
  3766. static void check_winsizes(void)
  3767. {
  3768. if (!use_curses)
  3769. return;
  3770. if (curses_active_locked()) {
  3771. int y, x;
  3772. erase();
  3773. x = getmaxx(statuswin);
  3774. if (logstart > LINES - 2)
  3775. statusy = LINES - 2;
  3776. else
  3777. statusy = logstart;
  3778. logcursor = statusy;
  3779. wresize(statuswin, statusy, x);
  3780. getmaxyx(mainwin, y, x);
  3781. y -= logcursor;
  3782. wresize(logwin, y, x);
  3783. mvwin(logwin, logcursor, 0);
  3784. unlock_curses();
  3785. }
  3786. }
  3787. static void disable_curses_windows(void);
  3788. static void enable_curses_windows(void);
  3789. static void switch_logsize(bool __maybe_unused newdevs)
  3790. {
  3791. if (curses_active_locked()) {
  3792. #ifdef WIN32
  3793. if (newdevs)
  3794. disable_curses_windows();
  3795. #endif
  3796. if (opt_compact) {
  3797. logstart = devcursor + 1;
  3798. logcursor = logstart + 1;
  3799. } else {
  3800. logstart = devcursor + most_devices + 1;
  3801. logcursor = logstart + 1;
  3802. }
  3803. #ifdef WIN32
  3804. if (newdevs)
  3805. enable_curses_windows();
  3806. #endif
  3807. unlock_curses();
  3808. check_winsizes();
  3809. }
  3810. }
  3811. /* For mandatory printing when mutex is already locked */
  3812. void _wlog(const char *str)
  3813. {
  3814. wprintw(logwin, "%s", str);
  3815. }
  3816. /* Mandatory printing */
  3817. void _wlogprint(const char *str)
  3818. {
  3819. if (curses_active_locked()) {
  3820. wprintw(logwin, "%s", str);
  3821. unlock_curses();
  3822. }
  3823. }
  3824. #endif
  3825. #ifdef HAVE_CURSES
  3826. bool log_curses_only(int prio, const char *datetime, const char *str)
  3827. {
  3828. bool high_prio;
  3829. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3830. if (curses_active_locked()) {
  3831. if (!opt_loginput || high_prio) {
  3832. wprintw(logwin, "%s%s\n", datetime, str);
  3833. if (high_prio) {
  3834. touchwin(logwin);
  3835. wrefresh(logwin);
  3836. }
  3837. }
  3838. unlock_curses();
  3839. return true;
  3840. }
  3841. return false;
  3842. }
  3843. void clear_logwin(void)
  3844. {
  3845. if (curses_active_locked()) {
  3846. erase();
  3847. wclear(logwin);
  3848. unlock_curses();
  3849. }
  3850. }
  3851. void logwin_update(void)
  3852. {
  3853. if (curses_active_locked()) {
  3854. touchwin(logwin);
  3855. wrefresh(logwin);
  3856. unlock_curses();
  3857. }
  3858. }
  3859. #endif
  3860. static void enable_pool(struct pool *pool)
  3861. {
  3862. if (pool->enabled != POOL_ENABLED) {
  3863. enabled_pools++;
  3864. pool->enabled = POOL_ENABLED;
  3865. }
  3866. }
  3867. #ifdef HAVE_CURSES
  3868. static void disable_pool(struct pool *pool)
  3869. {
  3870. if (pool->enabled == POOL_ENABLED)
  3871. enabled_pools--;
  3872. pool->enabled = POOL_DISABLED;
  3873. }
  3874. #endif
  3875. static void reject_pool(struct pool *pool)
  3876. {
  3877. if (pool->enabled == POOL_ENABLED)
  3878. enabled_pools--;
  3879. pool->enabled = POOL_REJECTING;
  3880. }
  3881. static void restart_threads(void);
  3882. /* Theoretically threads could race when modifying accepted and
  3883. * rejected values but the chance of two submits completing at the
  3884. * same time is zero so there is no point adding extra locking */
  3885. static void
  3886. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3887. char *hashshow, bool resubmit, char *worktime)
  3888. {
  3889. struct pool *pool = work->pool;
  3890. struct cgpu_info *cgpu;
  3891. cgpu = get_thr_cgpu(work->thr_id);
  3892. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  3893. mutex_lock(&stats_lock);
  3894. cgpu->accepted++;
  3895. total_accepted++;
  3896. pool->accepted++;
  3897. cgpu->diff_accepted += work->work_difficulty;
  3898. total_diff_accepted += work->work_difficulty;
  3899. pool->diff_accepted += work->work_difficulty;
  3900. mutex_unlock(&stats_lock);
  3901. pool->seq_rejects = 0;
  3902. cgpu->last_share_pool = pool->pool_no;
  3903. cgpu->last_share_pool_time = time(NULL);
  3904. cgpu->last_share_diff = work->work_difficulty;
  3905. pool->last_share_time = cgpu->last_share_pool_time;
  3906. pool->last_share_diff = work->work_difficulty;
  3907. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3908. if (!QUIET) {
  3909. if (total_pools > 1)
  3910. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  3911. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  3912. else
  3913. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  3914. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  3915. }
  3916. sharelog("accept", work);
  3917. if (opt_shares && total_diff_accepted >= opt_shares) {
  3918. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  3919. kill_work();
  3920. return;
  3921. }
  3922. /* Detect if a pool that has been temporarily disabled for
  3923. * continually rejecting shares has started accepting shares.
  3924. * This will only happen with the work returned from a
  3925. * longpoll */
  3926. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3927. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3928. enable_pool(pool);
  3929. switch_pools(NULL);
  3930. }
  3931. /* If we know we found the block we know better than anyone
  3932. * that new work is needed. */
  3933. if (unlikely(work->block))
  3934. restart_threads();
  3935. } else {
  3936. mutex_lock(&stats_lock);
  3937. cgpu->rejected++;
  3938. total_rejected++;
  3939. pool->rejected++;
  3940. cgpu->diff_rejected += work->work_difficulty;
  3941. total_diff_rejected += work->work_difficulty;
  3942. pool->diff_rejected += work->work_difficulty;
  3943. pool->seq_rejects++;
  3944. mutex_unlock(&stats_lock);
  3945. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  3946. if (!QUIET) {
  3947. char where[20];
  3948. char disposition[36] = "reject";
  3949. char reason[32];
  3950. strcpy(reason, "");
  3951. if (total_pools > 1)
  3952. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  3953. else
  3954. strcpy(where, "");
  3955. if (!work->gbt)
  3956. res = json_object_get(val, "reject-reason");
  3957. if (res) {
  3958. const char *reasontmp = json_string_value(res);
  3959. size_t reasonLen = strlen(reasontmp);
  3960. if (reasonLen > 28)
  3961. reasonLen = 28;
  3962. reason[0] = ' '; reason[1] = '(';
  3963. cg_memcpy(2 + reason, reasontmp, reasonLen);
  3964. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  3965. cg_memcpy(disposition + 7, reasontmp, reasonLen);
  3966. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  3967. } else if (work->stratum && err) {
  3968. if (json_is_array(err)) {
  3969. json_t *reason_val = json_array_get(err, 1);
  3970. char *reason_str;
  3971. if (reason_val && json_is_string(reason_val)) {
  3972. reason_str = (char *)json_string_value(reason_val);
  3973. snprintf(reason, 31, " (%s)", reason_str);
  3974. }
  3975. } else if (json_is_string(err)) {
  3976. const char *s = json_string_value(err);
  3977. snprintf(reason, 31, " (%s)", s);
  3978. }
  3979. }
  3980. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  3981. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  3982. sharelog(disposition, work);
  3983. }
  3984. /* Once we have more than a nominal amount of sequential rejects,
  3985. * at least 10 and more than 3 mins at the current utility,
  3986. * disable the pool because some pool error is likely to have
  3987. * ensued. Do not do this if we know the share just happened to
  3988. * be stale due to networking delays.
  3989. */
  3990. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  3991. double utility = total_accepted / total_secs * 60;
  3992. if (pool->seq_rejects > utility * 3 && enabled_pools > 1) {
  3993. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  3994. pool->pool_no, pool->seq_rejects);
  3995. reject_pool(pool);
  3996. if (pool == current_pool())
  3997. switch_pools(NULL);
  3998. pool->seq_rejects = 0;
  3999. }
  4000. }
  4001. }
  4002. }
  4003. static void show_hash(struct work *work, char *hashshow)
  4004. {
  4005. unsigned char rhash[32];
  4006. char diffdisp[16];
  4007. unsigned long h32;
  4008. uint32_t *hash32;
  4009. uint64_t uintdiff;
  4010. int ofs;
  4011. swab256(rhash, work->hash);
  4012. for (ofs = 0; ofs <= 28; ofs ++) {
  4013. if (rhash[ofs])
  4014. break;
  4015. }
  4016. hash32 = (uint32_t *)(rhash + ofs);
  4017. h32 = be32toh(*hash32);
  4018. uintdiff = round(work->work_difficulty);
  4019. suffix_string(work->share_diff, diffdisp, sizeof (diffdisp), 0);
  4020. snprintf(hashshow, 64, "%08lx Diff %s/%"PRIu64"%s", h32, diffdisp, uintdiff,
  4021. work->block? " BLOCK!" : "");
  4022. }
  4023. #ifdef HAVE_LIBCURL
  4024. static void text_print_status(int thr_id)
  4025. {
  4026. struct cgpu_info *cgpu;
  4027. char logline[256];
  4028. cgpu = get_thr_cgpu(thr_id);
  4029. if (cgpu) {
  4030. get_statline(logline, sizeof(logline), cgpu);
  4031. printf("%s\n", logline);
  4032. }
  4033. }
  4034. static void print_status(int thr_id)
  4035. {
  4036. if (!curses_active)
  4037. text_print_status(thr_id);
  4038. }
  4039. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  4040. {
  4041. json_t *val, *res, *err;
  4042. char *s;
  4043. bool rc = false;
  4044. int thr_id = work->thr_id;
  4045. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  4046. struct pool *pool = work->pool;
  4047. int rolltime;
  4048. struct timeval tv_submit, tv_submit_reply;
  4049. char hashshow[64 + 4] = "";
  4050. char worktime[200] = "";
  4051. struct timeval now;
  4052. double dev_runtime;
  4053. char gbt_block[1024], varint[12];
  4054. unsigned char data[80];
  4055. /* build JSON-RPC request */
  4056. flip80(data, work->data);
  4057. __bin2hex(gbt_block, data, 80); // 160 length
  4058. if (work->gbt_txns < 0xfd) {
  4059. uint8_t val8 = work->gbt_txns;
  4060. __bin2hex(varint, (const unsigned char *)&val8, 1);
  4061. } else if (work->gbt_txns <= 0xffff) {
  4062. uint16_t val16 = htole16(work->gbt_txns);
  4063. strcat(gbt_block, "fd"); // +2
  4064. __bin2hex(varint, (const unsigned char *)&val16, 2);
  4065. } else {
  4066. uint32_t val32 = htole32(work->gbt_txns);
  4067. strcat(gbt_block, "fe"); // +2
  4068. __bin2hex(varint, (const unsigned char *)&val32, 4);
  4069. }
  4070. strcat(gbt_block, varint); // +8 max
  4071. strcat(gbt_block, work->coinbase);
  4072. s = cgmalloc(1024);
  4073. sprintf(s, "{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"%s", gbt_block);
  4074. /* Has submit/coinbase support */
  4075. if (!pool->has_gbt) {
  4076. cg_rlock(&pool->gbt_lock);
  4077. if (pool->txn_data)
  4078. s = realloc_strcat(s, pool->txn_data);
  4079. cg_runlock(&pool->gbt_lock);
  4080. }
  4081. if (work->job_id) {
  4082. s = realloc_strcat(s, "\", {\"workid\": \"");
  4083. s = realloc_strcat(s, work->job_id);
  4084. s = realloc_strcat(s, "\"}]}");
  4085. } else
  4086. s = realloc_strcat(s, "\"]}");
  4087. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  4088. s = realloc_strcat(s, "\n");
  4089. cgtime(&tv_submit);
  4090. /* issue JSON-RPC request */
  4091. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  4092. cgtime(&tv_submit_reply);
  4093. free(s);
  4094. if (unlikely(!val)) {
  4095. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4096. if (!pool_tset(pool, &pool->submit_fail)) {
  4097. total_ro++;
  4098. pool->remotefail_occasions++;
  4099. if (opt_lowmem) {
  4100. applog(LOG_WARNING, "Pool %d communication failure, discarding shares", pool->pool_no);
  4101. goto out;
  4102. }
  4103. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4104. }
  4105. cgsleep_ms(5000);
  4106. goto out;
  4107. } else if (pool_tclear(pool, &pool->submit_fail))
  4108. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4109. res = json_object_get(val, "result");
  4110. err = json_object_get(val, "error");
  4111. if (!QUIET) {
  4112. show_hash(work, hashshow);
  4113. if (opt_worktime) {
  4114. char workclone[20];
  4115. struct tm *tm, tm_getwork, tm_submit_reply;
  4116. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4117. (struct timeval *)&(work->tv_getwork));
  4118. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4119. (struct timeval *)&(work->tv_getwork_reply));
  4120. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4121. (struct timeval *)&(work->tv_work_start));
  4122. double work_to_submit = tdiff(&tv_submit,
  4123. (struct timeval *)&(work->tv_work_found));
  4124. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  4125. int diffplaces = 3;
  4126. time_t tmp_time = work->tv_getwork.tv_sec;
  4127. tm = localtime(&tmp_time);
  4128. cg_memcpy(&tm_getwork, tm, sizeof(struct tm));
  4129. tmp_time = tv_submit_reply.tv_sec;
  4130. tm = localtime(&tmp_time);
  4131. cg_memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4132. if (work->clone) {
  4133. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4134. tdiff((struct timeval *)&(work->tv_cloned),
  4135. (struct timeval *)&(work->tv_getwork_reply)));
  4136. }
  4137. else
  4138. strcpy(workclone, "O");
  4139. if (work->work_difficulty < 1)
  4140. diffplaces = 6;
  4141. snprintf(worktime, sizeof(worktime),
  4142. " <-%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",
  4143. (unsigned long)be32toh(*(uint32_t *)&(work->data[28])),
  4144. (unsigned long)be32toh(*(uint32_t *)&(work->data[24])),
  4145. work->getwork_mode, diffplaces, work->work_difficulty,
  4146. tm_getwork.tm_hour, tm_getwork.tm_min,
  4147. tm_getwork.tm_sec, getwork_time, workclone,
  4148. getwork_to_work, work_time, work_to_submit, submit_time,
  4149. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4150. tm_submit_reply.tm_sec);
  4151. }
  4152. }
  4153. share_result(val, res, err, work, hashshow, resubmit, worktime);
  4154. if (cgpu->dev_start_tv.tv_sec == 0)
  4155. dev_runtime = total_secs;
  4156. else {
  4157. cgtime(&now);
  4158. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  4159. }
  4160. if (dev_runtime < 1.0)
  4161. dev_runtime = 1.0;
  4162. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  4163. if (!opt_realquiet)
  4164. print_status(thr_id);
  4165. if (!want_per_device_stats) {
  4166. char logline[256];
  4167. get_statline(logline, sizeof(logline), cgpu);
  4168. applog(LOG_INFO, "%s", logline);
  4169. }
  4170. json_decref(val);
  4171. rc = true;
  4172. out:
  4173. return rc;
  4174. }
  4175. #endif /* HAVE_LIBCURL */
  4176. /* Specifies whether we can use this pool for work or not. */
  4177. static bool pool_unusable(struct pool *pool)
  4178. {
  4179. if (pool->idle)
  4180. return true;
  4181. if (pool->enabled != POOL_ENABLED)
  4182. return true;
  4183. if (pool->has_stratum && (!pool->stratum_active || !pool->stratum_notify))
  4184. return true;
  4185. return false;
  4186. }
  4187. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4188. * rolling average per 10 minutes and if pools start getting more, it biases
  4189. * away from them to distribute work evenly. The share count is reset to the
  4190. * rolling average every 10 minutes to not send all work to one pool after it
  4191. * has been disabled/out for an extended period. */
  4192. static struct pool *select_balanced(struct pool *cp)
  4193. {
  4194. int i, lowest = cp->shares;
  4195. struct pool *ret = cp;
  4196. for (i = 0; i < total_pools; i++) {
  4197. struct pool *pool = pools[i];
  4198. if (pool_unusable(pool))
  4199. continue;
  4200. if (pool->shares < lowest) {
  4201. lowest = pool->shares;
  4202. ret = pool;
  4203. }
  4204. }
  4205. ret->shares++;
  4206. return ret;
  4207. }
  4208. static struct pool *priority_pool(int choice);
  4209. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4210. * it has any quota left. */
  4211. static inline struct pool *select_pool(void)
  4212. {
  4213. static int rotating_pool = 0;
  4214. struct pool *pool, *cp;
  4215. bool avail = false;
  4216. int tested, i;
  4217. cp = current_pool();
  4218. if (pool_strategy == POOL_BALANCE) {
  4219. pool = select_balanced(cp);
  4220. goto out;
  4221. }
  4222. if (pool_strategy != POOL_LOADBALANCE) {
  4223. pool = cp;
  4224. goto out;
  4225. } else
  4226. pool = NULL;
  4227. for (i = 0; i < total_pools; i++) {
  4228. struct pool *tp = pools[i];
  4229. if (tp->quota_used < tp->quota_gcd) {
  4230. avail = true;
  4231. break;
  4232. }
  4233. }
  4234. /* There are no pools with quota, so reset them. */
  4235. if (!avail) {
  4236. for (i = 0; i < total_pools; i++)
  4237. pools[i]->quota_used = 0;
  4238. if (++rotating_pool >= total_pools)
  4239. rotating_pool = 0;
  4240. }
  4241. /* Try to find the first pool in the rotation that is usable */
  4242. tested = 0;
  4243. while (!pool && tested++ < total_pools) {
  4244. pool = pools[rotating_pool];
  4245. if (pool->quota_used++ < pool->quota_gcd) {
  4246. if (!pool_unusable(pool))
  4247. break;
  4248. }
  4249. pool = NULL;
  4250. if (++rotating_pool >= total_pools)
  4251. rotating_pool = 0;
  4252. }
  4253. /* If there are no alive pools with quota, choose according to
  4254. * priority. */
  4255. if (!pool) {
  4256. for (i = 0; i < total_pools; i++) {
  4257. struct pool *tp = priority_pool(i);
  4258. if (!pool_unusable(tp)) {
  4259. pool = tp;
  4260. break;
  4261. }
  4262. }
  4263. }
  4264. /* If still nothing is usable, use the current pool */
  4265. if (!pool)
  4266. pool = cp;
  4267. out:
  4268. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4269. return pool;
  4270. }
  4271. /* truediffone == 0x00000000FFFF0000000000000000000000000000000000000000000000000000
  4272. * Generate a 256 bit binary LE target by cutting up diff into 64 bit sized
  4273. * portions or vice versa. */
  4274. static const double truediffone = 26959535291011309493156476344723991336010898738574164086137773096960.0;
  4275. static const double bits192 = 6277101735386680763835789423207666416102355444464034512896.0;
  4276. static const double bits128 = 340282366920938463463374607431768211456.0;
  4277. static const double bits64 = 18446744073709551616.0;
  4278. /* Converts a little endian 256 bit value to a double */
  4279. static double le256todouble(const void *target)
  4280. {
  4281. uint64_t *data64;
  4282. double dcut64;
  4283. data64 = (uint64_t *)(target + 24);
  4284. dcut64 = le64toh(*data64) * bits192;
  4285. data64 = (uint64_t *)(target + 16);
  4286. dcut64 += le64toh(*data64) * bits128;
  4287. data64 = (uint64_t *)(target + 8);
  4288. dcut64 += le64toh(*data64) * bits64;
  4289. data64 = (uint64_t *)(target);
  4290. dcut64 += le64toh(*data64);
  4291. return dcut64;
  4292. }
  4293. static double diff_from_target(void *target)
  4294. {
  4295. double d64, dcut64;
  4296. d64 = truediffone;
  4297. dcut64 = le256todouble(target);
  4298. if (unlikely(!dcut64))
  4299. dcut64 = 1;
  4300. return d64 / dcut64;
  4301. }
  4302. /*
  4303. * Calculate the work->work_difficulty based on the work->target
  4304. */
  4305. static void calc_diff(struct work *work, double known)
  4306. {
  4307. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4308. double difficulty;
  4309. uint64_t uintdiff;
  4310. if (known)
  4311. work->work_difficulty = known;
  4312. else
  4313. work->work_difficulty = diff_from_target(work->target);
  4314. difficulty = work->work_difficulty;
  4315. pool_stats->last_diff = difficulty;
  4316. uintdiff = round(difficulty);
  4317. suffix_string(uintdiff, work->pool->diff, sizeof(work->pool->diff), 0);
  4318. if (difficulty == pool_stats->min_diff)
  4319. pool_stats->min_diff_count++;
  4320. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4321. pool_stats->min_diff = difficulty;
  4322. pool_stats->min_diff_count = 1;
  4323. }
  4324. if (difficulty == pool_stats->max_diff)
  4325. pool_stats->max_diff_count++;
  4326. else if (difficulty > pool_stats->max_diff) {
  4327. pool_stats->max_diff = difficulty;
  4328. pool_stats->max_diff_count = 1;
  4329. }
  4330. }
  4331. static unsigned char bench_hidiff_bins[16][160];
  4332. static unsigned char bench_lodiff_bins[16][160];
  4333. static unsigned char bench_target[32];
  4334. /* Iterate over the lo and hi diff benchmark work items such that we find one
  4335. * diff 32+ share every 32 work items. */
  4336. static void get_benchmark_work(struct work *work)
  4337. {
  4338. work->work_difficulty = 32;
  4339. cg_memcpy(work->target, bench_target, 32);
  4340. work->drv_rolllimit = 0;
  4341. work->mandatory = true;
  4342. work->pool = pools[0];
  4343. cgtime(&work->tv_getwork);
  4344. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4345. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4346. }
  4347. static void benchfile_dspwork(struct work *work, uint32_t nonce)
  4348. {
  4349. char buf[1024];
  4350. uint32_t dn;
  4351. int i;
  4352. dn = 0;
  4353. for (i = 0; i < 4; i++) {
  4354. dn *= 0x100;
  4355. dn += nonce & 0xff;
  4356. nonce /= 0x100;
  4357. }
  4358. if ((sizeof(work->data) * 2 + 1) > sizeof(buf))
  4359. quithere(1, "BENCHFILE Invalid buf size");
  4360. __bin2hex(buf, work->data, sizeof(work->data));
  4361. applog(LOG_ERR, "BENCHFILE nonce %u=0x%08x for work=%s",
  4362. (unsigned int)dn, (unsigned int)dn, buf);
  4363. }
  4364. static bool benchfile_get_work(struct work *work)
  4365. {
  4366. char buf[1024];
  4367. char item[1024];
  4368. bool got = false;
  4369. if (!benchfile_in) {
  4370. if (opt_benchfile)
  4371. benchfile_in = fopen(opt_benchfile, "r");
  4372. else
  4373. quit(1, "BENCHFILE Invalid benchfile NULL");
  4374. if (!benchfile_in)
  4375. quit(1, "BENCHFILE Failed to open benchfile '%s'", opt_benchfile);
  4376. benchfile_line = 0;
  4377. if (!fgets(buf, 1024, benchfile_in))
  4378. quit(1, "BENCHFILE Failed to read benchfile '%s'", opt_benchfile);
  4379. got = true;
  4380. benchfile_work = 0;
  4381. }
  4382. if (!got) {
  4383. if (!fgets(buf, 1024, benchfile_in)) {
  4384. if (benchfile_work == 0)
  4385. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  4386. fclose(benchfile_in);
  4387. benchfile_in = NULL;
  4388. return benchfile_get_work(work);
  4389. }
  4390. }
  4391. do {
  4392. benchfile_line++;
  4393. // Empty lines and lines starting with '#' or '/' are ignored
  4394. if (*buf != '\0' && *buf != '#' && *buf != '/') {
  4395. char *commas[BENCHWORK_COUNT];
  4396. int i, j, len;
  4397. long nonce_time;
  4398. commas[0] = buf;
  4399. for (i = 1; i < BENCHWORK_COUNT; i++) {
  4400. commas[i] = strchr(commas[i-1], ',');
  4401. if (!commas[i]) {
  4402. quit(1, "BENCHFILE Invalid input file line %d"
  4403. " - field count is %d but should be %d",
  4404. benchfile_line, i, BENCHWORK_COUNT);
  4405. }
  4406. len = commas[i] - commas[i-1];
  4407. if (benchfile_data[i-1].length &&
  4408. (len != benchfile_data[i-1].length)) {
  4409. quit(1, "BENCHFILE Invalid input file line %d "
  4410. "field %d (%s) length is %d but should be %d",
  4411. benchfile_line, i,
  4412. benchfile_data[i-1].name,
  4413. len, benchfile_data[i-1].length);
  4414. }
  4415. *(commas[i]++) = '\0';
  4416. }
  4417. // NonceTime may have LF's etc
  4418. len = strlen(commas[BENCHWORK_NONCETIME]);
  4419. if (len < benchfile_data[BENCHWORK_NONCETIME].length) {
  4420. quit(1, "BENCHFILE Invalid input file line %d field %d"
  4421. " (%s) length is %d but should be least %d",
  4422. benchfile_line, BENCHWORK_NONCETIME+1,
  4423. benchfile_data[BENCHWORK_NONCETIME].name, len,
  4424. benchfile_data[BENCHWORK_NONCETIME].length);
  4425. }
  4426. sprintf(item, "0000000%c", commas[BENCHWORK_VERSION][0]);
  4427. j = strlen(item);
  4428. for (i = benchfile_data[BENCHWORK_PREVHASH].length-8; i >= 0; i -= 8) {
  4429. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_PREVHASH][i]);
  4430. j += 8;
  4431. }
  4432. for (i = benchfile_data[BENCHWORK_MERKLEROOT].length-8; i >= 0; i -= 8) {
  4433. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_MERKLEROOT][i]);
  4434. j += 8;
  4435. }
  4436. nonce_time = atol(commas[BENCHWORK_NONCETIME]);
  4437. sprintf(&(item[j]), "%08lx", nonce_time);
  4438. j += 8;
  4439. strcpy(&(item[j]), commas[BENCHWORK_DIFFBITS]);
  4440. j += benchfile_data[BENCHWORK_DIFFBITS].length;
  4441. memset(work, 0, sizeof(*work));
  4442. hex2bin(work->data, item, j >> 1);
  4443. calc_midstate(work->pool, work);
  4444. benchfile_work++;
  4445. return true;
  4446. }
  4447. } while (fgets(buf, 1024, benchfile_in));
  4448. if (benchfile_work == 0)
  4449. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  4450. fclose(benchfile_in);
  4451. benchfile_in = NULL;
  4452. return benchfile_get_work(work);
  4453. }
  4454. static void get_benchfile_work(struct work *work)
  4455. {
  4456. benchfile_get_work(work);
  4457. work->mandatory = true;
  4458. work->pool = pools[0];
  4459. cgtime(&work->tv_getwork);
  4460. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4461. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4462. calc_diff(work, 0);
  4463. }
  4464. #ifdef HAVE_CURSES
  4465. static void disable_curses_windows(void)
  4466. {
  4467. leaveok(logwin, false);
  4468. leaveok(statuswin, false);
  4469. leaveok(mainwin, false);
  4470. nocbreak();
  4471. echo();
  4472. delwin(logwin);
  4473. delwin(statuswin);
  4474. }
  4475. /* Force locking of curses console_lock on shutdown since a dead thread might
  4476. * have grabbed the lock. */
  4477. static bool curses_active_forcelocked(void)
  4478. {
  4479. bool ret;
  4480. mutex_trylock(&console_lock);
  4481. ret = curses_active;
  4482. if (!ret)
  4483. unlock_curses();
  4484. return ret;
  4485. }
  4486. static void disable_curses(void)
  4487. {
  4488. if (curses_active_forcelocked()) {
  4489. use_curses = false;
  4490. curses_active = false;
  4491. disable_curses_windows();
  4492. delwin(mainwin);
  4493. endwin();
  4494. #ifdef WIN32
  4495. // Move the cursor to after curses output.
  4496. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4497. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4498. COORD coord;
  4499. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4500. coord.X = 0;
  4501. coord.Y = csbi.dwSize.Y - 1;
  4502. SetConsoleCursorPosition(hout, coord);
  4503. }
  4504. #endif
  4505. unlock_curses();
  4506. }
  4507. }
  4508. #endif
  4509. static void kill_timeout(struct thr_info *thr)
  4510. {
  4511. cg_completion_timeout(&thr_info_cancel, thr, 1000);
  4512. }
  4513. static void kill_mining(void)
  4514. {
  4515. struct thr_info *thr;
  4516. int i;
  4517. forcelog(LOG_DEBUG, "Killing off mining threads");
  4518. /* Kill the mining threads*/
  4519. for (i = 0; i < mining_threads; i++) {
  4520. pthread_t *pth = NULL;
  4521. thr = get_thread(i);
  4522. if (thr && PTH(thr) != 0L)
  4523. pth = &thr->pth;
  4524. thr_info_cancel(thr);
  4525. #if !defined __MINGW32__ || __WINPTHREADS_VERSION >= 0x00050000
  4526. if (pth && *pth)
  4527. pthread_join(*pth, NULL);
  4528. #else
  4529. if (pth && pth->p)
  4530. pthread_join(*pth, NULL);
  4531. #endif
  4532. }
  4533. }
  4534. static void wait_mining(void)
  4535. {
  4536. struct thr_info *thr;
  4537. int i;
  4538. forcelog(LOG_DEBUG, "Waiting on mining threads");
  4539. /* Kill the mining threads*/
  4540. for (i = 0; i < mining_threads; i++) {
  4541. pthread_t *pth = NULL;
  4542. thr = get_thread(i);
  4543. if (thr && PTH(thr) != 0L)
  4544. pth = &thr->pth;
  4545. if (pth && *pth)
  4546. pthread_join(*pth, NULL);
  4547. }
  4548. }
  4549. static void __kill_work(void)
  4550. {
  4551. struct thr_info *thr;
  4552. int i;
  4553. if (!successful_connect)
  4554. return;
  4555. forcelog(LOG_INFO, "Received kill message");
  4556. #ifdef USE_USBUTILS
  4557. /* Best to get rid of it first so it doesn't
  4558. * try to create any new devices */
  4559. forcelog(LOG_DEBUG, "Killing off HotPlug thread");
  4560. thr = &control_thr[hotplug_thr_id];
  4561. kill_timeout(thr);
  4562. #endif
  4563. forcelog(LOG_DEBUG, "Killing off watchpool thread");
  4564. /* Kill the watchpool thread */
  4565. thr = &control_thr[watchpool_thr_id];
  4566. kill_timeout(thr);
  4567. forcelog(LOG_DEBUG, "Killing off watchdog thread");
  4568. /* Kill the watchdog thread */
  4569. thr = &control_thr[watchdog_thr_id];
  4570. kill_timeout(thr);
  4571. forcelog(LOG_DEBUG, "Shutting down mining threads");
  4572. for (i = 0; i < mining_threads; i++) {
  4573. struct cgpu_info *cgpu;
  4574. thr = get_thread(i);
  4575. if (!thr)
  4576. continue;
  4577. cgpu = thr->cgpu;
  4578. if (!cgpu)
  4579. continue;
  4580. cgpu->shutdown = true;
  4581. }
  4582. /* Give the threads a chance to shut down gracefully */
  4583. cg_completion_timeout(&wait_mining, NULL, 5000);
  4584. /* Kill the threads and wait for them to return if not */
  4585. cg_completion_timeout(&kill_mining, NULL, 5000);
  4586. /* Stop the others */
  4587. forcelog(LOG_DEBUG, "Killing off API thread");
  4588. thr = &control_thr[api_thr_id];
  4589. kill_timeout(thr);
  4590. #ifdef USE_USBUTILS
  4591. /* Release USB resources in case it's a restart
  4592. * and not a QUIT */
  4593. forcelog(LOG_DEBUG, "Releasing all USB devices");
  4594. cg_completion_timeout(&usb_cleanup, NULL, 1000);
  4595. forcelog(LOG_DEBUG, "Killing off usbres thread");
  4596. thr = &control_thr[usbres_thr_id];
  4597. kill_timeout(thr);
  4598. #endif
  4599. }
  4600. /* This should be the common exit path */
  4601. void kill_work(void)
  4602. {
  4603. cg_completion_timeout(&__kill_work, NULL, 10000);
  4604. quit(0, "Shutdown signal received.");
  4605. }
  4606. static
  4607. #ifdef WIN32
  4608. const
  4609. #endif
  4610. char **initial_args;
  4611. static void *raise_thread(void __maybe_unused *arg)
  4612. {
  4613. raise(SIGTERM);
  4614. return NULL;
  4615. }
  4616. /* This provides a mechanism for driver threads to initiate a shutdown without
  4617. * the cyclical problem of the shutdown path being cancelled while the driver
  4618. * thread shuts down.*/
  4619. void raise_cgminer(void)
  4620. {
  4621. pthread_t pth;
  4622. pthread_create(&pth, NULL, raise_thread, NULL);
  4623. }
  4624. static void clean_up(bool restarting);
  4625. void app_restart(void)
  4626. {
  4627. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4628. #ifdef USE_LIBSYSTEMD
  4629. sd_notify(false, "RELOADING=1\n"
  4630. "STATUS=Restarting...");
  4631. #endif
  4632. cg_completion_timeout(&__kill_work, NULL, 5000);
  4633. clean_up(true);
  4634. #if defined(unix) || defined(__APPLE__)
  4635. if (forkpid > 0) {
  4636. kill(forkpid, SIGTERM);
  4637. forkpid = 0;
  4638. }
  4639. #endif
  4640. execv(initial_args[0], (EXECV_2ND_ARG_TYPE)initial_args);
  4641. applog(LOG_WARNING, "Failed to restart application");
  4642. }
  4643. static void sighandler(int __maybe_unused sig)
  4644. {
  4645. /* Restore signal handlers so we can still quit if kill_work fails */
  4646. sigaction(SIGTERM, &termhandler, NULL);
  4647. sigaction(SIGINT, &inthandler, NULL);
  4648. sigaction(SIGABRT, &abrthandler, NULL);
  4649. kill_work();
  4650. }
  4651. static void _stage_work(struct work *work);
  4652. #define stage_work(WORK) do { \
  4653. _stage_work(WORK); \
  4654. WORK = NULL; \
  4655. } while (0)
  4656. /* Adjust an existing char ntime field with a relative noffset */
  4657. static void modify_ntime(char *ntime, int noffset)
  4658. {
  4659. unsigned char bin[4];
  4660. uint32_t h32, *be32 = (uint32_t *)bin;
  4661. hex2bin(bin, ntime, 4);
  4662. h32 = be32toh(*be32) + noffset;
  4663. *be32 = htobe32(h32);
  4664. __bin2hex(ntime, bin, 4);
  4665. }
  4666. void roll_work(struct work *work)
  4667. {
  4668. uint32_t *work_ntime;
  4669. uint32_t ntime;
  4670. work_ntime = (uint32_t *)(work->data + 68);
  4671. ntime = be32toh(*work_ntime);
  4672. ntime++;
  4673. *work_ntime = htobe32(ntime);
  4674. local_work++;
  4675. work->rolls++;
  4676. work->nonce = 0;
  4677. applog(LOG_DEBUG, "Successfully rolled work");
  4678. /* Change the ntime field if this is stratum work */
  4679. if (work->ntime)
  4680. modify_ntime(work->ntime, 1);
  4681. /* This is now a different work item so it needs a different ID for the
  4682. * hashtable */
  4683. work->id = total_work_inc();
  4684. }
  4685. void roll_work_ntime(struct work *work, int noffset)
  4686. {
  4687. uint32_t *work_ntime;
  4688. uint32_t ntime;
  4689. work_ntime = (uint32_t *)(work->data + 68);
  4690. ntime = be32toh(*work_ntime);
  4691. ntime += noffset;
  4692. *work_ntime = htobe32(ntime);
  4693. local_work++;
  4694. work->rolls += noffset;
  4695. work->nonce = 0;
  4696. applog(LOG_DEBUG, "Successfully rolled work");
  4697. /* Change the ntime field if this is stratum work */
  4698. if (work->ntime)
  4699. modify_ntime(work->ntime, noffset);
  4700. /* This is now a different work item so it needs a different ID for the
  4701. * hashtable */
  4702. work->id = total_work_inc();
  4703. }
  4704. struct work *make_clone(struct work *work)
  4705. {
  4706. struct work *work_clone = copy_work(work);
  4707. work_clone->clone = true;
  4708. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4709. work_clone->longpoll = false;
  4710. work_clone->mandatory = false;
  4711. /* Make cloned work appear slightly older to bias towards keeping the
  4712. * master work item which can be further rolled */
  4713. work_clone->tv_staged.tv_sec -= 1;
  4714. return work_clone;
  4715. }
  4716. #ifdef HAVE_LIBCURL
  4717. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4718. * this pool. */
  4719. static void recruit_curl(struct pool *pool)
  4720. {
  4721. struct curl_ent *ce = cgcalloc(sizeof(struct curl_ent), 1);
  4722. ce->curl = curl_easy_init();
  4723. if (unlikely(!ce->curl))
  4724. quit(1, "Failed to init in recruit_curl");
  4725. list_add(&ce->node, &pool->curlring);
  4726. pool->curls++;
  4727. }
  4728. /* Grab an available curl if there is one. If not, then recruit extra curls
  4729. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4730. * and there are already 5 curls in circulation. Limit total number to the
  4731. * number of mining threads per pool as well to prevent blasting a pool during
  4732. * network delays/outages. */
  4733. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4734. {
  4735. int curl_limit = opt_delaynet ? 5 : (mining_threads + max_queue) * 2;
  4736. bool recruited = false;
  4737. struct curl_ent *ce;
  4738. mutex_lock(&pool->pool_lock);
  4739. retry:
  4740. if (!pool->curls) {
  4741. recruit_curl(pool);
  4742. recruited = true;
  4743. } else if (list_empty(&pool->curlring)) {
  4744. if (pool->curls >= curl_limit) {
  4745. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4746. goto retry;
  4747. } else {
  4748. recruit_curl(pool);
  4749. recruited = true;
  4750. }
  4751. }
  4752. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  4753. list_del(&ce->node);
  4754. mutex_unlock(&pool->pool_lock);
  4755. if (recruited)
  4756. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4757. return ce;
  4758. }
  4759. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4760. {
  4761. mutex_lock(&pool->pool_lock);
  4762. list_add_tail(&ce->node, &pool->curlring);
  4763. cgtime(&ce->tv);
  4764. pthread_cond_broadcast(&pool->cr_cond);
  4765. mutex_unlock(&pool->pool_lock);
  4766. }
  4767. static bool stale_work(struct work *work, bool share);
  4768. static inline bool should_roll(struct work *work)
  4769. {
  4770. struct timeval now;
  4771. time_t expiry;
  4772. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  4773. return false;
  4774. if (work->rolltime > max_scantime)
  4775. expiry = work->rolltime;
  4776. else
  4777. expiry = max_scantime;
  4778. expiry = expiry * 2 / 3;
  4779. /* We shouldn't roll if we're unlikely to get one shares' duration
  4780. * work out of doing so */
  4781. cgtime(&now);
  4782. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4783. return false;
  4784. return true;
  4785. }
  4786. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4787. * reject blocks as invalid. */
  4788. static inline bool can_roll(struct work *work)
  4789. {
  4790. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  4791. work->rolls < 7000 && !stale_work(work, false));
  4792. }
  4793. static void *submit_work_thread(void *userdata)
  4794. {
  4795. struct work *work = (struct work *)userdata;
  4796. struct pool *pool = work->pool;
  4797. bool resubmit = false;
  4798. struct curl_ent *ce;
  4799. pthread_detach(pthread_self());
  4800. RenameThread("SubmitWork");
  4801. applog(LOG_DEBUG, "Creating extra submit work thread");
  4802. ce = pop_curl_entry(pool);
  4803. /* submit solution to bitcoin via JSON-RPC */
  4804. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  4805. if (opt_lowmem) {
  4806. applog(LOG_NOTICE, "Pool %d share being discarded to minimise memory cache", pool->pool_no);
  4807. break;
  4808. }
  4809. resubmit = true;
  4810. if (stale_work(work, true)) {
  4811. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  4812. mutex_lock(&stats_lock);
  4813. total_stale++;
  4814. pool->stale_shares++;
  4815. total_diff_stale += work->work_difficulty;
  4816. pool->diff_stale += work->work_difficulty;
  4817. mutex_unlock(&stats_lock);
  4818. free_work(work);
  4819. break;
  4820. }
  4821. /* pause, then restart work-request loop */
  4822. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  4823. }
  4824. push_curl_entry(ce, pool);
  4825. return NULL;
  4826. }
  4827. /* Clones work by rolling it if possible, and returning a clone instead of the
  4828. * original work item which gets staged again to possibly be rolled again in
  4829. * the future */
  4830. static struct work *clone_work(struct work *work)
  4831. {
  4832. int mrs = mining_threads + max_queue - total_staged();
  4833. struct work *work_clone;
  4834. bool cloned;
  4835. if (mrs < 1)
  4836. return work;
  4837. cloned = false;
  4838. work_clone = make_clone(work);
  4839. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4840. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4841. stage_work(work_clone);
  4842. roll_work(work);
  4843. work_clone = make_clone(work);
  4844. /* Roll it again to prevent duplicates should this be used
  4845. * directly later on */
  4846. roll_work(work);
  4847. cloned = true;
  4848. }
  4849. if (cloned) {
  4850. stage_work(work);
  4851. return work_clone;
  4852. }
  4853. free_work(work_clone);
  4854. return work;
  4855. }
  4856. #else /* HAVE_LIBCURL */
  4857. static void *submit_work_thread(void __maybe_unused *userdata)
  4858. {
  4859. pthread_detach(pthread_self());
  4860. return NULL;
  4861. }
  4862. #endif /* HAVE_LIBCURL */
  4863. /* Return an adjusted ntime if we're submitting work that a device has
  4864. * internally offset the ntime. */
  4865. static char *offset_ntime(const char *ntime, int noffset)
  4866. {
  4867. unsigned char bin[4];
  4868. uint32_t h32, *be32 = (uint32_t *)bin;
  4869. hex2bin(bin, ntime, 4);
  4870. h32 = be32toh(*be32) + noffset;
  4871. *be32 = htobe32(h32);
  4872. return bin2hex(bin, 4);
  4873. }
  4874. /* Duplicates any dynamically allocated arrays within the work struct to
  4875. * prevent a copied work struct from freeing ram belonging to another struct */
  4876. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4877. {
  4878. uint32_t id = work->id;
  4879. clean_work(work);
  4880. cg_memcpy(work, base_work, sizeof(struct work));
  4881. /* Keep the unique new id assigned during make_work to prevent copied
  4882. * work from having the same id. */
  4883. work->id = id;
  4884. if (base_work->job_id)
  4885. work->job_id = strdup(base_work->job_id);
  4886. if (base_work->nonce1)
  4887. work->nonce1 = strdup(base_work->nonce1);
  4888. if (base_work->ntime) {
  4889. /* If we are passed an noffset the binary work->data ntime and
  4890. * the work->ntime hex string need to be adjusted. */
  4891. if (noffset) {
  4892. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4893. uint32_t ntime = be32toh(*work_ntime);
  4894. ntime += noffset;
  4895. *work_ntime = htobe32(ntime);
  4896. work->ntime = offset_ntime(base_work->ntime, noffset);
  4897. } else
  4898. work->ntime = strdup(base_work->ntime);
  4899. } else if (noffset) {
  4900. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4901. uint32_t ntime = be32toh(*work_ntime);
  4902. ntime += noffset;
  4903. *work_ntime = htobe32(ntime);
  4904. }
  4905. if (base_work->coinbase)
  4906. work->coinbase = strdup(base_work->coinbase);
  4907. #ifdef USE_BITMAIN_SOC
  4908. work->version = base_work->version;
  4909. #endif
  4910. }
  4911. void set_work_ntime(struct work *work, int ntime)
  4912. {
  4913. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4914. *work_ntime = htobe32(ntime);
  4915. if (work->ntime) {
  4916. free(work->ntime);
  4917. work->ntime = bin2hex((unsigned char *)work_ntime, 4);
  4918. }
  4919. }
  4920. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4921. * for all dynamically allocated arrays within the struct. noffset is used for
  4922. * when a driver has internally rolled the ntime, noffset is a relative value.
  4923. * The macro copy_work() calls this function with an noffset of 0. */
  4924. struct work *copy_work_noffset(struct work *base_work, int noffset)
  4925. {
  4926. struct work *work = make_work();
  4927. _copy_work(work, base_work, noffset);
  4928. return work;
  4929. }
  4930. void pool_died(struct pool *pool)
  4931. {
  4932. if (!pool_tset(pool, &pool->idle)) {
  4933. cgtime(&pool->tv_idle);
  4934. if (pool == current_pool()) {
  4935. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4936. switch_pools(NULL);
  4937. } else
  4938. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4939. }
  4940. }
  4941. static bool stale_work(struct work *work, bool share)
  4942. {
  4943. struct timeval now;
  4944. time_t work_expiry;
  4945. struct pool *pool;
  4946. if (opt_benchmark || opt_benchfile)
  4947. return false;
  4948. if (work->work_block != work_block) {
  4949. applog(LOG_DEBUG, "Work stale due to block mismatch");
  4950. return true;
  4951. }
  4952. /* Technically the rolltime should be correct but some pools
  4953. * advertise a broken expire= that is lower than a meaningful
  4954. * scantime */
  4955. if (work->rolltime > max_scantime)
  4956. work_expiry = work->rolltime;
  4957. else
  4958. work_expiry = max_expiry;
  4959. pool = work->pool;
  4960. if (!share && pool->has_stratum) {
  4961. bool same_job;
  4962. if (!pool->stratum_active || !pool->stratum_notify) {
  4963. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4964. return true;
  4965. }
  4966. same_job = true;
  4967. cg_rlock(&pool->data_lock);
  4968. if (strcmp(work->job_id, pool->swork.job_id))
  4969. same_job = false;
  4970. cg_runlock(&pool->data_lock);
  4971. if (!same_job) {
  4972. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4973. return true;
  4974. }
  4975. }
  4976. if (unlikely(work_expiry < 5))
  4977. work_expiry = 5;
  4978. cgtime(&now);
  4979. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  4980. applog(LOG_DEBUG, "Work stale due to expiry");
  4981. return true;
  4982. }
  4983. return false;
  4984. }
  4985. uint64_t share_diff(const struct work *work)
  4986. {
  4987. bool new_best = false;
  4988. double d64, s64;
  4989. uint64_t ret;
  4990. d64 = truediffone;
  4991. s64 = le256todouble(work->hash);
  4992. if (unlikely(!s64))
  4993. s64 = 0;
  4994. ret = round(d64 / s64);
  4995. cg_wlock(&control_lock);
  4996. if (unlikely(ret > best_diff)) {
  4997. new_best = true;
  4998. best_diff = ret;
  4999. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5000. }
  5001. if (unlikely(ret > work->pool->best_diff))
  5002. work->pool->best_diff = ret;
  5003. cg_wunlock(&control_lock);
  5004. if (unlikely(new_best))
  5005. applog(LOG_INFO, "New best share: %s", best_share);
  5006. return ret;
  5007. }
  5008. static void regen_hash(struct work *work)
  5009. {
  5010. uint32_t *data32 = (uint32_t *)(work->data);
  5011. unsigned char swap[80];
  5012. uint32_t *swap32 = (uint32_t *)swap;
  5013. unsigned char hash1[32];
  5014. flip80(swap32, data32);
  5015. sha256(swap, 80, hash1);
  5016. sha256(hash1, 32, (unsigned char *)(work->hash));
  5017. }
  5018. static bool cnx_needed(struct pool *pool);
  5019. /* Find the pool that currently has the highest priority */
  5020. static struct pool *priority_pool(int choice)
  5021. {
  5022. struct pool *ret = NULL;
  5023. int i;
  5024. for (i = 0; i < total_pools; i++) {
  5025. struct pool *pool = pools[i];
  5026. if (pool->prio == choice) {
  5027. ret = pool;
  5028. break;
  5029. }
  5030. }
  5031. if (unlikely(!ret)) {
  5032. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5033. return pools[choice];
  5034. }
  5035. return ret;
  5036. }
  5037. void switch_pools(struct pool *selected)
  5038. {
  5039. struct pool *pool, *last_pool;
  5040. int i, pool_no, next_pool;
  5041. cg_wlock(&control_lock);
  5042. last_pool = currentpool;
  5043. pool_no = currentpool->pool_no;
  5044. /* Switch selected to pool number 0 and move the rest down */
  5045. if (selected) {
  5046. if (selected->prio != 0) {
  5047. for (i = 0; i < total_pools; i++) {
  5048. pool = pools[i];
  5049. if (pool->prio < selected->prio)
  5050. pool->prio++;
  5051. }
  5052. selected->prio = 0;
  5053. }
  5054. }
  5055. switch (pool_strategy) {
  5056. /* All of these set to the master pool */
  5057. case POOL_BALANCE:
  5058. case POOL_FAILOVER:
  5059. case POOL_LOADBALANCE:
  5060. for (i = 0; i < total_pools; i++) {
  5061. pool = priority_pool(i);
  5062. if (pool_unusable(pool))
  5063. continue;
  5064. pool_no = pool->pool_no;
  5065. break;
  5066. }
  5067. break;
  5068. /* Both of these simply increment and cycle */
  5069. case POOL_ROUNDROBIN:
  5070. case POOL_ROTATE:
  5071. if (selected && !selected->idle) {
  5072. pool_no = selected->pool_no;
  5073. break;
  5074. }
  5075. next_pool = pool_no;
  5076. /* Select the next alive pool */
  5077. for (i = 1; i < total_pools; i++) {
  5078. next_pool++;
  5079. if (next_pool >= total_pools)
  5080. next_pool = 0;
  5081. pool = pools[next_pool];
  5082. if (pool_unusable(pool))
  5083. continue;
  5084. pool_no = next_pool;
  5085. break;
  5086. }
  5087. break;
  5088. default:
  5089. break;
  5090. }
  5091. currentpool = pools[pool_no];
  5092. pool = currentpool;
  5093. cg_wunlock(&control_lock);
  5094. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5095. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5096. clear_pool_work(last_pool);
  5097. }
  5098. mutex_lock(&lp_lock);
  5099. pthread_cond_broadcast(&lp_cond);
  5100. mutex_unlock(&lp_lock);
  5101. }
  5102. void _discard_work(struct work **workptr, const char *file, const char *func, const int line)
  5103. {
  5104. struct work *work = *workptr;
  5105. if (unlikely(!work)) {
  5106. applog(LOG_ERR, "Discard work called with null work from %s %s:%d",
  5107. file, func, line);
  5108. return;
  5109. }
  5110. if (!work->clone && !work->rolls && !work->mined) {
  5111. if (work->pool) {
  5112. work->pool->discarded_work++;
  5113. work->pool->quota_used--;
  5114. work->pool->works--;
  5115. }
  5116. total_discarded++;
  5117. applog(LOG_DEBUG, "Discarded work");
  5118. } else
  5119. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5120. _free_work(workptr, file, func, line);
  5121. }
  5122. static void wake_gws(void)
  5123. {
  5124. mutex_lock(stgd_lock);
  5125. pthread_cond_signal(&gws_cond);
  5126. mutex_unlock(stgd_lock);
  5127. }
  5128. static void discard_stale(void)
  5129. {
  5130. struct work *work, *tmp;
  5131. int stale = 0;
  5132. mutex_lock(stgd_lock);
  5133. HASH_ITER(hh, staged_work, work, tmp) {
  5134. if (stale_work(work, false)) {
  5135. HASH_DEL(staged_work, work);
  5136. discard_work(work);
  5137. stale++;
  5138. }
  5139. }
  5140. pthread_cond_signal(&gws_cond);
  5141. mutex_unlock(stgd_lock);
  5142. if (stale)
  5143. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5144. }
  5145. /* A generic wait function for threads that poll that will wait a specified
  5146. * time tdiff waiting on the pthread conditional that is broadcast when a
  5147. * work restart is required. Returns the value of pthread_cond_timedwait
  5148. * which is zero if the condition was met or ETIMEDOUT if not.
  5149. */
  5150. int restart_wait(struct thr_info *thr, unsigned int mstime)
  5151. {
  5152. struct timespec abstime, tdiff;
  5153. int rc;
  5154. cgcond_time(&abstime);
  5155. ms_to_timespec(&tdiff, mstime);
  5156. timeraddspec(&abstime, &tdiff);
  5157. mutex_lock(&restart_lock);
  5158. if (thr->work_restart)
  5159. rc = 0;
  5160. else
  5161. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  5162. mutex_unlock(&restart_lock);
  5163. return rc;
  5164. }
  5165. static void *restart_thread(void __maybe_unused *arg)
  5166. {
  5167. struct cgpu_info *cgpu;
  5168. int i, mt;
  5169. pthread_detach(pthread_self());
  5170. /* Discard staged work that is now stale */
  5171. discard_stale();
  5172. rd_lock(&mining_thr_lock);
  5173. mt = mining_threads;
  5174. rd_unlock(&mining_thr_lock);
  5175. for (i = 0; i < mt; i++) {
  5176. cgpu = mining_thr[i]->cgpu;
  5177. if (unlikely(!cgpu))
  5178. continue;
  5179. if (cgpu->deven != DEV_ENABLED)
  5180. continue;
  5181. mining_thr[i]->work_restart = true;
  5182. flush_queue(cgpu);
  5183. cgpu->drv->flush_work(cgpu);
  5184. }
  5185. mutex_lock(&restart_lock);
  5186. pthread_cond_broadcast(&restart_cond);
  5187. mutex_unlock(&restart_lock);
  5188. #ifdef USE_USBUTILS
  5189. /* Cancels any cancellable usb transfers. Flagged as such it means they
  5190. * are usualy waiting on a read result and it's safe to abort the read
  5191. * early. */
  5192. cancel_usb_transfers();
  5193. #endif
  5194. return NULL;
  5195. }
  5196. /* In order to prevent a deadlock via the various drv->flush_work
  5197. * implementations we send the restart messages via a separate thread. */
  5198. static void restart_threads(void)
  5199. {
  5200. pthread_t rthread;
  5201. cgtime(&restart_tv_start);
  5202. if (unlikely(pthread_create(&rthread, NULL, restart_thread, NULL)))
  5203. quithere(1, "Failed to create restart thread errno=%d", errno);
  5204. }
  5205. static void signal_work_update(void)
  5206. {
  5207. int i;
  5208. applog(LOG_INFO, "Work update message received");
  5209. cgtime(&update_tv_start);
  5210. rd_lock(&mining_thr_lock);
  5211. for (i = 0; i < mining_threads; i++)
  5212. mining_thr[i]->work_update = true;
  5213. rd_unlock(&mining_thr_lock);
  5214. }
  5215. #if defined(USE_AVALON7) || defined(USE_AVALON8) || defined(USE_AVALON9) || defined(USE_AVALONLC3)
  5216. static void signal_clean_jobs(void)
  5217. {
  5218. int i;
  5219. applog(LOG_NOTICE, "Job clean message received");
  5220. rd_lock(&mining_thr_lock);
  5221. for (i = 0; i < mining_threads; i++)
  5222. mining_thr[i]->clean_jobs = true;
  5223. rd_unlock(&mining_thr_lock);
  5224. }
  5225. #endif
  5226. static void set_curblock(const char *hexstr, const unsigned char *bedata)
  5227. {
  5228. int ofs;
  5229. cg_wlock(&ch_lock);
  5230. cgtime_real(&block_timeval);
  5231. strcpy(current_hash, hexstr);
  5232. cg_memcpy(current_block, bedata, 32);
  5233. get_timestamp(blocktime, sizeof(blocktime), &block_timeval);
  5234. cg_wunlock(&ch_lock);
  5235. for (ofs = 0; ofs <= 56; ofs++) {
  5236. if (memcmp(&current_hash[ofs], "0", 1))
  5237. break;
  5238. }
  5239. strncpy(prev_block, &current_hash[ofs], 8);
  5240. prev_block[8] = '\0';
  5241. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  5242. }
  5243. static int block_sort(struct block *blocka, struct block *blockb)
  5244. {
  5245. return blocka->block_no - blockb->block_no;
  5246. }
  5247. /* Decode the current block difficulty which is in packed form */
  5248. static void set_blockdiff(const struct work *work)
  5249. {
  5250. uint8_t pow = work->data[72];
  5251. int powdiff = (8 * (0x1d - 3)) - (8 * (pow - 3));
  5252. #if defined(USE_AVALON7) || defined(USE_AVALON8) || defined(USE_AVALON9) || defined(USE_AVALONLC3)
  5253. if (powdiff < 8)
  5254. powdiff = 8;
  5255. #else
  5256. if (powdiff < 0)
  5257. powdiff = 0;
  5258. #endif
  5259. uint32_t diff32 = be32toh(*((uint32_t *)(work->data + 72))) & 0x00FFFFFF;
  5260. double numerator = 0xFFFFULL << powdiff;
  5261. double ddiff = numerator / (double)diff32;
  5262. if (unlikely(current_diff != ddiff)) {
  5263. suffix_string(ddiff, block_diff, sizeof(block_diff), 0);
  5264. current_diff = ddiff;
  5265. applog(LOG_NOTICE, "Network diff set to %s", block_diff);
  5266. }
  5267. }
  5268. /* Search to see if this string is from a block that has been seen before */
  5269. static bool block_exists(const char *hexstr, const unsigned char *bedata, const struct work *work)
  5270. {
  5271. int deleted_block = 0;
  5272. struct block *s;
  5273. bool ret = true;
  5274. wr_lock(&blk_lock);
  5275. HASH_FIND_STR(blocks, hexstr, s);
  5276. if (!s) {
  5277. s = cgcalloc(sizeof(struct block), 1);
  5278. if (unlikely(!s))
  5279. quit (1, "block_exists OOM");
  5280. strcpy(s->hash, hexstr);
  5281. s->block_no = new_blocks++;
  5282. ret = false;
  5283. /* Only keep the last hour's worth of blocks in memory since
  5284. * work from blocks before this is virtually impossible and we
  5285. * want to prevent memory usage from continually rising */
  5286. if (HASH_COUNT(blocks) > 6) {
  5287. struct block *oldblock;
  5288. HASH_SORT(blocks, block_sort);
  5289. oldblock = blocks;
  5290. deleted_block = oldblock->block_no;
  5291. HASH_DEL(blocks, oldblock);
  5292. free(oldblock);
  5293. }
  5294. HASH_ADD_STR(blocks, hash, s);
  5295. set_blockdiff(work);
  5296. if (deleted_block)
  5297. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5298. }
  5299. wr_unlock(&blk_lock);
  5300. if (!ret)
  5301. set_curblock(hexstr, bedata);
  5302. if (deleted_block)
  5303. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5304. return ret;
  5305. }
  5306. static bool test_work_current(struct work *work)
  5307. {
  5308. struct pool *pool = work->pool;
  5309. unsigned char bedata[32];
  5310. char hexstr[68];
  5311. bool ret = true;
  5312. unsigned char *bin_height = &pool->coinbase[43];
  5313. uint8_t cb_height_sz = bin_height[-1];
  5314. uint32_t height = 0;
  5315. if (work->mandatory)
  5316. return ret;
  5317. swap256(bedata, work->data + 4);
  5318. __bin2hex(hexstr, bedata, 32);
  5319. /* Calculate block height */
  5320. if (cb_height_sz <= 4) {
  5321. memcpy(&height, bin_height, cb_height_sz);
  5322. height = le32toh(height);
  5323. height--;
  5324. }
  5325. cg_wlock(&pool->data_lock);
  5326. if (pool->swork.clean) {
  5327. pool->swork.clean = false;
  5328. work->longpoll = true;
  5329. #if defined(USE_AVALON7) || defined(USE_AVALON8) || defined(USE_AVALON9) || defined(USE_AVALONLC3)
  5330. opt_clean_jobs = true;
  5331. #endif
  5332. }
  5333. if (pool->current_height != height) {
  5334. pool->current_height = height;
  5335. }
  5336. cg_wunlock(&pool->data_lock);
  5337. /* Search to see if this block exists yet and if not, consider it a
  5338. * new block and set the current block details to this one */
  5339. if (!block_exists(hexstr, bedata, work)) {
  5340. /* Copy the information to this pool's prev_block since it
  5341. * knows the new block exists. */
  5342. cg_memcpy(pool->prev_block, bedata, 32);
  5343. if (unlikely(new_blocks == 1)) {
  5344. ret = false;
  5345. goto out;
  5346. }
  5347. work->work_block = ++work_block;
  5348. if (work->longpoll) {
  5349. if (work->stratum) {
  5350. applog(LOG_NOTICE, "Stratum from pool %d detected new block at height %d",
  5351. pool->pool_no, height);
  5352. } else {
  5353. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block at height %d",
  5354. work->gbt ? "GBT " : "", pool->pool_no, height);
  5355. }
  5356. } else if (have_longpoll && !pool->gbt_solo)
  5357. applog(LOG_NOTICE, "New block detected on network before pool notification from pool %d at height %d",
  5358. pool->pool_no, height);
  5359. else if (!pool->gbt_solo)
  5360. applog(LOG_NOTICE, "New block detected on network from pool %d at height %d",
  5361. pool->pool_no, height);
  5362. restart_threads();
  5363. } else {
  5364. if (memcmp(pool->prev_block, bedata, 32)) {
  5365. /* Work doesn't match what this pool has stored as
  5366. * prev_block. Let's see if the work is from an old
  5367. * block or the pool is just learning about a new
  5368. * block. */
  5369. if (memcmp(bedata, current_block, 32)) {
  5370. /* Doesn't match current block. It's stale */
  5371. applog(LOG_DEBUG, "Stale data from pool %d at height %d", pool->pool_no, height);
  5372. ret = false;
  5373. } else {
  5374. /* Work is from new block and pool is up now
  5375. * current. */
  5376. applog(LOG_INFO, "Pool %d now up to date at height %d", pool->pool_no, height);
  5377. cg_memcpy(pool->prev_block, bedata, 32);
  5378. }
  5379. }
  5380. #if 0
  5381. /* This isn't ideal, this pool is still on an old block but
  5382. * accepting shares from it. To maintain fair work distribution
  5383. * we work on it anyway. */
  5384. if (memcmp(bedata, current_block, 32))
  5385. applog(LOG_DEBUG, "Pool %d still on old block", pool->pool_no);
  5386. #endif
  5387. if (work->longpoll) {
  5388. work->work_block = ++work_block;
  5389. if (shared_strategy() || work->pool == current_pool()) {
  5390. if (work->stratum) {
  5391. applog(LOG_NOTICE, "Stratum from pool %d requested work restart",
  5392. pool->pool_no);
  5393. } else {
  5394. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  5395. work->gbt ? "GBT " : "", pool->pool_no);
  5396. }
  5397. restart_threads();
  5398. }
  5399. }
  5400. }
  5401. out:
  5402. work->longpoll = false;
  5403. return ret;
  5404. }
  5405. static int tv_sort(struct work *worka, struct work *workb)
  5406. {
  5407. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5408. }
  5409. static bool work_rollable(struct work *work)
  5410. {
  5411. return (!work->clone && work->rolltime);
  5412. }
  5413. static bool hash_push(struct work *work)
  5414. {
  5415. bool rc = true;
  5416. mutex_lock(stgd_lock);
  5417. if (work_rollable(work))
  5418. staged_rollable++;
  5419. if (likely(!getq->frozen)) {
  5420. HASH_ADD_INT(staged_work, id, work);
  5421. HASH_SORT(staged_work, tv_sort);
  5422. } else
  5423. rc = false;
  5424. pthread_cond_broadcast(&getq->cond);
  5425. mutex_unlock(stgd_lock);
  5426. return rc;
  5427. }
  5428. static void _stage_work(struct work *work)
  5429. {
  5430. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  5431. work->work_block = work_block;
  5432. test_work_current(work);
  5433. work->pool->works++;
  5434. hash_push(work);
  5435. }
  5436. #ifdef HAVE_CURSES
  5437. int curses_int(const char *query)
  5438. {
  5439. int ret;
  5440. char *cvar;
  5441. cvar = curses_input(query);
  5442. ret = atoi(cvar);
  5443. free(cvar);
  5444. return ret;
  5445. }
  5446. #endif
  5447. #ifdef HAVE_CURSES
  5448. static bool input_pool(bool live);
  5449. #endif
  5450. #ifdef HAVE_CURSES
  5451. static void display_pool_summary(struct pool *pool)
  5452. {
  5453. if (curses_active_locked()) {
  5454. wlog("Pool: %s\n", pool->rpc_url);
  5455. if (pool->solved)
  5456. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5457. if (!pool->has_stratum)
  5458. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  5459. wlog(" Work templates received: %d\n", pool->getwork_requested);
  5460. wlog(" Share submissions: %"PRId64"\n", pool->accepted + pool->rejected);
  5461. wlog(" Accepted shares: %"PRId64"\n", pool->accepted);
  5462. wlog(" Rejected shares: %"PRId64"\n", pool->rejected);
  5463. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5464. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5465. if (pool->accepted || pool->rejected)
  5466. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  5467. wlog(" Items worked on: %d\n", pool->works);
  5468. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  5469. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5470. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5471. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5472. unlock_curses();
  5473. }
  5474. }
  5475. #endif
  5476. /* We can't remove the memory used for this struct pool because there may
  5477. * still be work referencing it. We just remove it from the pools list */
  5478. void remove_pool(struct pool *pool)
  5479. {
  5480. int i, last_pool = total_pools - 1;
  5481. struct pool *other;
  5482. /* Boost priority of any lower prio than this one */
  5483. for (i = 0; i < total_pools; i++) {
  5484. other = pools[i];
  5485. if (other->prio > pool->prio)
  5486. other->prio--;
  5487. }
  5488. if (pool->pool_no < last_pool) {
  5489. /* Swap the last pool for this one */
  5490. (pools[last_pool])->pool_no = pool->pool_no;
  5491. pools[pool->pool_no] = pools[last_pool];
  5492. }
  5493. /* Give it an invalid number */
  5494. pool->pool_no = total_pools;
  5495. pool->removed = true;
  5496. total_pools--;
  5497. }
  5498. /* add a mutex if this needs to be thread safe in the future */
  5499. static struct JE {
  5500. char *buf;
  5501. struct JE *next;
  5502. } *jedata = NULL;
  5503. static void json_escape_free()
  5504. {
  5505. struct JE *jeptr = jedata;
  5506. struct JE *jenext;
  5507. jedata = NULL;
  5508. while (jeptr) {
  5509. jenext = jeptr->next;
  5510. free(jeptr->buf);
  5511. free(jeptr);
  5512. jeptr = jenext;
  5513. }
  5514. }
  5515. static char *json_escape(char *str)
  5516. {
  5517. struct JE *jeptr;
  5518. char *buf, *ptr;
  5519. /* 2x is the max, may as well just allocate that */
  5520. ptr = buf = cgmalloc(strlen(str) * 2 + 1);
  5521. jeptr = cgmalloc(sizeof(*jeptr));
  5522. jeptr->buf = buf;
  5523. jeptr->next = jedata;
  5524. jedata = jeptr;
  5525. while (*str) {
  5526. if (*str == '\\' || *str == '"')
  5527. *(ptr++) = '\\';
  5528. *(ptr++) = *(str++);
  5529. }
  5530. *ptr = '\0';
  5531. return buf;
  5532. }
  5533. void write_config(FILE *fcfg)
  5534. {
  5535. struct opt_table *opt;
  5536. int i;
  5537. /* Write pool values */
  5538. fputs("{\n\"pools\" : [", fcfg);
  5539. for(i = 0; i < total_pools; i++) {
  5540. struct pool *pool = priority_pool(i);
  5541. if (pool->quota != 1) {
  5542. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%s%s%s%d;%s\",", i > 0 ? "," : "",
  5543. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  5544. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  5545. pool->rpc_proxy ? "|" : "",
  5546. pool->quota,
  5547. json_escape(pool->rpc_url));
  5548. } else {
  5549. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  5550. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  5551. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  5552. pool->rpc_proxy ? "|" : "",
  5553. json_escape(pool->rpc_url));
  5554. }
  5555. #ifdef USE_XTRANONCE
  5556. if (pool->extranonce_subscribe)
  5557. fputs("\n\t\t\"extranonce-subscribe\" : true,", fcfg);
  5558. #endif
  5559. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  5560. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pool->rpc_pass));
  5561. }
  5562. fputs("\n]\n", fcfg);
  5563. /* Simple bool,int and char options */
  5564. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5565. char *p, *name = strdup(opt->names);
  5566. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5567. if (p[1] != '-')
  5568. continue;
  5569. if (opt->desc == opt_hidden)
  5570. continue;
  5571. if (opt->type & OPT_NOARG &&
  5572. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5573. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool))) {
  5574. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5575. continue;
  5576. }
  5577. if (opt->type & OPT_HASARG &&
  5578. ((void *)opt->cb_arg == (void *)opt_set_intval ||
  5579. (void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5580. (void *)opt->cb_arg == (void *)set_int_0_to_65535 ||
  5581. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5582. (void *)opt->cb_arg == (void *)set_int_0_to_5 ||
  5583. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5584. (void *)opt->cb_arg == (void *)set_int_1_to_10 ||
  5585. (void *)opt->cb_arg == (void *)set_int_24_to_32 ||
  5586. (void *)opt->cb_arg == (void *)set_int_0_to_100 ||
  5587. (void *)opt->cb_arg == (void *)set_int_0_to_255 ||
  5588. (void *)opt->cb_arg == (void *)set_int_1_to_255 ||
  5589. (void *)opt->cb_arg == (void *)set_int_0_to_7680 ||
  5590. (void *)opt->cb_arg == (void *)set_int_0_to_200 ||
  5591. (void *)opt->cb_arg == (void *)set_int_0_to_4 ||
  5592. (void *)opt->cb_arg == (void *)set_int_32_to_63 ||
  5593. (void *)opt->cb_arg == (void *)set_int_22_to_75 ||
  5594. #ifdef USE_DRAGONMINT_T1
  5595. (void *)opt->cb_arg == (void *)set_int_voltage ||
  5596. (void *)opt->cb_arg == (void *)set_int_1_to_31 ||
  5597. #endif
  5598. #ifdef USE_AVALON4
  5599. (void *)opt->cb_arg == (void *)set_int_1_to_60 ||
  5600. #endif
  5601. (void *)opt->cb_arg == (void *)set_int_42_to_85)) {
  5602. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5603. continue;
  5604. }
  5605. if (opt->type & OPT_HASARG &&
  5606. ((void *)opt->cb_arg == (void *)set_float_0_to_500 ||
  5607. (void *)opt->cb_arg == (void *)set_float_125_to_500 ||
  5608. (void *)opt->cb_arg == (void *)set_float_100_to_250 ||
  5609. (void *)opt->cb_arg == (void *)set_float_100_to_500)) {
  5610. fprintf(fcfg, ",\n\"%s\" : \"%.1f\"", p+2, *(float *)opt->u.arg);
  5611. continue;
  5612. }
  5613. if (opt->type & (OPT_HASARG | OPT_PROCESSARG) &&
  5614. (opt->u.arg != &opt_set_null)) {
  5615. char *carg = *(char **)opt->u.arg;
  5616. if (carg)
  5617. fprintf(fcfg, ",\n\"%s\" : \"%s\"", p+2, json_escape(carg));
  5618. continue;
  5619. }
  5620. }
  5621. free(name);
  5622. }
  5623. /* Special case options */
  5624. if (pool_strategy == POOL_BALANCE)
  5625. fputs(",\n\"balance\" : true", fcfg);
  5626. if (pool_strategy == POOL_LOADBALANCE)
  5627. fputs(",\n\"load-balance\" : true", fcfg);
  5628. if (pool_strategy == POOL_ROUNDROBIN)
  5629. fputs(",\n\"round-robin\" : true", fcfg);
  5630. if (pool_strategy == POOL_ROTATE)
  5631. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5632. fputs("\n}\n", fcfg);
  5633. json_escape_free();
  5634. }
  5635. void zero_bestshare(void)
  5636. {
  5637. int i;
  5638. best_diff = 0;
  5639. memset(best_share, 0, 8);
  5640. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5641. for (i = 0; i < total_pools; i++) {
  5642. struct pool *pool = pools[i];
  5643. pool->best_diff = 0;
  5644. }
  5645. }
  5646. static struct timeval tv_hashmeter;
  5647. static time_t hashdisplay_t;
  5648. void zero_stats(void)
  5649. {
  5650. int i;
  5651. #ifdef USE_BITMAIN_SOC
  5652. struct sysinfo sInfo;
  5653. if (sysinfo(&sInfo))
  5654. {
  5655. applog(LOG_INFO, "Failed to get sysinfo, errno:%u, reason:%s\n",
  5656. errno, strerror(errno));
  5657. total_tv_start_sys=time(NULL);
  5658. }
  5659. else
  5660. {
  5661. total_tv_start_sys=sInfo.uptime;
  5662. }
  5663. #endif
  5664. cgtime(&total_tv_start);
  5665. copy_time(&tv_hashmeter, &total_tv_start);
  5666. total_rolling = 0;
  5667. rolling1 = 0;
  5668. rolling5 = 0;
  5669. rolling15 = 0;
  5670. total_mhashes_done = 0;
  5671. #ifdef USE_BITMAIN_SOC
  5672. new_total_mhashes_done = 0;
  5673. #endif
  5674. total_getworks = 0;
  5675. total_accepted = 0;
  5676. total_rejected = 0;
  5677. hw_errors = 0;
  5678. total_stale = 0;
  5679. total_discarded = 0;
  5680. local_work = 0;
  5681. total_go = 0;
  5682. total_ro = 0;
  5683. total_secs = 1.0;
  5684. #ifdef USE_BITMAIN_SOC
  5685. new_total_secs = 1.0;
  5686. #endif
  5687. total_diff1 = 0;
  5688. found_blocks = 0;
  5689. total_diff_accepted = 0;
  5690. total_diff_rejected = 0;
  5691. total_diff_stale = 0;
  5692. for (i = 0; i < total_pools; i++) {
  5693. struct pool *pool = pools[i];
  5694. pool->getwork_requested = 0;
  5695. pool->accepted = 0;
  5696. pool->rejected = 0;
  5697. pool->stale_shares = 0;
  5698. pool->discarded_work = 0;
  5699. pool->getfail_occasions = 0;
  5700. pool->remotefail_occasions = 0;
  5701. pool->last_share_time = 0;
  5702. pool->diff1 = 0;
  5703. pool->diff_accepted = 0;
  5704. pool->diff_rejected = 0;
  5705. pool->diff_stale = 0;
  5706. pool->last_share_diff = 0;
  5707. }
  5708. zero_bestshare();
  5709. for (i = 0; i < total_devices; ++i) {
  5710. struct cgpu_info *cgpu = get_devices(i);
  5711. copy_time(&cgpu->dev_start_tv, &total_tv_start);
  5712. mutex_lock(&hash_lock);
  5713. cgpu->total_mhashes = 0;
  5714. cgpu->accepted = 0;
  5715. cgpu->rejected = 0;
  5716. cgpu->hw_errors = 0;
  5717. cgpu->utility = 0.0;
  5718. cgpu->last_share_pool_time = 0;
  5719. cgpu->diff1 = 0;
  5720. cgpu->diff_accepted = 0;
  5721. cgpu->diff_rejected = 0;
  5722. cgpu->last_share_diff = 0;
  5723. mutex_unlock(&hash_lock);
  5724. /* Don't take any locks in the driver zero stats function, as
  5725. * it's called async from everything else and we don't want to
  5726. * deadlock. */
  5727. cgpu->drv->zero_stats(cgpu);
  5728. }
  5729. }
  5730. static void __maybe_unused set_highprio(void)
  5731. {
  5732. #ifndef WIN32
  5733. int ret = nice(-10);
  5734. if (!ret)
  5735. applog(LOG_DEBUG, "Unable to set thread to high priority");
  5736. #else
  5737. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
  5738. #endif
  5739. }
  5740. static void __maybe_unused set_lowprio(void)
  5741. {
  5742. #ifndef WIN32
  5743. int ret = nice(10);
  5744. if (!ret)
  5745. applog(LOG_INFO, "Unable to set thread to low priority");
  5746. #else
  5747. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
  5748. #endif
  5749. }
  5750. #ifdef HAVE_CURSES
  5751. static void display_pools(void)
  5752. {
  5753. struct pool *pool;
  5754. int selected, i;
  5755. char input;
  5756. opt_loginput = true;
  5757. immedok(logwin, true);
  5758. clear_logwin();
  5759. updated:
  5760. for (i = 0; i < total_pools; i++) {
  5761. pool = pools[i];
  5762. if (pool == current_pool())
  5763. wattron(logwin, A_BOLD);
  5764. if (pool->enabled != POOL_ENABLED)
  5765. wattron(logwin, A_DIM);
  5766. wlogprint("%d: ", pool->pool_no);
  5767. switch (pool->enabled) {
  5768. case POOL_ENABLED:
  5769. wlogprint("Enabled ");
  5770. break;
  5771. case POOL_DISABLED:
  5772. wlogprint("Disabled ");
  5773. break;
  5774. case POOL_REJECTING:
  5775. wlogprint("Rejecting ");
  5776. break;
  5777. }
  5778. wlogprint("%s Quota %d Prio %d: %s User:%s\n",
  5779. pool->idle? "Dead" : "Alive",
  5780. pool->quota,
  5781. pool->prio,
  5782. pool->rpc_url, pool->rpc_user);
  5783. wattroff(logwin, A_BOLD | A_DIM);
  5784. }
  5785. retry:
  5786. wlogprint("\nCurrent pool management strategy: %s\n",
  5787. strategies[pool_strategy].s);
  5788. if (pool_strategy == POOL_ROTATE)
  5789. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  5790. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [Q]uota change\n");
  5791. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  5792. wlogprint("Or press any other key to continue\n");
  5793. logwin_update();
  5794. input = getch();
  5795. if (!strncasecmp(&input, "a", 1)) {
  5796. input_pool(true);
  5797. goto updated;
  5798. } else if (!strncasecmp(&input, "r", 1)) {
  5799. if (total_pools <= 1) {
  5800. wlogprint("Cannot remove last pool");
  5801. goto retry;
  5802. }
  5803. selected = curses_int("Select pool number");
  5804. if (selected < 0 || selected >= total_pools) {
  5805. wlogprint("Invalid selection\n");
  5806. goto retry;
  5807. }
  5808. pool = pools[selected];
  5809. if (pool == current_pool())
  5810. switch_pools(NULL);
  5811. if (pool == current_pool()) {
  5812. wlogprint("Unable to remove pool due to activity\n");
  5813. goto retry;
  5814. }
  5815. disable_pool(pool);
  5816. remove_pool(pool);
  5817. goto updated;
  5818. } else if (!strncasecmp(&input, "s", 1)) {
  5819. selected = curses_int("Select pool number");
  5820. if (selected < 0 || selected >= total_pools) {
  5821. wlogprint("Invalid selection\n");
  5822. goto retry;
  5823. }
  5824. pool = pools[selected];
  5825. enable_pool(pool);
  5826. switch_pools(pool);
  5827. goto updated;
  5828. } else if (!strncasecmp(&input, "d", 1)) {
  5829. if (enabled_pools <= 1) {
  5830. wlogprint("Cannot disable last pool");
  5831. goto retry;
  5832. }
  5833. selected = curses_int("Select pool number");
  5834. if (selected < 0 || selected >= total_pools) {
  5835. wlogprint("Invalid selection\n");
  5836. goto retry;
  5837. }
  5838. pool = pools[selected];
  5839. disable_pool(pool);
  5840. if (pool == current_pool())
  5841. switch_pools(NULL);
  5842. goto updated;
  5843. } else if (!strncasecmp(&input, "e", 1)) {
  5844. selected = curses_int("Select pool number");
  5845. if (selected < 0 || selected >= total_pools) {
  5846. wlogprint("Invalid selection\n");
  5847. goto retry;
  5848. }
  5849. pool = pools[selected];
  5850. enable_pool(pool);
  5851. if (pool->prio < current_pool()->prio)
  5852. switch_pools(pool);
  5853. goto updated;
  5854. } else if (!strncasecmp(&input, "c", 1)) {
  5855. for (i = 0; i <= TOP_STRATEGY; i++)
  5856. wlogprint("%d: %s\n", i, strategies[i].s);
  5857. selected = curses_int("Select strategy number type");
  5858. if (selected < 0 || selected > TOP_STRATEGY) {
  5859. wlogprint("Invalid selection\n");
  5860. goto retry;
  5861. }
  5862. if (selected == POOL_ROTATE) {
  5863. opt_rotate_period = curses_int("Select interval in minutes");
  5864. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  5865. opt_rotate_period = 0;
  5866. wlogprint("Invalid selection\n");
  5867. goto retry;
  5868. }
  5869. }
  5870. pool_strategy = selected;
  5871. switch_pools(NULL);
  5872. goto updated;
  5873. } else if (!strncasecmp(&input, "i", 1)) {
  5874. selected = curses_int("Select pool number");
  5875. if (selected < 0 || selected >= total_pools) {
  5876. wlogprint("Invalid selection\n");
  5877. goto retry;
  5878. }
  5879. pool = pools[selected];
  5880. display_pool_summary(pool);
  5881. goto retry;
  5882. } else if (!strncasecmp(&input, "q", 1)) {
  5883. selected = curses_int("Select pool number");
  5884. if (selected < 0 || selected >= total_pools) {
  5885. wlogprint("Invalid selection\n");
  5886. goto retry;
  5887. }
  5888. pool = pools[selected];
  5889. selected = curses_int("Set quota");
  5890. if (selected < 0) {
  5891. wlogprint("Invalid negative quota\n");
  5892. goto retry;
  5893. }
  5894. pool->quota = selected;
  5895. adjust_quota_gcd();
  5896. goto updated;
  5897. } else
  5898. clear_logwin();
  5899. immedok(logwin, false);
  5900. opt_loginput = false;
  5901. }
  5902. static void display_options(void)
  5903. {
  5904. int selected;
  5905. char input;
  5906. opt_loginput = true;
  5907. immedok(logwin, true);
  5908. clear_logwin();
  5909. retry:
  5910. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  5911. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  5912. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  5913. "[T]oggle status switching:%s\n"
  5914. "w[I]descreen:%s\n"
  5915. "[Z]ero statistics\n"
  5916. "[L]og interval:%d\n",
  5917. opt_debug ? "on" : "off",
  5918. want_per_device_stats? "on" : "off",
  5919. opt_quiet ? "on" : "off",
  5920. opt_log_output ? "on" : "off",
  5921. opt_protocol ? "on" : "off",
  5922. opt_worktime ? "on" : "off",
  5923. opt_compact ? "on" : "off",
  5924. switch_status ? "enabled" : "disabled",
  5925. opt_widescreen ? "enabled" : "disabled",
  5926. opt_log_interval);
  5927. wlogprint("Select an option or any other key to return\n");
  5928. logwin_update();
  5929. input = getch();
  5930. if (!strncasecmp(&input, "q", 1)) {
  5931. opt_quiet ^= true;
  5932. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  5933. goto retry;
  5934. } else if (!strncasecmp(&input, "v", 1)) {
  5935. opt_log_output ^= true;
  5936. if (opt_log_output)
  5937. opt_quiet = false;
  5938. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  5939. goto retry;
  5940. } else if (!strncasecmp(&input, "n", 1)) {
  5941. opt_log_output = false;
  5942. opt_debug = false;
  5943. opt_quiet = false;
  5944. opt_protocol = false;
  5945. opt_compact = false;
  5946. want_per_device_stats = false;
  5947. wlogprint("Output mode reset to normal\n");
  5948. switch_logsize(false);
  5949. goto retry;
  5950. } else if (!strncasecmp(&input, "d", 1)) {
  5951. opt_debug ^= true;
  5952. opt_log_output = opt_debug;
  5953. if (opt_debug)
  5954. opt_quiet = false;
  5955. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  5956. goto retry;
  5957. } else if (!strncasecmp(&input, "m", 1)) {
  5958. opt_compact ^= true;
  5959. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  5960. switch_logsize(false);
  5961. goto retry;
  5962. } else if (!strncasecmp(&input, "p", 1)) {
  5963. want_per_device_stats ^= true;
  5964. opt_log_output = want_per_device_stats;
  5965. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  5966. goto retry;
  5967. } else if (!strncasecmp(&input, "r", 1)) {
  5968. opt_protocol ^= true;
  5969. if (opt_protocol)
  5970. opt_quiet = false;
  5971. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  5972. goto retry;
  5973. } else if (!strncasecmp(&input, "c", 1))
  5974. clear_logwin();
  5975. else if (!strncasecmp(&input, "l", 1)) {
  5976. selected = curses_int("Interval in seconds");
  5977. if (selected < 0 || selected > 9999) {
  5978. wlogprint("Invalid selection\n");
  5979. goto retry;
  5980. }
  5981. opt_log_interval = selected;
  5982. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  5983. goto retry;
  5984. } else if (!strncasecmp(&input, "s", 1)) {
  5985. opt_realquiet = true;
  5986. } else if (!strncasecmp(&input, "w", 1)) {
  5987. opt_worktime ^= true;
  5988. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  5989. goto retry;
  5990. } else if (!strncasecmp(&input, "t", 1)) {
  5991. switch_status ^= true;
  5992. goto retry;
  5993. } else if (!strncasecmp(&input, "i", 1)) {
  5994. opt_widescreen ^= true;
  5995. goto retry;
  5996. } else if (!strncasecmp(&input, "z", 1)) {
  5997. zero_stats();
  5998. goto retry;
  5999. } else
  6000. clear_logwin();
  6001. immedok(logwin, false);
  6002. opt_loginput = false;
  6003. }
  6004. #endif
  6005. void default_save_file(char *filename)
  6006. {
  6007. if (default_config && *default_config) {
  6008. strcpy(filename, default_config);
  6009. return;
  6010. }
  6011. #if defined(unix) || defined(__APPLE__)
  6012. if (getenv("HOME") && *getenv("HOME")) {
  6013. strcpy(filename, getenv("HOME"));
  6014. strcat(filename, "/");
  6015. }
  6016. else
  6017. strcpy(filename, "");
  6018. strcat(filename, ".cgminer/");
  6019. mkdir(filename, 0777);
  6020. #else
  6021. strcpy(filename, "");
  6022. #endif
  6023. strcat(filename, def_conf);
  6024. }
  6025. #ifdef HAVE_CURSES
  6026. static void set_options(void)
  6027. {
  6028. char input;
  6029. opt_loginput = true;
  6030. immedok(logwin, true);
  6031. clear_logwin();
  6032. retry:
  6033. wlogprint("[W]rite config file\n[C]gminer restart\n");
  6034. wlogprint("Select an option or any other key to return\n");
  6035. logwin_update();
  6036. input = getch();
  6037. if (!strncasecmp(&input, "w", 1)) {
  6038. FILE *fcfg;
  6039. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6040. default_save_file(filename);
  6041. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6042. str = curses_input(prompt);
  6043. if (strcmp(str, "-1")) {
  6044. struct stat statbuf;
  6045. strcpy(filename, str);
  6046. free(str);
  6047. if (!stat(filename, &statbuf)) {
  6048. wlogprint("File exists, overwrite?\n");
  6049. input = getch();
  6050. if (strncasecmp(&input, "y", 1))
  6051. goto retry;
  6052. }
  6053. }
  6054. else
  6055. free(str);
  6056. fcfg = fopen(filename, "w");
  6057. if (!fcfg) {
  6058. wlogprint("Cannot open or create file\n");
  6059. goto retry;
  6060. }
  6061. write_config(fcfg);
  6062. fclose(fcfg);
  6063. goto retry;
  6064. } else if (!strncasecmp(&input, "c", 1)) {
  6065. wlogprint("Are you sure?\n");
  6066. input = getch();
  6067. if (!strncasecmp(&input, "y", 1))
  6068. app_restart();
  6069. else
  6070. clear_logwin();
  6071. } else
  6072. clear_logwin();
  6073. immedok(logwin, false);
  6074. opt_loginput = false;
  6075. }
  6076. #ifdef USE_USBUTILS
  6077. static void mt_enable(struct thr_info *mythr)
  6078. {
  6079. cgsem_post(&mythr->sem);
  6080. }
  6081. static void set_usb(void)
  6082. {
  6083. int selected, i, mt, enabled, disabled, zombie, total, blacklisted;
  6084. struct cgpu_info *cgpu;
  6085. struct thr_info *thr;
  6086. double val;
  6087. char input;
  6088. opt_loginput = true;
  6089. immedok(logwin, true);
  6090. clear_logwin();
  6091. retry:
  6092. enabled = 0;
  6093. disabled = 0;
  6094. zombie = 0;
  6095. total = 0;
  6096. blacklisted = 0;
  6097. rd_lock(&mining_thr_lock);
  6098. mt = mining_threads;
  6099. rd_unlock(&mining_thr_lock);
  6100. for (i = 0; i < mt; i++) {
  6101. cgpu = mining_thr[i]->cgpu;
  6102. if (unlikely(!cgpu))
  6103. continue;
  6104. if (cgpu->usbinfo.nodev)
  6105. zombie++;
  6106. else if (cgpu->deven == DEV_DISABLED)
  6107. disabled++;
  6108. else
  6109. enabled++;
  6110. if (cgpu->blacklisted)
  6111. blacklisted++;
  6112. total++;
  6113. }
  6114. wlogprint("Hotplug interval:%d\n", hotplug_time);
  6115. wlogprint("%d USB devices, %d enabled, %d disabled, %d zombie\n",
  6116. total, enabled, disabled, zombie);
  6117. wlogprint("[S]ummary of device information\n");
  6118. wlogprint("[E]nable device\n");
  6119. wlogprint("[D]isable device\n");
  6120. wlogprint("[U]nplug to allow hotplug restart\n");
  6121. wlogprint("[R]eset device USB\n");
  6122. wlogprint("[L]ist all known devices\n");
  6123. wlogprint("[B]lacklist current device from current instance of cgminer\n");
  6124. wlogprint("[W]hitelist previously blacklisted device\n");
  6125. wlogprint("[H]otplug interval (0 to disable)\n");
  6126. wlogprint("Select an option or any other key to return\n");
  6127. logwin_update();
  6128. input = getch();
  6129. if (!strncasecmp(&input, "s", 1)) {
  6130. selected = curses_int("Select device number");
  6131. if (selected < 0 || selected >= mt) {
  6132. wlogprint("Invalid selection\n");
  6133. goto retry;
  6134. }
  6135. cgpu = mining_thr[selected]->cgpu;
  6136. wlogprint("Device %03u:%03u\n", cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  6137. wlogprint("Name %s\n", cgpu->drv->name);
  6138. wlogprint("ID %d\n", cgpu->device_id);
  6139. wlogprint("Enabled: %s\n", cgpu->deven != DEV_DISABLED ? "Yes" : "No");
  6140. wlogprint("Temperature %.1f\n", cgpu->temp);
  6141. wlogprint("MHS av %.0f\n", cgpu->total_mhashes / cgpu_runtime(cgpu));
  6142. wlogprint("Accepted %d\n", cgpu->accepted);
  6143. wlogprint("Rejected %d\n", cgpu->rejected);
  6144. wlogprint("Hardware Errors %d\n", cgpu->hw_errors);
  6145. wlogprint("Last Share Pool %d\n", cgpu->last_share_pool_time > 0 ? cgpu->last_share_pool : -1);
  6146. wlogprint("Total MH %.1f\n", cgpu->total_mhashes);
  6147. wlogprint("Diff1 Work %"PRId64"\n", cgpu->diff1);
  6148. wlogprint("Difficulty Accepted %.1f\n", cgpu->diff_accepted);
  6149. wlogprint("Difficulty Rejected %.1f\n", cgpu->diff_rejected);
  6150. wlogprint("Last Share Difficulty %.1f\n", cgpu->last_share_diff);
  6151. wlogprint("No Device: %s\n", cgpu->usbinfo.nodev ? "True" : "False");
  6152. wlogprint("Last Valid Work %"PRIu64"\n", (uint64_t)cgpu->last_device_valid_work);
  6153. val = 0;
  6154. if (cgpu->hw_errors + cgpu->diff1)
  6155. val = cgpu->hw_errors / (cgpu->hw_errors + cgpu->diff1);
  6156. wlogprint("Device Hardware %.1f%%\n", val);
  6157. val = 0;
  6158. if (cgpu->diff1)
  6159. val = cgpu->diff_rejected / cgpu->diff1;
  6160. wlogprint("Device Rejected %.1f%%\n", val);
  6161. goto retry;
  6162. } else if (!strncasecmp(&input, "e", 1)) {
  6163. selected = curses_int("Select device number");
  6164. if (selected < 0 || selected >= mt) {
  6165. wlogprint("Invalid selection\n");
  6166. goto retry;
  6167. }
  6168. cgpu = mining_thr[selected]->cgpu;
  6169. if (cgpu->usbinfo.nodev) {
  6170. wlogprint("Device removed, unable to re-enable!\n");
  6171. goto retry;
  6172. }
  6173. thr = get_thread(selected);
  6174. cgpu->deven = DEV_ENABLED;
  6175. mt_enable(thr);
  6176. goto retry;
  6177. } else if (!strncasecmp(&input, "d", 1)) {
  6178. selected = curses_int("Select device number");
  6179. if (selected < 0 || selected >= mt) {
  6180. wlogprint("Invalid selection\n");
  6181. goto retry;
  6182. }
  6183. cgpu = mining_thr[selected]->cgpu;
  6184. cgpu->deven = DEV_DISABLED;
  6185. goto retry;
  6186. } else if (!strncasecmp(&input, "u", 1)) {
  6187. selected = curses_int("Select device number");
  6188. if (selected < 0 || selected >= mt) {
  6189. wlogprint("Invalid selection\n");
  6190. goto retry;
  6191. }
  6192. cgpu = mining_thr[selected]->cgpu;
  6193. if (cgpu->usbinfo.nodev) {
  6194. wlogprint("Device already removed, unable to unplug!\n");
  6195. goto retry;
  6196. }
  6197. usb_nodev(cgpu);
  6198. goto retry;
  6199. } else if (!strncasecmp(&input, "r", 1)) {
  6200. selected = curses_int("Select device number");
  6201. if (selected < 0 || selected >= mt) {
  6202. wlogprint("Invalid selection\n");
  6203. goto retry;
  6204. }
  6205. cgpu = mining_thr[selected]->cgpu;
  6206. if (cgpu->usbinfo.nodev) {
  6207. wlogprint("Device already removed, unable to reset!\n");
  6208. goto retry;
  6209. }
  6210. usb_reset(cgpu);
  6211. goto retry;
  6212. } else if (!strncasecmp(&input, "b", 1)) {
  6213. selected = curses_int("Select device number");
  6214. if (selected < 0 || selected >= mt) {
  6215. wlogprint("Invalid selection\n");
  6216. goto retry;
  6217. }
  6218. cgpu = mining_thr[selected]->cgpu;
  6219. if (cgpu->usbinfo.nodev) {
  6220. wlogprint("Device already removed, unable to blacklist!\n");
  6221. goto retry;
  6222. }
  6223. blacklist_cgpu(cgpu);
  6224. goto retry;
  6225. } else if (!strncasecmp(&input, "w", 1)) {
  6226. if (!blacklisted) {
  6227. wlogprint("No blacklisted devices!\n");
  6228. goto retry;
  6229. }
  6230. wlogprint("Blacklisted devices:\n");
  6231. for (i = 0; i < mt; i++) {
  6232. cgpu = mining_thr[i]->cgpu;
  6233. if (unlikely(!cgpu))
  6234. continue;
  6235. if (cgpu->blacklisted) {
  6236. wlogprint("%d: %s %d %03u:%03u\n", i, cgpu->drv->name,
  6237. cgpu->device_id, cgpu->usbinfo.bus_number,
  6238. cgpu->usbinfo.device_address);
  6239. }
  6240. }
  6241. selected = curses_int("Select device number");
  6242. if (selected < 0 || selected >= mt) {
  6243. wlogprint("Invalid selection\n");
  6244. goto retry;
  6245. }
  6246. cgpu = mining_thr[selected]->cgpu;
  6247. if (!cgpu->blacklisted) {
  6248. wlogprint("Device not blacklisted, unable to whitelist\n");
  6249. goto retry;
  6250. }
  6251. whitelist_cgpu(cgpu);
  6252. goto retry;
  6253. } else if (!strncasecmp(&input, "h", 1)) {
  6254. selected = curses_int("Select hotplug interval in seconds (0 to disable)");
  6255. if (selected < 0 || selected > 9999) {
  6256. wlogprint("Invalid value\n");
  6257. goto retry;
  6258. }
  6259. hotplug_time = selected;
  6260. goto retry;
  6261. } else if (!strncasecmp(&input, "l", 1)) {
  6262. usb_list();
  6263. goto retry;
  6264. } else
  6265. clear_logwin();
  6266. immedok(logwin, false);
  6267. opt_loginput = false;
  6268. }
  6269. #endif
  6270. static void *input_thread(void __maybe_unused *userdata)
  6271. {
  6272. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6273. RenameThread("Input");
  6274. if (!curses_active)
  6275. return NULL;
  6276. while (1) {
  6277. char input;
  6278. input = getch();
  6279. if (!strncasecmp(&input, "q", 1)) {
  6280. kill_work();
  6281. return NULL;
  6282. } else if (!strncasecmp(&input, "d", 1))
  6283. display_options();
  6284. else if (!strncasecmp(&input, "p", 1))
  6285. display_pools();
  6286. else if (!strncasecmp(&input, "s", 1))
  6287. set_options();
  6288. #ifdef USE_USBUTILS
  6289. else if (!strncasecmp(&input, "u", 1))
  6290. set_usb();
  6291. #endif
  6292. if (opt_realquiet) {
  6293. disable_curses();
  6294. break;
  6295. }
  6296. }
  6297. return NULL;
  6298. }
  6299. #endif
  6300. static void *api_thread(void *userdata)
  6301. {
  6302. struct thr_info *mythr = userdata;
  6303. pthread_detach(pthread_self());
  6304. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6305. RenameThread("API");
  6306. set_lowprio();
  6307. api(api_thr_id);
  6308. PTH(mythr) = 0L;
  6309. return NULL;
  6310. }
  6311. /* Sole work devices are serialised wrt calling get_work so they report in on
  6312. * each pass through their scanhash function as well as in get_work whereas
  6313. * queued work devices work asynchronously so get them to report in and out
  6314. * only across get_work. */
  6315. static void thread_reportin(struct thr_info *thr)
  6316. {
  6317. thr->getwork = false;
  6318. cgtime(&thr->last);
  6319. thr->cgpu->status = LIFE_WELL;
  6320. thr->cgpu->device_last_well = time(NULL);
  6321. }
  6322. /* Tell the watchdog thread this thread is waiting on get work and should not
  6323. * be restarted */
  6324. static void thread_reportout(struct thr_info *thr)
  6325. {
  6326. thr->getwork = true;
  6327. cgtime(&thr->last);
  6328. thr->cgpu->status = LIFE_WELL;
  6329. thr->cgpu->device_last_well = time(NULL);
  6330. }
  6331. static void hashmeter(int thr_id, uint64_t hashes_done)
  6332. {
  6333. bool showlog = false;
  6334. double tv_tdiff;
  6335. time_t now_t;
  6336. int diff_t;
  6337. #ifdef USE_BITMAIN_SOC
  6338. struct sysinfo sInfo;
  6339. if (sysinfo(&sInfo))
  6340. {
  6341. applog(LOG_INFO, "Failed to get sysinfo, errno:%u, reason:%s\n",
  6342. errno, strerror(errno));
  6343. total_tv_end_sys=time(NULL);
  6344. }
  6345. else
  6346. {
  6347. total_tv_end_sys=sInfo.uptime;
  6348. }
  6349. #endif
  6350. cgtime(&total_tv_end);
  6351. tv_tdiff = tdiff(&total_tv_end, &tv_hashmeter);
  6352. now_t = total_tv_end.tv_sec;
  6353. diff_t = now_t - hashdisplay_t;
  6354. if (diff_t >= opt_log_interval) {
  6355. alt_status ^= switch_status;
  6356. hashdisplay_t = now_t;
  6357. showlog = true;
  6358. } else if (thr_id < 0) {
  6359. /* hashmeter is called by non-mining threads in case nothing
  6360. * has reported in to allow hashrate to converge to zero , but
  6361. * we only update if it has been more than opt_log_interval */
  6362. return;
  6363. }
  6364. copy_time(&tv_hashmeter, &total_tv_end);
  6365. if (thr_id >= 0) {
  6366. struct thr_info *thr = get_thread(thr_id);
  6367. struct cgpu_info *cgpu = thr->cgpu;
  6368. double device_tdiff, thr_mhs;
  6369. /* Update the last time this thread reported in */
  6370. copy_time(&thr->last, &total_tv_end);
  6371. cgpu->device_last_well = now_t;
  6372. device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  6373. copy_time(&cgpu->last_message_tv, &total_tv_end);
  6374. thr_mhs = (double)hashes_done / device_tdiff / 1000000;
  6375. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f mhash/sec]",
  6376. thr_id, hashes_done, thr_mhs);
  6377. hashes_done /= 1000000;
  6378. mutex_lock(&hash_lock);
  6379. cgpu->total_mhashes += hashes_done;
  6380. decay_time(&cgpu->rolling, hashes_done, device_tdiff, opt_log_interval);
  6381. decay_time(&cgpu->rolling1, hashes_done, device_tdiff, 60.0);
  6382. decay_time(&cgpu->rolling5, hashes_done, device_tdiff, 300.0);
  6383. decay_time(&cgpu->rolling15, hashes_done, device_tdiff, 900.0);
  6384. mutex_unlock(&hash_lock);
  6385. if (want_per_device_stats && showlog) {
  6386. char logline[256];
  6387. get_statline(logline, sizeof(logline), cgpu);
  6388. if (!curses_active) {
  6389. printf("%s \r", logline);
  6390. fflush(stdout);
  6391. } else
  6392. applog(LOG_INFO, "%s", logline);
  6393. }
  6394. } else {
  6395. /* No device has reported in, we have been called from the
  6396. * watchdog thread so decay all the hashrates */
  6397. mutex_lock(&hash_lock);
  6398. for (thr_id = 0; thr_id < mining_threads; thr_id++) {
  6399. struct thr_info *thr = get_thread(thr_id);
  6400. struct cgpu_info *cgpu = thr->cgpu;
  6401. double device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  6402. copy_time(&cgpu->last_message_tv, &total_tv_end);
  6403. decay_time(&cgpu->rolling, 0, device_tdiff, opt_log_interval);
  6404. decay_time(&cgpu->rolling1, 0, device_tdiff, 60.0);
  6405. decay_time(&cgpu->rolling5, 0, device_tdiff, 300.0);
  6406. decay_time(&cgpu->rolling15, 0, device_tdiff, 900.0);
  6407. }
  6408. mutex_unlock(&hash_lock);
  6409. }
  6410. mutex_lock(&hash_lock);
  6411. total_mhashes_done += hashes_done;
  6412. decay_time(&total_rolling, hashes_done, tv_tdiff, opt_log_interval);
  6413. decay_time(&rolling1, hashes_done, tv_tdiff, 60.0);
  6414. decay_time(&rolling5, hashes_done, tv_tdiff, 300.0);
  6415. decay_time(&rolling15, hashes_done, tv_tdiff, 900.0);
  6416. global_hashrate = llround(total_rolling) * 1000000;
  6417. #ifndef USE_BITMAIN_SOC
  6418. total_secs = tdiff(&total_tv_end, &total_tv_start);
  6419. #else
  6420. total_secs = total_tv_end_sys*1.0-total_tv_start_sys*1.0;
  6421. #endif
  6422. if (showlog) {
  6423. char displayed_hashes[16], displayed_rolling[16];
  6424. char displayed_r1[16], displayed_r5[16], displayed_r15[16];
  6425. uint64_t d64;
  6426. d64 = (double)total_mhashes_done / total_secs * 1000000ull;
  6427. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  6428. d64 = (double)total_rolling * 1000000ull;
  6429. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  6430. d64 = (double)rolling1 * 1000000ull;
  6431. suffix_string(d64, displayed_r1, sizeof(displayed_rolling), 4);
  6432. d64 = (double)rolling5 * 1000000ull;
  6433. suffix_string(d64, displayed_r5, sizeof(displayed_rolling), 4);
  6434. d64 = (double)rolling15 * 1000000ull;
  6435. suffix_string(d64, displayed_r15, sizeof(displayed_rolling), 4);
  6436. snprintf(statusline, sizeof(statusline),
  6437. "(%ds):%s (1m):%s (5m):%s (15m):%s (avg):%sh/s",
  6438. opt_log_interval, displayed_rolling, displayed_r1, displayed_r5,
  6439. displayed_r15, displayed_hashes);
  6440. }
  6441. mutex_unlock(&hash_lock);
  6442. #ifdef USE_LIBSYSTEMD
  6443. sd_notifyf(false, "STATUS=%s", statusline);
  6444. #endif
  6445. if (showlog) {
  6446. if (!curses_active) {
  6447. printf("%s \r", statusline);
  6448. fflush(stdout);
  6449. } else
  6450. applog(LOG_INFO, "%s", statusline);
  6451. }
  6452. }
  6453. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  6454. struct stratum_share *sshare)
  6455. {
  6456. struct work *work = sshare->work;
  6457. time_t now_t = time(NULL);
  6458. char hashshow[64];
  6459. int srdiff;
  6460. srdiff = now_t - sshare->sshare_sent;
  6461. if (opt_debug || srdiff > 0) {
  6462. applog(LOG_INFO, "Pool %d stratum share result lag time %d seconds",
  6463. work->pool->pool_no, srdiff);
  6464. }
  6465. show_hash(work, hashshow);
  6466. share_result(val, res_val, err_val, work, hashshow, false, "");
  6467. }
  6468. /* Parses stratum json responses and tries to find the id that the request
  6469. * matched to and treat it accordingly. */
  6470. static bool parse_stratum_response(struct pool *pool, char *s)
  6471. {
  6472. json_t *val = NULL, *err_val, *res_val, *id_val;
  6473. struct stratum_share *sshare;
  6474. json_error_t err;
  6475. bool ret = false;
  6476. int id;
  6477. val = JSON_LOADS(s, &err);
  6478. if (!val) {
  6479. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  6480. goto out;
  6481. }
  6482. res_val = json_object_get(val, "result");
  6483. err_val = json_object_get(val, "error");
  6484. id_val = json_object_get(val, "id");
  6485. if (json_is_null(id_val) || !id_val) {
  6486. char *ss;
  6487. if (err_val)
  6488. ss = json_dumps(err_val, JSON_INDENT(3));
  6489. else
  6490. ss = strdup("(unknown reason)");
  6491. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  6492. free(ss);
  6493. goto out;
  6494. }
  6495. id = json_integer_value(id_val);
  6496. mutex_lock(&sshare_lock);
  6497. HASH_FIND_INT(stratum_shares, &id, sshare);
  6498. if (sshare) {
  6499. HASH_DEL(stratum_shares, sshare);
  6500. pool->sshares--;
  6501. }
  6502. mutex_unlock(&sshare_lock);
  6503. if (!sshare) {
  6504. double pool_diff;
  6505. if (!res_val)
  6506. goto out;
  6507. /* Since the share is untracked, we can only guess at what the
  6508. * work difficulty is based on the current pool diff. */
  6509. cg_rlock(&pool->data_lock);
  6510. pool_diff = pool->sdiff;
  6511. cg_runlock(&pool->data_lock);
  6512. if (json_is_true(res_val)) {
  6513. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  6514. /* We don't know what device this came from so we can't
  6515. * attribute the work to the relevant cgpu */
  6516. mutex_lock(&stats_lock);
  6517. total_accepted++;
  6518. pool->accepted++;
  6519. total_diff_accepted += pool_diff;
  6520. pool->diff_accepted += pool_diff;
  6521. mutex_unlock(&stats_lock);
  6522. } else {
  6523. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  6524. mutex_lock(&stats_lock);
  6525. total_rejected++;
  6526. pool->rejected++;
  6527. total_diff_rejected += pool_diff;
  6528. pool->diff_rejected += pool_diff;
  6529. mutex_unlock(&stats_lock);
  6530. }
  6531. goto out;
  6532. }
  6533. stratum_share_result(val, res_val, err_val, sshare);
  6534. free_work(sshare->work);
  6535. free(sshare);
  6536. ret = true;
  6537. out:
  6538. if (val)
  6539. json_decref(val);
  6540. return ret;
  6541. }
  6542. void clear_stratum_shares(struct pool *pool)
  6543. {
  6544. struct stratum_share *sshare, *tmpshare;
  6545. double diff_cleared = 0;
  6546. int cleared = 0;
  6547. mutex_lock(&sshare_lock);
  6548. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  6549. if (sshare->work->pool == pool) {
  6550. HASH_DEL(stratum_shares, sshare);
  6551. diff_cleared += sshare->work->work_difficulty;
  6552. free_work(sshare->work);
  6553. pool->sshares--;
  6554. free(sshare);
  6555. cleared++;
  6556. }
  6557. }
  6558. mutex_unlock(&sshare_lock);
  6559. if (cleared) {
  6560. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  6561. pool->stale_shares += cleared;
  6562. total_stale += cleared;
  6563. pool->diff_stale += diff_cleared;
  6564. total_diff_stale += diff_cleared;
  6565. }
  6566. }
  6567. void clear_pool_work(struct pool *pool)
  6568. {
  6569. struct work *work, *tmp;
  6570. int cleared = 0;
  6571. mutex_lock(stgd_lock);
  6572. HASH_ITER(hh, staged_work, work, tmp) {
  6573. if (work->pool == pool) {
  6574. HASH_DEL(staged_work, work);
  6575. free_work(work);
  6576. cleared++;
  6577. }
  6578. }
  6579. mutex_unlock(stgd_lock);
  6580. if (cleared)
  6581. applog(LOG_INFO, "Cleared %d work items due to stratum disconnect on pool %d", cleared, pool->pool_no);
  6582. }
  6583. static int cp_prio(void)
  6584. {
  6585. int prio;
  6586. cg_rlock(&control_lock);
  6587. prio = currentpool->prio;
  6588. cg_runlock(&control_lock);
  6589. return prio;
  6590. }
  6591. /* We only need to maintain a secondary pool connection when we need the
  6592. * capacity to get work from the backup pools while still on the primary */
  6593. static bool cnx_needed(struct pool *pool)
  6594. {
  6595. struct pool *cp;
  6596. if (pool->enabled != POOL_ENABLED)
  6597. return false;
  6598. /* Balance strategies need all pools online */
  6599. if (pool_strategy == POOL_BALANCE)
  6600. return true;
  6601. if (pool_strategy == POOL_LOADBALANCE)
  6602. return true;
  6603. /* Idle stratum pool needs something to kick it alive again */
  6604. if (pool->has_stratum && pool->idle)
  6605. return true;
  6606. cp = current_pool();
  6607. if (cp == pool)
  6608. return true;
  6609. /* If we're waiting for a response from shares submitted, keep the
  6610. * connection open. */
  6611. if (pool->sshares)
  6612. return true;
  6613. /* If the pool has only just come to life and is higher priority than
  6614. * the current pool keep the connection open so we can fail back to
  6615. * it. */
  6616. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  6617. return true;
  6618. /* We've run out of work, bring anything back to life. */
  6619. if (no_work)
  6620. return true;
  6621. return false;
  6622. }
  6623. static void wait_lpcurrent(struct pool *pool);
  6624. static void pool_resus(struct pool *pool);
  6625. static void gen_stratum_work(struct pool *pool, struct work *work);
  6626. void stratum_resumed(struct pool *pool)
  6627. {
  6628. if (pool_tclear(pool, &pool->idle)) {
  6629. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  6630. pool_resus(pool);
  6631. }
  6632. }
  6633. static bool supports_resume(struct pool *pool)
  6634. {
  6635. bool ret;
  6636. cg_rlock(&pool->data_lock);
  6637. ret = (pool->sessionid != NULL);
  6638. cg_runlock(&pool->data_lock);
  6639. return ret;
  6640. }
  6641. /* One stratum receive thread per pool that has stratum waits on the socket
  6642. * checking for new messages and for the integrity of the socket connection. We
  6643. * reset the connection based on the integrity of the receive side only as the
  6644. * send side will eventually expire data it fails to send. */
  6645. static void *stratum_rthread(void *userdata)
  6646. {
  6647. struct pool *pool = (struct pool *)userdata;
  6648. char threadname[16];
  6649. pthread_detach(pthread_self());
  6650. snprintf(threadname, sizeof(threadname), "%d/RStratum", pool->pool_no);
  6651. RenameThread(threadname);
  6652. while (42) {
  6653. struct timeval timeout;
  6654. int sel_ret;
  6655. fd_set rd;
  6656. char *s;
  6657. if (unlikely(pool->removed)) {
  6658. suspend_stratum(pool);
  6659. break;
  6660. }
  6661. /* Check to see whether we need to maintain this connection
  6662. * indefinitely or just bring it up when we switch to this
  6663. * pool */
  6664. if (!sock_full(pool) && !cnx_needed(pool)) {
  6665. suspend_stratum(pool);
  6666. clear_stratum_shares(pool);
  6667. clear_pool_work(pool);
  6668. wait_lpcurrent(pool);
  6669. while (!restart_stratum(pool)) {
  6670. pool_died(pool);
  6671. if (pool->removed)
  6672. goto out;
  6673. cgsleep_ms(5000);
  6674. }
  6675. }
  6676. FD_ZERO(&rd);
  6677. FD_SET(pool->sock, &rd);
  6678. timeout.tv_sec = 90;
  6679. timeout.tv_usec = 0;
  6680. /* The protocol specifies that notify messages should be sent
  6681. * every minute so if we fail to receive any for 90 seconds we
  6682. * assume the connection has been dropped and treat this pool
  6683. * as dead */
  6684. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  6685. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  6686. s = NULL;
  6687. } else
  6688. s = recv_line(pool);
  6689. if (!s) {
  6690. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  6691. pool->getfail_occasions++;
  6692. total_go++;
  6693. /* If the socket to our stratum pool disconnects, all
  6694. * tracked submitted shares are lost and we will leak
  6695. * the memory if we don't discard their records. */
  6696. if (!supports_resume(pool) || opt_lowmem)
  6697. clear_stratum_shares(pool);
  6698. clear_pool_work(pool);
  6699. if (pool == current_pool())
  6700. restart_threads();
  6701. while (!restart_stratum(pool)) {
  6702. pool_died(pool);
  6703. if (pool->removed)
  6704. goto out;
  6705. cgsleep_ms(5000);
  6706. }
  6707. continue;
  6708. }
  6709. /* Check this pool hasn't died while being a backup pool and
  6710. * has not had its idle flag cleared */
  6711. stratum_resumed(pool);
  6712. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  6713. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  6714. else if (pool->swork.clean) {
  6715. struct work *work = make_work();
  6716. /* Generate a single work item to update the current
  6717. * block database */
  6718. gen_stratum_work(pool, work);
  6719. /* Return value doesn't matter. We're just informing
  6720. * that we may need to restart. */
  6721. test_work_current(work);
  6722. free_work(work);
  6723. }
  6724. free(s);
  6725. }
  6726. out:
  6727. return NULL;
  6728. }
  6729. /* Each pool has one stratum send thread for sending shares to avoid many
  6730. * threads being created for submission since all sends need to be serialised
  6731. * anyway. */
  6732. static void *stratum_sthread(void *userdata)
  6733. {
  6734. struct pool *pool = (struct pool *)userdata;
  6735. uint64_t last_nonce2 = 0;
  6736. uint32_t last_nonce = 0;
  6737. char threadname[16];
  6738. pthread_detach(pthread_self());
  6739. snprintf(threadname, sizeof(threadname), "%d/SStratum", pool->pool_no);
  6740. RenameThread(threadname);
  6741. pool->stratum_q = tq_new();
  6742. if (!pool->stratum_q)
  6743. quit(1, "Failed to create stratum_q in stratum_sthread");
  6744. while (42) {
  6745. char noncehex[12], nonce2hex[20], s[1024];
  6746. struct stratum_share *sshare;
  6747. uint32_t *hash32, nonce;
  6748. unsigned char nonce2[8];
  6749. uint64_t *nonce2_64;
  6750. struct work *work;
  6751. bool submitted;
  6752. if (unlikely(pool->removed))
  6753. break;
  6754. #if defined (USE_AVALON2) || defined (USE_AVALON4) || defined (USE_AVALON7) || defined (USE_AVALON8) || defined (USE_AVALON9) || defined (USE_AVALON_MINER) || defined (USE_HASHRATIO)
  6755. work = tq_pop(pool->stratum_q, NULL);
  6756. #else
  6757. work = tq_pop(pool->stratum_q);
  6758. #endif
  6759. if (unlikely(!work))
  6760. quit(1, "Stratum q returned empty work");
  6761. if (unlikely(work->nonce2_len > 8)) {
  6762. applog(LOG_ERR, "Pool %d asking for inappropriately long nonce2 length %d",
  6763. pool->pool_no, (int)work->nonce2_len);
  6764. applog(LOG_ERR, "Not attempting to submit shares");
  6765. free_work(work);
  6766. continue;
  6767. }
  6768. nonce = *((uint32_t *)(work->data + 76));
  6769. nonce2_64 = (uint64_t *)nonce2;
  6770. *nonce2_64 = htole64(work->nonce2);
  6771. /* Filter out duplicate shares */
  6772. if (unlikely(nonce == last_nonce && *nonce2_64 == last_nonce2)) {
  6773. applog(LOG_INFO, "Filtering duplicate share to pool %d",
  6774. pool->pool_no);
  6775. free_work(work);
  6776. continue;
  6777. }
  6778. last_nonce = nonce;
  6779. last_nonce2 = *nonce2_64;
  6780. __bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  6781. __bin2hex(nonce2hex, nonce2, work->nonce2_len);
  6782. sshare = cgcalloc(sizeof(struct stratum_share), 1);
  6783. hash32 = (uint32_t *)work->hash;
  6784. submitted = false;
  6785. sshare->sshare_time = time(NULL);
  6786. /* This work item is freed in parse_stratum_response */
  6787. sshare->work = work;
  6788. memset(s, 0, 1024);
  6789. mutex_lock(&sshare_lock);
  6790. /* Give the stratum share a unique id */
  6791. sshare->id = swork_id++;
  6792. mutex_unlock(&sshare_lock);
  6793. if (pool->vmask) {
  6794. snprintf(s, sizeof(s),
  6795. "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6796. pool->rpc_user, work->job_id, nonce2hex, work->ntime, noncehex, pool->vmask_002[work->micro_job_id], sshare->id);
  6797. } else {
  6798. snprintf(s, sizeof(s),
  6799. "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  6800. pool->rpc_user, work->job_id, nonce2hex, work->ntime, noncehex, sshare->id);
  6801. }
  6802. applog(LOG_INFO, "Submitting share %08lx to pool %d",
  6803. (long unsigned int)htole32(hash32[6]), pool->pool_no);
  6804. /* Try resubmitting for up to 2 minutes if we fail to submit
  6805. * once and the stratum pool nonce1 still matches suggesting
  6806. * we may be able to resume. */
  6807. while (time(NULL) < sshare->sshare_time + 120) {
  6808. bool sessionid_match;
  6809. if (likely(stratum_send(pool, s, strlen(s)))) {
  6810. mutex_lock(&sshare_lock);
  6811. HASH_ADD_INT(stratum_shares, id, sshare);
  6812. pool->sshares++;
  6813. mutex_unlock(&sshare_lock);
  6814. if (pool_tclear(pool, &pool->submit_fail))
  6815. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  6816. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  6817. submitted = true;
  6818. break;
  6819. }
  6820. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  6821. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  6822. total_ro++;
  6823. pool->remotefail_occasions++;
  6824. }
  6825. if (opt_lowmem) {
  6826. applog(LOG_DEBUG, "Lowmem option prevents resubmitting stratum share");
  6827. break;
  6828. }
  6829. cg_rlock(&pool->data_lock);
  6830. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  6831. cg_runlock(&pool->data_lock);
  6832. if (!sessionid_match) {
  6833. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  6834. break;
  6835. }
  6836. /* Retry every 5 seconds */
  6837. sleep(5);
  6838. }
  6839. if (unlikely(!submitted)) {
  6840. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  6841. free_work(work);
  6842. free(sshare);
  6843. pool->stale_shares++;
  6844. total_stale++;
  6845. } else {
  6846. int ssdiff;
  6847. sshare->sshare_sent = time(NULL);
  6848. ssdiff = sshare->sshare_sent - sshare->sshare_time;
  6849. if (opt_debug || ssdiff > 0) {
  6850. applog(LOG_INFO, "Pool %d stratum share submission lag time %d seconds",
  6851. pool->pool_no, ssdiff);
  6852. }
  6853. }
  6854. }
  6855. /* Freeze the work queue but don't free up its memory in case there is
  6856. * work still trying to be submitted to the removed pool. */
  6857. tq_freeze(pool->stratum_q);
  6858. return NULL;
  6859. }
  6860. static void init_stratum_threads(struct pool *pool)
  6861. {
  6862. have_longpoll = true;
  6863. if (unlikely(pthread_create(&pool->stratum_sthread, NULL, stratum_sthread, (void *)pool)))
  6864. quit(1, "Failed to create stratum sthread");
  6865. if (unlikely(pthread_create(&pool->stratum_rthread, NULL, stratum_rthread, (void *)pool)))
  6866. quit(1, "Failed to create stratum rthread");
  6867. }
  6868. static void *longpoll_thread(void *userdata);
  6869. static bool stratum_works(struct pool *pool)
  6870. {
  6871. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  6872. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  6873. return false;
  6874. if (!initiate_stratum(pool))
  6875. return false;
  6876. return true;
  6877. }
  6878. #ifdef HAVE_LIBCURL
  6879. static void __setup_gbt_solo(struct pool *pool)
  6880. {
  6881. cg_wlock(&pool->gbt_lock);
  6882. cg_memcpy(pool->coinbase, scriptsig_header_bin, 41);
  6883. pool->coinbase[41 + pool->n1_len + 4 + 1 + 8] = 25;
  6884. cg_memcpy(pool->coinbase + 41 + pool->n1_len + 4 + 1 + 8 + 1, pool->script_pubkey, 25);
  6885. cg_wunlock(&pool->gbt_lock);
  6886. }
  6887. static bool setup_gbt_solo(CURL *curl, struct pool *pool)
  6888. {
  6889. char s[256];
  6890. int uninitialised_var(rolltime);
  6891. bool ret = false;
  6892. json_t *val = NULL, *res_val, *valid_val;
  6893. if (!opt_btc_address) {
  6894. if (!opt_decode) {
  6895. applog(LOG_ERR, "No BTC address specified, unable to mine solo on %s",
  6896. pool->rpc_url);
  6897. }
  6898. goto out;
  6899. }
  6900. if (opt_btc_address[0] != '1')
  6901. {
  6902. applog(LOG_ERR, "Bitcoin address must start with 1");
  6903. goto out;
  6904. }
  6905. snprintf(s, 256, "{\"id\": 1, \"method\": \"validateaddress\", \"params\": [\"%s\"]}\n", opt_btc_address);
  6906. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, true,
  6907. false, &rolltime, pool, false);
  6908. if (!val)
  6909. goto out;
  6910. res_val = json_object_get(val, "result");
  6911. if (!res_val)
  6912. goto out;
  6913. valid_val = json_object_get(res_val, "isvalid");
  6914. if (!valid_val)
  6915. goto out;
  6916. if (!json_is_true(valid_val)) {
  6917. applog(LOG_ERR, "Bitcoin address %s is NOT valid", opt_btc_address);
  6918. goto out;
  6919. }
  6920. applog(LOG_NOTICE, "Solo mining to valid address: %s", opt_btc_address);
  6921. ret = true;
  6922. address_to_pubkeyhash(pool->script_pubkey, opt_btc_address);
  6923. hex2bin(scriptsig_header_bin, scriptsig_header, 41);
  6924. __setup_gbt_solo(pool);
  6925. if (opt_debug) {
  6926. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  6927. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  6928. free(cb);
  6929. }
  6930. out:
  6931. if (val)
  6932. json_decref(val);
  6933. return ret;
  6934. }
  6935. #else
  6936. static bool setup_gbt_solo(CURL __maybe_unused *curl, struct pool __maybe_unused *pool)
  6937. {
  6938. return false;
  6939. }
  6940. #endif
  6941. static void pool_start_lp(struct pool *pool)
  6942. {
  6943. if (!pool->lp_started) {
  6944. pool->lp_started = true;
  6945. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  6946. quit(1, "Failed to create pool longpoll thread");
  6947. }
  6948. }
  6949. static bool pool_active(struct pool *pool, bool pinging)
  6950. {
  6951. struct timeval tv_getwork, tv_getwork_reply;
  6952. json_t *val = NULL;
  6953. bool ret = false;
  6954. CURL *curl;
  6955. int uninitialised_var(rolltime);
  6956. if (pool->has_gbt)
  6957. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  6958. else
  6959. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  6960. /* This is the central point we activate stratum when we can */
  6961. retry_stratum:
  6962. if (pool->has_stratum) {
  6963. /* We create the stratum thread for each pool just after
  6964. * successful authorisation. Once the init flag has been set
  6965. * we never unset it and the stratum thread is responsible for
  6966. * setting/unsetting the active flag */
  6967. bool init = pool_tset(pool, &pool->stratum_init);
  6968. if (!init) {
  6969. #ifdef USE_XTRANONCE
  6970. bool ret = initiate_stratum(pool) && (!pool->extranonce_subscribe || subscribe_extranonce(pool)) && auth_stratum(pool);
  6971. #else
  6972. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  6973. #endif
  6974. if (ret)
  6975. init_stratum_threads(pool);
  6976. else
  6977. pool_tclear(pool, &pool->stratum_init);
  6978. return ret;
  6979. }
  6980. return pool->stratum_active;
  6981. }
  6982. curl = curl_easy_init();
  6983. if (unlikely(!curl)) {
  6984. applog(LOG_ERR, "CURL initialisation failed");
  6985. return false;
  6986. }
  6987. /* Probe for GBT support on first pass */
  6988. if (!pool->probed) {
  6989. applog(LOG_DEBUG, "Probing for GBT support");
  6990. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  6991. gbt_req, true, false, &rolltime, pool, false);
  6992. if (val) {
  6993. json_t *rules_arr = json_object_get(val, "rules");
  6994. if (!gbt_check_rules(rules_arr, gbt_understood_rules)) {
  6995. applog(LOG_DEBUG, "Not all rules understood for GBT");
  6996. json_decref(val);
  6997. val = NULL;
  6998. }
  6999. }
  7000. if (!val) {
  7001. json_t *rules_arr;
  7002. applog(LOG_DEBUG, "Probing for GBT solo support");
  7003. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  7004. gbt_solo_req, true, false, &rolltime, pool, false);
  7005. rules_arr = json_object_get(val, "rules");
  7006. if (!gbt_check_rules(rules_arr, gbt_solo_understood_rules)) {
  7007. applog(LOG_DEBUG, "Not all rules understood for GBT solo");
  7008. json_decref(val);
  7009. val = NULL;
  7010. }
  7011. }
  7012. if (val) {
  7013. bool append = false, submit = false, transactions = false;
  7014. json_t *res_val, *mutables;
  7015. int i, mutsize = 0;
  7016. res_val = json_object_get(val, "result");
  7017. if (res_val) {
  7018. mutables = json_object_get(res_val, "mutable");
  7019. mutsize = json_array_size(mutables);
  7020. }
  7021. for (i = 0; i < mutsize; i++) {
  7022. json_t *arrval = json_array_get(mutables, i);
  7023. if (json_is_string(arrval)) {
  7024. const char *mutable = json_string_value(arrval);
  7025. if (!strncasecmp(mutable, "coinbase/append", 15))
  7026. append = true;
  7027. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  7028. submit = true;
  7029. else if (!strncasecmp(mutable, "transactions", 12))
  7030. transactions = true;
  7031. }
  7032. }
  7033. json_decref(val);
  7034. /* Only use GBT if it supports coinbase append and
  7035. * submit coinbase */
  7036. if (append && submit) {
  7037. pool->has_gbt = true;
  7038. pool->rpc_req = gbt_req;
  7039. } else if (transactions) {
  7040. pool->rpc_req = gbt_solo_req;
  7041. /* Set up gbt_curl before setting gbt_solo
  7042. * flag to prevent longpoll thread from
  7043. * trying to use an un'inited gbt_curl */
  7044. pool->gbt_curl = curl_easy_init();
  7045. if (unlikely(!pool->gbt_curl))
  7046. quit(1, "GBT CURL initialisation failed");
  7047. pool->gbt_solo = true;
  7048. if (!opt_btcd)
  7049. opt_btcd = pool;
  7050. }
  7051. }
  7052. /* Reset this so we can probe fully just after this. It will be
  7053. * set to true that time.*/
  7054. pool->probed = false;
  7055. if (pool->has_gbt)
  7056. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  7057. else if (pool->gbt_solo)
  7058. applog(LOG_DEBUG, "GBT coinbase without append found, switching to GBT solo protocol");
  7059. else
  7060. applog(LOG_DEBUG, "No GBT coinbase + append support found, pool unusable if it has no stratum");
  7061. }
  7062. cgtime(&tv_getwork);
  7063. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  7064. pool->rpc_req, true, false, &rolltime, pool, false);
  7065. cgtime(&tv_getwork_reply);
  7066. /* Detect if a http pool has an X-Stratum header at startup,
  7067. * and if so, switch to that in preference to gbt if it works */
  7068. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  7069. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7070. if (!pool->rpc_url)
  7071. pool->rpc_url = strdup(pool->stratum_url);
  7072. pool->has_stratum = true;
  7073. curl_easy_cleanup(curl);
  7074. goto retry_stratum;
  7075. }
  7076. if (!pool->has_stratum && !pool->gbt_solo && !pool->has_gbt) {
  7077. applog(LOG_WARNING, "No Stratum, GBT or Solo support in pool %d %s unable to use", pool->pool_no, pool->rpc_url);
  7078. return false;
  7079. }
  7080. if (val) {
  7081. struct work *work = make_work();
  7082. bool rc;
  7083. rc = work_decode(pool, work, val);
  7084. if (rc) {
  7085. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7086. pool->pool_no, pool->rpc_url);
  7087. if (pool->gbt_solo) {
  7088. ret = setup_gbt_solo(curl, pool);
  7089. if (ret)
  7090. pool_start_lp(pool);
  7091. free_work(work);
  7092. goto out;
  7093. }
  7094. work->pool = pool;
  7095. work->rolltime = rolltime;
  7096. copy_time(&work->tv_getwork, &tv_getwork);
  7097. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7098. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7099. calc_diff(work, 0);
  7100. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7101. stage_work(work);
  7102. total_getworks++;
  7103. pool->getwork_requested++;
  7104. ret = true;
  7105. } else {
  7106. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7107. pool->pool_no, pool->rpc_url);
  7108. free_work(work);
  7109. }
  7110. if (pool->lp_url)
  7111. goto out;
  7112. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7113. if (pool->hdr_path) {
  7114. char *copy_start, *hdr_path;
  7115. bool need_slash = false;
  7116. size_t siz;
  7117. hdr_path = pool->hdr_path;
  7118. if (strstr(hdr_path, "://")) {
  7119. pool->lp_url = hdr_path;
  7120. hdr_path = NULL;
  7121. } else {
  7122. /* absolute path, on current server */
  7123. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  7124. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  7125. need_slash = true;
  7126. siz = strlen(pool->rpc_url) + strlen(copy_start) + 2;
  7127. pool->lp_url = cgmalloc(siz);
  7128. snprintf(pool->lp_url, siz, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  7129. }
  7130. } else
  7131. pool->lp_url = NULL;
  7132. pool_start_lp(pool);
  7133. } else {
  7134. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7135. pool->pool_no, pool->rpc_url);
  7136. if (!pinging && !pool->idle)
  7137. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7138. }
  7139. out:
  7140. if (val)
  7141. json_decref(val);
  7142. curl_easy_cleanup(curl);
  7143. return ret;
  7144. }
  7145. static void pool_resus(struct pool *pool)
  7146. {
  7147. pool->seq_getfails = 0;
  7148. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7149. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7150. else
  7151. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7152. }
  7153. static bool work_filled;
  7154. static bool work_emptied;
  7155. /* If this is called non_blocking, it will return NULL for work so that must
  7156. * be handled. */
  7157. static struct work *hash_pop(bool blocking)
  7158. {
  7159. struct work *work = NULL, *tmp;
  7160. int hc;
  7161. mutex_lock(stgd_lock);
  7162. if (!HASH_COUNT(staged_work)) {
  7163. work_emptied = true;
  7164. if (!blocking)
  7165. goto out_unlock;
  7166. do {
  7167. struct timespec abstime, tdiff = {10, 0};
  7168. int rc;
  7169. cgcond_time(&abstime);
  7170. timeraddspec(&abstime, &tdiff);
  7171. pthread_cond_signal(&gws_cond);
  7172. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, &abstime);
  7173. /* Check again for !no_work as multiple threads may be
  7174. * waiting on this condition and another may set the
  7175. * bool separately. */
  7176. if (rc && !no_work) {
  7177. no_work = true;
  7178. applog(LOG_WARNING, "Waiting for work to be available from pools.");
  7179. }
  7180. } while (!HASH_COUNT(staged_work));
  7181. }
  7182. if (no_work) {
  7183. applog(LOG_WARNING, "Work available from pools, resuming.");
  7184. no_work = false;
  7185. }
  7186. hc = HASH_COUNT(staged_work);
  7187. /* Find clone work if possible, to allow masters to be reused */
  7188. if (hc > staged_rollable) {
  7189. HASH_ITER(hh, staged_work, work, tmp) {
  7190. if (!work_rollable(work))
  7191. break;
  7192. }
  7193. } else
  7194. work = staged_work;
  7195. HASH_DEL(staged_work, work);
  7196. if (work_rollable(work))
  7197. staged_rollable--;
  7198. /* Signal the getwork scheduler to look for more work */
  7199. pthread_cond_signal(&gws_cond);
  7200. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7201. pthread_cond_signal(&getq->cond);
  7202. /* Keep track of last getwork grabbed */
  7203. last_getwork = time(NULL);
  7204. out_unlock:
  7205. mutex_unlock(stgd_lock);
  7206. return work;
  7207. }
  7208. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7209. {
  7210. unsigned char hash1[32];
  7211. sha256(data, len, hash1);
  7212. sha256(hash1, 32, hash);
  7213. }
  7214. void set_target(unsigned char *dest_target, double diff)
  7215. {
  7216. unsigned char target[32];
  7217. uint64_t *data64, h64;
  7218. double d64, dcut64;
  7219. if (unlikely(diff == 0.0)) {
  7220. /* This shouldn't happen but best we check to prevent a crash */
  7221. applog(LOG_ERR, "Diff zero passed to set_target");
  7222. diff = 1.0;
  7223. }
  7224. d64 = truediffone;
  7225. d64 /= diff;
  7226. dcut64 = d64 / bits192;
  7227. h64 = dcut64;
  7228. data64 = (uint64_t *)(target + 24);
  7229. *data64 = htole64(h64);
  7230. dcut64 = h64;
  7231. dcut64 *= bits192;
  7232. d64 -= dcut64;
  7233. dcut64 = d64 / bits128;
  7234. h64 = dcut64;
  7235. data64 = (uint64_t *)(target + 16);
  7236. *data64 = htole64(h64);
  7237. dcut64 = h64;
  7238. dcut64 *= bits128;
  7239. d64 -= dcut64;
  7240. dcut64 = d64 / bits64;
  7241. h64 = dcut64;
  7242. data64 = (uint64_t *)(target + 8);
  7243. *data64 = htole64(h64);
  7244. dcut64 = h64;
  7245. dcut64 *= bits64;
  7246. d64 -= dcut64;
  7247. h64 = d64;
  7248. data64 = (uint64_t *)(target);
  7249. *data64 = htole64(h64);
  7250. if (opt_debug) {
  7251. char *htarget = bin2hex(target, 32);
  7252. applog(LOG_DEBUG, "Generated target %s", htarget);
  7253. free(htarget);
  7254. }
  7255. cg_memcpy(dest_target, target, 32);
  7256. }
  7257. #if defined (USE_AVALON2) || defined (USE_AVALON4) || defined (USE_AVALON7) || defined (USE_AVALON8) || defined (USE_AVALON9) \
  7258. || defined (USE_AVALON_MINER) || defined (USE_HASHRATIO) || defined (USE_AVALONLC3)
  7259. bool submit_nonce2_nonce(struct thr_info *thr, struct pool *pool, struct pool *real_pool,
  7260. uint32_t nonce2, uint32_t nonce, uint32_t ntime)
  7261. {
  7262. const int thr_id = thr->id;
  7263. struct cgpu_info *cgpu = thr->cgpu;
  7264. struct device_drv *drv = cgpu->drv;
  7265. struct work *work = make_work();
  7266. bool ret;
  7267. cg_wlock(&pool->data_lock);
  7268. pool->nonce2 = nonce2;
  7269. cg_wunlock(&pool->data_lock);
  7270. gen_stratum_work(pool, work);
  7271. roll_work_ntime(work, ntime);
  7272. work->pool = real_pool;
  7273. /* Inherit the sdiff from the original stratum */
  7274. work->sdiff = pool->sdiff;
  7275. work->thr_id = thr_id;
  7276. work->work_block = work_block;
  7277. work->pool->works++;
  7278. work->mined = true;
  7279. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  7280. work->device_diff = MAX(drv->min_diff, work->device_diff);
  7281. ret = submit_nonce(thr, work, nonce);
  7282. free_work(work);
  7283. return ret;
  7284. }
  7285. uint32_t gen_merkle_root(struct pool *pool, uint64_t nonce2)
  7286. {
  7287. unsigned char merkle_root[32], merkle_sha[64];
  7288. uint32_t *data32, *swap32, tail;
  7289. uint64_t nonce2le;
  7290. int i;
  7291. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  7292. * from left to right and prevent overflow errors with small n2sizes */
  7293. nonce2le = htole64(nonce2);
  7294. cg_memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  7295. /* Generate merkle root */
  7296. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  7297. cg_memcpy(merkle_sha, merkle_root, 32);
  7298. for (i = 0; i < pool->merkles; i++) {
  7299. cg_memcpy(merkle_sha + 32, pool->swork.merkle_bin[i], 32);
  7300. gen_hash(merkle_sha, merkle_root, 64);
  7301. cg_memcpy(merkle_sha, merkle_root, 32);
  7302. }
  7303. data32 = (uint32_t *)merkle_sha;
  7304. swap32 = (uint32_t *)merkle_root;
  7305. flip32(swap32, data32);
  7306. {
  7307. char *merkle_hash;
  7308. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  7309. applog(LOG_DEBUG, "[M-N2]: %s-%08x-%08x", merkle_hash, (uint32_t)nonce2le, (uint32_t)nonce2);
  7310. free(merkle_hash);
  7311. }
  7312. cg_memcpy(&tail, merkle_root + 28, 4);
  7313. return tail;
  7314. }
  7315. #endif
  7316. #ifdef USE_BITMAIN_SOC
  7317. void get_work_by_nonce2(struct thr_info *thr,
  7318. struct work **work,
  7319. struct pool *pool,
  7320. struct pool *real_pool,
  7321. uint64_t nonce2,
  7322. uint32_t version)
  7323. {
  7324. *work = make_work();
  7325. const int thr_id = thr->id;
  7326. struct cgpu_info *cgpu = thr->cgpu;
  7327. struct device_drv *drv = cgpu->drv;
  7328. cg_wlock(&pool->data_lock);
  7329. pool->nonce2 = nonce2;
  7330. //if(pool->support_vil) // comment as default
  7331. version = Swap32(version);
  7332. cg_memcpy(pool->header_bin, &version, 4);
  7333. cg_wunlock(&pool->data_lock);
  7334. gen_stratum_work(pool, *work);
  7335. (*work)->pool = real_pool;
  7336. (*work)->thr_id = thr_id;
  7337. (*work)->work_block = work_block;
  7338. (*work)->pool->works++;
  7339. (*work)->mined = true;
  7340. (*work)->version = version;
  7341. }
  7342. #endif
  7343. #if STRATUM_WORK_TIMING
  7344. cglock_t swt_lock;
  7345. uint64_t stratum_work_count;
  7346. uint64_t stratum_work_time;
  7347. uint64_t stratum_work_min;
  7348. uint64_t stratum_work_max;
  7349. uint64_t stratum_work_time0;
  7350. uint64_t stratum_work_time10;
  7351. uint64_t stratum_work_time100;
  7352. #endif
  7353. /* Generates stratum based work based on the most recent notify information
  7354. * from the pool. This will keep generating work while a pool is down so we use
  7355. * other means to detect when the pool has died in stratum_thread */
  7356. static void gen_stratum_work(struct pool *pool, struct work *work)
  7357. {
  7358. unsigned char merkle_root[32], merkle_sha[64];
  7359. uint32_t *data32, *swap32;
  7360. #if STRATUM_WORK_TIMING
  7361. struct timeval stt;
  7362. double usec;
  7363. #endif
  7364. uint64_t nonce2le;
  7365. int i;
  7366. #if STRATUM_WORK_TIMING
  7367. cgtime(&stt);
  7368. #endif
  7369. cg_wlock(&pool->data_lock);
  7370. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  7371. * from left to right and prevent overflow errors with small n2sizes */
  7372. nonce2le = htole64(pool->nonce2);
  7373. cg_memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  7374. work->nonce2 = pool->nonce2++;
  7375. work->nonce2_len = pool->n2size;
  7376. /* Downgrade to a read lock to read off the pool variables */
  7377. cg_dwlock(&pool->data_lock);
  7378. /* Generate merkle root */
  7379. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  7380. cg_memcpy(merkle_sha, merkle_root, 32);
  7381. for (i = 0; i < pool->merkles; i++) {
  7382. cg_memcpy(merkle_sha + 32, pool->swork.merkle_bin[i], 32);
  7383. gen_hash(merkle_sha, merkle_root, 64);
  7384. cg_memcpy(merkle_sha, merkle_root, 32);
  7385. }
  7386. data32 = (uint32_t *)merkle_sha;
  7387. swap32 = (uint32_t *)merkle_root;
  7388. flip32(swap32, data32);
  7389. /* Copy the data template from header_bin */
  7390. cg_memcpy(work->data, pool->header_bin, 112);
  7391. cg_memcpy(work->data + 36, merkle_root, 32);
  7392. /* Store the stratum work diff to check it still matches the pool's
  7393. * stratum diff when submitting shares */
  7394. work->sdiff = pool->sdiff;
  7395. /* Copy parameters required for share submission */
  7396. work->job_id = strdup(pool->swork.job_id);
  7397. work->nonce1 = strdup(pool->nonce1);
  7398. work->ntime = strdup(pool->ntime);
  7399. cg_runlock(&pool->data_lock);
  7400. if (opt_debug) {
  7401. char *header, *merkle_hash;
  7402. header = bin2hex(work->data, 112);
  7403. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  7404. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  7405. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7406. applog(LOG_DEBUG, "Work job_id %s nonce2 %"PRIu64" ntime %s", work->job_id,
  7407. work->nonce2, work->ntime);
  7408. free(header);
  7409. free(merkle_hash);
  7410. }
  7411. calc_midstate(pool, work);
  7412. set_target(work->target, work->sdiff);
  7413. local_work++;
  7414. work->pool = pool;
  7415. work->stratum = true;
  7416. work->nonce = 0;
  7417. work->longpoll = false;
  7418. work->getwork_mode = GETWORK_MODE_STRATUM;
  7419. work->work_block = work_block;
  7420. /* Nominally allow a driver to ntime roll 60 seconds */
  7421. work->drv_rolllimit = 60;
  7422. calc_diff(work, work->sdiff);
  7423. cgtime(&work->tv_staged);
  7424. #if STRATUM_WORK_TIMING
  7425. usec = us_tdiff(&work->tv_staged, &stt);
  7426. cg_wlock(&swt_lock);
  7427. stratum_work_count++;
  7428. stratum_work_time += usec;
  7429. if (stratum_work_min == 0 || stratum_work_min > usec)
  7430. stratum_work_min = usec;
  7431. if (stratum_work_max < usec)
  7432. stratum_work_max = usec;
  7433. if (usec == 0)
  7434. stratum_work_time0++;
  7435. else
  7436. {
  7437. if (usec >= 10)
  7438. {
  7439. stratum_work_time10++;
  7440. if (usec >= 100)
  7441. stratum_work_time100++;
  7442. }
  7443. }
  7444. cg_wunlock(&swt_lock);
  7445. #endif
  7446. }
  7447. #ifdef HAVE_LIBCURL
  7448. static void gen_solo_work(struct pool *pool, struct work *work);
  7449. /* Use the one instance of gbt_curl, protecting the bool with the gbt_lock but
  7450. * avoiding holding the lock once we've set the bool. */
  7451. static void get_gbt_curl(struct pool *pool, int poll)
  7452. {
  7453. cg_ilock(&pool->gbt_lock);
  7454. while (pool->gbt_curl_inuse) {
  7455. cg_uilock(&pool->gbt_lock);
  7456. cgsleep_ms(poll);
  7457. cg_ilock(&pool->gbt_lock);
  7458. }
  7459. cg_ulock(&pool->gbt_lock);
  7460. pool->gbt_curl_inuse = true;
  7461. cg_wunlock(&pool->gbt_lock);
  7462. }
  7463. /* No need for locking here */
  7464. static inline void release_gbt_curl(struct pool *pool)
  7465. {
  7466. pool->gbt_curl_inuse = false;
  7467. }
  7468. static void update_gbt_solo(struct pool *pool)
  7469. {
  7470. struct work *work = make_work();
  7471. int rolltime;
  7472. json_t *val;
  7473. get_gbt_curl(pool, 10);
  7474. retry:
  7475. /* Bitcoind doesn't like many open RPC connections. */
  7476. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  7477. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, pool->rpc_req,
  7478. true, false, &rolltime, pool, false);
  7479. if (likely(val)) {
  7480. bool rc = work_decode(pool, work, val);
  7481. if (rc) {
  7482. __setup_gbt_solo(pool);
  7483. gen_solo_work(pool, work);
  7484. stage_work(work);
  7485. } else
  7486. free_work(work);
  7487. json_decref(val);
  7488. } else {
  7489. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get gbt, retrying in 5s",
  7490. pool->pool_no);
  7491. if (++pool->seq_getfails > 5) {
  7492. pool_died(pool);
  7493. goto out;
  7494. }
  7495. cgsleep_ms(5000);
  7496. goto retry;
  7497. }
  7498. out:
  7499. release_gbt_curl(pool);
  7500. }
  7501. static void gen_solo_work(struct pool *pool, struct work *work)
  7502. {
  7503. unsigned char merkle_root[32], merkle_sha[64];
  7504. uint32_t *data32, *swap32;
  7505. struct timeval now;
  7506. uint64_t nonce2le;
  7507. int i;
  7508. cgtime(&now);
  7509. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  7510. update_gbt_solo(pool);
  7511. cg_wlock(&pool->gbt_lock);
  7512. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  7513. * from left to right and prevent overflow errors with small n2sizes */
  7514. nonce2le = htole64(pool->nonce2);
  7515. cg_memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  7516. work->nonce2 = pool->nonce2++;
  7517. work->nonce2_len = pool->n2size;
  7518. work->gbt_txns = pool->transactions + 1;
  7519. /* Downgrade to a read lock to read off the pool variables */
  7520. cg_dwlock(&pool->gbt_lock);
  7521. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  7522. /* Generate merkle root */
  7523. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  7524. cg_memcpy(merkle_sha, merkle_root, 32);
  7525. for (i = 0; i < pool->merkles; i++) {
  7526. unsigned char *merkle_bin;
  7527. merkle_bin = pool->merklebin + (i * 32);
  7528. cg_memcpy(merkle_sha + 32, merkle_bin, 32);
  7529. gen_hash(merkle_sha, merkle_root, 64);
  7530. cg_memcpy(merkle_sha, merkle_root, 32);
  7531. }
  7532. data32 = (uint32_t *)merkle_sha;
  7533. swap32 = (uint32_t *)merkle_root;
  7534. flip32(swap32, data32);
  7535. /* Copy the data template from header_bin */
  7536. cg_memcpy(work->data, pool->header_bin, 112);
  7537. cg_memcpy(work->data + 36, merkle_root, 32);
  7538. work->sdiff = pool->sdiff;
  7539. /* Copy parameters required for share submission */
  7540. work->ntime = strdup(pool->ntime);
  7541. cg_memcpy(work->target, pool->gbt_target, 32);
  7542. cg_runlock(&pool->gbt_lock);
  7543. if (opt_debug) {
  7544. char *header, *merkle_hash;
  7545. header = bin2hex(work->data, 112);
  7546. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  7547. applog(LOG_DEBUG, "Generated GBT solo merkle %s", merkle_hash);
  7548. applog(LOG_DEBUG, "Generated GBT solo header %s", header);
  7549. applog(LOG_DEBUG, "Work nonce2 %"PRIu64" ntime %s", work->nonce2,
  7550. work->ntime);
  7551. free(header);
  7552. free(merkle_hash);
  7553. }
  7554. calc_midstate(pool, work);
  7555. local_work++;
  7556. work->gbt = true;
  7557. work->pool = pool;
  7558. work->nonce = 0;
  7559. work->longpoll = false;
  7560. work->getwork_mode = GETWORK_MODE_SOLO;
  7561. work->work_block = work_block;
  7562. /* Nominally allow a driver to ntime roll 60 seconds */
  7563. work->drv_rolllimit = 60;
  7564. calc_diff(work, work->sdiff);
  7565. cgtime(&work->tv_staged);
  7566. }
  7567. #endif
  7568. /* The time difference in seconds between when this device last got work via
  7569. * get_work() and generated a valid share. */
  7570. int share_work_tdiff(struct cgpu_info *cgpu)
  7571. {
  7572. return last_getwork - cgpu->last_device_valid_work;
  7573. }
  7574. static void set_benchmark_work(struct cgpu_info *cgpu, struct work *work)
  7575. {
  7576. cgpu->lodiff += cgpu->direction;
  7577. if (cgpu->lodiff < 1)
  7578. cgpu->direction = 1;
  7579. if (cgpu->lodiff > 15) {
  7580. cgpu->direction = -1;
  7581. if (++cgpu->hidiff > 15)
  7582. cgpu->hidiff = 0;
  7583. cg_memcpy(work, &bench_hidiff_bins[cgpu->hidiff][0], 160);
  7584. } else
  7585. cg_memcpy(work, &bench_lodiff_bins[cgpu->lodiff][0], 160);
  7586. }
  7587. struct work *get_work(struct thr_info *thr, const int thr_id)
  7588. {
  7589. struct cgpu_info *cgpu = thr->cgpu;
  7590. struct work *work = NULL;
  7591. time_t diff_t;
  7592. thread_reportout(thr);
  7593. applog(LOG_DEBUG, "Popping work from get queue to get work");
  7594. diff_t = time(NULL);
  7595. while (!work) {
  7596. work = hash_pop(true);
  7597. if (stale_work(work, false)) {
  7598. discard_work(work);
  7599. wake_gws();
  7600. }
  7601. }
  7602. diff_t = time(NULL) - diff_t;
  7603. /* Since this is a blocking function, we need to add grace time to
  7604. * the device's last valid work to not make outages appear to be
  7605. * device failures. */
  7606. if (diff_t > 0) {
  7607. applog(LOG_DEBUG, "Get work blocked for %d seconds", (int)diff_t);
  7608. cgpu->last_device_valid_work += diff_t;
  7609. }
  7610. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  7611. work->thr_id = thr_id;
  7612. if (opt_benchmark)
  7613. set_benchmark_work(cgpu, work);
  7614. thread_reportin(thr);
  7615. work->mined = true;
  7616. work->device_diff = MIN(cgpu->drv->max_diff, work->work_difficulty);
  7617. work->device_diff = MAX(cgpu->drv->min_diff, work->device_diff);
  7618. return work;
  7619. }
  7620. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  7621. static void submit_work_async(struct work *work)
  7622. {
  7623. struct pool *pool = work->pool;
  7624. pthread_t submit_thread;
  7625. cgtime(&work->tv_work_found);
  7626. if (opt_benchmark) {
  7627. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  7628. mutex_lock(&stats_lock);
  7629. cgpu->accepted++;
  7630. total_accepted++;
  7631. pool->accepted++;
  7632. cgpu->diff_accepted += work->work_difficulty;
  7633. total_diff_accepted += work->work_difficulty;
  7634. pool->diff_accepted += work->work_difficulty;
  7635. mutex_unlock(&stats_lock);
  7636. applog(LOG_NOTICE, "Accepted %s %d benchmark share nonce %08x",
  7637. cgpu->drv->name, cgpu->device_id, *(uint32_t *)(work->data + 64 + 12));
  7638. return;
  7639. }
  7640. if (stale_work(work, true)) {
  7641. if (opt_submit_stale)
  7642. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  7643. else if (pool->submit_old)
  7644. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  7645. else {
  7646. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  7647. sharelog("discard", work);
  7648. mutex_lock(&stats_lock);
  7649. total_stale++;
  7650. pool->stale_shares++;
  7651. total_diff_stale += work->work_difficulty;
  7652. pool->diff_stale += work->work_difficulty;
  7653. mutex_unlock(&stats_lock);
  7654. free_work(work);
  7655. return;
  7656. }
  7657. work->stale = true;
  7658. }
  7659. if (work->stratum) {
  7660. applog(LOG_DEBUG, "Pushing pool %d work to stratum queue", pool->pool_no);
  7661. if (unlikely(!pool->stratum_q || !tq_push(pool->stratum_q, work))) {
  7662. applog(LOG_DEBUG, "Discarding work from removed pool");
  7663. free_work(work);
  7664. }
  7665. } else {
  7666. applog(LOG_DEBUG, "Pushing submit work to work thread");
  7667. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  7668. quit(1, "Failed to create submit_work_thread");
  7669. }
  7670. }
  7671. void inc_hw_errors_n(struct thr_info *thr, int n)
  7672. {
  7673. applog(LOG_INFO, "%s %d: invalid nonce - HW error", thr->cgpu->drv->name,
  7674. thr->cgpu->device_id);
  7675. mutex_lock(&stats_lock);
  7676. hw_errors += n;
  7677. thr->cgpu->hw_errors += n;
  7678. mutex_unlock(&stats_lock);
  7679. thr->cgpu->drv->hw_error(thr);
  7680. }
  7681. void inc_hw_errors(struct thr_info *thr)
  7682. {
  7683. inc_hw_errors_n(thr, 1);
  7684. }
  7685. /* Fills in the work nonce and builds the output data in work->hash */
  7686. static void rebuild_nonce(struct work *work, uint32_t nonce)
  7687. {
  7688. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7689. *work_nonce = htole32(nonce);
  7690. regen_hash(work);
  7691. }
  7692. /* For testing a nonce against diff 1 */
  7693. bool test_nonce(struct work *work, uint32_t nonce)
  7694. {
  7695. uint32_t *hash_32 = (uint32_t *)(work->hash + 28);
  7696. rebuild_nonce(work, nonce);
  7697. return (*hash_32 == 0);
  7698. }
  7699. /* For testing a nonce against an arbitrary diff */
  7700. bool test_nonce_diff(struct work *work, uint32_t nonce, double diff)
  7701. {
  7702. uint64_t *hash64 = (uint64_t *)(work->hash + 24), diff64;
  7703. rebuild_nonce(work, nonce);
  7704. diff64 = 0x00000000ffff0000ULL;
  7705. diff64 /= diff;
  7706. return (le64toh(*hash64) <= diff64);
  7707. }
  7708. /* testing a nonce and return the diff - 0 means invalid */
  7709. double test_nonce_value(struct work *work, uint32_t nonce)
  7710. {
  7711. uint32_t *hash_32 = (uint32_t *)(work->hash + 28);
  7712. double d64, s64, ds;
  7713. rebuild_nonce(work, nonce);
  7714. if (*hash_32 != 0)
  7715. return 0.0;
  7716. d64 = truediffone;
  7717. s64 = le256todouble(work->hash);
  7718. ds = d64 / s64;
  7719. return ds;
  7720. }
  7721. static void update_work_stats(struct thr_info *thr, struct work *work)
  7722. {
  7723. double test_diff = current_diff;
  7724. work->share_diff = share_diff(work);
  7725. if (unlikely(work->share_diff >= test_diff)) {
  7726. work->block = true;
  7727. work->pool->solved++;
  7728. found_blocks++;
  7729. work->mandatory = true;
  7730. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  7731. }
  7732. mutex_lock(&stats_lock);
  7733. total_diff1 += work->device_diff;
  7734. thr->cgpu->diff1 += work->device_diff;
  7735. work->pool->diff1 += work->device_diff;
  7736. thr->cgpu->last_device_valid_work = time(NULL);
  7737. mutex_unlock(&stats_lock);
  7738. }
  7739. /* To be used once the work has been tested to be meet diff1 and has had its
  7740. * nonce adjusted. Returns true if the work target is met. */
  7741. bool submit_tested_work(struct thr_info *thr, struct work *work)
  7742. {
  7743. struct work *work_out;
  7744. update_work_stats(thr, work);
  7745. // dev testing logging the difficulty of all nonces
  7746. //double diff = truediffone / le256todouble(work->hash);
  7747. //applog(LOG_ERR, "%s() %s %d: diff=%.1f", __func__,
  7748. // thr->cgpu->drv->name, thr->cgpu->device_id, diff);
  7749. if (!fulltest(work->hash, work->target)) {
  7750. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  7751. thr->cgpu->device_id);
  7752. return false;
  7753. }
  7754. work_out = copy_work(work);
  7755. submit_work_async(work_out);
  7756. return true;
  7757. }
  7758. /* Rudimentary test to see if cgpu has returned the same nonce twice in a row which is
  7759. * always going to be a duplicate which should be reported as a hw error. */
  7760. static bool new_nonce(struct thr_info *thr, uint32_t nonce)
  7761. {
  7762. struct cgpu_info *cgpu = thr->cgpu;
  7763. if (unlikely(cgpu->last_nonce == nonce)) {
  7764. applog(LOG_INFO, "%s %d duplicate share detected as HW error",
  7765. cgpu->drv->name, cgpu->device_id);
  7766. return false;
  7767. }
  7768. cgpu->last_nonce = nonce;
  7769. return true;
  7770. }
  7771. /* Returns true if nonce for work was a valid share and not a dupe of the very last
  7772. * nonce submitted by this device. */
  7773. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  7774. {
  7775. if (new_nonce(thr, nonce) && test_nonce(work, nonce))
  7776. submit_tested_work(thr, work);
  7777. else {
  7778. inc_hw_errors(thr);
  7779. return false;
  7780. }
  7781. if (opt_benchfile && opt_benchfile_display)
  7782. benchfile_dspwork(work, nonce);
  7783. return true;
  7784. }
  7785. /* Allows drivers to submit work items where the driver has changed the ntime
  7786. * value by noffset. Must be only used with a work protocol that does not ntime
  7787. * roll itself intrinsically to generate work (eg stratum). We do not touch
  7788. * the original work struct, but the copy of it only. */
  7789. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  7790. int noffset)
  7791. {
  7792. struct work *work = make_work();
  7793. bool ret = false;
  7794. _copy_work(work, work_in, noffset);
  7795. if (!test_nonce(work, nonce)) {
  7796. free_work(work);
  7797. inc_hw_errors(thr);
  7798. goto out;
  7799. }
  7800. update_work_stats(thr, work);
  7801. if (opt_benchfile && opt_benchfile_display)
  7802. benchfile_dspwork(work, nonce);
  7803. ret = true;
  7804. if (!fulltest(work->hash, work->target)) {
  7805. free_work(work);
  7806. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  7807. thr->cgpu->device_id);
  7808. goto out;
  7809. }
  7810. submit_work_async(work);
  7811. out:
  7812. return ret;
  7813. }
  7814. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  7815. {
  7816. if (wdiff->tv_sec > max_scantime || hashes >= 0xfffffffe ||
  7817. stale_work(work, false))
  7818. return true;
  7819. return false;
  7820. }
  7821. static void mt_disable(struct thr_info *mythr, const int thr_id,
  7822. struct device_drv *drv)
  7823. {
  7824. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  7825. mythr->cgpu->rolling = 0;
  7826. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  7827. cgsem_wait(&mythr->sem);
  7828. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  7829. drv->thread_enable(mythr);
  7830. }
  7831. /* The main hashing loop for devices that are slow enough to work on one work
  7832. * item at a time, without a queue, aborting work before the entire nonce
  7833. * range has been hashed if needed. */
  7834. static void hash_sole_work(struct thr_info *mythr)
  7835. {
  7836. const int thr_id = mythr->id;
  7837. struct cgpu_info *cgpu = mythr->cgpu;
  7838. struct device_drv *drv = cgpu->drv;
  7839. struct timeval getwork_start, tv_start, *tv_end, tv_workstart, tv_lastupdate;
  7840. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7841. struct cgminer_stats *pool_stats;
  7842. /* Try to cycle approximately 5 times before each log update */
  7843. const long cycle = opt_log_interval / 5 ? : 1;
  7844. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  7845. struct timeval diff, sdiff, wdiff = {0, 0};
  7846. uint32_t max_nonce = drv->can_limit_work(mythr);
  7847. int64_t hashes_done = 0;
  7848. tv_end = &getwork_start;
  7849. cgtime(&getwork_start);
  7850. sdiff.tv_sec = sdiff.tv_usec = 0;
  7851. cgtime(&tv_lastupdate);
  7852. while (likely(!cgpu->shutdown)) {
  7853. struct work *work = get_work(mythr, thr_id);
  7854. int64_t hashes;
  7855. mythr->work_restart = false;
  7856. cgpu->new_work = true;
  7857. cgtime(&tv_workstart);
  7858. work->nonce = 0;
  7859. cgpu->max_hashes = 0;
  7860. if (!drv->prepare_work(mythr, work)) {
  7861. applog(LOG_ERR, "work prepare failed, exiting "
  7862. "mining thread %d", thr_id);
  7863. break;
  7864. }
  7865. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  7866. work->device_diff = MAX(drv->min_diff, work->device_diff);
  7867. do {
  7868. cgtime(&tv_start);
  7869. subtime(&tv_start, &getwork_start);
  7870. addtime(&getwork_start, &dev_stats->getwork_wait);
  7871. if (time_more(&getwork_start, &dev_stats->getwork_wait_max))
  7872. copy_time(&dev_stats->getwork_wait_max, &getwork_start);
  7873. if (time_less(&getwork_start, &dev_stats->getwork_wait_min))
  7874. copy_time(&dev_stats->getwork_wait_min, &getwork_start);
  7875. dev_stats->getwork_calls++;
  7876. pool_stats = &(work->pool->cgminer_stats);
  7877. addtime(&getwork_start, &pool_stats->getwork_wait);
  7878. if (time_more(&getwork_start, &pool_stats->getwork_wait_max))
  7879. copy_time(&pool_stats->getwork_wait_max, &getwork_start);
  7880. if (time_less(&getwork_start, &pool_stats->getwork_wait_min))
  7881. copy_time(&pool_stats->getwork_wait_min, &getwork_start);
  7882. pool_stats->getwork_calls++;
  7883. cgtime(&(work->tv_work_start));
  7884. /* Only allow the mining thread to be cancelled when
  7885. * it is not in the driver code. */
  7886. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  7887. thread_reportin(mythr);
  7888. hashes = drv->scanhash(mythr, work, work->nonce + max_nonce);
  7889. thread_reportout(mythr);
  7890. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  7891. pthread_testcancel();
  7892. /* tv_end is == &getwork_start */
  7893. cgtime(&getwork_start);
  7894. if (unlikely(hashes == -1)) {
  7895. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  7896. cgpu->deven = DEV_DISABLED;
  7897. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  7898. cgpu->shutdown = true;
  7899. break;
  7900. }
  7901. hashes_done += hashes;
  7902. if (hashes > cgpu->max_hashes)
  7903. cgpu->max_hashes = hashes;
  7904. timersub(tv_end, &tv_start, &diff);
  7905. sdiff.tv_sec += diff.tv_sec;
  7906. sdiff.tv_usec += diff.tv_usec;
  7907. if (sdiff.tv_usec > 1000000) {
  7908. ++sdiff.tv_sec;
  7909. sdiff.tv_usec -= 1000000;
  7910. }
  7911. timersub(tv_end, &tv_workstart, &wdiff);
  7912. if (unlikely((long)sdiff.tv_sec < cycle)) {
  7913. int mult;
  7914. if (likely(max_nonce == 0xffffffff))
  7915. continue;
  7916. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  7917. mult *= cycle;
  7918. if (max_nonce > (0xffffffff * 0x400) / mult)
  7919. max_nonce = 0xffffffff;
  7920. else
  7921. max_nonce = (max_nonce * mult) / 0x400;
  7922. } else if (unlikely(sdiff.tv_sec > cycle))
  7923. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  7924. else if (unlikely(sdiff.tv_usec > 100000))
  7925. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  7926. timersub(tv_end, &tv_lastupdate, &diff);
  7927. /* Update the hashmeter at most 5 times per second */
  7928. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  7929. diff.tv_sec >= opt_log_interval) {
  7930. hashmeter(thr_id, hashes_done);
  7931. hashes_done = 0;
  7932. copy_time(&tv_lastupdate, tv_end);
  7933. }
  7934. if (unlikely(mythr->work_restart)) {
  7935. /* Apart from device_thread 0, we stagger the
  7936. * starting of every next thread to try and get
  7937. * all devices busy before worrying about
  7938. * getting work for their extra threads */
  7939. if (!primary) {
  7940. struct timespec rgtp;
  7941. rgtp.tv_sec = 0;
  7942. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  7943. nanosleep(&rgtp, NULL);
  7944. }
  7945. break;
  7946. }
  7947. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  7948. mt_disable(mythr, thr_id, drv);
  7949. sdiff.tv_sec = sdiff.tv_usec = 0;
  7950. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  7951. free_work(work);
  7952. }
  7953. cgpu->deven = DEV_DISABLED;
  7954. }
  7955. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  7956. * the driver tells us it's full so that it may extract the work item using
  7957. * the get_queued() function which adds it to the hashtable on
  7958. * cgpu->queued_work. */
  7959. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  7960. {
  7961. do {
  7962. bool need_work;
  7963. /* Do this lockless just to know if we need more unqueued work. */
  7964. need_work = (!cgpu->unqueued_work);
  7965. /* get_work is a blocking function so do it outside of lock
  7966. * to prevent deadlocks with other locks. */
  7967. if (need_work) {
  7968. struct work *work = get_work(mythr, thr_id);
  7969. wr_lock(&cgpu->qlock);
  7970. /* Check we haven't grabbed work somehow between
  7971. * checking and picking up the lock. */
  7972. if (likely(!cgpu->unqueued_work))
  7973. cgpu->unqueued_work = work;
  7974. else
  7975. need_work = false;
  7976. wr_unlock(&cgpu->qlock);
  7977. if (unlikely(!need_work))
  7978. discard_work(work);
  7979. }
  7980. /* The queue_full function should be used by the driver to
  7981. * actually place work items on the physical device if it
  7982. * does have a queue. */
  7983. } while (!drv->queue_full(cgpu));
  7984. }
  7985. /* Add a work item to a cgpu's queued hashlist */
  7986. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  7987. {
  7988. cgpu->queued_count++;
  7989. HASH_ADD_INT(cgpu->queued_work, id, work);
  7990. }
  7991. struct work *__get_queued(struct cgpu_info *cgpu)
  7992. {
  7993. struct work *work = NULL;
  7994. if (cgpu->unqueued_work) {
  7995. work = cgpu->unqueued_work;
  7996. if (unlikely(stale_work(work, false))) {
  7997. discard_work(work);
  7998. } else
  7999. __add_queued(cgpu, work);
  8000. cgpu->unqueued_work = NULL;
  8001. wake_gws();
  8002. }
  8003. return work;
  8004. }
  8005. /* This function is for retrieving one work item from the unqueued pointer and
  8006. * adding it to the hashtable of queued work. Code using this function must be
  8007. * able to handle NULL as a return which implies there is no work available. */
  8008. struct work *get_queued(struct cgpu_info *cgpu)
  8009. {
  8010. struct work *work;
  8011. wr_lock(&cgpu->qlock);
  8012. work = __get_queued(cgpu);
  8013. wr_unlock(&cgpu->qlock);
  8014. return work;
  8015. }
  8016. void add_queued(struct cgpu_info *cgpu, struct work *work)
  8017. {
  8018. wr_lock(&cgpu->qlock);
  8019. __add_queued(cgpu, work);
  8020. wr_unlock(&cgpu->qlock);
  8021. }
  8022. /* Get fresh work and add it to cgpu's queued hashlist */
  8023. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  8024. {
  8025. struct work *work = get_work(thr, thr_id);
  8026. add_queued(cgpu, work);
  8027. return work;
  8028. }
  8029. /* This function is for finding an already queued work item in the
  8030. * given que hashtable. Code using this function must be able
  8031. * to handle NULL as a return which implies there is no matching work.
  8032. * The calling function must lock access to the que if it is required.
  8033. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8034. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8035. {
  8036. struct work *work, *tmp, *ret = NULL;
  8037. HASH_ITER(hh, que, work, tmp) {
  8038. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  8039. memcmp(work->data + offset, data, datalen) == 0) {
  8040. ret = work;
  8041. break;
  8042. }
  8043. }
  8044. return ret;
  8045. }
  8046. /* This function is for finding an already queued work item in the
  8047. * device's queued_work hashtable. Code using this function must be able
  8048. * to handle NULL as a return which implies there is no matching work.
  8049. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8050. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8051. {
  8052. struct work *ret;
  8053. rd_lock(&cgpu->qlock);
  8054. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8055. rd_unlock(&cgpu->qlock);
  8056. return ret;
  8057. }
  8058. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8059. {
  8060. struct work *work, *ret = NULL;
  8061. rd_lock(&cgpu->qlock);
  8062. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8063. if (work)
  8064. ret = copy_work(work);
  8065. rd_unlock(&cgpu->qlock);
  8066. return ret;
  8067. }
  8068. /* This function is for finding an already queued work item in the
  8069. * given que hashtable. Code using this function must be able
  8070. * to handle NULL as a return which implies there is no matching work.
  8071. * The calling function must lock access to the que if it is required. */
  8072. struct work *__find_work_byid(struct work *queue, uint32_t id)
  8073. {
  8074. struct work *ret = NULL;
  8075. HASH_FIND_INT(queue, &id, ret);
  8076. return ret;
  8077. }
  8078. struct work *find_queued_work_byid(struct cgpu_info *cgpu, uint32_t id)
  8079. {
  8080. struct work *ret;
  8081. rd_lock(&cgpu->qlock);
  8082. ret = __find_work_byid(cgpu->queued_work, id);
  8083. rd_unlock(&cgpu->qlock);
  8084. return ret;
  8085. }
  8086. struct work *clone_queued_work_byid(struct cgpu_info *cgpu, uint32_t id)
  8087. {
  8088. struct work *work, *ret = NULL;
  8089. rd_lock(&cgpu->qlock);
  8090. work = __find_work_byid(cgpu->queued_work, id);
  8091. if (work)
  8092. ret = copy_work(work);
  8093. rd_unlock(&cgpu->qlock);
  8094. return ret;
  8095. }
  8096. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8097. {
  8098. cgpu->queued_count--;
  8099. HASH_DEL(cgpu->queued_work, work);
  8100. }
  8101. /* This iterates over a queued hashlist finding work started more than secs
  8102. * seconds ago and discards the work as completed. The driver must set the
  8103. * work->tv_work_start value appropriately. Returns the number of items aged. */
  8104. int age_queued_work(struct cgpu_info *cgpu, double secs)
  8105. {
  8106. struct work *work, *tmp;
  8107. struct timeval tv_now;
  8108. int aged = 0;
  8109. cgtime(&tv_now);
  8110. wr_lock(&cgpu->qlock);
  8111. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  8112. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  8113. __work_completed(cgpu, work);
  8114. free_work(work);
  8115. aged++;
  8116. }
  8117. }
  8118. wr_unlock(&cgpu->qlock);
  8119. return aged;
  8120. }
  8121. /* This function should be used by queued device drivers when they're sure
  8122. * the work struct is no longer in use. */
  8123. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8124. {
  8125. wr_lock(&cgpu->qlock);
  8126. __work_completed(cgpu, work);
  8127. wr_unlock(&cgpu->qlock);
  8128. free_work(work);
  8129. }
  8130. /* Combines find_queued_work_bymidstate and work_completed in one function
  8131. * withOUT destroying the work so the driver must free it. */
  8132. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8133. {
  8134. struct work *work;
  8135. wr_lock(&cgpu->qlock);
  8136. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8137. if (work)
  8138. __work_completed(cgpu, work);
  8139. wr_unlock(&cgpu->qlock);
  8140. return work;
  8141. }
  8142. void flush_queue(struct cgpu_info *cgpu)
  8143. {
  8144. struct work *work = NULL;
  8145. if (unlikely(!cgpu))
  8146. return;
  8147. /* Use only a trylock in case we get into a deadlock with a queueing
  8148. * function holding the read lock when we're called. */
  8149. if (wr_trylock(&cgpu->qlock))
  8150. return;
  8151. work = cgpu->unqueued_work;
  8152. cgpu->unqueued_work = NULL;
  8153. wr_unlock(&cgpu->qlock);
  8154. if (work) {
  8155. free_work(work);
  8156. applog(LOG_DEBUG, "Discarded queued work item");
  8157. }
  8158. }
  8159. /* This version of hash work is for devices that are fast enough to always
  8160. * perform a full nonce range and need a queue to maintain the device busy.
  8161. * Work creation and destruction is not done from within this function
  8162. * directly. */
  8163. void hash_queued_work(struct thr_info *mythr)
  8164. {
  8165. struct timeval tv_start = {0, 0}, tv_end;
  8166. struct cgpu_info *cgpu = mythr->cgpu;
  8167. struct device_drv *drv = cgpu->drv;
  8168. const int thr_id = mythr->id;
  8169. int64_t hashes_done = 0;
  8170. while (likely(!cgpu->shutdown)) {
  8171. struct timeval diff;
  8172. int64_t hashes;
  8173. fill_queue(mythr, cgpu, drv, thr_id);
  8174. hashes = drv->scanwork(mythr);
  8175. /* Reset the bool here in case the driver looks for it
  8176. * synchronously in the scanwork loop. */
  8177. mythr->work_restart = false;
  8178. if (unlikely(hashes == -1 )) {
  8179. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8180. cgpu->deven = DEV_DISABLED;
  8181. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8182. break;
  8183. }
  8184. hashes_done += hashes;
  8185. cgtime(&tv_end);
  8186. timersub(&tv_end, &tv_start, &diff);
  8187. /* Update the hashmeter at most 5 times per second */
  8188. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  8189. diff.tv_sec >= opt_log_interval) {
  8190. hashmeter(thr_id, hashes_done);
  8191. hashes_done = 0;
  8192. copy_time(&tv_start, &tv_end);
  8193. }
  8194. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8195. mt_disable(mythr, thr_id, drv);
  8196. if (mythr->work_update) {
  8197. drv->update_work(cgpu);
  8198. mythr->work_update = false;
  8199. }
  8200. }
  8201. cgpu->deven = DEV_DISABLED;
  8202. }
  8203. /* This version of hash_work is for devices drivers that want to do their own
  8204. * work management entirely, usually by using get_work(). Note that get_work
  8205. * is a blocking function and will wait indefinitely if no work is available
  8206. * so this must be taken into consideration in the driver. */
  8207. void hash_driver_work(struct thr_info *mythr)
  8208. {
  8209. struct timeval tv_start = {0, 0}, tv_end;
  8210. struct cgpu_info *cgpu = mythr->cgpu;
  8211. struct device_drv *drv = cgpu->drv;
  8212. const int thr_id = mythr->id;
  8213. int64_t hashes_done = 0;
  8214. while (likely(!cgpu->shutdown)) {
  8215. struct timeval diff;
  8216. int64_t hashes;
  8217. hashes = drv->scanwork(mythr);
  8218. /* Reset the bool here in case the driver looks for it
  8219. * synchronously in the scanwork loop. */
  8220. mythr->work_restart = false;
  8221. if (unlikely(hashes == -1 )) {
  8222. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8223. cgpu->deven = DEV_DISABLED;
  8224. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8225. break;
  8226. }
  8227. hashes_done += hashes;
  8228. cgtime(&tv_end);
  8229. timersub(&tv_end, &tv_start, &diff);
  8230. /* Update the hashmeter at most 5 times per second */
  8231. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  8232. diff.tv_sec >= opt_log_interval) {
  8233. hashmeter(thr_id, hashes_done);
  8234. hashes_done = 0;
  8235. copy_time(&tv_start, &tv_end);
  8236. }
  8237. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8238. mt_disable(mythr, thr_id, drv);
  8239. if (mythr->work_update) {
  8240. drv->update_work(cgpu);
  8241. mythr->work_update = false;
  8242. }
  8243. }
  8244. cgpu->deven = DEV_DISABLED;
  8245. }
  8246. void *miner_thread(void *userdata)
  8247. {
  8248. struct thr_info *mythr = userdata;
  8249. const int thr_id = mythr->id;
  8250. struct cgpu_info *cgpu = mythr->cgpu;
  8251. struct device_drv *drv = cgpu->drv;
  8252. char threadname[16];
  8253. snprintf(threadname, sizeof(threadname), "%d/Miner", thr_id);
  8254. RenameThread(threadname);
  8255. thread_reportout(mythr);
  8256. if (!drv->thread_init(mythr)) {
  8257. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  8258. goto out;
  8259. }
  8260. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  8261. cgsem_wait(&mythr->sem);
  8262. cgpu->last_device_valid_work = time(NULL);
  8263. drv->hash_work(mythr);
  8264. drv->thread_shutdown(mythr);
  8265. out:
  8266. return NULL;
  8267. }
  8268. enum {
  8269. STAT_SLEEP_INTERVAL = 1,
  8270. STAT_CTR_INTERVAL = 10000000,
  8271. FAILURE_INTERVAL = 30,
  8272. };
  8273. #ifdef HAVE_LIBCURL
  8274. /* Stage another work item from the work returned in a longpoll */
  8275. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  8276. {
  8277. struct work *work;
  8278. bool rc;
  8279. work = make_work();
  8280. rc = work_decode(pool, work, val);
  8281. if (unlikely(!rc)) {
  8282. applog(LOG_ERR, "Could not convert longpoll data to work");
  8283. free_work(work);
  8284. return;
  8285. }
  8286. total_getworks++;
  8287. pool->getwork_requested++;
  8288. work->pool = pool;
  8289. work->rolltime = rolltime;
  8290. copy_time(&work->tv_getwork, tv_lp);
  8291. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8292. calc_diff(work, 0);
  8293. if (pool->enabled == POOL_REJECTING)
  8294. work->mandatory = true;
  8295. if (pool->has_gbt)
  8296. gen_gbt_work(pool, work);
  8297. work->longpoll = true;
  8298. work->getwork_mode = GETWORK_MODE_LP;
  8299. /* We'll be checking this work item twice, but we already know it's
  8300. * from a new block so explicitly force the new block detection now
  8301. * rather than waiting for it to hit the stage thread. This also
  8302. * allows testwork to know whether LP discovered the block or not. */
  8303. test_work_current(work);
  8304. work = clone_work(work);
  8305. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8306. stage_work(work);
  8307. applog(LOG_DEBUG, "Converted longpoll data to work");
  8308. }
  8309. /* If we want longpoll, enable it for the chosen default pool, or, if
  8310. * the pool does not support longpoll, find the first one that does
  8311. * and use its longpoll support */
  8312. static struct pool *select_longpoll_pool(struct pool *cp)
  8313. {
  8314. int i;
  8315. if (cp->hdr_path || cp->has_gbt || cp->gbt_solo)
  8316. return cp;
  8317. for (i = 0; i < total_pools; i++) {
  8318. struct pool *pool = pools[i];
  8319. if (pool->has_stratum || pool->hdr_path)
  8320. return pool;
  8321. }
  8322. return NULL;
  8323. }
  8324. #endif /* HAVE_LIBCURL */
  8325. /* This will make the longpoll thread wait till it's the current pool, or it
  8326. * has been flagged as rejecting, before attempting to open any connections.
  8327. */
  8328. static void wait_lpcurrent(struct pool *pool)
  8329. {
  8330. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  8331. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  8332. pool_strategy != POOL_BALANCE))) {
  8333. mutex_lock(&lp_lock);
  8334. pthread_cond_wait(&lp_cond, &lp_lock);
  8335. mutex_unlock(&lp_lock);
  8336. }
  8337. }
  8338. #ifdef HAVE_LIBCURL
  8339. static void *longpoll_thread(void *userdata)
  8340. {
  8341. struct pool *cp = (struct pool *)userdata;
  8342. /* This *pool is the source of the actual longpoll, not the pool we've
  8343. * tied it to */
  8344. struct timeval start, reply, end;
  8345. struct pool *pool = NULL;
  8346. char threadname[16];
  8347. CURL *curl = NULL;
  8348. int failures = 0;
  8349. char lpreq[1024];
  8350. char *lp_url;
  8351. int rolltime;
  8352. snprintf(threadname, sizeof(threadname), "%d/Longpoll", cp->pool_no);
  8353. RenameThread(threadname);
  8354. retry_pool:
  8355. pool = select_longpoll_pool(cp);
  8356. if (!pool) {
  8357. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8358. while (!pool) {
  8359. cgsleep_ms(60000);
  8360. pool = select_longpoll_pool(cp);
  8361. }
  8362. }
  8363. if (pool->has_stratum) {
  8364. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8365. cp->rpc_url, pool->rpc_url);
  8366. goto out;
  8367. }
  8368. if (pool->gbt_solo) {
  8369. applog(LOG_WARNING, "Block change for %s detection via getblockcount polling",
  8370. cp->rpc_url);
  8371. while (42) {
  8372. json_t *val, *res_val = NULL;
  8373. if (unlikely(pool->removed))
  8374. return NULL;
  8375. cgtime(&start);
  8376. wait_lpcurrent(cp);
  8377. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockcount\"}\n");
  8378. /* We will be making another call immediately after this
  8379. * one to get the height so allow this curl to be reused.*/
  8380. get_gbt_curl(pool, 500);
  8381. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 0);
  8382. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, lpreq, true,
  8383. false, &rolltime, pool, false);
  8384. release_gbt_curl(pool);
  8385. if (likely(val))
  8386. res_val = json_object_get(val, "result");
  8387. if (likely(res_val)) {
  8388. int height = json_integer_value(res_val);
  8389. const char *prev_hash;
  8390. failures = 0;
  8391. json_decref(val);
  8392. if (height >= cp->height) {
  8393. applog(LOG_WARNING, "Block height change to %d detected on pool %d",
  8394. height, cp->pool_no);
  8395. update_gbt_solo(pool);
  8396. continue;
  8397. }
  8398. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockhash\", \"params\": [%d]}\n", height);
  8399. get_gbt_curl(pool, 500);
  8400. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  8401. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass,
  8402. lpreq, true, false, &rolltime, pool, false);
  8403. release_gbt_curl(pool);
  8404. if (val) {
  8405. /* Do a comparison on a short stretch of
  8406. * the hash to make sure it hasn't changed
  8407. * due to mining on an orphan branch. */
  8408. prev_hash = json_string_value(json_object_get(val, "result"));
  8409. if (unlikely(prev_hash && strncasecmp(prev_hash + 56, pool->prev_hash, 8))) {
  8410. applog(LOG_WARNING, "Mining on orphan branch detected, switching!");
  8411. update_gbt_solo(pool);
  8412. }
  8413. json_decref(val);
  8414. }
  8415. cgsleep_ms(500);
  8416. } else {
  8417. if (val)
  8418. json_decref(val);
  8419. cgtime(&end);
  8420. if (end.tv_sec - start.tv_sec > 30)
  8421. continue;
  8422. if (failures == 1)
  8423. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8424. cgsleep_ms(30000);
  8425. }
  8426. }
  8427. }
  8428. curl = curl_easy_init();
  8429. if (unlikely(!curl))
  8430. quit (1, "Longpoll CURL initialisation failed");
  8431. /* Any longpoll from any pool is enough for this to be true */
  8432. have_longpoll = true;
  8433. wait_lpcurrent(cp);
  8434. lp_url = pool->rpc_url;
  8435. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  8436. while (42) {
  8437. json_t *val, *soval;
  8438. wait_lpcurrent(cp);
  8439. cgtime(&start);
  8440. /* Update the longpollid every time, but do it under lock to
  8441. * avoid races */
  8442. if (pool->has_gbt) {
  8443. cg_rlock(&pool->gbt_lock);
  8444. snprintf(lpreq, sizeof(lpreq),
  8445. "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  8446. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  8447. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  8448. cg_runlock(&pool->gbt_lock);
  8449. }
  8450. /* Longpoll connections can be persistent for a very long time
  8451. * and any number of issues could have come up in the meantime
  8452. * so always establish a fresh connection instead of relying on
  8453. * a persistent one. */
  8454. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8455. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8456. lpreq, false, true, &rolltime, pool, false);
  8457. cgtime(&reply);
  8458. if (likely(val)) {
  8459. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8460. if (soval)
  8461. pool->submit_old = json_is_true(soval);
  8462. else
  8463. pool->submit_old = false;
  8464. convert_to_work(val, rolltime, pool, &start, &reply);
  8465. failures = 0;
  8466. json_decref(val);
  8467. } else {
  8468. /* Some pools regularly drop the longpoll request so
  8469. * only see this as longpoll failure if it happens
  8470. * immediately and just restart it the rest of the
  8471. * time. */
  8472. cgtime(&end);
  8473. if (end.tv_sec - start.tv_sec > 30)
  8474. continue;
  8475. if (failures == 1)
  8476. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8477. cgsleep_ms(30000);
  8478. }
  8479. if (pool != cp) {
  8480. pool = select_longpoll_pool(cp);
  8481. if (pool->has_stratum) {
  8482. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8483. cp->rpc_url, pool->rpc_url);
  8484. break;
  8485. }
  8486. if (unlikely(!pool))
  8487. goto retry_pool;
  8488. }
  8489. if (unlikely(pool->removed))
  8490. break;
  8491. }
  8492. out:
  8493. curl_easy_cleanup(curl);
  8494. return NULL;
  8495. }
  8496. #else /* HAVE_LIBCURL */
  8497. static void *longpoll_thread(void __maybe_unused *userdata)
  8498. {
  8499. pthread_detach(pthread_self());
  8500. return NULL;
  8501. }
  8502. #endif /* HAVE_LIBCURL */
  8503. void reinit_device(struct cgpu_info *cgpu)
  8504. {
  8505. if (cgpu->deven == DEV_DISABLED)
  8506. return;
  8507. #ifdef USE_USBUTILS
  8508. /* Attempt a usb device reset if the device has gone sick */
  8509. if (cgpu->usbdev && cgpu->usbdev->handle)
  8510. libusb_reset_device(cgpu->usbdev->handle);
  8511. #endif
  8512. cgpu->drv->reinit_device(cgpu);
  8513. }
  8514. static struct timeval rotate_tv;
  8515. /* We reap curls if they are unused for over a minute */
  8516. static void reap_curl(struct pool *pool)
  8517. {
  8518. struct curl_ent *ent, *iter;
  8519. struct timeval now;
  8520. int reaped = 0;
  8521. cgtime(&now);
  8522. mutex_lock(&pool->pool_lock);
  8523. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  8524. if (pool->curls < 2)
  8525. break;
  8526. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8527. reaped++;
  8528. pool->curls--;
  8529. list_del(&ent->node);
  8530. curl_easy_cleanup(ent->curl);
  8531. free(ent);
  8532. }
  8533. }
  8534. mutex_unlock(&pool->pool_lock);
  8535. if (reaped)
  8536. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8537. }
  8538. /* Prune old shares we haven't had a response about for over 2 minutes in case
  8539. * the pool never plans to respond and we're just leaking memory. If we get a
  8540. * response beyond that time they will be seen as untracked shares. */
  8541. static void prune_stratum_shares(struct pool *pool)
  8542. {
  8543. struct stratum_share *sshare, *tmpshare;
  8544. time_t current_time = time(NULL);
  8545. int cleared = 0;
  8546. mutex_lock(&sshare_lock);
  8547. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  8548. if (sshare->work->pool == pool && current_time > sshare->sshare_time + 120) {
  8549. HASH_DEL(stratum_shares, sshare);
  8550. free_work(sshare->work);
  8551. free(sshare);
  8552. cleared++;
  8553. }
  8554. }
  8555. mutex_unlock(&sshare_lock);
  8556. if (cleared) {
  8557. applog(LOG_WARNING, "Lost %d shares due to no stratum share response from pool %d",
  8558. cleared, pool->pool_no);
  8559. pool->stale_shares += cleared;
  8560. total_stale += cleared;
  8561. }
  8562. }
  8563. static void *watchpool_thread(void __maybe_unused *userdata)
  8564. {
  8565. int intervals = 0;
  8566. cgtimer_t cgt;
  8567. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8568. RenameThread("Watchpool");
  8569. set_lowprio();
  8570. cgtimer_time(&cgt);
  8571. while (42) {
  8572. struct timeval now;
  8573. int i;
  8574. if (++intervals > 120)
  8575. intervals = 0;
  8576. cgtime(&now);
  8577. for (i = 0; i < total_pools; i++) {
  8578. struct pool *pool = pools[i];
  8579. if (!opt_benchmark && !opt_benchfile) {
  8580. reap_curl(pool);
  8581. prune_stratum_shares(pool);
  8582. }
  8583. /* Get a rolling utility per pool over 10 mins */
  8584. if (intervals > 119) {
  8585. double shares = pool->diff1 - pool->last_shares;
  8586. pool->last_shares = pool->diff1;
  8587. pool->utility = (pool->utility + shares * 0.63) / 1.63;
  8588. pool->shares = pool->utility;
  8589. }
  8590. if (pool->enabled == POOL_DISABLED)
  8591. continue;
  8592. /* Don't start testing a pool if its test thread
  8593. * from startup is still doing its first attempt. */
  8594. if (unlikely(pool->testing))
  8595. continue;
  8596. if (pool_active(pool, true)) {
  8597. if (pool_tclear(pool, &pool->idle))
  8598. pool_resus(pool);
  8599. } else
  8600. cgtime(&pool->tv_idle);
  8601. /* Only switch pools if the failback pool has been
  8602. * alive for more than 5 minutes to prevent
  8603. * intermittently failing pools from being used. */
  8604. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8605. now.tv_sec - pool->tv_idle.tv_sec > opt_pool_fallback) {
  8606. applog(LOG_WARNING, "Pool %d %s stable for >%d seconds",
  8607. pool->pool_no, pool->rpc_url, opt_pool_fallback);
  8608. switch_pools(NULL);
  8609. }
  8610. }
  8611. if (current_pool()->idle)
  8612. switch_pools(NULL);
  8613. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8614. cgtime(&rotate_tv);
  8615. switch_pools(NULL);
  8616. }
  8617. cgsleep_ms_r(&cgt, 5000);
  8618. cgtimer_time(&cgt);
  8619. }
  8620. return NULL;
  8621. }
  8622. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  8623. * the screen at regular intervals, and restarts threads if they appear to have
  8624. * died. */
  8625. #define WATCHDOG_INTERVAL 2
  8626. #define WATCHDOG_SICK_TIME 120
  8627. #define WATCHDOG_DEAD_TIME 600
  8628. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  8629. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  8630. static void *watchdog_thread(void __maybe_unused *userdata)
  8631. {
  8632. const unsigned int interval = WATCHDOG_INTERVAL;
  8633. struct timeval zero_tv;
  8634. #ifdef USE_LIBSYSTEMD
  8635. uint64_t notify_usec;
  8636. struct timeval notify_interval, notify_tv;
  8637. memset(&notify_interval, 0, sizeof(struct timeval));
  8638. memset(&notify_tv, 0, sizeof(struct timeval));
  8639. if (sd_watchdog_enabled(false, &notify_usec)) {
  8640. notify_usec = notify_usec / 2;
  8641. us_to_timeval(&notify_interval, notify_usec);
  8642. cgtime(&notify_tv);
  8643. addtime(&notify_interval, &notify_tv);
  8644. applog(LOG_DEBUG, "Watchdog notify interval: %.3gs",
  8645. notify_usec / 1000000.0);
  8646. }
  8647. #endif
  8648. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8649. RenameThread("Watchdog");
  8650. set_lowprio();
  8651. memset(&zero_tv, 0, sizeof(struct timeval));
  8652. cgtime(&rotate_tv);
  8653. while (1) {
  8654. int i;
  8655. struct timeval now;
  8656. sleep(interval);
  8657. discard_stale();
  8658. hashmeter(-1, 0);
  8659. #ifdef HAVE_CURSES
  8660. if (curses_active_locked()) {
  8661. struct cgpu_info *cgpu;
  8662. int count;
  8663. change_logwinsize();
  8664. curses_print_status();
  8665. count = 0;
  8666. for (i = 0; i < total_devices; i++) {
  8667. cgpu = get_devices(i);
  8668. #ifndef USE_USBUTILS
  8669. if (cgpu)
  8670. #else
  8671. if (cgpu && !cgpu->usbinfo.nodev)
  8672. #endif
  8673. curses_print_devstatus(cgpu, i, count++);
  8674. }
  8675. #ifdef USE_USBUTILS
  8676. for (i = 0; i < total_devices; i++) {
  8677. cgpu = get_devices(i);
  8678. if (cgpu && cgpu->usbinfo.nodev)
  8679. curses_print_devstatus(cgpu, i, count++);
  8680. }
  8681. #endif
  8682. touchwin(statuswin);
  8683. wrefresh(statuswin);
  8684. touchwin(logwin);
  8685. wrefresh(logwin);
  8686. unlock_curses();
  8687. }
  8688. #endif
  8689. cgtime(&now);
  8690. #if USE_LIBSYSTEMD
  8691. if (notify_usec && !time_more(&notify_tv, &now)) {
  8692. sd_notify(false, "WATCHDOG=1");
  8693. copy_time(&notify_tv, &now);
  8694. addtime(&notify_interval, &notify_tv);
  8695. applog(LOG_DEBUG, "Notified watchdog");
  8696. }
  8697. #endif
  8698. if (!sched_paused && !should_run()) {
  8699. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  8700. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8701. if (!schedstart.enable) {
  8702. quit(0, "Terminating execution as planned");
  8703. break;
  8704. }
  8705. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  8706. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8707. sched_paused = true;
  8708. rd_lock(&mining_thr_lock);
  8709. for (i = 0; i < mining_threads; i++)
  8710. mining_thr[i]->pause = true;
  8711. rd_unlock(&mining_thr_lock);
  8712. } else if (sched_paused && should_run()) {
  8713. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  8714. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8715. if (schedstop.enable)
  8716. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  8717. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8718. sched_paused = false;
  8719. for (i = 0; i < mining_threads; i++) {
  8720. struct thr_info *thr;
  8721. thr = get_thread(i);
  8722. /* Don't touch disabled devices */
  8723. if (thr->cgpu->deven == DEV_DISABLED)
  8724. continue;
  8725. thr->pause = false;
  8726. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  8727. cgsem_post(&thr->sem);
  8728. }
  8729. }
  8730. for (i = 0; i < total_devices; ++i) {
  8731. struct cgpu_info *cgpu = get_devices(i);
  8732. struct thr_info *thr = cgpu->thr[0];
  8733. enum dev_enable *denable;
  8734. char dev_str[8];
  8735. if (!thr)
  8736. continue;
  8737. cgpu->drv->get_stats(cgpu);
  8738. denable = &cgpu->deven;
  8739. snprintf(dev_str, sizeof(dev_str), "%s %d", cgpu->drv->name, cgpu->device_id);
  8740. /* Thread is waiting on getwork or disabled */
  8741. if (thr->getwork || *denable == DEV_DISABLED || thr->pause)
  8742. continue;
  8743. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  8744. if (cgpu->status != LIFE_INIT)
  8745. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  8746. cgpu->status = LIFE_WELL;
  8747. cgpu->device_last_well = time(NULL);
  8748. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  8749. cgpu->rolling = 0;
  8750. cgpu->status = LIFE_SICK;
  8751. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  8752. cgtime(&thr->sick);
  8753. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  8754. if (opt_restart) {
  8755. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  8756. reinit_device(cgpu);
  8757. }
  8758. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  8759. cgpu->status = LIFE_DEAD;
  8760. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  8761. cgtime(&thr->sick);
  8762. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  8763. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  8764. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  8765. /* Attempt to restart a GPU that's sick or dead once every minute */
  8766. cgtime(&thr->sick);
  8767. if (opt_restart)
  8768. reinit_device(cgpu);
  8769. }
  8770. }
  8771. }
  8772. return NULL;
  8773. }
  8774. static void log_print_status(struct cgpu_info *cgpu)
  8775. {
  8776. char logline[255];
  8777. get_statline(logline, sizeof(logline), cgpu);
  8778. applog(LOG_WARNING, "%s", logline);
  8779. }
  8780. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu);
  8781. void blank_get_statline_before(char *buf, size_t bufsiz, struct cgpu_info __maybe_unused *cgpu);
  8782. void print_summary(void)
  8783. {
  8784. struct timeval diff;
  8785. int hours, mins, secs, i;
  8786. double utility, displayed_hashes, work_util;
  8787. timersub(&total_tv_end, &total_tv_start, &diff);
  8788. hours = diff.tv_sec / 3600;
  8789. mins = (diff.tv_sec % 3600) / 60;
  8790. secs = diff.tv_sec % 60;
  8791. utility = total_accepted / total_secs * 60;
  8792. work_util = total_diff1 / total_secs * 60;
  8793. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  8794. applog(LOG_WARNING, "Started at %s", datestamp);
  8795. if (total_pools == 1)
  8796. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  8797. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  8798. displayed_hashes = total_mhashes_done / total_secs;
  8799. applog(LOG_WARNING, "Average hashrate: %.1f Mhash/s", displayed_hashes);
  8800. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  8801. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  8802. applog(LOG_WARNING, "Share submissions: %"PRId64, total_accepted + total_rejected);
  8803. applog(LOG_WARNING, "Accepted shares: %"PRId64, total_accepted);
  8804. applog(LOG_WARNING, "Rejected shares: %"PRId64, total_rejected);
  8805. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  8806. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  8807. if (total_accepted || total_rejected)
  8808. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  8809. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  8810. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  8811. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  8812. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %"PRId64, total_stale);
  8813. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  8814. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  8815. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  8816. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  8817. if (total_pools > 1) {
  8818. for (i = 0; i < total_pools; i++) {
  8819. struct pool *pool = pools[i];
  8820. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  8821. if (pool->solved)
  8822. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  8823. applog(LOG_WARNING, " Share submissions: %"PRId64, pool->accepted + pool->rejected);
  8824. applog(LOG_WARNING, " Accepted shares: %"PRId64, pool->accepted);
  8825. applog(LOG_WARNING, " Rejected shares: %"PRId64, pool->rejected);
  8826. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  8827. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  8828. if (pool->accepted || pool->rejected)
  8829. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  8830. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  8831. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  8832. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  8833. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  8834. }
  8835. }
  8836. applog(LOG_WARNING, "Summary of per device statistics:\n");
  8837. for (i = 0; i < total_devices; ++i) {
  8838. struct cgpu_info *cgpu = get_devices(i);
  8839. cgpu->drv->get_statline_before = &blank_get_statline_before;
  8840. cgpu->drv->get_statline = &noop_get_statline;
  8841. log_print_status(cgpu);
  8842. }
  8843. if (opt_shares) {
  8844. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  8845. if (opt_shares > total_diff_accepted)
  8846. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  8847. }
  8848. applog(LOG_WARNING, " ");
  8849. fflush(stderr);
  8850. fflush(stdout);
  8851. }
  8852. static void clean_up(bool restarting)
  8853. {
  8854. #ifdef USE_BITMAIN_SOC
  8855. struct sysinfo sInfo;
  8856. if (sysinfo(&sInfo))
  8857. {
  8858. applog(LOG_INFO, "Failed to get sysinfo, errno:%u, reason:%s\n",
  8859. errno, strerror(errno));
  8860. total_tv_end_sys=time(NULL);
  8861. }
  8862. else
  8863. {
  8864. total_tv_end_sys=sInfo.uptime;
  8865. }
  8866. #endif
  8867. #ifdef USE_USBUTILS
  8868. usb_polling = false;
  8869. pthread_join(usb_poll_thread, NULL);
  8870. libusb_exit(NULL);
  8871. #endif
  8872. cgtime(&total_tv_end);
  8873. #ifdef WIN32
  8874. timeEndPeriod(1);
  8875. #endif
  8876. #ifdef HAVE_CURSES
  8877. disable_curses();
  8878. #endif
  8879. if (!restarting && !opt_realquiet && successful_connect)
  8880. print_summary();
  8881. curl_global_cleanup();
  8882. }
  8883. /* Should all else fail and we're unable to clean up threads due to locking
  8884. * issues etc, just silently exit. */
  8885. static void *killall_thread(void __maybe_unused *arg)
  8886. {
  8887. pthread_detach(pthread_self());
  8888. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8889. sleep(5);
  8890. exit(1);
  8891. return NULL;
  8892. }
  8893. void __quit(int status, bool clean)
  8894. {
  8895. pthread_t killall_t;
  8896. #ifdef USE_LIBSYSTEMD
  8897. sd_notify(false, "STOPPING=1\n"
  8898. "STATUS=Shutting down...");
  8899. #endif
  8900. if (unlikely(pthread_create(&killall_t, NULL, killall_thread, NULL)))
  8901. exit(1);
  8902. if (clean)
  8903. clean_up(false);
  8904. #ifdef HAVE_CURSES
  8905. else
  8906. disable_curses();
  8907. #endif
  8908. #if defined(unix) || defined(__APPLE__)
  8909. if (forkpid > 0) {
  8910. kill(forkpid, SIGTERM);
  8911. forkpid = 0;
  8912. }
  8913. #endif
  8914. pthread_cancel(killall_t);
  8915. exit(status);
  8916. }
  8917. void _quit(int status)
  8918. {
  8919. __quit(status, true);
  8920. }
  8921. #ifdef HAVE_CURSES
  8922. char *curses_input(const char *query)
  8923. {
  8924. char *input;
  8925. echo();
  8926. input = cgmalloc(255);
  8927. leaveok(logwin, false);
  8928. wlogprint("%s:\n", query);
  8929. wgetnstr(logwin, input, 255);
  8930. if (!strlen(input))
  8931. strcpy(input, "-1");
  8932. leaveok(logwin, true);
  8933. noecho();
  8934. return input;
  8935. }
  8936. #endif
  8937. static bool pools_active = false;
  8938. static void *test_pool_thread(void *arg)
  8939. {
  8940. struct pool *pool = (struct pool *)arg;
  8941. if (!pool->blocking)
  8942. pthread_detach(pthread_self());
  8943. retry:
  8944. if (pool->removed)
  8945. goto out;
  8946. if (pool_active(pool, false)) {
  8947. pool_tclear(pool, &pool->idle);
  8948. bool first_pool = false;
  8949. cg_wlock(&control_lock);
  8950. if (!pools_active) {
  8951. currentpool = pool;
  8952. if (pool->pool_no != 0)
  8953. first_pool = true;
  8954. pools_active = true;
  8955. }
  8956. cg_wunlock(&control_lock);
  8957. if (unlikely(first_pool))
  8958. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  8959. pool_resus(pool);
  8960. switch_pools(NULL);
  8961. } else {
  8962. pool_died(pool);
  8963. if (!pool->blocking) {
  8964. sleep(5);
  8965. goto retry;
  8966. }
  8967. }
  8968. pool->testing = false;
  8969. out:
  8970. return NULL;
  8971. }
  8972. /* Always returns true that the pool details were added unless we are not
  8973. * live, implying this is the only pool being added, so if no pools are
  8974. * active it returns false. */
  8975. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  8976. {
  8977. size_t siz;
  8978. pool->rpc_url = url;
  8979. pool->rpc_user = user;
  8980. pool->rpc_pass = pass;
  8981. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8982. pool->rpc_userpass = cgmalloc(siz);
  8983. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8984. pool->testing = true;
  8985. pool->idle = true;
  8986. pool->blocking = !live;
  8987. enable_pool(pool);
  8988. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8989. if (!live) {
  8990. pthread_join(pool->test_thread, NULL);
  8991. return pools_active;
  8992. }
  8993. return true;
  8994. }
  8995. #ifdef HAVE_CURSES
  8996. static bool input_pool(bool live)
  8997. {
  8998. char *url, *user, *pass;
  8999. struct pool *pool;
  9000. bool ret = false;
  9001. immedok(logwin, true);
  9002. wlogprint("Input server details.\n");
  9003. retry:
  9004. url = NULL;
  9005. user = NULL;
  9006. pass = NULL;
  9007. url = curses_input("URL");
  9008. if (!strcmp(url, "-1")) {
  9009. wlogprint("Invalid input\n");
  9010. goto out;
  9011. }
  9012. user = curses_input("Username");
  9013. if (!strcmp(user, "-1")) {
  9014. wlogprint("Invalid input\n");
  9015. goto out;
  9016. }
  9017. pass = curses_input("Password [enter for none]");
  9018. if (!strcmp(pass, "-1")) {
  9019. free(pass);
  9020. pass = strdup("");
  9021. }
  9022. pool = add_pool();
  9023. url = setup_url(pool, url);
  9024. ret = add_pool_details(pool, live, url, user, pass);
  9025. if (!ret) {
  9026. remove_pool(pool);
  9027. wlogprint("URL %s failed alive testing, reinput details\n", url);
  9028. free(url);
  9029. free(user);
  9030. free(pass);
  9031. goto retry;
  9032. }
  9033. out:
  9034. immedok(logwin, false);
  9035. if (!ret) {
  9036. free(url);
  9037. free(user);
  9038. free(pass);
  9039. }
  9040. return ret;
  9041. }
  9042. #endif
  9043. #if defined(unix) || defined(__APPLE__)
  9044. static void fork_monitor()
  9045. {
  9046. // Make a pipe: [readFD, writeFD]
  9047. int pfd[2];
  9048. int r = pipe(pfd);
  9049. if (r < 0) {
  9050. perror("pipe - failed to create pipe for --monitor");
  9051. exit(1);
  9052. }
  9053. // Make stderr write end of pipe
  9054. fflush(stderr);
  9055. r = dup2(pfd[1], 2);
  9056. if (r < 0) {
  9057. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  9058. exit(1);
  9059. }
  9060. r = close(pfd[1]);
  9061. if (r < 0) {
  9062. perror("close - failed to close write end of pipe for --monitor");
  9063. exit(1);
  9064. }
  9065. // Don't allow a dying monitor to kill the main process
  9066. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9067. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9068. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9069. perror("signal - failed to edit signal mask for --monitor");
  9070. exit(1);
  9071. }
  9072. // Fork a child process
  9073. forkpid = fork();
  9074. if (forkpid < 0) {
  9075. perror("fork - failed to fork child process for --monitor");
  9076. exit(1);
  9077. }
  9078. // Child: launch monitor command
  9079. if (0 == forkpid) {
  9080. // Make stdin read end of pipe
  9081. r = dup2(pfd[0], 0);
  9082. if (r < 0) {
  9083. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9084. exit(1);
  9085. }
  9086. close(pfd[0]);
  9087. if (r < 0) {
  9088. perror("close - in child, failed to close read end of pipe for --monitor");
  9089. exit(1);
  9090. }
  9091. // Launch user specified command
  9092. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9093. perror("execl - in child failed to exec user specified command for --monitor");
  9094. exit(1);
  9095. }
  9096. // Parent: clean up unused fds and bail
  9097. r = close(pfd[0]);
  9098. if (r < 0) {
  9099. perror("close - failed to close read end of pipe for --monitor");
  9100. exit(1);
  9101. }
  9102. }
  9103. #endif // defined(unix)
  9104. #ifdef HAVE_CURSES
  9105. static void enable_curses_windows(void)
  9106. {
  9107. int x,y;
  9108. getmaxyx(mainwin, y, x);
  9109. statuswin = newwin(logstart, x, 0, 0);
  9110. leaveok(statuswin, true);
  9111. logwin = newwin(y - logcursor, 0, logcursor, 0);
  9112. idlok(logwin, true);
  9113. scrollok(logwin, true);
  9114. leaveok(logwin, true);
  9115. cbreak();
  9116. noecho();
  9117. }
  9118. void enable_curses(void) {
  9119. lock_curses();
  9120. if (curses_active) {
  9121. unlock_curses();
  9122. return;
  9123. }
  9124. mainwin = initscr();
  9125. enable_curses_windows();
  9126. curses_active = true;
  9127. statusy = logstart;
  9128. unlock_curses();
  9129. }
  9130. #endif
  9131. static int cgminer_id_count = 0;
  9132. /* Various noop functions for drivers that don't support or need their
  9133. * variants. */
  9134. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  9135. {
  9136. }
  9137. void blank_get_statline_before(char __maybe_unused *buf,size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  9138. {
  9139. }
  9140. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  9141. {
  9142. }
  9143. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  9144. {
  9145. return true;
  9146. }
  9147. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  9148. {
  9149. return true;
  9150. }
  9151. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  9152. {
  9153. return 0xffffffff;
  9154. }
  9155. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  9156. {
  9157. return true;
  9158. }
  9159. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  9160. {
  9161. return true;
  9162. }
  9163. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  9164. {
  9165. }
  9166. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  9167. {
  9168. }
  9169. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  9170. {
  9171. }
  9172. static void noop_detect(bool __maybe_unused hotplug)
  9173. {
  9174. }
  9175. static struct api_data *noop_get_api_stats(struct cgpu_info __maybe_unused *cgpu)
  9176. {
  9177. return NULL;
  9178. }
  9179. static void noop_hash_work(struct thr_info __maybe_unused *thr)
  9180. {
  9181. }
  9182. static void generic_zero_stats(struct cgpu_info *cgpu)
  9183. {
  9184. cgpu->diff_accepted =
  9185. cgpu->diff_rejected =
  9186. cgpu->hw_errors = 0;
  9187. }
  9188. #define noop_flush_work noop_reinit_device
  9189. #define noop_update_work noop_reinit_device
  9190. #define noop_queue_full noop_get_stats
  9191. #define noop_identify_device noop_reinit_device
  9192. /* Fill missing driver drv functions with noops */
  9193. void fill_device_drv(struct device_drv *drv)
  9194. {
  9195. if (!drv->drv_detect)
  9196. drv->drv_detect = &noop_detect;
  9197. if (!drv->reinit_device)
  9198. drv->reinit_device = &noop_reinit_device;
  9199. if (!drv->get_statline_before)
  9200. drv->get_statline_before = &blank_get_statline_before;
  9201. if (!drv->get_statline)
  9202. drv->get_statline = &noop_get_statline;
  9203. if (!drv->get_stats)
  9204. drv->get_stats = &noop_get_stats;
  9205. if (!drv->thread_prepare)
  9206. drv->thread_prepare = &noop_thread_prepare;
  9207. if (!drv->can_limit_work)
  9208. drv->can_limit_work = &noop_can_limit_work;
  9209. if (!drv->thread_init)
  9210. drv->thread_init = &noop_thread_init;
  9211. if (!drv->prepare_work)
  9212. drv->prepare_work = &noop_prepare_work;
  9213. if (!drv->hw_error)
  9214. drv->hw_error = &noop_hw_error;
  9215. if (!drv->thread_shutdown)
  9216. drv->thread_shutdown = &noop_thread_shutdown;
  9217. if (!drv->thread_enable)
  9218. drv->thread_enable = &noop_thread_enable;
  9219. if (!drv->hash_work)
  9220. drv->hash_work = &hash_sole_work;
  9221. if (!drv->flush_work)
  9222. drv->flush_work = &noop_flush_work;
  9223. if (!drv->update_work)
  9224. drv->update_work = &noop_update_work;
  9225. if (!drv->queue_full)
  9226. drv->queue_full = &noop_queue_full;
  9227. if (!drv->zero_stats)
  9228. drv->zero_stats = &generic_zero_stats;
  9229. /* If drivers support internal diff they should set a max_diff or
  9230. * we will assume they don't and set max to 1. */
  9231. if (!drv->max_diff)
  9232. drv->max_diff = 1;
  9233. if (!drv->genwork)
  9234. opt_gen_stratum_work = true;
  9235. }
  9236. void null_device_drv(struct device_drv *drv)
  9237. {
  9238. drv->drv_detect = &noop_detect;
  9239. drv->reinit_device = &noop_reinit_device;
  9240. drv->get_statline_before = &blank_get_statline_before;
  9241. drv->get_statline = &noop_get_statline;
  9242. drv->get_api_stats = &noop_get_api_stats;
  9243. drv->get_stats = &noop_get_stats;
  9244. drv->identify_device = &noop_identify_device;
  9245. drv->set_device = NULL;
  9246. drv->thread_prepare = &noop_thread_prepare;
  9247. drv->can_limit_work = &noop_can_limit_work;
  9248. drv->thread_init = &noop_thread_init;
  9249. drv->prepare_work = &noop_prepare_work;
  9250. /* This should make the miner thread just exit */
  9251. drv->hash_work = &noop_hash_work;
  9252. drv->hw_error = &noop_hw_error;
  9253. drv->thread_shutdown = &noop_thread_shutdown;
  9254. drv->thread_enable = &noop_thread_enable;
  9255. drv->zero_stats = &generic_zero_stats;
  9256. drv->hash_work = &noop_hash_work;
  9257. drv->queue_full = &noop_queue_full;
  9258. drv->flush_work = &noop_flush_work;
  9259. drv->update_work = &noop_update_work;
  9260. drv->max_diff = 1;
  9261. drv->min_diff = 1;
  9262. }
  9263. void enable_device(struct cgpu_info *cgpu)
  9264. {
  9265. cgpu->deven = DEV_ENABLED;
  9266. wr_lock(&devices_lock);
  9267. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9268. wr_unlock(&devices_lock);
  9269. if (hotplug_mode)
  9270. new_threads += cgpu->threads;
  9271. else
  9272. mining_threads += cgpu->threads;
  9273. rwlock_init(&cgpu->qlock);
  9274. cgpu->queued_work = NULL;
  9275. }
  9276. struct _cgpu_devid_counter {
  9277. char name[4];
  9278. int lastid;
  9279. UT_hash_handle hh;
  9280. };
  9281. static void adjust_mostdevs(void)
  9282. {
  9283. if (total_devices - zombie_devs > most_devices)
  9284. most_devices = total_devices - zombie_devs;
  9285. }
  9286. #ifdef USE_ICARUS
  9287. bool icarus_get_device_id(struct cgpu_info *cgpu)
  9288. {
  9289. static struct _cgpu_devid_counter *devids = NULL;
  9290. struct _cgpu_devid_counter *d;
  9291. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9292. if (d)
  9293. return (d->lastid + 1);
  9294. else
  9295. return 0;
  9296. }
  9297. #endif
  9298. bool add_cgpu(struct cgpu_info *cgpu)
  9299. {
  9300. static struct _cgpu_devid_counter *devids = NULL;
  9301. struct _cgpu_devid_counter *d;
  9302. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9303. if (d)
  9304. cgpu->device_id = ++d->lastid;
  9305. else {
  9306. d = cgmalloc(sizeof(*d));
  9307. cg_memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9308. cgpu->device_id = d->lastid = 0;
  9309. HASH_ADD_STR(devids, name, d);
  9310. }
  9311. wr_lock(&devices_lock);
  9312. devices = cgrealloc(devices, sizeof(struct cgpu_info *) * (total_devices + new_devices + 2));
  9313. wr_unlock(&devices_lock);
  9314. mutex_lock(&stats_lock);
  9315. cgpu->last_device_valid_work = time(NULL);
  9316. mutex_unlock(&stats_lock);
  9317. if (hotplug_mode)
  9318. devices[total_devices + new_devices++] = cgpu;
  9319. else
  9320. devices[total_devices++] = cgpu;
  9321. adjust_mostdevs();
  9322. #ifdef USE_USBUTILS
  9323. if (cgpu->usbdev && !cgpu->unique_id && cgpu->usbdev->serial_string &&
  9324. strlen(cgpu->usbdev->serial_string) > 4)
  9325. cgpu->unique_id = str_text(cgpu->usbdev->serial_string);
  9326. #endif
  9327. return true;
  9328. }
  9329. struct device_drv *copy_drv(struct device_drv *drv)
  9330. {
  9331. struct device_drv *copy;
  9332. copy = cgmalloc(sizeof(*copy));
  9333. cg_memcpy(copy, drv, sizeof(*copy));
  9334. copy->copy = true;
  9335. return copy;
  9336. }
  9337. #ifdef USE_USBUTILS
  9338. static void hotplug_process(void)
  9339. {
  9340. struct thr_info *thr;
  9341. int i, j;
  9342. for (i = 0; i < new_devices; i++) {
  9343. struct cgpu_info *cgpu;
  9344. int dev_no = total_devices + i;
  9345. cgpu = devices[dev_no];
  9346. enable_device(cgpu);
  9347. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9348. cgpu->rolling = cgpu->total_mhashes = 0;
  9349. }
  9350. wr_lock(&mining_thr_lock);
  9351. mining_thr = cgrealloc(mining_thr, sizeof(thr) * (mining_threads + new_threads + 1));
  9352. for (i = 0; i < new_threads; i++)
  9353. mining_thr[mining_threads + i] = cgcalloc(1, sizeof(*thr));
  9354. // Start threads
  9355. for (i = 0; i < new_devices; ++i) {
  9356. struct cgpu_info *cgpu = devices[total_devices];
  9357. cgpu->thr = cgmalloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  9358. cgpu->thr[cgpu->threads] = NULL;
  9359. cgpu->status = LIFE_INIT;
  9360. cgtime(&(cgpu->dev_start_tv));
  9361. for (j = 0; j < cgpu->threads; ++j) {
  9362. thr = __get_thread(mining_threads);
  9363. thr->id = mining_threads;
  9364. thr->cgpu = cgpu;
  9365. thr->device_thread = j;
  9366. if (!cgpu->drv->thread_prepare(thr)) {
  9367. null_device_drv(cgpu->drv);
  9368. cgpu->deven = DEV_DISABLED;
  9369. continue;
  9370. }
  9371. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9372. quit(1, "hotplug thread %d create failed", thr->id);
  9373. cgpu->thr[j] = thr;
  9374. /* Enable threads for devices set not to mine but disable
  9375. * their queue in case we wish to enable them later */
  9376. if (cgpu->deven != DEV_DISABLED) {
  9377. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  9378. cgsem_post(&thr->sem);
  9379. }
  9380. mining_threads++;
  9381. }
  9382. total_devices++;
  9383. applog(LOG_WARNING, "Hotplug: %s added %s %i", cgpu->drv->dname, cgpu->drv->name, cgpu->device_id);
  9384. }
  9385. wr_unlock(&mining_thr_lock);
  9386. adjust_mostdevs();
  9387. #ifdef HAVE_CURSES
  9388. switch_logsize(true);
  9389. #endif
  9390. }
  9391. #define DRIVER_DRV_DETECT_HOTPLUG(X) X##_drv.drv_detect(true);
  9392. static void reinit_usb(void)
  9393. {
  9394. int err;
  9395. usb_reinit = true;
  9396. /* Wait till libusb_poll_thread is no longer polling */
  9397. while (polling_usb)
  9398. cgsleep_ms(100);
  9399. applog(LOG_DEBUG, "Reinitialising libusb");
  9400. libusb_exit(NULL);
  9401. err = libusb_init(NULL);
  9402. if (err)
  9403. quit(1, "Reinit of libusb failed err %d:%s", err, libusb_error_name(err));
  9404. usb_reinit = false;
  9405. }
  9406. static void *hotplug_thread(void __maybe_unused *userdata)
  9407. {
  9408. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9409. RenameThread("Hotplug");
  9410. hotplug_mode = true;
  9411. cgsleep_ms(5000);
  9412. while (0x2a) {
  9413. // Version 0.1 just add the devices on - worry about using nodev later
  9414. if (hotplug_time == 0)
  9415. cgsleep_ms(5000);
  9416. else {
  9417. new_devices = 0;
  9418. new_threads = 0;
  9419. /* Use the DRIVER_PARSE_COMMANDS macro to detect all
  9420. * devices */
  9421. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_HOTPLUG)
  9422. if (new_devices)
  9423. hotplug_process();
  9424. /* If we have no active devices, libusb may need to
  9425. * be re-initialised to work properly */
  9426. if (total_devices == zombie_devs)
  9427. reinit_usb();
  9428. // hotplug_time >0 && <=9999
  9429. cgsleep_ms(hotplug_time * 1000);
  9430. }
  9431. }
  9432. return NULL;
  9433. }
  9434. #endif
  9435. static void probe_pools(void)
  9436. {
  9437. int i;
  9438. for (i = 0; i < total_pools; i++) {
  9439. struct pool *pool = pools[i];
  9440. pool->testing = true;
  9441. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9442. }
  9443. }
  9444. #define DRIVER_FILL_DEVICE_DRV(X) fill_device_drv(&X##_drv);
  9445. #define DRIVER_DRV_DETECT_ALL(X) X##_drv.drv_detect(false);
  9446. #ifdef USE_USBUTILS
  9447. static void *libusb_poll_thread(void __maybe_unused *arg)
  9448. {
  9449. struct timeval tv_end;
  9450. RenameThread("USBPoll");
  9451. while (likely(usb_polling)) {
  9452. tv_end.tv_sec = 0;
  9453. tv_end.tv_usec = 100000;
  9454. while (usb_reinit) {
  9455. polling_usb = false;
  9456. cgsleep_ms(100);
  9457. }
  9458. polling_usb = true;
  9459. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  9460. }
  9461. /* Cancel any cancellable usb transfers */
  9462. cancel_usb_transfers();
  9463. /* Keep event handling going until there are no async transfers in
  9464. * flight. */
  9465. while (async_usb_transfers()) {
  9466. tv_end.tv_sec = 0;
  9467. tv_end.tv_usec = 0;
  9468. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  9469. };
  9470. return NULL;
  9471. }
  9472. static void initialise_usb(void) {
  9473. int err = libusb_init(NULL);
  9474. if (err) {
  9475. fprintf(stderr, "libusb_init() failed err %d", err);
  9476. fflush(stderr);
  9477. quit(1, "libusb_init() failed");
  9478. }
  9479. initialise_usblocks();
  9480. usb_polling = true;
  9481. pthread_create(&usb_poll_thread, NULL, libusb_poll_thread, NULL);
  9482. }
  9483. #else
  9484. #define initialise_usb() {}
  9485. #endif
  9486. #ifdef USE_BITMAIN_SOC
  9487. void setStartTimePoint()
  9488. {
  9489. char logstr[256];
  9490. struct sysinfo sInfo;
  9491. if (sysinfo(&sInfo))
  9492. {
  9493. sprintf(logstr, "Failed to get sysinfo, errno:%u, reason:%s\n",
  9494. errno, strerror(errno));
  9495. writeInitLogFile(logstr);
  9496. total_tv_start_sys=time(NULL);
  9497. total_tv_end_sys=total_tv_start_sys+1;
  9498. }
  9499. else
  9500. {
  9501. total_tv_start_sys=sInfo.uptime;
  9502. total_tv_end_sys=total_tv_start_sys+1;
  9503. sprintf(logstr, "setStartTimePoint total_tv_start_sys=%d total_tv_end_sys=%d\n",total_tv_start_sys, total_tv_end_sys);
  9504. writeInitLogFile(logstr);
  9505. }
  9506. }
  9507. #endif
  9508. int main(int argc, char *argv[])
  9509. {
  9510. struct sigaction handler;
  9511. struct work *work = NULL;
  9512. bool pool_msg = false;
  9513. struct thr_info *thr;
  9514. struct block *block;
  9515. int i, j, slept = 0;
  9516. unsigned int k;
  9517. char *s;
  9518. /* This dangerous functions tramples random dynamically allocated
  9519. * variables so do it before anything at all */
  9520. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  9521. early_quit(1, "Failed to curl_global_init");
  9522. #ifdef USE_LIBSYSTEMD
  9523. sd_notify(false, "STATUS=Starting up...");
  9524. #endif
  9525. # ifdef __linux
  9526. /* If we're on a small lowspec platform with only one CPU, we should
  9527. * yield after dropping a lock to allow a thread waiting for it to be
  9528. * able to get CPU time to grab the lock. */
  9529. if (sysconf(_SC_NPROCESSORS_ONLN) == 1)
  9530. selective_yield = &sched_yield;
  9531. #endif
  9532. #if LOCK_TRACKING
  9533. // Must be first
  9534. if (unlikely(pthread_mutex_init(&lockstat_lock, NULL)))
  9535. quithere(1, "Failed to pthread_mutex_init lockstat_lock errno=%d", errno);
  9536. #endif
  9537. initial_args = cgmalloc(sizeof(char *) * (argc + 1));
  9538. for (i = 0; i < argc; i++)
  9539. initial_args[i] = strdup(argv[i]);
  9540. initial_args[argc] = NULL;
  9541. mutex_init(&hash_lock);
  9542. mutex_init(&console_lock);
  9543. cglock_init(&control_lock);
  9544. mutex_init(&stats_lock);
  9545. mutex_init(&sharelog_lock);
  9546. cglock_init(&ch_lock);
  9547. mutex_init(&sshare_lock);
  9548. rwlock_init(&blk_lock);
  9549. rwlock_init(&netacc_lock);
  9550. rwlock_init(&mining_thr_lock);
  9551. rwlock_init(&devices_lock);
  9552. #if STRATUM_WORK_TIMING
  9553. cglock_init(&swt_lock);
  9554. #endif
  9555. mutex_init(&lp_lock);
  9556. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  9557. early_quit(1, "Failed to pthread_cond_init lp_cond");
  9558. mutex_init(&restart_lock);
  9559. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  9560. early_quit(1, "Failed to pthread_cond_init restart_cond");
  9561. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  9562. early_quit(1, "Failed to pthread_cond_init gws_cond");
  9563. /* Create a unique get work queue */
  9564. getq = tq_new();
  9565. if (!getq)
  9566. early_quit(1, "Failed to create getq");
  9567. /* We use the getq mutex as the staged lock */
  9568. stgd_lock = &getq->mutex;
  9569. initialise_usb();
  9570. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  9571. handler.sa_handler = &sighandler;
  9572. handler.sa_flags = 0;
  9573. sigemptyset(&handler.sa_mask);
  9574. sigaction(SIGTERM, &handler, &termhandler);
  9575. sigaction(SIGINT, &handler, &inthandler);
  9576. sigaction(SIGABRT, &handler, &abrthandler);
  9577. #ifndef WIN32
  9578. signal(SIGPIPE, SIG_IGN);
  9579. #else
  9580. timeBeginPeriod(1);
  9581. #endif
  9582. opt_kernel_path = alloca(PATH_MAX);
  9583. strcpy(opt_kernel_path, CGMINER_PREFIX);
  9584. cgminer_path = alloca(PATH_MAX);
  9585. s = strdup(argv[0]);
  9586. strcpy(cgminer_path, dirname(s));
  9587. free(s);
  9588. strcat(cgminer_path, "/");
  9589. devcursor = 8;
  9590. logstart = devcursor + 1;
  9591. logcursor = logstart + 1;
  9592. block = cgcalloc(sizeof(struct block), 1);
  9593. for (i = 0; i < 36; i++)
  9594. strcat(block->hash, "0");
  9595. HASH_ADD_STR(blocks, hash, block);
  9596. strcpy(current_hash, block->hash);
  9597. INIT_LIST_HEAD(&scan_devices);
  9598. /* parse command line */
  9599. opt_register_table(opt_config_table,
  9600. "Options for both config file and command line");
  9601. opt_register_table(opt_cmdline_table,
  9602. "Options for command line only");
  9603. opt_parse(&argc, argv, applog_and_exit);
  9604. if (argc != 1)
  9605. early_quit(1, "Unexpected extra commandline arguments");
  9606. if (!config_loaded)
  9607. load_default_config();
  9608. // use this to test diff value handing on various builds and architectures.
  9609. // since share submission depends on the difficulty calculated vs the pool
  9610. // work requirement, if this test fails, cgminer could discard a block due
  9611. // to the difficulty calculation being wrong and too low vs the pool work
  9612. if (opt_blockcheck)
  9613. {
  9614. // how many bits are skipped for diffone
  9615. #define BC_DIFF1_BITS 32
  9616. // number of bits in a hash
  9617. #define BC_MAX_BITS 256
  9618. // number of bits set to 1 for diffone
  9619. #define BC_TEST_BITS 16
  9620. #define HEX_BYTE 8
  9621. // ratio limits on the difference between actual and test
  9622. #define BC_DELTA_PLUS_LIM 0.00000001
  9623. #define BC_DELTA_MINUS_LIM (-0.00000001)
  9624. struct work test_work;
  9625. #define ASSERTbc(condition) __maybe_unused static char sizeof_work_hash_must_be_32[(condition)?1:-1]
  9626. ASSERTbc(sizeof(test_work.hash) == (BC_MAX_BITS / HEX_BYTE));
  9627. double test, delta, ratio, change, powval, powdelta, powratio;
  9628. double diff = 1.0, prevdiff = 0.0, prevtest = 0.0;
  9629. bool deltabad, diffbad, fail = false;
  9630. int i, byte, j;
  9631. for (i = BC_DIFF1_BITS; i < BC_MAX_BITS - BC_TEST_BITS; i += HEX_BYTE)
  9632. {
  9633. byte = ((BC_MAX_BITS - 1) - i) / HEX_BYTE;
  9634. // set the hash value to 0000...00ffff00...0000
  9635. for (j = 0; j < (BC_MAX_BITS / HEX_BYTE); j++)
  9636. test_work.hash[j] = 0;
  9637. // BC_TEST_BITS
  9638. test_work.hash[byte] = 0xff;
  9639. test_work.hash[byte - 1] = 0xff;
  9640. // Of course MUST use the same calculation as all diff value tests
  9641. // use to decide when to submit shares
  9642. test = truediffone / le256todouble(test_work.hash);
  9643. delta = diff - test;
  9644. ratio = delta / diff;
  9645. if (ratio < BC_DELTA_MINUS_LIM || ratio > BC_DELTA_PLUS_LIM)
  9646. {
  9647. deltabad = true;
  9648. fail = true;
  9649. }
  9650. else
  9651. deltabad = false;
  9652. powval = pow(2.0, (double)(i - BC_DIFF1_BITS));
  9653. powdelta = diff - powval;
  9654. powratio = powdelta / powval;
  9655. if (powratio < BC_DELTA_MINUS_LIM || powratio > BC_DELTA_PLUS_LIM)
  9656. {
  9657. diffbad = true;
  9658. fail = true;
  9659. }
  9660. else
  9661. diffbad = false;
  9662. if (diff < prevdiff || test < prevtest)
  9663. fail = true;
  9664. printf("%3d%s%s real=%.8E calc=%.8E delta=%.8E%s pow=%.8E powdelta=%.8E%s\n",
  9665. i, (diff < prevdiff) ? " FATAL DROP IN DIFF:": "",
  9666. (test < prevtest) ? " FATAL DROP IN TEST:": "", diff,
  9667. test, delta, deltabad ? " DELTA TOO LARGE!" : "",
  9668. powval, powdelta, diffbad ? " POW DELTA TOO LARGE!" : "");
  9669. prevtest = test;
  9670. prevdiff = diff;
  9671. diff *= (1 << HEX_BYTE);
  9672. change = diff / prevdiff;
  9673. if (change != (1 << HEX_BYTE))
  9674. {
  9675. fail = true;
  9676. printf("FATAL for %d double size doesn't handle above %.8E\n", i, prevdiff);
  9677. }
  9678. }
  9679. if (fail)
  9680. printf("\nTEST FAILED! See above.\n");
  9681. else
  9682. printf("\nTest succeeded.\n");
  9683. return 0;
  9684. }
  9685. if (opt_benchmark || opt_benchfile) {
  9686. struct pool *pool;
  9687. pool = add_pool();
  9688. pool->rpc_url = cgmalloc(255);
  9689. if (opt_benchfile)
  9690. strcpy(pool->rpc_url, "Benchfile");
  9691. else
  9692. strcpy(pool->rpc_url, "Benchmark");
  9693. pool->rpc_user = pool->rpc_url;
  9694. pool->rpc_pass = pool->rpc_url;
  9695. pool->rpc_userpass = pool->rpc_url;
  9696. pool->sockaddr_url = pool->rpc_url;
  9697. strncpy(pool->diff, "?", sizeof(pool->diff)-1);
  9698. pool->diff[sizeof(pool->diff)-1] = '\0';
  9699. enable_pool(pool);
  9700. pool->idle = false;
  9701. successful_connect = true;
  9702. for (i = 0; i < 16; i++) {
  9703. hex2bin(&bench_hidiff_bins[i][0], &bench_hidiffs[i][0], 160);
  9704. hex2bin(&bench_lodiff_bins[i][0], &bench_lodiffs[i][0], 160);
  9705. }
  9706. set_target(bench_target, 32);
  9707. }
  9708. #ifdef USE_BITMAIN_SOC
  9709. if(opt_version_path)
  9710. {
  9711. FILE * fpversion = fopen(opt_version_path, "rb");
  9712. char tmp[256] = {0};
  9713. int len = 0;
  9714. char * start = 0;
  9715. if(fpversion == NULL)
  9716. {
  9717. applog(LOG_ERR, "Open miner version file %s error", opt_version_path);
  9718. }
  9719. else
  9720. {
  9721. len = fread(tmp, 1, 256, fpversion);
  9722. if(len <= 0)
  9723. {
  9724. applog(LOG_ERR, "Read miner version file %s error %d", opt_version_path, len);
  9725. }
  9726. else
  9727. {
  9728. start = strstr(tmp, "\n");
  9729. if(start == NULL)
  9730. {
  9731. strcpy(g_miner_compiletime, tmp);
  9732. }
  9733. else
  9734. {
  9735. cg_memcpy(g_miner_compiletime, tmp, start-tmp);
  9736. strcpy(g_miner_type, start+1);
  9737. }
  9738. if(g_miner_compiletime[strlen(g_miner_compiletime)-1] == '\n')
  9739. {
  9740. g_miner_compiletime[strlen(g_miner_compiletime)-1] = 0;
  9741. }
  9742. if(g_miner_compiletime[strlen(g_miner_compiletime)-1] == '\r')
  9743. {
  9744. g_miner_compiletime[strlen(g_miner_compiletime)-1] = 0;
  9745. }
  9746. if(g_miner_type[strlen(g_miner_type)-1] == '\n')
  9747. {
  9748. g_miner_type[strlen(g_miner_type)-1] = 0;
  9749. }
  9750. if(g_miner_type[strlen(g_miner_type)-1] == '\r')
  9751. {
  9752. g_miner_type[strlen(g_miner_type)-1] = 0;
  9753. }
  9754. }
  9755. }
  9756. applog(LOG_ERR, "Miner compile time: %s type: %s", g_miner_compiletime, g_miner_type);
  9757. }
  9758. #endif
  9759. #ifdef HAVE_CURSES
  9760. if (opt_realquiet || opt_display_devs || opt_decode)
  9761. use_curses = false;
  9762. if (use_curses)
  9763. enable_curses();
  9764. #endif
  9765. applog(LOG_WARNING, "Started %s", packagename);
  9766. if (cnfbuf) {
  9767. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  9768. switch (fileconf_load) {
  9769. case 0:
  9770. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  9771. applog(LOG_WARNING, "Configuration file could not be used.");
  9772. break;
  9773. case -1:
  9774. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  9775. if (use_curses)
  9776. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  9777. break;
  9778. default:
  9779. break;
  9780. }
  9781. free(cnfbuf);
  9782. cnfbuf = NULL;
  9783. }
  9784. strcat(opt_kernel_path, "/");
  9785. if (want_per_device_stats)
  9786. opt_log_output = true;
  9787. #ifdef HAVE_SYSLOG_H
  9788. if (opt_log_output)
  9789. setlogmask(LOG_UPTO(LOG_DEBUG));
  9790. else
  9791. setlogmask(LOG_UPTO(LOG_NOTICE));
  9792. #endif
  9793. total_control_threads = 8;
  9794. control_thr = cgcalloc(total_control_threads, sizeof(*thr));
  9795. gwsched_thr_id = 0;
  9796. #ifdef USE_AVALON7
  9797. if (opt_avalon7_ssplus_enable) {
  9798. ssp_sorter_init(HT_SIZE, HT_PRB_LMT, HT_PRB_C1, HT_PRB_C2);
  9799. ssp_hasher_init();
  9800. }
  9801. #endif
  9802. #ifdef USE_USBUTILS
  9803. usb_initialise();
  9804. // before device detection
  9805. cgsem_init(&usb_resource_sem);
  9806. usbres_thr_id = 1;
  9807. thr = &control_thr[usbres_thr_id];
  9808. if (thr_info_create(thr, NULL, usb_resource_thread, thr))
  9809. early_quit(1, "usb resource thread create failed");
  9810. pthread_detach(thr->pth);
  9811. #endif
  9812. /* Use the DRIVER_PARSE_COMMANDS macro to fill all the device_drvs */
  9813. DRIVER_PARSE_COMMANDS(DRIVER_FILL_DEVICE_DRV)
  9814. if (!total_pools) {
  9815. applog(LOG_WARNING, "Need to specify at least one pool server.");
  9816. #ifdef HAVE_CURSES
  9817. if (!use_curses || !input_pool(false))
  9818. #endif
  9819. early_quit(1, "Pool setup failed");
  9820. }
  9821. for (i = 0; i < total_pools; i++) {
  9822. struct pool *pool = pools[i];
  9823. size_t siz;
  9824. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9825. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9826. if (!pool->rpc_userpass) {
  9827. if (!pool->rpc_pass)
  9828. pool->rpc_pass = strdup("");
  9829. if (!pool->rpc_user)
  9830. early_quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  9831. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9832. pool->rpc_userpass = cgmalloc(siz);
  9833. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9834. }
  9835. }
  9836. /* Set the currentpool to pool 0 */
  9837. currentpool = pools[0];
  9838. #ifdef HAVE_SYSLOG_H
  9839. if (use_syslog)
  9840. openlog(PACKAGE, LOG_PID, LOG_USER);
  9841. #endif
  9842. #if defined(unix) || defined(__APPLE__)
  9843. if (opt_stderr_cmd)
  9844. fork_monitor();
  9845. #endif // defined(unix)
  9846. mining_thr = cgcalloc(mining_threads, sizeof(thr));
  9847. for (i = 0; i < mining_threads; i++)
  9848. mining_thr[i] = cgcalloc(1, sizeof(*thr));
  9849. // Start threads
  9850. k = 0;
  9851. for (i = 0; i < total_devices; ++i) {
  9852. struct cgpu_info *cgpu = devices[i];
  9853. cgpu->thr = cgmalloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  9854. cgpu->thr[cgpu->threads] = NULL;
  9855. cgpu->status = LIFE_INIT;
  9856. for (j = 0; j < cgpu->threads; ++j, ++k) {
  9857. thr = get_thread(k);
  9858. thr->id = k;
  9859. thr->cgpu = cgpu;
  9860. thr->device_thread = j;
  9861. if (!cgpu->drv->thread_prepare(thr))
  9862. continue;
  9863. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9864. early_quit(1, "thread %d create failed", thr->id);
  9865. cgpu->thr[j] = thr;
  9866. /* Enable threads for devices set not to mine but disable
  9867. * their queue in case we wish to enable them later */
  9868. if (cgpu->deven != DEV_DISABLED) {
  9869. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  9870. cgsem_post(&thr->sem);
  9871. }
  9872. }
  9873. }
  9874. if (opt_benchmark || opt_benchfile)
  9875. goto begin_bench;
  9876. for (i = 0; i < total_pools; i++) {
  9877. struct pool *pool = pools[i];
  9878. enable_pool(pool);
  9879. pool->idle = true;
  9880. }
  9881. /* Look for at least one active pool before starting */
  9882. applog(LOG_NOTICE, "Probing for an alive pool");
  9883. probe_pools();
  9884. do {
  9885. sleep(1);
  9886. slept++;
  9887. } while (!pools_active && slept < 60);
  9888. while (!pools_active) {
  9889. if (!pool_msg) {
  9890. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  9891. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  9892. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  9893. for (i = 0; i < total_pools; i++) {
  9894. struct pool *pool = pools[i];
  9895. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  9896. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  9897. }
  9898. pool_msg = true;
  9899. if (use_curses)
  9900. applog(LOG_ERR, "Press any key to exit, or cgminer will wait indefinitely for an alive pool.");
  9901. }
  9902. if (!use_curses)
  9903. early_quit(0, "No servers could be used! Exiting.");
  9904. #ifdef HAVE_CURSES
  9905. touchwin(logwin);
  9906. wrefresh(logwin);
  9907. halfdelay(10);
  9908. if (getch() != ERR)
  9909. early_quit(0, "No servers could be used! Exiting.");
  9910. cbreak();
  9911. #endif
  9912. };
  9913. begin_bench:
  9914. /* Use the DRIVER_PARSE_COMMANDS macro to detect all devices */
  9915. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_ALL)
  9916. if (opt_display_devs) {
  9917. applog(LOG_ERR, "Devices detected:");
  9918. for (i = 0; i < total_devices; ++i) {
  9919. struct cgpu_info *cgpu = devices[i];
  9920. if (cgpu->name)
  9921. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->name, cgpu->drv->dname);
  9922. else
  9923. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->drv->dname);
  9924. }
  9925. early_quit(0, "%d devices listed", total_devices);
  9926. }
  9927. mining_threads = 0;
  9928. for (i = 0; i < total_devices; ++i)
  9929. enable_device(devices[i]);
  9930. mining_thr = cgcalloc(mining_threads, sizeof(thr));
  9931. for (i = 0; i < mining_threads; i++)
  9932. mining_thr[i] = cgcalloc(1, sizeof(*thr));
  9933. if (!opt_decode) {
  9934. #ifdef USE_USBUTILS
  9935. if (!total_devices) {
  9936. applog(LOG_WARNING, "No devices detected!");
  9937. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  9938. }
  9939. #else
  9940. if (!total_devices)
  9941. early_quit(1, "All devices disabled, cannot mine!");
  9942. #endif
  9943. }
  9944. most_devices = total_devices;
  9945. load_temp_cutoffs();
  9946. for (i = 0; i < total_devices; ++i)
  9947. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9948. if (!opt_compact) {
  9949. logstart += most_devices;
  9950. logcursor = logstart + 1;
  9951. #ifdef HAVE_CURSES
  9952. check_winsizes();
  9953. #endif
  9954. }
  9955. // Start threads
  9956. k = 0;
  9957. for (i = 0; i < total_devices; ++i) {
  9958. struct cgpu_info *cgpu = devices[i];
  9959. cgpu->thr = cgmalloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  9960. cgpu->thr[cgpu->threads] = NULL;
  9961. cgpu->status = LIFE_INIT;
  9962. for (j = 0; j < cgpu->threads; ++j, ++k) {
  9963. thr = get_thread(k);
  9964. thr->id = k;
  9965. thr->cgpu = cgpu;
  9966. thr->device_thread = j;
  9967. if (!cgpu->drv->thread_prepare(thr))
  9968. continue;
  9969. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9970. early_quit(1, "thread %d create failed", thr->id);
  9971. cgpu->thr[j] = thr;
  9972. /* Enable threads for devices set not to mine but disable
  9973. * their queue in case we wish to enable them later */
  9974. if (cgpu->deven != DEV_DISABLED) {
  9975. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  9976. cgsem_post(&thr->sem);
  9977. }
  9978. }
  9979. }
  9980. total_mhashes_done = 0;
  9981. for (i = 0; i < total_devices; i++) {
  9982. struct cgpu_info *cgpu = devices[i];
  9983. cgpu->rolling = cgpu->total_mhashes = 0;
  9984. }
  9985. cgtime_real(&total_tv_start);
  9986. get_datestamp(datestamp, sizeof(datestamp), &total_tv_start);
  9987. #ifdef USE_BITMAIN_SOC
  9988. struct sysinfo sInfo;
  9989. if (sysinfo(&sInfo))
  9990. {
  9991. applog(LOG_INFO, "Failed to get sysinfo, errno:%u, reason:%s\n",
  9992. errno, strerror(errno));
  9993. total_tv_end_sys=time(NULL);
  9994. total_tv_start_sys=time(NULL);
  9995. }
  9996. else
  9997. {
  9998. total_tv_end_sys=sInfo.uptime;
  9999. total_tv_start_sys=sInfo.uptime;
  10000. }
  10001. #endif
  10002. cgtime(&total_tv_start);
  10003. cgtime(&total_tv_end);
  10004. cgtime(&tv_hashmeter);
  10005. watchpool_thr_id = 2;
  10006. thr = &control_thr[watchpool_thr_id];
  10007. /* start watchpool thread */
  10008. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  10009. early_quit(1, "watchpool thread create failed");
  10010. pthread_detach(thr->pth);
  10011. watchdog_thr_id = 3;
  10012. thr = &control_thr[watchdog_thr_id];
  10013. /* start watchdog thread */
  10014. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  10015. early_quit(1, "watchdog thread create failed");
  10016. pthread_detach(thr->pth);
  10017. /* Create API socket thread */
  10018. api_thr_id = 5;
  10019. thr = &control_thr[api_thr_id];
  10020. if (thr_info_create(thr, NULL, api_thread, thr))
  10021. early_quit(1, "API thread create failed");
  10022. #ifdef USE_USBUTILS
  10023. hotplug_thr_id = 6;
  10024. thr = &control_thr[hotplug_thr_id];
  10025. if (thr_info_create(thr, NULL, hotplug_thread, thr))
  10026. early_quit(1, "hotplug thread create failed");
  10027. pthread_detach(thr->pth);
  10028. #endif
  10029. #ifdef HAVE_CURSES
  10030. /* Create curses input thread for keyboard input. Create this last so
  10031. * that we know all threads are created since this can call kill_work
  10032. * to try and shut down all previous threads. */
  10033. input_thr_id = 7;
  10034. thr = &control_thr[input_thr_id];
  10035. if (thr_info_create(thr, NULL, input_thread, thr))
  10036. early_quit(1, "input thread create failed");
  10037. pthread_detach(thr->pth);
  10038. #endif
  10039. /* Just to be sure */
  10040. if (total_control_threads != 8)
  10041. early_quit(1, "incorrect total_control_threads (%d) should be 8", total_control_threads);
  10042. #ifdef USE_GEKKO
  10043. set_lowprio();
  10044. #else
  10045. set_highprio();
  10046. #endif
  10047. #ifdef USE_LIBSYSTEMD
  10048. sd_notify(false, "READY=1\n"
  10049. "STATUS=Started");
  10050. #endif
  10051. /* Once everything is set up, main() becomes the getwork scheduler */
  10052. while (42) {
  10053. int ts, max_staged = max_queue;
  10054. struct pool *pool;
  10055. if (opt_work_update)
  10056. signal_work_update();
  10057. opt_work_update = false;
  10058. #if defined(USE_AVALON7) || defined(USE_AVALON8) || defined(USE_AVALON9) || defined(USE_AVALONLC3)
  10059. if (opt_clean_jobs) {
  10060. signal_clean_jobs();
  10061. opt_clean_jobs = false;
  10062. }
  10063. #endif
  10064. mutex_lock(stgd_lock);
  10065. ts = __total_staged();
  10066. /* Wait until hash_pop tells us we need to create more work */
  10067. if (ts > max_staged) {
  10068. work_filled = true;
  10069. pthread_cond_wait(&gws_cond, stgd_lock);
  10070. ts = __total_staged();
  10071. }
  10072. mutex_unlock(stgd_lock);
  10073. if (ts > max_staged) {
  10074. /* Keeps slowly generating work even if it's not being
  10075. * used to keep last_getwork incrementing and to see
  10076. * if pools are still alive. */
  10077. work_filled = true;
  10078. work = hash_pop(false);
  10079. if (work)
  10080. discard_work(work);
  10081. continue;
  10082. }
  10083. if (work)
  10084. discard_work(work);
  10085. work = make_work();
  10086. while (42) {
  10087. pool = select_pool();
  10088. if (!pool_unusable(pool))
  10089. break;
  10090. switch_pools(NULL);
  10091. pool = select_pool();
  10092. if (pool_unusable(pool))
  10093. cgsleep_ms(5);
  10094. };
  10095. if (pool->has_stratum) {
  10096. if (opt_gen_stratum_work) {
  10097. gen_stratum_work(pool, work);
  10098. applog(LOG_DEBUG, "Generated stratum work");
  10099. stage_work(work);
  10100. }
  10101. continue;
  10102. }
  10103. #ifdef HAVE_LIBCURL
  10104. if (pool->gbt_solo) {
  10105. gen_solo_work(pool, work);
  10106. applog(LOG_DEBUG, "Generated GBT SOLO work");
  10107. stage_work(work);
  10108. continue;
  10109. }
  10110. if (pool->has_gbt) {
  10111. gen_gbt_work(pool, work);
  10112. applog(LOG_DEBUG, "Generated GBT work");
  10113. stage_work(work);
  10114. continue;
  10115. }
  10116. #endif
  10117. if (opt_benchfile) {
  10118. get_benchfile_work(work);
  10119. applog(LOG_DEBUG, "Generated benchfile work");
  10120. stage_work(work);
  10121. continue;
  10122. } else if (opt_benchmark) {
  10123. get_benchmark_work(work);
  10124. applog(LOG_DEBUG, "Generated benchmark work");
  10125. stage_work(work);
  10126. continue;
  10127. }
  10128. }
  10129. return 0;
  10130. }