miner.c 185 KB

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