cgminer.c 205 KB

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