main.c 162 KB

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