miner.c 181 KB

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