miner.c 226 KB

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