miner.c 285 KB

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