miner.c 228 KB

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