cgminer.c 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #ifdef HAVE_CURSES
  13. #include <curses.h>
  14. #endif
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <time.h>
  23. #include <math.h>
  24. #include <stdarg.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27. #ifdef USE_USBUTILS
  28. #include <semaphore.h>
  29. #endif
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #ifndef WIN32
  33. #include <sys/resource.h>
  34. #endif
  35. #include <ccan/opt/opt.h>
  36. #include <jansson.h>
  37. #include <curl/curl.h>
  38. #include <libgen.h>
  39. #include <sha2.h>
  40. #include "compat.h"
  41. #include "miner.h"
  42. #include "findnonce.h"
  43. #include "adl.h"
  44. #include "driver-opencl.h"
  45. #include "bench_block.h"
  46. #include "scrypt.h"
  47. #ifdef USE_AVALON
  48. #include "driver-avalon.h"
  49. #endif
  50. #if defined(unix)
  51. #include <errno.h>
  52. #include <fcntl.h>
  53. #include <sys/wait.h>
  54. #endif
  55. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_AVALON) || defined(USE_MODMINER)
  56. # define USE_FPGA
  57. #elif defined(USE_ZTEX)
  58. # define USE_FPGA
  59. #endif
  60. struct strategies strategies[] = {
  61. { "Failover" },
  62. { "Round Robin" },
  63. { "Rotate" },
  64. { "Load Balance" },
  65. { "Balance" },
  66. };
  67. static char packagename[256];
  68. bool opt_protocol;
  69. static bool opt_benchmark;
  70. bool have_longpoll;
  71. bool want_per_device_stats;
  72. bool use_syslog;
  73. bool opt_quiet;
  74. bool opt_realquiet;
  75. bool opt_loginput;
  76. bool opt_compact;
  77. const int opt_cutofftemp = 95;
  78. int opt_log_interval = 5;
  79. int opt_queue = 1;
  80. int opt_scantime = -1;
  81. int opt_expiry = 120;
  82. static const bool opt_time = true;
  83. unsigned long long global_hashrate;
  84. #if defined(HAVE_OPENCL) || defined(USE_USBUTILS)
  85. int nDevs;
  86. #endif
  87. #ifdef HAVE_OPENCL
  88. int opt_dynamic_interval = 7;
  89. int opt_g_threads = -1;
  90. int gpu_threads;
  91. #ifdef USE_SCRYPT
  92. bool opt_scrypt;
  93. #endif
  94. #endif
  95. bool opt_restart = true;
  96. static bool opt_nogpu;
  97. struct list_head scan_devices;
  98. static signed int devices_enabled;
  99. static bool opt_removedisabled;
  100. int total_devices;
  101. struct cgpu_info **devices;
  102. bool have_opencl;
  103. int mining_threads;
  104. int num_processors;
  105. #ifdef HAVE_CURSES
  106. bool use_curses = true;
  107. #else
  108. bool use_curses;
  109. #endif
  110. static bool opt_submit_stale = true;
  111. static int opt_shares;
  112. bool opt_fail_only;
  113. static bool opt_fix_protocol;
  114. static bool opt_lowmem;
  115. bool opt_autofan;
  116. bool opt_autoengine;
  117. bool opt_noadl;
  118. char *opt_api_allow = NULL;
  119. char *opt_api_groups;
  120. char *opt_api_description = PACKAGE_STRING;
  121. int opt_api_port = 4028;
  122. bool opt_api_listen;
  123. bool opt_api_network;
  124. bool opt_delaynet;
  125. bool opt_disable_pool;
  126. char *opt_icarus_options = NULL;
  127. char *opt_icarus_timing = NULL;
  128. bool opt_worktime;
  129. #ifdef USE_AVALON
  130. char *opt_avalon_options = NULL;
  131. #endif
  132. #ifdef USE_USBUTILS
  133. char *opt_usb_select = NULL;
  134. int opt_usbdump = -1;
  135. bool opt_usb_list_all;
  136. sem_t usb_resource_sem;
  137. #endif
  138. char *opt_kernel_path;
  139. char *cgminer_path;
  140. #if defined(USE_BITFORCE)
  141. bool opt_bfl_noncerange;
  142. #endif
  143. #define QUIET (opt_quiet || opt_realquiet)
  144. struct thr_info *control_thr;
  145. struct thr_info **mining_thr;
  146. static int gwsched_thr_id;
  147. static int stage_thr_id;
  148. static int watchpool_thr_id;
  149. static int watchdog_thr_id;
  150. #ifdef HAVE_CURSES
  151. static int input_thr_id;
  152. #endif
  153. int gpur_thr_id;
  154. static int api_thr_id;
  155. #ifdef USE_USBUTILS
  156. static int usbres_thr_id;
  157. static int hotplug_thr_id;
  158. #endif
  159. static int total_control_threads;
  160. bool hotplug_mode;
  161. static int new_devices;
  162. static int new_threads;
  163. static int start_devices;
  164. int hotplug_time = 5;
  165. #ifdef USE_USBUTILS
  166. pthread_mutex_t cgusb_lock;
  167. pthread_mutex_t cgusbres_lock;
  168. #endif
  169. pthread_mutex_t hash_lock;
  170. static pthread_mutex_t *stgd_lock;
  171. pthread_mutex_t console_lock;
  172. cglock_t ch_lock;
  173. static pthread_rwlock_t blk_lock;
  174. static pthread_mutex_t sshare_lock;
  175. pthread_rwlock_t netacc_lock;
  176. pthread_rwlock_t mining_thr_lock;
  177. pthread_rwlock_t devices_lock;
  178. static pthread_mutex_t lp_lock;
  179. static pthread_cond_t lp_cond;
  180. pthread_mutex_t restart_lock;
  181. pthread_cond_t restart_cond;
  182. pthread_cond_t gws_cond;
  183. double total_mhashes_done;
  184. static struct timeval total_tv_start, total_tv_end;
  185. cglock_t control_lock;
  186. pthread_mutex_t stats_lock;
  187. int hw_errors;
  188. int total_accepted, total_rejected, total_diff1;
  189. int total_getworks, total_stale, total_discarded;
  190. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  191. static int staged_rollable;
  192. unsigned int new_blocks;
  193. static unsigned int work_block;
  194. unsigned int found_blocks;
  195. unsigned int local_work;
  196. unsigned int total_go, total_ro;
  197. struct pool **pools;
  198. static struct pool *currentpool = NULL;
  199. int total_pools, enabled_pools;
  200. enum pool_strategy pool_strategy = POOL_FAILOVER;
  201. int opt_rotate_period;
  202. static int total_urls, total_users, total_passes, total_userpasses;
  203. static
  204. #ifndef HAVE_CURSES
  205. const
  206. #endif
  207. bool curses_active;
  208. static char current_block[40];
  209. /* Protected by ch_lock */
  210. static char *current_hash;
  211. char *current_fullhash;
  212. static char datestamp[40];
  213. static char blocktime[32];
  214. struct timeval block_timeval;
  215. static char best_share[8] = "0";
  216. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  217. static char block_diff[8];
  218. uint64_t best_diff = 0;
  219. struct block {
  220. char hash[40];
  221. UT_hash_handle hh;
  222. int block_no;
  223. };
  224. static struct block *blocks = NULL;
  225. int swork_id;
  226. /* For creating a hash database of stratum shares submitted that have not had
  227. * a response yet */
  228. struct stratum_share {
  229. UT_hash_handle hh;
  230. bool block;
  231. struct work *work;
  232. int id;
  233. time_t sshare_time;
  234. };
  235. static struct stratum_share *stratum_shares = NULL;
  236. char *opt_socks_proxy = NULL;
  237. static const char def_conf[] = "cgminer.conf";
  238. static char *default_config;
  239. static bool config_loaded;
  240. static int include_count;
  241. #define JSON_INCLUDE_CONF "include"
  242. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  243. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  244. #define JSON_MAX_DEPTH 10
  245. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  246. #if defined(unix)
  247. static char *opt_stderr_cmd = NULL;
  248. static int forkpid;
  249. #endif // defined(unix)
  250. bool ping = true;
  251. struct sigaction termhandler, inthandler;
  252. struct thread_q *getq;
  253. static int total_work;
  254. struct work *staged_work = NULL;
  255. struct schedtime {
  256. bool enable;
  257. struct tm tm;
  258. };
  259. struct schedtime schedstart;
  260. struct schedtime schedstop;
  261. bool sched_paused;
  262. static bool time_before(struct tm *tm1, struct tm *tm2)
  263. {
  264. if (tm1->tm_hour < tm2->tm_hour)
  265. return true;
  266. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  267. return true;
  268. return false;
  269. }
  270. static bool should_run(void)
  271. {
  272. struct timeval tv;
  273. struct tm *tm;
  274. if (!schedstart.enable && !schedstop.enable)
  275. return true;
  276. cgtime(&tv);
  277. const time_t tmp_time = tv.tv_sec;
  278. tm = localtime(&tmp_time);
  279. if (schedstart.enable) {
  280. if (!schedstop.enable) {
  281. if (time_before(tm, &schedstart.tm))
  282. return false;
  283. /* This is a once off event with no stop time set */
  284. schedstart.enable = false;
  285. return true;
  286. }
  287. if (time_before(&schedstart.tm, &schedstop.tm)) {
  288. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  289. return true;
  290. return false;
  291. } /* Times are reversed */
  292. if (time_before(tm, &schedstart.tm)) {
  293. if (time_before(tm, &schedstop.tm))
  294. return true;
  295. return false;
  296. }
  297. return true;
  298. }
  299. /* only schedstop.enable == true */
  300. if (!time_before(tm, &schedstop.tm))
  301. return false;
  302. return true;
  303. }
  304. void get_datestamp(char *f, struct timeval *tv)
  305. {
  306. struct tm *tm;
  307. const time_t tmp_time = tv->tv_sec;
  308. tm = localtime(&tmp_time);
  309. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  310. tm->tm_year + 1900,
  311. tm->tm_mon + 1,
  312. tm->tm_mday,
  313. tm->tm_hour,
  314. tm->tm_min,
  315. tm->tm_sec);
  316. }
  317. void get_timestamp(char *f, struct timeval *tv)
  318. {
  319. struct tm *tm;
  320. const time_t tmp_time = tv->tv_sec;
  321. tm = localtime(&tmp_time);
  322. sprintf(f, "[%02d:%02d:%02d]",
  323. tm->tm_hour,
  324. tm->tm_min,
  325. tm->tm_sec);
  326. }
  327. static void applog_and_exit(const char *fmt, ...)
  328. {
  329. va_list ap;
  330. va_start(ap, fmt);
  331. vapplog(LOG_ERR, fmt, ap);
  332. va_end(ap);
  333. exit(1);
  334. }
  335. static pthread_mutex_t sharelog_lock;
  336. static FILE *sharelog_file = NULL;
  337. struct thr_info *get_thread(int thr_id)
  338. {
  339. struct thr_info *thr;
  340. rd_lock(&mining_thr_lock);
  341. thr = mining_thr[thr_id];
  342. rd_unlock(&mining_thr_lock);
  343. return thr;
  344. }
  345. static struct cgpu_info *get_thr_cgpu(int thr_id)
  346. {
  347. struct thr_info *thr = get_thread(thr_id);
  348. return thr->cgpu;
  349. }
  350. struct cgpu_info *get_devices(int id)
  351. {
  352. struct cgpu_info *cgpu;
  353. rd_lock(&devices_lock);
  354. cgpu = devices[id];
  355. rd_unlock(&devices_lock);
  356. return cgpu;
  357. }
  358. static void sharelog(const char*disposition, const struct work*work)
  359. {
  360. char *target, *hash, *data;
  361. struct cgpu_info *cgpu;
  362. unsigned long int t;
  363. struct pool *pool;
  364. int thr_id, rv;
  365. char s[1024];
  366. size_t ret;
  367. if (!sharelog_file)
  368. return;
  369. thr_id = work->thr_id;
  370. cgpu = get_thr_cgpu(thr_id);
  371. pool = work->pool;
  372. t = (unsigned long int)(work->tv_work_found.tv_sec);
  373. target = bin2hex(work->target, sizeof(work->target));
  374. hash = bin2hex(work->hash, sizeof(work->hash));
  375. data = bin2hex(work->data, sizeof(work->data));
  376. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  377. 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);
  378. free(target);
  379. free(hash);
  380. free(data);
  381. if (rv >= (int)(sizeof(s)))
  382. s[sizeof(s) - 1] = '\0';
  383. else if (rv < 0) {
  384. applog(LOG_ERR, "sharelog printf error");
  385. return;
  386. }
  387. mutex_lock(&sharelog_lock);
  388. ret = fwrite(s, rv, 1, sharelog_file);
  389. fflush(sharelog_file);
  390. mutex_unlock(&sharelog_lock);
  391. if (ret != 1)
  392. applog(LOG_ERR, "sharelog fwrite error");
  393. }
  394. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  395. static char *gbt_req = "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"]}]}\n";
  396. /* Return value is ignored if not called from add_pool_details */
  397. struct pool *add_pool(void)
  398. {
  399. struct pool *pool;
  400. pool = calloc(sizeof(struct pool), 1);
  401. if (!pool)
  402. quit(1, "Failed to malloc pool in add_pool");
  403. pool->pool_no = pool->prio = total_pools;
  404. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  405. pools[total_pools++] = pool;
  406. mutex_init(&pool->pool_lock);
  407. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  408. quit(1, "Failed to pthread_cond_init in add_pool");
  409. cglock_init(&pool->data_lock);
  410. mutex_init(&pool->stratum_lock);
  411. cglock_init(&pool->gbt_lock);
  412. INIT_LIST_HEAD(&pool->curlring);
  413. /* Make sure the pool doesn't think we've been idle since time 0 */
  414. pool->tv_idle.tv_sec = ~0UL;
  415. pool->rpc_req = getwork_req;
  416. pool->rpc_proxy = NULL;
  417. return pool;
  418. }
  419. /* Pool variant of test and set */
  420. static bool pool_tset(struct pool *pool, bool *var)
  421. {
  422. bool ret;
  423. mutex_lock(&pool->pool_lock);
  424. ret = *var;
  425. *var = true;
  426. mutex_unlock(&pool->pool_lock);
  427. return ret;
  428. }
  429. bool pool_tclear(struct pool *pool, bool *var)
  430. {
  431. bool ret;
  432. mutex_lock(&pool->pool_lock);
  433. ret = *var;
  434. *var = false;
  435. mutex_unlock(&pool->pool_lock);
  436. return ret;
  437. }
  438. struct pool *current_pool(void)
  439. {
  440. struct pool *pool;
  441. cg_rlock(&control_lock);
  442. pool = currentpool;
  443. cg_runlock(&control_lock);
  444. return pool;
  445. }
  446. char *set_int_range(const char *arg, int *i, int min, int max)
  447. {
  448. char *err = opt_set_intval(arg, i);
  449. if (err)
  450. return err;
  451. if (*i < min || *i > max)
  452. return "Value out of range";
  453. return NULL;
  454. }
  455. static char *set_int_0_to_9999(const char *arg, int *i)
  456. {
  457. return set_int_range(arg, i, 0, 9999);
  458. }
  459. static char *set_int_1_to_65535(const char *arg, int *i)
  460. {
  461. return set_int_range(arg, i, 1, 65535);
  462. }
  463. static char *set_int_0_to_10(const char *arg, int *i)
  464. {
  465. return set_int_range(arg, i, 0, 10);
  466. }
  467. static char *set_int_1_to_10(const char *arg, int *i)
  468. {
  469. return set_int_range(arg, i, 1, 10);
  470. }
  471. #ifdef USE_FPGA_SERIAL
  472. static char *add_serial(char *arg)
  473. {
  474. string_elist_add(arg, &scan_devices);
  475. return NULL;
  476. }
  477. #endif
  478. static char *set_devices(char *arg)
  479. {
  480. int i = strtol(arg, &arg, 0);
  481. if (*arg) {
  482. if (*arg == '?') {
  483. devices_enabled = -1;
  484. return NULL;
  485. }
  486. return "Invalid device number";
  487. }
  488. if (i < 0 || i >= (int)(sizeof(devices_enabled) * 8) - 1)
  489. return "Invalid device number";
  490. devices_enabled |= 1 << i;
  491. return NULL;
  492. }
  493. static char *set_balance(enum pool_strategy *strategy)
  494. {
  495. *strategy = POOL_BALANCE;
  496. return NULL;
  497. }
  498. static char *set_loadbalance(enum pool_strategy *strategy)
  499. {
  500. *strategy = POOL_LOADBALANCE;
  501. return NULL;
  502. }
  503. static char *set_rotate(const char *arg, int *i)
  504. {
  505. pool_strategy = POOL_ROTATE;
  506. return set_int_range(arg, i, 0, 9999);
  507. }
  508. static char *set_rr(enum pool_strategy *strategy)
  509. {
  510. *strategy = POOL_ROUNDROBIN;
  511. return NULL;
  512. }
  513. /* Detect that url is for a stratum protocol either via the presence of
  514. * stratum+tcp or by detecting a stratum server response */
  515. bool detect_stratum(struct pool *pool, char *url)
  516. {
  517. if (!extract_sockaddr(pool, url))
  518. return false;
  519. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  520. pool->rpc_url = strdup(url);
  521. pool->has_stratum = true;
  522. pool->stratum_url = pool->sockaddr_url;
  523. return true;
  524. }
  525. return false;
  526. }
  527. static char *set_url(char *arg)
  528. {
  529. struct pool *pool;
  530. total_urls++;
  531. if (total_urls > total_pools)
  532. add_pool();
  533. pool = pools[total_urls - 1];
  534. arg = get_proxy(arg, pool);
  535. if (detect_stratum(pool, arg))
  536. return NULL;
  537. opt_set_charp(arg, &pool->rpc_url);
  538. if (strncmp(arg, "http://", 7) &&
  539. strncmp(arg, "https://", 8)) {
  540. char *httpinput;
  541. httpinput = malloc(255);
  542. if (!httpinput)
  543. quit(1, "Failed to malloc httpinput");
  544. strcpy(httpinput, "http://");
  545. strncat(httpinput, arg, 248);
  546. pool->rpc_url = httpinput;
  547. }
  548. return NULL;
  549. }
  550. static char *set_user(const char *arg)
  551. {
  552. struct pool *pool;
  553. if (total_userpasses)
  554. return "Use only user + pass or userpass, but not both";
  555. total_users++;
  556. if (total_users > total_pools)
  557. add_pool();
  558. pool = pools[total_users - 1];
  559. opt_set_charp(arg, &pool->rpc_user);
  560. return NULL;
  561. }
  562. static char *set_pass(const char *arg)
  563. {
  564. struct pool *pool;
  565. if (total_userpasses)
  566. return "Use only user + pass or userpass, but not both";
  567. total_passes++;
  568. if (total_passes > total_pools)
  569. add_pool();
  570. pool = pools[total_passes - 1];
  571. opt_set_charp(arg, &pool->rpc_pass);
  572. return NULL;
  573. }
  574. static char *set_userpass(const char *arg)
  575. {
  576. struct pool *pool;
  577. char *updup;
  578. if (total_users || total_passes)
  579. return "Use only user + pass or userpass, but not both";
  580. total_userpasses++;
  581. if (total_userpasses > total_pools)
  582. add_pool();
  583. pool = pools[total_userpasses - 1];
  584. updup = strdup(arg);
  585. opt_set_charp(arg, &pool->rpc_userpass);
  586. pool->rpc_user = strtok(updup, ":");
  587. if (!pool->rpc_user)
  588. return "Failed to find : delimited user info";
  589. pool->rpc_pass = strtok(NULL, ":");
  590. if (!pool->rpc_pass)
  591. return "Failed to find : delimited pass info";
  592. return NULL;
  593. }
  594. static char *enable_debug(bool *flag)
  595. {
  596. *flag = true;
  597. /* Turn on verbose output, too. */
  598. opt_log_output = true;
  599. return NULL;
  600. }
  601. static char *set_schedtime(const char *arg, struct schedtime *st)
  602. {
  603. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  604. return "Invalid time set, should be HH:MM";
  605. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  606. return "Invalid time set.";
  607. st->enable = true;
  608. return NULL;
  609. }
  610. static char* set_sharelog(char *arg)
  611. {
  612. char *r = "";
  613. long int i = strtol(arg, &r, 10);
  614. if ((!*r) && i >= 0 && i <= INT_MAX) {
  615. sharelog_file = fdopen((int)i, "a");
  616. if (!sharelog_file)
  617. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  618. } else if (!strcmp(arg, "-")) {
  619. sharelog_file = stdout;
  620. if (!sharelog_file)
  621. applog(LOG_ERR, "Standard output missing for share log");
  622. } else {
  623. sharelog_file = fopen(arg, "a");
  624. if (!sharelog_file)
  625. applog(LOG_ERR, "Failed to open %s for share log", arg);
  626. }
  627. return NULL;
  628. }
  629. static char *temp_cutoff_str = NULL;
  630. char *set_temp_cutoff(char *arg)
  631. {
  632. int val;
  633. if (!(arg && arg[0]))
  634. return "Invalid parameters for set temp cutoff";
  635. val = atoi(arg);
  636. if (val < 0 || val > 200)
  637. return "Invalid value passed to set temp cutoff";
  638. temp_cutoff_str = arg;
  639. return NULL;
  640. }
  641. static void load_temp_cutoffs()
  642. {
  643. int i, val = 0, device = 0;
  644. char *nextptr;
  645. if (temp_cutoff_str) {
  646. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  647. if (device >= total_devices)
  648. quit(1, "Too many values passed to set temp cutoff");
  649. val = atoi(nextptr);
  650. if (val < 0 || val > 200)
  651. quit(1, "Invalid value passed to set temp cutoff");
  652. rd_lock(&devices_lock);
  653. devices[device]->cutofftemp = val;
  654. rd_unlock(&devices_lock);
  655. }
  656. } else {
  657. rd_lock(&devices_lock);
  658. for (i = device; i < total_devices; ++i) {
  659. if (!devices[i]->cutofftemp)
  660. devices[i]->cutofftemp = opt_cutofftemp;
  661. }
  662. rd_unlock(&devices_lock);
  663. return;
  664. }
  665. if (device <= 1) {
  666. rd_lock(&devices_lock);
  667. for (i = device; i < total_devices; ++i)
  668. devices[i]->cutofftemp = val;
  669. rd_unlock(&devices_lock);
  670. }
  671. }
  672. static char *set_api_allow(const char *arg)
  673. {
  674. opt_set_charp(arg, &opt_api_allow);
  675. return NULL;
  676. }
  677. static char *set_api_groups(const char *arg)
  678. {
  679. opt_set_charp(arg, &opt_api_groups);
  680. return NULL;
  681. }
  682. static char *set_api_description(const char *arg)
  683. {
  684. opt_set_charp(arg, &opt_api_description);
  685. return NULL;
  686. }
  687. #ifdef USE_ICARUS
  688. static char *set_icarus_options(const char *arg)
  689. {
  690. opt_set_charp(arg, &opt_icarus_options);
  691. return NULL;
  692. }
  693. static char *set_icarus_timing(const char *arg)
  694. {
  695. opt_set_charp(arg, &opt_icarus_timing);
  696. return NULL;
  697. }
  698. #endif
  699. #ifdef USE_AVALON
  700. static char *set_avalon_options(const char *arg)
  701. {
  702. opt_set_charp(arg, &opt_avalon_options);
  703. return NULL;
  704. }
  705. #endif
  706. #ifdef USE_USBUTILS
  707. static char *set_usb_select(const char *arg)
  708. {
  709. opt_set_charp(arg, &opt_usb_select);
  710. return NULL;
  711. }
  712. #endif
  713. static char *set_null(const char __maybe_unused *arg)
  714. {
  715. return NULL;
  716. }
  717. /* These options are available from config file or commandline */
  718. static struct opt_table opt_config_table[] = {
  719. OPT_WITH_ARG("--api-allow",
  720. set_api_allow, NULL, NULL,
  721. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  722. OPT_WITH_ARG("--api-description",
  723. set_api_description, NULL, NULL,
  724. "Description placed in the API status header, default: cgminer version"),
  725. OPT_WITH_ARG("--api-groups",
  726. set_api_groups, NULL, NULL,
  727. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  728. OPT_WITHOUT_ARG("--api-listen",
  729. opt_set_bool, &opt_api_listen,
  730. "Enable API, default: disabled"),
  731. OPT_WITHOUT_ARG("--api-network",
  732. opt_set_bool, &opt_api_network,
  733. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  734. OPT_WITH_ARG("--api-port",
  735. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  736. "Port number of miner API"),
  737. #ifdef HAVE_ADL
  738. OPT_WITHOUT_ARG("--auto-fan",
  739. opt_set_bool, &opt_autofan,
  740. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  741. OPT_WITHOUT_ARG("--auto-gpu",
  742. opt_set_bool, &opt_autoengine,
  743. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  744. #endif
  745. OPT_WITHOUT_ARG("--balance",
  746. set_balance, &pool_strategy,
  747. "Change multipool strategy from failover to even share balance"),
  748. OPT_WITHOUT_ARG("--benchmark",
  749. opt_set_bool, &opt_benchmark,
  750. "Run cgminer in benchmark mode - produces no shares"),
  751. #if defined(USE_BITFORCE)
  752. OPT_WITHOUT_ARG("--bfl-range",
  753. opt_set_bool, &opt_bfl_noncerange,
  754. "Use nonce range on bitforce devices if supported"),
  755. #endif
  756. #ifdef HAVE_CURSES
  757. OPT_WITHOUT_ARG("--compact",
  758. opt_set_bool, &opt_compact,
  759. "Use compact display without per device statistics"),
  760. #endif
  761. OPT_WITHOUT_ARG("--debug|-D",
  762. enable_debug, &opt_debug,
  763. "Enable debug output"),
  764. OPT_WITH_ARG("--device|-d",
  765. set_devices, NULL, NULL,
  766. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  767. OPT_WITHOUT_ARG("--disable-gpu|-G",
  768. opt_set_bool, &opt_nogpu,
  769. #ifdef HAVE_OPENCL
  770. "Disable GPU mining even if suitable devices exist"
  771. #else
  772. opt_hidden
  773. #endif
  774. ),
  775. OPT_WITHOUT_ARG("--disable-rejecting",
  776. opt_set_bool, &opt_disable_pool,
  777. "Automatically disable pools that continually reject shares"),
  778. OPT_WITH_ARG("--expiry|-E",
  779. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  780. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  781. OPT_WITHOUT_ARG("--failover-only",
  782. opt_set_bool, &opt_fail_only,
  783. "Don't leak work to backup pools when primary pool is lagging"),
  784. OPT_WITHOUT_ARG("--fix-protocol",
  785. opt_set_bool, &opt_fix_protocol,
  786. "Do not redirect to a different getwork protocol (eg. stratum)"),
  787. #ifdef HAVE_OPENCL
  788. OPT_WITH_ARG("--gpu-dyninterval",
  789. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  790. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  791. OPT_WITH_ARG("--gpu-platform",
  792. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  793. "Select OpenCL platform ID to use for GPU mining"),
  794. OPT_WITH_ARG("--gpu-threads|-g",
  795. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  796. "Number of threads per GPU (1 - 10)"),
  797. #ifdef HAVE_ADL
  798. OPT_WITH_ARG("--gpu-engine",
  799. set_gpu_engine, NULL, NULL,
  800. "GPU engine (over)clock range in Mhz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  801. OPT_WITH_ARG("--gpu-fan",
  802. set_gpu_fan, NULL, NULL,
  803. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  804. OPT_WITH_ARG("--gpu-map",
  805. set_gpu_map, NULL, NULL,
  806. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  807. OPT_WITH_ARG("--gpu-memclock",
  808. set_gpu_memclock, NULL, NULL,
  809. "Set the GPU memory (over)clock in Mhz - one value for all or separate by commas for per card"),
  810. OPT_WITH_ARG("--gpu-memdiff",
  811. set_gpu_memdiff, NULL, NULL,
  812. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  813. OPT_WITH_ARG("--gpu-powertune",
  814. set_gpu_powertune, NULL, NULL,
  815. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  816. OPT_WITHOUT_ARG("--gpu-reorder",
  817. opt_set_bool, &opt_reorder,
  818. "Attempt to reorder GPU devices according to PCI Bus ID"),
  819. OPT_WITH_ARG("--gpu-vddc",
  820. set_gpu_vddc, NULL, NULL,
  821. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  822. #endif
  823. #ifdef USE_SCRYPT
  824. OPT_WITH_ARG("--lookup-gap",
  825. set_lookup_gap, NULL, NULL,
  826. "Set GPU lookup gap for scrypt mining, comma separated"),
  827. #endif
  828. OPT_WITH_ARG("--intensity|-I",
  829. set_intensity, NULL, NULL,
  830. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  831. #endif
  832. OPT_WITH_ARG("--hotplug",
  833. set_int_0_to_9999, NULL, &hotplug_time,
  834. #ifdef USE_USBUTILS
  835. "Seconds between hotplug checks (0 means never check)"
  836. #else
  837. opt_hidden
  838. #endif
  839. ),
  840. #if defined(HAVE_OPENCL) || defined(HAVE_MODMINER)
  841. OPT_WITH_ARG("--kernel-path|-K",
  842. opt_set_charp, opt_show_charp, &opt_kernel_path,
  843. "Specify a path to where bitstream and kernel files are"),
  844. #endif
  845. #ifdef HAVE_OPENCL
  846. OPT_WITH_ARG("--kernel|-k",
  847. set_kernel, NULL, NULL,
  848. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  849. #endif
  850. #ifdef USE_ICARUS
  851. OPT_WITH_ARG("--icarus-options",
  852. set_icarus_options, NULL, NULL,
  853. opt_hidden),
  854. OPT_WITH_ARG("--icarus-timing",
  855. set_icarus_timing, NULL, NULL,
  856. opt_hidden),
  857. #endif
  858. #ifdef USE_AVALON
  859. OPT_WITH_ARG("--avalon-options",
  860. set_avalon_options, NULL, NULL,
  861. opt_hidden),
  862. #endif
  863. OPT_WITHOUT_ARG("--load-balance",
  864. set_loadbalance, &pool_strategy,
  865. "Change multipool strategy from failover to efficiency based balance"),
  866. OPT_WITH_ARG("--log|-l",
  867. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  868. "Interval in seconds between log output"),
  869. OPT_WITHOUT_ARG("--lowmem",
  870. opt_set_bool, &opt_lowmem,
  871. "Minimise caching of shares for low memory applications"),
  872. #if defined(unix)
  873. OPT_WITH_ARG("--monitor|-m",
  874. opt_set_charp, NULL, &opt_stderr_cmd,
  875. "Use custom pipe cmd for output messages"),
  876. #endif // defined(unix)
  877. OPT_WITHOUT_ARG("--net-delay",
  878. opt_set_bool, &opt_delaynet,
  879. "Impose small delays in networking to not overload slow routers"),
  880. OPT_WITHOUT_ARG("--no-adl",
  881. opt_set_bool, &opt_noadl,
  882. #ifdef HAVE_ADL
  883. "Disable the ATI display library used for monitoring and setting GPU parameters"
  884. #else
  885. opt_hidden
  886. #endif
  887. ),
  888. OPT_WITHOUT_ARG("--no-pool-disable",
  889. opt_set_invbool, &opt_disable_pool,
  890. opt_hidden),
  891. OPT_WITHOUT_ARG("--no-restart",
  892. opt_set_invbool, &opt_restart,
  893. #ifdef HAVE_OPENCL
  894. "Do not attempt to restart GPUs that hang"
  895. #else
  896. opt_hidden
  897. #endif
  898. ),
  899. OPT_WITHOUT_ARG("--no-submit-stale",
  900. opt_set_invbool, &opt_submit_stale,
  901. "Don't submit shares if they are detected as stale"),
  902. OPT_WITH_ARG("--pass|-p",
  903. set_pass, NULL, NULL,
  904. "Password for bitcoin JSON-RPC server"),
  905. OPT_WITHOUT_ARG("--per-device-stats",
  906. opt_set_bool, &want_per_device_stats,
  907. "Force verbose mode and output per-device statistics"),
  908. OPT_WITHOUT_ARG("--protocol-dump|-P",
  909. opt_set_bool, &opt_protocol,
  910. "Verbose dump of protocol-level activities"),
  911. OPT_WITH_ARG("--queue|-Q",
  912. set_int_0_to_9999, opt_show_intval, &opt_queue,
  913. "Minimum number of work items to have queued (0+)"),
  914. OPT_WITHOUT_ARG("--quiet|-q",
  915. opt_set_bool, &opt_quiet,
  916. "Disable logging output, display status and errors"),
  917. OPT_WITHOUT_ARG("--real-quiet",
  918. opt_set_bool, &opt_realquiet,
  919. "Disable all output"),
  920. OPT_WITHOUT_ARG("--remove-disabled",
  921. opt_set_bool, &opt_removedisabled,
  922. "Remove disabled devices entirely, as if they didn't exist"),
  923. OPT_WITH_ARG("--retries",
  924. set_null, NULL, NULL,
  925. opt_hidden),
  926. OPT_WITH_ARG("--retry-pause",
  927. set_null, NULL, NULL,
  928. opt_hidden),
  929. OPT_WITH_ARG("--rotate",
  930. set_rotate, opt_show_intval, &opt_rotate_period,
  931. "Change multipool strategy from failover to regularly rotate at N minutes"),
  932. OPT_WITHOUT_ARG("--round-robin",
  933. set_rr, &pool_strategy,
  934. "Change multipool strategy from failover to round robin on failure"),
  935. #ifdef USE_FPGA_SERIAL
  936. OPT_WITH_ARG("--scan-serial|-S",
  937. add_serial, NULL, NULL,
  938. "Serial port to probe for Serial FPGA Mining device"),
  939. #endif
  940. OPT_WITH_ARG("--scan-time|-s",
  941. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  942. "Upper bound on time spent scanning current work, in seconds"),
  943. OPT_WITH_ARG("--sched-start",
  944. set_schedtime, NULL, &schedstart,
  945. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  946. OPT_WITH_ARG("--sched-stop",
  947. set_schedtime, NULL, &schedstop,
  948. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  949. #ifdef USE_SCRYPT
  950. OPT_WITHOUT_ARG("--scrypt",
  951. opt_set_bool, &opt_scrypt,
  952. "Use the scrypt algorithm for mining (litecoin only)"),
  953. OPT_WITH_ARG("--shaders",
  954. set_shaders, NULL, NULL,
  955. "GPU shaders per card for tuning scrypt, comma separated"),
  956. #endif
  957. OPT_WITH_ARG("--sharelog",
  958. set_sharelog, NULL, NULL,
  959. "Append share log to file"),
  960. OPT_WITH_ARG("--shares",
  961. opt_set_intval, NULL, &opt_shares,
  962. "Quit after mining N shares (default: unlimited)"),
  963. OPT_WITH_ARG("--socks-proxy",
  964. opt_set_charp, NULL, &opt_socks_proxy,
  965. "Set socks4 proxy (host:port)"),
  966. #ifdef HAVE_SYSLOG_H
  967. OPT_WITHOUT_ARG("--syslog",
  968. opt_set_bool, &use_syslog,
  969. "Use system log for output messages (default: standard error)"),
  970. #endif
  971. #if defined(HAVE_ADL) || defined(USE_BITFORCE) || defined(USE_MODMINER) || defined(USE_BFLSC)
  972. OPT_WITH_ARG("--temp-cutoff",
  973. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  974. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  975. #endif
  976. #ifdef HAVE_ADL
  977. OPT_WITH_ARG("--temp-hysteresis",
  978. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  979. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  980. OPT_WITH_ARG("--temp-overheat",
  981. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  982. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  983. OPT_WITH_ARG("--temp-target",
  984. set_temp_target, opt_show_intval, &opt_targettemp,
  985. "Target temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  986. #endif
  987. OPT_WITHOUT_ARG("--text-only|-T",
  988. opt_set_invbool, &use_curses,
  989. #ifdef HAVE_CURSES
  990. "Disable ncurses formatted screen output"
  991. #else
  992. opt_hidden
  993. #endif
  994. ),
  995. #ifdef USE_SCRYPT
  996. OPT_WITH_ARG("--thread-concurrency",
  997. set_thread_concurrency, NULL, NULL,
  998. "Set GPU thread concurrency for scrypt mining, comma separated"),
  999. #endif
  1000. OPT_WITH_ARG("--url|-o",
  1001. set_url, NULL, NULL,
  1002. "URL for bitcoin JSON-RPC server"),
  1003. OPT_WITH_ARG("--user|-u",
  1004. set_user, NULL, NULL,
  1005. "Username for bitcoin JSON-RPC server"),
  1006. #ifdef USE_USBUTILS
  1007. OPT_WITH_ARG("--usb",
  1008. set_usb_select, NULL, NULL,
  1009. "USB device selection"),
  1010. OPT_WITH_ARG("--usb-dump",
  1011. set_int_0_to_10, opt_show_intval, &opt_usbdump,
  1012. opt_hidden),
  1013. OPT_WITHOUT_ARG("--usb-list-all",
  1014. opt_set_bool, &opt_usb_list_all,
  1015. opt_hidden),
  1016. #endif
  1017. #ifdef HAVE_OPENCL
  1018. OPT_WITH_ARG("--vectors|-v",
  1019. set_vector, NULL, NULL,
  1020. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  1021. #endif
  1022. OPT_WITHOUT_ARG("--verbose",
  1023. opt_set_bool, &opt_log_output,
  1024. "Log verbose output to stderr as well as status output"),
  1025. #ifdef HAVE_OPENCL
  1026. OPT_WITH_ARG("--worksize|-w",
  1027. set_worksize, NULL, NULL,
  1028. "Override detected optimal worksize - one value or comma separated list"),
  1029. #endif
  1030. OPT_WITH_ARG("--userpass|-O",
  1031. set_userpass, NULL, NULL,
  1032. "Username:Password pair for bitcoin JSON-RPC server"),
  1033. OPT_WITHOUT_ARG("--worktime",
  1034. opt_set_bool, &opt_worktime,
  1035. "Display extra work time debug information"),
  1036. OPT_WITH_ARG("--pools",
  1037. opt_set_bool, NULL, NULL, opt_hidden),
  1038. OPT_ENDTABLE
  1039. };
  1040. static char *load_config(const char *arg, void __maybe_unused *unused);
  1041. static int fileconf_load;
  1042. static char *parse_config(json_t *config, bool fileconf)
  1043. {
  1044. static char err_buf[200];
  1045. struct opt_table *opt;
  1046. json_t *val;
  1047. if (fileconf && !fileconf_load)
  1048. fileconf_load = 1;
  1049. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1050. char *p, *name;
  1051. /* We don't handle subtables. */
  1052. assert(!(opt->type & OPT_SUBTABLE));
  1053. /* Pull apart the option name(s). */
  1054. name = strdup(opt->names);
  1055. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1056. char *err = NULL;
  1057. /* Ignore short options. */
  1058. if (p[1] != '-')
  1059. continue;
  1060. val = json_object_get(config, p+2);
  1061. if (!val)
  1062. continue;
  1063. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  1064. err = opt->cb_arg(json_string_value(val),
  1065. opt->u.arg);
  1066. } else if ((opt->type & OPT_HASARG) && json_is_array(val)) {
  1067. int n, size = json_array_size(val);
  1068. for (n = 0; n < size && !err; n++) {
  1069. if (json_is_string(json_array_get(val, n)))
  1070. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  1071. else if (json_is_object(json_array_get(val, n)))
  1072. err = parse_config(json_array_get(val, n), false);
  1073. }
  1074. } else if ((opt->type & OPT_NOARG) && json_is_true(val))
  1075. err = opt->cb(opt->u.arg);
  1076. else
  1077. err = "Invalid value";
  1078. if (err) {
  1079. /* Allow invalid values to be in configuration
  1080. * file, just skipping over them provided the
  1081. * JSON is still valid after that. */
  1082. if (fileconf) {
  1083. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1084. fileconf_load = -1;
  1085. } else {
  1086. sprintf(err_buf, "Parsing JSON option %s: %s",
  1087. p, err);
  1088. return err_buf;
  1089. }
  1090. }
  1091. }
  1092. free(name);
  1093. }
  1094. val = json_object_get(config, JSON_INCLUDE_CONF);
  1095. if (val && json_is_string(val))
  1096. return load_config(json_string_value(val), NULL);
  1097. return NULL;
  1098. }
  1099. char *cnfbuf = NULL;
  1100. static char *load_config(const char *arg, void __maybe_unused *unused)
  1101. {
  1102. json_error_t err;
  1103. json_t *config;
  1104. char *json_error;
  1105. if (!cnfbuf)
  1106. cnfbuf = strdup(arg);
  1107. if (++include_count > JSON_MAX_DEPTH)
  1108. return JSON_MAX_DEPTH_ERR;
  1109. #if JANSSON_MAJOR_VERSION > 1
  1110. config = json_load_file(arg, 0, &err);
  1111. #else
  1112. config = json_load_file(arg, &err);
  1113. #endif
  1114. if (!json_is_object(config)) {
  1115. json_error = malloc(JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text));
  1116. if (!json_error)
  1117. quit(1, "Malloc failure in json error");
  1118. sprintf(json_error, JSON_LOAD_ERROR, arg, err.text);
  1119. return json_error;
  1120. }
  1121. config_loaded = true;
  1122. /* Parse the config now, so we can override it. That can keep pointers
  1123. * so don't free config object. */
  1124. return parse_config(config, true);
  1125. }
  1126. static char *set_default_config(const char *arg)
  1127. {
  1128. opt_set_charp(arg, &default_config);
  1129. return NULL;
  1130. }
  1131. void default_save_file(char *filename);
  1132. static void load_default_config(void)
  1133. {
  1134. cnfbuf = malloc(PATH_MAX);
  1135. default_save_file(cnfbuf);
  1136. if (!access(cnfbuf, R_OK))
  1137. load_config(cnfbuf, NULL);
  1138. else {
  1139. free(cnfbuf);
  1140. cnfbuf = NULL;
  1141. }
  1142. }
  1143. extern const char *opt_argv0;
  1144. static char *opt_verusage_and_exit(const char *extra)
  1145. {
  1146. printf("%s\nBuilt with "
  1147. #ifdef USE_BFLSC
  1148. "bflsc "
  1149. #endif
  1150. #ifdef HAVE_OPENCL
  1151. "GPU "
  1152. #endif
  1153. #ifdef USE_BITFORCE
  1154. "bitforce "
  1155. #endif
  1156. #ifdef USE_ICARUS
  1157. "icarus "
  1158. #endif
  1159. #ifdef USE_AVALON
  1160. "avalon "
  1161. #endif
  1162. #ifdef USE_MODMINER
  1163. "modminer "
  1164. #endif
  1165. #ifdef USE_ZTEX
  1166. "ztex "
  1167. #endif
  1168. #ifdef USE_SCRYPT
  1169. "scrypt "
  1170. #endif
  1171. "mining support.\n"
  1172. , packagename);
  1173. printf("%s", opt_usage(opt_argv0, extra));
  1174. fflush(stdout);
  1175. exit(0);
  1176. }
  1177. #if defined(HAVE_OPENCL) || defined(USE_USBUTILS)
  1178. char *display_devs(int *ndevs)
  1179. {
  1180. *ndevs = 0;
  1181. #ifdef HAVE_OPENCL
  1182. print_ndevs(ndevs);
  1183. #endif
  1184. #ifdef USE_USBUTILS
  1185. usb_all(0);
  1186. #endif
  1187. exit(*ndevs);
  1188. }
  1189. #endif
  1190. /* These options are available from commandline only */
  1191. static struct opt_table opt_cmdline_table[] = {
  1192. OPT_WITH_ARG("--config|-c",
  1193. load_config, NULL, NULL,
  1194. "Load a JSON-format configuration file\n"
  1195. "See example.conf for an example configuration."),
  1196. OPT_WITH_ARG("--default-config",
  1197. set_default_config, NULL, NULL,
  1198. "Specify the filename of the default config file\n"
  1199. "Loaded at start and used when saving without a name."),
  1200. OPT_WITHOUT_ARG("--help|-h",
  1201. opt_verusage_and_exit, NULL,
  1202. "Print this message"),
  1203. #if defined(HAVE_OPENCL) || defined(USE_USBUTILS)
  1204. OPT_WITHOUT_ARG("--ndevs|-n",
  1205. display_devs, &nDevs,
  1206. "Display "
  1207. #ifdef HAVE_OPENCL
  1208. "number of detected GPUs, OpenCL platform information, "
  1209. #endif
  1210. #ifdef USE_USBUTILS
  1211. "all USB devices, "
  1212. #endif
  1213. "and exit"),
  1214. #endif
  1215. OPT_WITHOUT_ARG("--version|-V",
  1216. opt_version_and_exit, packagename,
  1217. "Display version and exit"),
  1218. OPT_ENDTABLE
  1219. };
  1220. static bool jobj_binary(const json_t *obj, const char *key,
  1221. void *buf, size_t buflen, bool required)
  1222. {
  1223. const char *hexstr;
  1224. json_t *tmp;
  1225. tmp = json_object_get(obj, key);
  1226. if (unlikely(!tmp)) {
  1227. if (unlikely(required))
  1228. applog(LOG_ERR, "JSON key '%s' not found", key);
  1229. return false;
  1230. }
  1231. hexstr = json_string_value(tmp);
  1232. if (unlikely(!hexstr)) {
  1233. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1234. return false;
  1235. }
  1236. if (!hex2bin(buf, hexstr, buflen))
  1237. return false;
  1238. return true;
  1239. }
  1240. static void calc_midstate(struct work *work)
  1241. {
  1242. unsigned char data[64];
  1243. uint32_t *data32 = (uint32_t *)data;
  1244. sha2_context ctx;
  1245. flip64(data32, work->data);
  1246. sha2_starts(&ctx);
  1247. sha2_update(&ctx, data, 64);
  1248. memcpy(work->midstate, ctx.state, 32);
  1249. endian_flip32(work->midstate, work->midstate);
  1250. }
  1251. static struct work *make_work(void)
  1252. {
  1253. struct work *work = calloc(1, sizeof(struct work));
  1254. if (unlikely(!work))
  1255. quit(1, "Failed to calloc work in make_work");
  1256. cg_wlock(&control_lock);
  1257. work->id = total_work++;
  1258. cg_wunlock(&control_lock);
  1259. return work;
  1260. }
  1261. /* This is the central place all work that is about to be retired should be
  1262. * cleaned to remove any dynamically allocated arrays within the struct */
  1263. void clean_work(struct work *work)
  1264. {
  1265. free(work->job_id);
  1266. free(work->nonce2);
  1267. free(work->ntime);
  1268. free(work->gbt_coinbase);
  1269. free(work->nonce1);
  1270. memset(work, 0, sizeof(struct work));
  1271. }
  1272. /* All dynamically allocated work structs should be freed here to not leak any
  1273. * ram from arrays allocated within the work struct */
  1274. void free_work(struct work *work)
  1275. {
  1276. clean_work(work);
  1277. free(work);
  1278. }
  1279. /* Generate a GBT coinbase from the existing GBT variables stored. Must be
  1280. * entered under gbt_lock */
  1281. static void __build_gbt_coinbase(struct pool *pool)
  1282. {
  1283. unsigned char *coinbase;
  1284. int cbt_len, orig_len;
  1285. uint8_t *extra_len;
  1286. size_t cal_len;
  1287. cbt_len = strlen(pool->coinbasetxn) / 2;
  1288. pool->coinbase_len = cbt_len + 4;
  1289. /* We add 4 bytes of extra data corresponding to nonce2 of stratum */
  1290. cal_len = pool->coinbase_len + 1;
  1291. align_len(&cal_len);
  1292. coinbase = calloc(cal_len, 1);
  1293. hex2bin(coinbase, pool->coinbasetxn, 42);
  1294. extra_len = (uint8_t *)(coinbase + 41);
  1295. orig_len = *extra_len;
  1296. hex2bin(coinbase + 42, pool->coinbasetxn + 84, orig_len);
  1297. memcpy(coinbase + 42 + orig_len, &pool->nonce2, 4);
  1298. *extra_len += 4;
  1299. hex2bin(coinbase + 42 + *extra_len, pool->coinbasetxn + 84 + (orig_len * 2), cbt_len - orig_len - 42);
  1300. pool->nonce2++;
  1301. free(pool->gbt_coinbase);
  1302. pool->gbt_coinbase = coinbase;
  1303. }
  1304. static void gen_hash(unsigned char *data, unsigned char *hash, int len);
  1305. /* Process transactions with GBT by storing the binary value of the first
  1306. * transaction, and the hashes of the remaining transactions since these
  1307. * remain constant with an altered coinbase when generating work. Must be
  1308. * entered under gbt_lock */
  1309. static bool __build_gbt_txns(struct pool *pool, json_t *res_val)
  1310. {
  1311. json_t *txn_array;
  1312. bool ret = false;
  1313. size_t cal_len;
  1314. int i;
  1315. free(pool->txn_hashes);
  1316. pool->txn_hashes = NULL;
  1317. pool->gbt_txns = 0;
  1318. txn_array = json_object_get(res_val, "transactions");
  1319. if (!json_is_array(txn_array))
  1320. goto out;
  1321. ret = true;
  1322. pool->gbt_txns = json_array_size(txn_array);
  1323. if (!pool->gbt_txns)
  1324. goto out;
  1325. pool->txn_hashes = calloc(32 * (pool->gbt_txns + 1), 1);
  1326. if (unlikely(!pool->txn_hashes))
  1327. quit(1, "Failed to calloc txn_hashes in __build_gbt_txns");
  1328. for (i = 0; i < pool->gbt_txns; i++) {
  1329. json_t *txn_val = json_object_get(json_array_get(txn_array, i), "data");
  1330. const char *txn = json_string_value(txn_val);
  1331. int txn_len = strlen(txn);
  1332. unsigned char *txn_bin;
  1333. cal_len = txn_len;
  1334. align_len(&cal_len);
  1335. txn_bin = calloc(cal_len, 1);
  1336. if (unlikely(!txn_bin))
  1337. quit(1, "Failed to calloc txn_bin in __build_gbt_txns");
  1338. if (unlikely(!hex2bin(txn_bin, txn, txn_len / 2)))
  1339. quit(1, "Failed to hex2bin txn_bin");
  1340. gen_hash(txn_bin, pool->txn_hashes + (32 * i), txn_len / 2);
  1341. free(txn_bin);
  1342. }
  1343. out:
  1344. return ret;
  1345. }
  1346. static unsigned char *__gbt_merkleroot(struct pool *pool)
  1347. {
  1348. unsigned char *merkle_hash;
  1349. int i, txns;
  1350. merkle_hash = calloc(32 * (pool->gbt_txns + 2), 1);
  1351. if (unlikely(!merkle_hash))
  1352. quit(1, "Failed to calloc merkle_hash in __gbt_merkleroot");
  1353. gen_hash(pool->gbt_coinbase, merkle_hash, pool->coinbase_len);
  1354. if (pool->gbt_txns)
  1355. memcpy(merkle_hash + 32, pool->txn_hashes, pool->gbt_txns * 32);
  1356. txns = pool->gbt_txns + 1;
  1357. while (txns > 1) {
  1358. if (txns % 2) {
  1359. memcpy(&merkle_hash[txns * 32], &merkle_hash[(txns - 1) * 32], 32);
  1360. txns++;
  1361. }
  1362. for (i = 0; i < txns; i += 2){
  1363. unsigned char hashout[32];
  1364. gen_hash(merkle_hash + (i * 32), hashout, 64);
  1365. memcpy(merkle_hash + (i / 2 * 32), hashout, 32);
  1366. }
  1367. txns /= 2;
  1368. }
  1369. return merkle_hash;
  1370. }
  1371. static void calc_diff(struct work *work, int known);
  1372. static bool work_decode(struct pool *pool, struct work *work, json_t *val);
  1373. static void update_gbt(struct pool *pool)
  1374. {
  1375. int rolltime;
  1376. json_t *val;
  1377. CURL *curl;
  1378. curl = curl_easy_init();
  1379. if (unlikely(!curl))
  1380. quit (1, "CURL initialisation failed in update_gbt");
  1381. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  1382. pool->rpc_req, true, false, &rolltime, pool, false);
  1383. if (val) {
  1384. struct work *work = make_work();
  1385. bool rc = work_decode(pool, work, val);
  1386. total_getworks++;
  1387. pool->getwork_requested++;
  1388. if (rc) {
  1389. applog(LOG_DEBUG, "Successfully retrieved and updated GBT from pool %u %s",
  1390. pool->pool_no, pool->rpc_url);
  1391. cgtime(&pool->tv_idle);
  1392. } else {
  1393. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher GBT from pool %u %s",
  1394. pool->pool_no, pool->rpc_url);
  1395. }
  1396. json_decref(val);
  1397. free_work(work);
  1398. } else {
  1399. applog(LOG_DEBUG, "FAILED to update GBT from pool %u %s",
  1400. pool->pool_no, pool->rpc_url);
  1401. }
  1402. curl_easy_cleanup(curl);
  1403. }
  1404. static char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
  1405. static void gen_gbt_work(struct pool *pool, struct work *work)
  1406. {
  1407. unsigned char *merkleroot;
  1408. struct timeval now;
  1409. cgtime(&now);
  1410. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  1411. update_gbt(pool);
  1412. cg_ilock(&pool->gbt_lock);
  1413. __build_gbt_coinbase(pool);
  1414. cg_dlock(&pool->gbt_lock);
  1415. merkleroot = __gbt_merkleroot(pool);
  1416. memcpy(work->data, &pool->gbt_version, 4);
  1417. memcpy(work->data + 4, pool->previousblockhash, 32);
  1418. memcpy(work->data + 4 + 32 + 32, &pool->curtime, 4);
  1419. memcpy(work->data + 4 + 32 + 32 + 4, &pool->gbt_bits, 4);
  1420. memcpy(work->target, pool->gbt_target, 32);
  1421. work->gbt_coinbase = bin2hex(pool->gbt_coinbase, pool->coinbase_len);
  1422. /* For encoding the block data on submission */
  1423. work->gbt_txns = pool->gbt_txns + 1;
  1424. if (pool->gbt_workid)
  1425. work->job_id = strdup(pool->gbt_workid);
  1426. cg_runlock(&pool->gbt_lock);
  1427. memcpy(work->data + 4 + 32, merkleroot, 32);
  1428. flip32(work->data + 4 + 32, merkleroot);
  1429. free(merkleroot);
  1430. memset(work->data + 4 + 32 + 32 + 4 + 4, 0, 4); /* nonce */
  1431. hex2bin(work->data + 4 + 32 + 32 + 4 + 4 + 4, workpadding, 48);
  1432. if (opt_debug) {
  1433. char *header = bin2hex(work->data, 128);
  1434. applog(LOG_DEBUG, "Generated GBT header %s", header);
  1435. applog(LOG_DEBUG, "Work coinbase %s", work->gbt_coinbase);
  1436. free(header);
  1437. }
  1438. calc_midstate(work);
  1439. local_work++;
  1440. work->pool = pool;
  1441. work->gbt = true;
  1442. work->id = total_work++;
  1443. work->longpoll = false;
  1444. work->getwork_mode = GETWORK_MODE_GBT;
  1445. work->work_block = work_block;
  1446. calc_diff(work, 0);
  1447. cgtime(&work->tv_staged);
  1448. }
  1449. static bool gbt_decode(struct pool *pool, json_t *res_val)
  1450. {
  1451. const char *previousblockhash;
  1452. const char *target;
  1453. const char *coinbasetxn;
  1454. const char *longpollid;
  1455. unsigned char hash_swap[32];
  1456. int expires;
  1457. int version;
  1458. int curtime;
  1459. bool submitold;
  1460. const char *bits;
  1461. const char *workid;
  1462. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  1463. target = json_string_value(json_object_get(res_val, "target"));
  1464. coinbasetxn = json_string_value(json_object_get(json_object_get(res_val, "coinbasetxn"), "data"));
  1465. longpollid = json_string_value(json_object_get(res_val, "longpollid"));
  1466. expires = json_integer_value(json_object_get(res_val, "expires"));
  1467. version = json_integer_value(json_object_get(res_val, "version"));
  1468. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  1469. submitold = json_is_true(json_object_get(res_val, "submitold"));
  1470. bits = json_string_value(json_object_get(res_val, "bits"));
  1471. workid = json_string_value(json_object_get(res_val, "workid"));
  1472. if (!previousblockhash || !target || !coinbasetxn || !longpollid ||
  1473. !expires || !version || !curtime || !bits) {
  1474. applog(LOG_ERR, "JSON failed to decode GBT");
  1475. return false;
  1476. }
  1477. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  1478. applog(LOG_DEBUG, "target: %s", target);
  1479. applog(LOG_DEBUG, "coinbasetxn: %s", coinbasetxn);
  1480. applog(LOG_DEBUG, "longpollid: %s", longpollid);
  1481. applog(LOG_DEBUG, "expires: %d", expires);
  1482. applog(LOG_DEBUG, "version: %d", version);
  1483. applog(LOG_DEBUG, "curtime: %d", curtime);
  1484. applog(LOG_DEBUG, "submitold: %s", submitold ? "true" : "false");
  1485. applog(LOG_DEBUG, "bits: %s", bits);
  1486. if (workid)
  1487. applog(LOG_DEBUG, "workid: %s", workid);
  1488. cg_wlock(&pool->gbt_lock);
  1489. free(pool->coinbasetxn);
  1490. pool->coinbasetxn = strdup(coinbasetxn);
  1491. free(pool->longpollid);
  1492. pool->longpollid = strdup(longpollid);
  1493. free(pool->gbt_workid);
  1494. if (workid)
  1495. pool->gbt_workid = strdup(workid);
  1496. else
  1497. pool->gbt_workid = NULL;
  1498. hex2bin(hash_swap, previousblockhash, 32);
  1499. swap256(pool->previousblockhash, hash_swap);
  1500. hex2bin(hash_swap, target, 32);
  1501. swab256(pool->gbt_target, hash_swap);
  1502. pool->gbt_expires = expires;
  1503. pool->gbt_version = htobe32(version);
  1504. pool->curtime = htobe32(curtime);
  1505. pool->submit_old = submitold;
  1506. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  1507. __build_gbt_txns(pool, res_val);
  1508. cg_wunlock(&pool->gbt_lock);
  1509. return true;
  1510. }
  1511. static bool getwork_decode(json_t *res_val, struct work *work)
  1512. {
  1513. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  1514. applog(LOG_ERR, "JSON inval data");
  1515. return false;
  1516. }
  1517. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  1518. // Calculate it ourselves
  1519. applog(LOG_DEBUG, "Calculating midstate locally");
  1520. calc_midstate(work);
  1521. }
  1522. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  1523. applog(LOG_ERR, "JSON inval target");
  1524. return false;
  1525. }
  1526. return true;
  1527. }
  1528. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  1529. {
  1530. json_t *res_val = json_object_get(val, "result");
  1531. bool ret = false;
  1532. cgtime(&pool->tv_lastwork);
  1533. if (!res_val || json_is_null(res_val)) {
  1534. applog(LOG_ERR, "JSON Failed to decode result");
  1535. goto out;
  1536. }
  1537. if (pool->has_gbt) {
  1538. if (unlikely(!gbt_decode(pool, res_val)))
  1539. goto out;
  1540. work->gbt = true;
  1541. ret = true;
  1542. goto out;
  1543. } else if (unlikely(!getwork_decode(res_val, work)))
  1544. goto out;
  1545. memset(work->hash, 0, sizeof(work->hash));
  1546. cgtime(&work->tv_staged);
  1547. ret = true;
  1548. out:
  1549. return ret;
  1550. }
  1551. int dev_from_id(int thr_id)
  1552. {
  1553. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  1554. return cgpu->device_id;
  1555. }
  1556. /* Make the change in the recent value adjust dynamically when the difference
  1557. * is large, but damp it when the values are closer together. This allows the
  1558. * value to change quickly, but not fluctuate too dramatically when it has
  1559. * stabilised. */
  1560. void decay_time(double *f, double fadd)
  1561. {
  1562. double ratio = 0;
  1563. if (likely(*f > 0)) {
  1564. ratio = fadd / *f;
  1565. if (ratio > 1)
  1566. ratio = 1 / ratio;
  1567. }
  1568. if (ratio > 0.63)
  1569. *f = (fadd * 0.58 + *f) / 1.58;
  1570. else
  1571. *f = (fadd + *f * 0.58) / 1.58;
  1572. }
  1573. static int __total_staged(void)
  1574. {
  1575. return HASH_COUNT(staged_work);
  1576. }
  1577. static int total_staged(void)
  1578. {
  1579. int ret;
  1580. mutex_lock(stgd_lock);
  1581. ret = __total_staged();
  1582. mutex_unlock(stgd_lock);
  1583. return ret;
  1584. }
  1585. #ifdef HAVE_CURSES
  1586. WINDOW *mainwin, *statuswin, *logwin;
  1587. #endif
  1588. double total_secs = 1.0;
  1589. static char statusline[256];
  1590. /* logstart is where the log window should start */
  1591. static int devcursor, logstart, logcursor;
  1592. #ifdef HAVE_CURSES
  1593. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  1594. static int statusy;
  1595. #endif
  1596. #ifdef HAVE_OPENCL
  1597. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  1598. #endif
  1599. #ifdef HAVE_CURSES
  1600. static inline void unlock_curses(void)
  1601. {
  1602. mutex_unlock(&console_lock);
  1603. }
  1604. static inline void lock_curses(void)
  1605. {
  1606. mutex_lock(&console_lock);
  1607. }
  1608. static bool curses_active_locked(void)
  1609. {
  1610. bool ret;
  1611. lock_curses();
  1612. ret = curses_active;
  1613. if (!ret)
  1614. unlock_curses();
  1615. return ret;
  1616. }
  1617. #endif
  1618. void tailsprintf(char *f, const char *fmt, ...)
  1619. {
  1620. va_list ap;
  1621. va_start(ap, fmt);
  1622. vsprintf(f + strlen(f), fmt, ap);
  1623. va_end(ap);
  1624. }
  1625. /* Convert a uint64_t value into a truncated string for displaying with its
  1626. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  1627. static void suffix_string(uint64_t val, char *buf, int sigdigits)
  1628. {
  1629. const double dkilo = 1000.0;
  1630. const uint64_t kilo = 1000ull;
  1631. const uint64_t mega = 1000000ull;
  1632. const uint64_t giga = 1000000000ull;
  1633. const uint64_t tera = 1000000000000ull;
  1634. const uint64_t peta = 1000000000000000ull;
  1635. const uint64_t exa = 1000000000000000000ull;
  1636. char suffix[2] = "";
  1637. bool decimal = true;
  1638. double dval;
  1639. if (val >= exa) {
  1640. val /= peta;
  1641. dval = (double)val / dkilo;
  1642. sprintf(suffix, "E");
  1643. } else if (val >= peta) {
  1644. val /= tera;
  1645. dval = (double)val / dkilo;
  1646. sprintf(suffix, "P");
  1647. } else if (val >= tera) {
  1648. val /= giga;
  1649. dval = (double)val / dkilo;
  1650. sprintf(suffix, "T");
  1651. } else if (val >= giga) {
  1652. val /= mega;
  1653. dval = (double)val / dkilo;
  1654. sprintf(suffix, "G");
  1655. } else if (val >= mega) {
  1656. val /= kilo;
  1657. dval = (double)val / dkilo;
  1658. sprintf(suffix, "M");
  1659. } else if (val >= kilo) {
  1660. dval = (double)val / dkilo;
  1661. sprintf(suffix, "K");
  1662. } else {
  1663. dval = val;
  1664. decimal = false;
  1665. }
  1666. if (!sigdigits) {
  1667. if (decimal)
  1668. sprintf(buf, "%.3g%s", dval, suffix);
  1669. else
  1670. sprintf(buf, "%d%s", (unsigned int)dval, suffix);
  1671. } else {
  1672. /* Always show sigdigits + 1, padded on right with zeroes
  1673. * followed by suffix */
  1674. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  1675. sprintf(buf, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  1676. }
  1677. }
  1678. static void get_statline(char *buf, struct cgpu_info *cgpu)
  1679. {
  1680. char displayed_hashes[16], displayed_rolling[16];
  1681. uint64_t dh64, dr64;
  1682. dh64 = (double)cgpu->total_mhashes / total_secs * 1000000ull;
  1683. dr64 = (double)cgpu->rolling * 1000000ull;
  1684. suffix_string(dh64, displayed_hashes, 4);
  1685. suffix_string(dr64, displayed_rolling, 4);
  1686. sprintf(buf, "%s%d ", cgpu->drv->name, cgpu->device_id);
  1687. cgpu->drv->get_statline_before(buf, cgpu);
  1688. tailsprintf(buf, "(%ds):%s (avg):%sh/s | A:%d R:%d HW:%d U:%.1f/m",
  1689. opt_log_interval,
  1690. displayed_rolling,
  1691. displayed_hashes,
  1692. cgpu->accepted,
  1693. cgpu->rejected,
  1694. cgpu->hw_errors,
  1695. cgpu->utility);
  1696. cgpu->drv->get_statline(buf, cgpu);
  1697. }
  1698. static void text_print_status(int thr_id)
  1699. {
  1700. struct cgpu_info *cgpu;
  1701. char logline[256];
  1702. cgpu = get_thr_cgpu(thr_id);
  1703. if (cgpu) {
  1704. get_statline(logline, cgpu);
  1705. printf("%s\n", logline);
  1706. }
  1707. }
  1708. #ifdef HAVE_CURSES
  1709. /* Must be called with curses mutex lock held and curses_active */
  1710. static void curses_print_status(void)
  1711. {
  1712. struct pool *pool = current_pool();
  1713. wattron(statuswin, A_BOLD);
  1714. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1715. wattroff(statuswin, A_BOLD);
  1716. mvwhline(statuswin, 1, 0, '-', 80);
  1717. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1718. wclrtoeol(statuswin);
  1719. mvwprintw(statuswin, 3, 0, " ST: %d SS: %d NB: %d LW: %d GF: %d RF: %d",
  1720. total_staged(), total_stale, new_blocks,
  1721. local_work, total_go, total_ro);
  1722. wclrtoeol(statuswin);
  1723. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  1724. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1725. have_longpoll ? "": "out");
  1726. } else if (pool->has_stratum) {
  1727. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  1728. pool->sockaddr_url, pool->diff, pool->rpc_user);
  1729. } else {
  1730. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s %s as user %s",
  1731. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out",
  1732. pool->has_gbt ? "GBT" : "LP", pool->rpc_user);
  1733. }
  1734. wclrtoeol(statuswin);
  1735. mvwprintw(statuswin, 5, 0, " Block: %s... Diff:%s Started: %s Best share: %s ",
  1736. current_hash, block_diff, blocktime, best_share);
  1737. mvwhline(statuswin, 6, 0, '-', 80);
  1738. mvwhline(statuswin, statusy - 1, 0, '-', 80);
  1739. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1740. have_opencl ? "[G]PU management " : "");
  1741. }
  1742. static void adj_width(int var, int *length)
  1743. {
  1744. if ((int)(log10(var) + 1) > *length)
  1745. (*length)++;
  1746. }
  1747. static int dev_width;
  1748. static void curses_print_devstatus(int thr_id)
  1749. {
  1750. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1751. struct cgpu_info *cgpu;
  1752. char logline[256];
  1753. char displayed_hashes[16], displayed_rolling[16];
  1754. uint64_t dh64, dr64;
  1755. if (opt_compact)
  1756. return;
  1757. cgpu = get_thr_cgpu(thr_id);
  1758. if (cgpu->cgminer_id >= start_devices || devcursor + cgpu->cgminer_id > LINES - 2)
  1759. return;
  1760. cgpu->utility = cgpu->accepted / total_secs * 60;
  1761. wmove(statuswin,devcursor + cgpu->cgminer_id, 0);
  1762. wprintw(statuswin, " %s %*d: ", cgpu->drv->name, dev_width, cgpu->device_id);
  1763. logline[0] = '\0';
  1764. cgpu->drv->get_statline_before(logline, cgpu);
  1765. wprintw(statuswin, "%s", logline);
  1766. dh64 = (double)cgpu->total_mhashes / total_secs * 1000000ull;
  1767. dr64 = (double)cgpu->rolling * 1000000ull;
  1768. suffix_string(dh64, displayed_hashes, 4);
  1769. suffix_string(dr64, displayed_rolling, 4);
  1770. #ifdef USE_USBUTILS
  1771. if (cgpu->usbinfo.nodev)
  1772. wprintw(statuswin, "ZOMBIE");
  1773. else
  1774. #endif
  1775. if (cgpu->status == LIFE_DEAD)
  1776. wprintw(statuswin, "DEAD ");
  1777. else if (cgpu->status == LIFE_SICK)
  1778. wprintw(statuswin, "SICK ");
  1779. else if (cgpu->deven == DEV_DISABLED)
  1780. wprintw(statuswin, "OFF ");
  1781. else if (cgpu->deven == DEV_RECOVER)
  1782. wprintw(statuswin, "REST ");
  1783. else
  1784. wprintw(statuswin, "%6s", displayed_rolling);
  1785. adj_width(cgpu->accepted, &awidth);
  1786. adj_width(cgpu->rejected, &rwidth);
  1787. adj_width(cgpu->hw_errors, &hwwidth);
  1788. adj_width(cgpu->utility, &uwidth);
  1789. wprintw(statuswin, "/%6sh/s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1790. displayed_hashes,
  1791. awidth, cgpu->accepted,
  1792. rwidth, cgpu->rejected,
  1793. hwwidth, cgpu->hw_errors,
  1794. uwidth + 3, cgpu->utility);
  1795. logline[0] = '\0';
  1796. cgpu->drv->get_statline(logline, cgpu);
  1797. wprintw(statuswin, "%s", logline);
  1798. wclrtoeol(statuswin);
  1799. }
  1800. #endif
  1801. static void print_status(int thr_id)
  1802. {
  1803. if (!curses_active)
  1804. text_print_status(thr_id);
  1805. }
  1806. #ifdef HAVE_CURSES
  1807. /* Check for window resize. Called with curses mutex locked */
  1808. static inline void change_logwinsize(void)
  1809. {
  1810. int x, y, logx, logy;
  1811. getmaxyx(mainwin, y, x);
  1812. if (x < 80 || y < 25)
  1813. return;
  1814. if (y > statusy + 2 && statusy < logstart) {
  1815. if (y - 2 < logstart)
  1816. statusy = y - 2;
  1817. else
  1818. statusy = logstart;
  1819. logcursor = statusy + 1;
  1820. mvwin(logwin, logcursor, 0);
  1821. wresize(statuswin, statusy, x);
  1822. }
  1823. y -= logcursor;
  1824. getmaxyx(logwin, logy, logx);
  1825. /* Detect screen size change */
  1826. if (x != logx || y != logy)
  1827. wresize(logwin, y, x);
  1828. }
  1829. static void check_winsizes(void)
  1830. {
  1831. if (!use_curses)
  1832. return;
  1833. if (curses_active_locked()) {
  1834. int y, x;
  1835. erase();
  1836. x = getmaxx(statuswin);
  1837. if (logstart > LINES - 2)
  1838. statusy = LINES - 2;
  1839. else
  1840. statusy = logstart;
  1841. logcursor = statusy + 1;
  1842. wresize(statuswin, statusy, x);
  1843. getmaxyx(mainwin, y, x);
  1844. y -= logcursor;
  1845. wresize(logwin, y, x);
  1846. mvwin(logwin, logcursor, 0);
  1847. unlock_curses();
  1848. }
  1849. }
  1850. static void switch_compact(void)
  1851. {
  1852. if (opt_compact) {
  1853. logstart = devcursor + 1;
  1854. logcursor = logstart + 1;
  1855. } else {
  1856. logstart = devcursor + total_devices + 1;
  1857. logcursor = logstart + 1;
  1858. }
  1859. check_winsizes();
  1860. }
  1861. /* For mandatory printing when mutex is already locked */
  1862. void wlog(const char *f, ...)
  1863. {
  1864. va_list ap;
  1865. va_start(ap, f);
  1866. vw_printw(logwin, f, ap);
  1867. va_end(ap);
  1868. }
  1869. /* Mandatory printing */
  1870. void wlogprint(const char *f, ...)
  1871. {
  1872. va_list ap;
  1873. if (curses_active_locked()) {
  1874. va_start(ap, f);
  1875. vw_printw(logwin, f, ap);
  1876. va_end(ap);
  1877. unlock_curses();
  1878. }
  1879. }
  1880. #endif
  1881. #ifdef HAVE_CURSES
  1882. bool log_curses_only(int prio, const char *f, va_list ap)
  1883. {
  1884. bool high_prio;
  1885. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  1886. if (curses_active_locked()) {
  1887. if (!opt_loginput || high_prio) {
  1888. vw_printw(logwin, f, ap);
  1889. if (high_prio) {
  1890. touchwin(logwin);
  1891. wrefresh(logwin);
  1892. }
  1893. }
  1894. unlock_curses();
  1895. return true;
  1896. }
  1897. return false;
  1898. }
  1899. void clear_logwin(void)
  1900. {
  1901. if (curses_active_locked()) {
  1902. erase();
  1903. wclear(logwin);
  1904. unlock_curses();
  1905. }
  1906. }
  1907. void logwin_update(void)
  1908. {
  1909. if (curses_active_locked()) {
  1910. touchwin(logwin);
  1911. wrefresh(logwin);
  1912. unlock_curses();
  1913. }
  1914. }
  1915. #endif
  1916. static void enable_pool(struct pool *pool)
  1917. {
  1918. if (pool->enabled != POOL_ENABLED) {
  1919. enabled_pools++;
  1920. pool->enabled = POOL_ENABLED;
  1921. }
  1922. }
  1923. #ifdef HAVE_CURSES
  1924. static void disable_pool(struct pool *pool)
  1925. {
  1926. if (pool->enabled == POOL_ENABLED)
  1927. enabled_pools--;
  1928. pool->enabled = POOL_DISABLED;
  1929. }
  1930. #endif
  1931. static void reject_pool(struct pool *pool)
  1932. {
  1933. if (pool->enabled == POOL_ENABLED)
  1934. enabled_pools--;
  1935. pool->enabled = POOL_REJECTING;
  1936. }
  1937. static void restart_threads(void);
  1938. /* Theoretically threads could race when modifying accepted and
  1939. * rejected values but the chance of two submits completing at the
  1940. * same time is zero so there is no point adding extra locking */
  1941. static void
  1942. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  1943. char *hashshow, bool resubmit, char *worktime)
  1944. {
  1945. struct pool *pool = work->pool;
  1946. struct cgpu_info *cgpu;
  1947. cgpu = get_thr_cgpu(work->thr_id);
  1948. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  1949. mutex_lock(&stats_lock);
  1950. cgpu->accepted++;
  1951. total_accepted++;
  1952. pool->accepted++;
  1953. cgpu->diff_accepted += work->work_difficulty;
  1954. total_diff_accepted += work->work_difficulty;
  1955. pool->diff_accepted += work->work_difficulty;
  1956. mutex_unlock(&stats_lock);
  1957. pool->seq_rejects = 0;
  1958. cgpu->last_share_pool = pool->pool_no;
  1959. cgpu->last_share_pool_time = time(NULL);
  1960. cgpu->last_share_diff = work->work_difficulty;
  1961. pool->last_share_time = cgpu->last_share_pool_time;
  1962. pool->last_share_diff = work->work_difficulty;
  1963. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1964. if (!QUIET) {
  1965. if (total_pools > 1)
  1966. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  1967. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  1968. else
  1969. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  1970. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  1971. }
  1972. sharelog("accept", work);
  1973. if (opt_shares && total_accepted >= opt_shares) {
  1974. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  1975. kill_work();
  1976. return;
  1977. }
  1978. /* Detect if a pool that has been temporarily disabled for
  1979. * continually rejecting shares has started accepting shares.
  1980. * This will only happen with the work returned from a
  1981. * longpoll */
  1982. if (unlikely(pool->enabled == POOL_REJECTING)) {
  1983. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  1984. enable_pool(pool);
  1985. switch_pools(NULL);
  1986. }
  1987. /* If we know we found the block we know better than anyone
  1988. * that new work is needed. */
  1989. if (unlikely(work->block))
  1990. restart_threads();
  1991. } else {
  1992. mutex_lock(&stats_lock);
  1993. cgpu->rejected++;
  1994. total_rejected++;
  1995. pool->rejected++;
  1996. cgpu->diff_rejected += work->work_difficulty;
  1997. total_diff_rejected += work->work_difficulty;
  1998. pool->diff_rejected += work->work_difficulty;
  1999. pool->seq_rejects++;
  2000. mutex_unlock(&stats_lock);
  2001. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2002. if (!QUIET) {
  2003. char where[20];
  2004. char disposition[36] = "reject";
  2005. char reason[32];
  2006. strcpy(reason, "");
  2007. if (total_pools > 1)
  2008. sprintf(where, "pool %d", work->pool->pool_no);
  2009. else
  2010. strcpy(where, "");
  2011. if (!work->gbt)
  2012. res = json_object_get(val, "reject-reason");
  2013. if (res) {
  2014. const char *reasontmp = json_string_value(res);
  2015. size_t reasonLen = strlen(reasontmp);
  2016. if (reasonLen > 28)
  2017. reasonLen = 28;
  2018. reason[0] = ' '; reason[1] = '(';
  2019. memcpy(2 + reason, reasontmp, reasonLen);
  2020. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2021. memcpy(disposition + 7, reasontmp, reasonLen);
  2022. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2023. } else if (work->stratum && err && json_is_array(err)) {
  2024. json_t *reason_val = json_array_get(err, 1);
  2025. char *reason_str;
  2026. if (reason_val && json_is_string(reason_val)) {
  2027. reason_str = (char *)json_string_value(reason_val);
  2028. snprintf(reason, 31, " (%s)", reason_str);
  2029. }
  2030. }
  2031. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2032. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2033. sharelog(disposition, work);
  2034. }
  2035. /* Once we have more than a nominal amount of sequential rejects,
  2036. * at least 10 and more than 3 mins at the current utility,
  2037. * disable the pool because some pool error is likely to have
  2038. * ensued. Do not do this if we know the share just happened to
  2039. * be stale due to networking delays.
  2040. */
  2041. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2042. double utility = total_accepted / total_secs * 60;
  2043. if (pool->seq_rejects > utility * 3) {
  2044. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2045. pool->pool_no, pool->seq_rejects);
  2046. reject_pool(pool);
  2047. if (pool == current_pool())
  2048. switch_pools(NULL);
  2049. pool->seq_rejects = 0;
  2050. }
  2051. }
  2052. }
  2053. }
  2054. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2055. {
  2056. char *hexstr = NULL;
  2057. json_t *val, *res, *err;
  2058. char *s;
  2059. bool rc = false;
  2060. int thr_id = work->thr_id;
  2061. struct cgpu_info *cgpu;
  2062. struct pool *pool = work->pool;
  2063. int rolltime;
  2064. struct timeval tv_submit, tv_submit_reply;
  2065. char hashshow[64 + 4] = "";
  2066. char worktime[200] = "";
  2067. cgpu = get_thr_cgpu(thr_id);
  2068. endian_flip128(work->data, work->data);
  2069. /* build hex string */
  2070. hexstr = bin2hex(work->data, sizeof(work->data));
  2071. /* build JSON-RPC request */
  2072. if (work->gbt) {
  2073. char *gbt_block, *varint;
  2074. unsigned char data[80];
  2075. flip80(data, work->data);
  2076. gbt_block = bin2hex(data, 80);
  2077. if (work->gbt_txns < 0xfd) {
  2078. uint8_t val = work->gbt_txns;
  2079. varint = bin2hex((const unsigned char *)&val, 1);
  2080. } else if (work->gbt_txns <= 0xffff) {
  2081. uint16_t val = htole16(work->gbt_txns);
  2082. gbt_block = realloc_strcat(gbt_block, "fd");
  2083. varint = bin2hex((const unsigned char *)&val, 2);
  2084. } else {
  2085. uint32_t val = htole32(work->gbt_txns);
  2086. gbt_block = realloc_strcat(gbt_block, "fe");
  2087. varint = bin2hex((const unsigned char *)&val, 4);
  2088. }
  2089. gbt_block = realloc_strcat(gbt_block, varint);
  2090. free(varint);
  2091. gbt_block = realloc_strcat(gbt_block, work->gbt_coinbase);
  2092. s = strdup("{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"");
  2093. s = realloc_strcat(s, gbt_block);
  2094. if (work->job_id) {
  2095. s = realloc_strcat(s, "\", {\"workid\": \"");
  2096. s = realloc_strcat(s, work->job_id);
  2097. s = realloc_strcat(s, "\"}]}");
  2098. } else
  2099. s = realloc_strcat(s, "\", {}]}");
  2100. free(gbt_block);
  2101. } else {
  2102. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2103. s = realloc_strcat(s, hexstr);
  2104. s = realloc_strcat(s, "\" ], \"id\":1}");
  2105. }
  2106. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  2107. s = realloc_strcat(s, "\n");
  2108. cgtime(&tv_submit);
  2109. /* issue JSON-RPC request */
  2110. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2111. cgtime(&tv_submit_reply);
  2112. free(s);
  2113. if (unlikely(!val)) {
  2114. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2115. if (!pool_tset(pool, &pool->submit_fail)) {
  2116. total_ro++;
  2117. pool->remotefail_occasions++;
  2118. if (opt_lowmem) {
  2119. applog(LOG_WARNING, "Pool %d communication failure, discarding shares", pool->pool_no);
  2120. goto out;
  2121. }
  2122. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2123. }
  2124. nmsleep(5000);
  2125. goto out;
  2126. } else if (pool_tclear(pool, &pool->submit_fail))
  2127. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2128. res = json_object_get(val, "result");
  2129. err = json_object_get(val, "error");
  2130. if (!QUIET) {
  2131. int intdiff = floor(work->work_difficulty);
  2132. char diffdisp[16], *outhash;
  2133. unsigned char rhash[32];
  2134. swab256(rhash, work->hash);
  2135. if (opt_scrypt)
  2136. outhash = bin2hex(rhash + 2, 4);
  2137. else
  2138. outhash = bin2hex(rhash + 4, 4);
  2139. suffix_string(work->share_diff, diffdisp, 0);
  2140. sprintf(hashshow, "%s Diff %s/%d%s", outhash, diffdisp, intdiff,
  2141. work->block? " BLOCK!" : "");
  2142. free(outhash);
  2143. if (opt_worktime) {
  2144. char workclone[20];
  2145. struct tm *tm, tm_getwork, tm_submit_reply;
  2146. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2147. (struct timeval *)&(work->tv_getwork));
  2148. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2149. (struct timeval *)&(work->tv_getwork_reply));
  2150. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2151. (struct timeval *)&(work->tv_work_start));
  2152. double work_to_submit = tdiff(&tv_submit,
  2153. (struct timeval *)&(work->tv_work_found));
  2154. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  2155. int diffplaces = 3;
  2156. time_t tmp_time = work->tv_getwork.tv_sec;
  2157. tm = localtime(&tmp_time);
  2158. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2159. tmp_time = tv_submit_reply.tv_sec;
  2160. tm = localtime(&tmp_time);
  2161. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2162. if (work->clone) {
  2163. sprintf(workclone, "C:%1.3f",
  2164. tdiff((struct timeval *)&(work->tv_cloned),
  2165. (struct timeval *)&(work->tv_getwork_reply)));
  2166. }
  2167. else
  2168. strcpy(workclone, "O");
  2169. if (work->work_difficulty < 1)
  2170. diffplaces = 6;
  2171. sprintf(worktime, " <-%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",
  2172. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2173. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2174. work->getwork_mode, diffplaces, work->work_difficulty,
  2175. tm_getwork.tm_hour, tm_getwork.tm_min,
  2176. tm_getwork.tm_sec, getwork_time, workclone,
  2177. getwork_to_work, work_time, work_to_submit, submit_time,
  2178. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2179. tm_submit_reply.tm_sec);
  2180. }
  2181. }
  2182. share_result(val, res, err, work, hashshow, resubmit, worktime);
  2183. cgpu->utility = cgpu->accepted / total_secs * 60;
  2184. if (!opt_realquiet)
  2185. print_status(thr_id);
  2186. if (!want_per_device_stats) {
  2187. char logline[256];
  2188. get_statline(logline, cgpu);
  2189. applog(LOG_INFO, "%s", logline);
  2190. }
  2191. json_decref(val);
  2192. rc = true;
  2193. out:
  2194. free(hexstr);
  2195. return rc;
  2196. }
  2197. /* Specifies whether we can use this pool for work or not. */
  2198. static bool pool_unworkable(struct pool *pool)
  2199. {
  2200. if (pool->idle)
  2201. return true;
  2202. if (pool->enabled != POOL_ENABLED)
  2203. return true;
  2204. if (pool->has_stratum && !pool->stratum_active)
  2205. return true;
  2206. return false;
  2207. }
  2208. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2209. * rolling average per 10 minutes and if pools start getting more, it biases
  2210. * away from them to distribute work evenly. The share count is reset to the
  2211. * rolling average every 10 minutes to not send all work to one pool after it
  2212. * has been disabled/out for an extended period. */
  2213. static struct pool *select_balanced(struct pool *cp)
  2214. {
  2215. int i, lowest = cp->shares;
  2216. struct pool *ret = cp;
  2217. for (i = 0; i < total_pools; i++) {
  2218. struct pool *pool = pools[i];
  2219. if (pool_unworkable(pool))
  2220. continue;
  2221. if (pool->shares < lowest) {
  2222. lowest = pool->shares;
  2223. ret = pool;
  2224. }
  2225. }
  2226. ret->shares++;
  2227. return ret;
  2228. }
  2229. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2230. static inline struct pool *select_pool(bool lagging)
  2231. {
  2232. static int rotating_pool = 0;
  2233. struct pool *pool, *cp;
  2234. int tested;
  2235. cp = current_pool();
  2236. if (pool_strategy == POOL_BALANCE)
  2237. return select_balanced(cp);
  2238. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2239. pool = cp;
  2240. else
  2241. pool = NULL;
  2242. /* Try to find the first pool in the rotation that is usable */
  2243. tested = 0;
  2244. while (!pool && tested++ < total_pools) {
  2245. if (++rotating_pool >= total_pools)
  2246. rotating_pool = 0;
  2247. pool = pools[rotating_pool];
  2248. if (!pool_unworkable(pool))
  2249. break;
  2250. pool = NULL;
  2251. }
  2252. /* If still nothing is usable, use the current pool */
  2253. if (!pool)
  2254. pool = cp;
  2255. return pool;
  2256. }
  2257. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  2258. static const uint64_t diffone = 0xFFFF000000000000ull;
  2259. /*
  2260. * Calculate the work share difficulty
  2261. */
  2262. static void calc_diff(struct work *work, int known)
  2263. {
  2264. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2265. double difficulty;
  2266. if (opt_scrypt) {
  2267. uint64_t *data64, d64;
  2268. char rtarget[32];
  2269. swab256(rtarget, work->target);
  2270. data64 = (uint64_t *)(rtarget + 2);
  2271. d64 = be64toh(*data64);
  2272. if (unlikely(!d64))
  2273. d64 = 1;
  2274. work->work_difficulty = diffone / d64;
  2275. } else if (!known) {
  2276. double targ = 0;
  2277. int i;
  2278. for (i = 31; i >= 0; i--) {
  2279. targ *= 256;
  2280. targ += work->target[i];
  2281. }
  2282. work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
  2283. } else
  2284. work->work_difficulty = known;
  2285. difficulty = work->work_difficulty;
  2286. pool_stats->last_diff = difficulty;
  2287. suffix_string((uint64_t)difficulty, work->pool->diff, 0);
  2288. if (difficulty == pool_stats->min_diff)
  2289. pool_stats->min_diff_count++;
  2290. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2291. pool_stats->min_diff = difficulty;
  2292. pool_stats->min_diff_count = 1;
  2293. }
  2294. if (difficulty == pool_stats->max_diff)
  2295. pool_stats->max_diff_count++;
  2296. else if (difficulty > pool_stats->max_diff) {
  2297. pool_stats->max_diff = difficulty;
  2298. pool_stats->max_diff_count = 1;
  2299. }
  2300. }
  2301. static void get_benchmark_work(struct work *work)
  2302. {
  2303. // Use a random work block pulled from a pool
  2304. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2305. size_t bench_size = sizeof(*work);
  2306. size_t work_size = sizeof(bench_block);
  2307. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2308. memset(work, 0, sizeof(*work));
  2309. memcpy(work, &bench_block, min_size);
  2310. work->mandatory = true;
  2311. work->pool = pools[0];
  2312. cgtime(&work->tv_getwork);
  2313. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  2314. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2315. calc_diff(work, 0);
  2316. }
  2317. static bool get_upstream_work(struct work *work, CURL *curl)
  2318. {
  2319. struct pool *pool = work->pool;
  2320. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2321. struct timeval tv_elapsed;
  2322. json_t *val = NULL;
  2323. bool rc = false;
  2324. char *url;
  2325. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, pool->rpc_req);
  2326. url = pool->rpc_url;
  2327. cgtime(&work->tv_getwork);
  2328. val = json_rpc_call(curl, url, pool->rpc_userpass, pool->rpc_req, false,
  2329. false, &work->rolltime, pool, false);
  2330. pool_stats->getwork_attempts++;
  2331. if (likely(val)) {
  2332. rc = work_decode(pool, work, val);
  2333. if (unlikely(!rc))
  2334. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2335. } else
  2336. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2337. cgtime(&work->tv_getwork_reply);
  2338. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2339. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2340. pool_stats->getwork_wait_rolling /= 1.63;
  2341. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2342. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2343. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2344. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2345. }
  2346. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2347. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2348. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2349. }
  2350. pool_stats->getwork_calls++;
  2351. work->pool = pool;
  2352. work->longpoll = false;
  2353. work->getwork_mode = GETWORK_MODE_POOL;
  2354. calc_diff(work, 0);
  2355. total_getworks++;
  2356. pool->getwork_requested++;
  2357. if (likely(val))
  2358. json_decref(val);
  2359. return rc;
  2360. }
  2361. #ifdef HAVE_CURSES
  2362. static void disable_curses(void)
  2363. {
  2364. if (curses_active_locked()) {
  2365. use_curses = false;
  2366. curses_active = false;
  2367. leaveok(logwin, false);
  2368. leaveok(statuswin, false);
  2369. leaveok(mainwin, false);
  2370. nocbreak();
  2371. echo();
  2372. delwin(logwin);
  2373. delwin(statuswin);
  2374. delwin(mainwin);
  2375. endwin();
  2376. #ifdef WIN32
  2377. // Move the cursor to after curses output.
  2378. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2379. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2380. COORD coord;
  2381. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2382. coord.X = 0;
  2383. coord.Y = csbi.dwSize.Y - 1;
  2384. SetConsoleCursorPosition(hout, coord);
  2385. }
  2386. #endif
  2387. unlock_curses();
  2388. }
  2389. }
  2390. #endif
  2391. static void __kill_work(void)
  2392. {
  2393. struct thr_info *thr;
  2394. int i;
  2395. if (!successful_connect)
  2396. return;
  2397. applog(LOG_INFO, "Received kill message");
  2398. #ifdef USE_USBUTILS
  2399. /* Best to get rid of it first so it doesn't
  2400. * try to create any new devices */
  2401. if (!opt_scrypt) {
  2402. applog(LOG_DEBUG, "Killing off HotPlug thread");
  2403. thr = &control_thr[hotplug_thr_id];
  2404. thr_info_cancel(thr);
  2405. }
  2406. #endif
  2407. applog(LOG_DEBUG, "Killing off watchpool thread");
  2408. /* Kill the watchpool thread */
  2409. thr = &control_thr[watchpool_thr_id];
  2410. thr_info_cancel(thr);
  2411. applog(LOG_DEBUG, "Killing off watchdog thread");
  2412. /* Kill the watchdog thread */
  2413. thr = &control_thr[watchdog_thr_id];
  2414. thr_info_cancel(thr);
  2415. applog(LOG_DEBUG, "Shutting down mining threads");
  2416. for (i = 0; i < mining_threads; i++) {
  2417. struct cgpu_info *cgpu;
  2418. thr = get_thread(i);
  2419. if (!thr)
  2420. continue;
  2421. cgpu = thr->cgpu;
  2422. if (!cgpu)
  2423. continue;
  2424. cgpu->shutdown = true;
  2425. }
  2426. sleep(1);
  2427. applog(LOG_DEBUG, "Killing off mining threads");
  2428. /* Kill the mining threads*/
  2429. for (i = 0; i < mining_threads; i++) {
  2430. pthread_t *pth = NULL;
  2431. thr = get_thread(i);
  2432. if (thr && PTH(thr) != 0L)
  2433. pth = &thr->pth;
  2434. thr_info_cancel(thr);
  2435. #ifndef WIN32
  2436. if (pth && *pth)
  2437. pthread_join(*pth, NULL);
  2438. #else
  2439. if (pth && pth->p)
  2440. pthread_join(*pth, NULL);
  2441. #endif
  2442. }
  2443. applog(LOG_DEBUG, "Killing off stage thread");
  2444. /* Stop the others */
  2445. thr = &control_thr[stage_thr_id];
  2446. thr_info_cancel(thr);
  2447. applog(LOG_DEBUG, "Killing off API thread");
  2448. thr = &control_thr[api_thr_id];
  2449. thr_info_cancel(thr);
  2450. #ifdef USE_USBUTILS
  2451. /* Release USB resources in case it's a restart
  2452. * and not a QUIT */
  2453. if (!opt_scrypt) {
  2454. applog(LOG_DEBUG, "Releasing all USB devices");
  2455. usb_cleanup();
  2456. applog(LOG_DEBUG, "Killing off usbres thread");
  2457. thr = &control_thr[usbres_thr_id];
  2458. thr_info_cancel(thr);
  2459. }
  2460. #endif
  2461. }
  2462. /* This should be the common exit path */
  2463. void kill_work(void)
  2464. {
  2465. __kill_work();
  2466. quit(0, "Shutdown signal received.");
  2467. }
  2468. static
  2469. #ifdef WIN32
  2470. const
  2471. #endif
  2472. char **initial_args;
  2473. static void clean_up(void);
  2474. void app_restart(void)
  2475. {
  2476. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2477. __kill_work();
  2478. clean_up();
  2479. #if defined(unix)
  2480. if (forkpid > 0) {
  2481. kill(forkpid, SIGTERM);
  2482. forkpid = 0;
  2483. }
  2484. #endif
  2485. execv(initial_args[0], (EXECV_2ND_ARG_TYPE)initial_args);
  2486. applog(LOG_WARNING, "Failed to restart application");
  2487. }
  2488. static void sighandler(int __maybe_unused sig)
  2489. {
  2490. /* Restore signal handlers so we can still quit if kill_work fails */
  2491. sigaction(SIGTERM, &termhandler, NULL);
  2492. sigaction(SIGINT, &inthandler, NULL);
  2493. kill_work();
  2494. }
  2495. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2496. * this pool. */
  2497. static void recruit_curl(struct pool *pool)
  2498. {
  2499. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2500. if (unlikely(!ce))
  2501. quit(1, "Failed to calloc in recruit_curl");
  2502. ce->curl = curl_easy_init();
  2503. if (unlikely(!ce->curl))
  2504. quit(1, "Failed to init in recruit_curl");
  2505. list_add(&ce->node, &pool->curlring);
  2506. pool->curls++;
  2507. }
  2508. /* Grab an available curl if there is one. If not, then recruit extra curls
  2509. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2510. * and there are already 5 curls in circulation. Limit total number to the
  2511. * number of mining threads per pool as well to prevent blasting a pool during
  2512. * network delays/outages. */
  2513. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2514. {
  2515. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2516. bool recruited = false;
  2517. struct curl_ent *ce;
  2518. mutex_lock(&pool->pool_lock);
  2519. retry:
  2520. if (!pool->curls) {
  2521. recruit_curl(pool);
  2522. recruited = true;
  2523. } else if (list_empty(&pool->curlring)) {
  2524. if (pool->curls >= curl_limit) {
  2525. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2526. goto retry;
  2527. } else {
  2528. recruit_curl(pool);
  2529. recruited = true;
  2530. }
  2531. }
  2532. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2533. list_del(&ce->node);
  2534. mutex_unlock(&pool->pool_lock);
  2535. if (recruited)
  2536. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  2537. return ce;
  2538. }
  2539. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2540. {
  2541. mutex_lock(&pool->pool_lock);
  2542. list_add_tail(&ce->node, &pool->curlring);
  2543. cgtime(&ce->tv);
  2544. pthread_cond_broadcast(&pool->cr_cond);
  2545. mutex_unlock(&pool->pool_lock);
  2546. }
  2547. static bool stale_work(struct work *work, bool share);
  2548. static inline bool should_roll(struct work *work)
  2549. {
  2550. struct timeval now;
  2551. time_t expiry;
  2552. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  2553. return false;
  2554. if (work->rolltime > opt_scantime)
  2555. expiry = work->rolltime;
  2556. else
  2557. expiry = opt_scantime;
  2558. expiry = expiry * 2 / 3;
  2559. /* We shouldn't roll if we're unlikely to get one shares' duration
  2560. * work out of doing so */
  2561. cgtime(&now);
  2562. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  2563. return false;
  2564. return true;
  2565. }
  2566. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  2567. * reject blocks as invalid. */
  2568. static inline bool can_roll(struct work *work)
  2569. {
  2570. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  2571. work->rolls < 7000 && !stale_work(work, false));
  2572. }
  2573. static void roll_work(struct work *work)
  2574. {
  2575. uint32_t *work_ntime;
  2576. uint32_t ntime;
  2577. work_ntime = (uint32_t *)(work->data + 68);
  2578. ntime = be32toh(*work_ntime);
  2579. ntime++;
  2580. *work_ntime = htobe32(ntime);
  2581. local_work++;
  2582. work->rolls++;
  2583. work->blk.nonce = 0;
  2584. applog(LOG_DEBUG, "Successfully rolled work");
  2585. /* This is now a different work item so it needs a different ID for the
  2586. * hashtable */
  2587. work->id = total_work++;
  2588. }
  2589. /* Duplicates any dynamically allocated arrays within the work struct to
  2590. * prevent a copied work struct from freeing ram belonging to another struct */
  2591. void __copy_work(struct work *work, struct work *base_work)
  2592. {
  2593. int id = work->id;
  2594. clean_work(work);
  2595. memcpy(work, base_work, sizeof(struct work));
  2596. /* Keep the unique new id assigned during make_work to prevent copied
  2597. * work from having the same id. */
  2598. work->id = id;
  2599. if (base_work->job_id)
  2600. work->job_id = strdup(base_work->job_id);
  2601. if (base_work->nonce1)
  2602. work->nonce1 = strdup(base_work->nonce1);
  2603. if (base_work->nonce2)
  2604. work->nonce2 = strdup(base_work->nonce2);
  2605. if (base_work->ntime)
  2606. work->ntime = strdup(base_work->ntime);
  2607. if (base_work->gbt_coinbase)
  2608. work->gbt_coinbase = strdup(base_work->gbt_coinbase);
  2609. }
  2610. /* Generates a copy of an existing work struct, creating fresh heap allocations
  2611. * for all dynamically allocated arrays within the struct */
  2612. struct work *copy_work(struct work *base_work)
  2613. {
  2614. struct work *work = make_work();
  2615. __copy_work(work, base_work);
  2616. return work;
  2617. }
  2618. static struct work *make_clone(struct work *work)
  2619. {
  2620. struct work *work_clone = copy_work(work);
  2621. work_clone->clone = true;
  2622. cgtime((struct timeval *)&(work_clone->tv_cloned));
  2623. work_clone->longpoll = false;
  2624. work_clone->mandatory = false;
  2625. /* Make cloned work appear slightly older to bias towards keeping the
  2626. * master work item which can be further rolled */
  2627. work_clone->tv_staged.tv_sec -= 1;
  2628. return work_clone;
  2629. }
  2630. static void stage_work(struct work *work);
  2631. static bool clone_available(void)
  2632. {
  2633. struct work *work_clone = NULL, *work, *tmp;
  2634. bool cloned = false;
  2635. mutex_lock(stgd_lock);
  2636. if (!staged_rollable)
  2637. goto out_unlock;
  2638. HASH_ITER(hh, staged_work, work, tmp) {
  2639. if (can_roll(work) && should_roll(work)) {
  2640. roll_work(work);
  2641. work_clone = make_clone(work);
  2642. roll_work(work);
  2643. cloned = true;
  2644. break;
  2645. }
  2646. }
  2647. out_unlock:
  2648. mutex_unlock(stgd_lock);
  2649. if (cloned) {
  2650. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2651. stage_work(work_clone);
  2652. }
  2653. return cloned;
  2654. }
  2655. static void pool_died(struct pool *pool)
  2656. {
  2657. if (!pool_tset(pool, &pool->idle)) {
  2658. cgtime(&pool->tv_idle);
  2659. if (pool == current_pool()) {
  2660. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2661. switch_pools(NULL);
  2662. } else
  2663. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  2664. }
  2665. }
  2666. static bool stale_work(struct work *work, bool share)
  2667. {
  2668. struct timeval now;
  2669. time_t work_expiry;
  2670. struct pool *pool;
  2671. int getwork_delay;
  2672. if (opt_benchmark)
  2673. return false;
  2674. if (work->work_block != work_block) {
  2675. applog(LOG_DEBUG, "Work stale due to block mismatch");
  2676. return true;
  2677. }
  2678. /* Technically the rolltime should be correct but some pools
  2679. * advertise a broken expire= that is lower than a meaningful
  2680. * scantime */
  2681. if (work->rolltime > opt_scantime)
  2682. work_expiry = work->rolltime;
  2683. else
  2684. work_expiry = opt_expiry;
  2685. pool = work->pool;
  2686. if (!share && pool->has_stratum) {
  2687. bool same_job;
  2688. if (!pool->stratum_active || !pool->stratum_notify) {
  2689. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  2690. return true;
  2691. }
  2692. same_job = true;
  2693. cg_rlock(&pool->data_lock);
  2694. if (strcmp(work->job_id, pool->swork.job_id))
  2695. same_job = false;
  2696. cg_runlock(&pool->data_lock);
  2697. if (!same_job) {
  2698. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  2699. return true;
  2700. }
  2701. }
  2702. /* Factor in the average getwork delay of this pool, rounding it up to
  2703. * the nearest second */
  2704. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2705. work_expiry -= getwork_delay;
  2706. if (unlikely(work_expiry < 5))
  2707. work_expiry = 5;
  2708. cgtime(&now);
  2709. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2710. applog(LOG_DEBUG, "Work stale due to expiry");
  2711. return true;
  2712. }
  2713. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2714. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2715. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  2716. return true;
  2717. }
  2718. return false;
  2719. }
  2720. static uint64_t share_diff(const struct work *work)
  2721. {
  2722. uint64_t *data64, d64, ret;
  2723. bool new_best = false;
  2724. char rhash[32];
  2725. swab256(rhash, work->hash);
  2726. if (opt_scrypt)
  2727. data64 = (uint64_t *)(rhash + 2);
  2728. else
  2729. data64 = (uint64_t *)(rhash + 4);
  2730. d64 = be64toh(*data64);
  2731. if (unlikely(!d64))
  2732. d64 = 1;
  2733. ret = diffone / d64;
  2734. cg_wlock(&control_lock);
  2735. if (unlikely(ret > best_diff)) {
  2736. new_best = true;
  2737. best_diff = ret;
  2738. suffix_string(best_diff, best_share, 0);
  2739. }
  2740. if (unlikely(ret > work->pool->best_diff))
  2741. work->pool->best_diff = ret;
  2742. cg_wunlock(&control_lock);
  2743. if (unlikely(new_best))
  2744. applog(LOG_INFO, "New best share: %s", best_share);
  2745. return ret;
  2746. }
  2747. static void regen_hash(struct work *work)
  2748. {
  2749. uint32_t *data32 = (uint32_t *)(work->data);
  2750. unsigned char swap[80];
  2751. uint32_t *swap32 = (uint32_t *)swap;
  2752. unsigned char hash1[32];
  2753. flip80(swap32, data32);
  2754. sha2(swap, 80, hash1);
  2755. sha2(hash1, 32, (unsigned char *)(work->hash));
  2756. }
  2757. static void rebuild_hash(struct work *work)
  2758. {
  2759. if (opt_scrypt)
  2760. scrypt_regenhash(work);
  2761. else
  2762. regen_hash(work);
  2763. work->share_diff = share_diff(work);
  2764. if (unlikely(work->share_diff >= current_diff)) {
  2765. work->block = true;
  2766. work->pool->solved++;
  2767. found_blocks++;
  2768. work->mandatory = true;
  2769. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  2770. }
  2771. }
  2772. static bool cnx_needed(struct pool *pool);
  2773. static void *submit_work_thread(void *userdata)
  2774. {
  2775. struct work *work = (struct work *)userdata;
  2776. struct pool *pool = work->pool;
  2777. bool resubmit = false;
  2778. struct curl_ent *ce;
  2779. pthread_detach(pthread_self());
  2780. RenameThread("submit_work");
  2781. applog(LOG_DEBUG, "Creating extra submit work thread");
  2782. ce = pop_curl_entry(pool);
  2783. /* submit solution to bitcoin via JSON-RPC */
  2784. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2785. if (opt_lowmem) {
  2786. applog(LOG_NOTICE, "Pool %d share being discarded to minimise memory cache", pool->pool_no);
  2787. break;
  2788. }
  2789. resubmit = true;
  2790. if (stale_work(work, true)) {
  2791. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  2792. mutex_lock(&stats_lock);
  2793. total_stale++;
  2794. pool->stale_shares++;
  2795. total_diff_stale += work->work_difficulty;
  2796. pool->diff_stale += work->work_difficulty;
  2797. mutex_unlock(&stats_lock);
  2798. free_work(work);
  2799. break;
  2800. }
  2801. /* pause, then restart work-request loop */
  2802. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2803. }
  2804. push_curl_entry(ce, pool);
  2805. return NULL;
  2806. }
  2807. /* Find the pool that currently has the highest priority */
  2808. static struct pool *priority_pool(int choice)
  2809. {
  2810. struct pool *ret = NULL;
  2811. int i;
  2812. for (i = 0; i < total_pools; i++) {
  2813. struct pool *pool = pools[i];
  2814. if (pool->prio == choice) {
  2815. ret = pool;
  2816. break;
  2817. }
  2818. }
  2819. if (unlikely(!ret)) {
  2820. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2821. return pools[choice];
  2822. }
  2823. return ret;
  2824. }
  2825. static void clear_pool_work(struct pool *pool);
  2826. /* Specifies whether we can switch to this pool or not. */
  2827. static bool pool_unusable(struct pool *pool)
  2828. {
  2829. if (pool->idle)
  2830. return true;
  2831. if (pool->enabled != POOL_ENABLED)
  2832. return true;
  2833. return false;
  2834. }
  2835. void switch_pools(struct pool *selected)
  2836. {
  2837. struct pool *pool, *last_pool;
  2838. int i, pool_no, next_pool;
  2839. cg_wlock(&control_lock);
  2840. last_pool = currentpool;
  2841. pool_no = currentpool->pool_no;
  2842. /* Switch selected to pool number 0 and move the rest down */
  2843. if (selected) {
  2844. if (selected->prio != 0) {
  2845. for (i = 0; i < total_pools; i++) {
  2846. pool = pools[i];
  2847. if (pool->prio < selected->prio)
  2848. pool->prio++;
  2849. }
  2850. selected->prio = 0;
  2851. }
  2852. }
  2853. switch (pool_strategy) {
  2854. /* Both of these set to the master pool */
  2855. case POOL_BALANCE:
  2856. case POOL_FAILOVER:
  2857. case POOL_LOADBALANCE:
  2858. for (i = 0; i < total_pools; i++) {
  2859. pool = priority_pool(i);
  2860. if (pool_unusable(pool))
  2861. continue;
  2862. pool_no = pool->pool_no;
  2863. break;
  2864. }
  2865. break;
  2866. /* Both of these simply increment and cycle */
  2867. case POOL_ROUNDROBIN:
  2868. case POOL_ROTATE:
  2869. if (selected && !selected->idle) {
  2870. pool_no = selected->pool_no;
  2871. break;
  2872. }
  2873. next_pool = pool_no;
  2874. /* Select the next alive pool */
  2875. for (i = 1; i < total_pools; i++) {
  2876. next_pool++;
  2877. if (next_pool >= total_pools)
  2878. next_pool = 0;
  2879. pool = pools[next_pool];
  2880. if (pool_unusable(pool))
  2881. continue;
  2882. pool_no = next_pool;
  2883. break;
  2884. }
  2885. break;
  2886. default:
  2887. break;
  2888. }
  2889. currentpool = pools[pool_no];
  2890. pool = currentpool;
  2891. cg_wunlock(&control_lock);
  2892. /* Set the lagging flag to avoid pool not providing work fast enough
  2893. * messages in failover only mode since we have to get all fresh work
  2894. * as in restart_threads */
  2895. if (opt_fail_only)
  2896. pool_tset(pool, &pool->lagging);
  2897. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2898. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  2899. if (pool->has_gbt || pool->has_stratum || opt_fail_only)
  2900. clear_pool_work(last_pool);
  2901. }
  2902. mutex_lock(&lp_lock);
  2903. pthread_cond_broadcast(&lp_cond);
  2904. mutex_unlock(&lp_lock);
  2905. }
  2906. void discard_work(struct work *work)
  2907. {
  2908. if (!work->clone && !work->rolls && !work->mined) {
  2909. if (work->pool)
  2910. work->pool->discarded_work++;
  2911. total_discarded++;
  2912. applog(LOG_DEBUG, "Discarded work");
  2913. } else
  2914. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2915. free_work(work);
  2916. }
  2917. static void wake_gws(void)
  2918. {
  2919. mutex_lock(stgd_lock);
  2920. pthread_cond_signal(&gws_cond);
  2921. mutex_unlock(stgd_lock);
  2922. }
  2923. static void discard_stale(void)
  2924. {
  2925. struct work *work, *tmp;
  2926. int stale = 0;
  2927. mutex_lock(stgd_lock);
  2928. HASH_ITER(hh, staged_work, work, tmp) {
  2929. if (stale_work(work, false)) {
  2930. HASH_DEL(staged_work, work);
  2931. discard_work(work);
  2932. stale++;
  2933. }
  2934. }
  2935. pthread_cond_signal(&gws_cond);
  2936. mutex_unlock(stgd_lock);
  2937. if (stale)
  2938. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2939. }
  2940. /* A generic wait function for threads that poll that will wait a specified
  2941. * time tdiff waiting on the pthread conditional that is broadcast when a
  2942. * work restart is required. Returns the value of pthread_cond_timedwait
  2943. * which is zero if the condition was met or ETIMEDOUT if not.
  2944. */
  2945. int restart_wait(unsigned int mstime)
  2946. {
  2947. struct timeval now, then, tdiff;
  2948. struct timespec abstime;
  2949. int rc;
  2950. tdiff.tv_sec = mstime / 1000;
  2951. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  2952. cgtime(&now);
  2953. timeradd(&now, &tdiff, &then);
  2954. abstime.tv_sec = then.tv_sec;
  2955. abstime.tv_nsec = then.tv_usec * 1000;
  2956. mutex_lock(&restart_lock);
  2957. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  2958. mutex_unlock(&restart_lock);
  2959. return rc;
  2960. }
  2961. static void restart_threads(void)
  2962. {
  2963. struct pool *cp = current_pool();
  2964. int i;
  2965. /* Artificially set the lagging flag to avoid pool not providing work
  2966. * fast enough messages after every long poll */
  2967. pool_tset(cp, &cp->lagging);
  2968. /* Discard staged work that is now stale */
  2969. discard_stale();
  2970. rd_lock(&mining_thr_lock);
  2971. for (i = 0; i < mining_threads; i++)
  2972. mining_thr[i]->work_restart = true;
  2973. rd_unlock(&mining_thr_lock);
  2974. mutex_lock(&restart_lock);
  2975. pthread_cond_broadcast(&restart_cond);
  2976. mutex_unlock(&restart_lock);
  2977. }
  2978. static void set_curblock(char *hexstr, unsigned char *hash)
  2979. {
  2980. unsigned char hash_swap[32];
  2981. unsigned char block_hash_swap[32];
  2982. strcpy(current_block, hexstr);
  2983. swap256(hash_swap, hash);
  2984. swap256(block_hash_swap, hash + 4);
  2985. cg_wlock(&ch_lock);
  2986. cgtime(&block_timeval);
  2987. free(current_hash);
  2988. current_hash = bin2hex(hash_swap + 2, 8);
  2989. free(current_fullhash);
  2990. current_fullhash = bin2hex(block_hash_swap, 32);
  2991. get_timestamp(blocktime, &block_timeval);
  2992. cg_wunlock(&ch_lock);
  2993. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  2994. }
  2995. /* Search to see if this string is from a block that has been seen before */
  2996. static bool block_exists(char *hexstr)
  2997. {
  2998. struct block *s;
  2999. rd_lock(&blk_lock);
  3000. HASH_FIND_STR(blocks, hexstr, s);
  3001. rd_unlock(&blk_lock);
  3002. if (s)
  3003. return true;
  3004. return false;
  3005. }
  3006. /* Tests if this work is from a block that has been seen before */
  3007. static inline bool from_existing_block(struct work *work)
  3008. {
  3009. char *hexstr = bin2hex(work->data + 8, 18);
  3010. bool ret;
  3011. ret = block_exists(hexstr);
  3012. free(hexstr);
  3013. return ret;
  3014. }
  3015. static int block_sort(struct block *blocka, struct block *blockb)
  3016. {
  3017. return blocka->block_no - blockb->block_no;
  3018. }
  3019. static void set_blockdiff(const struct work *work)
  3020. {
  3021. uint64_t *data64, d64, diff64;
  3022. double previous_diff;
  3023. uint32_t diffhash[8];
  3024. uint32_t difficulty;
  3025. uint32_t diffbytes;
  3026. uint32_t diffvalue;
  3027. char rhash[32];
  3028. int diffshift;
  3029. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  3030. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  3031. diffvalue = difficulty & 0x00ffffff;
  3032. diffshift = (diffbytes % 4) * 8;
  3033. if (diffshift == 0) {
  3034. diffshift = 32;
  3035. diffbytes--;
  3036. }
  3037. memset(diffhash, 0, 32);
  3038. diffbytes >>= 2;
  3039. if (unlikely(diffbytes > 6))
  3040. return;
  3041. diffhash[diffbytes + 1] = diffvalue >> (32 - diffshift);
  3042. diffhash[diffbytes] = diffvalue << diffshift;
  3043. swab256(rhash, diffhash);
  3044. if (opt_scrypt)
  3045. data64 = (uint64_t *)(rhash + 2);
  3046. else
  3047. data64 = (uint64_t *)(rhash + 4);
  3048. d64 = be64toh(*data64);
  3049. if (unlikely(!d64))
  3050. d64 = 1;
  3051. previous_diff = current_diff;
  3052. diff64 = diffone / d64;
  3053. suffix_string(diff64, block_diff, 0);
  3054. current_diff = (double)diffone / (double)d64;
  3055. if (unlikely(current_diff != previous_diff))
  3056. applog(LOG_NOTICE, "Network diff set to %s", block_diff);
  3057. }
  3058. static bool test_work_current(struct work *work)
  3059. {
  3060. bool ret = true;
  3061. char *hexstr;
  3062. if (work->mandatory)
  3063. return ret;
  3064. /* Hack to work around dud work sneaking into test */
  3065. hexstr = bin2hex(work->data + 8, 18);
  3066. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  3067. goto out_free;
  3068. /* Search to see if this block exists yet and if not, consider it a
  3069. * new block and set the current block details to this one */
  3070. if (!block_exists(hexstr)) {
  3071. struct block *s = calloc(sizeof(struct block), 1);
  3072. int deleted_block = 0;
  3073. ret = false;
  3074. if (unlikely(!s))
  3075. quit (1, "test_work_current OOM");
  3076. strcpy(s->hash, hexstr);
  3077. s->block_no = new_blocks++;
  3078. wr_lock(&blk_lock);
  3079. /* Only keep the last hour's worth of blocks in memory since
  3080. * work from blocks before this is virtually impossible and we
  3081. * want to prevent memory usage from continually rising */
  3082. if (HASH_COUNT(blocks) > 6) {
  3083. struct block *oldblock;
  3084. HASH_SORT(blocks, block_sort);
  3085. oldblock = blocks;
  3086. deleted_block = oldblock->block_no;
  3087. HASH_DEL(blocks, oldblock);
  3088. free(oldblock);
  3089. }
  3090. HASH_ADD_STR(blocks, hash, s);
  3091. set_blockdiff(work);
  3092. wr_unlock(&blk_lock);
  3093. if (deleted_block)
  3094. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3095. set_curblock(hexstr, work->data);
  3096. if (unlikely(new_blocks == 1))
  3097. goto out_free;
  3098. work->work_block = ++work_block;
  3099. if (!work->stratum) {
  3100. if (work->longpoll) {
  3101. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
  3102. work->gbt ? "GBT " : "", work->pool->pool_no);
  3103. } else if (have_longpoll)
  3104. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3105. else
  3106. applog(LOG_NOTICE, "New block detected on network");
  3107. }
  3108. restart_threads();
  3109. } else if (work->longpoll) {
  3110. work->work_block = ++work_block;
  3111. if (work->pool == current_pool()) {
  3112. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  3113. work->gbt ? "GBT " : "", work->pool->pool_no);
  3114. restart_threads();
  3115. }
  3116. }
  3117. work->longpoll = false;
  3118. out_free:
  3119. free(hexstr);
  3120. return ret;
  3121. }
  3122. static int tv_sort(struct work *worka, struct work *workb)
  3123. {
  3124. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3125. }
  3126. static bool work_rollable(struct work *work)
  3127. {
  3128. return (!work->clone && work->rolltime);
  3129. }
  3130. static bool hash_push(struct work *work)
  3131. {
  3132. bool rc = true;
  3133. mutex_lock(stgd_lock);
  3134. if (work_rollable(work))
  3135. staged_rollable++;
  3136. if (likely(!getq->frozen)) {
  3137. HASH_ADD_INT(staged_work, id, work);
  3138. HASH_SORT(staged_work, tv_sort);
  3139. } else
  3140. rc = false;
  3141. pthread_cond_broadcast(&getq->cond);
  3142. mutex_unlock(stgd_lock);
  3143. return rc;
  3144. }
  3145. static void *stage_thread(void *userdata)
  3146. {
  3147. struct thr_info *mythr = userdata;
  3148. bool ok = true;
  3149. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3150. RenameThread("stage");
  3151. while (ok) {
  3152. struct work *work = NULL;
  3153. applog(LOG_DEBUG, "Popping work to stage thread");
  3154. work = tq_pop(mythr->q, NULL);
  3155. if (unlikely(!work)) {
  3156. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3157. ok = false;
  3158. break;
  3159. }
  3160. work->work_block = work_block;
  3161. test_work_current(work);
  3162. applog(LOG_DEBUG, "Pushing work to getwork queue");
  3163. if (unlikely(!hash_push(work))) {
  3164. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3165. continue;
  3166. }
  3167. }
  3168. tq_freeze(mythr->q);
  3169. return NULL;
  3170. }
  3171. static void stage_work(struct work *work)
  3172. {
  3173. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  3174. work->work_block = work_block;
  3175. test_work_current(work);
  3176. hash_push(work);
  3177. }
  3178. #ifdef HAVE_CURSES
  3179. int curses_int(const char *query)
  3180. {
  3181. int ret;
  3182. char *cvar;
  3183. cvar = curses_input(query);
  3184. ret = atoi(cvar);
  3185. free(cvar);
  3186. return ret;
  3187. }
  3188. #endif
  3189. #ifdef HAVE_CURSES
  3190. static bool input_pool(bool live);
  3191. #endif
  3192. #ifdef HAVE_CURSES
  3193. static void display_pool_summary(struct pool *pool)
  3194. {
  3195. double efficiency = 0.0;
  3196. if (curses_active_locked()) {
  3197. wlog("Pool: %s\n", pool->rpc_url);
  3198. if (pool->solved)
  3199. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3200. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  3201. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3202. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3203. wlog(" Accepted shares: %d\n", pool->accepted);
  3204. wlog(" Rejected shares: %d\n", pool->rejected);
  3205. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  3206. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  3207. if (pool->accepted || pool->rejected)
  3208. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3209. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3210. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3211. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3212. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3213. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3214. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3215. unlock_curses();
  3216. }
  3217. }
  3218. #endif
  3219. /* We can't remove the memory used for this struct pool because there may
  3220. * still be work referencing it. We just remove it from the pools list */
  3221. void remove_pool(struct pool *pool)
  3222. {
  3223. int i, last_pool = total_pools - 1;
  3224. struct pool *other;
  3225. /* Boost priority of any lower prio than this one */
  3226. for (i = 0; i < total_pools; i++) {
  3227. other = pools[i];
  3228. if (other->prio > pool->prio)
  3229. other->prio--;
  3230. }
  3231. if (pool->pool_no < last_pool) {
  3232. /* Swap the last pool for this one */
  3233. (pools[last_pool])->pool_no = pool->pool_no;
  3234. pools[pool->pool_no] = pools[last_pool];
  3235. }
  3236. /* Give it an invalid number */
  3237. pool->pool_no = total_pools;
  3238. pool->removed = true;
  3239. total_pools--;
  3240. }
  3241. /* add a mutex if this needs to be thread safe in the future */
  3242. static struct JE {
  3243. char *buf;
  3244. struct JE *next;
  3245. } *jedata = NULL;
  3246. static void json_escape_free()
  3247. {
  3248. struct JE *jeptr = jedata;
  3249. struct JE *jenext;
  3250. jedata = NULL;
  3251. while (jeptr) {
  3252. jenext = jeptr->next;
  3253. free(jeptr->buf);
  3254. free(jeptr);
  3255. jeptr = jenext;
  3256. }
  3257. }
  3258. static char *json_escape(char *str)
  3259. {
  3260. struct JE *jeptr;
  3261. char *buf, *ptr;
  3262. /* 2x is the max, may as well just allocate that */
  3263. ptr = buf = malloc(strlen(str) * 2 + 1);
  3264. jeptr = malloc(sizeof(*jeptr));
  3265. jeptr->buf = buf;
  3266. jeptr->next = jedata;
  3267. jedata = jeptr;
  3268. while (*str) {
  3269. if (*str == '\\' || *str == '"')
  3270. *(ptr++) = '\\';
  3271. *(ptr++) = *(str++);
  3272. }
  3273. *ptr = '\0';
  3274. return buf;
  3275. }
  3276. void write_config(FILE *fcfg)
  3277. {
  3278. int i;
  3279. /* Write pool values */
  3280. fputs("{\n\"pools\" : [", fcfg);
  3281. for(i = 0; i < total_pools; i++) {
  3282. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  3283. pools[i]->rpc_proxy ? json_escape((char *)proxytype(pools[i]->rpc_proxytype)) : "",
  3284. pools[i]->rpc_proxy ? json_escape(pools[i]->rpc_proxy) : "",
  3285. pools[i]->rpc_proxy ? "|" : "",
  3286. json_escape(pools[i]->rpc_url));
  3287. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3288. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  3289. }
  3290. fputs("\n]\n", fcfg);
  3291. #ifdef HAVE_OPENCL
  3292. if (nDevs) {
  3293. /* Write GPU device values */
  3294. fputs(",\n\"intensity\" : \"", fcfg);
  3295. for(i = 0; i < nDevs; i++)
  3296. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3297. fputs("\",\n\"vectors\" : \"", fcfg);
  3298. for(i = 0; i < nDevs; i++)
  3299. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3300. gpus[i].vwidth);
  3301. fputs("\",\n\"worksize\" : \"", fcfg);
  3302. for(i = 0; i < nDevs; i++)
  3303. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3304. (int)gpus[i].work_size);
  3305. fputs("\",\n\"kernel\" : \"", fcfg);
  3306. for(i = 0; i < nDevs; i++) {
  3307. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3308. switch (gpus[i].kernel) {
  3309. case KL_NONE: // Shouldn't happen
  3310. break;
  3311. case KL_POCLBM:
  3312. fprintf(fcfg, "poclbm");
  3313. break;
  3314. case KL_PHATK:
  3315. fprintf(fcfg, "phatk");
  3316. break;
  3317. case KL_DIAKGCN:
  3318. fprintf(fcfg, "diakgcn");
  3319. break;
  3320. case KL_DIABLO:
  3321. fprintf(fcfg, "diablo");
  3322. break;
  3323. case KL_SCRYPT:
  3324. fprintf(fcfg, "scrypt");
  3325. break;
  3326. }
  3327. }
  3328. #ifdef USE_SCRYPT
  3329. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3330. for(i = 0; i < nDevs; i++)
  3331. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3332. (int)gpus[i].opt_lg);
  3333. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3334. for(i = 0; i < nDevs; i++)
  3335. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3336. (int)gpus[i].opt_tc);
  3337. fputs("\",\n\"shaders\" : \"", fcfg);
  3338. for(i = 0; i < nDevs; i++)
  3339. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3340. (int)gpus[i].shaders);
  3341. #endif
  3342. #ifdef HAVE_ADL
  3343. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3344. for(i = 0; i < nDevs; i++)
  3345. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3346. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3347. for(i = 0; i < nDevs; i++)
  3348. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3349. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3350. for(i = 0; i < nDevs; i++)
  3351. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3352. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3353. for(i = 0; i < nDevs; i++)
  3354. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3355. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3356. for(i = 0; i < nDevs; i++)
  3357. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3358. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3359. for(i = 0; i < nDevs; i++)
  3360. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3361. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3362. for(i = 0; i < nDevs; i++)
  3363. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3364. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3365. for(i = 0; i < nDevs; i++)
  3366. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3367. fputs("\",\n\"temp-target\" : \"", fcfg);
  3368. for(i = 0; i < nDevs; i++)
  3369. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  3370. #endif
  3371. fputs("\"", fcfg);
  3372. }
  3373. #endif
  3374. #ifdef HAVE_ADL
  3375. if (opt_reorder)
  3376. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3377. #endif
  3378. /* Simple bool and int options */
  3379. struct opt_table *opt;
  3380. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3381. char *p, *name = strdup(opt->names);
  3382. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3383. if (p[1] != '-')
  3384. continue;
  3385. if (opt->type & OPT_NOARG &&
  3386. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3387. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3388. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3389. if (opt->type & OPT_HASARG &&
  3390. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3391. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3392. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3393. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  3394. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3395. }
  3396. }
  3397. /* Special case options */
  3398. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3399. if (pool_strategy == POOL_BALANCE)
  3400. fputs(",\n\"balance\" : true", fcfg);
  3401. if (pool_strategy == POOL_LOADBALANCE)
  3402. fputs(",\n\"load-balance\" : true", fcfg);
  3403. if (pool_strategy == POOL_ROUNDROBIN)
  3404. fputs(",\n\"round-robin\" : true", fcfg);
  3405. if (pool_strategy == POOL_ROTATE)
  3406. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3407. #if defined(unix)
  3408. if (opt_stderr_cmd && *opt_stderr_cmd)
  3409. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3410. #endif // defined(unix)
  3411. if (opt_kernel_path && *opt_kernel_path) {
  3412. char *kpath = strdup(opt_kernel_path);
  3413. if (kpath[strlen(kpath)-1] == '/')
  3414. kpath[strlen(kpath)-1] = 0;
  3415. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3416. }
  3417. if (schedstart.enable)
  3418. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3419. if (schedstop.enable)
  3420. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3421. if (opt_socks_proxy && *opt_socks_proxy)
  3422. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3423. if (devices_enabled) {
  3424. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  3425. if (devices_enabled & (1 << i))
  3426. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3427. }
  3428. }
  3429. if (opt_removedisabled)
  3430. fprintf(fcfg, ",\n\"remove-disabled\" : true");
  3431. if (opt_api_allow)
  3432. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3433. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3434. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3435. if (opt_api_groups)
  3436. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3437. if (opt_icarus_options)
  3438. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3439. if (opt_icarus_timing)
  3440. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3441. #ifdef USE_USBUTILS
  3442. if (opt_usb_select)
  3443. fprintf(fcfg, ",\n\"usb\" : \"%s\"", json_escape(opt_usb_select));
  3444. #endif
  3445. fputs("\n}\n", fcfg);
  3446. json_escape_free();
  3447. }
  3448. void zero_bestshare(void)
  3449. {
  3450. int i;
  3451. best_diff = 0;
  3452. memset(best_share, 0, 8);
  3453. suffix_string(best_diff, best_share, 0);
  3454. for (i = 0; i < total_pools; i++) {
  3455. struct pool *pool = pools[i];
  3456. pool->best_diff = 0;
  3457. }
  3458. }
  3459. void zero_stats(void)
  3460. {
  3461. int i;
  3462. cgtime(&total_tv_start);
  3463. total_mhashes_done = 0;
  3464. total_getworks = 0;
  3465. total_accepted = 0;
  3466. total_rejected = 0;
  3467. hw_errors = 0;
  3468. total_stale = 0;
  3469. total_discarded = 0;
  3470. local_work = 0;
  3471. total_go = 0;
  3472. total_ro = 0;
  3473. total_secs = 1.0;
  3474. total_diff1 = 0;
  3475. found_blocks = 0;
  3476. total_diff_accepted = 0;
  3477. total_diff_rejected = 0;
  3478. total_diff_stale = 0;
  3479. for (i = 0; i < total_pools; i++) {
  3480. struct pool *pool = pools[i];
  3481. pool->getwork_requested = 0;
  3482. pool->accepted = 0;
  3483. pool->rejected = 0;
  3484. pool->stale_shares = 0;
  3485. pool->discarded_work = 0;
  3486. pool->getfail_occasions = 0;
  3487. pool->remotefail_occasions = 0;
  3488. pool->last_share_time = 0;
  3489. pool->diff1 = 0;
  3490. pool->diff_accepted = 0;
  3491. pool->diff_rejected = 0;
  3492. pool->diff_stale = 0;
  3493. pool->last_share_diff = 0;
  3494. }
  3495. zero_bestshare();
  3496. for (i = 0; i < total_devices; ++i) {
  3497. struct cgpu_info *cgpu = get_devices(i);
  3498. mutex_lock(&hash_lock);
  3499. cgpu->total_mhashes = 0;
  3500. cgpu->accepted = 0;
  3501. cgpu->rejected = 0;
  3502. cgpu->hw_errors = 0;
  3503. cgpu->utility = 0.0;
  3504. cgpu->last_share_pool_time = 0;
  3505. cgpu->diff1 = 0;
  3506. cgpu->diff_accepted = 0;
  3507. cgpu->diff_rejected = 0;
  3508. cgpu->last_share_diff = 0;
  3509. mutex_unlock(&hash_lock);
  3510. }
  3511. }
  3512. #ifdef HAVE_CURSES
  3513. static void display_pools(void)
  3514. {
  3515. struct pool *pool;
  3516. int selected, i;
  3517. char input;
  3518. opt_loginput = true;
  3519. immedok(logwin, true);
  3520. clear_logwin();
  3521. updated:
  3522. for (i = 0; i < total_pools; i++) {
  3523. pool = pools[i];
  3524. if (pool == current_pool())
  3525. wattron(logwin, A_BOLD);
  3526. if (pool->enabled != POOL_ENABLED)
  3527. wattron(logwin, A_DIM);
  3528. wlogprint("%d: ", pool->pool_no);
  3529. switch (pool->enabled) {
  3530. case POOL_ENABLED:
  3531. wlogprint("Enabled ");
  3532. break;
  3533. case POOL_DISABLED:
  3534. wlogprint("Disabled ");
  3535. break;
  3536. case POOL_REJECTING:
  3537. wlogprint("Rejecting ");
  3538. break;
  3539. }
  3540. wlogprint("%s Priority %d: %s User:%s\n",
  3541. pool->idle? "Dead" : "Alive",
  3542. pool->prio,
  3543. pool->rpc_url, pool->rpc_user);
  3544. wattroff(logwin, A_BOLD | A_DIM);
  3545. }
  3546. retry:
  3547. wlogprint("\nCurrent pool management strategy: %s\n",
  3548. strategies[pool_strategy]);
  3549. if (pool_strategy == POOL_ROTATE)
  3550. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3551. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3552. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3553. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3554. wlogprint("Or press any other key to continue\n");
  3555. logwin_update();
  3556. input = getch();
  3557. if (!strncasecmp(&input, "a", 1)) {
  3558. input_pool(true);
  3559. goto updated;
  3560. } else if (!strncasecmp(&input, "r", 1)) {
  3561. if (total_pools <= 1) {
  3562. wlogprint("Cannot remove last pool");
  3563. goto retry;
  3564. }
  3565. selected = curses_int("Select pool number");
  3566. if (selected < 0 || selected >= total_pools) {
  3567. wlogprint("Invalid selection\n");
  3568. goto retry;
  3569. }
  3570. pool = pools[selected];
  3571. if (pool == current_pool())
  3572. switch_pools(NULL);
  3573. if (pool == current_pool()) {
  3574. wlogprint("Unable to remove pool due to activity\n");
  3575. goto retry;
  3576. }
  3577. disable_pool(pool);
  3578. remove_pool(pool);
  3579. goto updated;
  3580. } else if (!strncasecmp(&input, "s", 1)) {
  3581. selected = curses_int("Select pool number");
  3582. if (selected < 0 || selected >= total_pools) {
  3583. wlogprint("Invalid selection\n");
  3584. goto retry;
  3585. }
  3586. pool = pools[selected];
  3587. enable_pool(pool);
  3588. switch_pools(pool);
  3589. goto updated;
  3590. } else if (!strncasecmp(&input, "d", 1)) {
  3591. if (enabled_pools <= 1) {
  3592. wlogprint("Cannot disable last pool");
  3593. goto retry;
  3594. }
  3595. selected = curses_int("Select pool number");
  3596. if (selected < 0 || selected >= total_pools) {
  3597. wlogprint("Invalid selection\n");
  3598. goto retry;
  3599. }
  3600. pool = pools[selected];
  3601. disable_pool(pool);
  3602. if (pool == current_pool())
  3603. switch_pools(NULL);
  3604. goto updated;
  3605. } else if (!strncasecmp(&input, "e", 1)) {
  3606. selected = curses_int("Select pool number");
  3607. if (selected < 0 || selected >= total_pools) {
  3608. wlogprint("Invalid selection\n");
  3609. goto retry;
  3610. }
  3611. pool = pools[selected];
  3612. enable_pool(pool);
  3613. if (pool->prio < current_pool()->prio)
  3614. switch_pools(pool);
  3615. goto updated;
  3616. } else if (!strncasecmp(&input, "c", 1)) {
  3617. for (i = 0; i <= TOP_STRATEGY; i++)
  3618. wlogprint("%d: %s\n", i, strategies[i]);
  3619. selected = curses_int("Select strategy number type");
  3620. if (selected < 0 || selected > TOP_STRATEGY) {
  3621. wlogprint("Invalid selection\n");
  3622. goto retry;
  3623. }
  3624. if (selected == POOL_ROTATE) {
  3625. opt_rotate_period = curses_int("Select interval in minutes");
  3626. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3627. opt_rotate_period = 0;
  3628. wlogprint("Invalid selection\n");
  3629. goto retry;
  3630. }
  3631. }
  3632. pool_strategy = selected;
  3633. switch_pools(NULL);
  3634. goto updated;
  3635. } else if (!strncasecmp(&input, "i", 1)) {
  3636. selected = curses_int("Select pool number");
  3637. if (selected < 0 || selected >= total_pools) {
  3638. wlogprint("Invalid selection\n");
  3639. goto retry;
  3640. }
  3641. pool = pools[selected];
  3642. display_pool_summary(pool);
  3643. goto retry;
  3644. } else if (!strncasecmp(&input, "f", 1)) {
  3645. opt_fail_only ^= true;
  3646. goto updated;
  3647. } else
  3648. clear_logwin();
  3649. immedok(logwin, false);
  3650. opt_loginput = false;
  3651. }
  3652. static void display_options(void)
  3653. {
  3654. int selected;
  3655. char input;
  3656. opt_loginput = true;
  3657. immedok(logwin, true);
  3658. clear_logwin();
  3659. retry:
  3660. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3661. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  3662. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  3663. "[L]og interval:%d\n[Z]ero statistics\n",
  3664. opt_debug ? "on" : "off",
  3665. want_per_device_stats? "on" : "off",
  3666. opt_quiet ? "on" : "off",
  3667. opt_log_output ? "on" : "off",
  3668. opt_protocol ? "on" : "off",
  3669. opt_worktime ? "on" : "off",
  3670. opt_compact ? "on" : "off",
  3671. opt_log_interval);
  3672. wlogprint("Select an option or any other key to return\n");
  3673. logwin_update();
  3674. input = getch();
  3675. if (!strncasecmp(&input, "q", 1)) {
  3676. opt_quiet ^= true;
  3677. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3678. goto retry;
  3679. } else if (!strncasecmp(&input, "v", 1)) {
  3680. opt_log_output ^= true;
  3681. if (opt_log_output)
  3682. opt_quiet = false;
  3683. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3684. goto retry;
  3685. } else if (!strncasecmp(&input, "n", 1)) {
  3686. opt_log_output = false;
  3687. opt_debug = false;
  3688. opt_quiet = false;
  3689. opt_protocol = false;
  3690. opt_compact = false;
  3691. want_per_device_stats = false;
  3692. wlogprint("Output mode reset to normal\n");
  3693. switch_compact();
  3694. goto retry;
  3695. } else if (!strncasecmp(&input, "d", 1)) {
  3696. opt_debug ^= true;
  3697. opt_log_output = opt_debug;
  3698. if (opt_debug)
  3699. opt_quiet = false;
  3700. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  3701. goto retry;
  3702. } else if (!strncasecmp(&input, "m", 1)) {
  3703. opt_compact ^= true;
  3704. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  3705. switch_compact();
  3706. goto retry;
  3707. } else if (!strncasecmp(&input, "p", 1)) {
  3708. want_per_device_stats ^= true;
  3709. opt_log_output = want_per_device_stats;
  3710. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3711. goto retry;
  3712. } else if (!strncasecmp(&input, "r", 1)) {
  3713. opt_protocol ^= true;
  3714. if (opt_protocol)
  3715. opt_quiet = false;
  3716. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3717. goto retry;
  3718. } else if (!strncasecmp(&input, "c", 1))
  3719. clear_logwin();
  3720. else if (!strncasecmp(&input, "l", 1)) {
  3721. selected = curses_int("Interval in seconds");
  3722. if (selected < 0 || selected > 9999) {
  3723. wlogprint("Invalid selection\n");
  3724. goto retry;
  3725. }
  3726. opt_log_interval = selected;
  3727. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3728. goto retry;
  3729. } else if (!strncasecmp(&input, "s", 1)) {
  3730. opt_realquiet = true;
  3731. } else if (!strncasecmp(&input, "w", 1)) {
  3732. opt_worktime ^= true;
  3733. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  3734. goto retry;
  3735. } else if (!strncasecmp(&input, "z", 1)) {
  3736. zero_stats();
  3737. goto retry;
  3738. } else
  3739. clear_logwin();
  3740. immedok(logwin, false);
  3741. opt_loginput = false;
  3742. }
  3743. #endif
  3744. void default_save_file(char *filename)
  3745. {
  3746. if (default_config && *default_config) {
  3747. strcpy(filename, default_config);
  3748. return;
  3749. }
  3750. #if defined(unix)
  3751. if (getenv("HOME") && *getenv("HOME")) {
  3752. strcpy(filename, getenv("HOME"));
  3753. strcat(filename, "/");
  3754. }
  3755. else
  3756. strcpy(filename, "");
  3757. strcat(filename, ".cgminer/");
  3758. mkdir(filename, 0777);
  3759. #else
  3760. strcpy(filename, "");
  3761. #endif
  3762. strcat(filename, def_conf);
  3763. }
  3764. #ifdef HAVE_CURSES
  3765. static void set_options(void)
  3766. {
  3767. int selected;
  3768. char input;
  3769. opt_loginput = true;
  3770. immedok(logwin, true);
  3771. clear_logwin();
  3772. retry:
  3773. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  3774. "[W]rite config file\n[C]gminer restart\n",
  3775. opt_queue, opt_scantime, opt_expiry);
  3776. wlogprint("Select an option or any other key to return\n");
  3777. logwin_update();
  3778. input = getch();
  3779. if (!strncasecmp(&input, "q", 1)) {
  3780. selected = curses_int("Extra work items to queue");
  3781. if (selected < 0 || selected > 9999) {
  3782. wlogprint("Invalid selection\n");
  3783. goto retry;
  3784. }
  3785. opt_queue = selected;
  3786. goto retry;
  3787. } else if (!strncasecmp(&input, "s", 1)) {
  3788. selected = curses_int("Set scantime in seconds");
  3789. if (selected < 0 || selected > 9999) {
  3790. wlogprint("Invalid selection\n");
  3791. goto retry;
  3792. }
  3793. opt_scantime = selected;
  3794. goto retry;
  3795. } else if (!strncasecmp(&input, "e", 1)) {
  3796. selected = curses_int("Set expiry time in seconds");
  3797. if (selected < 0 || selected > 9999) {
  3798. wlogprint("Invalid selection\n");
  3799. goto retry;
  3800. }
  3801. opt_expiry = selected;
  3802. goto retry;
  3803. } else if (!strncasecmp(&input, "w", 1)) {
  3804. FILE *fcfg;
  3805. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3806. default_save_file(filename);
  3807. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3808. str = curses_input(prompt);
  3809. if (strcmp(str, "-1")) {
  3810. struct stat statbuf;
  3811. strcpy(filename, str);
  3812. free(str);
  3813. if (!stat(filename, &statbuf)) {
  3814. wlogprint("File exists, overwrite?\n");
  3815. input = getch();
  3816. if (strncasecmp(&input, "y", 1))
  3817. goto retry;
  3818. }
  3819. }
  3820. else
  3821. free(str);
  3822. fcfg = fopen(filename, "w");
  3823. if (!fcfg) {
  3824. wlogprint("Cannot open or create file\n");
  3825. goto retry;
  3826. }
  3827. write_config(fcfg);
  3828. fclose(fcfg);
  3829. goto retry;
  3830. } else if (!strncasecmp(&input, "c", 1)) {
  3831. wlogprint("Are you sure?\n");
  3832. input = getch();
  3833. if (!strncasecmp(&input, "y", 1))
  3834. app_restart();
  3835. else
  3836. clear_logwin();
  3837. } else
  3838. clear_logwin();
  3839. immedok(logwin, false);
  3840. opt_loginput = false;
  3841. }
  3842. static void *input_thread(void __maybe_unused *userdata)
  3843. {
  3844. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3845. RenameThread("input");
  3846. if (!curses_active)
  3847. return NULL;
  3848. while (1) {
  3849. char input;
  3850. input = getch();
  3851. if (!strncasecmp(&input, "q", 1)) {
  3852. kill_work();
  3853. return NULL;
  3854. } else if (!strncasecmp(&input, "d", 1))
  3855. display_options();
  3856. else if (!strncasecmp(&input, "p", 1))
  3857. display_pools();
  3858. else if (!strncasecmp(&input, "s", 1))
  3859. set_options();
  3860. else if (have_opencl && !strncasecmp(&input, "g", 1))
  3861. manage_gpu();
  3862. if (opt_realquiet) {
  3863. disable_curses();
  3864. break;
  3865. }
  3866. }
  3867. return NULL;
  3868. }
  3869. #endif
  3870. static void *api_thread(void *userdata)
  3871. {
  3872. struct thr_info *mythr = userdata;
  3873. pthread_detach(pthread_self());
  3874. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3875. RenameThread("api");
  3876. api(api_thr_id);
  3877. PTH(mythr) = 0L;
  3878. return NULL;
  3879. }
  3880. void thread_reportin(struct thr_info *thr)
  3881. {
  3882. cgtime(&thr->last);
  3883. thr->cgpu->status = LIFE_WELL;
  3884. thr->getwork = false;
  3885. thr->cgpu->device_last_well = time(NULL);
  3886. }
  3887. static inline void thread_reportout(struct thr_info *thr)
  3888. {
  3889. thr->getwork = true;
  3890. }
  3891. static void hashmeter(int thr_id, struct timeval *diff,
  3892. uint64_t hashes_done)
  3893. {
  3894. struct timeval temp_tv_end, total_diff;
  3895. double secs;
  3896. double local_secs;
  3897. double utility;
  3898. static double local_mhashes_done = 0;
  3899. static double rolling = 0;
  3900. double local_mhashes;
  3901. bool showlog = false;
  3902. char displayed_hashes[16], displayed_rolling[16];
  3903. uint64_t dh64, dr64;
  3904. struct thr_info *thr;
  3905. local_mhashes = (double)hashes_done / 1000000.0;
  3906. /* Update the last time this thread reported in */
  3907. if (thr_id >= 0) {
  3908. thr = get_thread(thr_id);
  3909. cgtime(&(thr->last));
  3910. thr->cgpu->device_last_well = time(NULL);
  3911. }
  3912. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3913. /* So we can call hashmeter from a non worker thread */
  3914. if (thr_id >= 0) {
  3915. struct cgpu_info *cgpu = thr->cgpu;
  3916. double thread_rolling = 0.0;
  3917. int i;
  3918. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  3919. thr_id, hashes_done, hashes_done / 1000 / secs);
  3920. /* Rolling average for each thread and each device */
  3921. decay_time(&thr->rolling, local_mhashes / secs);
  3922. for (i = 0; i < cgpu->threads; i++)
  3923. thread_rolling += cgpu->thr[i]->rolling;
  3924. mutex_lock(&hash_lock);
  3925. decay_time(&cgpu->rolling, thread_rolling);
  3926. cgpu->total_mhashes += local_mhashes;
  3927. mutex_unlock(&hash_lock);
  3928. // If needed, output detailed, per-device stats
  3929. if (want_per_device_stats) {
  3930. struct timeval now;
  3931. struct timeval elapsed;
  3932. cgtime(&now);
  3933. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  3934. if (opt_log_interval <= elapsed.tv_sec) {
  3935. struct cgpu_info *cgpu = thr->cgpu;
  3936. char logline[255];
  3937. cgpu->last_message_tv = now;
  3938. get_statline(logline, cgpu);
  3939. if (!curses_active) {
  3940. printf("%s \r", logline);
  3941. fflush(stdout);
  3942. } else
  3943. applog(LOG_INFO, "%s", logline);
  3944. }
  3945. }
  3946. }
  3947. /* Totals are updated by all threads so can race without locking */
  3948. mutex_lock(&hash_lock);
  3949. cgtime(&temp_tv_end);
  3950. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  3951. total_mhashes_done += local_mhashes;
  3952. local_mhashes_done += local_mhashes;
  3953. /* Only update with opt_log_interval */
  3954. if (total_diff.tv_sec < opt_log_interval)
  3955. goto out_unlock;
  3956. showlog = true;
  3957. cgtime(&total_tv_end);
  3958. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3959. decay_time(&rolling, local_mhashes_done / local_secs);
  3960. global_hashrate = roundl(rolling) * 1000000;
  3961. timersub(&total_tv_end, &total_tv_start, &total_diff);
  3962. total_secs = (double)total_diff.tv_sec +
  3963. ((double)total_diff.tv_usec / 1000000.0);
  3964. utility = total_accepted / total_secs * 60;
  3965. dh64 = (double)total_mhashes_done / total_secs * 1000000ull;
  3966. dr64 = (double)rolling * 1000000ull;
  3967. suffix_string(dh64, displayed_hashes, 4);
  3968. suffix_string(dr64, displayed_rolling, 4);
  3969. sprintf(statusline, "%s(%ds):%s (avg):%sh/s | A:%d R:%d HW:%d U:%.1f/m WU:%.1f/m",
  3970. want_per_device_stats ? "ALL " : "",
  3971. opt_log_interval, displayed_rolling, displayed_hashes,
  3972. total_accepted, total_rejected, hw_errors, utility,
  3973. total_diff1 / total_secs * 60);
  3974. local_mhashes_done = 0;
  3975. out_unlock:
  3976. mutex_unlock(&hash_lock);
  3977. if (showlog) {
  3978. if (!curses_active) {
  3979. printf("%s \r", statusline);
  3980. fflush(stdout);
  3981. } else
  3982. applog(LOG_INFO, "%s", statusline);
  3983. }
  3984. }
  3985. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  3986. struct stratum_share *sshare)
  3987. {
  3988. struct work *work = sshare->work;
  3989. char hashshow[65];
  3990. uint32_t *hash32;
  3991. char diffdisp[16];
  3992. int intdiff;
  3993. hash32 = (uint32_t *)(work->hash);
  3994. intdiff = floor(work->work_difficulty);
  3995. suffix_string(work->share_diff, diffdisp, 0);
  3996. sprintf(hashshow, "%08lx Diff %s/%d%s", (unsigned long)htole32(hash32[6]), diffdisp, intdiff,
  3997. work->block? " BLOCK!" : "");
  3998. share_result(val, res_val, err_val, work, hashshow, false, "");
  3999. }
  4000. /* Parses stratum json responses and tries to find the id that the request
  4001. * matched to and treat it accordingly. */
  4002. static bool parse_stratum_response(struct pool *pool, char *s)
  4003. {
  4004. json_t *val = NULL, *err_val, *res_val, *id_val;
  4005. struct stratum_share *sshare;
  4006. json_error_t err;
  4007. bool ret = false;
  4008. int id;
  4009. val = JSON_LOADS(s, &err);
  4010. if (!val) {
  4011. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  4012. goto out;
  4013. }
  4014. res_val = json_object_get(val, "result");
  4015. err_val = json_object_get(val, "error");
  4016. id_val = json_object_get(val, "id");
  4017. if (json_is_null(id_val) || !id_val) {
  4018. char *ss;
  4019. if (err_val)
  4020. ss = json_dumps(err_val, JSON_INDENT(3));
  4021. else
  4022. ss = strdup("(unknown reason)");
  4023. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  4024. free(ss);
  4025. goto out;
  4026. }
  4027. id = json_integer_value(id_val);
  4028. mutex_lock(&sshare_lock);
  4029. HASH_FIND_INT(stratum_shares, &id, sshare);
  4030. if (sshare) {
  4031. HASH_DEL(stratum_shares, sshare);
  4032. pool->sshares--;
  4033. }
  4034. mutex_unlock(&sshare_lock);
  4035. if (!sshare) {
  4036. double pool_diff;
  4037. /* Since the share is untracked, we can only guess at what the
  4038. * work difficulty is based on the current pool diff. */
  4039. cg_rlock(&pool->data_lock);
  4040. pool_diff = pool->swork.diff;
  4041. cg_runlock(&pool->data_lock);
  4042. if (json_is_true(res_val)) {
  4043. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  4044. /* We don't know what device this came from so we can't
  4045. * attribute the work to the relevant cgpu */
  4046. mutex_lock(&stats_lock);
  4047. total_accepted++;
  4048. pool->accepted++;
  4049. total_diff_accepted += pool_diff;
  4050. pool->diff_accepted += pool_diff;
  4051. mutex_unlock(&stats_lock);
  4052. } else {
  4053. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  4054. mutex_lock(&stats_lock);
  4055. total_rejected++;
  4056. pool->rejected++;
  4057. total_diff_rejected += pool_diff;
  4058. pool->diff_rejected += pool_diff;
  4059. mutex_unlock(&stats_lock);
  4060. }
  4061. goto out;
  4062. }
  4063. stratum_share_result(val, res_val, err_val, sshare);
  4064. free_work(sshare->work);
  4065. free(sshare);
  4066. ret = true;
  4067. out:
  4068. if (val)
  4069. json_decref(val);
  4070. return ret;
  4071. }
  4072. void clear_stratum_shares(struct pool *pool)
  4073. {
  4074. struct stratum_share *sshare, *tmpshare;
  4075. double diff_cleared = 0;
  4076. int cleared = 0;
  4077. mutex_lock(&sshare_lock);
  4078. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  4079. if (sshare->work->pool == pool) {
  4080. HASH_DEL(stratum_shares, sshare);
  4081. diff_cleared += sshare->work->work_difficulty;
  4082. free_work(sshare->work);
  4083. pool->sshares--;
  4084. free(sshare);
  4085. cleared++;
  4086. }
  4087. }
  4088. mutex_unlock(&sshare_lock);
  4089. if (cleared) {
  4090. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  4091. pool->stale_shares += cleared;
  4092. total_stale += cleared;
  4093. pool->diff_stale += diff_cleared;
  4094. total_diff_stale += diff_cleared;
  4095. }
  4096. }
  4097. static void clear_pool_work(struct pool *pool)
  4098. {
  4099. struct work *work, *tmp;
  4100. int cleared = 0;
  4101. mutex_lock(stgd_lock);
  4102. HASH_ITER(hh, staged_work, work, tmp) {
  4103. if (work->pool == pool) {
  4104. HASH_DEL(staged_work, work);
  4105. free_work(work);
  4106. cleared++;
  4107. }
  4108. }
  4109. mutex_unlock(stgd_lock);
  4110. }
  4111. static int cp_prio(void)
  4112. {
  4113. int prio;
  4114. cg_rlock(&control_lock);
  4115. prio = currentpool->prio;
  4116. cg_runlock(&control_lock);
  4117. return prio;
  4118. }
  4119. /* We only need to maintain a secondary pool connection when we need the
  4120. * capacity to get work from the backup pools while still on the primary */
  4121. static bool cnx_needed(struct pool *pool)
  4122. {
  4123. struct pool *cp;
  4124. /* Balance strategies need all pools online */
  4125. if (pool_strategy == POOL_BALANCE)
  4126. return true;
  4127. if (pool_strategy == POOL_LOADBALANCE)
  4128. return true;
  4129. /* Idle stratum pool needs something to kick it alive again */
  4130. if (pool->has_stratum && pool->idle)
  4131. return true;
  4132. /* Getwork pools without opt_fail_only need backup pools up to be able
  4133. * to leak shares */
  4134. cp = current_pool();
  4135. if (cp == pool)
  4136. return true;
  4137. if (!cp->has_gbt && !cp->has_stratum && (!opt_fail_only || !cp->hdr_path))
  4138. return true;
  4139. /* If we're waiting for a response from shares submitted, keep the
  4140. * connection open. */
  4141. if (pool->sshares)
  4142. return true;
  4143. /* If the pool has only just come to life and is higher priority than
  4144. * the current pool keep the connection open so we can fail back to
  4145. * it. */
  4146. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  4147. return true;
  4148. if (pool_unworkable(cp))
  4149. return true;
  4150. return false;
  4151. }
  4152. static void wait_lpcurrent(struct pool *pool);
  4153. static void pool_resus(struct pool *pool);
  4154. static void gen_stratum_work(struct pool *pool, struct work *work);
  4155. static void stratum_resumed(struct pool *pool)
  4156. {
  4157. if (!pool->stratum_notify)
  4158. return;
  4159. if (pool_tclear(pool, &pool->idle)) {
  4160. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  4161. pool_resus(pool);
  4162. }
  4163. }
  4164. static bool supports_resume(struct pool *pool)
  4165. {
  4166. bool ret;
  4167. cg_rlock(&pool->data_lock);
  4168. ret = (pool->sessionid != NULL);
  4169. cg_runlock(&pool->data_lock);
  4170. return ret;
  4171. }
  4172. /* One stratum receive thread per pool that has stratum waits on the socket
  4173. * checking for new messages and for the integrity of the socket connection. We
  4174. * reset the connection based on the integrity of the receive side only as the
  4175. * send side will eventually expire data it fails to send. */
  4176. static void *stratum_rthread(void *userdata)
  4177. {
  4178. struct pool *pool = (struct pool *)userdata;
  4179. char threadname[16];
  4180. pthread_detach(pthread_self());
  4181. snprintf(threadname, 16, "StratumR/%d", pool->pool_no);
  4182. RenameThread(threadname);
  4183. while (42) {
  4184. struct timeval timeout;
  4185. int sel_ret;
  4186. fd_set rd;
  4187. char *s;
  4188. if (unlikely(pool->removed))
  4189. break;
  4190. /* Check to see whether we need to maintain this connection
  4191. * indefinitely or just bring it up when we switch to this
  4192. * pool */
  4193. if (!sock_full(pool) && !cnx_needed(pool)) {
  4194. suspend_stratum(pool);
  4195. clear_stratum_shares(pool);
  4196. clear_pool_work(pool);
  4197. wait_lpcurrent(pool);
  4198. if (!restart_stratum(pool)) {
  4199. pool_died(pool);
  4200. while (!restart_stratum(pool)) {
  4201. if (pool->removed)
  4202. goto out;
  4203. nmsleep(30000);
  4204. }
  4205. }
  4206. }
  4207. FD_ZERO(&rd);
  4208. FD_SET(pool->sock, &rd);
  4209. timeout.tv_sec = 90;
  4210. timeout.tv_usec = 0;
  4211. /* The protocol specifies that notify messages should be sent
  4212. * every minute so if we fail to receive any for 90 seconds we
  4213. * assume the connection has been dropped and treat this pool
  4214. * as dead */
  4215. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  4216. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  4217. s = NULL;
  4218. } else
  4219. s = recv_line(pool);
  4220. if (!s) {
  4221. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  4222. pool->getfail_occasions++;
  4223. total_go++;
  4224. /* If the socket to our stratum pool disconnects, all
  4225. * tracked submitted shares are lost and we will leak
  4226. * the memory if we don't discard their records. */
  4227. if (!supports_resume(pool) || opt_lowmem)
  4228. clear_stratum_shares(pool);
  4229. clear_pool_work(pool);
  4230. if (pool == current_pool())
  4231. restart_threads();
  4232. if (restart_stratum(pool))
  4233. continue;
  4234. pool_died(pool);
  4235. while (!restart_stratum(pool)) {
  4236. if (pool->removed)
  4237. goto out;
  4238. nmsleep(30000);
  4239. }
  4240. stratum_resumed(pool);
  4241. continue;
  4242. }
  4243. /* Check this pool hasn't died while being a backup pool and
  4244. * has not had its idle flag cleared */
  4245. stratum_resumed(pool);
  4246. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  4247. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  4248. free(s);
  4249. if (pool->swork.clean) {
  4250. struct work *work = make_work();
  4251. /* Generate a single work item to update the current
  4252. * block database */
  4253. pool->swork.clean = false;
  4254. gen_stratum_work(pool, work);
  4255. if (test_work_current(work)) {
  4256. /* Only accept a work restart if this stratum
  4257. * connection is from the current pool */
  4258. if (pool == current_pool()) {
  4259. restart_threads();
  4260. applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
  4261. }
  4262. } else
  4263. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  4264. free_work(work);
  4265. }
  4266. }
  4267. out:
  4268. return NULL;
  4269. }
  4270. /* Each pool has one stratum send thread for sending shares to avoid many
  4271. * threads being created for submission since all sends need to be serialised
  4272. * anyway. */
  4273. static void *stratum_sthread(void *userdata)
  4274. {
  4275. struct pool *pool = (struct pool *)userdata;
  4276. char threadname[16];
  4277. pthread_detach(pthread_self());
  4278. snprintf(threadname, 16, "StratumS/%d", pool->pool_no);
  4279. RenameThread(threadname);
  4280. pool->stratum_q = tq_new();
  4281. if (!pool->stratum_q)
  4282. quit(1, "Failed to create stratum_q in stratum_sthread");
  4283. while (42) {
  4284. struct stratum_share *sshare;
  4285. uint32_t *hash32, nonce;
  4286. struct work *work;
  4287. bool submitted;
  4288. char *noncehex;
  4289. char s[1024];
  4290. if (unlikely(pool->removed))
  4291. break;
  4292. work = tq_pop(pool->stratum_q, NULL);
  4293. if (unlikely(!work))
  4294. quit(1, "Stratum q returned empty work");
  4295. sshare = calloc(sizeof(struct stratum_share), 1);
  4296. hash32 = (uint32_t *)work->hash;
  4297. submitted = false;
  4298. sshare->sshare_time = time(NULL);
  4299. /* This work item is freed in parse_stratum_response */
  4300. sshare->work = work;
  4301. nonce = *((uint32_t *)(work->data + 76));
  4302. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  4303. memset(s, 0, 1024);
  4304. mutex_lock(&sshare_lock);
  4305. /* Give the stratum share a unique id */
  4306. sshare->id = swork_id++;
  4307. mutex_unlock(&sshare_lock);
  4308. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  4309. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  4310. free(noncehex);
  4311. applog(LOG_INFO, "Submitting share %08lx to pool %d",
  4312. (long unsigned int)htole32(hash32[6]), pool->pool_no);
  4313. /* Try resubmitting for up to 2 minutes if we fail to submit
  4314. * once and the stratum pool nonce1 still matches suggesting
  4315. * we may be able to resume. */
  4316. while (time(NULL) < sshare->sshare_time + 120) {
  4317. bool sessionid_match;
  4318. if (likely(stratum_send(pool, s, strlen(s)))) {
  4319. if (pool_tclear(pool, &pool->submit_fail))
  4320. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4321. mutex_lock(&sshare_lock);
  4322. HASH_ADD_INT(stratum_shares, id, sshare);
  4323. pool->sshares++;
  4324. mutex_unlock(&sshare_lock);
  4325. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  4326. submitted = true;
  4327. break;
  4328. }
  4329. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  4330. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  4331. total_ro++;
  4332. pool->remotefail_occasions++;
  4333. }
  4334. if (opt_lowmem) {
  4335. applog(LOG_DEBUG, "Lowmem option prevents resubmitting stratum share");
  4336. break;
  4337. }
  4338. cg_rlock(&pool->data_lock);
  4339. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  4340. cg_runlock(&pool->data_lock);
  4341. if (!sessionid_match) {
  4342. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4343. break;
  4344. }
  4345. /* Retry every 5 seconds */
  4346. sleep(5);
  4347. }
  4348. if (unlikely(!submitted)) {
  4349. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  4350. free_work(work);
  4351. free(sshare);
  4352. pool->stale_shares++;
  4353. total_stale++;
  4354. }
  4355. }
  4356. /* Freeze the work queue but don't free up its memory in case there is
  4357. * work still trying to be submitted to the removed pool. */
  4358. tq_freeze(pool->stratum_q);
  4359. return NULL;
  4360. }
  4361. static void init_stratum_threads(struct pool *pool)
  4362. {
  4363. if (unlikely(pthread_create(&pool->stratum_sthread, NULL, stratum_sthread, (void *)pool)))
  4364. quit(1, "Failed to create stratum sthread");
  4365. if (unlikely(pthread_create(&pool->stratum_rthread, NULL, stratum_rthread, (void *)pool)))
  4366. quit(1, "Failed to create stratum rthread");
  4367. }
  4368. static void *longpoll_thread(void *userdata);
  4369. static bool stratum_works(struct pool *pool)
  4370. {
  4371. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  4372. if (!extract_sockaddr(pool, pool->stratum_url))
  4373. return false;
  4374. if (!initiate_stratum(pool))
  4375. return false;
  4376. return true;
  4377. }
  4378. static bool pool_active(struct pool *pool, bool pinging)
  4379. {
  4380. struct timeval tv_getwork, tv_getwork_reply;
  4381. bool ret = false;
  4382. json_t *val;
  4383. CURL *curl;
  4384. int rolltime;
  4385. if (pool->has_gbt)
  4386. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  4387. else
  4388. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  4389. /* This is the central point we activate stratum when we can */
  4390. retry_stratum:
  4391. if (pool->has_stratum) {
  4392. /* We create the stratum thread for each pool just after
  4393. * successful authorisation. Once the init flag has been set
  4394. * we never unset it and the stratum thread is responsible for
  4395. * setting/unsetting the active flag */
  4396. bool init = pool_tset(pool, &pool->stratum_init);
  4397. if (!init) {
  4398. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  4399. if (ret)
  4400. init_stratum_threads(pool);
  4401. else
  4402. pool_tclear(pool, &pool->stratum_init);
  4403. return ret;
  4404. }
  4405. return pool->stratum_active;
  4406. }
  4407. curl = curl_easy_init();
  4408. if (unlikely(!curl)) {
  4409. applog(LOG_ERR, "CURL initialisation failed");
  4410. return false;
  4411. }
  4412. /* Probe for GBT support on first pass */
  4413. if (!pool->probed && !opt_fix_protocol) {
  4414. applog(LOG_DEBUG, "Probing for GBT support");
  4415. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4416. gbt_req, true, false, &rolltime, pool, false);
  4417. if (val) {
  4418. bool append = false, submit = false;
  4419. json_t *res_val, *mutables;
  4420. int i, mutsize = 0;
  4421. res_val = json_object_get(val, "result");
  4422. if (res_val) {
  4423. mutables = json_object_get(res_val, "mutable");
  4424. mutsize = json_array_size(mutables);
  4425. }
  4426. for (i = 0; i < mutsize; i++) {
  4427. json_t *arrval = json_array_get(mutables, i);
  4428. if (json_is_string(arrval)) {
  4429. const char *mutable = json_string_value(arrval);
  4430. if (!strncasecmp(mutable, "coinbase/append", 15))
  4431. append = true;
  4432. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  4433. submit = true;
  4434. }
  4435. }
  4436. json_decref(val);
  4437. /* Only use GBT if it supports coinbase append and
  4438. * submit coinbase */
  4439. if (append && submit) {
  4440. pool->has_gbt = true;
  4441. pool->rpc_req = gbt_req;
  4442. }
  4443. }
  4444. /* Reset this so we can probe fully just after this. It will be
  4445. * set to true that time.*/
  4446. pool->probed = false;
  4447. if (pool->has_gbt)
  4448. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  4449. else
  4450. applog(LOG_DEBUG, "No GBT coinbase + append support found, using getwork protocol");
  4451. }
  4452. cgtime(&tv_getwork);
  4453. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4454. pool->rpc_req, true, false, &rolltime, pool, false);
  4455. cgtime(&tv_getwork_reply);
  4456. /* Detect if a http getwork pool has an X-Stratum header at startup,
  4457. * and if so, switch to that in preference to getwork if it works */
  4458. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  4459. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  4460. if (!pool->rpc_url)
  4461. pool->rpc_url = strdup(pool->stratum_url);
  4462. pool->has_stratum = true;
  4463. curl_easy_cleanup(curl);
  4464. goto retry_stratum;
  4465. }
  4466. if (val) {
  4467. struct work *work = make_work();
  4468. bool rc;
  4469. rc = work_decode(pool, work, val);
  4470. if (rc) {
  4471. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4472. pool->pool_no, pool->rpc_url);
  4473. work->pool = pool;
  4474. work->rolltime = rolltime;
  4475. copy_time(&work->tv_getwork, &tv_getwork);
  4476. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  4477. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  4478. calc_diff(work, 0);
  4479. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4480. tq_push(control_thr[stage_thr_id].q, work);
  4481. total_getworks++;
  4482. pool->getwork_requested++;
  4483. ret = true;
  4484. cgtime(&pool->tv_idle);
  4485. } else {
  4486. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4487. pool->pool_no, pool->rpc_url);
  4488. free_work(work);
  4489. }
  4490. json_decref(val);
  4491. if (pool->lp_url)
  4492. goto out;
  4493. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4494. if (pool->hdr_path) {
  4495. char *copy_start, *hdr_path;
  4496. bool need_slash = false;
  4497. hdr_path = pool->hdr_path;
  4498. if (strstr(hdr_path, "://")) {
  4499. pool->lp_url = hdr_path;
  4500. hdr_path = NULL;
  4501. } else {
  4502. /* absolute path, on current server */
  4503. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  4504. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  4505. need_slash = true;
  4506. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  4507. if (!pool->lp_url) {
  4508. applog(LOG_ERR, "Malloc failure in pool_active");
  4509. return false;
  4510. }
  4511. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  4512. }
  4513. } else
  4514. pool->lp_url = NULL;
  4515. if (!pool->lp_started) {
  4516. pool->lp_started = true;
  4517. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4518. quit(1, "Failed to create pool longpoll thread");
  4519. }
  4520. } else {
  4521. /* If we failed to parse a getwork, this could be a stratum
  4522. * url without the prefix stratum+tcp:// so let's check it */
  4523. if (initiate_stratum(pool)) {
  4524. pool->has_stratum = true;
  4525. goto retry_stratum;
  4526. }
  4527. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4528. pool->pool_no, pool->rpc_url);
  4529. if (!pinging)
  4530. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4531. }
  4532. out:
  4533. curl_easy_cleanup(curl);
  4534. return ret;
  4535. }
  4536. static void pool_resus(struct pool *pool)
  4537. {
  4538. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio()) {
  4539. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4540. switch_pools(NULL);
  4541. } else
  4542. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4543. }
  4544. static struct work *hash_pop(void)
  4545. {
  4546. struct work *work = NULL, *tmp;
  4547. int hc;
  4548. mutex_lock(stgd_lock);
  4549. while (!getq->frozen && !HASH_COUNT(staged_work))
  4550. pthread_cond_wait(&getq->cond, stgd_lock);
  4551. hc = HASH_COUNT(staged_work);
  4552. /* Find clone work if possible, to allow masters to be reused */
  4553. if (hc > staged_rollable) {
  4554. HASH_ITER(hh, staged_work, work, tmp) {
  4555. if (!work_rollable(work))
  4556. break;
  4557. }
  4558. } else
  4559. work = staged_work;
  4560. HASH_DEL(staged_work, work);
  4561. if (work_rollable(work))
  4562. staged_rollable--;
  4563. /* Signal the getwork scheduler to look for more work */
  4564. pthread_cond_signal(&gws_cond);
  4565. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  4566. pthread_cond_signal(&getq->cond);
  4567. mutex_unlock(stgd_lock);
  4568. return work;
  4569. }
  4570. /* Clones work by rolling it if possible, and returning a clone instead of the
  4571. * original work item which gets staged again to possibly be rolled again in
  4572. * the future */
  4573. static struct work *clone_work(struct work *work)
  4574. {
  4575. int mrs = mining_threads + opt_queue - total_staged();
  4576. struct work *work_clone;
  4577. bool cloned;
  4578. if (mrs < 1)
  4579. return work;
  4580. cloned = false;
  4581. work_clone = make_clone(work);
  4582. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4583. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4584. stage_work(work_clone);
  4585. roll_work(work);
  4586. work_clone = make_clone(work);
  4587. /* Roll it again to prevent duplicates should this be used
  4588. * directly later on */
  4589. roll_work(work);
  4590. cloned = true;
  4591. }
  4592. if (cloned) {
  4593. stage_work(work);
  4594. return work_clone;
  4595. }
  4596. free_work(work_clone);
  4597. return work;
  4598. }
  4599. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  4600. {
  4601. unsigned char hash1[32];
  4602. sha2(data, len, hash1);
  4603. sha2(hash1, 32, hash);
  4604. }
  4605. /* Diff 1 is a 256 bit unsigned integer of
  4606. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  4607. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  4608. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  4609. void set_target(unsigned char *dest_target, double diff)
  4610. {
  4611. unsigned char target[32];
  4612. uint64_t *data64, h64;
  4613. double d64;
  4614. d64 = diffone;
  4615. d64 /= diff;
  4616. h64 = d64;
  4617. memset(target, 0, 32);
  4618. if (h64) {
  4619. unsigned char rtarget[32];
  4620. memset(rtarget, 0, 32);
  4621. if (opt_scrypt)
  4622. data64 = (uint64_t *)(rtarget + 2);
  4623. else
  4624. data64 = (uint64_t *)(rtarget + 4);
  4625. *data64 = htobe64(h64);
  4626. swab256(target, rtarget);
  4627. } else {
  4628. /* Support for the classic all FFs just-below-1 diff */
  4629. if (opt_scrypt)
  4630. memset(target, 0xff, 30);
  4631. else
  4632. memset(target, 0xff, 28);
  4633. }
  4634. if (opt_debug) {
  4635. char *htarget = bin2hex(target, 32);
  4636. applog(LOG_DEBUG, "Generated target %s", htarget);
  4637. free(htarget);
  4638. }
  4639. memcpy(dest_target, target, 32);
  4640. }
  4641. /* Generates stratum based work based on the most recent notify information
  4642. * from the pool. This will keep generating work while a pool is down so we use
  4643. * other means to detect when the pool has died in stratum_thread */
  4644. static void gen_stratum_work(struct pool *pool, struct work *work)
  4645. {
  4646. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  4647. char *header, *merkle_hash;
  4648. uint32_t *data32, *swap32;
  4649. size_t alloc_len;
  4650. int i;
  4651. /* Use intermediate lock to update the one pool variable */
  4652. cg_ilock(&pool->data_lock);
  4653. /* Generate coinbase */
  4654. work->nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  4655. pool->nonce2++;
  4656. /* Downgrade to a read lock to read off the pool variables */
  4657. cg_dlock(&pool->data_lock);
  4658. alloc_len = pool->swork.cb_len;
  4659. align_len(&alloc_len);
  4660. coinbase = calloc(alloc_len, 1);
  4661. if (unlikely(!coinbase))
  4662. quit(1, "Failed to calloc coinbase in gen_stratum_work");
  4663. hex2bin(coinbase, pool->swork.coinbase1, pool->swork.cb1_len);
  4664. hex2bin(coinbase + pool->swork.cb1_len, pool->nonce1, pool->n1_len);
  4665. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len, work->nonce2, pool->n2size);
  4666. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len + pool->n2size, pool->swork.coinbase2, pool->swork.cb2_len);
  4667. /* Generate merkle root */
  4668. gen_hash(coinbase, merkle_root, pool->swork.cb_len);
  4669. free(coinbase);
  4670. memcpy(merkle_sha, merkle_root, 32);
  4671. for (i = 0; i < pool->swork.merkles; i++) {
  4672. unsigned char merkle_bin[32];
  4673. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  4674. memcpy(merkle_sha + 32, merkle_bin, 32);
  4675. gen_hash(merkle_sha, merkle_root, 64);
  4676. memcpy(merkle_sha, merkle_root, 32);
  4677. }
  4678. data32 = (uint32_t *)merkle_sha;
  4679. swap32 = (uint32_t *)merkle_root;
  4680. flip32(swap32, data32);
  4681. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  4682. header = calloc(pool->swork.header_len, 1);
  4683. if (unlikely(!header))
  4684. quit(1, "Failed to calloc header in gen_stratum_work");
  4685. sprintf(header, "%s%s%s%s%s%s%s",
  4686. pool->swork.bbversion,
  4687. pool->swork.prev_hash,
  4688. merkle_hash,
  4689. pool->swork.ntime,
  4690. pool->swork.nbit,
  4691. "00000000", /* nonce */
  4692. workpadding);
  4693. /* Store the stratum work diff to check it still matches the pool's
  4694. * stratum diff when submitting shares */
  4695. work->sdiff = pool->swork.diff;
  4696. /* Copy parameters required for share submission */
  4697. work->job_id = strdup(pool->swork.job_id);
  4698. work->nonce1 = strdup(pool->nonce1);
  4699. work->ntime = strdup(pool->swork.ntime);
  4700. cg_runlock(&pool->data_lock);
  4701. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  4702. applog(LOG_DEBUG, "Generated stratum header %s", header);
  4703. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  4704. free(merkle_hash);
  4705. /* Convert hex data to binary data for work */
  4706. if (unlikely(!hex2bin(work->data, header, 128)))
  4707. quit(1, "Failed to convert header to data in gen_stratum_work");
  4708. free(header);
  4709. calc_midstate(work);
  4710. set_target(work->target, work->sdiff);
  4711. local_work++;
  4712. work->pool = pool;
  4713. work->stratum = true;
  4714. work->blk.nonce = 0;
  4715. work->id = total_work++;
  4716. work->longpoll = false;
  4717. work->getwork_mode = GETWORK_MODE_STRATUM;
  4718. work->work_block = work_block;
  4719. calc_diff(work, work->sdiff);
  4720. cgtime(&work->tv_staged);
  4721. }
  4722. static struct work *get_work(struct thr_info *thr, const int thr_id)
  4723. {
  4724. struct work *work = NULL;
  4725. /* Tell the watchdog thread this thread is waiting on getwork and
  4726. * should not be restarted */
  4727. thread_reportout(thr);
  4728. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4729. while (!work) {
  4730. work = hash_pop();
  4731. if (stale_work(work, false)) {
  4732. discard_work(work);
  4733. work = NULL;
  4734. wake_gws();
  4735. }
  4736. }
  4737. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  4738. work->thr_id = thr_id;
  4739. thread_reportin(thr);
  4740. work->mined = true;
  4741. return work;
  4742. }
  4743. static void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  4744. {
  4745. struct work *work = copy_work(work_in);
  4746. struct pool *pool = work->pool;
  4747. pthread_t submit_thread;
  4748. if (tv_work_found)
  4749. copy_time(&work->tv_work_found, tv_work_found);
  4750. if (stale_work(work, true)) {
  4751. if (opt_submit_stale)
  4752. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4753. else if (pool->submit_old)
  4754. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4755. else {
  4756. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4757. sharelog("discard", work);
  4758. mutex_lock(&stats_lock);
  4759. total_stale++;
  4760. pool->stale_shares++;
  4761. total_diff_stale += work->work_difficulty;
  4762. pool->diff_stale += work->work_difficulty;
  4763. mutex_unlock(&stats_lock);
  4764. free_work(work);
  4765. return;
  4766. }
  4767. work->stale = true;
  4768. }
  4769. if (work->stratum) {
  4770. applog(LOG_DEBUG, "Pushing pool %d work to stratum queue", pool->pool_no);
  4771. if (unlikely(!tq_push(pool->stratum_q, work))) {
  4772. applog(LOG_DEBUG, "Discarding work from removed pool");
  4773. free_work(work);
  4774. }
  4775. } else {
  4776. applog(LOG_DEBUG, "Pushing submit work to work thread");
  4777. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  4778. quit(1, "Failed to create submit_work_thread");
  4779. }
  4780. }
  4781. void inc_hw_errors(struct thr_info *thr)
  4782. {
  4783. mutex_lock(&stats_lock);
  4784. hw_errors++;
  4785. thr->cgpu->hw_errors++;
  4786. mutex_unlock(&stats_lock);
  4787. thr->cgpu->drv->hw_error(thr);
  4788. }
  4789. /* Returns true if nonce for work was a valid share */
  4790. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4791. {
  4792. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  4793. struct timeval tv_work_found;
  4794. unsigned char hash2[32];
  4795. uint32_t *hash2_32 = (uint32_t *)hash2;
  4796. uint32_t diff1targ;
  4797. bool ret = true;
  4798. thread_reportout(thr);
  4799. cgtime(&tv_work_found);
  4800. *work_nonce = htole32(nonce);
  4801. mutex_lock(&stats_lock);
  4802. total_diff1 += work->device_diff;
  4803. thr->cgpu->diff1 += work->device_diff;
  4804. work->pool->diff1 += work->device_diff;
  4805. mutex_unlock(&stats_lock);
  4806. /* Do one last check before attempting to submit the work */
  4807. rebuild_hash(work);
  4808. flip32(hash2_32, work->hash);
  4809. diff1targ = opt_scrypt ? 0x0000ffffUL : 0;
  4810. if (be32toh(hash2_32[7]) > diff1targ) {
  4811. applog(LOG_WARNING, "%s%d: invalid nonce - HW error",
  4812. thr->cgpu->drv->name, thr->cgpu->device_id);
  4813. inc_hw_errors(thr);
  4814. ret = false;
  4815. goto out;
  4816. }
  4817. mutex_lock(&stats_lock);
  4818. thr->cgpu->last_device_valid_work = time(NULL);
  4819. mutex_unlock(&stats_lock);
  4820. if (!fulltest(hash2, work->target)) {
  4821. applog(LOG_INFO, "Share below target");
  4822. goto out;
  4823. }
  4824. submit_work_async(work, &tv_work_found);
  4825. out:
  4826. thread_reportin(thr);
  4827. return ret;
  4828. }
  4829. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  4830. {
  4831. if (wdiff->tv_sec > opt_scantime ||
  4832. work->blk.nonce >= MAXTHREADS - hashes ||
  4833. hashes >= 0xfffffffe ||
  4834. stale_work(work, false))
  4835. return true;
  4836. return false;
  4837. }
  4838. static void mt_disable(struct thr_info *mythr, const int thr_id,
  4839. struct device_drv *drv)
  4840. {
  4841. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4842. mythr->rolling = mythr->cgpu->rolling = 0;
  4843. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  4844. thread_reportout(mythr);
  4845. do {
  4846. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4847. } while (mythr->pause);
  4848. thread_reportin(mythr);
  4849. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4850. drv->thread_enable(mythr);
  4851. }
  4852. /* The main hashing loop for devices that are slow enough to work on one work
  4853. * item at a time, without a queue, aborting work before the entire nonce
  4854. * range has been hashed if needed. */
  4855. static void hash_sole_work(struct thr_info *mythr)
  4856. {
  4857. const int thr_id = mythr->id;
  4858. struct cgpu_info *cgpu = mythr->cgpu;
  4859. struct device_drv *drv = cgpu->drv;
  4860. struct timeval getwork_start, tv_start, *tv_end, tv_workstart, tv_lastupdate;
  4861. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  4862. struct cgminer_stats *pool_stats;
  4863. /* Try to cycle approximately 5 times before each log update */
  4864. const long cycle = opt_log_interval / 5 ? : 1;
  4865. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  4866. struct timeval diff, sdiff, wdiff = {0, 0};
  4867. uint32_t max_nonce = drv->can_limit_work(mythr);
  4868. int64_t hashes_done = 0;
  4869. tv_end = &getwork_start;
  4870. cgtime(&getwork_start);
  4871. sdiff.tv_sec = sdiff.tv_usec = 0;
  4872. cgtime(&tv_lastupdate);
  4873. while (likely(!cgpu->shutdown)) {
  4874. struct work *work = get_work(mythr, thr_id);
  4875. int64_t hashes;
  4876. mythr->work_restart = false;
  4877. cgpu->new_work = true;
  4878. cgtime(&tv_workstart);
  4879. work->blk.nonce = 0;
  4880. cgpu->max_hashes = 0;
  4881. if (!drv->prepare_work(mythr, work)) {
  4882. applog(LOG_ERR, "work prepare failed, exiting "
  4883. "mining thread %d", thr_id);
  4884. break;
  4885. }
  4886. work->device_diff = MIN(drv->working_diff, work->work_difficulty);
  4887. #ifdef USE_SCRYPT
  4888. /* Dynamically adjust the working diff even if the target
  4889. * diff is very high to ensure we can still validate scrypt is
  4890. * returning shares. */
  4891. if (opt_scrypt) {
  4892. double wu;
  4893. wu = total_diff1 / total_secs * 60;
  4894. if (wu > 30 && drv->working_diff < drv->max_diff &&
  4895. drv->working_diff < work->work_difficulty) {
  4896. drv->working_diff++;
  4897. applog(LOG_DEBUG, "Driver %s working diff changed to %.0f",
  4898. drv->dname, drv->working_diff);
  4899. work->device_diff = MIN(drv->working_diff, work->work_difficulty);
  4900. } else if (drv->working_diff > work->work_difficulty)
  4901. drv->working_diff = work->work_difficulty;
  4902. set_target(work->device_target, work->device_diff);
  4903. }
  4904. #endif
  4905. do {
  4906. cgtime(&tv_start);
  4907. subtime(&tv_start, &getwork_start);
  4908. addtime(&getwork_start, &dev_stats->getwork_wait);
  4909. if (time_more(&getwork_start, &dev_stats->getwork_wait_max))
  4910. copy_time(&dev_stats->getwork_wait_max, &getwork_start);
  4911. if (time_less(&getwork_start, &dev_stats->getwork_wait_min))
  4912. copy_time(&dev_stats->getwork_wait_min, &getwork_start);
  4913. dev_stats->getwork_calls++;
  4914. pool_stats = &(work->pool->cgminer_stats);
  4915. addtime(&getwork_start, &pool_stats->getwork_wait);
  4916. if (time_more(&getwork_start, &pool_stats->getwork_wait_max))
  4917. copy_time(&pool_stats->getwork_wait_max, &getwork_start);
  4918. if (time_less(&getwork_start, &pool_stats->getwork_wait_min))
  4919. copy_time(&pool_stats->getwork_wait_min, &getwork_start);
  4920. pool_stats->getwork_calls++;
  4921. cgtime(&(work->tv_work_start));
  4922. thread_reportin(mythr);
  4923. /* Only allow the mining thread to be cancelled when
  4924. * it is not in the driver code. */
  4925. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  4926. hashes = drv->scanhash(mythr, work, work->blk.nonce + max_nonce);
  4927. thread_reportin(mythr);
  4928. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  4929. pthread_testcancel();
  4930. /* tv_end is == &getwork_start */
  4931. cgtime(&getwork_start);
  4932. if (unlikely(hashes == -1)) {
  4933. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  4934. cgpu->deven = DEV_DISABLED;
  4935. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  4936. mt_disable(mythr, thr_id, drv);
  4937. }
  4938. hashes_done += hashes;
  4939. if (hashes > cgpu->max_hashes)
  4940. cgpu->max_hashes = hashes;
  4941. timersub(tv_end, &tv_start, &diff);
  4942. sdiff.tv_sec += diff.tv_sec;
  4943. sdiff.tv_usec += diff.tv_usec;
  4944. if (sdiff.tv_usec > 1000000) {
  4945. ++sdiff.tv_sec;
  4946. sdiff.tv_usec -= 1000000;
  4947. }
  4948. timersub(tv_end, &tv_workstart, &wdiff);
  4949. if (unlikely((long)sdiff.tv_sec < cycle)) {
  4950. int mult;
  4951. if (likely(max_nonce == 0xffffffff))
  4952. continue;
  4953. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  4954. mult *= cycle;
  4955. if (max_nonce > (0xffffffff * 0x400) / mult)
  4956. max_nonce = 0xffffffff;
  4957. else
  4958. max_nonce = (max_nonce * mult) / 0x400;
  4959. } else if (unlikely(sdiff.tv_sec > cycle))
  4960. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  4961. else if (unlikely(sdiff.tv_usec > 100000))
  4962. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  4963. timersub(tv_end, &tv_lastupdate, &diff);
  4964. /* Update the hashmeter at most 5 times per second */
  4965. if (diff.tv_sec > 0 || diff.tv_usec > 200) {
  4966. hashmeter(thr_id, &diff, hashes_done);
  4967. hashes_done = 0;
  4968. copy_time(&tv_lastupdate, tv_end);
  4969. }
  4970. if (unlikely(mythr->work_restart)) {
  4971. /* Apart from device_thread 0, we stagger the
  4972. * starting of every next thread to try and get
  4973. * all devices busy before worrying about
  4974. * getting work for their extra threads */
  4975. if (!primary) {
  4976. struct timespec rgtp;
  4977. rgtp.tv_sec = 0;
  4978. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  4979. nanosleep(&rgtp, NULL);
  4980. }
  4981. break;
  4982. }
  4983. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  4984. mt_disable(mythr, thr_id, drv);
  4985. sdiff.tv_sec = sdiff.tv_usec = 0;
  4986. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  4987. free_work(work);
  4988. }
  4989. cgpu->deven = DEV_DISABLED;
  4990. }
  4991. /* Create a hashtable of work items for devices with a queue. The device
  4992. * driver must have a custom queue_full function or it will default to true
  4993. * and put only one work item in the queue. Work items should not be removed
  4994. * from this hashtable until they are no longer in use anywhere. Once a work
  4995. * item is physically queued on the device itself, the work->queued flag
  4996. * should be set under cgpu->qlock write lock to prevent it being dereferenced
  4997. * while still in use. */
  4998. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  4999. {
  5000. thread_reportout(mythr);
  5001. do {
  5002. bool need_work;
  5003. rd_lock(&cgpu->qlock);
  5004. need_work = (HASH_COUNT(cgpu->queued_work) == cgpu->queued_count);
  5005. rd_unlock(&cgpu->qlock);
  5006. if (need_work) {
  5007. struct work *work = get_work(mythr, thr_id);
  5008. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  5009. wr_lock(&cgpu->qlock);
  5010. HASH_ADD_INT(cgpu->queued_work, id, work);
  5011. wr_unlock(&cgpu->qlock);
  5012. }
  5013. /* The queue_full function should be used by the driver to
  5014. * actually place work items on the physical device if it
  5015. * does have a queue. */
  5016. } while (!drv->queue_full(cgpu));
  5017. }
  5018. /* This function is for retrieving one work item from the queued hashtable of
  5019. * available work items that are not yet physically on a device (which is
  5020. * flagged with the work->queued bool). Code using this function must be able
  5021. * to handle NULL as a return which implies there is no work available. */
  5022. struct work *get_queued(struct cgpu_info *cgpu)
  5023. {
  5024. struct work *work, *tmp, *ret = NULL;
  5025. wr_lock(&cgpu->qlock);
  5026. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  5027. if (!work->queued) {
  5028. work->queued = true;
  5029. cgpu->queued_count++;
  5030. ret = work;
  5031. break;
  5032. }
  5033. }
  5034. wr_unlock(&cgpu->qlock);
  5035. return ret;
  5036. }
  5037. /* This function is for finding an already queued work item in the
  5038. * given que hashtable. Code using this function must be able
  5039. * to handle NULL as a return which implies there is no matching work.
  5040. * The calling function must lock access to the que if it is required.
  5041. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  5042. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  5043. {
  5044. struct work *work, *tmp, *ret = NULL;
  5045. HASH_ITER(hh, que, work, tmp) {
  5046. if (work->queued &&
  5047. memcmp(work->midstate, midstate, midstatelen) == 0 &&
  5048. memcmp(work->data + offset, data, datalen) == 0) {
  5049. ret = work;
  5050. break;
  5051. }
  5052. }
  5053. return ret;
  5054. }
  5055. /* This function is for finding an already queued work item in the
  5056. * device's queued_work hashtable. Code using this function must be able
  5057. * to handle NULL as a return which implies there is no matching work.
  5058. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  5059. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  5060. {
  5061. struct work *ret;
  5062. rd_lock(&cgpu->qlock);
  5063. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  5064. rd_unlock(&cgpu->qlock);
  5065. return ret;
  5066. }
  5067. /* This function should be used by queued device drivers when they're sure
  5068. * the work struct is no longer in use. */
  5069. void work_completed(struct cgpu_info *cgpu, struct work *work)
  5070. {
  5071. wr_lock(&cgpu->qlock);
  5072. if (work->queued)
  5073. cgpu->queued_count--;
  5074. HASH_DEL(cgpu->queued_work, work);
  5075. wr_unlock(&cgpu->qlock);
  5076. free_work(work);
  5077. }
  5078. static void flush_queue(struct cgpu_info *cgpu)
  5079. {
  5080. struct work *work, *tmp;
  5081. int discarded = 0;
  5082. wr_lock(&cgpu->qlock);
  5083. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  5084. /* Can only discard the work items if they're not physically
  5085. * queued on the device. */
  5086. if (!work->queued) {
  5087. HASH_DEL(cgpu->queued_work, work);
  5088. discard_work(work);
  5089. discarded++;
  5090. }
  5091. }
  5092. wr_unlock(&cgpu->qlock);
  5093. if (discarded)
  5094. applog(LOG_DEBUG, "Discarded %d queued work items", discarded);
  5095. }
  5096. /* This version of hash work is for devices that are fast enough to always
  5097. * perform a full nonce range and need a queue to maintain the device busy.
  5098. * Work creation and destruction is not done from within this function
  5099. * directly. */
  5100. void hash_queued_work(struct thr_info *mythr)
  5101. {
  5102. struct timeval tv_start = {0, 0}, tv_end;
  5103. struct cgpu_info *cgpu = mythr->cgpu;
  5104. struct device_drv *drv = cgpu->drv;
  5105. const int thr_id = mythr->id;
  5106. int64_t hashes_done = 0;
  5107. while (likely(!cgpu->shutdown)) {
  5108. struct timeval diff;
  5109. int64_t hashes;
  5110. mythr->work_restart = false;
  5111. fill_queue(mythr, cgpu, drv, thr_id);
  5112. thread_reportin(mythr);
  5113. hashes = drv->scanwork(mythr);
  5114. if (unlikely(hashes == -1 )) {
  5115. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  5116. cgpu->deven = DEV_DISABLED;
  5117. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  5118. mt_disable(mythr, thr_id, drv);
  5119. }
  5120. hashes_done += hashes;
  5121. cgtime(&tv_end);
  5122. timersub(&tv_end, &tv_start, &diff);
  5123. /* Update the hashmeter at most 5 times per second */
  5124. if (diff.tv_sec > 0 || diff.tv_usec > 200) {
  5125. hashmeter(thr_id, &diff, hashes_done);
  5126. hashes_done = 0;
  5127. copy_time(&tv_start, &tv_end);
  5128. }
  5129. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  5130. mt_disable(mythr, thr_id, drv);
  5131. if (unlikely(mythr->work_restart)) {
  5132. flush_queue(cgpu);
  5133. drv->flush_work(cgpu);
  5134. }
  5135. }
  5136. cgpu->deven = DEV_DISABLED;
  5137. }
  5138. void *miner_thread(void *userdata)
  5139. {
  5140. struct thr_info *mythr = userdata;
  5141. const int thr_id = mythr->id;
  5142. struct cgpu_info *cgpu = mythr->cgpu;
  5143. struct device_drv *drv = cgpu->drv;
  5144. char threadname[24];
  5145. snprintf(threadname, 24, "miner/%d", thr_id);
  5146. RenameThread(threadname);
  5147. if (!drv->thread_init(mythr)) {
  5148. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  5149. goto out;
  5150. }
  5151. thread_reportout(mythr);
  5152. applog(LOG_DEBUG, "Popping ping in miner thread");
  5153. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  5154. drv->hash_work(mythr);
  5155. out:
  5156. drv->thread_shutdown(mythr);
  5157. thread_reportin(mythr);
  5158. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  5159. tq_freeze(mythr->q);
  5160. return NULL;
  5161. }
  5162. enum {
  5163. STAT_SLEEP_INTERVAL = 1,
  5164. STAT_CTR_INTERVAL = 10000000,
  5165. FAILURE_INTERVAL = 30,
  5166. };
  5167. /* Stage another work item from the work returned in a longpoll */
  5168. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  5169. {
  5170. struct work *work;
  5171. bool rc;
  5172. work = make_work();
  5173. rc = work_decode(pool, work, val);
  5174. if (unlikely(!rc)) {
  5175. applog(LOG_ERR, "Could not convert longpoll data to work");
  5176. free_work(work);
  5177. return;
  5178. }
  5179. total_getworks++;
  5180. pool->getwork_requested++;
  5181. work->pool = pool;
  5182. work->rolltime = rolltime;
  5183. copy_time(&work->tv_getwork, tv_lp);
  5184. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  5185. calc_diff(work, 0);
  5186. if (pool->enabled == POOL_REJECTING)
  5187. work->mandatory = true;
  5188. if (pool->has_gbt)
  5189. gen_gbt_work(pool, work);
  5190. work->longpoll = true;
  5191. work->getwork_mode = GETWORK_MODE_LP;
  5192. /* We'll be checking this work item twice, but we already know it's
  5193. * from a new block so explicitly force the new block detection now
  5194. * rather than waiting for it to hit the stage thread. This also
  5195. * allows testwork to know whether LP discovered the block or not. */
  5196. test_work_current(work);
  5197. /* Don't use backup LPs as work if we have failover-only enabled. Use
  5198. * the longpoll work from a pool that has been rejecting shares as a
  5199. * way to detect when the pool has recovered.
  5200. */
  5201. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  5202. free_work(work);
  5203. return;
  5204. }
  5205. work = clone_work(work);
  5206. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  5207. stage_work(work);
  5208. applog(LOG_DEBUG, "Converted longpoll data to work");
  5209. }
  5210. /* If we want longpoll, enable it for the chosen default pool, or, if
  5211. * the pool does not support longpoll, find the first one that does
  5212. * and use its longpoll support */
  5213. static struct pool *select_longpoll_pool(struct pool *cp)
  5214. {
  5215. int i;
  5216. if (cp->hdr_path || cp->has_gbt)
  5217. return cp;
  5218. for (i = 0; i < total_pools; i++) {
  5219. struct pool *pool = pools[i];
  5220. if (pool->has_stratum || pool->hdr_path)
  5221. return pool;
  5222. }
  5223. return NULL;
  5224. }
  5225. /* This will make the longpoll thread wait till it's the current pool, or it
  5226. * has been flagged as rejecting, before attempting to open any connections.
  5227. */
  5228. static void wait_lpcurrent(struct pool *pool)
  5229. {
  5230. if (cnx_needed(pool))
  5231. return;
  5232. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5233. mutex_lock(&lp_lock);
  5234. pthread_cond_wait(&lp_cond, &lp_lock);
  5235. mutex_unlock(&lp_lock);
  5236. }
  5237. }
  5238. static void *longpoll_thread(void *userdata)
  5239. {
  5240. struct pool *cp = (struct pool *)userdata;
  5241. /* This *pool is the source of the actual longpoll, not the pool we've
  5242. * tied it to */
  5243. struct timeval start, reply, end;
  5244. struct pool *pool = NULL;
  5245. char threadname[16];
  5246. CURL *curl = NULL;
  5247. int failures = 0;
  5248. char lpreq[1024];
  5249. char *lp_url;
  5250. int rolltime;
  5251. snprintf(threadname, 16, "longpoll/%d", cp->pool_no);
  5252. RenameThread(threadname);
  5253. curl = curl_easy_init();
  5254. if (unlikely(!curl)) {
  5255. applog(LOG_ERR, "CURL initialisation failed");
  5256. return NULL;
  5257. }
  5258. retry_pool:
  5259. pool = select_longpoll_pool(cp);
  5260. if (!pool) {
  5261. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  5262. while (!pool) {
  5263. nmsleep(60000);
  5264. pool = select_longpoll_pool(cp);
  5265. }
  5266. }
  5267. if (pool->has_stratum) {
  5268. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5269. cp->rpc_url, pool->rpc_url);
  5270. goto out;
  5271. }
  5272. /* Any longpoll from any pool is enough for this to be true */
  5273. have_longpoll = true;
  5274. wait_lpcurrent(cp);
  5275. if (pool->has_gbt) {
  5276. lp_url = pool->rpc_url;
  5277. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  5278. } else {
  5279. strcpy(lpreq, getwork_req);
  5280. lp_url = pool->lp_url;
  5281. if (cp == pool)
  5282. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  5283. else
  5284. applog(LOG_WARNING, "Long-polling activated for %s via %s", cp->rpc_url, lp_url);
  5285. }
  5286. while (42) {
  5287. json_t *val, *soval;
  5288. wait_lpcurrent(cp);
  5289. cgtime(&start);
  5290. /* Update the longpollid every time, but do it under lock to
  5291. * avoid races */
  5292. if (pool->has_gbt) {
  5293. cg_rlock(&pool->gbt_lock);
  5294. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  5295. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  5296. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  5297. cg_runlock(&pool->gbt_lock);
  5298. }
  5299. /* Longpoll connections can be persistent for a very long time
  5300. * and any number of issues could have come up in the meantime
  5301. * so always establish a fresh connection instead of relying on
  5302. * a persistent one. */
  5303. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  5304. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  5305. lpreq, false, true, &rolltime, pool, false);
  5306. cgtime(&reply);
  5307. if (likely(val)) {
  5308. soval = json_object_get(json_object_get(val, "result"), "submitold");
  5309. if (soval)
  5310. pool->submit_old = json_is_true(soval);
  5311. else
  5312. pool->submit_old = false;
  5313. convert_to_work(val, rolltime, pool, &start, &reply);
  5314. failures = 0;
  5315. json_decref(val);
  5316. } else {
  5317. /* Some pools regularly drop the longpoll request so
  5318. * only see this as longpoll failure if it happens
  5319. * immediately and just restart it the rest of the
  5320. * time. */
  5321. cgtime(&end);
  5322. if (end.tv_sec - start.tv_sec > 30)
  5323. continue;
  5324. if (failures == 1)
  5325. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  5326. nmsleep(30000);
  5327. }
  5328. if (pool != cp) {
  5329. pool = select_longpoll_pool(cp);
  5330. if (pool->has_stratum) {
  5331. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5332. cp->rpc_url, pool->rpc_url);
  5333. break;
  5334. }
  5335. if (unlikely(!pool))
  5336. goto retry_pool;
  5337. }
  5338. if (unlikely(pool->removed))
  5339. break;
  5340. }
  5341. out:
  5342. curl_easy_cleanup(curl);
  5343. return NULL;
  5344. }
  5345. void reinit_device(struct cgpu_info *cgpu)
  5346. {
  5347. cgpu->drv->reinit_device(cgpu);
  5348. }
  5349. static struct timeval rotate_tv;
  5350. /* We reap curls if they are unused for over a minute */
  5351. static void reap_curl(struct pool *pool)
  5352. {
  5353. struct curl_ent *ent, *iter;
  5354. struct timeval now;
  5355. int reaped = 0;
  5356. cgtime(&now);
  5357. mutex_lock(&pool->pool_lock);
  5358. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  5359. if (pool->curls < 2)
  5360. break;
  5361. if (now.tv_sec - ent->tv.tv_sec > 300) {
  5362. reaped++;
  5363. pool->curls--;
  5364. list_del(&ent->node);
  5365. curl_easy_cleanup(ent->curl);
  5366. free(ent);
  5367. }
  5368. }
  5369. mutex_unlock(&pool->pool_lock);
  5370. if (reaped)
  5371. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  5372. }
  5373. static void *watchpool_thread(void __maybe_unused *userdata)
  5374. {
  5375. int intervals = 0;
  5376. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5377. RenameThread("watchpool");
  5378. while (42) {
  5379. struct timeval now;
  5380. int i;
  5381. if (++intervals > 20)
  5382. intervals = 0;
  5383. cgtime(&now);
  5384. for (i = 0; i < total_pools; i++) {
  5385. struct pool *pool = pools[i];
  5386. if (!opt_benchmark)
  5387. reap_curl(pool);
  5388. /* Get a rolling utility per pool over 10 mins */
  5389. if (intervals > 19) {
  5390. int shares = pool->diff1 - pool->last_shares;
  5391. pool->last_shares = pool->diff1;
  5392. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  5393. pool->shares = pool->utility;
  5394. }
  5395. if (pool->enabled == POOL_DISABLED)
  5396. continue;
  5397. /* Don't start testing any pools if the test threads
  5398. * from startup are still doing their first attempt. */
  5399. if (unlikely(pool->testing)) {
  5400. pthread_join(pool->test_thread, NULL);
  5401. pool->testing = false;
  5402. }
  5403. /* Test pool is idle once every minute */
  5404. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  5405. cgtime(&pool->tv_idle);
  5406. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  5407. pool_resus(pool);
  5408. }
  5409. }
  5410. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  5411. cgtime(&rotate_tv);
  5412. switch_pools(NULL);
  5413. }
  5414. nmsleep(30000);
  5415. }
  5416. return NULL;
  5417. }
  5418. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  5419. * the screen at regular intervals, and restarts threads if they appear to have
  5420. * died. */
  5421. #define WATCHDOG_INTERVAL 2
  5422. #define WATCHDOG_SICK_TIME 60
  5423. #define WATCHDOG_DEAD_TIME 600
  5424. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  5425. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  5426. static void *watchdog_thread(void __maybe_unused *userdata)
  5427. {
  5428. const unsigned int interval = WATCHDOG_INTERVAL;
  5429. struct timeval zero_tv;
  5430. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5431. RenameThread("watchdog");
  5432. memset(&zero_tv, 0, sizeof(struct timeval));
  5433. cgtime(&rotate_tv);
  5434. while (1) {
  5435. int i;
  5436. struct timeval now;
  5437. sleep(interval);
  5438. discard_stale();
  5439. hashmeter(-1, &zero_tv, 0);
  5440. #ifdef HAVE_CURSES
  5441. if (curses_active_locked()) {
  5442. change_logwinsize();
  5443. curses_print_status();
  5444. for (i = 0; i < mining_threads; i++)
  5445. curses_print_devstatus(i);
  5446. touchwin(statuswin);
  5447. wrefresh(statuswin);
  5448. touchwin(logwin);
  5449. wrefresh(logwin);
  5450. unlock_curses();
  5451. }
  5452. #endif
  5453. cgtime(&now);
  5454. if (!sched_paused && !should_run()) {
  5455. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  5456. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5457. if (!schedstart.enable) {
  5458. quit(0, "Terminating execution as planned");
  5459. break;
  5460. }
  5461. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  5462. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5463. sched_paused = true;
  5464. rd_lock(&mining_thr_lock);
  5465. for (i = 0; i < mining_threads; i++)
  5466. mining_thr[i]->pause = true;
  5467. rd_unlock(&mining_thr_lock);
  5468. } else if (sched_paused && should_run()) {
  5469. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  5470. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5471. if (schedstop.enable)
  5472. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  5473. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5474. sched_paused = false;
  5475. for (i = 0; i < mining_threads; i++) {
  5476. struct thr_info *thr;
  5477. thr = get_thread(i);
  5478. /* Don't touch disabled devices */
  5479. if (thr->cgpu->deven == DEV_DISABLED)
  5480. continue;
  5481. thr->pause = false;
  5482. tq_push(thr->q, &ping);
  5483. }
  5484. }
  5485. for (i = 0; i < total_devices; ++i) {
  5486. struct cgpu_info *cgpu = get_devices(i);
  5487. struct thr_info *thr = cgpu->thr[0];
  5488. enum dev_enable *denable;
  5489. char dev_str[8];
  5490. int gpu;
  5491. cgpu->drv->get_stats(cgpu);
  5492. gpu = cgpu->device_id;
  5493. denable = &cgpu->deven;
  5494. sprintf(dev_str, "%s%d", cgpu->drv->name, gpu);
  5495. #ifdef HAVE_ADL
  5496. if (adl_active && cgpu->has_adl)
  5497. gpu_autotune(gpu, denable);
  5498. if (opt_debug && cgpu->has_adl) {
  5499. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  5500. float temp = 0, vddc = 0;
  5501. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  5502. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  5503. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  5504. }
  5505. #endif
  5506. /* Thread is waiting on getwork or disabled */
  5507. if (thr->getwork || *denable == DEV_DISABLED)
  5508. continue;
  5509. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  5510. if (cgpu->status != LIFE_INIT)
  5511. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  5512. cgpu->status = LIFE_WELL;
  5513. cgpu->device_last_well = time(NULL);
  5514. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  5515. thr->rolling = cgpu->rolling = 0;
  5516. cgpu->status = LIFE_SICK;
  5517. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  5518. cgtime(&thr->sick);
  5519. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  5520. #ifdef HAVE_ADL
  5521. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5522. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  5523. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  5524. } else
  5525. #endif
  5526. if (opt_restart) {
  5527. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  5528. reinit_device(cgpu);
  5529. }
  5530. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  5531. cgpu->status = LIFE_DEAD;
  5532. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  5533. cgtime(&thr->sick);
  5534. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  5535. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  5536. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  5537. /* Attempt to restart a GPU that's sick or dead once every minute */
  5538. cgtime(&thr->sick);
  5539. #ifdef HAVE_ADL
  5540. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5541. /* Again do not attempt to restart a device that may have hard hung */
  5542. } else
  5543. #endif
  5544. if (opt_restart)
  5545. reinit_device(cgpu);
  5546. }
  5547. }
  5548. }
  5549. return NULL;
  5550. }
  5551. static void log_print_status(struct cgpu_info *cgpu)
  5552. {
  5553. char logline[255];
  5554. get_statline(logline, cgpu);
  5555. applog(LOG_WARNING, "%s", logline);
  5556. }
  5557. void print_summary(void)
  5558. {
  5559. struct timeval diff;
  5560. int hours, mins, secs, i;
  5561. double utility, displayed_hashes, work_util;
  5562. bool mhash_base = true;
  5563. timersub(&total_tv_end, &total_tv_start, &diff);
  5564. hours = diff.tv_sec / 3600;
  5565. mins = (diff.tv_sec % 3600) / 60;
  5566. secs = diff.tv_sec % 60;
  5567. utility = total_accepted / total_secs * 60;
  5568. work_util = total_diff1 / total_secs * 60;
  5569. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  5570. applog(LOG_WARNING, "Started at %s", datestamp);
  5571. if (total_pools == 1)
  5572. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  5573. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  5574. displayed_hashes = total_mhashes_done / total_secs;
  5575. if (displayed_hashes < 1) {
  5576. displayed_hashes *= 1000;
  5577. mhash_base = false;
  5578. }
  5579. applog(LOG_WARNING, "Average hashrate: %.1f %shash/s", displayed_hashes, mhash_base? "Mega" : "Kilo");
  5580. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  5581. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  5582. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  5583. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  5584. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  5585. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  5586. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  5587. if (total_accepted || total_rejected)
  5588. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  5589. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  5590. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  5591. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  5592. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  5593. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  5594. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  5595. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  5596. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  5597. if (total_pools > 1) {
  5598. for (i = 0; i < total_pools; i++) {
  5599. struct pool *pool = pools[i];
  5600. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  5601. if (pool->solved)
  5602. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  5603. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  5604. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  5605. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  5606. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  5607. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  5608. if (pool->accepted || pool->rejected)
  5609. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  5610. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  5611. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  5612. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  5613. }
  5614. }
  5615. applog(LOG_WARNING, "Summary of per device statistics:\n");
  5616. for (i = 0; i < total_devices; ++i) {
  5617. struct cgpu_info *cgpu = get_devices(i);
  5618. log_print_status(cgpu);
  5619. }
  5620. if (opt_shares) {
  5621. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  5622. if (opt_shares > total_accepted)
  5623. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  5624. }
  5625. applog(LOG_WARNING, " ");
  5626. fflush(stderr);
  5627. fflush(stdout);
  5628. }
  5629. static void clean_up(void)
  5630. {
  5631. #ifdef HAVE_OPENCL
  5632. clear_adl(nDevs);
  5633. #endif
  5634. #ifdef HAVE_LIBUSB
  5635. libusb_exit(NULL);
  5636. #endif
  5637. cgtime(&total_tv_end);
  5638. #ifdef HAVE_CURSES
  5639. disable_curses();
  5640. #endif
  5641. if (!opt_realquiet && successful_connect)
  5642. print_summary();
  5643. curl_global_cleanup();
  5644. }
  5645. void quit(int status, const char *format, ...)
  5646. {
  5647. if (format) {
  5648. va_list ap;
  5649. va_start(ap, format);
  5650. vapplog(LOG_ERR, format, ap);
  5651. va_end(ap);
  5652. }
  5653. clean_up();
  5654. #if defined(unix)
  5655. if (forkpid > 0) {
  5656. kill(forkpid, SIGTERM);
  5657. forkpid = 0;
  5658. }
  5659. #endif
  5660. exit(status);
  5661. }
  5662. #ifdef HAVE_CURSES
  5663. char *curses_input(const char *query)
  5664. {
  5665. char *input;
  5666. echo();
  5667. input = malloc(255);
  5668. if (!input)
  5669. quit(1, "Failed to malloc input");
  5670. leaveok(logwin, false);
  5671. wlogprint("%s:\n", query);
  5672. wgetnstr(logwin, input, 255);
  5673. if (!strlen(input))
  5674. strcpy(input, "-1");
  5675. leaveok(logwin, true);
  5676. noecho();
  5677. return input;
  5678. }
  5679. #endif
  5680. static bool pools_active = false;
  5681. static void *test_pool_thread(void *arg)
  5682. {
  5683. struct pool *pool = (struct pool *)arg;
  5684. if (pool_active(pool, false)) {
  5685. pool_tset(pool, &pool->lagging);
  5686. pool_tclear(pool, &pool->idle);
  5687. bool first_pool = false;
  5688. cg_wlock(&control_lock);
  5689. if (!pools_active) {
  5690. currentpool = pool;
  5691. if (pool->pool_no != 0)
  5692. first_pool = true;
  5693. pools_active = true;
  5694. }
  5695. cg_wunlock(&control_lock);
  5696. if (unlikely(first_pool))
  5697. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  5698. pool_resus(pool);
  5699. } else
  5700. pool_died(pool);
  5701. return NULL;
  5702. }
  5703. /* Always returns true that the pool details were added unless we are not
  5704. * live, implying this is the only pool being added, so if no pools are
  5705. * active it returns false. */
  5706. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  5707. {
  5708. url = get_proxy(url, pool);
  5709. pool->rpc_url = url;
  5710. pool->rpc_user = user;
  5711. pool->rpc_pass = pass;
  5712. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5713. if (!pool->rpc_userpass)
  5714. quit(1, "Failed to malloc userpass");
  5715. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5716. pool->testing = true;
  5717. pool->idle = true;
  5718. enable_pool(pool);
  5719. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  5720. if (!live) {
  5721. pthread_join(pool->test_thread, NULL);
  5722. pool->testing = false;
  5723. return pools_active;
  5724. }
  5725. return true;
  5726. }
  5727. #ifdef HAVE_CURSES
  5728. static bool input_pool(bool live)
  5729. {
  5730. char *url = NULL, *user = NULL, *pass = NULL;
  5731. struct pool *pool;
  5732. bool ret = false;
  5733. immedok(logwin, true);
  5734. wlogprint("Input server details.\n");
  5735. url = curses_input("URL");
  5736. if (!url)
  5737. goto out;
  5738. user = curses_input("Username");
  5739. if (!user)
  5740. goto out;
  5741. pass = curses_input("Password");
  5742. if (!pass)
  5743. goto out;
  5744. pool = add_pool();
  5745. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  5746. strncmp(url, "https://", 8)) {
  5747. char *httpinput;
  5748. httpinput = malloc(256);
  5749. if (!httpinput)
  5750. quit(1, "Failed to malloc httpinput");
  5751. strcpy(httpinput, "http://");
  5752. strncat(httpinput, url, 248);
  5753. free(url);
  5754. url = httpinput;
  5755. }
  5756. ret = add_pool_details(pool, live, url, user, pass);
  5757. out:
  5758. immedok(logwin, false);
  5759. if (!ret) {
  5760. if (url)
  5761. free(url);
  5762. if (user)
  5763. free(user);
  5764. if (pass)
  5765. free(pass);
  5766. }
  5767. return ret;
  5768. }
  5769. #endif
  5770. #if defined(unix)
  5771. static void fork_monitor()
  5772. {
  5773. // Make a pipe: [readFD, writeFD]
  5774. int pfd[2];
  5775. int r = pipe(pfd);
  5776. if (r < 0) {
  5777. perror("pipe - failed to create pipe for --monitor");
  5778. exit(1);
  5779. }
  5780. // Make stderr write end of pipe
  5781. fflush(stderr);
  5782. r = dup2(pfd[1], 2);
  5783. if (r < 0) {
  5784. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  5785. exit(1);
  5786. }
  5787. r = close(pfd[1]);
  5788. if (r < 0) {
  5789. perror("close - failed to close write end of pipe for --monitor");
  5790. exit(1);
  5791. }
  5792. // Don't allow a dying monitor to kill the main process
  5793. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  5794. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  5795. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  5796. perror("signal - failed to edit signal mask for --monitor");
  5797. exit(1);
  5798. }
  5799. // Fork a child process
  5800. forkpid = fork();
  5801. if (forkpid < 0) {
  5802. perror("fork - failed to fork child process for --monitor");
  5803. exit(1);
  5804. }
  5805. // Child: launch monitor command
  5806. if (0 == forkpid) {
  5807. // Make stdin read end of pipe
  5808. r = dup2(pfd[0], 0);
  5809. if (r < 0) {
  5810. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  5811. exit(1);
  5812. }
  5813. close(pfd[0]);
  5814. if (r < 0) {
  5815. perror("close - in child, failed to close read end of pipe for --monitor");
  5816. exit(1);
  5817. }
  5818. // Launch user specified command
  5819. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  5820. perror("execl - in child failed to exec user specified command for --monitor");
  5821. exit(1);
  5822. }
  5823. // Parent: clean up unused fds and bail
  5824. r = close(pfd[0]);
  5825. if (r < 0) {
  5826. perror("close - failed to close read end of pipe for --monitor");
  5827. exit(1);
  5828. }
  5829. }
  5830. #endif // defined(unix)
  5831. #ifdef HAVE_CURSES
  5832. void enable_curses(void) {
  5833. int x,y;
  5834. lock_curses();
  5835. if (curses_active) {
  5836. unlock_curses();
  5837. return;
  5838. }
  5839. mainwin = initscr();
  5840. getmaxyx(mainwin, y, x);
  5841. statuswin = newwin(logstart, x, 0, 0);
  5842. leaveok(statuswin, true);
  5843. logwin = newwin(y - logcursor, 0, logcursor, 0);
  5844. idlok(logwin, true);
  5845. scrollok(logwin, true);
  5846. leaveok(logwin, true);
  5847. cbreak();
  5848. noecho();
  5849. curses_active = true;
  5850. statusy = logstart;
  5851. unlock_curses();
  5852. }
  5853. #endif
  5854. #ifdef USE_BFLSC
  5855. extern struct device_drv bflsc_drv;
  5856. #endif
  5857. #ifdef USE_BITFORCE
  5858. extern struct device_drv bitforce_drv;
  5859. #endif
  5860. #ifdef USE_ICARUS
  5861. extern struct device_drv icarus_drv;
  5862. #endif
  5863. #ifdef USE_AVALON
  5864. extern struct device_drv avalon_drv;
  5865. #endif
  5866. #ifdef USE_MODMINER
  5867. extern struct device_drv modminer_drv;
  5868. #endif
  5869. #ifdef USE_ZTEX
  5870. extern struct device_drv ztex_drv;
  5871. #endif
  5872. static int cgminer_id_count = 0;
  5873. /* Various noop functions for drivers that don't support or need their
  5874. * variants. */
  5875. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  5876. {
  5877. }
  5878. void blank_get_statline_before(char *buf, struct cgpu_info __maybe_unused *cgpu)
  5879. {
  5880. tailsprintf(buf, " | ");
  5881. }
  5882. static void noop_get_statline(char __maybe_unused *buf, struct cgpu_info __maybe_unused *cgpu)
  5883. {
  5884. }
  5885. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  5886. {
  5887. return true;
  5888. }
  5889. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  5890. {
  5891. return true;
  5892. }
  5893. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  5894. {
  5895. return 0xffffffff;
  5896. }
  5897. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  5898. {
  5899. return true;
  5900. }
  5901. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  5902. {
  5903. return true;
  5904. }
  5905. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  5906. {
  5907. }
  5908. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  5909. {
  5910. }
  5911. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  5912. {
  5913. }
  5914. #define noop_flush_work noop_reinit_device
  5915. #define noop_queue_full noop_get_stats
  5916. /* Fill missing driver drv functions with noops */
  5917. void fill_device_drv(struct cgpu_info *cgpu)
  5918. {
  5919. struct device_drv *drv = cgpu->drv;
  5920. if (!drv->reinit_device)
  5921. drv->reinit_device = &noop_reinit_device;
  5922. if (!drv->get_statline_before)
  5923. drv->get_statline_before = &blank_get_statline_before;
  5924. if (!drv->get_statline)
  5925. drv->get_statline = &noop_get_statline;
  5926. if (!drv->get_stats)
  5927. drv->get_stats = &noop_get_stats;
  5928. if (!drv->thread_prepare)
  5929. drv->thread_prepare = &noop_thread_prepare;
  5930. if (!drv->can_limit_work)
  5931. drv->can_limit_work = &noop_can_limit_work;
  5932. if (!drv->thread_init)
  5933. drv->thread_init = &noop_thread_init;
  5934. if (!drv->prepare_work)
  5935. drv->prepare_work = &noop_prepare_work;
  5936. if (!drv->hw_error)
  5937. drv->hw_error = &noop_hw_error;
  5938. if (!drv->thread_shutdown)
  5939. drv->thread_shutdown = &noop_thread_shutdown;
  5940. if (!drv->thread_enable)
  5941. drv->thread_enable = &noop_thread_enable;
  5942. if (!drv->hash_work)
  5943. drv->hash_work = &hash_sole_work;
  5944. if (!drv->flush_work)
  5945. drv->flush_work = &noop_flush_work;
  5946. if (!drv->queue_full)
  5947. drv->queue_full = &noop_queue_full;
  5948. if (!drv->max_diff)
  5949. drv->max_diff = 1;
  5950. if (!drv->working_diff)
  5951. drv->working_diff = 1;
  5952. }
  5953. void enable_device(struct cgpu_info *cgpu)
  5954. {
  5955. cgpu->deven = DEV_ENABLED;
  5956. wr_lock(&devices_lock);
  5957. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  5958. wr_unlock(&devices_lock);
  5959. if (hotplug_mode) {
  5960. new_threads += cgpu->threads;
  5961. #ifdef HAVE_CURSES
  5962. adj_width(mining_threads + new_threads, &dev_width);
  5963. #endif
  5964. } else {
  5965. mining_threads += cgpu->threads;
  5966. #ifdef HAVE_CURSES
  5967. adj_width(mining_threads, &dev_width);
  5968. #endif
  5969. }
  5970. #ifdef HAVE_OPENCL
  5971. if (cgpu->drv->drv_id == DRIVER_OPENCL) {
  5972. gpu_threads += cgpu->threads;
  5973. }
  5974. #endif
  5975. fill_device_drv(cgpu);
  5976. rwlock_init(&cgpu->qlock);
  5977. cgpu->queued_work = NULL;
  5978. }
  5979. struct _cgpu_devid_counter {
  5980. char name[4];
  5981. int lastid;
  5982. UT_hash_handle hh;
  5983. };
  5984. bool add_cgpu(struct cgpu_info *cgpu)
  5985. {
  5986. static struct _cgpu_devid_counter *devids = NULL;
  5987. struct _cgpu_devid_counter *d;
  5988. HASH_FIND_STR(devids, cgpu->drv->name, d);
  5989. if (d)
  5990. cgpu->device_id = ++d->lastid;
  5991. else {
  5992. d = malloc(sizeof(*d));
  5993. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  5994. cgpu->device_id = d->lastid = 0;
  5995. HASH_ADD_STR(devids, name, d);
  5996. }
  5997. wr_lock(&devices_lock);
  5998. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + new_devices + 2));
  5999. wr_unlock(&devices_lock);
  6000. mutex_lock(&stats_lock);
  6001. cgpu->last_device_valid_work = time(NULL);
  6002. mutex_unlock(&stats_lock);
  6003. if (hotplug_mode)
  6004. devices[total_devices + new_devices++] = cgpu;
  6005. else
  6006. devices[total_devices++] = cgpu;
  6007. return true;
  6008. }
  6009. struct device_drv *copy_drv(struct device_drv *drv)
  6010. {
  6011. struct device_drv *copy;
  6012. char buf[100];
  6013. if (unlikely(!(copy = malloc(sizeof(*copy))))) {
  6014. sprintf(buf, "Failed to allocate device_drv copy of %s (%s)",
  6015. drv->name, drv->copy ? "copy" : "original");
  6016. quit(1, buf);
  6017. }
  6018. memcpy(copy, drv, sizeof(*copy));
  6019. copy->copy = true;
  6020. return copy;
  6021. }
  6022. #ifdef USE_USBUTILS
  6023. static void hotplug_process()
  6024. {
  6025. struct thr_info *thr;
  6026. int i, j;
  6027. for (i = 0; i < new_devices; i++) {
  6028. struct cgpu_info *cgpu = devices[total_devices + i];
  6029. enable_device(cgpu);
  6030. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6031. cgpu->rolling = cgpu->total_mhashes = 0;
  6032. }
  6033. wr_lock(&mining_thr_lock);
  6034. mining_thr = realloc(mining_thr, sizeof(thr) * (mining_threads + new_threads + 1));
  6035. wr_unlock(&mining_thr_lock);
  6036. if (!mining_thr)
  6037. quit(1, "Failed to hotplug realloc mining_thr");
  6038. for (i = 0; i < new_threads; i++) {
  6039. mining_thr[mining_threads + i] = calloc(1, sizeof(*thr));
  6040. if (!mining_thr[mining_threads + i])
  6041. quit(1, "Failed to hotplug calloc mining_thr[%d]", i);
  6042. }
  6043. // Start threads
  6044. for (i = 0; i < new_devices; ++i) {
  6045. struct cgpu_info *cgpu = devices[total_devices];
  6046. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  6047. cgpu->thr[cgpu->threads] = NULL;
  6048. cgpu->status = LIFE_INIT;
  6049. for (j = 0; j < cgpu->threads; ++j) {
  6050. thr = get_thread(mining_threads);
  6051. thr->id = mining_threads;
  6052. thr->cgpu = cgpu;
  6053. thr->device_thread = j;
  6054. thr->q = tq_new();
  6055. if (!thr->q)
  6056. quit(1, "tq_new hotplug failed in starting %s%d mining thread (#%d)", cgpu->drv->name, cgpu->device_id, total_devices);
  6057. /* Enable threads for devices set not to mine but disable
  6058. * their queue in case we wish to enable them later */
  6059. if (cgpu->deven != DEV_DISABLED) {
  6060. applog(LOG_DEBUG, "Pushing hotplug ping to thread %d", thr->id);
  6061. tq_push(thr->q, &ping);
  6062. }
  6063. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  6064. continue;
  6065. thread_reportout(thr);
  6066. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  6067. quit(1, "hotplug thread %d create failed", thr->id);
  6068. cgpu->thr[j] = thr;
  6069. mining_threads++;
  6070. }
  6071. total_devices++;
  6072. applog(LOG_WARNING, "Hotplug: %s added %s %i", cgpu->drv->dname, cgpu->drv->name, cgpu->device_id);
  6073. }
  6074. }
  6075. static void *hotplug_thread(void __maybe_unused *userdata)
  6076. {
  6077. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6078. RenameThread("hotplug");
  6079. hotplug_mode = true;
  6080. nmsleep(5000);
  6081. while (0x2a) {
  6082. // Version 0.1 just add the devices on - worry about using nodev later
  6083. if (hotplug_time == 0)
  6084. nmsleep(5000);
  6085. else {
  6086. new_devices = 0;
  6087. new_threads = 0;
  6088. #ifdef USE_ICARUS
  6089. icarus_drv.drv_detect();
  6090. #endif
  6091. #ifdef USE_BFLSC
  6092. bflsc_drv.drv_detect();
  6093. #endif
  6094. #ifdef USE_BITFORCE
  6095. bitforce_drv.drv_detect();
  6096. #endif
  6097. #ifdef USE_MODMINER
  6098. modminer_drv.drv_detect();
  6099. #endif
  6100. #ifdef USE_AVALON
  6101. avalon_drv.drv_detect();
  6102. #endif
  6103. if (new_devices)
  6104. hotplug_process();
  6105. // hotplug_time >0 && <=9999
  6106. nmsleep(hotplug_time * 1000);
  6107. }
  6108. }
  6109. return NULL;
  6110. }
  6111. #endif
  6112. static void probe_pools(void)
  6113. {
  6114. int i;
  6115. for (i = 0; i < total_pools; i++) {
  6116. struct pool *pool = pools[i];
  6117. pool->testing = true;
  6118. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  6119. }
  6120. }
  6121. int main(int argc, char *argv[])
  6122. {
  6123. struct sigaction handler;
  6124. struct thr_info *thr;
  6125. struct block *block;
  6126. unsigned int k;
  6127. int i, j;
  6128. char *s;
  6129. /* This dangerous functions tramples random dynamically allocated
  6130. * variables so do it before anything at all */
  6131. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  6132. quit(1, "Failed to curl_global_init");
  6133. initial_args = malloc(sizeof(char *) * (argc + 1));
  6134. for (i = 0; i < argc; i++)
  6135. initial_args[i] = strdup(argv[i]);
  6136. initial_args[argc] = NULL;
  6137. #ifdef HAVE_LIBUSB
  6138. int err = libusb_init(NULL);
  6139. if (err) {
  6140. fprintf(stderr, "libusb_init() failed err %d", err);
  6141. fflush(stderr);
  6142. quit(1, "libusb_init() failed");
  6143. }
  6144. #ifdef USE_USBUTILS
  6145. mutex_init(&cgusb_lock);
  6146. mutex_init(&cgusbres_lock);
  6147. #endif
  6148. #endif
  6149. mutex_init(&hash_lock);
  6150. mutex_init(&console_lock);
  6151. cglock_init(&control_lock);
  6152. mutex_init(&stats_lock);
  6153. mutex_init(&sharelog_lock);
  6154. cglock_init(&ch_lock);
  6155. mutex_init(&sshare_lock);
  6156. rwlock_init(&blk_lock);
  6157. rwlock_init(&netacc_lock);
  6158. rwlock_init(&mining_thr_lock);
  6159. rwlock_init(&devices_lock);
  6160. mutex_init(&lp_lock);
  6161. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  6162. quit(1, "Failed to pthread_cond_init lp_cond");
  6163. mutex_init(&restart_lock);
  6164. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  6165. quit(1, "Failed to pthread_cond_init restart_cond");
  6166. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  6167. quit(1, "Failed to pthread_cond_init gws_cond");
  6168. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  6169. handler.sa_handler = &sighandler;
  6170. handler.sa_flags = 0;
  6171. sigemptyset(&handler.sa_mask);
  6172. sigaction(SIGTERM, &handler, &termhandler);
  6173. sigaction(SIGINT, &handler, &inthandler);
  6174. #ifndef WIN32
  6175. signal(SIGPIPE, SIG_IGN);
  6176. #endif
  6177. opt_kernel_path = alloca(PATH_MAX);
  6178. strcpy(opt_kernel_path, CGMINER_PREFIX);
  6179. cgminer_path = alloca(PATH_MAX);
  6180. s = strdup(argv[0]);
  6181. strcpy(cgminer_path, dirname(s));
  6182. free(s);
  6183. strcat(cgminer_path, "/");
  6184. devcursor = 8;
  6185. logstart = devcursor + 1;
  6186. logcursor = logstart + 1;
  6187. block = calloc(sizeof(struct block), 1);
  6188. if (unlikely(!block))
  6189. quit (1, "main OOM");
  6190. for (i = 0; i < 36; i++)
  6191. strcat(block->hash, "0");
  6192. HASH_ADD_STR(blocks, hash, block);
  6193. strcpy(current_block, block->hash);
  6194. INIT_LIST_HEAD(&scan_devices);
  6195. #ifdef HAVE_OPENCL
  6196. memset(gpus, 0, sizeof(gpus));
  6197. for (i = 0; i < MAX_GPUDEVICES; i++)
  6198. gpus[i].dynamic = true;
  6199. #endif
  6200. /* parse command line */
  6201. opt_register_table(opt_config_table,
  6202. "Options for both config file and command line");
  6203. opt_register_table(opt_cmdline_table,
  6204. "Options for command line only");
  6205. opt_parse(&argc, argv, applog_and_exit);
  6206. if (argc != 1)
  6207. quit(1, "Unexpected extra commandline arguments");
  6208. if (!config_loaded)
  6209. load_default_config();
  6210. if (opt_benchmark) {
  6211. struct pool *pool;
  6212. pool = add_pool();
  6213. pool->rpc_url = malloc(255);
  6214. strcpy(pool->rpc_url, "Benchmark");
  6215. pool->rpc_user = pool->rpc_url;
  6216. pool->rpc_pass = pool->rpc_url;
  6217. enable_pool(pool);
  6218. pool->idle = false;
  6219. successful_connect = true;
  6220. }
  6221. #ifdef HAVE_CURSES
  6222. if (opt_realquiet || devices_enabled == -1)
  6223. use_curses = false;
  6224. if (use_curses)
  6225. enable_curses();
  6226. #endif
  6227. applog(LOG_WARNING, "Started %s", packagename);
  6228. if (cnfbuf) {
  6229. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  6230. switch (fileconf_load) {
  6231. case 0:
  6232. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  6233. applog(LOG_WARNING, "Configuration file could not be used.");
  6234. break;
  6235. case -1:
  6236. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  6237. if (use_curses)
  6238. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  6239. break;
  6240. default:
  6241. break;
  6242. }
  6243. free(cnfbuf);
  6244. cnfbuf = NULL;
  6245. }
  6246. strcat(opt_kernel_path, "/");
  6247. if (want_per_device_stats)
  6248. opt_log_output = true;
  6249. /* Use a shorter scantime for scrypt */
  6250. if (opt_scantime < 0)
  6251. opt_scantime = opt_scrypt ? 30 : 60;
  6252. total_control_threads = 9;
  6253. control_thr = calloc(total_control_threads, sizeof(*thr));
  6254. if (!control_thr)
  6255. quit(1, "Failed to calloc control_thr");
  6256. gwsched_thr_id = 0;
  6257. #ifdef USE_USBUTILS
  6258. usb_initialise();
  6259. // before device detection
  6260. if (!opt_scrypt) {
  6261. if (sem_init(&usb_resource_sem, 0, 0))
  6262. quit(1, "Failed to sem_init usb_resource_sem");
  6263. usbres_thr_id = 1;
  6264. thr = &control_thr[usbres_thr_id];
  6265. if (thr_info_create(thr, NULL, usb_resource_thread, thr))
  6266. quit(1, "usb resource thread create failed");
  6267. pthread_detach(thr->pth);
  6268. }
  6269. #endif
  6270. #ifdef HAVE_OPENCL
  6271. if (!opt_nogpu)
  6272. opencl_drv.drv_detect();
  6273. gpu_threads = 0;
  6274. #endif
  6275. #ifdef USE_ICARUS
  6276. if (!opt_scrypt)
  6277. icarus_drv.drv_detect();
  6278. #endif
  6279. #ifdef USE_BFLSC
  6280. if (!opt_scrypt)
  6281. bflsc_drv.drv_detect();
  6282. #endif
  6283. #ifdef USE_BITFORCE
  6284. if (!opt_scrypt)
  6285. bitforce_drv.drv_detect();
  6286. #endif
  6287. #ifdef USE_MODMINER
  6288. if (!opt_scrypt)
  6289. modminer_drv.drv_detect();
  6290. #endif
  6291. #ifdef USE_ZTEX
  6292. if (!opt_scrypt)
  6293. ztex_drv.drv_detect();
  6294. #endif
  6295. /* Detect avalon last since it will try to claim the device regardless
  6296. * as detection is unreliable. */
  6297. #ifdef USE_AVALON
  6298. if (!opt_scrypt)
  6299. avalon_drv.drv_detect();
  6300. #endif
  6301. if (devices_enabled == -1) {
  6302. applog(LOG_ERR, "Devices detected:");
  6303. for (i = 0; i < total_devices; ++i) {
  6304. struct cgpu_info *cgpu = devices[i];
  6305. if (cgpu->name)
  6306. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->name, cgpu->drv->dname);
  6307. else
  6308. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->drv->dname);
  6309. }
  6310. quit(0, "%d devices listed", total_devices);
  6311. }
  6312. mining_threads = 0;
  6313. if (devices_enabled) {
  6314. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  6315. if (devices_enabled & (1 << i)) {
  6316. if (i >= total_devices)
  6317. quit (1, "Command line options set a device that doesn't exist");
  6318. enable_device(devices[i]);
  6319. } else if (i < total_devices) {
  6320. if (!opt_removedisabled)
  6321. enable_device(devices[i]);
  6322. devices[i]->deven = DEV_DISABLED;
  6323. }
  6324. }
  6325. total_devices = cgminer_id_count;
  6326. } else {
  6327. for (i = 0; i < total_devices; ++i)
  6328. enable_device(devices[i]);
  6329. }
  6330. #ifdef USE_USBUTILS
  6331. if (!total_devices) {
  6332. applog(LOG_WARNING, "No devices detected!");
  6333. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  6334. }
  6335. #else
  6336. if (!total_devices)
  6337. quit(1, "All devices disabled, cannot mine!");
  6338. #endif
  6339. start_devices = total_devices;
  6340. load_temp_cutoffs();
  6341. for (i = 0; i < total_devices; ++i)
  6342. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6343. if (!opt_compact) {
  6344. logstart += total_devices;
  6345. logcursor = logstart + 1;
  6346. #ifdef HAVE_CURSES
  6347. check_winsizes();
  6348. #endif
  6349. }
  6350. if (!total_pools) {
  6351. applog(LOG_WARNING, "Need to specify at least one pool server.");
  6352. #ifdef HAVE_CURSES
  6353. if (!use_curses || !input_pool(false))
  6354. #endif
  6355. quit(1, "Pool setup failed");
  6356. }
  6357. for (i = 0; i < total_pools; i++) {
  6358. struct pool *pool = pools[i];
  6359. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6360. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6361. if (!pool->rpc_userpass) {
  6362. if (!pool->rpc_user || !pool->rpc_pass)
  6363. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  6364. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6365. if (!pool->rpc_userpass)
  6366. quit(1, "Failed to malloc userpass");
  6367. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6368. }
  6369. }
  6370. /* Set the currentpool to pool 0 */
  6371. currentpool = pools[0];
  6372. #ifdef HAVE_SYSLOG_H
  6373. if (use_syslog)
  6374. openlog(PACKAGE, LOG_PID, LOG_USER);
  6375. #endif
  6376. #if defined(unix)
  6377. if (opt_stderr_cmd)
  6378. fork_monitor();
  6379. #endif // defined(unix)
  6380. mining_thr = calloc(mining_threads, sizeof(thr));
  6381. if (!mining_thr)
  6382. quit(1, "Failed to calloc mining_thr");
  6383. for (i = 0; i < mining_threads; i++) {
  6384. mining_thr[i] = calloc(1, sizeof(*thr));
  6385. if (!mining_thr[i])
  6386. quit(1, "Failed to calloc mining_thr[%d]", i);
  6387. }
  6388. stage_thr_id = 2;
  6389. thr = &control_thr[stage_thr_id];
  6390. thr->q = tq_new();
  6391. if (!thr->q)
  6392. quit(1, "Failed to tq_new");
  6393. /* start stage thread */
  6394. if (thr_info_create(thr, NULL, stage_thread, thr))
  6395. quit(1, "stage thread create failed");
  6396. pthread_detach(thr->pth);
  6397. /* Create a unique get work queue */
  6398. getq = tq_new();
  6399. if (!getq)
  6400. quit(1, "Failed to create getq");
  6401. /* We use the getq mutex as the staged lock */
  6402. stgd_lock = &getq->mutex;
  6403. if (opt_benchmark)
  6404. goto begin_bench;
  6405. for (i = 0; i < total_pools; i++) {
  6406. struct pool *pool = pools[i];
  6407. enable_pool(pool);
  6408. pool->idle = true;
  6409. }
  6410. applog(LOG_NOTICE, "Probing for an alive pool");
  6411. do {
  6412. int slept = 0;
  6413. /* Look for at least one active pool before starting */
  6414. probe_pools();
  6415. do {
  6416. sleep(1);
  6417. slept++;
  6418. } while (!pools_active && slept < 60);
  6419. if (!pools_active) {
  6420. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  6421. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  6422. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  6423. for (i = 0; i < total_pools; i++) {
  6424. struct pool *pool;
  6425. pool = pools[i];
  6426. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  6427. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  6428. }
  6429. #ifdef HAVE_CURSES
  6430. if (use_curses) {
  6431. halfdelay(150);
  6432. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  6433. if (getch() != ERR)
  6434. quit(0, "No servers could be used! Exiting.");
  6435. cbreak();
  6436. } else
  6437. #endif
  6438. quit(0, "No servers could be used! Exiting.");
  6439. }
  6440. } while (!pools_active);
  6441. begin_bench:
  6442. total_mhashes_done = 0;
  6443. for (i = 0; i < total_devices; i++) {
  6444. struct cgpu_info *cgpu = devices[i];
  6445. cgpu->rolling = cgpu->total_mhashes = 0;
  6446. }
  6447. cgtime(&total_tv_start);
  6448. cgtime(&total_tv_end);
  6449. get_datestamp(datestamp, &total_tv_start);
  6450. // Start threads
  6451. k = 0;
  6452. for (i = 0; i < total_devices; ++i) {
  6453. struct cgpu_info *cgpu = devices[i];
  6454. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  6455. cgpu->thr[cgpu->threads] = NULL;
  6456. cgpu->status = LIFE_INIT;
  6457. for (j = 0; j < cgpu->threads; ++j, ++k) {
  6458. thr = get_thread(k);
  6459. thr->id = k;
  6460. thr->cgpu = cgpu;
  6461. thr->device_thread = j;
  6462. thr->q = tq_new();
  6463. if (!thr->q)
  6464. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->drv->name, cgpu->device_id, i);
  6465. /* Enable threads for devices set not to mine but disable
  6466. * their queue in case we wish to enable them later */
  6467. if (cgpu->deven != DEV_DISABLED) {
  6468. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  6469. tq_push(thr->q, &ping);
  6470. }
  6471. if (!cgpu->drv->thread_prepare(thr))
  6472. continue;
  6473. thread_reportout(thr);
  6474. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  6475. quit(1, "thread %d create failed", thr->id);
  6476. cgpu->thr[j] = thr;
  6477. }
  6478. }
  6479. #ifdef HAVE_OPENCL
  6480. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  6481. for (i = 0; i < nDevs; i++)
  6482. pause_dynamic_threads(i);
  6483. #endif
  6484. cgtime(&total_tv_start);
  6485. cgtime(&total_tv_end);
  6486. watchpool_thr_id = 3;
  6487. thr = &control_thr[watchpool_thr_id];
  6488. /* start watchpool thread */
  6489. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  6490. quit(1, "watchpool thread create failed");
  6491. pthread_detach(thr->pth);
  6492. watchdog_thr_id = 4;
  6493. thr = &control_thr[watchdog_thr_id];
  6494. /* start watchdog thread */
  6495. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  6496. quit(1, "watchdog thread create failed");
  6497. pthread_detach(thr->pth);
  6498. #ifdef HAVE_OPENCL
  6499. /* Create reinit gpu thread */
  6500. gpur_thr_id = 5;
  6501. thr = &control_thr[gpur_thr_id];
  6502. thr->q = tq_new();
  6503. if (!thr->q)
  6504. quit(1, "tq_new failed for gpur_thr_id");
  6505. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  6506. quit(1, "reinit_gpu thread create failed");
  6507. #endif
  6508. /* Create API socket thread */
  6509. api_thr_id = 6;
  6510. thr = &control_thr[api_thr_id];
  6511. if (thr_info_create(thr, NULL, api_thread, thr))
  6512. quit(1, "API thread create failed");
  6513. #ifdef USE_USBUTILS
  6514. if (!opt_scrypt) {
  6515. hotplug_thr_id = 7;
  6516. thr = &control_thr[hotplug_thr_id];
  6517. if (thr_info_create(thr, NULL, hotplug_thread, thr))
  6518. quit(1, "hotplug thread create failed");
  6519. pthread_detach(thr->pth);
  6520. }
  6521. #endif
  6522. #ifdef HAVE_CURSES
  6523. /* Create curses input thread for keyboard input. Create this last so
  6524. * that we know all threads are created since this can call kill_work
  6525. * to try and shut down all previous threads. */
  6526. input_thr_id = 8;
  6527. thr = &control_thr[input_thr_id];
  6528. if (thr_info_create(thr, NULL, input_thread, thr))
  6529. quit(1, "input thread create failed");
  6530. pthread_detach(thr->pth);
  6531. #endif
  6532. /* Just to be sure */
  6533. if (total_control_threads != 9)
  6534. quit(1, "incorrect total_control_threads (%d) should be 9", total_control_threads);
  6535. /* Once everything is set up, main() becomes the getwork scheduler */
  6536. while (42) {
  6537. int ts, max_staged = opt_queue;
  6538. struct pool *pool, *cp;
  6539. bool lagging = false;
  6540. struct curl_ent *ce;
  6541. struct work *work;
  6542. cp = current_pool();
  6543. /* If the primary pool is a getwork pool and cannot roll work,
  6544. * try to stage one extra work per mining thread */
  6545. if (!cp->has_stratum && !cp->has_gbt && !staged_rollable)
  6546. max_staged += mining_threads;
  6547. mutex_lock(stgd_lock);
  6548. ts = __total_staged();
  6549. if (!cp->has_stratum && !cp->has_gbt && !ts && !opt_fail_only)
  6550. lagging = true;
  6551. /* Wait until hash_pop tells us we need to create more work */
  6552. if (ts > max_staged) {
  6553. pthread_cond_wait(&gws_cond, stgd_lock);
  6554. ts = __total_staged();
  6555. }
  6556. mutex_unlock(stgd_lock);
  6557. if (ts > max_staged)
  6558. continue;
  6559. work = make_work();
  6560. if (lagging && !pool_tset(cp, &cp->lagging)) {
  6561. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  6562. cp->getfail_occasions++;
  6563. total_go++;
  6564. }
  6565. pool = select_pool(lagging);
  6566. retry:
  6567. if (pool->has_stratum) {
  6568. while (!pool->stratum_active || !pool->stratum_notify) {
  6569. struct pool *altpool = select_pool(true);
  6570. nmsleep(5000);
  6571. if (altpool != pool) {
  6572. pool = altpool;
  6573. goto retry;
  6574. }
  6575. }
  6576. gen_stratum_work(pool, work);
  6577. applog(LOG_DEBUG, "Generated stratum work");
  6578. stage_work(work);
  6579. continue;
  6580. }
  6581. if (pool->has_gbt) {
  6582. while (pool->idle) {
  6583. struct pool *altpool = select_pool(true);
  6584. nmsleep(5000);
  6585. if (altpool != pool) {
  6586. pool = altpool;
  6587. goto retry;
  6588. }
  6589. }
  6590. gen_gbt_work(pool, work);
  6591. applog(LOG_DEBUG, "Generated GBT work");
  6592. stage_work(work);
  6593. continue;
  6594. }
  6595. if (clone_available()) {
  6596. applog(LOG_DEBUG, "Cloned getwork work");
  6597. free_work(work);
  6598. continue;
  6599. }
  6600. if (opt_benchmark) {
  6601. get_benchmark_work(work);
  6602. applog(LOG_DEBUG, "Generated benchmark work");
  6603. stage_work(work);
  6604. continue;
  6605. }
  6606. work->pool = pool;
  6607. ce = pop_curl_entry(pool);
  6608. /* obtain new work from bitcoin via JSON-RPC */
  6609. if (!get_upstream_work(work, ce->curl)) {
  6610. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  6611. /* Make sure the pool just hasn't stopped serving
  6612. * requests but is up as we'll keep hammering it */
  6613. if (++pool->seq_getfails > mining_threads + opt_queue)
  6614. pool_died(pool);
  6615. nmsleep(5000);
  6616. push_curl_entry(ce, pool);
  6617. pool = select_pool(!opt_fail_only);
  6618. goto retry;
  6619. }
  6620. if (ts >= max_staged)
  6621. pool_tclear(pool, &pool->lagging);
  6622. if (pool_tclear(pool, &pool->idle))
  6623. pool_resus(pool);
  6624. applog(LOG_DEBUG, "Generated getwork work");
  6625. stage_work(work);
  6626. push_curl_entry(ce, pool);
  6627. }
  6628. return 0;
  6629. }