cgminer.c 181 KB

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