cgminer.c 187 KB

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