miner.c 182 KB

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