cgminer.c 185 KB

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