cgminer.c 322 KB

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