cgminer.c 181 KB

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