miner.c 230 KB

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