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 = -1;
  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. mvwprintw(statuswin, 3, 0, " ST: %d SS: %d DW: %d NB: %d LW: %d GF: %d RF: %d WU: %.1f",
  1753. total_staged(), total_stale, total_discarded, new_blocks,
  1754. local_work, total_go, total_ro, total_diff1 / total_secs * 60);
  1755. wclrtoeol(statuswin);
  1756. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  1757. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1758. have_longpoll ? "": "out");
  1759. } else if (pool->has_stratum) {
  1760. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  1761. pool->sockaddr_url, pool->diff, pool->rpc_user);
  1762. } else {
  1763. mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s %s as user %s",
  1764. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out",
  1765. pool->has_gbt ? "GBT" : "LP", pool->rpc_user);
  1766. }
  1767. wclrtoeol(statuswin);
  1768. cg_rlock(&ch_lock);
  1769. mvwprintw(statuswin, 5, 0, " Block: %s... Diff:%s Started: %s Best share: %s ",
  1770. current_hash, block_diff, blocktime, best_share);
  1771. cg_runlock(&ch_lock);
  1772. mvwhline(statuswin, 6, 0, '-', 80);
  1773. mvwhline(statuswin, statusy - 1, 0, '-', 80);
  1774. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1775. have_opencl ? "[G]PU management " : "");
  1776. }
  1777. static void adj_width(int var, int *length)
  1778. {
  1779. if ((int)(log10(var) + 1) > *length)
  1780. (*length)++;
  1781. }
  1782. static int dev_width;
  1783. static void curses_print_devstatus(int thr_id)
  1784. {
  1785. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1786. struct cgpu_info *cgpu;
  1787. char logline[256];
  1788. char displayed_hashes[16], displayed_rolling[16];
  1789. uint64_t dh64, dr64;
  1790. if (opt_compact)
  1791. return;
  1792. cgpu = get_thr_cgpu(thr_id);
  1793. if (cgpu->cgminer_id >= start_devices || devcursor + cgpu->cgminer_id > LINES - 2)
  1794. return;
  1795. cgpu->utility = cgpu->accepted / total_secs * 60;
  1796. wmove(statuswin,devcursor + cgpu->cgminer_id, 0);
  1797. wprintw(statuswin, " %s %*d: ", cgpu->drv->name, dev_width, cgpu->device_id);
  1798. logline[0] = '\0';
  1799. cgpu->drv->get_statline_before(logline, cgpu);
  1800. wprintw(statuswin, "%s", logline);
  1801. dh64 = (double)cgpu->total_mhashes / total_secs * 1000000ull;
  1802. dr64 = (double)cgpu->rolling * 1000000ull;
  1803. suffix_string(dh64, displayed_hashes, 4);
  1804. suffix_string(dr64, displayed_rolling, 4);
  1805. #ifdef USE_USBUTILS
  1806. if (cgpu->usbinfo.nodev)
  1807. wprintw(statuswin, "ZOMBIE");
  1808. else
  1809. #endif
  1810. if (cgpu->status == LIFE_DEAD)
  1811. wprintw(statuswin, "DEAD ");
  1812. else if (cgpu->status == LIFE_SICK)
  1813. wprintw(statuswin, "SICK ");
  1814. else if (cgpu->deven == DEV_DISABLED)
  1815. wprintw(statuswin, "OFF ");
  1816. else if (cgpu->deven == DEV_RECOVER)
  1817. wprintw(statuswin, "REST ");
  1818. else
  1819. wprintw(statuswin, "%6s", displayed_rolling);
  1820. adj_width(cgpu->accepted, &awidth);
  1821. adj_width(cgpu->rejected, &rwidth);
  1822. adj_width(cgpu->hw_errors, &hwwidth);
  1823. adj_width(cgpu->utility, &uwidth);
  1824. wprintw(statuswin, "/%6sh/s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1825. displayed_hashes,
  1826. awidth, cgpu->accepted,
  1827. rwidth, cgpu->rejected,
  1828. hwwidth, cgpu->hw_errors,
  1829. uwidth + 3, cgpu->utility);
  1830. logline[0] = '\0';
  1831. cgpu->drv->get_statline(logline, cgpu);
  1832. wprintw(statuswin, "%s", logline);
  1833. wclrtoeol(statuswin);
  1834. }
  1835. #endif
  1836. static void print_status(int thr_id)
  1837. {
  1838. if (!curses_active)
  1839. text_print_status(thr_id);
  1840. }
  1841. #ifdef HAVE_CURSES
  1842. /* Check for window resize. Called with curses mutex locked */
  1843. static inline void change_logwinsize(void)
  1844. {
  1845. int x, y, logx, logy;
  1846. getmaxyx(mainwin, y, x);
  1847. if (x < 80 || y < 25)
  1848. return;
  1849. if (y > statusy + 2 && statusy < logstart) {
  1850. if (y - 2 < logstart)
  1851. statusy = y - 2;
  1852. else
  1853. statusy = logstart;
  1854. logcursor = statusy + 1;
  1855. mvwin(logwin, logcursor, 0);
  1856. wresize(statuswin, statusy, x);
  1857. }
  1858. y -= logcursor;
  1859. getmaxyx(logwin, logy, logx);
  1860. /* Detect screen size change */
  1861. if (x != logx || y != logy)
  1862. wresize(logwin, y, x);
  1863. }
  1864. static void check_winsizes(void)
  1865. {
  1866. if (!use_curses)
  1867. return;
  1868. if (curses_active_locked()) {
  1869. int y, x;
  1870. erase();
  1871. x = getmaxx(statuswin);
  1872. if (logstart > LINES - 2)
  1873. statusy = LINES - 2;
  1874. else
  1875. statusy = logstart;
  1876. logcursor = statusy + 1;
  1877. wresize(statuswin, statusy, x);
  1878. getmaxyx(mainwin, y, x);
  1879. y -= logcursor;
  1880. wresize(logwin, y, x);
  1881. mvwin(logwin, logcursor, 0);
  1882. unlock_curses();
  1883. }
  1884. }
  1885. static void switch_compact(void)
  1886. {
  1887. if (opt_compact) {
  1888. logstart = devcursor + 1;
  1889. logcursor = logstart + 1;
  1890. } else {
  1891. logstart = devcursor + total_devices + 1;
  1892. logcursor = logstart + 1;
  1893. }
  1894. check_winsizes();
  1895. }
  1896. /* For mandatory printing when mutex is already locked */
  1897. void wlog(const char *f, ...)
  1898. {
  1899. va_list ap;
  1900. va_start(ap, f);
  1901. vw_printw(logwin, f, ap);
  1902. va_end(ap);
  1903. }
  1904. /* Mandatory printing */
  1905. void wlogprint(const char *f, ...)
  1906. {
  1907. va_list ap;
  1908. if (curses_active_locked()) {
  1909. va_start(ap, f);
  1910. vw_printw(logwin, f, ap);
  1911. va_end(ap);
  1912. unlock_curses();
  1913. }
  1914. }
  1915. #endif
  1916. #ifdef HAVE_CURSES
  1917. bool log_curses_only(int prio, const char *f, va_list ap)
  1918. {
  1919. bool high_prio;
  1920. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  1921. if (curses_active_locked()) {
  1922. if (!opt_loginput || high_prio) {
  1923. vw_printw(logwin, f, ap);
  1924. if (high_prio) {
  1925. touchwin(logwin);
  1926. wrefresh(logwin);
  1927. }
  1928. }
  1929. unlock_curses();
  1930. return true;
  1931. }
  1932. return false;
  1933. }
  1934. void clear_logwin(void)
  1935. {
  1936. if (curses_active_locked()) {
  1937. erase();
  1938. wclear(logwin);
  1939. unlock_curses();
  1940. }
  1941. }
  1942. #endif
  1943. /* Returns true if the regenerated work->hash solves a block */
  1944. static bool solves_block(const struct work *work)
  1945. {
  1946. uint32_t *hash32 = (uint32_t *)(work->hash);
  1947. uint32_t difficulty = 0;
  1948. uint32_t diffbytes = 0;
  1949. uint32_t diffvalue = 0;
  1950. uint32_t diffcmp[8];
  1951. int diffshift = 0;
  1952. int i;
  1953. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  1954. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1955. diffvalue = difficulty & 0x00ffffff;
  1956. diffshift = (diffbytes % 4) * 8;
  1957. if (diffshift == 0) {
  1958. diffshift = 32;
  1959. diffbytes--;
  1960. }
  1961. memset(diffcmp, 0, 32);
  1962. diffbytes >>= 2;
  1963. /* Sanity check looking for overflow */
  1964. if (unlikely(diffbytes > 6))
  1965. return false;
  1966. diffcmp[diffbytes + 1] = diffvalue >> (32 - diffshift);
  1967. diffcmp[diffbytes] = diffvalue << diffshift;
  1968. for (i = 7; i >= 0; i--) {
  1969. if (hash32[i] > diffcmp[i])
  1970. return false;
  1971. if (hash32[i] < diffcmp[i])
  1972. return true;
  1973. }
  1974. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1975. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1976. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1977. if (hash32[0] == diffcmp[0])
  1978. return true;
  1979. else
  1980. return false;
  1981. }
  1982. static void enable_pool(struct pool *pool)
  1983. {
  1984. if (pool->enabled != POOL_ENABLED) {
  1985. enabled_pools++;
  1986. pool->enabled = POOL_ENABLED;
  1987. }
  1988. }
  1989. static void disable_pool(struct pool *pool)
  1990. {
  1991. if (pool->enabled == POOL_ENABLED)
  1992. enabled_pools--;
  1993. pool->enabled = POOL_DISABLED;
  1994. }
  1995. static void reject_pool(struct pool *pool)
  1996. {
  1997. if (pool->enabled == POOL_ENABLED)
  1998. enabled_pools--;
  1999. pool->enabled = POOL_REJECTING;
  2000. }
  2001. /* Theoretically threads could race when modifying accepted and
  2002. * rejected values but the chance of two submits completing at the
  2003. * same time is zero so there is no point adding extra locking */
  2004. static void
  2005. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2006. char *hashshow, bool resubmit, char *worktime)
  2007. {
  2008. struct pool *pool = work->pool;
  2009. struct cgpu_info *cgpu;
  2010. cgpu = get_thr_cgpu(work->thr_id);
  2011. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  2012. mutex_lock(&stats_lock);
  2013. cgpu->accepted++;
  2014. total_accepted++;
  2015. pool->accepted++;
  2016. cgpu->diff_accepted += work->work_difficulty;
  2017. total_diff_accepted += work->work_difficulty;
  2018. pool->diff_accepted += work->work_difficulty;
  2019. mutex_unlock(&stats_lock);
  2020. pool->seq_rejects = 0;
  2021. cgpu->last_share_pool = pool->pool_no;
  2022. cgpu->last_share_pool_time = time(NULL);
  2023. cgpu->last_share_diff = work->work_difficulty;
  2024. pool->last_share_time = cgpu->last_share_pool_time;
  2025. pool->last_share_diff = work->work_difficulty;
  2026. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2027. if (!QUIET) {
  2028. if (total_pools > 1)
  2029. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  2030. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  2031. else
  2032. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  2033. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  2034. }
  2035. sharelog("accept", work);
  2036. if (opt_shares && total_accepted >= opt_shares) {
  2037. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2038. kill_work();
  2039. return;
  2040. }
  2041. /* Detect if a pool that has been temporarily disabled for
  2042. * continually rejecting shares has started accepting shares.
  2043. * This will only happen with the work returned from a
  2044. * longpoll */
  2045. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2046. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2047. enable_pool(pool);
  2048. switch_pools(NULL);
  2049. }
  2050. } else {
  2051. mutex_lock(&stats_lock);
  2052. cgpu->rejected++;
  2053. total_rejected++;
  2054. pool->rejected++;
  2055. cgpu->diff_rejected += work->work_difficulty;
  2056. total_diff_rejected += work->work_difficulty;
  2057. pool->diff_rejected += work->work_difficulty;
  2058. pool->seq_rejects++;
  2059. mutex_unlock(&stats_lock);
  2060. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2061. if (!QUIET) {
  2062. char where[20];
  2063. char disposition[36] = "reject";
  2064. char reason[32];
  2065. strcpy(reason, "");
  2066. if (total_pools > 1)
  2067. sprintf(where, "pool %d", work->pool->pool_no);
  2068. else
  2069. strcpy(where, "");
  2070. if (!work->gbt)
  2071. res = json_object_get(val, "reject-reason");
  2072. if (res) {
  2073. const char *reasontmp = json_string_value(res);
  2074. size_t reasonLen = strlen(reasontmp);
  2075. if (reasonLen > 28)
  2076. reasonLen = 28;
  2077. reason[0] = ' '; reason[1] = '(';
  2078. memcpy(2 + reason, reasontmp, reasonLen);
  2079. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2080. memcpy(disposition + 7, reasontmp, reasonLen);
  2081. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2082. } else if (work->stratum && err && json_is_array(err)) {
  2083. json_t *reason_val = json_array_get(err, 1);
  2084. char *reason_str;
  2085. if (reason_val && json_is_string(reason_val)) {
  2086. reason_str = (char *)json_string_value(reason_val);
  2087. snprintf(reason, 31, " (%s)", reason_str);
  2088. }
  2089. }
  2090. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2091. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2092. sharelog(disposition, work);
  2093. }
  2094. /* Once we have more than a nominal amount of sequential rejects,
  2095. * at least 10 and more than 3 mins at the current utility,
  2096. * disable the pool because some pool error is likely to have
  2097. * ensued. Do not do this if we know the share just happened to
  2098. * be stale due to networking delays.
  2099. */
  2100. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2101. double utility = total_accepted / total_secs * 60;
  2102. if (pool->seq_rejects > utility * 3) {
  2103. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2104. pool->pool_no, pool->seq_rejects);
  2105. reject_pool(pool);
  2106. if (pool == current_pool())
  2107. switch_pools(NULL);
  2108. pool->seq_rejects = 0;
  2109. }
  2110. }
  2111. }
  2112. }
  2113. static const uint64_t diffone = 0xFFFF000000000000ull;
  2114. static uint64_t share_diff(const struct work *work)
  2115. {
  2116. uint64_t *data64, d64;
  2117. char rhash[32];
  2118. uint64_t ret;
  2119. swab256(rhash, work->hash);
  2120. if (opt_scrypt)
  2121. data64 = (uint64_t *)(rhash + 2);
  2122. else
  2123. data64 = (uint64_t *)(rhash + 4);
  2124. d64 = be64toh(*data64);
  2125. if (unlikely(!d64))
  2126. d64 = 1;
  2127. ret = diffone / d64;
  2128. cg_wlock(&control_lock);
  2129. if (ret > best_diff) {
  2130. best_diff = ret;
  2131. suffix_string(best_diff, best_share, 0);
  2132. }
  2133. if (ret > work->pool->best_diff)
  2134. work->pool->best_diff = ret;
  2135. cg_wunlock(&control_lock);
  2136. return ret;
  2137. }
  2138. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2139. {
  2140. char *hexstr = NULL;
  2141. json_t *val, *res, *err;
  2142. char *s;
  2143. bool rc = false;
  2144. int thr_id = work->thr_id;
  2145. struct cgpu_info *cgpu;
  2146. struct pool *pool = work->pool;
  2147. int rolltime;
  2148. struct timeval tv_submit, tv_submit_reply;
  2149. char hashshow[64 + 4] = "";
  2150. char worktime[200] = "";
  2151. cgpu = get_thr_cgpu(thr_id);
  2152. #ifdef __BIG_ENDIAN__
  2153. int swapcounter = 0;
  2154. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  2155. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  2156. #endif
  2157. /* build hex string */
  2158. hexstr = bin2hex(work->data, sizeof(work->data));
  2159. /* build JSON-RPC request */
  2160. if (work->gbt) {
  2161. char *gbt_block, *varint;
  2162. unsigned char data[80];
  2163. flip80(data, work->data);
  2164. gbt_block = bin2hex(data, 80);
  2165. if (work->gbt_txns < 0xfd) {
  2166. uint8_t val = work->gbt_txns;
  2167. varint = bin2hex((const unsigned char *)&val, 1);
  2168. } else if (work->gbt_txns <= 0xffff) {
  2169. uint16_t val = htole16(work->gbt_txns);
  2170. gbt_block = realloc_strcat(gbt_block, "fd");
  2171. varint = bin2hex((const unsigned char *)&val, 2);
  2172. } else {
  2173. uint32_t val = htole32(work->gbt_txns);
  2174. gbt_block = realloc_strcat(gbt_block, "fe");
  2175. varint = bin2hex((const unsigned char *)&val, 4);
  2176. }
  2177. gbt_block = realloc_strcat(gbt_block, varint);
  2178. free(varint);
  2179. gbt_block = realloc_strcat(gbt_block, work->gbt_coinbase);
  2180. s = strdup("{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"");
  2181. s = realloc_strcat(s, gbt_block);
  2182. if (work->job_id) {
  2183. s = realloc_strcat(s, "\", {\"workid\": \"");
  2184. s = realloc_strcat(s, work->job_id);
  2185. s = realloc_strcat(s, "\"}]}");
  2186. } else
  2187. s = realloc_strcat(s, "\", {}]}");
  2188. free(gbt_block);
  2189. } else {
  2190. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2191. s = realloc_strcat(s, hexstr);
  2192. s = realloc_strcat(s, "\" ], \"id\":1}");
  2193. }
  2194. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  2195. s = realloc_strcat(s, "\n");
  2196. gettimeofday(&tv_submit, NULL);
  2197. /* issue JSON-RPC request */
  2198. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2199. gettimeofday(&tv_submit_reply, NULL);
  2200. free(s);
  2201. if (unlikely(!val)) {
  2202. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2203. if (!pool_tset(pool, &pool->submit_fail)) {
  2204. total_ro++;
  2205. pool->remotefail_occasions++;
  2206. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2207. }
  2208. nmsleep(5000);
  2209. goto out;
  2210. } else if (pool_tclear(pool, &pool->submit_fail))
  2211. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2212. res = json_object_get(val, "result");
  2213. err = json_object_get(val, "error");
  2214. if (!QUIET) {
  2215. int intdiff = floor(work->work_difficulty);
  2216. char diffdisp[16], *outhash;
  2217. unsigned char rhash[32];
  2218. uint64_t sharediff;
  2219. swab256(rhash, work->hash);
  2220. if (opt_scrypt)
  2221. outhash = bin2hex(rhash + 2, 4);
  2222. else
  2223. outhash = bin2hex(rhash + 4, 4);
  2224. sharediff = share_diff(work);
  2225. suffix_string(sharediff, diffdisp, 0);
  2226. sprintf(hashshow, "%s Diff %s/%d%s", outhash, diffdisp, intdiff,
  2227. work->block? " BLOCK!" : "");
  2228. free(outhash);
  2229. if (opt_worktime) {
  2230. char workclone[20];
  2231. struct tm *tm, tm_getwork, tm_submit_reply;
  2232. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2233. (struct timeval *)&(work->tv_getwork));
  2234. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2235. (struct timeval *)&(work->tv_getwork_reply));
  2236. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2237. (struct timeval *)&(work->tv_work_start));
  2238. double work_to_submit = tdiff(&tv_submit,
  2239. (struct timeval *)&(work->tv_work_found));
  2240. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  2241. int diffplaces = 3;
  2242. tm = localtime(&(work->tv_getwork.tv_sec));
  2243. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2244. tm = localtime(&(tv_submit_reply.tv_sec));
  2245. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2246. if (work->clone) {
  2247. sprintf(workclone, "C:%1.3f",
  2248. tdiff((struct timeval *)&(work->tv_cloned),
  2249. (struct timeval *)&(work->tv_getwork_reply)));
  2250. }
  2251. else
  2252. strcpy(workclone, "O");
  2253. if (work->work_difficulty < 1)
  2254. diffplaces = 6;
  2255. 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",
  2256. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2257. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2258. work->getwork_mode, diffplaces, work->work_difficulty,
  2259. tm_getwork.tm_hour, tm_getwork.tm_min,
  2260. tm_getwork.tm_sec, getwork_time, workclone,
  2261. getwork_to_work, work_time, work_to_submit, submit_time,
  2262. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2263. tm_submit_reply.tm_sec);
  2264. }
  2265. }
  2266. share_result(val, res, err, work, hashshow, resubmit, worktime);
  2267. cgpu->utility = cgpu->accepted / total_secs * 60;
  2268. if (!opt_realquiet)
  2269. print_status(thr_id);
  2270. if (!want_per_device_stats) {
  2271. char logline[256];
  2272. get_statline(logline, cgpu);
  2273. applog(LOG_INFO, "%s", logline);
  2274. }
  2275. json_decref(val);
  2276. rc = true;
  2277. out:
  2278. free(hexstr);
  2279. return rc;
  2280. }
  2281. /* Specifies whether we can use this pool for work or not. */
  2282. static bool pool_unworkable(struct pool *pool)
  2283. {
  2284. if (pool->idle)
  2285. return true;
  2286. if (pool->enabled != POOL_ENABLED)
  2287. return true;
  2288. if (pool->has_stratum && !pool->stratum_active)
  2289. return true;
  2290. return false;
  2291. }
  2292. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2293. * rolling average per 10 minutes and if pools start getting more, it biases
  2294. * away from them to distribute work evenly. The share count is reset to the
  2295. * rolling average every 10 minutes to not send all work to one pool after it
  2296. * has been disabled/out for an extended period. */
  2297. static struct pool *select_balanced(struct pool *cp)
  2298. {
  2299. int i, lowest = cp->shares;
  2300. struct pool *ret = cp;
  2301. for (i = 0; i < total_pools; i++) {
  2302. struct pool *pool = pools[i];
  2303. if (pool_unworkable(pool))
  2304. continue;
  2305. if (pool->shares < lowest) {
  2306. lowest = pool->shares;
  2307. ret = pool;
  2308. }
  2309. }
  2310. ret->shares++;
  2311. return ret;
  2312. }
  2313. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2314. static inline struct pool *select_pool(bool lagging)
  2315. {
  2316. static int rotating_pool = 0;
  2317. struct pool *pool, *cp;
  2318. int tested;
  2319. cp = current_pool();
  2320. if (pool_strategy == POOL_BALANCE)
  2321. return select_balanced(cp);
  2322. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2323. pool = cp;
  2324. else
  2325. pool = NULL;
  2326. /* Try to find the first pool in the rotation that is usable */
  2327. tested = 0;
  2328. while (!pool && tested++ < total_pools) {
  2329. if (++rotating_pool >= total_pools)
  2330. rotating_pool = 0;
  2331. pool = pools[rotating_pool];
  2332. if (!pool_unworkable(pool))
  2333. break;
  2334. pool = NULL;
  2335. }
  2336. /* If still nothing is usable, use the current pool */
  2337. if (!pool)
  2338. pool = cp;
  2339. return pool;
  2340. }
  2341. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  2342. /*
  2343. * Calculate the work share difficulty
  2344. */
  2345. static void calc_diff(struct work *work, int known)
  2346. {
  2347. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2348. double difficulty;
  2349. if (opt_scrypt) {
  2350. uint64_t *data64, d64;
  2351. char rtarget[32];
  2352. swab256(rtarget, work->target);
  2353. data64 = (uint64_t *)(rtarget + 2);
  2354. d64 = be64toh(*data64);
  2355. if (unlikely(!d64))
  2356. d64 = 1;
  2357. work->work_difficulty = diffone / d64;
  2358. } else if (!known) {
  2359. double targ = 0;
  2360. int i;
  2361. for (i = 31; i >= 0; i--) {
  2362. targ *= 256;
  2363. targ += work->target[i];
  2364. }
  2365. work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
  2366. } else
  2367. work->work_difficulty = known;
  2368. difficulty = work->work_difficulty;
  2369. pool_stats->last_diff = difficulty;
  2370. suffix_string((uint64_t)difficulty, work->pool->diff, 0);
  2371. if (difficulty == pool_stats->min_diff)
  2372. pool_stats->min_diff_count++;
  2373. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2374. pool_stats->min_diff = difficulty;
  2375. pool_stats->min_diff_count = 1;
  2376. }
  2377. if (difficulty == pool_stats->max_diff)
  2378. pool_stats->max_diff_count++;
  2379. else if (difficulty > pool_stats->max_diff) {
  2380. pool_stats->max_diff = difficulty;
  2381. pool_stats->max_diff_count = 1;
  2382. }
  2383. }
  2384. static void get_benchmark_work(struct work *work)
  2385. {
  2386. // Use a random work block pulled from a pool
  2387. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2388. size_t bench_size = sizeof(*work);
  2389. size_t work_size = sizeof(bench_block);
  2390. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2391. memset(work, 0, sizeof(*work));
  2392. memcpy(work, &bench_block, min_size);
  2393. work->mandatory = true;
  2394. work->pool = pools[0];
  2395. gettimeofday(&(work->tv_getwork), NULL);
  2396. memcpy(&(work->tv_getwork_reply), &(work->tv_getwork), sizeof(struct timeval));
  2397. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2398. calc_diff(work, 0);
  2399. }
  2400. static bool get_upstream_work(struct work *work, CURL *curl)
  2401. {
  2402. struct pool *pool = work->pool;
  2403. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2404. struct timeval tv_elapsed;
  2405. json_t *val = NULL;
  2406. bool rc = false;
  2407. char *url;
  2408. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, pool->rpc_req);
  2409. url = pool->rpc_url;
  2410. gettimeofday(&(work->tv_getwork), NULL);
  2411. val = json_rpc_call(curl, url, pool->rpc_userpass, pool->rpc_req, false,
  2412. false, &work->rolltime, pool, false);
  2413. pool_stats->getwork_attempts++;
  2414. if (likely(val)) {
  2415. rc = work_decode(pool, work, val);
  2416. if (unlikely(!rc))
  2417. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2418. } else
  2419. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2420. gettimeofday(&(work->tv_getwork_reply), NULL);
  2421. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2422. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2423. pool_stats->getwork_wait_rolling /= 1.63;
  2424. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2425. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2426. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2427. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2428. }
  2429. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2430. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2431. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2432. }
  2433. pool_stats->getwork_calls++;
  2434. work->pool = pool;
  2435. work->longpoll = false;
  2436. work->getwork_mode = GETWORK_MODE_POOL;
  2437. calc_diff(work, 0);
  2438. total_getworks++;
  2439. pool->getwork_requested++;
  2440. if (likely(val))
  2441. json_decref(val);
  2442. return rc;
  2443. }
  2444. #ifdef HAVE_CURSES
  2445. static void disable_curses(void)
  2446. {
  2447. if (curses_active_locked()) {
  2448. curses_active = false;
  2449. leaveok(logwin, false);
  2450. leaveok(statuswin, false);
  2451. leaveok(mainwin, false);
  2452. nocbreak();
  2453. echo();
  2454. delwin(logwin);
  2455. delwin(statuswin);
  2456. delwin(mainwin);
  2457. endwin();
  2458. #ifdef WIN32
  2459. // Move the cursor to after curses output.
  2460. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2461. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2462. COORD coord;
  2463. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2464. coord.X = 0;
  2465. coord.Y = csbi.dwSize.Y - 1;
  2466. SetConsoleCursorPosition(hout, coord);
  2467. }
  2468. #endif
  2469. unlock_curses();
  2470. }
  2471. }
  2472. #endif
  2473. static void __kill_work(void)
  2474. {
  2475. struct thr_info *thr;
  2476. int i;
  2477. if (!successful_connect)
  2478. return;
  2479. applog(LOG_INFO, "Received kill message");
  2480. #ifdef USE_USBUTILS
  2481. /* Best to get rid of it first so it doesn't
  2482. * try to create any new devices */
  2483. if (!opt_scrypt) {
  2484. applog(LOG_DEBUG, "Killing off HotPlug thread");
  2485. thr = &control_thr[hotplug_thr_id];
  2486. thr_info_cancel(thr);
  2487. }
  2488. #endif
  2489. applog(LOG_DEBUG, "Killing off watchpool thread");
  2490. /* Kill the watchpool thread */
  2491. thr = &control_thr[watchpool_thr_id];
  2492. thr_info_cancel(thr);
  2493. applog(LOG_DEBUG, "Killing off watchdog thread");
  2494. /* Kill the watchdog thread */
  2495. thr = &control_thr[watchdog_thr_id];
  2496. thr_info_cancel(thr);
  2497. applog(LOG_DEBUG, "Stopping mining threads");
  2498. /* Stop the mining threads*/
  2499. for (i = 0; i < mining_threads; i++) {
  2500. thr = get_thread(i);
  2501. thr_info_freeze(thr);
  2502. thr->pause = true;
  2503. }
  2504. nmsleep(1000);
  2505. applog(LOG_DEBUG, "Killing off mining threads");
  2506. /* Kill the mining threads*/
  2507. for (i = 0; i < mining_threads; i++) {
  2508. thr = get_thread(i);
  2509. thr_info_cancel(thr);
  2510. }
  2511. applog(LOG_DEBUG, "Killing off stage thread");
  2512. /* Stop the others */
  2513. thr = &control_thr[stage_thr_id];
  2514. thr_info_cancel(thr);
  2515. applog(LOG_DEBUG, "Killing off API thread");
  2516. thr = &control_thr[api_thr_id];
  2517. thr_info_cancel(thr);
  2518. #ifdef USE_USBUTILS
  2519. /* Release USB resources in case it's a restart
  2520. * and not a QUIT */
  2521. if (!opt_scrypt) {
  2522. applog(LOG_DEBUG, "Releasing all USB devices");
  2523. usb_cleanup();
  2524. }
  2525. #endif
  2526. }
  2527. /* This should be the common exit path */
  2528. void kill_work(void)
  2529. {
  2530. __kill_work();
  2531. quit(0, "Shutdown signal received.");
  2532. }
  2533. static
  2534. #ifdef WIN32
  2535. const
  2536. #endif
  2537. char **initial_args;
  2538. static void clean_up(void);
  2539. void app_restart(void)
  2540. {
  2541. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2542. __kill_work();
  2543. clean_up();
  2544. #if defined(unix)
  2545. if (forkpid > 0) {
  2546. kill(forkpid, SIGTERM);
  2547. forkpid = 0;
  2548. }
  2549. #endif
  2550. execv(initial_args[0], initial_args);
  2551. applog(LOG_WARNING, "Failed to restart application");
  2552. }
  2553. static void sighandler(int __maybe_unused sig)
  2554. {
  2555. /* Restore signal handlers so we can still quit if kill_work fails */
  2556. sigaction(SIGTERM, &termhandler, NULL);
  2557. sigaction(SIGINT, &inthandler, NULL);
  2558. kill_work();
  2559. }
  2560. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2561. * this pool. */
  2562. static void recruit_curl(struct pool *pool)
  2563. {
  2564. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2565. if (unlikely(!ce))
  2566. quit(1, "Failed to calloc in recruit_curl");
  2567. ce->curl = curl_easy_init();
  2568. if (unlikely(!ce->curl))
  2569. quit(1, "Failed to init in recruit_curl");
  2570. list_add(&ce->node, &pool->curlring);
  2571. pool->curls++;
  2572. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  2573. }
  2574. /* Grab an available curl if there is one. If not, then recruit extra curls
  2575. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2576. * and there are already 5 curls in circulation. Limit total number to the
  2577. * number of mining threads per pool as well to prevent blasting a pool during
  2578. * network delays/outages. */
  2579. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2580. {
  2581. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2582. struct curl_ent *ce;
  2583. mutex_lock(&pool->pool_lock);
  2584. retry:
  2585. if (!pool->curls)
  2586. recruit_curl(pool);
  2587. else if (list_empty(&pool->curlring)) {
  2588. if (pool->curls >= curl_limit) {
  2589. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2590. goto retry;
  2591. } else
  2592. recruit_curl(pool);
  2593. }
  2594. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2595. list_del(&ce->node);
  2596. mutex_unlock(&pool->pool_lock);
  2597. return ce;
  2598. }
  2599. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2600. {
  2601. mutex_lock(&pool->pool_lock);
  2602. list_add_tail(&ce->node, &pool->curlring);
  2603. gettimeofday(&ce->tv, NULL);
  2604. pthread_cond_broadcast(&pool->cr_cond);
  2605. mutex_unlock(&pool->pool_lock);
  2606. }
  2607. static bool stale_work(struct work *work, bool share);
  2608. static inline bool should_roll(struct work *work)
  2609. {
  2610. struct timeval now;
  2611. time_t expiry;
  2612. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  2613. return false;
  2614. if (work->rolltime > opt_scantime)
  2615. expiry = work->rolltime;
  2616. else
  2617. expiry = opt_scantime;
  2618. expiry = expiry * 2 / 3;
  2619. /* We shouldn't roll if we're unlikely to get one shares' duration
  2620. * work out of doing so */
  2621. gettimeofday(&now, NULL);
  2622. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  2623. return false;
  2624. return true;
  2625. }
  2626. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  2627. * reject blocks as invalid. */
  2628. static inline bool can_roll(struct work *work)
  2629. {
  2630. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  2631. work->rolls < 7000 && !stale_work(work, false));
  2632. }
  2633. static void roll_work(struct work *work)
  2634. {
  2635. uint32_t *work_ntime;
  2636. uint32_t ntime;
  2637. work_ntime = (uint32_t *)(work->data + 68);
  2638. ntime = be32toh(*work_ntime);
  2639. ntime++;
  2640. *work_ntime = htobe32(ntime);
  2641. local_work++;
  2642. work->rolls++;
  2643. work->blk.nonce = 0;
  2644. applog(LOG_DEBUG, "Successfully rolled work");
  2645. /* This is now a different work item so it needs a different ID for the
  2646. * hashtable */
  2647. work->id = total_work++;
  2648. }
  2649. /* Duplicates any dynamically allocated arrays within the work struct to
  2650. * prevent a copied work struct from freeing ram belonging to another struct */
  2651. void __copy_work(struct work *work, struct work *base_work)
  2652. {
  2653. int id = work->id;
  2654. clean_work(work);
  2655. memcpy(work, base_work, sizeof(struct work));
  2656. /* Keep the unique new id assigned during make_work to prevent copied
  2657. * work from having the same id. */
  2658. work->id = id;
  2659. if (base_work->job_id)
  2660. work->job_id = strdup(base_work->job_id);
  2661. if (base_work->nonce1)
  2662. work->nonce1 = strdup(base_work->nonce1);
  2663. if (base_work->nonce2)
  2664. work->nonce2 = strdup(base_work->nonce2);
  2665. if (base_work->ntime)
  2666. work->ntime = strdup(base_work->ntime);
  2667. if (base_work->gbt_coinbase)
  2668. work->gbt_coinbase = strdup(base_work->gbt_coinbase);
  2669. }
  2670. /* Generates a copy of an existing work struct, creating fresh heap allocations
  2671. * for all dynamically allocated arrays within the struct */
  2672. struct work *copy_work(struct work *base_work)
  2673. {
  2674. struct work *work = make_work();
  2675. __copy_work(work, base_work);
  2676. return work;
  2677. }
  2678. static struct work *make_clone(struct work *work)
  2679. {
  2680. struct work *work_clone = copy_work(work);
  2681. work_clone->clone = true;
  2682. gettimeofday((struct timeval *)&(work_clone->tv_cloned), NULL);
  2683. work_clone->longpoll = false;
  2684. work_clone->mandatory = false;
  2685. /* Make cloned work appear slightly older to bias towards keeping the
  2686. * master work item which can be further rolled */
  2687. work_clone->tv_staged.tv_sec -= 1;
  2688. return work_clone;
  2689. }
  2690. static void stage_work(struct work *work);
  2691. static bool clone_available(void)
  2692. {
  2693. struct work *work_clone = NULL, *work, *tmp;
  2694. bool cloned = false;
  2695. mutex_lock(stgd_lock);
  2696. if (!staged_rollable)
  2697. goto out_unlock;
  2698. HASH_ITER(hh, staged_work, work, tmp) {
  2699. if (can_roll(work) && should_roll(work)) {
  2700. roll_work(work);
  2701. work_clone = make_clone(work);
  2702. roll_work(work);
  2703. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2704. cloned = true;
  2705. break;
  2706. }
  2707. }
  2708. out_unlock:
  2709. mutex_unlock(stgd_lock);
  2710. if (cloned)
  2711. stage_work(work_clone);
  2712. return cloned;
  2713. }
  2714. static void pool_died(struct pool *pool)
  2715. {
  2716. if (!pool_tset(pool, &pool->idle)) {
  2717. gettimeofday(&pool->tv_idle, NULL);
  2718. if (pool == current_pool()) {
  2719. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2720. switch_pools(NULL);
  2721. } else
  2722. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  2723. }
  2724. }
  2725. static bool stale_work(struct work *work, bool share)
  2726. {
  2727. struct timeval now;
  2728. time_t work_expiry;
  2729. struct pool *pool;
  2730. int getwork_delay;
  2731. if (opt_benchmark)
  2732. return false;
  2733. if (work->work_block != work_block) {
  2734. applog(LOG_DEBUG, "Work stale due to block mismatch");
  2735. return true;
  2736. }
  2737. /* Technically the rolltime should be correct but some pools
  2738. * advertise a broken expire= that is lower than a meaningful
  2739. * scantime */
  2740. if (work->rolltime > opt_scantime)
  2741. work_expiry = work->rolltime;
  2742. else
  2743. work_expiry = opt_expiry;
  2744. pool = work->pool;
  2745. if (!share && pool->has_stratum) {
  2746. bool same_job;
  2747. if (!pool->stratum_active || !pool->stratum_notify) {
  2748. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  2749. return true;
  2750. }
  2751. same_job = true;
  2752. cg_rlock(&pool->data_lock);
  2753. if (strcmp(work->job_id, pool->swork.job_id))
  2754. same_job = false;
  2755. cg_runlock(&pool->data_lock);
  2756. if (!same_job) {
  2757. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  2758. return true;
  2759. }
  2760. }
  2761. /* Factor in the average getwork delay of this pool, rounding it up to
  2762. * the nearest second */
  2763. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2764. work_expiry -= getwork_delay;
  2765. if (unlikely(work_expiry < 5))
  2766. work_expiry = 5;
  2767. gettimeofday(&now, NULL);
  2768. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2769. applog(LOG_DEBUG, "Work stale due to expiry");
  2770. return true;
  2771. }
  2772. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2773. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2774. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  2775. return true;
  2776. }
  2777. return false;
  2778. }
  2779. static void regen_hash(struct work *work)
  2780. {
  2781. uint32_t *data32 = (uint32_t *)(work->data);
  2782. unsigned char swap[80];
  2783. uint32_t *swap32 = (uint32_t *)swap;
  2784. unsigned char hash1[32];
  2785. flip80(swap32, data32);
  2786. sha2(swap, 80, hash1);
  2787. sha2(hash1, 32, (unsigned char *)(work->hash));
  2788. }
  2789. static void check_solve(struct work *work)
  2790. {
  2791. if (opt_scrypt)
  2792. scrypt_outputhash(work);
  2793. else
  2794. regen_hash(work);
  2795. work->block = solves_block(work);
  2796. if (unlikely(work->block)) {
  2797. work->pool->solved++;
  2798. found_blocks++;
  2799. work->mandatory = true;
  2800. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  2801. }
  2802. }
  2803. static bool cnx_needed(struct pool *pool);
  2804. static void *submit_work_thread(void *userdata)
  2805. {
  2806. struct work *work = (struct work *)userdata;
  2807. struct pool *pool = work->pool;
  2808. bool resubmit = false;
  2809. struct curl_ent *ce;
  2810. pthread_detach(pthread_self());
  2811. RenameThread("submit_work");
  2812. applog(LOG_DEBUG, "Creating extra submit work thread");
  2813. check_solve(work);
  2814. if (stale_work(work, true)) {
  2815. if (opt_submit_stale)
  2816. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  2817. else if (pool->submit_old)
  2818. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  2819. else {
  2820. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  2821. sharelog("discard", work);
  2822. mutex_lock(&stats_lock);
  2823. total_stale++;
  2824. pool->stale_shares++;
  2825. total_diff_stale += work->work_difficulty;
  2826. pool->diff_stale += work->work_difficulty;
  2827. mutex_unlock(&stats_lock);
  2828. goto out;
  2829. }
  2830. work->stale = true;
  2831. }
  2832. if (work->stratum) {
  2833. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  2834. uint32_t *hash32 = (uint32_t *)work->hash, nonce;
  2835. bool submitted = false;
  2836. char *noncehex;
  2837. char s[1024];
  2838. sshare->sshare_time = time(NULL);
  2839. /* This work item is freed in parse_stratum_response */
  2840. sshare->work = work;
  2841. nonce = *((uint32_t *)(work->data + 76));
  2842. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  2843. memset(s, 0, 1024);
  2844. mutex_lock(&sshare_lock);
  2845. /* Give the stratum share a unique id */
  2846. sshare->id = swork_id++;
  2847. mutex_unlock(&sshare_lock);
  2848. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  2849. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  2850. free(noncehex);
  2851. applog(LOG_INFO, "Submitting share %08lx to pool %d", hash32[6], pool->pool_no);
  2852. /* Try resubmitting for up to 2 minutes if we fail to submit
  2853. * once and the stratum pool nonce1 still matches suggesting
  2854. * we may be able to resume. */
  2855. while (time(NULL) < sshare->sshare_time + 120) {
  2856. bool sessionid_match;
  2857. if (likely(stratum_send(pool, s, strlen(s)))) {
  2858. if (pool_tclear(pool, &pool->submit_fail))
  2859. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2860. mutex_lock(&sshare_lock);
  2861. HASH_ADD_INT(stratum_shares, id, sshare);
  2862. pool->sshares++;
  2863. mutex_unlock(&sshare_lock);
  2864. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  2865. submitted = true;
  2866. break;
  2867. }
  2868. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  2869. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  2870. total_ro++;
  2871. pool->remotefail_occasions++;
  2872. }
  2873. cg_rlock(&pool->data_lock);
  2874. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  2875. cg_runlock(&pool->data_lock);
  2876. if (!sessionid_match) {
  2877. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  2878. break;
  2879. }
  2880. /* Retry every 5 seconds */
  2881. sleep(5);
  2882. }
  2883. if (unlikely(!submitted)) {
  2884. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  2885. free_work(work);
  2886. free(sshare);
  2887. pool->stale_shares++;
  2888. total_stale++;
  2889. }
  2890. goto out;
  2891. }
  2892. ce = pop_curl_entry(pool);
  2893. /* submit solution to bitcoin via JSON-RPC */
  2894. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2895. resubmit = true;
  2896. if (stale_work(work, true)) {
  2897. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  2898. mutex_lock(&stats_lock);
  2899. total_stale++;
  2900. pool->stale_shares++;
  2901. total_diff_stale += work->work_difficulty;
  2902. pool->diff_stale += work->work_difficulty;
  2903. mutex_unlock(&stats_lock);
  2904. break;
  2905. }
  2906. /* pause, then restart work-request loop */
  2907. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2908. }
  2909. push_curl_entry(ce, pool);
  2910. out:
  2911. return NULL;
  2912. }
  2913. /* Find the pool that currently has the highest priority */
  2914. static struct pool *priority_pool(int choice)
  2915. {
  2916. struct pool *ret = NULL;
  2917. int i;
  2918. for (i = 0; i < total_pools; i++) {
  2919. struct pool *pool = pools[i];
  2920. if (pool->prio == choice) {
  2921. ret = pool;
  2922. break;
  2923. }
  2924. }
  2925. if (unlikely(!ret)) {
  2926. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2927. return pools[choice];
  2928. }
  2929. return ret;
  2930. }
  2931. static void clear_pool_work(struct pool *pool);
  2932. /* Specifies whether we can switch to this pool or not. */
  2933. static bool pool_unusable(struct pool *pool)
  2934. {
  2935. if (pool->idle)
  2936. return true;
  2937. if (pool->enabled != POOL_ENABLED)
  2938. return true;
  2939. return false;
  2940. }
  2941. void switch_pools(struct pool *selected)
  2942. {
  2943. struct pool *pool, *last_pool;
  2944. int i, pool_no, next_pool;
  2945. cg_wlock(&control_lock);
  2946. last_pool = currentpool;
  2947. pool_no = currentpool->pool_no;
  2948. /* Switch selected to pool number 0 and move the rest down */
  2949. if (selected) {
  2950. if (selected->prio != 0) {
  2951. for (i = 0; i < total_pools; i++) {
  2952. pool = pools[i];
  2953. if (pool->prio < selected->prio)
  2954. pool->prio++;
  2955. }
  2956. selected->prio = 0;
  2957. }
  2958. }
  2959. switch (pool_strategy) {
  2960. /* Both of these set to the master pool */
  2961. case POOL_BALANCE:
  2962. case POOL_FAILOVER:
  2963. case POOL_LOADBALANCE:
  2964. for (i = 0; i < total_pools; i++) {
  2965. pool = priority_pool(i);
  2966. if (pool_unusable(pool))
  2967. continue;
  2968. pool_no = pool->pool_no;
  2969. break;
  2970. }
  2971. break;
  2972. /* Both of these simply increment and cycle */
  2973. case POOL_ROUNDROBIN:
  2974. case POOL_ROTATE:
  2975. if (selected && !selected->idle) {
  2976. pool_no = selected->pool_no;
  2977. break;
  2978. }
  2979. next_pool = pool_no;
  2980. /* Select the next alive pool */
  2981. for (i = 1; i < total_pools; i++) {
  2982. next_pool++;
  2983. if (next_pool >= total_pools)
  2984. next_pool = 0;
  2985. pool = pools[next_pool];
  2986. if (pool_unusable(pool))
  2987. continue;
  2988. pool_no = next_pool;
  2989. break;
  2990. }
  2991. break;
  2992. default:
  2993. break;
  2994. }
  2995. currentpool = pools[pool_no];
  2996. pool = currentpool;
  2997. cg_wunlock(&control_lock);
  2998. /* Set the lagging flag to avoid pool not providing work fast enough
  2999. * messages in failover only mode since we have to get all fresh work
  3000. * as in restart_threads */
  3001. if (opt_fail_only)
  3002. pool_tset(pool, &pool->lagging);
  3003. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3004. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  3005. if (pool->has_gbt || pool->has_stratum || opt_fail_only)
  3006. clear_pool_work(last_pool);
  3007. }
  3008. mutex_lock(&lp_lock);
  3009. pthread_cond_broadcast(&lp_cond);
  3010. mutex_unlock(&lp_lock);
  3011. }
  3012. void discard_work(struct work *work)
  3013. {
  3014. if (!work->clone && !work->rolls && !work->mined) {
  3015. if (work->pool)
  3016. work->pool->discarded_work++;
  3017. total_discarded++;
  3018. applog(LOG_DEBUG, "Discarded work");
  3019. } else
  3020. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3021. free_work(work);
  3022. }
  3023. static void wake_gws(void)
  3024. {
  3025. mutex_lock(stgd_lock);
  3026. pthread_cond_signal(&gws_cond);
  3027. mutex_unlock(stgd_lock);
  3028. }
  3029. static void discard_stale(void)
  3030. {
  3031. struct work *work, *tmp;
  3032. int stale = 0;
  3033. mutex_lock(stgd_lock);
  3034. HASH_ITER(hh, staged_work, work, tmp) {
  3035. if (stale_work(work, false)) {
  3036. HASH_DEL(staged_work, work);
  3037. discard_work(work);
  3038. stale++;
  3039. }
  3040. }
  3041. pthread_cond_signal(&gws_cond);
  3042. mutex_unlock(stgd_lock);
  3043. if (stale)
  3044. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3045. }
  3046. /* A generic wait function for threads that poll that will wait a specified
  3047. * time tdiff waiting on the pthread conditional that is broadcast when a
  3048. * work restart is required. Returns the value of pthread_cond_timedwait
  3049. * which is zero if the condition was met or ETIMEDOUT if not.
  3050. */
  3051. int restart_wait(unsigned int mstime)
  3052. {
  3053. struct timeval now, then, tdiff;
  3054. struct timespec abstime;
  3055. int rc;
  3056. tdiff.tv_sec = mstime / 1000;
  3057. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  3058. gettimeofday(&now, NULL);
  3059. timeradd(&now, &tdiff, &then);
  3060. abstime.tv_sec = then.tv_sec;
  3061. abstime.tv_nsec = then.tv_usec * 1000;
  3062. mutex_lock(&restart_lock);
  3063. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  3064. mutex_unlock(&restart_lock);
  3065. return rc;
  3066. }
  3067. static void restart_threads(void)
  3068. {
  3069. struct pool *cp = current_pool();
  3070. int i;
  3071. /* Artificially set the lagging flag to avoid pool not providing work
  3072. * fast enough messages after every long poll */
  3073. pool_tset(cp, &cp->lagging);
  3074. /* Discard staged work that is now stale */
  3075. discard_stale();
  3076. rd_lock(&mining_thr_lock);
  3077. for (i = 0; i < mining_threads; i++)
  3078. mining_thr[i]->work_restart = true;
  3079. rd_unlock(&mining_thr_lock);
  3080. mutex_lock(&restart_lock);
  3081. pthread_cond_broadcast(&restart_cond);
  3082. mutex_unlock(&restart_lock);
  3083. }
  3084. static void set_curblock(char *hexstr, unsigned char *hash)
  3085. {
  3086. unsigned char hash_swap[32];
  3087. unsigned char block_hash_swap[32];
  3088. strcpy(current_block, hexstr);
  3089. swap256(hash_swap, hash);
  3090. swap256(block_hash_swap, hash + 4);
  3091. cg_wlock(&ch_lock);
  3092. gettimeofday(&block_timeval, NULL);
  3093. free(current_hash);
  3094. current_hash = bin2hex(hash_swap + 2, 8);
  3095. free(current_fullhash);
  3096. current_fullhash = bin2hex(block_hash_swap, 32);
  3097. get_timestamp(blocktime, &block_timeval);
  3098. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  3099. cg_wunlock(&ch_lock);
  3100. }
  3101. /* Search to see if this string is from a block that has been seen before */
  3102. static bool block_exists(char *hexstr)
  3103. {
  3104. struct block *s;
  3105. rd_lock(&blk_lock);
  3106. HASH_FIND_STR(blocks, hexstr, s);
  3107. rd_unlock(&blk_lock);
  3108. if (s)
  3109. return true;
  3110. return false;
  3111. }
  3112. /* Tests if this work is from a block that has been seen before */
  3113. static inline bool from_existing_block(struct work *work)
  3114. {
  3115. char *hexstr = bin2hex(work->data + 8, 18);
  3116. bool ret;
  3117. ret = block_exists(hexstr);
  3118. free(hexstr);
  3119. return ret;
  3120. }
  3121. static int block_sort(struct block *blocka, struct block *blockb)
  3122. {
  3123. return blocka->block_no - blockb->block_no;
  3124. }
  3125. static void set_blockdiff(const struct work *work)
  3126. {
  3127. uint64_t *data64, d64, diff64;
  3128. uint32_t diffhash[8];
  3129. uint32_t difficulty;
  3130. uint32_t diffbytes;
  3131. uint32_t diffvalue;
  3132. char rhash[32];
  3133. int diffshift;
  3134. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  3135. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  3136. diffvalue = difficulty & 0x00ffffff;
  3137. diffshift = (diffbytes % 4) * 8;
  3138. if (diffshift == 0) {
  3139. diffshift = 32;
  3140. diffbytes--;
  3141. }
  3142. memset(diffhash, 0, 32);
  3143. diffbytes >>= 2;
  3144. if (unlikely(diffbytes > 6))
  3145. return;
  3146. diffhash[diffbytes + 1] = diffvalue >> (32 - diffshift);
  3147. diffhash[diffbytes] = diffvalue << diffshift;
  3148. swab256(rhash, diffhash);
  3149. if (opt_scrypt)
  3150. data64 = (uint64_t *)(rhash + 2);
  3151. else
  3152. data64 = (uint64_t *)(rhash + 4);
  3153. d64 = be64toh(*data64);
  3154. if (unlikely(!d64))
  3155. d64 = 1;
  3156. diff64 = diffone / d64;
  3157. suffix_string(diff64, block_diff, 0);
  3158. current_diff = (double)diffone / (double)d64;
  3159. }
  3160. static bool test_work_current(struct work *work)
  3161. {
  3162. bool ret = true;
  3163. char *hexstr;
  3164. if (work->mandatory)
  3165. return ret;
  3166. /* Hack to work around dud work sneaking into test */
  3167. hexstr = bin2hex(work->data + 8, 18);
  3168. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  3169. goto out_free;
  3170. /* Search to see if this block exists yet and if not, consider it a
  3171. * new block and set the current block details to this one */
  3172. if (!block_exists(hexstr)) {
  3173. struct block *s = calloc(sizeof(struct block), 1);
  3174. int deleted_block = 0;
  3175. ret = false;
  3176. if (unlikely(!s))
  3177. quit (1, "test_work_current OOM");
  3178. strcpy(s->hash, hexstr);
  3179. s->block_no = new_blocks++;
  3180. wr_lock(&blk_lock);
  3181. /* Only keep the last hour's worth of blocks in memory since
  3182. * work from blocks before this is virtually impossible and we
  3183. * want to prevent memory usage from continually rising */
  3184. if (HASH_COUNT(blocks) > 6) {
  3185. struct block *oldblock;
  3186. HASH_SORT(blocks, block_sort);
  3187. oldblock = blocks;
  3188. deleted_block = oldblock->block_no;
  3189. HASH_DEL(blocks, oldblock);
  3190. free(oldblock);
  3191. }
  3192. HASH_ADD_STR(blocks, hash, s);
  3193. set_blockdiff(work);
  3194. wr_unlock(&blk_lock);
  3195. if (deleted_block)
  3196. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3197. set_curblock(hexstr, work->data);
  3198. if (unlikely(new_blocks == 1))
  3199. goto out_free;
  3200. work->work_block = ++work_block;
  3201. if (!work->stratum) {
  3202. if (work->longpoll) {
  3203. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
  3204. work->gbt ? "GBT " : "", work->pool->pool_no);
  3205. } else if (have_longpoll)
  3206. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3207. else
  3208. applog(LOG_NOTICE, "New block detected on network");
  3209. }
  3210. restart_threads();
  3211. } else if (work->longpoll) {
  3212. work->work_block = ++work_block;
  3213. if (work->pool == current_pool()) {
  3214. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  3215. work->gbt ? "GBT " : "", work->pool->pool_no);
  3216. restart_threads();
  3217. }
  3218. }
  3219. work->longpoll = false;
  3220. out_free:
  3221. free(hexstr);
  3222. return ret;
  3223. }
  3224. static int tv_sort(struct work *worka, struct work *workb)
  3225. {
  3226. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3227. }
  3228. static bool work_rollable(struct work *work)
  3229. {
  3230. return (!work->clone && work->rolltime);
  3231. }
  3232. static bool hash_push(struct work *work)
  3233. {
  3234. bool rc = true;
  3235. mutex_lock(stgd_lock);
  3236. if (work_rollable(work))
  3237. staged_rollable++;
  3238. if (likely(!getq->frozen)) {
  3239. HASH_ADD_INT(staged_work, id, work);
  3240. HASH_SORT(staged_work, tv_sort);
  3241. } else
  3242. rc = false;
  3243. pthread_cond_broadcast(&getq->cond);
  3244. mutex_unlock(stgd_lock);
  3245. return rc;
  3246. }
  3247. static void *stage_thread(void *userdata)
  3248. {
  3249. struct thr_info *mythr = userdata;
  3250. bool ok = true;
  3251. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3252. RenameThread("stage");
  3253. while (ok) {
  3254. struct work *work = NULL;
  3255. applog(LOG_DEBUG, "Popping work to stage thread");
  3256. work = tq_pop(mythr->q, NULL);
  3257. if (unlikely(!work)) {
  3258. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3259. ok = false;
  3260. break;
  3261. }
  3262. work->work_block = work_block;
  3263. test_work_current(work);
  3264. applog(LOG_DEBUG, "Pushing work to getwork queue");
  3265. if (unlikely(!hash_push(work))) {
  3266. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3267. continue;
  3268. }
  3269. }
  3270. tq_freeze(mythr->q);
  3271. return NULL;
  3272. }
  3273. static void stage_work(struct work *work)
  3274. {
  3275. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  3276. work->work_block = work_block;
  3277. test_work_current(work);
  3278. hash_push(work);
  3279. }
  3280. #ifdef HAVE_CURSES
  3281. int curses_int(const char *query)
  3282. {
  3283. int ret;
  3284. char *cvar;
  3285. cvar = curses_input(query);
  3286. ret = atoi(cvar);
  3287. free(cvar);
  3288. return ret;
  3289. }
  3290. #endif
  3291. #ifdef HAVE_CURSES
  3292. static bool input_pool(bool live);
  3293. #endif
  3294. #ifdef HAVE_CURSES
  3295. static void display_pool_summary(struct pool *pool)
  3296. {
  3297. double efficiency = 0.0;
  3298. if (curses_active_locked()) {
  3299. wlog("Pool: %s\n", pool->rpc_url);
  3300. if (pool->solved)
  3301. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3302. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  3303. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3304. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3305. wlog(" Accepted shares: %d\n", pool->accepted);
  3306. wlog(" Rejected shares: %d\n", pool->rejected);
  3307. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  3308. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  3309. if (pool->accepted || pool->rejected)
  3310. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3311. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3312. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3313. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3314. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3315. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3316. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3317. unlock_curses();
  3318. }
  3319. }
  3320. #endif
  3321. /* We can't remove the memory used for this struct pool because there may
  3322. * still be work referencing it. We just remove it from the pools list */
  3323. void remove_pool(struct pool *pool)
  3324. {
  3325. int i, last_pool = total_pools - 1;
  3326. struct pool *other;
  3327. /* Boost priority of any lower prio than this one */
  3328. for (i = 0; i < total_pools; i++) {
  3329. other = pools[i];
  3330. if (other->prio > pool->prio)
  3331. other->prio--;
  3332. }
  3333. if (pool->pool_no < last_pool) {
  3334. /* Swap the last pool for this one */
  3335. (pools[last_pool])->pool_no = pool->pool_no;
  3336. pools[pool->pool_no] = pools[last_pool];
  3337. }
  3338. /* Give it an invalid number */
  3339. pool->pool_no = total_pools;
  3340. pool->removed = true;
  3341. total_pools--;
  3342. }
  3343. /* add a mutex if this needs to be thread safe in the future */
  3344. static struct JE {
  3345. char *buf;
  3346. struct JE *next;
  3347. } *jedata = NULL;
  3348. static void json_escape_free()
  3349. {
  3350. struct JE *jeptr = jedata;
  3351. struct JE *jenext;
  3352. jedata = NULL;
  3353. while (jeptr) {
  3354. jenext = jeptr->next;
  3355. free(jeptr->buf);
  3356. free(jeptr);
  3357. jeptr = jenext;
  3358. }
  3359. }
  3360. static char *json_escape(char *str)
  3361. {
  3362. struct JE *jeptr;
  3363. char *buf, *ptr;
  3364. /* 2x is the max, may as well just allocate that */
  3365. ptr = buf = malloc(strlen(str) * 2 + 1);
  3366. jeptr = malloc(sizeof(*jeptr));
  3367. jeptr->buf = buf;
  3368. jeptr->next = jedata;
  3369. jedata = jeptr;
  3370. while (*str) {
  3371. if (*str == '\\' || *str == '"')
  3372. *(ptr++) = '\\';
  3373. *(ptr++) = *(str++);
  3374. }
  3375. *ptr = '\0';
  3376. return buf;
  3377. }
  3378. void write_config(FILE *fcfg)
  3379. {
  3380. int i;
  3381. /* Write pool values */
  3382. fputs("{\n\"pools\" : [", fcfg);
  3383. for(i = 0; i < total_pools; i++) {
  3384. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  3385. pools[i]->rpc_proxy ? json_escape((char *)proxytype(pools[i]->rpc_proxytype)) : "",
  3386. pools[i]->rpc_proxy ? json_escape(pools[i]->rpc_proxy) : "",
  3387. pools[i]->rpc_proxy ? "|" : "",
  3388. json_escape(pools[i]->rpc_url));
  3389. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3390. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  3391. }
  3392. fputs("\n]\n", fcfg);
  3393. #ifdef HAVE_OPENCL
  3394. if (nDevs) {
  3395. /* Write GPU device values */
  3396. fputs(",\n\"intensity\" : \"", fcfg);
  3397. for(i = 0; i < nDevs; i++)
  3398. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3399. fputs("\",\n\"vectors\" : \"", fcfg);
  3400. for(i = 0; i < nDevs; i++)
  3401. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3402. gpus[i].vwidth);
  3403. fputs("\",\n\"worksize\" : \"", fcfg);
  3404. for(i = 0; i < nDevs; i++)
  3405. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3406. (int)gpus[i].work_size);
  3407. fputs("\",\n\"kernel\" : \"", fcfg);
  3408. for(i = 0; i < nDevs; i++) {
  3409. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3410. switch (gpus[i].kernel) {
  3411. case KL_NONE: // Shouldn't happen
  3412. break;
  3413. case KL_POCLBM:
  3414. fprintf(fcfg, "poclbm");
  3415. break;
  3416. case KL_PHATK:
  3417. fprintf(fcfg, "phatk");
  3418. break;
  3419. case KL_DIAKGCN:
  3420. fprintf(fcfg, "diakgcn");
  3421. break;
  3422. case KL_DIABLO:
  3423. fprintf(fcfg, "diablo");
  3424. break;
  3425. case KL_SCRYPT:
  3426. fprintf(fcfg, "scrypt");
  3427. break;
  3428. }
  3429. }
  3430. #ifdef USE_SCRYPT
  3431. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3432. for(i = 0; i < nDevs; i++)
  3433. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3434. (int)gpus[i].opt_lg);
  3435. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3436. for(i = 0; i < nDevs; i++)
  3437. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3438. (int)gpus[i].opt_tc);
  3439. fputs("\",\n\"shaders\" : \"", fcfg);
  3440. for(i = 0; i < nDevs; i++)
  3441. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3442. (int)gpus[i].shaders);
  3443. #endif
  3444. #ifdef HAVE_ADL
  3445. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3446. for(i = 0; i < nDevs; i++)
  3447. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3448. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3449. for(i = 0; i < nDevs; i++)
  3450. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3451. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3452. for(i = 0; i < nDevs; i++)
  3453. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3454. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3455. for(i = 0; i < nDevs; i++)
  3456. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3457. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3458. for(i = 0; i < nDevs; i++)
  3459. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3460. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3461. for(i = 0; i < nDevs; i++)
  3462. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3463. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3464. for(i = 0; i < nDevs; i++)
  3465. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3466. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3467. for(i = 0; i < nDevs; i++)
  3468. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3469. fputs("\",\n\"temp-target\" : \"", fcfg);
  3470. for(i = 0; i < nDevs; i++)
  3471. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  3472. #endif
  3473. fputs("\"", fcfg);
  3474. }
  3475. #endif
  3476. #ifdef HAVE_ADL
  3477. if (opt_reorder)
  3478. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3479. #endif
  3480. #ifdef WANT_CPUMINE
  3481. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  3482. #endif
  3483. /* Simple bool and int options */
  3484. struct opt_table *opt;
  3485. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3486. char *p, *name = strdup(opt->names);
  3487. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3488. if (p[1] != '-')
  3489. continue;
  3490. if (opt->type & OPT_NOARG &&
  3491. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3492. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3493. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3494. if (opt->type & OPT_HASARG &&
  3495. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3496. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3497. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3498. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  3499. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3500. }
  3501. }
  3502. /* Special case options */
  3503. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3504. if (pool_strategy == POOL_BALANCE)
  3505. fputs(",\n\"balance\" : true", fcfg);
  3506. if (pool_strategy == POOL_LOADBALANCE)
  3507. fputs(",\n\"load-balance\" : true", fcfg);
  3508. if (pool_strategy == POOL_ROUNDROBIN)
  3509. fputs(",\n\"round-robin\" : true", fcfg);
  3510. if (pool_strategy == POOL_ROTATE)
  3511. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3512. #if defined(unix)
  3513. if (opt_stderr_cmd && *opt_stderr_cmd)
  3514. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3515. #endif // defined(unix)
  3516. if (opt_kernel_path && *opt_kernel_path) {
  3517. char *kpath = strdup(opt_kernel_path);
  3518. if (kpath[strlen(kpath)-1] == '/')
  3519. kpath[strlen(kpath)-1] = 0;
  3520. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3521. }
  3522. if (schedstart.enable)
  3523. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3524. if (schedstop.enable)
  3525. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3526. if (opt_socks_proxy && *opt_socks_proxy)
  3527. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3528. #ifdef HAVE_OPENCL
  3529. for(i = 0; i < nDevs; i++)
  3530. if (gpus[i].deven == DEV_DISABLED)
  3531. break;
  3532. if (i < nDevs)
  3533. for (i = 0; i < nDevs; i++)
  3534. if (gpus[i].deven != DEV_DISABLED)
  3535. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3536. #endif
  3537. if (opt_api_allow)
  3538. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3539. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3540. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3541. if (opt_api_groups)
  3542. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3543. if (opt_icarus_options)
  3544. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3545. if (opt_icarus_timing)
  3546. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3547. #ifdef USE_USBUTILS
  3548. if (opt_usb_select)
  3549. fprintf(fcfg, ",\n\"usb\" : \"%s\"", json_escape(opt_usb_select));
  3550. #endif
  3551. fputs("\n}\n", fcfg);
  3552. json_escape_free();
  3553. }
  3554. void zero_bestshare(void)
  3555. {
  3556. int i;
  3557. best_diff = 0;
  3558. memset(best_share, 0, 8);
  3559. suffix_string(best_diff, best_share, 0);
  3560. for (i = 0; i < total_pools; i++) {
  3561. struct pool *pool = pools[i];
  3562. pool->best_diff = 0;
  3563. }
  3564. }
  3565. void zero_stats(void)
  3566. {
  3567. int i;
  3568. gettimeofday(&total_tv_start, NULL);
  3569. total_mhashes_done = 0;
  3570. total_getworks = 0;
  3571. total_accepted = 0;
  3572. total_rejected = 0;
  3573. hw_errors = 0;
  3574. total_stale = 0;
  3575. total_discarded = 0;
  3576. local_work = 0;
  3577. total_go = 0;
  3578. total_ro = 0;
  3579. total_secs = 1.0;
  3580. total_diff1 = 0;
  3581. found_blocks = 0;
  3582. total_diff_accepted = 0;
  3583. total_diff_rejected = 0;
  3584. total_diff_stale = 0;
  3585. for (i = 0; i < total_pools; i++) {
  3586. struct pool *pool = pools[i];
  3587. pool->getwork_requested = 0;
  3588. pool->accepted = 0;
  3589. pool->rejected = 0;
  3590. pool->stale_shares = 0;
  3591. pool->discarded_work = 0;
  3592. pool->getfail_occasions = 0;
  3593. pool->remotefail_occasions = 0;
  3594. pool->last_share_time = 0;
  3595. pool->diff1 = 0;
  3596. pool->diff_accepted = 0;
  3597. pool->diff_rejected = 0;
  3598. pool->diff_stale = 0;
  3599. pool->last_share_diff = 0;
  3600. }
  3601. zero_bestshare();
  3602. for (i = 0; i < total_devices; ++i) {
  3603. struct cgpu_info *cgpu = get_devices(i);
  3604. mutex_lock(&hash_lock);
  3605. cgpu->total_mhashes = 0;
  3606. cgpu->accepted = 0;
  3607. cgpu->rejected = 0;
  3608. cgpu->hw_errors = 0;
  3609. cgpu->utility = 0.0;
  3610. cgpu->last_share_pool_time = 0;
  3611. cgpu->diff1 = 0;
  3612. cgpu->diff_accepted = 0;
  3613. cgpu->diff_rejected = 0;
  3614. cgpu->last_share_diff = 0;
  3615. mutex_unlock(&hash_lock);
  3616. }
  3617. }
  3618. #ifdef HAVE_CURSES
  3619. static void display_pools(void)
  3620. {
  3621. struct pool *pool;
  3622. int selected, i;
  3623. char input;
  3624. opt_loginput = true;
  3625. immedok(logwin, true);
  3626. clear_logwin();
  3627. updated:
  3628. for (i = 0; i < total_pools; i++) {
  3629. pool = pools[i];
  3630. if (pool == current_pool())
  3631. wattron(logwin, A_BOLD);
  3632. if (pool->enabled != POOL_ENABLED)
  3633. wattron(logwin, A_DIM);
  3634. wlogprint("%d: ", pool->pool_no);
  3635. switch (pool->enabled) {
  3636. case POOL_ENABLED:
  3637. wlogprint("Enabled ");
  3638. break;
  3639. case POOL_DISABLED:
  3640. wlogprint("Disabled ");
  3641. break;
  3642. case POOL_REJECTING:
  3643. wlogprint("Rejecting ");
  3644. break;
  3645. }
  3646. wlogprint("%s Priority %d: %s User:%s\n",
  3647. pool->idle? "Dead" : "Alive",
  3648. pool->prio,
  3649. pool->rpc_url, pool->rpc_user);
  3650. wattroff(logwin, A_BOLD | A_DIM);
  3651. }
  3652. retry:
  3653. wlogprint("\nCurrent pool management strategy: %s\n",
  3654. strategies[pool_strategy]);
  3655. if (pool_strategy == POOL_ROTATE)
  3656. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3657. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3658. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3659. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3660. wlogprint("Or press any other key to continue\n");
  3661. input = getch();
  3662. if (!strncasecmp(&input, "a", 1)) {
  3663. input_pool(true);
  3664. goto updated;
  3665. } else if (!strncasecmp(&input, "r", 1)) {
  3666. if (total_pools <= 1) {
  3667. wlogprint("Cannot remove last pool");
  3668. goto retry;
  3669. }
  3670. selected = curses_int("Select pool number");
  3671. if (selected < 0 || selected >= total_pools) {
  3672. wlogprint("Invalid selection\n");
  3673. goto retry;
  3674. }
  3675. pool = pools[selected];
  3676. if (pool == current_pool())
  3677. switch_pools(NULL);
  3678. if (pool == current_pool()) {
  3679. wlogprint("Unable to remove pool due to activity\n");
  3680. goto retry;
  3681. }
  3682. disable_pool(pool);
  3683. remove_pool(pool);
  3684. goto updated;
  3685. } else if (!strncasecmp(&input, "s", 1)) {
  3686. selected = curses_int("Select pool number");
  3687. if (selected < 0 || selected >= total_pools) {
  3688. wlogprint("Invalid selection\n");
  3689. goto retry;
  3690. }
  3691. pool = pools[selected];
  3692. enable_pool(pool);
  3693. switch_pools(pool);
  3694. goto updated;
  3695. } else if (!strncasecmp(&input, "d", 1)) {
  3696. if (enabled_pools <= 1) {
  3697. wlogprint("Cannot disable last pool");
  3698. goto retry;
  3699. }
  3700. selected = curses_int("Select pool number");
  3701. if (selected < 0 || selected >= total_pools) {
  3702. wlogprint("Invalid selection\n");
  3703. goto retry;
  3704. }
  3705. pool = pools[selected];
  3706. disable_pool(pool);
  3707. if (pool == current_pool())
  3708. switch_pools(NULL);
  3709. goto updated;
  3710. } else if (!strncasecmp(&input, "e", 1)) {
  3711. selected = curses_int("Select pool number");
  3712. if (selected < 0 || selected >= total_pools) {
  3713. wlogprint("Invalid selection\n");
  3714. goto retry;
  3715. }
  3716. pool = pools[selected];
  3717. enable_pool(pool);
  3718. if (pool->prio < current_pool()->prio)
  3719. switch_pools(pool);
  3720. goto updated;
  3721. } else if (!strncasecmp(&input, "c", 1)) {
  3722. for (i = 0; i <= TOP_STRATEGY; i++)
  3723. wlogprint("%d: %s\n", i, strategies[i]);
  3724. selected = curses_int("Select strategy number type");
  3725. if (selected < 0 || selected > TOP_STRATEGY) {
  3726. wlogprint("Invalid selection\n");
  3727. goto retry;
  3728. }
  3729. if (selected == POOL_ROTATE) {
  3730. opt_rotate_period = curses_int("Select interval in minutes");
  3731. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3732. opt_rotate_period = 0;
  3733. wlogprint("Invalid selection\n");
  3734. goto retry;
  3735. }
  3736. }
  3737. pool_strategy = selected;
  3738. switch_pools(NULL);
  3739. goto updated;
  3740. } else if (!strncasecmp(&input, "i", 1)) {
  3741. selected = curses_int("Select pool number");
  3742. if (selected < 0 || selected >= total_pools) {
  3743. wlogprint("Invalid selection\n");
  3744. goto retry;
  3745. }
  3746. pool = pools[selected];
  3747. display_pool_summary(pool);
  3748. goto retry;
  3749. } else if (!strncasecmp(&input, "f", 1)) {
  3750. opt_fail_only ^= true;
  3751. goto updated;
  3752. } else
  3753. clear_logwin();
  3754. immedok(logwin, false);
  3755. opt_loginput = false;
  3756. }
  3757. static void display_options(void)
  3758. {
  3759. int selected;
  3760. char input;
  3761. opt_loginput = true;
  3762. immedok(logwin, true);
  3763. clear_logwin();
  3764. retry:
  3765. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3766. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  3767. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  3768. "[L]og interval:%d\n[Z]ero statistics\n",
  3769. opt_debug ? "on" : "off",
  3770. want_per_device_stats? "on" : "off",
  3771. opt_quiet ? "on" : "off",
  3772. opt_log_output ? "on" : "off",
  3773. opt_protocol ? "on" : "off",
  3774. opt_worktime ? "on" : "off",
  3775. opt_compact ? "on" : "off",
  3776. opt_log_interval);
  3777. wlogprint("Select an option or any other key to return\n");
  3778. input = getch();
  3779. if (!strncasecmp(&input, "q", 1)) {
  3780. opt_quiet ^= true;
  3781. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3782. goto retry;
  3783. } else if (!strncasecmp(&input, "v", 1)) {
  3784. opt_log_output ^= true;
  3785. if (opt_log_output)
  3786. opt_quiet = false;
  3787. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3788. goto retry;
  3789. } else if (!strncasecmp(&input, "n", 1)) {
  3790. opt_log_output = false;
  3791. opt_debug = false;
  3792. opt_quiet = false;
  3793. opt_protocol = false;
  3794. opt_compact = false;
  3795. want_per_device_stats = false;
  3796. wlogprint("Output mode reset to normal\n");
  3797. switch_compact();
  3798. goto retry;
  3799. } else if (!strncasecmp(&input, "d", 1)) {
  3800. opt_debug ^= true;
  3801. opt_log_output = opt_debug;
  3802. if (opt_debug)
  3803. opt_quiet = false;
  3804. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  3805. goto retry;
  3806. } else if (!strncasecmp(&input, "m", 1)) {
  3807. opt_compact ^= true;
  3808. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  3809. switch_compact();
  3810. goto retry;
  3811. } else if (!strncasecmp(&input, "p", 1)) {
  3812. want_per_device_stats ^= true;
  3813. opt_log_output = want_per_device_stats;
  3814. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3815. goto retry;
  3816. } else if (!strncasecmp(&input, "r", 1)) {
  3817. opt_protocol ^= true;
  3818. if (opt_protocol)
  3819. opt_quiet = false;
  3820. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3821. goto retry;
  3822. } else if (!strncasecmp(&input, "c", 1))
  3823. clear_logwin();
  3824. else if (!strncasecmp(&input, "l", 1)) {
  3825. selected = curses_int("Interval in seconds");
  3826. if (selected < 0 || selected > 9999) {
  3827. wlogprint("Invalid selection\n");
  3828. goto retry;
  3829. }
  3830. opt_log_interval = selected;
  3831. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3832. goto retry;
  3833. } else if (!strncasecmp(&input, "s", 1)) {
  3834. opt_realquiet = true;
  3835. } else if (!strncasecmp(&input, "w", 1)) {
  3836. opt_worktime ^= true;
  3837. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  3838. goto retry;
  3839. } else if (!strncasecmp(&input, "z", 1)) {
  3840. zero_stats();
  3841. goto retry;
  3842. } else
  3843. clear_logwin();
  3844. immedok(logwin, false);
  3845. opt_loginput = false;
  3846. }
  3847. #endif
  3848. void default_save_file(char *filename)
  3849. {
  3850. if (default_config && *default_config) {
  3851. strcpy(filename, default_config);
  3852. return;
  3853. }
  3854. #if defined(unix)
  3855. if (getenv("HOME") && *getenv("HOME")) {
  3856. strcpy(filename, getenv("HOME"));
  3857. strcat(filename, "/");
  3858. }
  3859. else
  3860. strcpy(filename, "");
  3861. strcat(filename, ".cgminer/");
  3862. mkdir(filename, 0777);
  3863. #else
  3864. strcpy(filename, "");
  3865. #endif
  3866. strcat(filename, def_conf);
  3867. }
  3868. #ifdef HAVE_CURSES
  3869. static void set_options(void)
  3870. {
  3871. int selected;
  3872. char input;
  3873. opt_loginput = true;
  3874. immedok(logwin, true);
  3875. clear_logwin();
  3876. retry:
  3877. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  3878. "[W]rite config file\n[C]gminer restart\n",
  3879. opt_queue, opt_scantime, opt_expiry);
  3880. wlogprint("Select an option or any other key to return\n");
  3881. input = getch();
  3882. if (!strncasecmp(&input, "q", 1)) {
  3883. selected = curses_int("Extra work items to queue");
  3884. if (selected < 0 || selected > 9999) {
  3885. wlogprint("Invalid selection\n");
  3886. goto retry;
  3887. }
  3888. opt_queue = selected;
  3889. goto retry;
  3890. } else if (!strncasecmp(&input, "s", 1)) {
  3891. selected = curses_int("Set scantime in seconds");
  3892. if (selected < 0 || selected > 9999) {
  3893. wlogprint("Invalid selection\n");
  3894. goto retry;
  3895. }
  3896. opt_scantime = selected;
  3897. goto retry;
  3898. } else if (!strncasecmp(&input, "e", 1)) {
  3899. selected = curses_int("Set expiry time in seconds");
  3900. if (selected < 0 || selected > 9999) {
  3901. wlogprint("Invalid selection\n");
  3902. goto retry;
  3903. }
  3904. opt_expiry = selected;
  3905. goto retry;
  3906. } else if (!strncasecmp(&input, "w", 1)) {
  3907. FILE *fcfg;
  3908. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3909. default_save_file(filename);
  3910. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3911. str = curses_input(prompt);
  3912. if (strcmp(str, "-1")) {
  3913. struct stat statbuf;
  3914. strcpy(filename, str);
  3915. free(str);
  3916. if (!stat(filename, &statbuf)) {
  3917. wlogprint("File exists, overwrite?\n");
  3918. input = getch();
  3919. if (strncasecmp(&input, "y", 1))
  3920. goto retry;
  3921. }
  3922. }
  3923. else
  3924. free(str);
  3925. fcfg = fopen(filename, "w");
  3926. if (!fcfg) {
  3927. wlogprint("Cannot open or create file\n");
  3928. goto retry;
  3929. }
  3930. write_config(fcfg);
  3931. fclose(fcfg);
  3932. goto retry;
  3933. } else if (!strncasecmp(&input, "c", 1)) {
  3934. wlogprint("Are you sure?\n");
  3935. input = getch();
  3936. if (!strncasecmp(&input, "y", 1))
  3937. app_restart();
  3938. else
  3939. clear_logwin();
  3940. } else
  3941. clear_logwin();
  3942. immedok(logwin, false);
  3943. opt_loginput = false;
  3944. }
  3945. static void *input_thread(void __maybe_unused *userdata)
  3946. {
  3947. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3948. RenameThread("input");
  3949. if (!curses_active)
  3950. return NULL;
  3951. while (1) {
  3952. char input;
  3953. input = getch();
  3954. if (!strncasecmp(&input, "q", 1)) {
  3955. kill_work();
  3956. return NULL;
  3957. } else if (!strncasecmp(&input, "d", 1))
  3958. display_options();
  3959. else if (!strncasecmp(&input, "p", 1))
  3960. display_pools();
  3961. else if (!strncasecmp(&input, "s", 1))
  3962. set_options();
  3963. else if (have_opencl && !strncasecmp(&input, "g", 1))
  3964. manage_gpu();
  3965. if (opt_realquiet) {
  3966. disable_curses();
  3967. break;
  3968. }
  3969. }
  3970. return NULL;
  3971. }
  3972. #endif
  3973. static void *api_thread(void *userdata)
  3974. {
  3975. struct thr_info *mythr = userdata;
  3976. pthread_detach(pthread_self());
  3977. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3978. RenameThread("api");
  3979. api(api_thr_id);
  3980. PTH(mythr) = 0L;
  3981. return NULL;
  3982. }
  3983. void thread_reportin(struct thr_info *thr)
  3984. {
  3985. gettimeofday(&thr->last, NULL);
  3986. thr->cgpu->status = LIFE_WELL;
  3987. thr->getwork = false;
  3988. thr->cgpu->device_last_well = time(NULL);
  3989. }
  3990. static inline void thread_reportout(struct thr_info *thr)
  3991. {
  3992. thr->getwork = true;
  3993. }
  3994. static void hashmeter(int thr_id, struct timeval *diff,
  3995. uint64_t hashes_done)
  3996. {
  3997. struct timeval temp_tv_end, total_diff;
  3998. double secs;
  3999. double local_secs;
  4000. double utility, efficiency = 0.0;
  4001. static double local_mhashes_done = 0;
  4002. static double rolling = 0;
  4003. double local_mhashes;
  4004. bool showlog = false;
  4005. char displayed_hashes[16], displayed_rolling[16];
  4006. uint64_t dh64, dr64;
  4007. struct thr_info *thr;
  4008. local_mhashes = (double)hashes_done / 1000000.0;
  4009. /* Update the last time this thread reported in */
  4010. if (thr_id >= 0) {
  4011. thr = get_thread(thr_id);
  4012. gettimeofday(&(thr->last), NULL);
  4013. thr->cgpu->device_last_well = time(NULL);
  4014. }
  4015. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  4016. /* So we can call hashmeter from a non worker thread */
  4017. if (thr_id >= 0) {
  4018. struct cgpu_info *cgpu = thr->cgpu;
  4019. double thread_rolling = 0.0;
  4020. int i;
  4021. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  4022. thr_id, hashes_done, hashes_done / 1000 / secs);
  4023. /* Rolling average for each thread and each device */
  4024. decay_time(&thr->rolling, local_mhashes / secs);
  4025. for (i = 0; i < cgpu->threads; i++)
  4026. thread_rolling += cgpu->thr[i]->rolling;
  4027. mutex_lock(&hash_lock);
  4028. decay_time(&cgpu->rolling, thread_rolling);
  4029. cgpu->total_mhashes += local_mhashes;
  4030. mutex_unlock(&hash_lock);
  4031. // If needed, output detailed, per-device stats
  4032. if (want_per_device_stats) {
  4033. struct timeval now;
  4034. struct timeval elapsed;
  4035. gettimeofday(&now, NULL);
  4036. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  4037. if (opt_log_interval <= elapsed.tv_sec) {
  4038. struct cgpu_info *cgpu = thr->cgpu;
  4039. char logline[255];
  4040. cgpu->last_message_tv = now;
  4041. get_statline(logline, cgpu);
  4042. if (!curses_active) {
  4043. printf("%s \r", logline);
  4044. fflush(stdout);
  4045. } else
  4046. applog(LOG_INFO, "%s", logline);
  4047. }
  4048. }
  4049. }
  4050. /* Totals are updated by all threads so can race without locking */
  4051. mutex_lock(&hash_lock);
  4052. gettimeofday(&temp_tv_end, NULL);
  4053. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  4054. total_mhashes_done += local_mhashes;
  4055. local_mhashes_done += local_mhashes;
  4056. /* Only update the total every second */
  4057. if (!total_diff.tv_sec)
  4058. goto out_unlock;
  4059. if (total_diff.tv_sec >= opt_log_interval)
  4060. showlog = true;
  4061. gettimeofday(&total_tv_end, NULL);
  4062. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  4063. decay_time(&rolling, local_mhashes_done / local_secs);
  4064. global_hashrate = roundl(rolling) * 1000000;
  4065. timersub(&total_tv_end, &total_tv_start, &total_diff);
  4066. total_secs = (double)total_diff.tv_sec +
  4067. ((double)total_diff.tv_usec / 1000000.0);
  4068. utility = total_accepted / total_secs * 60;
  4069. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4070. dh64 = (double)total_mhashes_done / total_secs * 1000000ull;
  4071. dr64 = (double)rolling * 1000000ull;
  4072. suffix_string(dh64, displayed_hashes, 4);
  4073. suffix_string(dr64, displayed_rolling, 4);
  4074. sprintf(statusline, "%s(%ds):%s (avg):%sh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  4075. want_per_device_stats ? "ALL " : "",
  4076. opt_log_interval, displayed_rolling, displayed_hashes,
  4077. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  4078. local_mhashes_done = 0;
  4079. out_unlock:
  4080. mutex_unlock(&hash_lock);
  4081. if (showlog) {
  4082. if (!curses_active) {
  4083. printf("%s \r", statusline);
  4084. fflush(stdout);
  4085. } else
  4086. applog(LOG_INFO, "%s", statusline);
  4087. }
  4088. }
  4089. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  4090. struct stratum_share *sshare)
  4091. {
  4092. struct work *work = sshare->work;
  4093. uint64_t sharediff = share_diff(work);
  4094. char hashshow[65];
  4095. uint32_t *hash32;
  4096. char diffdisp[16];
  4097. int intdiff;
  4098. hash32 = (uint32_t *)(work->hash);
  4099. intdiff = floor(work->work_difficulty);
  4100. suffix_string(sharediff, diffdisp, 0);
  4101. sprintf(hashshow, "%08lx Diff %s/%d%s", (unsigned long)(hash32[6]), diffdisp, intdiff,
  4102. work->block? " BLOCK!" : "");
  4103. share_result(val, res_val, err_val, work, hashshow, false, "");
  4104. }
  4105. /* Parses stratum json responses and tries to find the id that the request
  4106. * matched to and treat it accordingly. */
  4107. static bool parse_stratum_response(struct pool *pool, char *s)
  4108. {
  4109. json_t *val = NULL, *err_val, *res_val, *id_val;
  4110. struct stratum_share *sshare;
  4111. json_error_t err;
  4112. bool ret = false;
  4113. int id;
  4114. val = JSON_LOADS(s, &err);
  4115. if (!val) {
  4116. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  4117. goto out;
  4118. }
  4119. res_val = json_object_get(val, "result");
  4120. err_val = json_object_get(val, "error");
  4121. id_val = json_object_get(val, "id");
  4122. if (json_is_null(id_val) || !id_val) {
  4123. char *ss;
  4124. if (err_val)
  4125. ss = json_dumps(err_val, JSON_INDENT(3));
  4126. else
  4127. ss = strdup("(unknown reason)");
  4128. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  4129. free(ss);
  4130. goto out;
  4131. }
  4132. id = json_integer_value(id_val);
  4133. mutex_lock(&sshare_lock);
  4134. HASH_FIND_INT(stratum_shares, &id, sshare);
  4135. if (sshare) {
  4136. HASH_DEL(stratum_shares, sshare);
  4137. pool->sshares--;
  4138. }
  4139. mutex_unlock(&sshare_lock);
  4140. if (!sshare) {
  4141. if (json_is_true(res_val))
  4142. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  4143. else
  4144. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  4145. goto out;
  4146. }
  4147. stratum_share_result(val, res_val, err_val, sshare);
  4148. free_work(sshare->work);
  4149. free(sshare);
  4150. ret = true;
  4151. out:
  4152. if (val)
  4153. json_decref(val);
  4154. return ret;
  4155. }
  4156. void clear_stratum_shares(struct pool *pool)
  4157. {
  4158. struct stratum_share *sshare, *tmpshare;
  4159. double diff_cleared = 0;
  4160. int cleared = 0;
  4161. mutex_lock(&sshare_lock);
  4162. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  4163. if (sshare->work->pool == pool) {
  4164. HASH_DEL(stratum_shares, sshare);
  4165. diff_cleared += sshare->work->work_difficulty;
  4166. free_work(sshare->work);
  4167. pool->sshares--;
  4168. free(sshare);
  4169. cleared++;
  4170. }
  4171. }
  4172. mutex_unlock(&sshare_lock);
  4173. if (cleared) {
  4174. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  4175. pool->stale_shares += cleared;
  4176. total_stale += cleared;
  4177. pool->diff_stale += diff_cleared;
  4178. total_diff_stale += diff_cleared;
  4179. }
  4180. }
  4181. static void clear_pool_work(struct pool *pool)
  4182. {
  4183. struct work *work, *tmp;
  4184. int cleared = 0;
  4185. mutex_lock(stgd_lock);
  4186. HASH_ITER(hh, staged_work, work, tmp) {
  4187. if (work->pool == pool) {
  4188. HASH_DEL(staged_work, work);
  4189. free_work(work);
  4190. cleared++;
  4191. }
  4192. }
  4193. mutex_unlock(stgd_lock);
  4194. }
  4195. static int cp_prio(void)
  4196. {
  4197. int prio;
  4198. cg_rlock(&control_lock);
  4199. prio = currentpool->prio;
  4200. cg_runlock(&control_lock);
  4201. return prio;
  4202. }
  4203. /* We only need to maintain a secondary pool connection when we need the
  4204. * capacity to get work from the backup pools while still on the primary */
  4205. static bool cnx_needed(struct pool *pool)
  4206. {
  4207. struct pool *cp;
  4208. /* Balance strategies need all pools online */
  4209. if (pool_strategy == POOL_BALANCE)
  4210. return true;
  4211. if (pool_strategy == POOL_LOADBALANCE)
  4212. return true;
  4213. /* Idle stratum pool needs something to kick it alive again */
  4214. if (pool->has_stratum && pool->idle)
  4215. return true;
  4216. /* Getwork pools without opt_fail_only need backup pools up to be able
  4217. * to leak shares */
  4218. cp = current_pool();
  4219. if (cp == pool)
  4220. return true;
  4221. if (!cp->has_gbt && !cp->has_stratum && (!opt_fail_only || !cp->hdr_path))
  4222. return true;
  4223. /* If we're waiting for a response from shares submitted, keep the
  4224. * connection open. */
  4225. if (pool->sshares)
  4226. return true;
  4227. /* If the pool has only just come to life and is higher priority than
  4228. * the current pool keep the connection open so we can fail back to
  4229. * it. */
  4230. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  4231. return true;
  4232. if (pool_unworkable(cp))
  4233. return true;
  4234. return false;
  4235. }
  4236. static void wait_lpcurrent(struct pool *pool);
  4237. static void pool_resus(struct pool *pool);
  4238. static void gen_stratum_work(struct pool *pool, struct work *work);
  4239. static void stratum_resumed(struct pool *pool)
  4240. {
  4241. if (!pool->stratum_notify)
  4242. return;
  4243. if (pool_tclear(pool, &pool->idle)) {
  4244. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  4245. pool_resus(pool);
  4246. }
  4247. }
  4248. static bool supports_resume(struct pool *pool)
  4249. {
  4250. bool ret;
  4251. cg_rlock(&pool->data_lock);
  4252. ret = (pool->sessionid != NULL);
  4253. cg_runlock(&pool->data_lock);
  4254. return ret;
  4255. }
  4256. /* One stratum thread per pool that has stratum waits on the socket checking
  4257. * for new messages and for the integrity of the socket connection. We reset
  4258. * the connection based on the integrity of the receive side only as the send
  4259. * side will eventually expire data it fails to send. */
  4260. static void *stratum_thread(void *userdata)
  4261. {
  4262. struct pool *pool = (struct pool *)userdata;
  4263. char threadname[16];
  4264. pthread_detach(pthread_self());
  4265. snprintf(threadname, 16, "stratum/%d", pool->pool_no);
  4266. RenameThread(threadname);
  4267. while (42) {
  4268. struct timeval timeout;
  4269. int sel_ret;
  4270. fd_set rd;
  4271. char *s;
  4272. if (unlikely(pool->removed))
  4273. break;
  4274. /* Check to see whether we need to maintain this connection
  4275. * indefinitely or just bring it up when we switch to this
  4276. * pool */
  4277. if (!sock_full(pool) && !cnx_needed(pool)) {
  4278. suspend_stratum(pool);
  4279. clear_stratum_shares(pool);
  4280. clear_pool_work(pool);
  4281. wait_lpcurrent(pool);
  4282. if (!restart_stratum(pool)) {
  4283. pool_died(pool);
  4284. while (!restart_stratum(pool)) {
  4285. if (pool->removed)
  4286. goto out;
  4287. nmsleep(30000);
  4288. }
  4289. }
  4290. }
  4291. FD_ZERO(&rd);
  4292. FD_SET(pool->sock, &rd);
  4293. timeout.tv_sec = 90;
  4294. timeout.tv_usec = 0;
  4295. /* The protocol specifies that notify messages should be sent
  4296. * every minute so if we fail to receive any for 90 seconds we
  4297. * assume the connection has been dropped and treat this pool
  4298. * as dead */
  4299. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  4300. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  4301. s = NULL;
  4302. } else
  4303. s = recv_line(pool);
  4304. if (!s) {
  4305. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  4306. pool->getfail_occasions++;
  4307. total_go++;
  4308. /* If the socket to our stratum pool disconnects, all
  4309. * tracked submitted shares are lost and we will leak
  4310. * the memory if we don't discard their records. */
  4311. if (!supports_resume(pool))
  4312. clear_stratum_shares(pool);
  4313. clear_pool_work(pool);
  4314. if (pool == current_pool())
  4315. restart_threads();
  4316. if (restart_stratum(pool))
  4317. continue;
  4318. pool_died(pool);
  4319. while (!restart_stratum(pool)) {
  4320. if (pool->removed)
  4321. goto out;
  4322. nmsleep(30000);
  4323. }
  4324. stratum_resumed(pool);
  4325. continue;
  4326. }
  4327. /* Check this pool hasn't died while being a backup pool and
  4328. * has not had its idle flag cleared */
  4329. stratum_resumed(pool);
  4330. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  4331. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  4332. free(s);
  4333. if (pool->swork.clean) {
  4334. struct work *work = make_work();
  4335. /* Generate a single work item to update the current
  4336. * block database */
  4337. pool->swork.clean = false;
  4338. gen_stratum_work(pool, work);
  4339. if (test_work_current(work)) {
  4340. /* Only accept a work restart if this stratum
  4341. * connection is from the current pool */
  4342. if (pool == current_pool()) {
  4343. restart_threads();
  4344. applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
  4345. }
  4346. } else
  4347. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  4348. free_work(work);
  4349. }
  4350. }
  4351. out:
  4352. return NULL;
  4353. }
  4354. static void init_stratum_thread(struct pool *pool)
  4355. {
  4356. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  4357. quit(1, "Failed to create stratum thread");
  4358. }
  4359. static void *longpoll_thread(void *userdata);
  4360. static bool stratum_works(struct pool *pool)
  4361. {
  4362. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  4363. if (!extract_sockaddr(pool, pool->stratum_url))
  4364. return false;
  4365. if (!initiate_stratum(pool))
  4366. return false;
  4367. return true;
  4368. }
  4369. static bool pool_active(struct pool *pool, bool pinging)
  4370. {
  4371. struct timeval tv_getwork, tv_getwork_reply;
  4372. bool ret = false;
  4373. json_t *val;
  4374. CURL *curl;
  4375. int rolltime;
  4376. if (pool->has_gbt)
  4377. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  4378. else
  4379. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  4380. /* This is the central point we activate stratum when we can */
  4381. retry_stratum:
  4382. if (pool->has_stratum) {
  4383. /* We create the stratum thread for each pool just after
  4384. * successful authorisation. Once the init flag has been set
  4385. * we never unset it and the stratum thread is responsible for
  4386. * setting/unsetting the active flag */
  4387. bool init = pool_tset(pool, &pool->stratum_init);
  4388. if (!init) {
  4389. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  4390. if (ret)
  4391. init_stratum_thread(pool);
  4392. else
  4393. pool_tclear(pool, &pool->stratum_init);
  4394. return ret;
  4395. }
  4396. return pool->stratum_active;
  4397. }
  4398. curl = curl_easy_init();
  4399. if (unlikely(!curl)) {
  4400. applog(LOG_ERR, "CURL initialisation failed");
  4401. return false;
  4402. }
  4403. /* Probe for GBT support on first pass */
  4404. if (!pool->probed && !opt_fix_protocol) {
  4405. applog(LOG_DEBUG, "Probing for GBT support");
  4406. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4407. gbt_req, true, false, &rolltime, pool, false);
  4408. if (val) {
  4409. bool append = false, submit = false;
  4410. json_t *res_val, *mutables;
  4411. int i, mutsize = 0;
  4412. res_val = json_object_get(val, "result");
  4413. if (res_val) {
  4414. mutables = json_object_get(res_val, "mutable");
  4415. mutsize = json_array_size(mutables);
  4416. }
  4417. for (i = 0; i < mutsize; i++) {
  4418. json_t *arrval = json_array_get(mutables, i);
  4419. if (json_is_string(arrval)) {
  4420. const char *mutable = json_string_value(arrval);
  4421. if (!strncasecmp(mutable, "coinbase/append", 15))
  4422. append = true;
  4423. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  4424. submit = true;
  4425. }
  4426. }
  4427. json_decref(val);
  4428. /* Only use GBT if it supports coinbase append and
  4429. * submit coinbase */
  4430. if (append && submit) {
  4431. pool->has_gbt = true;
  4432. pool->rpc_req = gbt_req;
  4433. }
  4434. }
  4435. /* Reset this so we can probe fully just after this. It will be
  4436. * set to true that time.*/
  4437. pool->probed = false;
  4438. if (pool->has_gbt)
  4439. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  4440. else
  4441. applog(LOG_DEBUG, "No GBT coinbase + append support found, using getwork protocol");
  4442. }
  4443. gettimeofday(&tv_getwork, NULL);
  4444. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  4445. pool->rpc_req, true, false, &rolltime, pool, false);
  4446. gettimeofday(&tv_getwork_reply, NULL);
  4447. /* Detect if a http getwork pool has an X-Stratum header at startup,
  4448. * and if so, switch to that in preference to getwork if it works */
  4449. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  4450. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  4451. if (!pool->rpc_url)
  4452. pool->rpc_url = strdup(pool->stratum_url);
  4453. pool->has_stratum = true;
  4454. curl_easy_cleanup(curl);
  4455. goto retry_stratum;
  4456. }
  4457. if (val) {
  4458. struct work *work = make_work();
  4459. bool rc;
  4460. rc = work_decode(pool, work, val);
  4461. if (rc) {
  4462. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4463. pool->pool_no, pool->rpc_url);
  4464. work->pool = pool;
  4465. work->rolltime = rolltime;
  4466. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  4467. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  4468. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  4469. calc_diff(work, 0);
  4470. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4471. tq_push(control_thr[stage_thr_id].q, work);
  4472. total_getworks++;
  4473. pool->getwork_requested++;
  4474. ret = true;
  4475. gettimeofday(&pool->tv_idle, NULL);
  4476. } else {
  4477. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4478. pool->pool_no, pool->rpc_url);
  4479. free_work(work);
  4480. }
  4481. json_decref(val);
  4482. if (pool->lp_url)
  4483. goto out;
  4484. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4485. if (pool->hdr_path) {
  4486. char *copy_start, *hdr_path;
  4487. bool need_slash = false;
  4488. hdr_path = pool->hdr_path;
  4489. if (strstr(hdr_path, "://")) {
  4490. pool->lp_url = hdr_path;
  4491. hdr_path = NULL;
  4492. } else {
  4493. /* absolute path, on current server */
  4494. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  4495. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  4496. need_slash = true;
  4497. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  4498. if (!pool->lp_url) {
  4499. applog(LOG_ERR, "Malloc failure in pool_active");
  4500. return false;
  4501. }
  4502. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  4503. }
  4504. } else
  4505. pool->lp_url = NULL;
  4506. if (!pool->lp_started) {
  4507. pool->lp_started = true;
  4508. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4509. quit(1, "Failed to create pool longpoll thread");
  4510. }
  4511. } else {
  4512. /* If we failed to parse a getwork, this could be a stratum
  4513. * url without the prefix stratum+tcp:// so let's check it */
  4514. if (initiate_stratum(pool)) {
  4515. pool->has_stratum = true;
  4516. goto retry_stratum;
  4517. }
  4518. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4519. pool->pool_no, pool->rpc_url);
  4520. if (!pinging)
  4521. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4522. }
  4523. out:
  4524. curl_easy_cleanup(curl);
  4525. return ret;
  4526. }
  4527. static void pool_resus(struct pool *pool)
  4528. {
  4529. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio()) {
  4530. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4531. switch_pools(NULL);
  4532. } else
  4533. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4534. }
  4535. static struct work *hash_pop(void)
  4536. {
  4537. struct work *work = NULL, *tmp;
  4538. int hc;
  4539. mutex_lock(stgd_lock);
  4540. while (!getq->frozen && !HASH_COUNT(staged_work))
  4541. pthread_cond_wait(&getq->cond, stgd_lock);
  4542. hc = HASH_COUNT(staged_work);
  4543. /* Find clone work if possible, to allow masters to be reused */
  4544. if (hc > staged_rollable) {
  4545. HASH_ITER(hh, staged_work, work, tmp) {
  4546. if (!work_rollable(work))
  4547. break;
  4548. }
  4549. } else
  4550. work = staged_work;
  4551. HASH_DEL(staged_work, work);
  4552. if (work_rollable(work))
  4553. staged_rollable--;
  4554. /* Signal the getwork scheduler to look for more work */
  4555. pthread_cond_signal(&gws_cond);
  4556. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  4557. pthread_cond_signal(&getq->cond);
  4558. mutex_unlock(stgd_lock);
  4559. return work;
  4560. }
  4561. /* Clones work by rolling it if possible, and returning a clone instead of the
  4562. * original work item which gets staged again to possibly be rolled again in
  4563. * the future */
  4564. static struct work *clone_work(struct work *work)
  4565. {
  4566. int mrs = mining_threads + opt_queue - total_staged();
  4567. struct work *work_clone;
  4568. bool cloned;
  4569. if (mrs < 1)
  4570. return work;
  4571. cloned = false;
  4572. work_clone = make_clone(work);
  4573. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4574. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4575. stage_work(work_clone);
  4576. roll_work(work);
  4577. work_clone = make_clone(work);
  4578. /* Roll it again to prevent duplicates should this be used
  4579. * directly later on */
  4580. roll_work(work);
  4581. cloned = true;
  4582. }
  4583. if (cloned) {
  4584. stage_work(work);
  4585. return work_clone;
  4586. }
  4587. free_work(work_clone);
  4588. return work;
  4589. }
  4590. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  4591. {
  4592. unsigned char hash1[32];
  4593. sha2(data, len, hash1);
  4594. sha2(hash1, 32, hash);
  4595. }
  4596. /* Diff 1 is a 256 bit unsigned integer of
  4597. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  4598. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  4599. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  4600. static void set_work_target(struct work *work, double diff)
  4601. {
  4602. unsigned char target[32];
  4603. uint64_t *data64, h64;
  4604. double d64;
  4605. d64 = diffone;
  4606. d64 /= diff;
  4607. h64 = d64;
  4608. memset(target, 0, 32);
  4609. if (h64) {
  4610. unsigned char rtarget[32];
  4611. memset(rtarget, 0, 32);
  4612. if (opt_scrypt)
  4613. data64 = (uint64_t *)(rtarget + 2);
  4614. else
  4615. data64 = (uint64_t *)(rtarget + 4);
  4616. *data64 = htobe64(h64);
  4617. swab256(target, rtarget);
  4618. } else {
  4619. /* Support for the classic all FFs just-below-1 diff */
  4620. if (opt_scrypt)
  4621. memset(target, 0xff, 30);
  4622. else
  4623. memset(target, 0xff, 28);
  4624. }
  4625. if (opt_debug) {
  4626. char *htarget = bin2hex(target, 32);
  4627. applog(LOG_DEBUG, "Generated target %s", htarget);
  4628. free(htarget);
  4629. }
  4630. memcpy(work->target, target, 32);
  4631. }
  4632. /* Generates stratum based work based on the most recent notify information
  4633. * from the pool. This will keep generating work while a pool is down so we use
  4634. * other means to detect when the pool has died in stratum_thread */
  4635. static void gen_stratum_work(struct pool *pool, struct work *work)
  4636. {
  4637. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  4638. char *header, *merkle_hash;
  4639. uint32_t *data32, *swap32;
  4640. size_t alloc_len;
  4641. int i;
  4642. /* Use intermediate lock to update the one pool variable */
  4643. cg_ilock(&pool->data_lock);
  4644. /* Generate coinbase */
  4645. work->nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  4646. pool->nonce2++;
  4647. /* Downgrade to a read lock to read off the pool variables */
  4648. cg_dlock(&pool->data_lock);
  4649. alloc_len = pool->swork.cb_len;
  4650. align_len(&alloc_len);
  4651. coinbase = calloc(alloc_len, 1);
  4652. if (unlikely(!coinbase))
  4653. quit(1, "Failed to calloc coinbase in gen_stratum_work");
  4654. hex2bin(coinbase, pool->swork.coinbase1, pool->swork.cb1_len);
  4655. hex2bin(coinbase + pool->swork.cb1_len, pool->nonce1, pool->n1_len);
  4656. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len, work->nonce2, pool->n2size);
  4657. hex2bin(coinbase + pool->swork.cb1_len + pool->n1_len + pool->n2size, pool->swork.coinbase2, pool->swork.cb2_len);
  4658. /* Generate merkle root */
  4659. gen_hash(coinbase, merkle_root, pool->swork.cb_len);
  4660. free(coinbase);
  4661. memcpy(merkle_sha, merkle_root, 32);
  4662. for (i = 0; i < pool->swork.merkles; i++) {
  4663. unsigned char merkle_bin[32];
  4664. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  4665. memcpy(merkle_sha + 32, merkle_bin, 32);
  4666. gen_hash(merkle_sha, merkle_root, 64);
  4667. memcpy(merkle_sha, merkle_root, 32);
  4668. }
  4669. data32 = (uint32_t *)merkle_sha;
  4670. swap32 = (uint32_t *)merkle_root;
  4671. for (i = 0; i < 32 / 4; i++)
  4672. swap32[i] = swab32(data32[i]);
  4673. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  4674. header = calloc(pool->swork.header_len, 1);
  4675. if (unlikely(!header))
  4676. quit(1, "Failed to calloc header in gen_stratum_work");
  4677. sprintf(header, "%s%s%s%s%s%s%s",
  4678. pool->swork.bbversion,
  4679. pool->swork.prev_hash,
  4680. merkle_hash,
  4681. pool->swork.ntime,
  4682. pool->swork.nbit,
  4683. "00000000", /* nonce */
  4684. workpadding);
  4685. /* Store the stratum work diff to check it still matches the pool's
  4686. * stratum diff when submitting shares */
  4687. work->sdiff = pool->swork.diff;
  4688. /* Copy parameters required for share submission */
  4689. work->job_id = strdup(pool->swork.job_id);
  4690. work->nonce1 = strdup(pool->nonce1);
  4691. work->ntime = strdup(pool->swork.ntime);
  4692. cg_runlock(&pool->data_lock);
  4693. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  4694. applog(LOG_DEBUG, "Generated stratum header %s", header);
  4695. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  4696. free(merkle_hash);
  4697. /* Convert hex data to binary data for work */
  4698. if (unlikely(!hex2bin(work->data, header, 128)))
  4699. quit(1, "Failed to convert header to data in gen_stratum_work");
  4700. free(header);
  4701. calc_midstate(work);
  4702. set_work_target(work, work->sdiff);
  4703. local_work++;
  4704. work->pool = pool;
  4705. work->stratum = true;
  4706. work->blk.nonce = 0;
  4707. work->id = total_work++;
  4708. work->longpoll = false;
  4709. work->getwork_mode = GETWORK_MODE_STRATUM;
  4710. work->work_block = work_block;
  4711. calc_diff(work, work->sdiff);
  4712. gettimeofday(&work->tv_staged, NULL);
  4713. }
  4714. static struct work *get_work(struct thr_info *thr, const int thr_id)
  4715. {
  4716. struct work *work = NULL;
  4717. /* Tell the watchdog thread this thread is waiting on getwork and
  4718. * should not be restarted */
  4719. thread_reportout(thr);
  4720. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4721. while (!work) {
  4722. work = hash_pop();
  4723. if (stale_work(work, false)) {
  4724. discard_work(work);
  4725. work = NULL;
  4726. wake_gws();
  4727. }
  4728. }
  4729. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  4730. work->thr_id = thr_id;
  4731. thread_reportin(thr);
  4732. work->mined = true;
  4733. return work;
  4734. }
  4735. void submit_work_async(struct work *work_in, struct timeval *tv_work_found)
  4736. {
  4737. struct work *work = copy_work(work_in);
  4738. pthread_t submit_thread;
  4739. if (tv_work_found)
  4740. memcpy(&(work->tv_work_found), tv_work_found, sizeof(struct timeval));
  4741. applog(LOG_DEBUG, "Pushing submit work to work thread");
  4742. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  4743. quit(1, "Failed to create submit_work_thread");
  4744. }
  4745. static bool hashtest(struct thr_info *thr, struct work *work)
  4746. {
  4747. uint32_t *data32 = (uint32_t *)(work->data);
  4748. unsigned char swap[80];
  4749. uint32_t *swap32 = (uint32_t *)swap;
  4750. unsigned char hash1[32];
  4751. unsigned char hash2[32];
  4752. uint32_t *hash2_32 = (uint32_t *)hash2;
  4753. bool ret = false;
  4754. flip80(swap32, data32);
  4755. sha2(swap, 80, hash1);
  4756. sha2(hash1, 32, work->hash);
  4757. flip32(hash2_32, work->hash);
  4758. if (hash2_32[7] != 0) {
  4759. applog(LOG_WARNING, "%s%d: invalid nonce - HW error",
  4760. thr->cgpu->drv->name, thr->cgpu->device_id);
  4761. mutex_lock(&stats_lock);
  4762. hw_errors++;
  4763. thr->cgpu->hw_errors++;
  4764. mutex_unlock(&stats_lock);
  4765. thr->cgpu->drv->hw_error(thr);
  4766. goto out;
  4767. }
  4768. mutex_lock(&stats_lock);
  4769. thr->cgpu->last_device_valid_work = time(NULL);
  4770. mutex_unlock(&stats_lock);
  4771. ret = fulltest(hash2, work->target);
  4772. if (!ret) {
  4773. applog(LOG_INFO, "Share below target");
  4774. /* Check the diff of the share, even if it didn't reach the
  4775. * target, just to set the best share value if it's higher. */
  4776. share_diff(work);
  4777. }
  4778. out:
  4779. return ret;
  4780. }
  4781. void submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4782. {
  4783. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  4784. struct timeval tv_work_found;
  4785. gettimeofday(&tv_work_found, NULL);
  4786. *work_nonce = htole32(nonce);
  4787. mutex_lock(&stats_lock);
  4788. total_diff1 += work->device_diff;
  4789. thr->cgpu->diff1 += work->device_diff;
  4790. work->pool->diff1 += work->device_diff;
  4791. mutex_unlock(&stats_lock);
  4792. /* Do one last check before attempting to submit the work */
  4793. if (!opt_scrypt && !hashtest(thr, work))
  4794. return;
  4795. submit_work_async(work, &tv_work_found);
  4796. }
  4797. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  4798. {
  4799. if (wdiff->tv_sec > opt_scantime ||
  4800. work->blk.nonce >= MAXTHREADS - hashes ||
  4801. hashes >= 0xfffffffe ||
  4802. stale_work(work, false))
  4803. return true;
  4804. return false;
  4805. }
  4806. static void mt_disable(struct thr_info *mythr, const int thr_id,
  4807. struct device_drv *drv)
  4808. {
  4809. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4810. mythr->rolling = mythr->cgpu->rolling = 0;
  4811. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  4812. thread_reportout(mythr);
  4813. do {
  4814. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4815. } while (mythr->pause);
  4816. thread_reportin(mythr);
  4817. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4818. drv->thread_enable(mythr);
  4819. }
  4820. /* The main hashing loop for devices that are slow enough to work on one work
  4821. * item at a time, without a queue, aborting work before the entire nonce
  4822. * range has been hashed if needed. */
  4823. static void hash_sole_work(struct thr_info *mythr)
  4824. {
  4825. const int thr_id = mythr->id;
  4826. struct cgpu_info *cgpu = mythr->cgpu;
  4827. struct device_drv *drv = cgpu->drv;
  4828. struct timeval getwork_start, tv_start, tv_end, tv_workstart, tv_lastupdate;
  4829. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  4830. struct cgminer_stats *pool_stats;
  4831. /* Try to cycle approximately 5 times before each log update */
  4832. const long cycle = opt_log_interval / 5 ? : 1;
  4833. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  4834. struct timeval diff, sdiff, wdiff = {0, 0};
  4835. uint32_t max_nonce = drv->can_limit_work(mythr);
  4836. int64_t hashes_done = 0;
  4837. gettimeofday(&getwork_start, NULL);
  4838. sdiff.tv_sec = sdiff.tv_usec = 0;
  4839. gettimeofday(&tv_lastupdate, NULL);
  4840. while (42) {
  4841. struct work *work = get_work(mythr, thr_id);
  4842. int64_t hashes;
  4843. mythr->work_restart = false;
  4844. cgpu->new_work = true;
  4845. gettimeofday(&tv_workstart, NULL);
  4846. work->blk.nonce = 0;
  4847. cgpu->max_hashes = 0;
  4848. if (!drv->prepare_work(mythr, work)) {
  4849. applog(LOG_ERR, "work prepare failed, exiting "
  4850. "mining thread %d", thr_id);
  4851. break;
  4852. }
  4853. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  4854. do {
  4855. gettimeofday(&tv_start, NULL);
  4856. timersub(&tv_start, &getwork_start, &getwork_start);
  4857. timeradd(&getwork_start,
  4858. &(dev_stats->getwork_wait),
  4859. &(dev_stats->getwork_wait));
  4860. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  4861. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4862. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4863. }
  4864. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  4865. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4866. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4867. }
  4868. dev_stats->getwork_calls++;
  4869. pool_stats = &(work->pool->cgminer_stats);
  4870. timeradd(&getwork_start,
  4871. &(pool_stats->getwork_wait),
  4872. &(pool_stats->getwork_wait));
  4873. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  4874. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4875. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4876. }
  4877. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  4878. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4879. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4880. }
  4881. pool_stats->getwork_calls++;
  4882. gettimeofday(&(work->tv_work_start), NULL);
  4883. thread_reportin(mythr);
  4884. hashes = drv->scanhash(mythr, work, work->blk.nonce + max_nonce);
  4885. thread_reportin(mythr);
  4886. gettimeofday(&getwork_start, NULL);
  4887. if (unlikely(hashes == -1)) {
  4888. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  4889. cgpu->deven = DEV_DISABLED;
  4890. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  4891. mt_disable(mythr, thr_id, drv);
  4892. }
  4893. hashes_done += hashes;
  4894. if (hashes > cgpu->max_hashes)
  4895. cgpu->max_hashes = hashes;
  4896. gettimeofday(&tv_end, NULL);
  4897. timersub(&tv_end, &tv_start, &diff);
  4898. sdiff.tv_sec += diff.tv_sec;
  4899. sdiff.tv_usec += diff.tv_usec;
  4900. if (sdiff.tv_usec > 1000000) {
  4901. ++sdiff.tv_sec;
  4902. sdiff.tv_usec -= 1000000;
  4903. }
  4904. timersub(&tv_end, &tv_workstart, &wdiff);
  4905. if (unlikely((long)sdiff.tv_sec < cycle)) {
  4906. int mult;
  4907. if (likely(max_nonce == 0xffffffff))
  4908. continue;
  4909. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  4910. mult *= cycle;
  4911. if (max_nonce > (0xffffffff * 0x400) / mult)
  4912. max_nonce = 0xffffffff;
  4913. else
  4914. max_nonce = (max_nonce * mult) / 0x400;
  4915. } else if (unlikely(sdiff.tv_sec > cycle))
  4916. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  4917. else if (unlikely(sdiff.tv_usec > 100000))
  4918. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  4919. timersub(&tv_end, &tv_lastupdate, &diff);
  4920. if (diff.tv_sec >= cycle) {
  4921. hashmeter(thr_id, &diff, hashes_done);
  4922. hashes_done = 0;
  4923. memcpy(&tv_lastupdate, &tv_end, sizeof(struct timeval));
  4924. }
  4925. if (unlikely(mythr->work_restart)) {
  4926. /* Apart from device_thread 0, we stagger the
  4927. * starting of every next thread to try and get
  4928. * all devices busy before worrying about
  4929. * getting work for their extra threads */
  4930. if (!primary) {
  4931. struct timespec rgtp;
  4932. rgtp.tv_sec = 0;
  4933. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  4934. nanosleep(&rgtp, NULL);
  4935. }
  4936. break;
  4937. }
  4938. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  4939. mt_disable(mythr, thr_id, drv);
  4940. sdiff.tv_sec = sdiff.tv_usec = 0;
  4941. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  4942. free_work(work);
  4943. }
  4944. }
  4945. /* Create a hashtable of work items for devices with a queue. The device
  4946. * driver must have a custom queue_full function or it will default to true
  4947. * and put only one work item in the queue. Work items should not be removed
  4948. * from this hashtable until they are no longer in use anywhere. Once a work
  4949. * item is physically queued on the device itself, the work->queued flag
  4950. * should be set under cgpu->qlock write lock to prevent it being dereferenced
  4951. * while still in use. */
  4952. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  4953. {
  4954. thread_reportout(mythr);
  4955. do {
  4956. struct work *work = get_work(mythr, thr_id);
  4957. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  4958. wr_lock(&cgpu->qlock);
  4959. HASH_ADD_INT(cgpu->queued_work, id, work);
  4960. wr_unlock(&cgpu->qlock);
  4961. /* The queue_full function should be used by the driver to
  4962. * actually place work items on the physical device if it
  4963. * does have a queue. */
  4964. } while (!drv->queue_full(cgpu));
  4965. }
  4966. /* This function is for retrieving one work item from the queued hashtable of
  4967. * available work items that are not yet physically on a device (which is
  4968. * flagged with the work->queued bool). Code using this function must be able
  4969. * to handle NULL as a return which implies there is no work available. */
  4970. struct work *get_queued(struct cgpu_info *cgpu)
  4971. {
  4972. struct work *work, *tmp, *ret = NULL;
  4973. wr_lock(&cgpu->qlock);
  4974. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  4975. if (!work->queued) {
  4976. work->queued = true;
  4977. ret = work;
  4978. break;
  4979. }
  4980. }
  4981. wr_unlock(&cgpu->qlock);
  4982. return ret;
  4983. }
  4984. /* This function should be used by queued device drivers when they're sure
  4985. * the work struct is no longer in use. */
  4986. void work_completed(struct cgpu_info *cgpu, struct work *work)
  4987. {
  4988. wr_lock(&cgpu->qlock);
  4989. HASH_DEL(cgpu->queued_work, work);
  4990. wr_unlock(&cgpu->qlock);
  4991. free_work(work);
  4992. }
  4993. static void flush_queue(struct cgpu_info *cgpu)
  4994. {
  4995. struct work *work, *tmp;
  4996. int discarded = 0;
  4997. wr_lock(&cgpu->qlock);
  4998. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  4999. /* Can only discard the work items if they're not physically
  5000. * queued on the device. */
  5001. if (!work->queued) {
  5002. HASH_DEL(cgpu->queued_work, work);
  5003. discard_work(work);
  5004. discarded++;
  5005. }
  5006. }
  5007. wr_unlock(&cgpu->qlock);
  5008. if (discarded)
  5009. applog(LOG_DEBUG, "Discarded %d queued work items", discarded);
  5010. }
  5011. /* This version of hash work is for devices that are fast enough to always
  5012. * perform a full nonce range and need a queue to maintain the device busy.
  5013. * Work creation and destruction is not done from within this function
  5014. * directly. */
  5015. void hash_queued_work(struct thr_info *mythr)
  5016. {
  5017. const long cycle = opt_log_interval / 5 ? : 1;
  5018. struct timeval tv_start = {0, 0}, tv_end;
  5019. struct cgpu_info *cgpu = mythr->cgpu;
  5020. struct device_drv *drv = cgpu->drv;
  5021. const int thr_id = mythr->id;
  5022. int64_t hashes_done = 0;
  5023. while (42) {
  5024. struct timeval diff;
  5025. int64_t hashes;
  5026. mythr->work_restart = false;
  5027. fill_queue(mythr, cgpu, drv, thr_id);
  5028. thread_reportin(mythr);
  5029. hashes = drv->scanwork(mythr);
  5030. if (unlikely(hashes == -1 )) {
  5031. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  5032. cgpu->deven = DEV_DISABLED;
  5033. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  5034. mt_disable(mythr, thr_id, drv);
  5035. }
  5036. hashes_done += hashes;
  5037. gettimeofday(&tv_end, NULL);
  5038. timersub(&tv_end, &tv_start, &diff);
  5039. if (diff.tv_sec >= cycle) {
  5040. hashmeter(thr_id, &diff, hashes_done);
  5041. hashes_done = 0;
  5042. memcpy(&tv_start, &tv_end, sizeof(struct timeval));
  5043. }
  5044. if (unlikely(mythr->work_restart)) {
  5045. flush_queue(cgpu);
  5046. drv->flush_work(cgpu);
  5047. }
  5048. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  5049. mt_disable(mythr, thr_id, drv);
  5050. }
  5051. }
  5052. void *miner_thread(void *userdata)
  5053. {
  5054. struct thr_info *mythr = userdata;
  5055. const int thr_id = mythr->id;
  5056. struct cgpu_info *cgpu = mythr->cgpu;
  5057. struct device_drv *drv = cgpu->drv;
  5058. char threadname[24];
  5059. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5060. snprintf(threadname, 24, "miner/%d", thr_id);
  5061. RenameThread(threadname);
  5062. if (!drv->thread_init(mythr)) {
  5063. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  5064. goto out;
  5065. }
  5066. thread_reportout(mythr);
  5067. applog(LOG_DEBUG, "Popping ping in miner thread");
  5068. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  5069. drv->hash_work(mythr);
  5070. out:
  5071. drv->thread_shutdown(mythr);
  5072. thread_reportin(mythr);
  5073. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  5074. tq_freeze(mythr->q);
  5075. return NULL;
  5076. }
  5077. enum {
  5078. STAT_SLEEP_INTERVAL = 1,
  5079. STAT_CTR_INTERVAL = 10000000,
  5080. FAILURE_INTERVAL = 30,
  5081. };
  5082. /* Stage another work item from the work returned in a longpoll */
  5083. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  5084. {
  5085. struct work *work;
  5086. bool rc;
  5087. work = make_work();
  5088. rc = work_decode(pool, work, val);
  5089. if (unlikely(!rc)) {
  5090. applog(LOG_ERR, "Could not convert longpoll data to work");
  5091. free_work(work);
  5092. return;
  5093. }
  5094. total_getworks++;
  5095. pool->getwork_requested++;
  5096. work->pool = pool;
  5097. work->rolltime = rolltime;
  5098. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  5099. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  5100. calc_diff(work, 0);
  5101. if (pool->enabled == POOL_REJECTING)
  5102. work->mandatory = true;
  5103. if (pool->has_gbt)
  5104. gen_gbt_work(pool, work);
  5105. work->longpoll = true;
  5106. work->getwork_mode = GETWORK_MODE_LP;
  5107. /* We'll be checking this work item twice, but we already know it's
  5108. * from a new block so explicitly force the new block detection now
  5109. * rather than waiting for it to hit the stage thread. This also
  5110. * allows testwork to know whether LP discovered the block or not. */
  5111. test_work_current(work);
  5112. /* Don't use backup LPs as work if we have failover-only enabled. Use
  5113. * the longpoll work from a pool that has been rejecting shares as a
  5114. * way to detect when the pool has recovered.
  5115. */
  5116. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  5117. free_work(work);
  5118. return;
  5119. }
  5120. work = clone_work(work);
  5121. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  5122. stage_work(work);
  5123. applog(LOG_DEBUG, "Converted longpoll data to work");
  5124. }
  5125. /* If we want longpoll, enable it for the chosen default pool, or, if
  5126. * the pool does not support longpoll, find the first one that does
  5127. * and use its longpoll support */
  5128. static struct pool *select_longpoll_pool(struct pool *cp)
  5129. {
  5130. int i;
  5131. if (cp->hdr_path || cp->has_gbt)
  5132. return cp;
  5133. for (i = 0; i < total_pools; i++) {
  5134. struct pool *pool = pools[i];
  5135. if (pool->has_stratum || pool->hdr_path)
  5136. return pool;
  5137. }
  5138. return NULL;
  5139. }
  5140. /* This will make the longpoll thread wait till it's the current pool, or it
  5141. * has been flagged as rejecting, before attempting to open any connections.
  5142. */
  5143. static void wait_lpcurrent(struct pool *pool)
  5144. {
  5145. if (cnx_needed(pool))
  5146. return;
  5147. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5148. mutex_lock(&lp_lock);
  5149. pthread_cond_wait(&lp_cond, &lp_lock);
  5150. mutex_unlock(&lp_lock);
  5151. }
  5152. }
  5153. static void *longpoll_thread(void *userdata)
  5154. {
  5155. struct pool *cp = (struct pool *)userdata;
  5156. /* This *pool is the source of the actual longpoll, not the pool we've
  5157. * tied it to */
  5158. struct timeval start, reply, end;
  5159. struct pool *pool = NULL;
  5160. char threadname[16];
  5161. CURL *curl = NULL;
  5162. int failures = 0;
  5163. char lpreq[1024];
  5164. char *lp_url;
  5165. int rolltime;
  5166. snprintf(threadname, 16, "longpoll/%d", cp->pool_no);
  5167. RenameThread(threadname);
  5168. curl = curl_easy_init();
  5169. if (unlikely(!curl)) {
  5170. applog(LOG_ERR, "CURL initialisation failed");
  5171. return NULL;
  5172. }
  5173. retry_pool:
  5174. pool = select_longpoll_pool(cp);
  5175. if (!pool) {
  5176. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  5177. while (!pool) {
  5178. nmsleep(60000);
  5179. pool = select_longpoll_pool(cp);
  5180. }
  5181. }
  5182. if (pool->has_stratum) {
  5183. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5184. cp->rpc_url, pool->rpc_url);
  5185. goto out;
  5186. }
  5187. /* Any longpoll from any pool is enough for this to be true */
  5188. have_longpoll = true;
  5189. wait_lpcurrent(cp);
  5190. if (pool->has_gbt) {
  5191. lp_url = pool->rpc_url;
  5192. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  5193. } else {
  5194. strcpy(lpreq, getwork_req);
  5195. lp_url = pool->lp_url;
  5196. if (cp == pool)
  5197. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  5198. else
  5199. applog(LOG_WARNING, "Long-polling activated for %s via %s", cp->rpc_url, lp_url);
  5200. }
  5201. while (42) {
  5202. json_t *val, *soval;
  5203. wait_lpcurrent(cp);
  5204. gettimeofday(&start, NULL);
  5205. /* Update the longpollid every time, but do it under lock to
  5206. * avoid races */
  5207. if (pool->has_gbt) {
  5208. cg_rlock(&pool->gbt_lock);
  5209. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  5210. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  5211. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  5212. cg_runlock(&pool->gbt_lock);
  5213. }
  5214. /* Longpoll connections can be persistent for a very long time
  5215. * and any number of issues could have come up in the meantime
  5216. * so always establish a fresh connection instead of relying on
  5217. * a persistent one. */
  5218. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  5219. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  5220. lpreq, false, true, &rolltime, pool, false);
  5221. gettimeofday(&reply, NULL);
  5222. if (likely(val)) {
  5223. soval = json_object_get(json_object_get(val, "result"), "submitold");
  5224. if (soval)
  5225. pool->submit_old = json_is_true(soval);
  5226. else
  5227. pool->submit_old = false;
  5228. convert_to_work(val, rolltime, pool, &start, &reply);
  5229. failures = 0;
  5230. json_decref(val);
  5231. } else {
  5232. /* Some pools regularly drop the longpoll request so
  5233. * only see this as longpoll failure if it happens
  5234. * immediately and just restart it the rest of the
  5235. * time. */
  5236. gettimeofday(&end, NULL);
  5237. if (end.tv_sec - start.tv_sec > 30)
  5238. continue;
  5239. if (failures == 1)
  5240. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  5241. nmsleep(30000);
  5242. }
  5243. if (pool != cp) {
  5244. pool = select_longpoll_pool(cp);
  5245. if (pool->has_stratum) {
  5246. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  5247. cp->rpc_url, pool->rpc_url);
  5248. break;
  5249. }
  5250. if (unlikely(!pool))
  5251. goto retry_pool;
  5252. }
  5253. if (unlikely(pool->removed))
  5254. break;
  5255. }
  5256. out:
  5257. curl_easy_cleanup(curl);
  5258. return NULL;
  5259. }
  5260. void reinit_device(struct cgpu_info *cgpu)
  5261. {
  5262. cgpu->drv->reinit_device(cgpu);
  5263. }
  5264. static struct timeval rotate_tv;
  5265. /* We reap curls if they are unused for over a minute */
  5266. static void reap_curl(struct pool *pool)
  5267. {
  5268. struct curl_ent *ent, *iter;
  5269. struct timeval now;
  5270. int reaped = 0;
  5271. gettimeofday(&now, NULL);
  5272. mutex_lock(&pool->pool_lock);
  5273. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  5274. if (pool->curls < 2)
  5275. break;
  5276. if (now.tv_sec - ent->tv.tv_sec > 300) {
  5277. reaped++;
  5278. pool->curls--;
  5279. list_del(&ent->node);
  5280. curl_easy_cleanup(ent->curl);
  5281. free(ent);
  5282. }
  5283. }
  5284. mutex_unlock(&pool->pool_lock);
  5285. if (reaped)
  5286. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  5287. }
  5288. static void *watchpool_thread(void __maybe_unused *userdata)
  5289. {
  5290. int intervals = 0;
  5291. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5292. RenameThread("watchpool");
  5293. while (42) {
  5294. struct timeval now;
  5295. int i;
  5296. if (++intervals > 20)
  5297. intervals = 0;
  5298. gettimeofday(&now, NULL);
  5299. for (i = 0; i < total_pools; i++) {
  5300. struct pool *pool = pools[i];
  5301. if (!opt_benchmark)
  5302. reap_curl(pool);
  5303. /* Get a rolling utility per pool over 10 mins */
  5304. if (intervals > 19) {
  5305. int shares = pool->diff1 - pool->last_shares;
  5306. pool->last_shares = pool->diff1;
  5307. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  5308. pool->shares = pool->utility;
  5309. }
  5310. if (pool->enabled == POOL_DISABLED)
  5311. continue;
  5312. /* Don't start testing any pools if the test threads
  5313. * from startup are still doing their first attempt. */
  5314. if (unlikely(pool->testing)) {
  5315. pthread_join(pool->test_thread, NULL);
  5316. pool->testing = false;
  5317. }
  5318. /* Test pool is idle once every minute */
  5319. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  5320. gettimeofday(&pool->tv_idle, NULL);
  5321. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  5322. pool_resus(pool);
  5323. }
  5324. }
  5325. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  5326. gettimeofday(&rotate_tv, NULL);
  5327. switch_pools(NULL);
  5328. }
  5329. nmsleep(30000);
  5330. }
  5331. return NULL;
  5332. }
  5333. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  5334. * the screen at regular intervals, and restarts threads if they appear to have
  5335. * died. */
  5336. #define WATCHDOG_INTERVAL 2
  5337. #define WATCHDOG_SICK_TIME 60
  5338. #define WATCHDOG_DEAD_TIME 600
  5339. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  5340. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  5341. static void *watchdog_thread(void __maybe_unused *userdata)
  5342. {
  5343. const unsigned int interval = WATCHDOG_INTERVAL;
  5344. struct timeval zero_tv;
  5345. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5346. RenameThread("watchdog");
  5347. memset(&zero_tv, 0, sizeof(struct timeval));
  5348. gettimeofday(&rotate_tv, NULL);
  5349. while (1) {
  5350. int i;
  5351. struct timeval now;
  5352. sleep(interval);
  5353. discard_stale();
  5354. hashmeter(-1, &zero_tv, 0);
  5355. #ifdef HAVE_CURSES
  5356. if (curses_active_locked()) {
  5357. change_logwinsize();
  5358. curses_print_status();
  5359. for (i = 0; i < mining_threads; i++)
  5360. curses_print_devstatus(i);
  5361. touchwin(statuswin);
  5362. wrefresh(statuswin);
  5363. touchwin(logwin);
  5364. wrefresh(logwin);
  5365. unlock_curses();
  5366. }
  5367. #endif
  5368. gettimeofday(&now, NULL);
  5369. if (!sched_paused && !should_run()) {
  5370. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  5371. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5372. if (!schedstart.enable) {
  5373. quit(0, "Terminating execution as planned");
  5374. break;
  5375. }
  5376. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  5377. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5378. sched_paused = true;
  5379. rd_lock(&mining_thr_lock);
  5380. for (i = 0; i < mining_threads; i++)
  5381. mining_thr[i]->pause = true;
  5382. rd_unlock(&mining_thr_lock);
  5383. } else if (sched_paused && should_run()) {
  5384. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  5385. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5386. if (schedstop.enable)
  5387. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  5388. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5389. sched_paused = false;
  5390. for (i = 0; i < mining_threads; i++) {
  5391. struct thr_info *thr;
  5392. thr = get_thread(i);
  5393. /* Don't touch disabled devices */
  5394. if (thr->cgpu->deven == DEV_DISABLED)
  5395. continue;
  5396. thr->pause = false;
  5397. tq_push(thr->q, &ping);
  5398. }
  5399. }
  5400. for (i = 0; i < total_devices; ++i) {
  5401. struct cgpu_info *cgpu = get_devices(i);
  5402. struct thr_info *thr = cgpu->thr[0];
  5403. enum dev_enable *denable;
  5404. char dev_str[8];
  5405. int gpu;
  5406. cgpu->drv->get_stats(cgpu);
  5407. gpu = cgpu->device_id;
  5408. denable = &cgpu->deven;
  5409. sprintf(dev_str, "%s%d", cgpu->drv->name, gpu);
  5410. #ifdef HAVE_ADL
  5411. if (adl_active && cgpu->has_adl)
  5412. gpu_autotune(gpu, denable);
  5413. if (opt_debug && cgpu->has_adl) {
  5414. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  5415. float temp = 0, vddc = 0;
  5416. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  5417. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  5418. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  5419. }
  5420. #endif
  5421. /* Thread is waiting on getwork or disabled */
  5422. if (thr->getwork || *denable == DEV_DISABLED)
  5423. continue;
  5424. #ifdef WANT_CPUMINE
  5425. if (cgpu->drv->drv_id == DRIVER_CPU)
  5426. continue;
  5427. #endif
  5428. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  5429. if (cgpu->status != LIFE_INIT)
  5430. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  5431. cgpu->status = LIFE_WELL;
  5432. cgpu->device_last_well = time(NULL);
  5433. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  5434. thr->rolling = cgpu->rolling = 0;
  5435. cgpu->status = LIFE_SICK;
  5436. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  5437. gettimeofday(&thr->sick, NULL);
  5438. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  5439. #ifdef HAVE_ADL
  5440. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5441. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  5442. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  5443. } else
  5444. #endif
  5445. if (opt_restart) {
  5446. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  5447. reinit_device(cgpu);
  5448. }
  5449. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  5450. cgpu->status = LIFE_DEAD;
  5451. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  5452. gettimeofday(&thr->sick, NULL);
  5453. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  5454. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  5455. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  5456. /* Attempt to restart a GPU that's sick or dead once every minute */
  5457. gettimeofday(&thr->sick, NULL);
  5458. #ifdef HAVE_ADL
  5459. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5460. /* Again do not attempt to restart a device that may have hard hung */
  5461. } else
  5462. #endif
  5463. if (opt_restart)
  5464. reinit_device(cgpu);
  5465. }
  5466. }
  5467. }
  5468. return NULL;
  5469. }
  5470. static void log_print_status(struct cgpu_info *cgpu)
  5471. {
  5472. char logline[255];
  5473. get_statline(logline, cgpu);
  5474. applog(LOG_WARNING, "%s", logline);
  5475. }
  5476. void print_summary(void)
  5477. {
  5478. struct timeval diff;
  5479. int hours, mins, secs, i;
  5480. double utility, efficiency = 0.0, displayed_hashes, work_util;
  5481. bool mhash_base = true;
  5482. timersub(&total_tv_end, &total_tv_start, &diff);
  5483. hours = diff.tv_sec / 3600;
  5484. mins = (diff.tv_sec % 3600) / 60;
  5485. secs = diff.tv_sec % 60;
  5486. utility = total_accepted / total_secs * 60;
  5487. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  5488. work_util = total_diff1 / total_secs * 60;
  5489. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  5490. applog(LOG_WARNING, "Started at %s", datestamp);
  5491. if (total_pools == 1)
  5492. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  5493. #ifdef WANT_CPUMINE
  5494. if (opt_n_threads)
  5495. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  5496. #endif
  5497. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  5498. displayed_hashes = total_mhashes_done / total_secs;
  5499. if (displayed_hashes < 1) {
  5500. displayed_hashes *= 1000;
  5501. mhash_base = false;
  5502. }
  5503. applog(LOG_WARNING, "Average hashrate: %.1f %shash/s", displayed_hashes, mhash_base? "Mega" : "Kilo");
  5504. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  5505. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  5506. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  5507. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  5508. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  5509. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  5510. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  5511. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  5512. if (total_accepted || total_rejected)
  5513. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  5514. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  5515. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  5516. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  5517. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  5518. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  5519. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  5520. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  5521. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  5522. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  5523. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  5524. if (total_pools > 1) {
  5525. for (i = 0; i < total_pools; i++) {
  5526. struct pool *pool = pools[i];
  5527. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  5528. if (pool->solved)
  5529. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  5530. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  5531. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  5532. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  5533. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  5534. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  5535. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  5536. if (pool->accepted || pool->rejected)
  5537. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  5538. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  5539. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  5540. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  5541. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  5542. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  5543. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  5544. }
  5545. }
  5546. applog(LOG_WARNING, "Summary of per device statistics:\n");
  5547. for (i = 0; i < total_devices; ++i) {
  5548. struct cgpu_info *cgpu = get_devices(i);
  5549. log_print_status(cgpu);
  5550. }
  5551. if (opt_shares)
  5552. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  5553. fflush(stdout);
  5554. fflush(stderr);
  5555. if (opt_shares > total_accepted)
  5556. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  5557. }
  5558. static void clean_up(void)
  5559. {
  5560. #ifdef HAVE_OPENCL
  5561. clear_adl(nDevs);
  5562. #endif
  5563. #ifdef HAVE_LIBUSB
  5564. libusb_exit(NULL);
  5565. #endif
  5566. gettimeofday(&total_tv_end, NULL);
  5567. #ifdef HAVE_CURSES
  5568. disable_curses();
  5569. #endif
  5570. if (!opt_realquiet && successful_connect)
  5571. print_summary();
  5572. if (opt_n_threads)
  5573. free(cpus);
  5574. curl_global_cleanup();
  5575. }
  5576. void quit(int status, const char *format, ...)
  5577. {
  5578. va_list ap;
  5579. clean_up();
  5580. if (format) {
  5581. va_start(ap, format);
  5582. vfprintf(stderr, format, ap);
  5583. va_end(ap);
  5584. }
  5585. fprintf(stderr, "\n");
  5586. fflush(stderr);
  5587. #if defined(unix)
  5588. if (forkpid > 0) {
  5589. kill(forkpid, SIGTERM);
  5590. forkpid = 0;
  5591. }
  5592. #endif
  5593. exit(status);
  5594. }
  5595. #ifdef HAVE_CURSES
  5596. char *curses_input(const char *query)
  5597. {
  5598. char *input;
  5599. echo();
  5600. input = malloc(255);
  5601. if (!input)
  5602. quit(1, "Failed to malloc input");
  5603. leaveok(logwin, false);
  5604. wlogprint("%s:\n", query);
  5605. wgetnstr(logwin, input, 255);
  5606. if (!strlen(input))
  5607. strcpy(input, "-1");
  5608. leaveok(logwin, true);
  5609. noecho();
  5610. return input;
  5611. }
  5612. #endif
  5613. static bool pools_active = false;
  5614. static void *test_pool_thread(void *arg)
  5615. {
  5616. struct pool *pool = (struct pool *)arg;
  5617. if (pool_active(pool, false)) {
  5618. pool_tset(pool, &pool->lagging);
  5619. pool_tclear(pool, &pool->idle);
  5620. cg_wlock(&control_lock);
  5621. if (!pools_active) {
  5622. currentpool = pool;
  5623. if (pool->pool_no != 0)
  5624. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  5625. pools_active = true;
  5626. }
  5627. cg_wunlock(&control_lock);
  5628. pool_resus(pool);
  5629. } else
  5630. pool_died(pool);
  5631. return NULL;
  5632. }
  5633. /* Always returns true that the pool details were added unless we are not
  5634. * live, implying this is the only pool being added, so if no pools are
  5635. * active it returns false. */
  5636. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  5637. {
  5638. url = get_proxy(url, pool);
  5639. pool->rpc_url = url;
  5640. pool->rpc_user = user;
  5641. pool->rpc_pass = pass;
  5642. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5643. if (!pool->rpc_userpass)
  5644. quit(1, "Failed to malloc userpass");
  5645. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5646. pool->testing = true;
  5647. pool->idle = true;
  5648. enable_pool(pool);
  5649. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  5650. if (!live) {
  5651. pthread_join(pool->test_thread, NULL);
  5652. pool->testing = false;
  5653. return pools_active;
  5654. }
  5655. return true;
  5656. }
  5657. #ifdef HAVE_CURSES
  5658. static bool input_pool(bool live)
  5659. {
  5660. char *url = NULL, *user = NULL, *pass = NULL;
  5661. struct pool *pool;
  5662. bool ret = false;
  5663. immedok(logwin, true);
  5664. wlogprint("Input server details.\n");
  5665. url = curses_input("URL");
  5666. if (!url)
  5667. goto out;
  5668. user = curses_input("Username");
  5669. if (!user)
  5670. goto out;
  5671. pass = curses_input("Password");
  5672. if (!pass)
  5673. goto out;
  5674. pool = add_pool();
  5675. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  5676. strncmp(url, "https://", 8)) {
  5677. char *httpinput;
  5678. httpinput = malloc(256);
  5679. if (!httpinput)
  5680. quit(1, "Failed to malloc httpinput");
  5681. strcpy(httpinput, "http://");
  5682. strncat(httpinput, url, 248);
  5683. free(url);
  5684. url = httpinput;
  5685. }
  5686. ret = add_pool_details(pool, live, url, user, pass);
  5687. out:
  5688. immedok(logwin, false);
  5689. if (!ret) {
  5690. if (url)
  5691. free(url);
  5692. if (user)
  5693. free(user);
  5694. if (pass)
  5695. free(pass);
  5696. }
  5697. return ret;
  5698. }
  5699. #endif
  5700. #if defined(unix)
  5701. static void fork_monitor()
  5702. {
  5703. // Make a pipe: [readFD, writeFD]
  5704. int pfd[2];
  5705. int r = pipe(pfd);
  5706. if (r < 0) {
  5707. perror("pipe - failed to create pipe for --monitor");
  5708. exit(1);
  5709. }
  5710. // Make stderr write end of pipe
  5711. fflush(stderr);
  5712. r = dup2(pfd[1], 2);
  5713. if (r < 0) {
  5714. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  5715. exit(1);
  5716. }
  5717. r = close(pfd[1]);
  5718. if (r < 0) {
  5719. perror("close - failed to close write end of pipe for --monitor");
  5720. exit(1);
  5721. }
  5722. // Don't allow a dying monitor to kill the main process
  5723. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  5724. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  5725. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  5726. perror("signal - failed to edit signal mask for --monitor");
  5727. exit(1);
  5728. }
  5729. // Fork a child process
  5730. forkpid = fork();
  5731. if (forkpid < 0) {
  5732. perror("fork - failed to fork child process for --monitor");
  5733. exit(1);
  5734. }
  5735. // Child: launch monitor command
  5736. if (0 == forkpid) {
  5737. // Make stdin read end of pipe
  5738. r = dup2(pfd[0], 0);
  5739. if (r < 0) {
  5740. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  5741. exit(1);
  5742. }
  5743. close(pfd[0]);
  5744. if (r < 0) {
  5745. perror("close - in child, failed to close read end of pipe for --monitor");
  5746. exit(1);
  5747. }
  5748. // Launch user specified command
  5749. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  5750. perror("execl - in child failed to exec user specified command for --monitor");
  5751. exit(1);
  5752. }
  5753. // Parent: clean up unused fds and bail
  5754. r = close(pfd[0]);
  5755. if (r < 0) {
  5756. perror("close - failed to close read end of pipe for --monitor");
  5757. exit(1);
  5758. }
  5759. }
  5760. #endif // defined(unix)
  5761. #ifdef HAVE_CURSES
  5762. void enable_curses(void) {
  5763. int x,y;
  5764. lock_curses();
  5765. if (curses_active) {
  5766. unlock_curses();
  5767. return;
  5768. }
  5769. mainwin = initscr();
  5770. getmaxyx(mainwin, y, x);
  5771. statuswin = newwin(logstart, x, 0, 0);
  5772. leaveok(statuswin, true);
  5773. logwin = newwin(y - logcursor, 0, logcursor, 0);
  5774. idlok(logwin, true);
  5775. scrollok(logwin, true);
  5776. leaveok(logwin, true);
  5777. cbreak();
  5778. noecho();
  5779. curses_active = true;
  5780. statusy = logstart;
  5781. unlock_curses();
  5782. }
  5783. #endif
  5784. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  5785. #ifndef WANT_CPUMINE
  5786. struct device_drv cpu_drv;
  5787. struct device_drv cpu_drv = {
  5788. .drv_id = DRIVER_CPU,
  5789. .name = "CPU",
  5790. };
  5791. #endif
  5792. #ifdef USE_BFLSC
  5793. extern struct device_drv bflsc_drv;
  5794. #endif
  5795. #ifdef USE_BITFORCE
  5796. extern struct device_drv bitforce_drv;
  5797. #endif
  5798. #ifdef USE_ICARUS
  5799. extern struct device_drv icarus_drv;
  5800. #endif
  5801. #ifdef USE_MODMINER
  5802. extern struct device_drv modminer_drv;
  5803. #endif
  5804. #ifdef USE_ZTEX
  5805. extern struct device_drv ztex_drv;
  5806. #endif
  5807. static int cgminer_id_count = 0;
  5808. /* Various noop functions for drivers that don't support or need their
  5809. * variants. */
  5810. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  5811. {
  5812. }
  5813. void blank_get_statline_before(char *buf, struct cgpu_info __maybe_unused *cgpu)
  5814. {
  5815. tailsprintf(buf, " | ");
  5816. }
  5817. static void noop_get_statline(char __maybe_unused *buf, struct cgpu_info __maybe_unused *cgpu)
  5818. {
  5819. }
  5820. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  5821. {
  5822. return true;
  5823. }
  5824. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  5825. {
  5826. return true;
  5827. }
  5828. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  5829. {
  5830. return 0xffffffff;
  5831. }
  5832. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  5833. {
  5834. return true;
  5835. }
  5836. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  5837. {
  5838. return true;
  5839. }
  5840. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  5841. {
  5842. }
  5843. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  5844. {
  5845. }
  5846. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  5847. {
  5848. }
  5849. #define noop_flush_work noop_reinit_device
  5850. #define noop_queue_full noop_get_stats
  5851. /* Fill missing driver drv functions with noops */
  5852. void fill_device_drv(struct cgpu_info *cgpu)
  5853. {
  5854. struct device_drv *drv = cgpu->drv;
  5855. if (!drv->reinit_device)
  5856. drv->reinit_device = &noop_reinit_device;
  5857. if (!drv->get_statline_before)
  5858. drv->get_statline_before = &blank_get_statline_before;
  5859. if (!drv->get_statline)
  5860. drv->get_statline = &noop_get_statline;
  5861. if (!drv->get_stats)
  5862. drv->get_stats = &noop_get_stats;
  5863. if (!drv->thread_prepare)
  5864. drv->thread_prepare = &noop_thread_prepare;
  5865. if (!drv->can_limit_work)
  5866. drv->can_limit_work = &noop_can_limit_work;
  5867. if (!drv->thread_init)
  5868. drv->thread_init = &noop_thread_init;
  5869. if (!drv->prepare_work)
  5870. drv->prepare_work = &noop_prepare_work;
  5871. if (!drv->hw_error)
  5872. drv->hw_error = &noop_hw_error;
  5873. if (!drv->thread_shutdown)
  5874. drv->thread_shutdown = &noop_thread_shutdown;
  5875. if (!drv->thread_enable)
  5876. drv->thread_enable = &noop_thread_enable;
  5877. if (!drv->hash_work)
  5878. drv->hash_work = &hash_sole_work;
  5879. if (!drv->flush_work)
  5880. drv->flush_work = &noop_flush_work;
  5881. if (!drv->queue_full)
  5882. drv->queue_full = &noop_queue_full;
  5883. if (!drv->max_diff)
  5884. drv->max_diff = 1;
  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. }