cgminer.c 197 KB

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