cgminer.c 164 KB

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