miner.c 229 KB

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