miner.c 180 KB

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