miner.c 239 KB

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