miner.c 224 KB

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