miner.c 169 KB

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