miner.c 267 KB

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