miner.c 178 KB

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