main.c 160 KB

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