cgminer.c 200 KB

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