miner.c 221 KB

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