miner.c 182 KB

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