miner.c 181 KB

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