miner.c 259 KB

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