cgminer.c 182 KB

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