main.c 163 KB

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