main.c 144 KB

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