cgminer.c 182 KB

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