miner.c 216 KB

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