cgminer.c 204 KB

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