cgminer.c 203 KB

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