cgminer.c 164 KB

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