main.c 162 KB

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