main.c 158 KB

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