miner.c 211 KB

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