miner.c 260 KB

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