cgminer.c 189 KB

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