cgminer.c 165 KB

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