cgminer.c 184 KB

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