miner.c 225 KB

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