miner.c 265 KB

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