cgminer.c 199 KB

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