miner.c 200 KB

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