cgminer.c 173 KB

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