miner.c 238 KB

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