miner.c 272 KB

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