cgminer.c 183 KB

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