main.c 162 KB

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