miner.c 163 KB

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