miner.c 242 KB

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