miner.c 192 KB

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