main.c 161 KB

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