miner.c 259 KB

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