miner.c 231 KB

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