miner.c 237 KB

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