main.c 151 KB

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