miner.c 183 KB

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