miner.c 235 KB

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