miner.c 236 KB

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