miner.c 221 KB

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