miner.c 205 KB

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