cgminer.c 199 KB

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