miner.c 169 KB

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