main.c 163 KB

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