cgminer.c 200 KB

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