miner.c 226 KB

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