cgminer.c 188 KB

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