miner.c 169 KB

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