main.c 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125
  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 "compat.h"
  31. #include "miner.h"
  32. #include "findnonce.h"
  33. #include "ocl.h"
  34. #define PROGRAM_NAME "cgminer"
  35. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  36. #define DEF_RPC_USERNAME "rpcuser"
  37. #define DEF_RPC_PASSWORD "rpcpass"
  38. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  39. #ifdef __linux /* Linux specific policy and affinity management */
  40. #include <sched.h>
  41. static inline void drop_policy(void)
  42. {
  43. struct sched_param param;
  44. #ifdef SCHED_BATCH
  45. #ifdef SCHED_IDLE
  46. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  47. #endif
  48. sched_setscheduler(0, SCHED_BATCH, &param);
  49. #endif
  50. }
  51. static inline void affine_to_cpu(int id, int cpu)
  52. {
  53. cpu_set_t set;
  54. CPU_ZERO(&set);
  55. CPU_SET(cpu, &set);
  56. sched_setaffinity(0, sizeof(&set), &set);
  57. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  58. }
  59. #else
  60. static inline void drop_policy(void)
  61. {
  62. }
  63. static inline void affine_to_cpu(int id, int cpu)
  64. {
  65. }
  66. #endif
  67. enum workio_commands {
  68. WC_GET_WORK,
  69. WC_SUBMIT_WORK,
  70. WC_DIE,
  71. };
  72. struct workio_cmd {
  73. enum workio_commands cmd;
  74. struct thr_info *thr;
  75. union {
  76. struct work *work;
  77. } u;
  78. bool lagging;
  79. };
  80. enum sha256_algos {
  81. ALGO_C, /* plain C */
  82. ALGO_4WAY, /* parallel SSE2 */
  83. ALGO_VIA, /* VIA padlock */
  84. ALGO_CRYPTOPP, /* Crypto++ (C) */
  85. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  86. ALGO_SSE2_64, /* SSE2 for x86_64 */
  87. ALGO_SSE4_64, /* SSE4 for x86_64 */
  88. };
  89. enum pool_strategy {
  90. POOL_FAILOVER,
  91. POOL_ROUNDROBIN,
  92. POOL_ROTATE,
  93. POOL_LOADBALANCE,
  94. };
  95. #define TOP_STRATEGY (POOL_LOADBALANCE)
  96. struct strategies {
  97. const char *s;
  98. } strategies[] = {
  99. { "Failover" },
  100. { "Round Robin" },
  101. { "Rotate" },
  102. { "Load Balance" },
  103. };
  104. static const char *algo_names[] = {
  105. [ALGO_C] = "c",
  106. #ifdef WANT_SSE2_4WAY
  107. [ALGO_4WAY] = "4way",
  108. #endif
  109. #ifdef WANT_VIA_PADLOCK
  110. [ALGO_VIA] = "via",
  111. #endif
  112. [ALGO_CRYPTOPP] = "cryptopp",
  113. #ifdef WANT_CRYPTOPP_ASM32
  114. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  115. #endif
  116. #ifdef WANT_X8664_SSE2
  117. [ALGO_SSE2_64] = "sse2_64",
  118. #endif
  119. #ifdef WANT_X8664_SSE4
  120. [ALGO_SSE4_64] = "sse4_64",
  121. #endif
  122. };
  123. bool opt_debug = false;
  124. bool opt_protocol = false;
  125. bool want_longpoll = true;
  126. bool have_longpoll = false;
  127. bool use_syslog = false;
  128. static bool opt_quiet = false;
  129. static bool opt_realquiet = false;
  130. static bool opt_loginput = false;
  131. static int opt_retries = -1;
  132. static int opt_fail_pause = 5;
  133. static int opt_log_interval = 5;
  134. bool opt_log_output = false;
  135. static bool opt_dynamic = true;
  136. static int opt_queue;
  137. int opt_vectors;
  138. int opt_worksize;
  139. int opt_scantime = 60;
  140. static const bool opt_time = true;
  141. #if defined(WANT_X8664_SSE4) && defined(__SSE4_1__)
  142. static enum sha256_algos opt_algo = ALGO_SSE4_64;
  143. #elif defined(WANT_X8664_SSE2) && defined(__SSE2__)
  144. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  145. #else
  146. static enum sha256_algos opt_algo = ALGO_C;
  147. #endif
  148. static int nDevs;
  149. static int opt_g_threads = 2;
  150. static int opt_device;
  151. static int total_devices;
  152. static bool gpu_devices[16];
  153. static int gpu_threads;
  154. static bool forced_n_threads;
  155. static int opt_n_threads;
  156. static int mining_threads;
  157. static int num_processors;
  158. static int scan_intensity;
  159. static bool use_curses = true;
  160. #define QUIET (opt_quiet || opt_realquiet)
  161. struct thr_info *thr_info;
  162. static int work_thr_id;
  163. int longpoll_thr_id;
  164. static int stage_thr_id;
  165. static int watchdog_thr_id;
  166. static int input_thr_id;
  167. static int total_threads;
  168. struct work_restart *work_restart = NULL;
  169. static pthread_mutex_t hash_lock;
  170. static pthread_mutex_t qd_lock;
  171. static pthread_mutex_t stgd_lock;
  172. static pthread_mutex_t curses_lock;
  173. static double total_mhashes_done;
  174. static struct timeval total_tv_start, total_tv_end;
  175. pthread_mutex_t control_lock;
  176. int hw_errors;
  177. static int total_accepted, total_rejected;
  178. static int total_getworks, total_stale, total_discarded;
  179. static int total_queued, total_staged, lp_staged;
  180. static unsigned int new_blocks;
  181. enum block_change {
  182. BLOCK_NONE,
  183. BLOCK_LP,
  184. BLOCK_DETECT,
  185. BLOCK_FIRST,
  186. };
  187. static enum block_change block_changed = BLOCK_FIRST;
  188. static unsigned int local_work;
  189. static unsigned int total_lo, total_ro;
  190. #define MAX_POOLS (32)
  191. static struct pool *pools[MAX_POOLS];
  192. static struct pool *currentpool = NULL;
  193. static int total_pools;
  194. static enum pool_strategy pool_strategy = POOL_FAILOVER;
  195. static int opt_rotate_period;
  196. static int total_urls, total_users, total_passes, total_userpasses;
  197. static bool curses_active = false;
  198. static char current_block[37];
  199. static char *current_hash;
  200. static char datestamp[40];
  201. static char blocktime[30];
  202. static char *opt_kernel = NULL;
  203. static char *opt_stderr_cmd = NULL;
  204. enum cl_kernel chosen_kernel;
  205. static bool ping = true;
  206. struct sigaction termhandler, inthandler;
  207. struct thread_q *getq;
  208. void get_datestamp(char *f, struct timeval *tv)
  209. {
  210. struct tm tm;
  211. localtime_r(&tv->tv_sec, &tm);
  212. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  213. tm.tm_year + 1900,
  214. tm.tm_mon + 1,
  215. tm.tm_mday,
  216. tm.tm_hour,
  217. tm.tm_min,
  218. tm.tm_sec);
  219. }
  220. void get_timestamp(char *f, struct timeval *tv)
  221. {
  222. struct tm tm;
  223. localtime_r(&tv->tv_sec, &tm);
  224. sprintf(f, "[%02d:%02d:%02d]",
  225. tm.tm_hour,
  226. tm.tm_min,
  227. tm.tm_sec);
  228. }
  229. static void applog_and_exit(const char *fmt, ...)
  230. {
  231. va_list ap;
  232. va_start(ap, fmt);
  233. vapplog(LOG_ERR, fmt, ap);
  234. va_end(ap);
  235. exit(1);
  236. }
  237. static void add_pool(void)
  238. {
  239. struct pool *pool;
  240. pool = calloc(sizeof(struct pool), 1);
  241. if (!pool) {
  242. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  243. exit (1);
  244. }
  245. pool->pool_no = pool->prio = total_pools;
  246. pools[total_pools++] = pool;
  247. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  248. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  249. exit (1);
  250. }
  251. /* Make sure the pool doesn't think we've been idle since time 0 */
  252. pool->tv_idle.tv_sec = ~0UL;
  253. }
  254. /* Pool variant of test and set */
  255. static bool pool_tset(struct pool *pool, bool *var)
  256. {
  257. bool ret;
  258. mutex_lock(&pool->pool_lock);
  259. ret = *var;
  260. *var = true;
  261. mutex_unlock(&pool->pool_lock);
  262. return ret;
  263. }
  264. static bool pool_tclear(struct pool *pool, bool *var)
  265. {
  266. bool ret;
  267. mutex_lock(&pool->pool_lock);
  268. ret = *var;
  269. *var = false;
  270. mutex_unlock(&pool->pool_lock);
  271. return ret;
  272. }
  273. static struct pool *current_pool(void)
  274. {
  275. struct pool *pool;
  276. mutex_lock(&control_lock);
  277. pool = currentpool;
  278. mutex_unlock(&control_lock);
  279. return pool;
  280. }
  281. /* FIXME: Use asprintf for better errors. */
  282. static char *set_algo(const char *arg, enum sha256_algos *algo)
  283. {
  284. enum sha256_algos i;
  285. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  286. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  287. *algo = i;
  288. return NULL;
  289. }
  290. }
  291. return "Unknown algorithm";
  292. }
  293. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  294. {
  295. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  296. }
  297. static char *set_int_range(const char *arg, int *i, int min, int max)
  298. {
  299. char *err = opt_set_intval(arg, i);
  300. if (err)
  301. return err;
  302. if (*i < min || *i > max)
  303. return "Value out of range";
  304. return NULL;
  305. }
  306. static char *set_int_0_to_9999(const char *arg, int *i)
  307. {
  308. return set_int_range(arg, i, 0, 9999);
  309. }
  310. static char *forced_int_1010(const char *arg, int *i)
  311. {
  312. opt_dynamic = false;
  313. return set_int_range(arg, i, -10, 10);
  314. }
  315. static char *force_nthreads_int(const char *arg, int *i)
  316. {
  317. forced_n_threads = true;
  318. return set_int_range(arg, i, 0, 9999);
  319. }
  320. static char *set_int_0_to_10(const char *arg, int *i)
  321. {
  322. return set_int_range(arg, i, 0, 10);
  323. }
  324. static char *set_devices(const char *arg, int *i)
  325. {
  326. char *err = opt_set_intval(arg, i);
  327. if (err)
  328. return err;
  329. if (*i < 0 || *i > 15)
  330. return "Invalid GPU device number";
  331. total_devices++;
  332. gpu_devices[*i] = true;
  333. return NULL;
  334. }
  335. static char *set_loadbalance(enum pool_strategy *strategy)
  336. {
  337. *strategy = POOL_LOADBALANCE;
  338. return NULL;
  339. }
  340. static char *set_rotate(const char *arg, int *i)
  341. {
  342. pool_strategy = POOL_ROTATE;
  343. return set_int_range(arg, i, 0, 9999);
  344. }
  345. static char *set_rr(enum pool_strategy *strategy)
  346. {
  347. *strategy = POOL_ROUNDROBIN;
  348. return NULL;
  349. }
  350. static char *set_url(char *arg, char **p)
  351. {
  352. struct pool *pool;
  353. total_urls++;
  354. if (total_urls > total_pools)
  355. add_pool();
  356. pool = pools[total_urls - 1];
  357. opt_set_charp(arg, &pool->rpc_url);
  358. if (strncmp(arg, "http://", 7) &&
  359. strncmp(arg, "https://", 8)) {
  360. char *httpinput;
  361. httpinput = malloc(255);
  362. if (!httpinput)
  363. quit(1, "Failed to malloc httpinput");
  364. strcpy(httpinput, "http://");
  365. strncat(httpinput, arg, 248);
  366. pool->rpc_url = httpinput;
  367. }
  368. return NULL;
  369. }
  370. static char *set_user(const char *arg, char **p)
  371. {
  372. struct pool *pool;
  373. if (total_userpasses)
  374. return "Use only user + pass or userpass, but not both";
  375. total_users++;
  376. if (total_users > total_pools)
  377. add_pool();
  378. pool = pools[total_users - 1];
  379. opt_set_charp(arg, &pool->rpc_user);
  380. return NULL;
  381. }
  382. static char *set_pass(const char *arg, char **p)
  383. {
  384. struct pool *pool;
  385. if (total_userpasses)
  386. return "Use only user + pass or userpass, but not both";
  387. total_passes++;
  388. if (total_passes > total_pools)
  389. add_pool();
  390. pool = pools[total_passes - 1];
  391. opt_set_charp(arg, &pool->rpc_pass);
  392. return NULL;
  393. }
  394. static char *set_userpass(const char *arg, char **p)
  395. {
  396. struct pool *pool;
  397. if (total_users || total_passes)
  398. return "Use only user + pass or userpass, but not both";
  399. total_userpasses++;
  400. if (total_userpasses > total_pools)
  401. add_pool();
  402. pool = pools[total_userpasses - 1];
  403. opt_set_charp(arg, &pool->rpc_userpass);
  404. return NULL;
  405. }
  406. static char *set_vector(const char *arg, int *i)
  407. {
  408. char *err = opt_set_intval(arg, i);
  409. if (err)
  410. return err;
  411. if (*i != 1 && *i != 2 && *i != 4)
  412. return "Valid vectors are 1, 2 or 4";
  413. return NULL;
  414. }
  415. static char *enable_debug(bool *flag)
  416. {
  417. *flag = true;
  418. /* Turn out verbose output, too. */
  419. opt_log_output = true;
  420. return NULL;
  421. }
  422. static char *trpc_url;
  423. static char *trpc_userpass;
  424. static char *trpc_user, *trpc_pass;
  425. /* These options are available from config file or commandline */
  426. static struct opt_table opt_config_table[] = {
  427. OPT_WITH_ARG("--algo|-a",
  428. set_algo, show_algo, &opt_algo,
  429. "Specify sha256 implementation for CPU mining:\n"
  430. "\tc\t\tLinux kernel sha256, implemented in C"
  431. #ifdef WANT_SSE2_4WAY
  432. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  433. #endif
  434. #ifdef WANT_VIA_PADLOCK
  435. "\n\tvia\t\tVIA padlock implementation"
  436. #endif
  437. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  438. #ifdef WANT_CRYPTOPP_ASM32
  439. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  440. #endif
  441. #ifdef WANT_X8664_SSE2
  442. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  443. #endif
  444. #ifdef WANT_X8664_SSE4
  445. "\n\tsse4_64\t\tSSE4 implementation for x86_64 machines"
  446. #endif
  447. ),
  448. OPT_WITH_ARG("--cpu-threads|-t",
  449. force_nthreads_int, opt_show_intval, &opt_n_threads,
  450. "Number of miner CPU threads"),
  451. OPT_WITHOUT_ARG("--debug|-D",
  452. enable_debug, &opt_debug,
  453. "Enable debug output"),
  454. #ifdef HAVE_OPENCL
  455. OPT_WITH_ARG("--device|-d",
  456. set_devices, NULL, &opt_device,
  457. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  458. OPT_WITH_ARG("--gpu-threads|-g",
  459. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  460. "Number of threads per GPU (0 - 10)"),
  461. OPT_WITH_ARG("--intensity|-I",
  462. forced_int_1010, opt_show_intval, &scan_intensity,
  463. "Intensity of GPU scanning (-10 -> 10, default: dynamic to maintain desktop interactivity)"),
  464. OPT_WITH_ARG("--kernel|-k",
  465. opt_set_charp, NULL, &opt_kernel,
  466. "Select kernel to use (poclbm or phatk - default: auto)"),
  467. #endif
  468. OPT_WITHOUT_ARG("--load-balance",
  469. set_loadbalance, &pool_strategy,
  470. "Change multipool strategy from failover to even load balance"),
  471. OPT_WITH_ARG("--log|-l",
  472. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  473. "Interval in seconds between log output"),
  474. OPT_WITHOUT_ARG("--no-longpoll",
  475. opt_set_invbool, &want_longpoll,
  476. "Disable X-Long-Polling support"),
  477. OPT_WITH_ARG("--pass|-p",
  478. set_pass, NULL, &trpc_pass,
  479. "Password for bitcoin JSON-RPC server"),
  480. OPT_WITHOUT_ARG("--protocol-dump|-P",
  481. opt_set_bool, &opt_protocol,
  482. "Verbose dump of protocol-level activities"),
  483. OPT_WITH_ARG("--queue|-Q",
  484. set_int_0_to_10, opt_show_intval, &opt_queue,
  485. "Number of extra work items to queue (0 - 10)"),
  486. OPT_WITHOUT_ARG("--quiet|-q",
  487. opt_set_bool, &opt_quiet,
  488. "Disable logging output, display status and errors"),
  489. OPT_WITHOUT_ARG("--real-quiet",
  490. opt_set_bool, &opt_realquiet,
  491. "Disable all output"),
  492. OPT_WITH_ARG("--retries|-r",
  493. opt_set_intval, opt_show_intval, &opt_retries,
  494. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  495. OPT_WITH_ARG("--retry-pause|-R",
  496. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  497. "Number of seconds to pause, between retries"),
  498. OPT_WITH_ARG("--rotate",
  499. set_rotate, opt_show_intval, &opt_rotate_period,
  500. "Change multipool strategy from failover to regularly rotate at N minutes"),
  501. OPT_WITHOUT_ARG("--round-robin",
  502. set_rr, &pool_strategy,
  503. "Change multipool strategy from failover to round robin on failure"),
  504. OPT_WITH_ARG("--scan-time|-s",
  505. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  506. "Upper bound on time spent scanning current work, in seconds"),
  507. #ifdef HAVE_SYSLOG_H
  508. OPT_WITHOUT_ARG("--syslog",
  509. opt_set_bool, &use_syslog,
  510. "Use system log for output messages (default: standard error)"),
  511. #endif
  512. #if !defined(WIN32)
  513. OPT_WITH_ARG("--monitor|-m",
  514. opt_set_charp, NULL, &opt_stderr_cmd,
  515. "Use custom pipe cmd for output messages"),
  516. #endif // !WIN32
  517. OPT_WITHOUT_ARG("--text-only|-T",
  518. opt_set_invbool, &use_curses,
  519. "Disable ncurses formatted screen output"),
  520. OPT_WITH_ARG("--url|-o",
  521. set_url, opt_show_charp, &trpc_url,
  522. "URL for bitcoin JSON-RPC server"),
  523. OPT_WITH_ARG("--user|-u",
  524. set_user, NULL, &trpc_user,
  525. "Username for bitcoin JSON-RPC server"),
  526. #ifdef HAVE_OPENCL
  527. OPT_WITH_ARG("--vectors|-v",
  528. set_vector, NULL, &opt_vectors,
  529. "Override detected optimal vector width (1, 2 or 4)"),
  530. #endif
  531. OPT_WITHOUT_ARG("--verbose",
  532. opt_set_bool, &opt_log_output,
  533. "Log verbose output to stderr as well as status output"),
  534. #ifdef HAVE_OPENCL
  535. OPT_WITH_ARG("--worksize|-w",
  536. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  537. "Override detected optimal worksize"),
  538. #endif
  539. OPT_WITH_ARG("--userpass|-O",
  540. set_userpass, NULL, &trpc_userpass,
  541. "Username:Password pair for bitcoin JSON-RPC server"),
  542. OPT_ENDTABLE
  543. };
  544. static char *parse_config(json_t *config)
  545. {
  546. static char err_buf[200];
  547. json_t *val;
  548. struct opt_table *opt;
  549. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  550. char *p, *name;
  551. /* We don't handle subtables. */
  552. assert(!(opt->type & OPT_SUBTABLE));
  553. /* Pull apart the option name(s). */
  554. name = strdup(opt->names);
  555. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  556. char *err;
  557. /* Ignore short options. */
  558. if (p[1] != '-')
  559. continue;
  560. val = json_object_get(config, p+2);
  561. if (!val)
  562. continue;
  563. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  564. err = opt->cb_arg(json_string_value(val),
  565. opt->u.arg);
  566. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  567. err = opt->cb(opt->u.arg);
  568. } else {
  569. err = "Invalid value";
  570. }
  571. if (err) {
  572. sprintf(err_buf, "Parsing JSON option %s: %s",
  573. p, err);
  574. return err_buf;
  575. }
  576. }
  577. free(name);
  578. }
  579. return NULL;
  580. }
  581. static char *load_config(const char *arg, void *unused)
  582. {
  583. json_error_t err;
  584. json_t *config;
  585. config = json_load_file(arg, 0, &err);
  586. if (!json_is_object(config))
  587. return "JSON decode of file failed";
  588. /* Parse the config now, so we can override it. That can keep pointers
  589. * so don't free config object. */
  590. return parse_config(config);
  591. }
  592. #ifdef HAVE_OPENCL
  593. static char *print_ndevs_and_exit(int *ndevs)
  594. {
  595. printf("%i GPU devices detected\n", *ndevs);
  596. exit(*ndevs);
  597. }
  598. #endif
  599. /* These options are available from commandline only */
  600. static struct opt_table opt_cmdline_table[] = {
  601. OPT_WITH_ARG("--config|-c",
  602. load_config, NULL, NULL,
  603. "Load a JSON-format configuration file\n"
  604. "See example-cfg.json for an example configuration."),
  605. OPT_WITHOUT_ARG("--help|-h",
  606. opt_usage_and_exit,
  607. #ifdef HAVE_OPENCL
  608. "\nBuilt with CPU and GPU mining support.\n",
  609. #else
  610. "\nBuilt with CPU mining support only.\n",
  611. #endif
  612. "Print this message"),
  613. #ifdef HAVE_OPENCL
  614. OPT_WITHOUT_ARG("--ndevs|-n",
  615. print_ndevs_and_exit, &nDevs,
  616. "Enumerate number of detected GPUs and exit"),
  617. #endif
  618. OPT_ENDTABLE
  619. };
  620. static bool jobj_binary(const json_t *obj, const char *key,
  621. void *buf, size_t buflen)
  622. {
  623. const char *hexstr;
  624. json_t *tmp;
  625. tmp = json_object_get(obj, key);
  626. if (unlikely(!tmp)) {
  627. applog(LOG_ERR, "JSON key '%s' not found", key);
  628. return false;
  629. }
  630. hexstr = json_string_value(tmp);
  631. if (unlikely(!hexstr)) {
  632. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  633. return false;
  634. }
  635. if (!hex2bin(buf, hexstr, buflen))
  636. return false;
  637. return true;
  638. }
  639. static bool work_decode(const json_t *val, struct work *work)
  640. {
  641. if (unlikely(!jobj_binary(val, "midstate",
  642. work->midstate, sizeof(work->midstate)))) {
  643. applog(LOG_ERR, "JSON inval midstate");
  644. goto err_out;
  645. }
  646. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  647. applog(LOG_ERR, "JSON inval data");
  648. goto err_out;
  649. }
  650. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  651. applog(LOG_ERR, "JSON inval hash1");
  652. goto err_out;
  653. }
  654. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  655. applog(LOG_ERR, "JSON inval target");
  656. goto err_out;
  657. }
  658. memset(work->hash, 0, sizeof(work->hash));
  659. return true;
  660. err_out:
  661. return false;
  662. }
  663. static inline int dev_from_id(int thr_id)
  664. {
  665. return thr_info[thr_id].cgpu->cpu_gpu;
  666. }
  667. /* Simulate a rolling average by faking an exponential decay over 5 * log */
  668. static inline void decay_time(double *f, double fadd)
  669. {
  670. *f = (fadd + *f * 0.9) / 1.9;
  671. }
  672. static WINDOW *mainwin, *statuswin, *logwin;
  673. static double total_secs = 0.1;
  674. static char statusline[256];
  675. static int cpucursor, gpucursor, logstart, logcursor;
  676. static struct cgpu_info *gpus, *cpus;
  677. static void text_print_status(int thr_id)
  678. {
  679. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  680. printf(" %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  681. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  682. cgpu->total_mhashes / total_secs, cgpu->getworks,
  683. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  684. cgpu->efficiency, cgpu->utility);
  685. }
  686. /* Must be called with curses mutex lock held and curses_active */
  687. static void curses_print_status(int thr_id)
  688. {
  689. struct pool *pool = current_pool();
  690. wmove(statuswin, 0, 0);
  691. wattron(statuswin, A_BOLD);
  692. wprintw(statuswin, " " PROGRAM_NAME " version " VERSION " - Started: %s", datestamp);
  693. wattroff(statuswin, A_BOLD);
  694. wmove(statuswin, 1, 0);
  695. whline(statuswin, '-', 80);
  696. wmove(statuswin, 2,0);
  697. wprintw(statuswin, " %s", statusline);
  698. wclrtoeol(statuswin);
  699. wmove(statuswin, 3,0);
  700. wprintw(statuswin, " TQ: %d ST: %d LS: %d SS: %d DW: %d NB: %d LW: %d LO: %d RF: %d I: %d",
  701. total_queued, total_staged, lp_staged, total_stale, total_discarded, new_blocks,
  702. local_work, total_lo, total_ro, scan_intensity);
  703. wclrtoeol(statuswin);
  704. wmove(statuswin, 4, 0);
  705. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  706. wprintw(statuswin, " Connected to multiple pools");
  707. else
  708. wprintw(statuswin, " Connected to %s as user %s", pool->rpc_url, pool->rpc_user);
  709. wclrtoeol(statuswin);
  710. wmove(statuswin, 5, 0);
  711. wprintw(statuswin, " Block: %s... Started: %s", current_hash, blocktime);
  712. wmove(statuswin, 6, 0);
  713. whline(statuswin, '-', 80);
  714. wmove(statuswin, logstart - 1, 0);
  715. whline(statuswin, '-', 80);
  716. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  717. opt_g_threads ? "[G]PU management " : "");
  718. if (thr_id >= 0 && thr_id < gpu_threads) {
  719. int gpu = dev_from_id(thr_id);
  720. struct cgpu_info *cgpu = &gpus[gpu];
  721. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  722. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  723. wmove(statuswin, gpucursor + gpu, 0);
  724. if (cgpu->status == LIFE_DEAD)
  725. wprintw(statuswin, " GPU %d: [DEAD / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  726. gpu, cgpu->total_mhashes / total_secs,
  727. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  728. cgpu->efficiency, cgpu->utility);
  729. else if (cgpu->status == LIFE_SICK)
  730. wprintw(statuswin, " GPU %d: [SICK / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  731. gpu, cgpu->total_mhashes / total_secs,
  732. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  733. cgpu->efficiency, cgpu->utility);
  734. else if (!gpu_devices[gpu])
  735. wprintw(statuswin, " GPU %d: [DISABLED / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  736. gpu, cgpu->total_mhashes / total_secs,
  737. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  738. cgpu->efficiency, cgpu->utility);
  739. else
  740. wprintw(statuswin, " GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  741. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  742. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  743. cgpu->efficiency, cgpu->utility);
  744. wclrtoeol(statuswin);
  745. } else if (thr_id >= gpu_threads) {
  746. int cpu = dev_from_id(thr_id);
  747. struct cgpu_info *cgpu = &cpus[cpu];
  748. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  749. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  750. wmove(statuswin, cpucursor + cpu, 0);
  751. wprintw(statuswin, " CPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  752. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  753. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  754. cgpu->efficiency, cgpu->utility);
  755. wclrtoeol(statuswin);
  756. }
  757. wrefresh(statuswin);
  758. }
  759. static void print_status(int thr_id)
  760. {
  761. if (!curses_active)
  762. text_print_status(thr_id);
  763. else {
  764. mutex_lock(&curses_lock);
  765. curses_print_status(thr_id);
  766. mutex_unlock(&curses_lock);
  767. }
  768. }
  769. /* Check for window resize. Called with curses mutex locked */
  770. static inline void check_logwinsize(void)
  771. {
  772. int x, y, logx, logy;
  773. getmaxyx(mainwin, y, x);
  774. getmaxyx(logwin, logy, logx);
  775. y -= logcursor;
  776. /* Detect screen size change */
  777. if ((x != logx || y != logy) && x >= 80 && y >= 25)
  778. wresize(logwin, y, x);
  779. }
  780. /* For mandatory printing when mutex is already locked */
  781. static void wlog(const char *f, ...)
  782. {
  783. va_list ap;
  784. va_start(ap, f);
  785. vw_printw(logwin, f, ap);
  786. va_end(ap);
  787. }
  788. /* Mandatory printing */
  789. static void wlogprint(const char *f, ...)
  790. {
  791. va_list ap;
  792. mutex_lock(&curses_lock);
  793. va_start(ap, f);
  794. vw_printw(logwin, f, ap);
  795. va_end(ap);
  796. wrefresh(logwin);
  797. mutex_unlock(&curses_lock);
  798. }
  799. void log_curses(int prio, const char *f, va_list ap)
  800. {
  801. if (opt_quiet && prio != LOG_ERR)
  802. return;
  803. if (curses_active) {
  804. if (!opt_loginput) {
  805. mutex_lock(&curses_lock);
  806. vw_printw(logwin, f, ap);
  807. wrefresh(logwin);
  808. mutex_unlock(&curses_lock);
  809. }
  810. } else
  811. vprintf(f, ap);
  812. }
  813. static void clear_logwin(void)
  814. {
  815. mutex_lock(&curses_lock);
  816. wclear(logwin);
  817. wrefresh(logwin);
  818. mutex_unlock(&curses_lock);
  819. }
  820. static bool submit_upstream_work(const struct work *work)
  821. {
  822. char *hexstr = NULL;
  823. json_t *val, *res;
  824. char s[345], sd[345];
  825. bool rc = false;
  826. int thr_id = work->thr_id;
  827. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  828. CURL *curl = curl_easy_init();
  829. struct pool *pool = work->pool;
  830. if (unlikely(!curl)) {
  831. applog(LOG_ERR, "CURL initialisation failed");
  832. return rc;
  833. }
  834. /* build hex string */
  835. hexstr = bin2hex(work->data, sizeof(work->data));
  836. if (unlikely(!hexstr)) {
  837. applog(LOG_ERR, "submit_upstream_work OOM");
  838. goto out_nofree;
  839. }
  840. /* build JSON-RPC request */
  841. sprintf(s,
  842. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  843. hexstr);
  844. sprintf(sd,
  845. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  846. hexstr);
  847. if (opt_debug)
  848. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  849. /* issue JSON-RPC request */
  850. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, pool);
  851. if (unlikely(!val)) {
  852. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  853. if (!pool_tset(pool, &pool->submit_fail)) {
  854. total_ro++;
  855. pool->remotefail_occasions++;
  856. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  857. }
  858. goto out;
  859. } else if (pool_tclear(pool, &pool->submit_fail))
  860. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  861. res = json_object_get(val, "result");
  862. /* Theoretically threads could race when modifying accepted and
  863. * rejected values but the chance of two submits completing at the
  864. * same time is zero so there is no point adding extra locking */
  865. if (json_is_true(res)) {
  866. cgpu->accepted++;
  867. total_accepted++;
  868. pool->accepted++;
  869. if (opt_debug)
  870. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  871. if (!QUIET) {
  872. if (total_pools > 1)
  873. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  874. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  875. else
  876. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  877. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  878. }
  879. } else {
  880. cgpu->rejected++;
  881. total_rejected++;
  882. pool->rejected++;
  883. if (opt_debug)
  884. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  885. if (!QUIET) {
  886. if (total_pools > 1)
  887. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  888. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  889. else
  890. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  891. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  892. }
  893. }
  894. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  895. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  896. if (!opt_realquiet)
  897. print_status(thr_id);
  898. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  899. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  900. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  901. json_decref(val);
  902. rc = true;
  903. out:
  904. free(hexstr);
  905. out_nofree:
  906. curl_easy_cleanup(curl);
  907. return rc;
  908. }
  909. static const char *rpc_req =
  910. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  911. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  912. static inline struct pool *select_pool(bool lagging)
  913. {
  914. static int rotating_pool = 0;
  915. struct pool *pool, *cp;
  916. cp = current_pool();
  917. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  918. pool = cp;
  919. else
  920. pool = NULL;
  921. while (!pool) {
  922. if (++rotating_pool >= total_pools)
  923. rotating_pool = 0;
  924. pool = pools[rotating_pool];
  925. if ((!pool->idle && pool->enabled) || pool == cp)
  926. break;
  927. pool = NULL;
  928. }
  929. return pool;
  930. }
  931. static bool get_upstream_work(struct work *work, bool lagging)
  932. {
  933. struct pool *pool;
  934. json_t *val;
  935. bool rc = false;
  936. CURL *curl;
  937. curl = curl_easy_init();
  938. if (unlikely(!curl)) {
  939. applog(LOG_ERR, "CURL initialisation failed");
  940. return rc;
  941. }
  942. pool = select_pool(lagging);
  943. if (opt_debug)
  944. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  945. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  946. want_longpoll, false, pool);
  947. if (unlikely(!val)) {
  948. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  949. goto out;
  950. }
  951. rc = work_decode(json_object_get(val, "result"), work);
  952. work->pool = pool;
  953. total_getworks++;
  954. pool->getwork_requested++;
  955. if (work->thr)
  956. work->thr->cgpu->getworks++;
  957. json_decref(val);
  958. out:
  959. curl_easy_cleanup(curl);
  960. return rc;
  961. }
  962. static void workio_cmd_free(struct workio_cmd *wc)
  963. {
  964. if (!wc)
  965. return;
  966. switch (wc->cmd) {
  967. case WC_SUBMIT_WORK:
  968. free(wc->u.work);
  969. break;
  970. default: /* do nothing */
  971. break;
  972. }
  973. memset(wc, 0, sizeof(*wc)); /* poison */
  974. free(wc);
  975. }
  976. static void disable_curses(void)
  977. {
  978. if (test_and_clear(&curses_active)) {
  979. leaveok(logwin, false);
  980. leaveok(statuswin, false);
  981. leaveok(mainwin, false);
  982. nocbreak();
  983. echo();
  984. delwin(logwin);
  985. delwin(statuswin);
  986. delwin(mainwin);
  987. endwin();
  988. refresh();
  989. #ifdef WIN32
  990. // Move the cursor to after curses output.
  991. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  992. CONSOLE_SCREEN_BUFFER_INFO csbi;
  993. COORD coord;
  994. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  995. coord.X = 0;
  996. coord.Y = csbi.dwSize.Y - 1;
  997. SetConsoleCursorPosition(hout, coord);
  998. }
  999. #endif
  1000. }
  1001. }
  1002. void kill_work(void)
  1003. {
  1004. struct workio_cmd *wc;
  1005. struct thr_info *thr;
  1006. unsigned int i;
  1007. disable_curses();
  1008. applog(LOG_INFO, "Received kill message");
  1009. /* Kill the watchdog thread */
  1010. thr = &thr_info[watchdog_thr_id];
  1011. pthread_cancel(*thr->pth);
  1012. /* Stop the mining threads*/
  1013. for (i = 0; i < mining_threads; i++) {
  1014. thr = &thr_info[i];
  1015. if (!thr->pth)
  1016. continue;
  1017. tq_freeze(thr->q);
  1018. /* No need to check if this succeeds or not */
  1019. pthread_cancel(*thr->pth);
  1020. }
  1021. /* Stop the others */
  1022. thr = &thr_info[stage_thr_id];
  1023. pthread_cancel(*thr->pth);
  1024. thr = &thr_info[longpoll_thr_id];
  1025. pthread_cancel(*thr->pth);
  1026. wc = calloc(1, sizeof(*wc));
  1027. if (unlikely(!wc)) {
  1028. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  1029. /* We're just trying to die anyway, so forget graceful */
  1030. exit (1);
  1031. }
  1032. wc->cmd = WC_DIE;
  1033. wc->thr = 0;
  1034. if (opt_debug)
  1035. applog(LOG_DEBUG, "Pushing die request to work thread");
  1036. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1037. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  1038. exit (1);
  1039. }
  1040. }
  1041. static void sighandler(int sig)
  1042. {
  1043. /* Restore signal handlers so we can still quit if kill_work fails */
  1044. sigaction(SIGTERM, &termhandler, NULL);
  1045. sigaction(SIGINT, &inthandler, NULL);
  1046. kill_work();
  1047. }
  1048. static struct work *make_work(void)
  1049. {
  1050. struct work *work = calloc(1, sizeof(struct work));
  1051. if (unlikely(!work))
  1052. quit(1, "Failed to calloc work in make_work");
  1053. return work;
  1054. }
  1055. static void *get_work_thread(void *userdata)
  1056. {
  1057. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1058. struct work *ret_work;
  1059. int failures = 0;
  1060. pthread_detach(pthread_self());
  1061. ret_work = make_work();
  1062. if (wc->thr)
  1063. ret_work->thr = wc->thr;
  1064. else
  1065. ret_work->thr = NULL;
  1066. /* obtain new work from bitcoin via JSON-RPC */
  1067. while (!get_upstream_work(ret_work, wc->lagging)) {
  1068. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1069. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1070. free(ret_work);
  1071. kill_work();
  1072. goto out;
  1073. }
  1074. /* pause, then restart work-request loop */
  1075. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1076. opt_fail_pause);
  1077. sleep(opt_fail_pause);
  1078. }
  1079. if (opt_debug)
  1080. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1081. /* send work to requesting thread */
  1082. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1083. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1084. kill_work();
  1085. free(ret_work);
  1086. }
  1087. out:
  1088. workio_cmd_free(wc);
  1089. return NULL;
  1090. }
  1091. static bool workio_get_work(struct workio_cmd *wc)
  1092. {
  1093. pthread_t get_thread;
  1094. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1095. applog(LOG_ERR, "Failed to create get_work_thread");
  1096. return false;
  1097. }
  1098. return true;
  1099. }
  1100. static bool stale_work(struct work *work)
  1101. {
  1102. struct timeval now;
  1103. bool ret = false;
  1104. char *hexstr;
  1105. gettimeofday(&now, NULL);
  1106. if ((now.tv_sec - work->tv_staged.tv_sec) > opt_scantime)
  1107. return true;
  1108. /* Only use the primary pool for determination as the work may
  1109. * interleave at times of new blocks */
  1110. if (work->pool != current_pool())
  1111. return ret;
  1112. hexstr = bin2hex(work->data, 36);
  1113. if (unlikely(!hexstr)) {
  1114. applog(LOG_ERR, "submit_work_thread OOM");
  1115. return ret;
  1116. }
  1117. if (strncmp(hexstr, current_block, 36))
  1118. ret = true;
  1119. free(hexstr);
  1120. return ret;
  1121. }
  1122. static void *submit_work_thread(void *userdata)
  1123. {
  1124. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1125. struct work *work = wc->u.work;
  1126. struct pool *pool = work->pool;
  1127. int failures = 0;
  1128. pthread_detach(pthread_self());
  1129. if (stale_work(work)) {
  1130. applog(LOG_WARNING, "Stale share detected, discarding");
  1131. total_stale++;
  1132. pool->stale_shares++;
  1133. goto out;
  1134. }
  1135. /* submit solution to bitcoin via JSON-RPC */
  1136. while (!submit_upstream_work(work)) {
  1137. if (stale_work(work)) {
  1138. applog(LOG_WARNING, "Stale share detected, discarding");
  1139. total_stale++;
  1140. pool->stale_shares++;
  1141. break;
  1142. }
  1143. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1144. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1145. kill_work();
  1146. break;
  1147. }
  1148. /* pause, then restart work-request loop */
  1149. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1150. opt_fail_pause);
  1151. sleep(opt_fail_pause);
  1152. }
  1153. out:
  1154. workio_cmd_free(wc);
  1155. return NULL;
  1156. }
  1157. static bool workio_submit_work(struct workio_cmd *wc)
  1158. {
  1159. pthread_t submit_thread;
  1160. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1161. applog(LOG_ERR, "Failed to create submit_work_thread");
  1162. return false;
  1163. }
  1164. return true;
  1165. }
  1166. static void inc_staged(struct pool *pool, int inc, bool lp)
  1167. {
  1168. mutex_lock(&stgd_lock);
  1169. if (lp) {
  1170. lp_staged += inc;
  1171. total_staged += inc;
  1172. } else if (lp_staged)
  1173. --lp_staged;
  1174. else
  1175. total_staged += inc;
  1176. mutex_unlock(&stgd_lock);
  1177. }
  1178. static void dec_staged(int inc)
  1179. {
  1180. mutex_lock(&stgd_lock);
  1181. total_staged -= inc;
  1182. mutex_unlock(&stgd_lock);
  1183. }
  1184. static int requests_staged(void)
  1185. {
  1186. int ret;
  1187. mutex_lock(&stgd_lock);
  1188. ret = total_staged;
  1189. mutex_unlock(&stgd_lock);
  1190. return ret;
  1191. }
  1192. static int real_staged(void)
  1193. {
  1194. int ret;
  1195. mutex_lock(&stgd_lock);
  1196. ret = total_staged - lp_staged;
  1197. mutex_unlock(&stgd_lock);
  1198. return ret;
  1199. }
  1200. /* Find the pool that currently has the highest priority */
  1201. static struct pool *priority_pool(int choice)
  1202. {
  1203. struct pool *ret = NULL;
  1204. int i;
  1205. for (i = 0; i < total_pools; i++) {
  1206. struct pool *pool = pools[i];
  1207. if (pool->prio == choice) {
  1208. ret = pool;
  1209. break;
  1210. }
  1211. }
  1212. if (unlikely(!ret)) {
  1213. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1214. return pools[choice];
  1215. }
  1216. return ret;
  1217. }
  1218. static void restart_longpoll(void);
  1219. static void switch_pools(struct pool *selected)
  1220. {
  1221. struct pool *pool, *last_pool;
  1222. int i, pool_no;
  1223. mutex_lock(&control_lock);
  1224. last_pool = currentpool;
  1225. pool_no = currentpool->pool_no;
  1226. /* Switch selected to pool number 0 and move the rest down */
  1227. if (selected) {
  1228. if (selected->prio != 0) {
  1229. for (i = 0; i < total_pools; i++) {
  1230. pool = pools[i];
  1231. if (pool->prio < selected->prio)
  1232. pool->prio++;
  1233. }
  1234. selected->prio = 0;
  1235. }
  1236. }
  1237. switch (pool_strategy) {
  1238. /* Both of these set to the master pool */
  1239. case POOL_FAILOVER:
  1240. case POOL_LOADBALANCE:
  1241. for (i = 0; i < total_pools; i++) {
  1242. pool = priority_pool(i);
  1243. if (!pool->idle && pool->enabled) {
  1244. pool_no = pool->pool_no;
  1245. break;
  1246. }
  1247. }
  1248. break;
  1249. /* Both of these simply increment and cycle */
  1250. case POOL_ROUNDROBIN:
  1251. case POOL_ROTATE:
  1252. if (selected) {
  1253. pool_no = selected->pool_no;
  1254. break;
  1255. }
  1256. pool_no++;
  1257. if (pool_no >= total_pools)
  1258. pool_no = 0;
  1259. break;
  1260. default:
  1261. break;
  1262. }
  1263. currentpool = pools[pool_no];
  1264. pool = currentpool;
  1265. mutex_unlock(&control_lock);
  1266. if (pool != last_pool) {
  1267. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1268. restart_longpoll();
  1269. }
  1270. /* Reset the queued amount to allow more to be queued for the new pool */
  1271. mutex_lock(&qd_lock);
  1272. total_queued = 0;
  1273. mutex_unlock(&qd_lock);
  1274. inc_staged(pool, 1, true);
  1275. }
  1276. static void set_curblock(char *hexstr, unsigned char *hash)
  1277. {
  1278. unsigned char hash_swap[32];
  1279. char *old_hash = NULL;
  1280. struct timeval tv_now;
  1281. /* Don't free current_hash directly to avoid dereferencing it when
  1282. * we might be accessing its data elsewhere */
  1283. if (current_hash)
  1284. old_hash = current_hash;
  1285. memcpy(current_block, hexstr, 36);
  1286. gettimeofday(&tv_now, NULL);
  1287. get_timestamp(blocktime, &tv_now);
  1288. swap256(hash_swap, hash);
  1289. current_hash = bin2hex(hash_swap, 16);
  1290. if (unlikely(!current_hash))
  1291. quit (1, "set_curblock OOM");
  1292. if (old_hash)
  1293. free(old_hash);
  1294. }
  1295. static void test_work_current(struct work *work)
  1296. {
  1297. char *hexstr;
  1298. /* Only use the primary pool for determination */
  1299. if (work->pool != current_pool() || work->cloned || work->rolls || work->clone)
  1300. return;
  1301. hexstr = bin2hex(work->data, 36);
  1302. if (unlikely(!hexstr)) {
  1303. applog(LOG_ERR, "stage_thread OOM");
  1304. return;
  1305. }
  1306. /* current_block is blanked out on successful longpoll */
  1307. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1308. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1309. block_changed = BLOCK_DETECT;
  1310. new_blocks++;
  1311. if (have_longpoll)
  1312. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1313. else
  1314. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1315. /* As we can't flush the work from here, signal the
  1316. * wakeup thread to restart all the threads */
  1317. work_restart[watchdog_thr_id].restart = 1;
  1318. } else
  1319. block_changed = BLOCK_NONE;
  1320. set_curblock(hexstr, work->data);
  1321. }
  1322. free(hexstr);
  1323. }
  1324. static void *stage_thread(void *userdata)
  1325. {
  1326. struct thr_info *mythr = userdata;
  1327. bool ok = true;
  1328. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1329. while (ok) {
  1330. struct work *work = NULL;
  1331. if (opt_debug)
  1332. applog(LOG_DEBUG, "Popping work to stage thread");
  1333. work = tq_pop(mythr->q, NULL);
  1334. if (unlikely(!work)) {
  1335. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1336. ok = false;
  1337. break;
  1338. }
  1339. test_work_current(work);
  1340. if (!work->cloned && !work->clone)
  1341. gettimeofday(&work->tv_staged, NULL);
  1342. if (opt_debug)
  1343. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1344. if (unlikely(!tq_push(getq, work))) {
  1345. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1346. ok = false;
  1347. break;
  1348. }
  1349. inc_staged(work->pool, 1, false);
  1350. }
  1351. tq_freeze(mythr->q);
  1352. return NULL;
  1353. }
  1354. static char *curses_input(const char *query);
  1355. static int curses_int(const char *query)
  1356. {
  1357. int ret;
  1358. char *cvar;
  1359. cvar = curses_input(query);
  1360. ret = atoi(cvar);
  1361. free(cvar);
  1362. return ret;
  1363. }
  1364. static bool input_pool(bool live);
  1365. static int active_pools(void)
  1366. {
  1367. int ret = 0;
  1368. int i;
  1369. for (i = 0; i < total_pools; i++) {
  1370. if ((pools[i])->enabled)
  1371. ret++;
  1372. }
  1373. return ret;
  1374. }
  1375. static void display_pool_summary(struct pool *pool)
  1376. {
  1377. double efficiency = 0.0;
  1378. mutex_lock(&curses_lock);
  1379. wlog("Pool: %s\n", pool->rpc_url);
  1380. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1381. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1382. wlog(" Accepted shares: %d\n", pool->accepted);
  1383. wlog(" Rejected shares: %d\n", pool->rejected);
  1384. if (pool->accepted || pool->rejected)
  1385. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1386. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1387. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1388. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1389. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1390. wlog(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1391. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1392. wrefresh(logwin);
  1393. mutex_unlock(&curses_lock);
  1394. }
  1395. /* We can't remove the memory used for this struct pool because there may
  1396. * still be work referencing it. We just remove it from the pools list */
  1397. static void remove_pool(struct pool *pool)
  1398. {
  1399. int i, last_pool = total_pools - 1;
  1400. struct pool *other;
  1401. /* Boost priority of any lower prio than this one */
  1402. for (i = 0; i < total_pools; i++) {
  1403. other = pools[i];
  1404. if (other->prio > pool->prio)
  1405. other->prio--;
  1406. }
  1407. if (pool->pool_no < last_pool) {
  1408. /* Swap the last pool for this one */
  1409. (pools[last_pool])->pool_no = pool->pool_no;
  1410. pools[pool->pool_no] = pools[last_pool];
  1411. }
  1412. /* Give it an invalid number */
  1413. pool->pool_no = total_pools;
  1414. total_pools--;
  1415. }
  1416. static void display_pools(void)
  1417. {
  1418. struct pool *pool;
  1419. int selected, i;
  1420. char input;
  1421. opt_loginput = true;
  1422. immedok(logwin, true);
  1423. updated:
  1424. clear_logwin();
  1425. for (i = 0; i < total_pools; i++) {
  1426. pool = pools[i];
  1427. if (pool == current_pool())
  1428. wattron(logwin, A_BOLD);
  1429. if (!pool->enabled)
  1430. wattron(logwin, A_DIM);
  1431. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  1432. pool->pool_no,
  1433. pool->enabled? "Enabled" : "Disabled",
  1434. pool->idle? "Dead" : "Alive",
  1435. pool->prio,
  1436. pool->rpc_url, pool->rpc_user);
  1437. wattroff(logwin, A_BOLD | A_DIM);
  1438. }
  1439. retry:
  1440. wlogprint("\nCurrent pool management strategy: %s\n",
  1441. strategies[pool_strategy]);
  1442. if (pool_strategy == POOL_ROTATE)
  1443. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  1444. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  1445. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  1446. wlogprint("Or press any other key to continue\n");
  1447. input = getch();
  1448. if (!strncasecmp(&input, "a", 1)) {
  1449. input_pool(true);
  1450. goto updated;
  1451. } else if (!strncasecmp(&input, "r", 1)) {
  1452. if (total_pools <= 1) {
  1453. wlogprint("Cannot remove last pool");
  1454. goto retry;
  1455. }
  1456. selected = curses_int("Select pool number");
  1457. if (selected < 0 || selected >= total_pools) {
  1458. wlogprint("Invalid selection\n");
  1459. goto retry;
  1460. }
  1461. pool = pools[selected];
  1462. if (pool == current_pool())
  1463. switch_pools(NULL);
  1464. if (pool == current_pool()) {
  1465. wlogprint("Unable to remove pool due to activity\n");
  1466. goto retry;
  1467. }
  1468. pool->enabled = false;
  1469. remove_pool(pool);
  1470. goto updated;
  1471. } else if (!strncasecmp(&input, "s", 1)) {
  1472. selected = curses_int("Select pool number");
  1473. if (selected < 0 || selected >= total_pools) {
  1474. wlogprint("Invalid selection\n");
  1475. goto retry;
  1476. }
  1477. pool = pools[selected];
  1478. pool->enabled = true;
  1479. switch_pools(pool);
  1480. goto updated;
  1481. } else if (!strncasecmp(&input, "d", 1)) {
  1482. if (active_pools() <= 1) {
  1483. wlogprint("Cannot disable last pool");
  1484. goto retry;
  1485. }
  1486. selected = curses_int("Select pool number");
  1487. if (selected < 0 || selected >= total_pools) {
  1488. wlogprint("Invalid selection\n");
  1489. goto retry;
  1490. }
  1491. pool = pools[selected];
  1492. pool->enabled = false;
  1493. if (pool == current_pool())
  1494. switch_pools(NULL);
  1495. goto updated;
  1496. } else if (!strncasecmp(&input, "e", 1)) {
  1497. selected = curses_int("Select pool number");
  1498. if (selected < 0 || selected >= total_pools) {
  1499. wlogprint("Invalid selection\n");
  1500. goto retry;
  1501. }
  1502. pool = pools[selected];
  1503. pool->enabled = true;
  1504. if (pool->prio < current_pool()->prio)
  1505. switch_pools(pool);
  1506. goto updated;
  1507. } else if (!strncasecmp(&input, "c", 1)) {
  1508. for (i = 0; i <= TOP_STRATEGY; i++)
  1509. wlogprint("%d: %s\n", i, strategies[i]);
  1510. selected = curses_int("Select strategy number type");
  1511. if (selected < 0 || selected > TOP_STRATEGY) {
  1512. wlogprint("Invalid selection\n");
  1513. goto retry;
  1514. }
  1515. if (selected == POOL_ROTATE) {
  1516. opt_rotate_period = curses_int("Select interval in minutes");
  1517. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  1518. opt_rotate_period = 0;
  1519. wlogprint("Invalid selection\n");
  1520. goto retry;
  1521. }
  1522. }
  1523. pool_strategy = selected;
  1524. switch_pools(NULL);
  1525. goto updated;
  1526. } else if (!strncasecmp(&input, "i", 1)) {
  1527. selected = curses_int("Select pool number");
  1528. if (selected < 0 || selected >= total_pools) {
  1529. wlogprint("Invalid selection\n");
  1530. goto retry;
  1531. }
  1532. pool = pools[selected];
  1533. display_pool_summary(pool);
  1534. goto retry;
  1535. }
  1536. clear_logwin();
  1537. immedok(logwin, false);
  1538. opt_loginput = false;
  1539. }
  1540. static void display_options(void)
  1541. {
  1542. int selected;
  1543. char input;
  1544. opt_loginput = true;
  1545. immedok(logwin, true);
  1546. retry:
  1547. clear_logwin();
  1548. wlogprint("\n[D]ebug:%s [Q]uiet:%s [V]erbose:%s [R]PC debug:%s [L]og interval:%d\n",
  1549. opt_debug ? "on" : "off",
  1550. opt_quiet ? "on" : "off",
  1551. opt_log_output ? "on" : "off",
  1552. opt_protocol ? "on" : "off",
  1553. opt_log_interval);
  1554. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  1555. wlogprint("Select an option or any other key to return\n");
  1556. input = getch();
  1557. if (!strncasecmp(&input, "q", 1)) {
  1558. opt_quiet ^= true;
  1559. clear_logwin();
  1560. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  1561. } else if (!strncasecmp(&input, "v", 1)) {
  1562. opt_log_output ^= true;
  1563. if (opt_log_output)
  1564. opt_quiet = false;
  1565. clear_logwin();
  1566. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  1567. } else if (!strncasecmp(&input, "n", 1)) {
  1568. opt_log_output = false;
  1569. opt_debug = false;
  1570. opt_quiet = false;
  1571. opt_protocol = false;
  1572. clear_logwin();
  1573. wlogprint("Output mode reset to normal\n");
  1574. } else if (!strncasecmp(&input, "d", 1)) {
  1575. opt_debug ^= true;
  1576. if (opt_debug) {
  1577. opt_log_output = true;
  1578. opt_quiet = false;
  1579. }
  1580. clear_logwin();
  1581. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  1582. } else if (!strncasecmp(&input, "r", 1)) {
  1583. opt_protocol ^= true;
  1584. if (opt_protocol)
  1585. opt_quiet = false;
  1586. clear_logwin();
  1587. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  1588. } else if (!strncasecmp(&input, "c", 1))
  1589. clear_logwin();
  1590. else if (!strncasecmp(&input, "l", 1)) {
  1591. selected = curses_int("Interval in seconds");
  1592. if (selected < 0 || selected > 9999) {
  1593. wlogprint("Invalid selection\n");
  1594. goto retry;
  1595. }
  1596. opt_log_interval = selected;
  1597. clear_logwin();
  1598. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  1599. } else if (!strncasecmp(&input, "s", 1)) {
  1600. opt_realquiet = true;
  1601. clear_logwin();
  1602. } else clear_logwin();
  1603. immedok(logwin, false);
  1604. opt_loginput = false;
  1605. }
  1606. static void set_options(void)
  1607. {
  1608. int selected;
  1609. char input;
  1610. opt_loginput = true;
  1611. immedok(logwin, true);
  1612. retry:
  1613. clear_logwin();
  1614. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  1615. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  1616. if (opt_dynamic)
  1617. wlogprint("[I]ntensity: Dynamic\n");
  1618. else
  1619. wlogprint("[I]ntensity: %d\n", scan_intensity);
  1620. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  1621. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  1622. wlogprint("Select an option or any other key to return\n");
  1623. input = getch();
  1624. if (!strncasecmp(&input, "q", 1)) {
  1625. selected = curses_int("Extra work items to queue");
  1626. if (selected < 0 || selected > 9999) {
  1627. wlogprint("Invalid selection\n");
  1628. goto retry;
  1629. }
  1630. opt_queue = selected;
  1631. goto retry;
  1632. } else if (!strncasecmp(&input, "d", 1)) {
  1633. opt_dynamic ^= true;
  1634. goto retry;
  1635. } else if (!strncasecmp(&input, "l", 1)) {
  1636. want_longpoll ^= true;
  1637. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  1638. restart_longpoll();
  1639. goto retry;
  1640. } else if (!strncasecmp(&input, "i", 1)) {
  1641. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  1642. if (selected < -10 || selected > 10) {
  1643. wlogprint("Invalid selection\n");
  1644. goto retry;
  1645. }
  1646. opt_dynamic = false;
  1647. scan_intensity = selected;
  1648. goto retry;
  1649. } else if (!strncasecmp(&input, "s", 1)) {
  1650. selected = curses_int("Set scantime in seconds");
  1651. if (selected < 0 || selected > 9999) {
  1652. wlogprint("Invalid selection\n");
  1653. goto retry;
  1654. }
  1655. opt_scantime = selected;
  1656. goto retry;
  1657. } else if (!strncasecmp(&input, "r", 1)) {
  1658. selected = curses_int("Retries before failing (-1 infinite)");
  1659. if (selected < -1 || selected > 9999) {
  1660. wlogprint("Invalid selection\n");
  1661. goto retry;
  1662. }
  1663. opt_retries = selected;
  1664. goto retry;
  1665. } else if (!strncasecmp(&input, "p", 1)) {
  1666. selected = curses_int("Seconds to pause before network retries");
  1667. if (selected < 1 || selected > 9999) {
  1668. wlogprint("Invalid selection\n");
  1669. goto retry;
  1670. }
  1671. opt_fail_pause = selected;
  1672. goto retry;
  1673. }
  1674. clear_logwin();
  1675. immedok(logwin, false);
  1676. opt_loginput = false;
  1677. }
  1678. #ifdef HAVE_OPENCL
  1679. static void reinit_device(struct cgpu_info *cgpu);
  1680. static void manage_gpu(void)
  1681. {
  1682. struct thr_info *thr;
  1683. int selected, gpu, i;
  1684. char checkin[40];
  1685. char input;
  1686. if (!opt_g_threads)
  1687. return;
  1688. opt_loginput = true;
  1689. immedok(logwin, true);
  1690. clear_logwin();
  1691. retry:
  1692. for (gpu = 0; gpu < nDevs; gpu++) {
  1693. struct cgpu_info *cgpu = &gpus[gpu];
  1694. wlog("GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  1695. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1696. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1697. cgpu->efficiency, cgpu->utility);
  1698. for (i = 0; i < mining_threads; i++) {
  1699. thr = &thr_info[i];
  1700. if (thr->cgpu != cgpu)
  1701. continue;
  1702. get_datestamp(checkin, &thr->last);
  1703. switch (cgpu->status) {
  1704. case LIFE_WELL:
  1705. wlog("Thread %d: %.1f Mh/s %s ALIVE\n", i,
  1706. thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  1707. break;
  1708. case LIFE_SICK:
  1709. wlog("Thread %d: %.1f Mh/s %s SICK reported in %s\n", i,
  1710. thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled",
  1711. checkin);
  1712. break;
  1713. case LIFE_DEAD:
  1714. wlog("Thread %d: %.1f Mh/s %s DEAD reported in %s\n", i,
  1715. thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled",
  1716. checkin);
  1717. break;
  1718. }
  1719. }
  1720. }
  1721. wlogprint("[E]nable [D]isable [R]estart GPU\n");
  1722. wlogprint("Or press any other key to continue\n");
  1723. input = getch();
  1724. if (!strncasecmp(&input, "e", 1)) {
  1725. selected = curses_int("Select GPU to enable");
  1726. if (selected < 0 || selected >= nDevs) {
  1727. wlogprint("Invalid selection\n");
  1728. goto retry;
  1729. }
  1730. if (gpu_devices[selected]) {
  1731. wlogprint("Device already enabled\n");
  1732. goto retry;
  1733. }
  1734. gpu_devices[selected] = true;
  1735. for (i = 0; i < gpu_threads; i++) {
  1736. if (dev_from_id(i) != selected)
  1737. continue;
  1738. thr = &thr_info[i];
  1739. if (opt_debug)
  1740. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  1741. tq_push(thr->q, &ping);
  1742. }
  1743. } if (!strncasecmp(&input, "d", 1)) {
  1744. selected = curses_int("Select GPU to disable");
  1745. if (selected < 0 || selected >= nDevs) {
  1746. wlogprint("Invalid selection\n");
  1747. goto retry;
  1748. }
  1749. if (!gpu_devices[selected]) {
  1750. wlogprint("Device already disabled\n");
  1751. goto retry;
  1752. }
  1753. gpu_devices[selected] = false;
  1754. } else if (!strncasecmp(&input, "r", 1)) {
  1755. selected = curses_int("Select GPU to attempt to restart");
  1756. if (selected < 0 || selected >= nDevs) {
  1757. wlogprint("Invalid selection\n");
  1758. goto retry;
  1759. }
  1760. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  1761. reinit_device(&gpus[selected]);
  1762. }
  1763. clear_logwin();
  1764. immedok(logwin, false);
  1765. opt_loginput = false;
  1766. }
  1767. #else
  1768. static void manage_gpu(void)
  1769. {
  1770. }
  1771. #endif
  1772. static void *input_thread(void *userdata)
  1773. {
  1774. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1775. if (!curses_active)
  1776. return NULL;
  1777. while (1) {
  1778. char input;
  1779. input = getch();
  1780. if (!strncasecmp(&input, "q", 1)) {
  1781. kill_work();
  1782. return NULL;
  1783. } else if (!strncasecmp(&input, "d", 1))
  1784. display_options();
  1785. else if (!strncasecmp(&input, "p", 1))
  1786. display_pools();
  1787. else if (!strncasecmp(&input, "s", 1))
  1788. set_options();
  1789. else if (!strncasecmp(&input, "g", 1))
  1790. manage_gpu();
  1791. if (opt_realquiet) {
  1792. disable_curses();
  1793. break;
  1794. }
  1795. }
  1796. return NULL;
  1797. }
  1798. static void *workio_thread(void *userdata)
  1799. {
  1800. struct thr_info *mythr = userdata;
  1801. bool ok = true;
  1802. while (ok) {
  1803. struct workio_cmd *wc;
  1804. if (opt_debug)
  1805. applog(LOG_DEBUG, "Popping work to work thread");
  1806. /* wait for workio_cmd sent to us, on our queue */
  1807. wc = tq_pop(mythr->q, NULL);
  1808. if (unlikely(!wc)) {
  1809. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  1810. ok = false;
  1811. break;
  1812. }
  1813. /* process workio_cmd */
  1814. switch (wc->cmd) {
  1815. case WC_GET_WORK:
  1816. ok = workio_get_work(wc);
  1817. break;
  1818. case WC_SUBMIT_WORK:
  1819. ok = workio_submit_work(wc);
  1820. break;
  1821. case WC_DIE:
  1822. default:
  1823. ok = false;
  1824. break;
  1825. }
  1826. }
  1827. tq_freeze(mythr->q);
  1828. return NULL;
  1829. }
  1830. static void thread_reportin(struct thr_info *thr)
  1831. {
  1832. gettimeofday(&thr->last, NULL);
  1833. thr->cgpu->status = LIFE_WELL;
  1834. thr->getwork = false;
  1835. }
  1836. static inline void thread_reportout(struct thr_info *thr)
  1837. {
  1838. thr->getwork = true;
  1839. }
  1840. static void hashmeter(int thr_id, struct timeval *diff,
  1841. unsigned long hashes_done)
  1842. {
  1843. struct timeval temp_tv_end, total_diff;
  1844. double secs;
  1845. double local_secs;
  1846. double utility, efficiency = 0.0;
  1847. static double local_mhashes_done = 0;
  1848. static double rolling = 0;
  1849. double local_mhashes = (double)hashes_done / 1000000.0;
  1850. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1851. bool showlog = false;
  1852. /* Update the last time this thread reported in */
  1853. if (thr_id >= 0)
  1854. gettimeofday(&thr_info[thr_id].last, NULL);
  1855. /* Don't bother calculating anything if we're not displaying it */
  1856. if (opt_realquiet || !opt_log_interval)
  1857. return;
  1858. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  1859. /* So we can call hashmeter from a non worker thread */
  1860. if (thr_id >= 0) {
  1861. struct thr_info *thr = &thr_info[thr_id];
  1862. double thread_rolling = 0.0;
  1863. int i;
  1864. if (opt_debug)
  1865. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  1866. thr_id, hashes_done, hashes_done / secs);
  1867. /* Rolling average for each thread and each device */
  1868. decay_time(&thr->rolling, local_mhashes / secs);
  1869. for (i = 0; i < mining_threads; i++) {
  1870. struct thr_info *th = &thr_info[i];
  1871. if (th->cgpu == cgpu)
  1872. thread_rolling += th->rolling;
  1873. }
  1874. decay_time(&cgpu->rolling, thread_rolling);
  1875. cgpu->total_mhashes += local_mhashes;
  1876. }
  1877. /* Totals are updated by all threads so can race without locking */
  1878. mutex_lock(&hash_lock);
  1879. gettimeofday(&temp_tv_end, NULL);
  1880. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  1881. total_mhashes_done += local_mhashes;
  1882. local_mhashes_done += local_mhashes;
  1883. if (total_diff.tv_sec < opt_log_interval)
  1884. /* Only update the total every opt_log_interval seconds */
  1885. goto out_unlock;
  1886. showlog = true;
  1887. gettimeofday(&total_tv_end, NULL);
  1888. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  1889. decay_time(&rolling, local_mhashes_done / local_secs);
  1890. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  1891. total_secs = (double)total_diff.tv_sec +
  1892. ((double)total_diff.tv_usec / 1000000.0);
  1893. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1894. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  1895. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1896. opt_log_interval, rolling, total_mhashes_done / total_secs,
  1897. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  1898. local_mhashes_done = 0;
  1899. out_unlock:
  1900. mutex_unlock(&hash_lock);
  1901. if (showlog) {
  1902. if (!curses_active) {
  1903. printf("%s \r", statusline);
  1904. fflush(stdout);
  1905. } else
  1906. applog(LOG_INFO, "%s", statusline);
  1907. }
  1908. }
  1909. /* This is overkill, but at least we'll know accurately how much work is
  1910. * queued to prevent ever being left without work */
  1911. static void inc_queued(void)
  1912. {
  1913. mutex_lock(&qd_lock);
  1914. total_queued++;
  1915. mutex_unlock(&qd_lock);
  1916. }
  1917. static void dec_queued(void)
  1918. {
  1919. mutex_lock(&qd_lock);
  1920. if (total_queued > 0)
  1921. total_queued--;
  1922. mutex_unlock(&qd_lock);
  1923. dec_staged(1);
  1924. }
  1925. static int requests_queued(void)
  1926. {
  1927. int ret;
  1928. mutex_lock(&qd_lock);
  1929. ret = total_queued;
  1930. mutex_unlock(&qd_lock);
  1931. return ret;
  1932. }
  1933. static bool pool_active(struct pool *pool)
  1934. {
  1935. bool ret = false;
  1936. json_t *val;
  1937. CURL *curl;
  1938. curl = curl_easy_init();
  1939. if (unlikely(!curl)) {
  1940. applog(LOG_ERR, "CURL initialisation failed");
  1941. return false;
  1942. }
  1943. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  1944. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1945. true, false, pool);
  1946. if (val) {
  1947. struct work *work = make_work();
  1948. bool rc;
  1949. rc = work_decode(json_object_get(val, "result"), work);
  1950. if (rc) {
  1951. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  1952. pool->pool_no, pool->rpc_url);
  1953. work->pool = pool;
  1954. if (opt_debug)
  1955. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  1956. tq_push(thr_info[stage_thr_id].q, work);
  1957. total_getworks++;
  1958. pool->getwork_requested++;
  1959. inc_queued();
  1960. ret = true;
  1961. gettimeofday(&pool->tv_idle, NULL);
  1962. } else {
  1963. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  1964. pool->pool_no, pool->rpc_url);
  1965. free(work);
  1966. }
  1967. json_decref(val);
  1968. } else {
  1969. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  1970. pool->pool_no, pool->rpc_url);
  1971. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  1972. }
  1973. curl_easy_cleanup(curl);
  1974. return ret;
  1975. }
  1976. static void pool_died(struct pool *pool)
  1977. {
  1978. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  1979. gettimeofday(&pool->tv_idle, NULL);
  1980. switch_pools(NULL);
  1981. }
  1982. static void pool_resus(struct pool *pool)
  1983. {
  1984. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  1985. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  1986. switch_pools(NULL);
  1987. }
  1988. static bool queue_request(struct thr_info *thr)
  1989. {
  1990. int maxq = opt_queue + mining_threads;
  1991. struct workio_cmd *wc;
  1992. int rq, rs;
  1993. rq = requests_queued();
  1994. rs = real_staged();
  1995. /* If we've been generating lots of local work we may already have
  1996. * enough in the queue */
  1997. if (rq >= maxq || rs >= maxq)
  1998. return true;
  1999. /* fill out work request message */
  2000. wc = calloc(1, sizeof(*wc));
  2001. if (unlikely(!wc)) {
  2002. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2003. return false;
  2004. }
  2005. wc->cmd = WC_GET_WORK;
  2006. if (thr)
  2007. wc->thr = thr;
  2008. else
  2009. wc->thr = NULL;
  2010. /* If we're queueing work faster than we can stage it, consider the
  2011. * system lagging and allow work to be gathered from another pool if
  2012. * possible */
  2013. if (rq > rs)
  2014. wc->lagging = true;
  2015. if (opt_debug)
  2016. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2017. /* send work request to workio thread */
  2018. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2019. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2020. workio_cmd_free(wc);
  2021. return false;
  2022. }
  2023. inc_queued();
  2024. return true;
  2025. }
  2026. static void discard_work(struct work *work)
  2027. {
  2028. if (!work->clone) {
  2029. if (work->pool)
  2030. work->pool->discarded_work++;
  2031. total_discarded++;
  2032. if (opt_debug)
  2033. applog(LOG_DEBUG, "Discarded cloned work");
  2034. } else if (opt_debug)
  2035. applog(LOG_DEBUG, "Discarded work");
  2036. free(work);
  2037. }
  2038. static void discard_staged(void)
  2039. {
  2040. struct timespec abstime = {};
  2041. struct timeval now;
  2042. struct work *work_heap;
  2043. /* Just in case we fell in a hole and missed a queue filling */
  2044. if (unlikely(!requests_staged()))
  2045. return;
  2046. gettimeofday(&now, NULL);
  2047. abstime.tv_sec = now.tv_sec + 60;
  2048. if (opt_debug)
  2049. applog(LOG_DEBUG, "Popping work to discard staged");
  2050. work_heap = tq_pop(getq, &abstime);
  2051. if (unlikely(!work_heap))
  2052. return;
  2053. discard_work(work_heap);
  2054. dec_queued();
  2055. }
  2056. static void flush_requests(void)
  2057. {
  2058. struct pool *pool = current_pool();
  2059. int i, stale;
  2060. /* We should have one fresh work item staged from the block change. */
  2061. stale = requests_staged() - 1;
  2062. /* Temporarily increase the staged count so that get_work thinks there
  2063. * is work available instead of making threads reuse existing work */
  2064. inc_staged(pool, mining_threads, true);
  2065. for (i = 0; i < stale; i++) {
  2066. /* Queue a whole batch of new requests */
  2067. if (unlikely(!queue_request(NULL))) {
  2068. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  2069. kill_work();
  2070. break;
  2071. }
  2072. /* Pop off the old requests. Cancelling the requests would be better
  2073. * but is tricky */
  2074. discard_staged();
  2075. }
  2076. }
  2077. static inline bool can_roll(struct work *work)
  2078. {
  2079. return (work->pool && !stale_work(work) && work->pool->has_rolltime &&
  2080. work->rolls < 11 && !work->clone);
  2081. }
  2082. static void roll_work(struct work *work)
  2083. {
  2084. uint32_t *work_ntime;
  2085. uint32_t ntime;
  2086. work_ntime = (uint32_t *)(work->data + 68);
  2087. ntime = be32toh(*work_ntime);
  2088. ntime++;
  2089. *work_ntime = htobe32(ntime);
  2090. local_work++;
  2091. work->rolls++;
  2092. work->blk.nonce = 0;
  2093. gettimeofday(&work->tv_staged, NULL);
  2094. if (opt_debug)
  2095. applog(LOG_DEBUG, "Successfully rolled work");
  2096. }
  2097. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  2098. * giving it to will not finish scanning it. We keep the master copy to be
  2099. * recycled more rapidly and discard the clone to avoid repeating work */
  2100. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  2101. {
  2102. uint64_t hash_inc;
  2103. if (hash_div < 3 || work->clone)
  2104. return false;
  2105. hash_inc = MAXTHREADS / hash_div * 2;
  2106. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  2107. /* Don't keep handing it out if it's getting old, but try to
  2108. * roll it instead */
  2109. if ((now->tv_sec - work->tv_staged.tv_sec) > opt_scantime) {
  2110. if (!can_roll(work))
  2111. return false;
  2112. else {
  2113. roll_work(work);
  2114. return true;
  2115. }
  2116. }
  2117. /* Okay we can divide it up */
  2118. work->blk.nonce += hash_inc;
  2119. work->cloned = true;
  2120. local_work++;
  2121. if (opt_debug)
  2122. applog(LOG_DEBUG, "Successfully divided work");
  2123. return true;
  2124. }
  2125. return false;
  2126. }
  2127. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2128. const int thr_id, uint32_t hash_div)
  2129. {
  2130. struct timespec abstime = {};
  2131. struct timeval now;
  2132. struct work *work_heap;
  2133. struct pool *pool;
  2134. bool ret = false;
  2135. int failures = 0;
  2136. /* Tell the watchdog thread this thread is waiting on getwork and
  2137. * should not be restarted */
  2138. thread_reportout(thr);
  2139. retry:
  2140. pool = current_pool();
  2141. if (unlikely(!requested && !queue_request(thr))) {
  2142. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2143. goto out;
  2144. }
  2145. requested = false;
  2146. if (!requests_staged() && can_roll(work)) {
  2147. /* Only print this message once each time we shift to localgen */
  2148. if (!pool_tset(pool, &pool->idle)) {
  2149. applog(LOG_WARNING, "Pool %d not providing work fast enough, generating work locally",
  2150. pool->pool_no);
  2151. pool->localgen_occasions++;
  2152. total_lo++;
  2153. gettimeofday(&pool->tv_idle, NULL);
  2154. } else {
  2155. struct timeval tv_now, diff;
  2156. gettimeofday(&tv_now, NULL);
  2157. timeval_subtract(&diff, &tv_now, &pool->tv_idle);
  2158. /* Attempt to switch pools if this one has been unresponsive for >half
  2159. * a block's duration */
  2160. if (diff.tv_sec > 300) {
  2161. pool_died(pool);
  2162. goto retry;
  2163. }
  2164. }
  2165. roll_work(work);
  2166. ret = true;
  2167. goto out;
  2168. }
  2169. gettimeofday(&now, NULL);
  2170. abstime.tv_sec = now.tv_sec + 60;
  2171. if (opt_debug)
  2172. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2173. /* wait for 1st response, or get cached response */
  2174. work_heap = tq_pop(getq, &abstime);
  2175. if (unlikely(!work_heap)) {
  2176. /* Attempt to switch pools if this one has mandatory work that
  2177. * has timed out or does not support rolltime */
  2178. pool->localgen_occasions++;
  2179. total_lo++;
  2180. pool_died(pool);
  2181. goto retry;
  2182. }
  2183. if (stale_work(work_heap)) {
  2184. dec_queued();
  2185. discard_work(work_heap);
  2186. goto retry;
  2187. }
  2188. pool = work_heap->pool;
  2189. /* If we make it here we have succeeded in getting fresh work */
  2190. if (pool_tclear(pool, &pool->idle))
  2191. pool_resus(pool);
  2192. memcpy(work, work_heap, sizeof(*work));
  2193. /* Copy the res nonce back so we know to start at a higher baseline
  2194. * should we divide the same work up again. Make the work we're
  2195. * handing out be clone */
  2196. if (divide_work(&now, work_heap, hash_div)) {
  2197. if (opt_debug)
  2198. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2199. tq_push_head(getq, work_heap);
  2200. work->clone = true;
  2201. } else {
  2202. dec_queued();
  2203. free(work_heap);
  2204. }
  2205. ret = true;
  2206. out:
  2207. if (unlikely(ret == false)) {
  2208. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2209. applog(LOG_ERR, "Failed %d times to get_work");
  2210. return ret;
  2211. }
  2212. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  2213. sleep(opt_fail_pause);
  2214. goto retry;
  2215. }
  2216. work->thr_id = thr_id;
  2217. thread_reportin(thr);
  2218. return ret;
  2219. }
  2220. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2221. {
  2222. struct workio_cmd *wc;
  2223. /* fill out work request message */
  2224. wc = calloc(1, sizeof(*wc));
  2225. if (unlikely(!wc)) {
  2226. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2227. return false;
  2228. }
  2229. wc->u.work = make_work();
  2230. wc->cmd = WC_SUBMIT_WORK;
  2231. wc->thr = thr;
  2232. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2233. if (opt_debug)
  2234. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2235. /* send solution to workio thread */
  2236. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2237. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2238. goto err_out;
  2239. }
  2240. return true;
  2241. err_out:
  2242. workio_cmd_free(wc);
  2243. return false;
  2244. }
  2245. struct swa {
  2246. struct thr_info *thr;
  2247. const struct work *work_in;
  2248. };
  2249. static void *swasync_thread(void *userdata)
  2250. {
  2251. struct swa *swa = (struct swa *)userdata;
  2252. /* Return value ignored */
  2253. submit_work_sync(swa->thr, swa->work_in);
  2254. free(swa);
  2255. return NULL;
  2256. }
  2257. static bool submit_work_async(struct thr_info *thr, const struct work *work_in)
  2258. {
  2259. pthread_t sw_thread;
  2260. struct swa *swa;
  2261. swa = malloc(sizeof(struct swa));
  2262. if (unlikely(!swa)) {
  2263. applog(LOG_ERR, "Failed to malloc swa in submit_work_async");
  2264. return false;
  2265. }
  2266. swa->thr = thr;
  2267. swa->work_in = work_in;
  2268. if (unlikely(pthread_create(&sw_thread, NULL, swasync_thread, (void *)swa))) {
  2269. applog(LOG_ERR, "Failed to create swasync_thread");
  2270. return false;
  2271. }
  2272. return true;
  2273. }
  2274. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2275. {
  2276. work->data[64+12+0] = (nonce>>0) & 0xff;
  2277. work->data[64+12+1] = (nonce>>8) & 0xff;
  2278. work->data[64+12+2] = (nonce>>16) & 0xff;
  2279. work->data[64+12+3] = (nonce>>24) & 0xff;
  2280. /* Do one last check before attempting to submit the work */
  2281. if (!fulltest(work->data + 64, work->target))
  2282. return true;
  2283. return submit_work_sync(thr, work);
  2284. }
  2285. static void *miner_thread(void *userdata)
  2286. {
  2287. struct work *work = make_work();
  2288. struct thr_info *mythr = userdata;
  2289. const int thr_id = mythr->id;
  2290. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  2291. unsigned long hashes_done = max_nonce;
  2292. bool needs_work = true;
  2293. /* Try to cycle approximately 5 times before each log update */
  2294. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2295. int request_interval;
  2296. bool requested = false;
  2297. uint32_t hash_div = 1;
  2298. double hash_divfloat = 1.0;
  2299. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2300. /* Request the next work item just before the end of the scantime. We
  2301. * don't want the work lying around too long since the CPU will always
  2302. * spend the full scantime */
  2303. request_interval = opt_scantime - 5;
  2304. if (request_interval < 1)
  2305. request_interval = 1;
  2306. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  2307. * and if that fails, then SCHED_BATCH. No need for this to be an
  2308. * error if it fails */
  2309. setpriority(PRIO_PROCESS, 0, 19);
  2310. drop_policy();
  2311. /* Cpu affinity only makes sense if the number of threads is a multiple
  2312. * of the number of CPUs */
  2313. if (!(opt_n_threads % num_processors))
  2314. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  2315. /* Invalidate pool so it fails can_roll() test */
  2316. work->pool = NULL;
  2317. while (1) {
  2318. struct timeval tv_workstart, tv_start, tv_end, diff;
  2319. uint64_t max64;
  2320. bool rc;
  2321. if (needs_work) {
  2322. gettimeofday(&tv_workstart, NULL);
  2323. /* obtain new work from internal workio thread */
  2324. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2325. applog(LOG_ERR, "work retrieval failed, exiting "
  2326. "mining thread %d", thr_id);
  2327. goto out;
  2328. }
  2329. needs_work = requested = false;
  2330. total_hashes = 0;
  2331. max_nonce = work->blk.nonce + hashes_done;
  2332. }
  2333. hashes_done = 0;
  2334. gettimeofday(&tv_start, NULL);
  2335. /* scan nonces for a proof-of-work hash */
  2336. switch (opt_algo) {
  2337. case ALGO_C:
  2338. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  2339. work->hash1, work->hash, work->target,
  2340. max_nonce, &hashes_done,
  2341. work->blk.nonce);
  2342. break;
  2343. #ifdef WANT_X8664_SSE2
  2344. case ALGO_SSE2_64: {
  2345. unsigned int rc5 =
  2346. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  2347. work->hash1, work->hash,
  2348. work->target,
  2349. max_nonce, &hashes_done,
  2350. work->blk.nonce);
  2351. rc = (rc5 == -1) ? false : true;
  2352. }
  2353. break;
  2354. #endif
  2355. #ifdef WANT_X8664_SSE4
  2356. case ALGO_SSE4_64: {
  2357. unsigned int rc5 =
  2358. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  2359. work->hash1, work->hash,
  2360. work->target,
  2361. max_nonce, &hashes_done,
  2362. work->blk.nonce);
  2363. rc = (rc5 == -1) ? false : true;
  2364. }
  2365. break;
  2366. #endif
  2367. #ifdef WANT_SSE2_4WAY
  2368. case ALGO_4WAY: {
  2369. unsigned int rc4 =
  2370. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  2371. work->hash1, work->hash,
  2372. work->target,
  2373. max_nonce, &hashes_done,
  2374. work->blk.nonce);
  2375. rc = (rc4 == -1) ? false : true;
  2376. }
  2377. break;
  2378. #endif
  2379. #ifdef WANT_VIA_PADLOCK
  2380. case ALGO_VIA:
  2381. rc = scanhash_via(thr_id, work->data, work->target,
  2382. max_nonce, &hashes_done,
  2383. work->blk.nonce);
  2384. break;
  2385. #endif
  2386. case ALGO_CRYPTOPP:
  2387. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  2388. work->hash1, work->hash, work->target,
  2389. max_nonce, &hashes_done,
  2390. work->blk.nonce);
  2391. break;
  2392. #ifdef WANT_CRYPTOPP_ASM32
  2393. case ALGO_CRYPTOPP_ASM32:
  2394. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  2395. work->hash1, work->hash, work->target,
  2396. max_nonce, &hashes_done,
  2397. work->blk.nonce);
  2398. break;
  2399. #endif
  2400. default:
  2401. /* should never happen */
  2402. goto out;
  2403. }
  2404. /* record scanhash elapsed time */
  2405. gettimeofday(&tv_end, NULL);
  2406. timeval_subtract(&diff, &tv_end, &tv_start);
  2407. hashes_done -= work->blk.nonce;
  2408. hashmeter(thr_id, &diff, hashes_done);
  2409. total_hashes += hashes_done;
  2410. work->blk.nonce += hashes_done;
  2411. /* adjust max_nonce to meet target cycle time */
  2412. if (diff.tv_usec > 500000)
  2413. diff.tv_sec++;
  2414. if (diff.tv_sec && diff.tv_sec != cycle) {
  2415. max64 = work->blk.nonce +
  2416. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  2417. } else if (!diff.tv_sec)
  2418. max64 = work->blk.nonce + (hashes_done * 2);
  2419. else
  2420. max64 = work->blk.nonce + hashes_done;
  2421. if (max64 > 0xfffffffaULL)
  2422. max64 = 0xfffffffaULL;
  2423. max_nonce = max64;
  2424. /* if nonce found, submit work */
  2425. if (unlikely(rc)) {
  2426. if (opt_debug)
  2427. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  2428. if (unlikely(!submit_work_async(mythr, work))) {
  2429. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  2430. break;
  2431. }
  2432. work->blk.nonce += 4;
  2433. }
  2434. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2435. if (!requested && (diff.tv_sec >= request_interval)) {
  2436. thread_reportout(mythr);
  2437. if (unlikely(!queue_request(mythr))) {
  2438. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2439. goto out;
  2440. }
  2441. thread_reportin(mythr);
  2442. requested = true;
  2443. }
  2444. if (diff.tv_sec > opt_scantime) {
  2445. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  2446. hash_div = hash_divfloat;
  2447. needs_work = true;
  2448. } else if (work_restart[thr_id].restart || stale_work(work) ||
  2449. work->blk.nonce >= MAXTHREADS - hashes_done)
  2450. needs_work = true;
  2451. }
  2452. out:
  2453. thread_reportin(mythr);
  2454. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2455. tq_freeze(mythr->q);
  2456. return NULL;
  2457. }
  2458. enum {
  2459. STAT_SLEEP_INTERVAL = 1,
  2460. STAT_CTR_INTERVAL = 10000000,
  2461. FAILURE_INTERVAL = 30,
  2462. };
  2463. #ifdef HAVE_OPENCL
  2464. static _clState *clStates[16];
  2465. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  2466. {
  2467. cl_kernel *kernel = &clState->kernel;
  2468. cl_int status = 0;
  2469. int num = 0;
  2470. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2471. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2472. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2473. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2474. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2475. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2476. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2477. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2478. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2479. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2480. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  2481. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2482. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2483. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2484. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2485. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  2486. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  2487. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  2488. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  2489. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  2490. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  2491. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  2492. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  2493. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2494. (void *)&clState->outputBuffer);
  2495. return status;
  2496. }
  2497. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  2498. {
  2499. cl_kernel *kernel = &clState->kernel;
  2500. cl_int status = 0;
  2501. int num = 0;
  2502. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  2503. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  2504. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  2505. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  2506. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  2507. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  2508. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  2509. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  2510. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  2511. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  2512. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->C1addK5);
  2513. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->D1A);
  2514. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  2515. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  2516. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  2517. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  2518. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2A);
  2519. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  2520. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  2521. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17_2);
  2522. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4addT1);
  2523. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1substate0);
  2524. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  2525. (void *)&clState->outputBuffer);
  2526. return status;
  2527. }
  2528. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  2529. unsigned int *hashes, size_t *globalThreads,
  2530. unsigned int minthreads)
  2531. {
  2532. *threads = 1 << (15 + scan_intensity);
  2533. if (*threads < minthreads)
  2534. *threads = minthreads;
  2535. *globalThreads = *threads;
  2536. *hashes = *threads * vectors;
  2537. }
  2538. static void *gpuminer_thread(void *userdata)
  2539. {
  2540. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  2541. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2542. struct timeval tv_start, tv_end, diff, tv_workstart;
  2543. struct thr_info *mythr = userdata;
  2544. const int thr_id = mythr->id;
  2545. uint32_t *res, *blank_res;
  2546. double gpu_ms_average = 7;
  2547. int gpu = dev_from_id(thr_id);
  2548. size_t globalThreads[1];
  2549. size_t localThreads[1];
  2550. cl_int status;
  2551. _clState *clState = clStates[thr_id];
  2552. const cl_kernel *kernel = &clState->kernel;
  2553. struct work *work = make_work();
  2554. unsigned int threads;
  2555. unsigned const int vectors = clState->preferred_vwidth;
  2556. unsigned int hashes;
  2557. unsigned int hashes_done = 0;
  2558. /* Request the next work item at 2/3 of the scantime */
  2559. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2560. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  2561. bool requested = false;
  2562. uint32_t total_hashes = 0, hash_div = 1;
  2563. switch (chosen_kernel) {
  2564. case KL_POCLBM:
  2565. queue_kernel_parameters = &queue_poclbm_kernel;
  2566. break;
  2567. case KL_PHATK:
  2568. default:
  2569. queue_kernel_parameters = &queue_phatk_kernel;
  2570. break;
  2571. }
  2572. if (opt_dynamic) {
  2573. /* Minimise impact on desktop if we want dynamic mode */
  2574. setpriority(PRIO_PROCESS, 0, 19);
  2575. drop_policy();
  2576. }
  2577. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2578. res = calloc(BUFFERSIZE, 1);
  2579. blank_res = calloc(BUFFERSIZE, 1);
  2580. if (!res || !blank_res) {
  2581. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  2582. goto out;
  2583. }
  2584. gettimeofday(&tv_start, NULL);
  2585. localThreads[0] = clState->work_size;
  2586. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  2587. localThreads[0]);
  2588. diff.tv_sec = 0;
  2589. gettimeofday(&tv_end, NULL);
  2590. work->pool = NULL;
  2591. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  2592. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2593. if (unlikely(status != CL_SUCCESS))
  2594. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2595. mythr->cgpu->status = LIFE_WELL;
  2596. if (opt_debug)
  2597. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  2598. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  2599. gettimeofday(&tv_workstart, NULL);
  2600. /* obtain new work from internal workio thread */
  2601. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2602. applog(LOG_ERR, "work retrieval failed, exiting "
  2603. "gpu mining thread %d", thr_id);
  2604. goto out;
  2605. }
  2606. requested = false;
  2607. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2608. work->blk.nonce = 0;
  2609. while (1) {
  2610. struct timeval tv_gpustart, tv_gpuend;
  2611. suseconds_t gpu_us;
  2612. gettimeofday(&tv_gpustart, NULL);
  2613. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  2614. /* This finish flushes the readbuffer set with CL_FALSE later */
  2615. clFinish(clState->commandQueue);
  2616. gettimeofday(&tv_gpuend, NULL);
  2617. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  2618. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  2619. decay_time(&gpu_ms_average, gpu_us / 1000);
  2620. if (opt_dynamic) {
  2621. /* Try to not let the GPU be out for longer than 6ms, but
  2622. * increase intensity when the system is idle, unless
  2623. * dynamic is disabled. */
  2624. if (gpu_ms_average > 7) {
  2625. if (scan_intensity > -10)
  2626. scan_intensity--;
  2627. } else if (gpu_ms_average < 3) {
  2628. if (scan_intensity < 10)
  2629. scan_intensity++;
  2630. }
  2631. }
  2632. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  2633. if (diff.tv_sec > opt_scantime ||
  2634. work->blk.nonce >= MAXTHREADS - hashes ||
  2635. work_restart[thr_id].restart ||
  2636. stale_work(work)) {
  2637. /* Ignore any reads since we're getting new work and queue a clean buffer */
  2638. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2639. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2640. if (unlikely(status != CL_SUCCESS))
  2641. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2642. memset(res, 0, BUFFERSIZE);
  2643. gettimeofday(&tv_workstart, NULL);
  2644. if (opt_debug)
  2645. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  2646. /* obtain new work from internal workio thread */
  2647. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2648. applog(LOG_ERR, "work retrieval failed, exiting "
  2649. "gpu mining thread %d", thr_id);
  2650. goto out;
  2651. }
  2652. requested = false;
  2653. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  2654. work_restart[thr_id].restart = 0;
  2655. /* Flushes the writebuffer set with CL_FALSE above */
  2656. clFinish(clState->commandQueue);
  2657. }
  2658. status = queue_kernel_parameters(clState, &work->blk);
  2659. if (unlikely(status != CL_SUCCESS))
  2660. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  2661. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  2662. if (res[MAXBUFFERS]) {
  2663. /* Clear the buffer again */
  2664. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2665. BUFFERSIZE, blank_res, 0, NULL, NULL);
  2666. if (unlikely(status != CL_SUCCESS))
  2667. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  2668. if (opt_debug)
  2669. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  2670. postcalc_hash_async(mythr, work, res);
  2671. memset(res, 0, BUFFERSIZE);
  2672. clFinish(clState->commandQueue);
  2673. }
  2674. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  2675. globalThreads, localThreads, 0, NULL, NULL);
  2676. if (unlikely(status != CL_SUCCESS))
  2677. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  2678. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  2679. BUFFERSIZE, res, 0, NULL, NULL);
  2680. if (unlikely(status != CL_SUCCESS))
  2681. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  2682. gettimeofday(&tv_end, NULL);
  2683. timeval_subtract(&diff, &tv_end, &tv_start);
  2684. hashes_done += hashes;
  2685. total_hashes += hashes;
  2686. work->blk.nonce += hashes;
  2687. if (diff.tv_sec >= cycle) {
  2688. hashmeter(thr_id, &diff, hashes_done);
  2689. gettimeofday(&tv_start, NULL);
  2690. hashes_done = 0;
  2691. }
  2692. timeval_subtract(&diff, &tv_end, &tv_workstart);
  2693. if (!requested) {
  2694. #if 0
  2695. if (diff.tv_sec > request_interval)
  2696. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  2697. #endif
  2698. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  2699. thread_reportout(mythr);
  2700. if (unlikely(!queue_request(mythr))) {
  2701. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  2702. goto out;
  2703. }
  2704. thread_reportin(mythr);
  2705. requested = true;
  2706. }
  2707. }
  2708. if (unlikely(!gpu_devices[gpu])) {
  2709. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  2710. mythr->rolling = mythr->cgpu->rolling = 0;
  2711. if (opt_debug)
  2712. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  2713. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  2714. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  2715. }
  2716. }
  2717. out:
  2718. thread_reportin(mythr);
  2719. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2720. tq_freeze(mythr->q);
  2721. return NULL;
  2722. }
  2723. #endif /* HAVE_OPENCL */
  2724. static void restart_threads(void)
  2725. {
  2726. int i;
  2727. if (block_changed == BLOCK_DETECT)
  2728. block_changed = BLOCK_NONE;
  2729. /* Discard old queued requests and get new ones */
  2730. flush_requests();
  2731. for (i = 0; i < mining_threads; i++)
  2732. work_restart[i].restart = 1;
  2733. }
  2734. /* Stage another work item from the work returned in a longpoll */
  2735. static void convert_to_work(json_t *val)
  2736. {
  2737. struct work *work;
  2738. bool rc;
  2739. work = make_work();
  2740. rc= work_decode(json_object_get(val, "result"), work);
  2741. if (unlikely(!rc)) {
  2742. applog(LOG_ERR, "Could not convert longpoll data to work");
  2743. return;
  2744. }
  2745. work->pool = current_pool();
  2746. if (opt_debug)
  2747. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  2748. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  2749. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  2750. else if (opt_debug)
  2751. applog(LOG_DEBUG, "Converted longpoll data to work");
  2752. }
  2753. static void *longpoll_thread(void *userdata)
  2754. {
  2755. struct thr_info *mythr = userdata;
  2756. CURL *curl = NULL;
  2757. char *copy_start, *hdr_path, *lp_url = NULL;
  2758. bool need_slash = false;
  2759. int failures = 0;
  2760. struct pool *pool = current_pool();
  2761. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2762. curl = curl_easy_init();
  2763. if (unlikely(!curl)) {
  2764. applog(LOG_ERR, "CURL initialisation failed");
  2765. goto out;
  2766. }
  2767. if (opt_debug)
  2768. applog(LOG_DEBUG, "Popping hdr path in longpoll thread");
  2769. hdr_path = tq_pop(mythr->q, NULL);
  2770. if (!hdr_path) {
  2771. applog(LOG_WARNING, "No long-poll found on this server");
  2772. goto out;
  2773. }
  2774. /* full URL */
  2775. if (strstr(hdr_path, "://")) {
  2776. lp_url = hdr_path;
  2777. hdr_path = NULL;
  2778. }
  2779. /* absolute path, on current server */
  2780. else {
  2781. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2782. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  2783. need_slash = true;
  2784. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  2785. if (!lp_url)
  2786. goto out;
  2787. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  2788. }
  2789. free(hdr_path);
  2790. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  2791. while (1) {
  2792. struct timeval start, end;
  2793. json_t *val;
  2794. gettimeofday(&start, NULL);
  2795. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  2796. false, true, pool);
  2797. if (likely(val)) {
  2798. /* Keep track of who ordered a restart_threads to make
  2799. * sure it's only done once per new block */
  2800. if (block_changed != BLOCK_DETECT) {
  2801. block_changed = BLOCK_LP;
  2802. new_blocks++;
  2803. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  2804. restart_threads();
  2805. } else {
  2806. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  2807. block_changed = BLOCK_NONE;
  2808. }
  2809. convert_to_work(val);
  2810. failures = 0;
  2811. json_decref(val);
  2812. } else {
  2813. /* Some pools regularly drop the longpoll request so
  2814. * only see this as longpoll failure if it happens
  2815. * immediately and just restart it the rest of the
  2816. * time. */
  2817. gettimeofday(&end, NULL);
  2818. if (end.tv_sec - start.tv_sec > 30)
  2819. continue;
  2820. if (failures++ < 10) {
  2821. sleep(30);
  2822. applog(LOG_WARNING,
  2823. "longpoll failed, sleeping for 30s");
  2824. } else {
  2825. applog(LOG_ERR,
  2826. "longpoll failed, ending thread");
  2827. goto out;
  2828. }
  2829. }
  2830. }
  2831. out:
  2832. free(lp_url);
  2833. tq_freeze(mythr->q);
  2834. if (curl)
  2835. curl_easy_cleanup(curl);
  2836. return NULL;
  2837. }
  2838. static void stop_longpoll(void)
  2839. {
  2840. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2841. tq_freeze(thr->q);
  2842. pthread_cancel(*thr->pth);
  2843. have_longpoll = false;
  2844. }
  2845. static void start_longpoll(void)
  2846. {
  2847. struct thr_info *thr = &thr_info[longpoll_thr_id];
  2848. tq_thaw(thr->q);
  2849. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  2850. quit(1, "longpoll thread create failed");
  2851. pthread_detach(*thr->pth);
  2852. }
  2853. static void restart_longpoll(void)
  2854. {
  2855. stop_longpoll();
  2856. if (want_longpoll)
  2857. start_longpoll();
  2858. }
  2859. static void *reinit_cpu(void *userdata)
  2860. {
  2861. #if 0
  2862. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  2863. int cpu = cgpu->cpu_gpu;
  2864. long thr_id = ....(long)userdata;
  2865. struct thr_info *thr = &thr_info[thr_id];
  2866. int cpu = dev_from_id(thr_id);
  2867. cpus[cpu].alive = false;
  2868. thr->rolling = thr->cgpu->rolling = 0;
  2869. tq_freeze(thr->q);
  2870. if (!pthread_cancel(*thr->pth))
  2871. pthread_join(*thr->pth, NULL);
  2872. free(thr->q);
  2873. thr->q = tq_new();
  2874. if (!thr->q)
  2875. quit(1, "Failed to tq_new in reinit_cputhread");
  2876. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  2877. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  2878. applog(LOG_ERR, "thread %d create failed", thr_id);
  2879. return NULL;
  2880. }
  2881. tq_push(thr->q, &ping);
  2882. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  2883. #endif
  2884. return NULL;
  2885. }
  2886. #ifdef HAVE_OPENCL
  2887. static void *reinit_gpu(void *userdata)
  2888. {
  2889. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  2890. int gpu = cgpu->cpu_gpu;
  2891. struct thr_info *thr;
  2892. int thr_id;
  2893. _clState *clState;
  2894. /* Send threads message to stop */
  2895. gpu_devices[gpu] = false;
  2896. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  2897. if (dev_from_id(thr_id) != gpu)
  2898. continue;
  2899. thr = &thr_info[thr_id];
  2900. thr->rolling = thr->cgpu->rolling = 0;
  2901. if (!pthread_cancel(*thr->pth)) {
  2902. applog(LOG_WARNING, "Thread still exists, killing it off");
  2903. } else
  2904. applog(LOG_WARNING, "Thread no longer exists!");
  2905. /* Lose this ram cause we may get stuck here! */
  2906. //tq_freeze(thr->q);
  2907. thr->q = tq_new();
  2908. if (!thr->q)
  2909. quit(1, "Failed to tq_new in reinit_gpu");
  2910. /* Create a new clstate */
  2911. applog(LOG_WARNING, "Attempting to create a new clState");
  2912. clState = initCQ(clStates[thr_id], gpu);
  2913. /* Lose this ram cause we may dereference in the dying thread! */
  2914. //free(clState);
  2915. applog(LOG_WARNING, "Command successful, attempting to create new thread");
  2916. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  2917. applog(LOG_ERR, "thread %d create failed", thr_id);
  2918. return NULL;
  2919. }
  2920. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  2921. }
  2922. /* Try to re-enable it */
  2923. gpu_devices[gpu] = true;
  2924. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  2925. thr = &thr_info[thr_id];
  2926. if (dev_from_id(thr_id) == gpu)
  2927. tq_push(thr->q, &ping);
  2928. }
  2929. return NULL;
  2930. }
  2931. #else
  2932. static void *reinit_gpu(void *userdata)
  2933. {
  2934. }
  2935. #endif
  2936. static void reinit_device(struct cgpu_info *cgpu)
  2937. {
  2938. pthread_t resus_thread;
  2939. void *reinit;
  2940. if (cgpu->is_gpu)
  2941. reinit = reinit_gpu;
  2942. else
  2943. reinit = reinit_cpu;
  2944. if (unlikely(pthread_create(&resus_thread, NULL, reinit, (void *)cgpu)))
  2945. applog(LOG_ERR, "Failed to create reinit thread");
  2946. }
  2947. /* Determine which are the first threads belonging to a device and if they're
  2948. * active */
  2949. static bool active_device(int thr_id)
  2950. {
  2951. if (thr_id < gpu_threads) {
  2952. if (thr_id >= total_devices)
  2953. return false;
  2954. if (!gpu_devices[dev_from_id(thr_id)])
  2955. return false;
  2956. } else if (thr_id > gpu_threads + num_processors)
  2957. return false;
  2958. return true;
  2959. }
  2960. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  2961. * the screen at regular intervals, and restarts threads if they appear to have
  2962. * died. */
  2963. static void *watchdog_thread(void *userdata)
  2964. {
  2965. const unsigned int interval = opt_log_interval / 2 ? : 1;
  2966. static struct timeval rotate_tv;
  2967. struct timeval zero_tv;
  2968. bool statwin = false;
  2969. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2970. memset(&zero_tv, 0, sizeof(struct timeval));
  2971. gettimeofday(&rotate_tv, NULL);
  2972. while (1) {
  2973. int i;
  2974. struct timeval now;
  2975. sleep(interval);
  2976. if (requests_queued() < opt_queue)
  2977. queue_request(NULL);
  2978. hashmeter(-1, &zero_tv, 0);
  2979. if (curses_active) {
  2980. statwin ^= true;
  2981. mutex_lock(&curses_lock);
  2982. for (i = 0; i < mining_threads; i++)
  2983. curses_print_status(i);
  2984. if (statwin)
  2985. redrawwin(statuswin);
  2986. else {
  2987. check_logwinsize();
  2988. redrawwin(logwin);
  2989. }
  2990. mutex_unlock(&curses_lock);
  2991. }
  2992. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  2993. restart_threads();
  2994. work_restart[watchdog_thr_id].restart = 0;
  2995. }
  2996. gettimeofday(&now, NULL);
  2997. for (i = 0; i < total_pools; i++) {
  2998. struct pool *pool = pools[i];
  2999. if (!pool->enabled)
  3000. continue;
  3001. /* Test pool is idle once every minute */
  3002. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3003. gettimeofday(&pool->tv_idle, NULL);
  3004. if (pool_active(pool) && pool_tclear(pool, &pool->idle))
  3005. pool_resus(pool);
  3006. }
  3007. }
  3008. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3009. gettimeofday(&rotate_tv, NULL);
  3010. switch_pools(NULL);
  3011. }
  3012. //for (i = 0; i < mining_threads; i++) {
  3013. for (i = 0; i < gpu_threads; i++) {
  3014. struct thr_info *thr = &thr_info[i];
  3015. int gpu = thr->cgpu->cpu_gpu;
  3016. /* Thread is waiting on getwork or disabled */
  3017. if (thr->getwork || !gpu_devices[gpu])
  3018. continue;
  3019. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3020. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  3021. gpus[gpu].status = LIFE_WELL;
  3022. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3023. thr->rolling = thr->cgpu->rolling = 0;
  3024. gpus[gpu].status = LIFE_SICK;
  3025. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3026. /* Sent it a ping, it might respond */
  3027. tq_push(thr->q, &ping);
  3028. } else if (now.tv_sec - thr->last.tv_sec > 300 && gpus[i].status == LIFE_SICK) {
  3029. gpus[gpu].status = LIFE_DEAD;
  3030. applog(LOG_ERR, "Thread %d idle for more than 5 minutes, GPU %d declared DEAD!", i, gpu);
  3031. applog(LOG_ERR, "Attempting to restart GPU");
  3032. reinit_device(thr->cgpu);
  3033. break;
  3034. }
  3035. }
  3036. }
  3037. return NULL;
  3038. }
  3039. static void print_summary(void)
  3040. {
  3041. struct timeval diff;
  3042. int hours, mins, secs, i;
  3043. double utility, efficiency = 0.0;
  3044. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3045. hours = diff.tv_sec / 3600;
  3046. mins = (diff.tv_sec % 3600) / 60;
  3047. secs = diff.tv_sec % 60;
  3048. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3049. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3050. printf("\nSummary of runtime statistics:\n\n");
  3051. printf("Started at %s\n", datestamp);
  3052. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  3053. if (total_secs)
  3054. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  3055. printf("Queued work requests: %d\n", total_getworks);
  3056. printf("Share submissions: %d\n", total_accepted + total_rejected);
  3057. printf("Accepted shares: %d\n", total_accepted);
  3058. printf("Rejected shares: %d\n", total_rejected);
  3059. if (total_accepted || total_rejected)
  3060. printf("Reject ratio: %.1f\n", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3061. printf("Hardware errors: %d\n", hw_errors);
  3062. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3063. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  3064. printf("Discarded work due to new blocks: %d\n", total_discarded);
  3065. printf("Stale submissions discarded due to new blocks: %d\n", total_stale);
  3066. printf("Unable to get work from server occasions: %d\n", total_lo);
  3067. printf("Work items generated locally: %d\n", local_work);
  3068. printf("Submitting work remotely delay occasions: %d\n", total_ro);
  3069. printf("New blocks detected on network: %d\n\n", new_blocks);
  3070. if (total_pools > 1) {
  3071. for (i = 0; i < total_pools; i++) {
  3072. struct pool *pool = pools[i];
  3073. printf("Pool: %s\n", pool->rpc_url);
  3074. printf(" Queued work requests: %d\n", pool->getwork_requested);
  3075. printf(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3076. printf(" Accepted shares: %d\n", pool->accepted);
  3077. printf(" Rejected shares: %d\n", pool->rejected);
  3078. if (pool->accepted || pool->rejected)
  3079. printf(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3080. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3081. printf(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3082. printf(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3083. printf(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3084. printf(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  3085. printf(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3086. }
  3087. }
  3088. printf("Summary of per device statistics:\n\n");
  3089. for (i = 0; i < mining_threads; i++) {
  3090. if (active_device(i))
  3091. print_status(i);
  3092. }
  3093. printf("\n");
  3094. }
  3095. void quit(int status, const char *format, ...)
  3096. {
  3097. va_list ap;
  3098. disable_curses();
  3099. if (format) {
  3100. va_start(ap, format);
  3101. vfprintf(stderr, format, ap);
  3102. va_end(ap);
  3103. }
  3104. fprintf(stderr, "\n");
  3105. fflush(stderr);
  3106. exit(status);
  3107. }
  3108. static char *curses_input(const char *query)
  3109. {
  3110. char *input;
  3111. echo();
  3112. input = malloc(255);
  3113. if (!input)
  3114. quit(1, "Failed to malloc input");
  3115. leaveok(logwin, false);
  3116. wlogprint("%s: ", query);
  3117. wgetnstr(logwin, input, 255);
  3118. leaveok(logwin, true);
  3119. noecho();
  3120. return input;
  3121. }
  3122. static bool input_pool(bool live)
  3123. {
  3124. char *url = NULL, *user = NULL, *pass = NULL;
  3125. struct pool *pool = NULL;
  3126. bool ret = false;
  3127. immedok(logwin, true);
  3128. if (total_pools == MAX_POOLS) {
  3129. wlogprint("Reached maximum number of pools.\n");
  3130. goto out;
  3131. }
  3132. wlogprint("Input server details.\n");
  3133. url = curses_input("URL");
  3134. if (!url)
  3135. goto out;
  3136. if (strncmp(url, "http://", 7) &&
  3137. strncmp(url, "https://", 8)) {
  3138. char *httpinput;
  3139. httpinput = malloc(255);
  3140. if (!httpinput)
  3141. quit(1, "Failed to malloc httpinput");
  3142. strcpy(httpinput, "http://");
  3143. strncat(httpinput, url, 248);
  3144. free(url);
  3145. url = httpinput;
  3146. }
  3147. user = curses_input("Username");
  3148. if (!user)
  3149. goto out;
  3150. pass = curses_input("Password");
  3151. if (!pass)
  3152. goto out;
  3153. pool = calloc(sizeof(struct pool), 1);
  3154. if (!pool)
  3155. quit(1, "Failed to realloc pools in input_pool");
  3156. pool->pool_no = total_pools;
  3157. pool->prio = total_pools;
  3158. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3159. quit (1, "Failed to pthread_mutex_init in input_pool");
  3160. pool->rpc_url = url;
  3161. pool->rpc_user = user;
  3162. pool->rpc_pass = pass;
  3163. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3164. if (!pool->rpc_userpass)
  3165. quit(1, "Failed to malloc userpass");
  3166. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3167. pool->tv_idle.tv_sec = ~0UL;
  3168. /* Test the pool before we enable it if we're live running, otherwise
  3169. * it will be tested separately */
  3170. ret = true;
  3171. if (live && pool_active(pool))
  3172. pool->enabled = true;
  3173. pools[total_pools++] = pool;
  3174. out:
  3175. immedok(logwin, false);
  3176. if (!ret) {
  3177. if (url)
  3178. free(url);
  3179. if (user)
  3180. free(user);
  3181. if (pass)
  3182. free(pass);
  3183. if (pool)
  3184. free(pool);
  3185. }
  3186. return ret;
  3187. }
  3188. #if !defined(WIN32)
  3189. static void fork_monitor()
  3190. {
  3191. // Make a pipe: [readFD, writeFD]
  3192. int pfd[2];
  3193. int r = pipe(pfd);
  3194. if (r<0) {
  3195. perror("pipe - failed to create pipe for --monitor");
  3196. exit(1);
  3197. }
  3198. // Make stderr write end of pipe
  3199. fflush(stderr);
  3200. r = dup2(pfd[1], 2);
  3201. if (r<0) {
  3202. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3203. exit(1);
  3204. }
  3205. r = close(pfd[1]);
  3206. if (r<0) {
  3207. perror("close - failed to close write end of pipe for --monitor");
  3208. exit(1);
  3209. }
  3210. // Don't let a dying monitor kill the main process
  3211. sighandler_t sr = signal(SIGPIPE, SIG_IGN);
  3212. if (SIG_ERR==sr) {
  3213. perror("signal - failed to edit signal mask for --monitor");
  3214. exit(1);
  3215. }
  3216. // Fork a child process
  3217. r = fork();
  3218. if (r<0) {
  3219. perror("fork - failed to fork child process for --monitor");
  3220. exit(1);
  3221. }
  3222. // In child, launch command
  3223. if (0==r) {
  3224. // Make stdin read end of pipe
  3225. r = dup2(pfd[0], 0);
  3226. if (r<0) {
  3227. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3228. exit(1);
  3229. }
  3230. close(pfd[0]);
  3231. if (r<0) {
  3232. perror("close - in child, failed to close read end of pipe for --monitor");
  3233. exit(1);
  3234. }
  3235. // Launch user specified command
  3236. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3237. perror("execl - in child failed to exec user specified command for --monitor");
  3238. exit(1);
  3239. }
  3240. // In parent, clean up unused fds
  3241. r = close(pfd[0]);
  3242. if (r<0) {
  3243. perror("close - failed to close read end of pipe for --monitor");
  3244. exit(1);
  3245. }
  3246. }
  3247. #endif // !WIN32
  3248. int main (int argc, char *argv[])
  3249. {
  3250. unsigned int i, j = 0, x, y, pools_active = 0;
  3251. struct sigaction handler;
  3252. struct thr_info *thr;
  3253. char name[256];
  3254. /* This dangerous functions tramples random dynamically allocated
  3255. * variables so do it before anything at all */
  3256. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3257. quit(1, "Failed to curl_global_init");
  3258. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  3259. quit(1, "Failed to pthread_mutex_init");
  3260. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  3261. quit(1, "Failed to pthread_mutex_init");
  3262. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  3263. quit(1, "Failed to pthread_mutex_init");
  3264. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  3265. quit(1, "Failed to pthread_mutex_init");
  3266. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  3267. quit(1, "Failed to pthread_mutex_init");
  3268. handler.sa_handler = &sighandler;
  3269. sigaction(SIGTERM, &handler, &termhandler);
  3270. sigaction(SIGINT, &handler, &inthandler);
  3271. gettimeofday(&total_tv_start, NULL);
  3272. gettimeofday(&total_tv_end, NULL);
  3273. get_datestamp(datestamp, &total_tv_start);
  3274. for (i = 0; i < 36; i++)
  3275. strcat(current_block, "0");
  3276. current_hash = calloc(sizeof(current_hash), 1);
  3277. if (unlikely(!current_hash))
  3278. quit (1, "main OOM");
  3279. #ifdef WIN32
  3280. opt_n_threads = num_processors = 1;
  3281. #else
  3282. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  3283. opt_n_threads = num_processors;
  3284. #endif /* !WIN32 */
  3285. #ifdef HAVE_OPENCL
  3286. for (i = 0; i < 16; i++)
  3287. gpu_devices[i] = false;
  3288. nDevs = clDevicesNum();
  3289. if (nDevs < 0) {
  3290. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  3291. nDevs = 0;
  3292. }
  3293. #endif
  3294. if (nDevs)
  3295. opt_n_threads = 0;
  3296. trpc_url = strdup(DEF_RPC_URL);
  3297. /* parse command line */
  3298. opt_register_table(opt_config_table,
  3299. "Options for both config file and command line");
  3300. opt_register_table(opt_cmdline_table,
  3301. "Options for command line only");
  3302. opt_parse(&argc, argv, applog_and_exit);
  3303. if (argc != 1)
  3304. quit(1, "Unexpected extra commandline arguments");
  3305. if (opt_kernel) {
  3306. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  3307. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  3308. if (!strcmp(opt_kernel, "poclbm"))
  3309. chosen_kernel = KL_POCLBM;
  3310. else
  3311. chosen_kernel = KL_PHATK;
  3312. } else
  3313. chosen_kernel = KL_NONE;
  3314. gpu_threads = nDevs * opt_g_threads;
  3315. if (total_devices) {
  3316. if (total_devices > nDevs)
  3317. quit(1, "More devices specified than exist");
  3318. for (i = 0; i < 16; i++)
  3319. if (gpu_devices[i] && i + 1 > nDevs)
  3320. quit (1, "Command line options set a device that doesn't exist");
  3321. } else {
  3322. for (i = 0; i < nDevs; i++)
  3323. gpu_devices[i] = true;
  3324. total_devices = nDevs;
  3325. }
  3326. if (!gpu_threads && !forced_n_threads) {
  3327. /* Maybe they turned GPU off; restore default CPU threads. */
  3328. opt_n_threads = num_processors;
  3329. }
  3330. logcursor = 8;
  3331. gpucursor = logcursor;
  3332. cpucursor = gpucursor + nDevs;
  3333. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  3334. logcursor = logstart + 1;
  3335. /* Set up the ncurses interface */
  3336. if (!opt_realquiet && use_curses) {
  3337. mainwin = initscr();
  3338. getmaxyx(mainwin, y, x);
  3339. statuswin = newwin(logstart, x, 0, 0);
  3340. leaveok(statuswin, true);
  3341. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3342. idlok(logwin, true);
  3343. scrollok(logwin, true);
  3344. leaveok(logwin, true);
  3345. cbreak();
  3346. noecho();
  3347. test_and_set(&curses_active);
  3348. }
  3349. if (!total_pools) {
  3350. if (curses_active) {
  3351. if (!input_pool(false))
  3352. quit(1, "Pool setup failed");
  3353. } else
  3354. quit(1, "No server specified");
  3355. }
  3356. for (i = 0; i < total_pools; i++) {
  3357. struct pool *pool = pools[i];
  3358. if (!pool->rpc_userpass) {
  3359. if (!pool->rpc_user || !pool->rpc_pass)
  3360. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3361. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3362. if (!pool->rpc_userpass)
  3363. quit(1, "Failed to malloc userpass");
  3364. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3365. } else {
  3366. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  3367. if (!pool->rpc_user)
  3368. quit(1, "Failed to malloc user");
  3369. strcpy(pool->rpc_user, pool->rpc_userpass);
  3370. pool->rpc_user = strtok(pool->rpc_user, ":");
  3371. if (!pool->rpc_user)
  3372. quit(1, "Failed to find colon delimiter in userpass");
  3373. }
  3374. }
  3375. /* Set the currentpool to pool 0 */
  3376. currentpool = pools[0];
  3377. #ifdef HAVE_SYSLOG_H
  3378. if (use_syslog)
  3379. openlog(PROGRAM_NAME, LOG_PID, LOG_USER);
  3380. #endif
  3381. #if !defined(WIN32)
  3382. if (opt_stderr_cmd)
  3383. fork_monitor();
  3384. #endif // !WIN32
  3385. mining_threads = opt_n_threads + gpu_threads;
  3386. total_threads = mining_threads + 5;
  3387. work_restart = calloc(total_threads, sizeof(*work_restart));
  3388. if (!work_restart)
  3389. quit(1, "Failed to calloc work_restart");
  3390. thr_info = calloc(total_threads, sizeof(*thr));
  3391. if (!thr_info)
  3392. quit(1, "Failed to calloc thr_info");
  3393. /* init workio thread info */
  3394. work_thr_id = mining_threads;
  3395. thr = &thr_info[work_thr_id];
  3396. thr->id = work_thr_id;
  3397. thr->q = tq_new();
  3398. if (!thr->q)
  3399. quit(1, "Failed to tq_new");
  3400. /* start work I/O thread */
  3401. if (thr_info_create(thr, NULL, workio_thread, thr))
  3402. quit(1, "workio thread create failed");
  3403. /* init longpoll thread info */
  3404. longpoll_thr_id = mining_threads + 1;
  3405. thr = &thr_info[longpoll_thr_id];
  3406. thr->id = longpoll_thr_id;
  3407. thr->q = tq_new();
  3408. if (!thr->q)
  3409. quit(1, "Failed to tq_new");
  3410. if (want_longpoll)
  3411. start_longpoll();
  3412. if (opt_n_threads ) {
  3413. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  3414. if (unlikely(!cpus))
  3415. quit(1, "Failed to calloc cpus");
  3416. }
  3417. if (gpu_threads) {
  3418. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  3419. if (unlikely(!gpus))
  3420. quit(1, "Failed to calloc gpus");
  3421. }
  3422. stage_thr_id = mining_threads + 3;
  3423. thr = &thr_info[stage_thr_id];
  3424. thr->q = tq_new();
  3425. if (!thr->q)
  3426. quit(1, "Failed to tq_new");
  3427. /* start stage thread */
  3428. if (thr_info_create(thr, NULL, stage_thread, thr))
  3429. quit(1, "stage thread create failed");
  3430. pthread_detach(*thr->pth);
  3431. /* Create a unique get work queue */
  3432. getq = tq_new();
  3433. if (!getq)
  3434. quit(1, "Failed to create getq");
  3435. /* Test each pool to see if we can retrieve and use work and for what
  3436. * it supports */
  3437. for (i = 0; i < total_pools; i++) {
  3438. struct pool *pool;
  3439. pool = pools[i];
  3440. if (pool_active(pool)) {
  3441. if (!currentpool)
  3442. currentpool = pool;
  3443. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  3444. pools_active++;
  3445. pool->enabled = true;
  3446. } else {
  3447. if (pool == currentpool)
  3448. currentpool = NULL;
  3449. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  3450. }
  3451. }
  3452. if (!pools_active)
  3453. quit(0, "No pools active! Exiting.");
  3454. #ifdef HAVE_OPENCL
  3455. i = 0;
  3456. /* start GPU mining threads */
  3457. for (j = 0; j < nDevs * opt_g_threads; j++) {
  3458. int gpu = j % nDevs;
  3459. gpus[gpu].is_gpu = 1;
  3460. gpus[gpu].cpu_gpu = gpu;
  3461. thr = &thr_info[i];
  3462. thr->id = i;
  3463. thr->cgpu = &gpus[gpu];
  3464. thr->q = tq_new();
  3465. if (!thr->q)
  3466. quit(1, "tq_new failed in starting gpu mining threads");
  3467. /* Enable threads for devices set not to mine but disable
  3468. * their queue in case we wish to enable them later*/
  3469. if (gpu_devices[gpu]) {
  3470. if (opt_debug)
  3471. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  3472. tq_push(thr->q, &ping);
  3473. }
  3474. applog(LOG_INFO, "Init GPU thread %i", i);
  3475. clStates[i] = initCl(gpu, name, sizeof(name));
  3476. if (!clStates[i]) {
  3477. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  3478. gpu_devices[i] = false;
  3479. continue;
  3480. }
  3481. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3482. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  3483. quit(1, "thread %d create failed", i);
  3484. i++;
  3485. }
  3486. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  3487. #else
  3488. opt_g_threads = 0;
  3489. #endif
  3490. /* start CPU mining threads */
  3491. for (i = gpu_threads; i < mining_threads; i++) {
  3492. int cpu = (i - gpu_threads) % num_processors;
  3493. thr = &thr_info[i];
  3494. thr->id = i;
  3495. cpus[cpu].cpu_gpu = cpu;
  3496. thr->cgpu = &cpus[cpu];
  3497. thr->q = tq_new();
  3498. if (!thr->q)
  3499. quit(1, "tq_new failed in starting cpu mining threads");
  3500. thread_reportin(thr);
  3501. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  3502. quit(1, "thread %d create failed", i);
  3503. }
  3504. applog(LOG_INFO, "%d cpu miner threads started, "
  3505. "using SHA256 '%s' algorithm.",
  3506. opt_n_threads,
  3507. algo_names[opt_algo]);
  3508. watchdog_thr_id = mining_threads + 2;
  3509. thr = &thr_info[watchdog_thr_id];
  3510. /* start wakeup thread */
  3511. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  3512. quit(1, "wakeup thread create failed");
  3513. /* Create curses input thread for keyboard input */
  3514. input_thr_id = mining_threads + 4;
  3515. thr = &thr_info[input_thr_id];
  3516. if (thr_info_create(thr, NULL, input_thread, thr))
  3517. quit(1, "input thread create failed");
  3518. pthread_detach(*thr->pth);
  3519. /* main loop - simply wait for workio thread to exit */
  3520. pthread_join(*thr_info[work_thr_id].pth, NULL);
  3521. applog(LOG_INFO, "workio thread dead, exiting.");
  3522. gettimeofday(&total_tv_end, NULL);
  3523. disable_curses();
  3524. if (!opt_realquiet && successful_connect)
  3525. print_summary();
  3526. if (gpu_threads)
  3527. free(gpus);
  3528. if (opt_n_threads)
  3529. free(cpus);
  3530. curl_global_cleanup();
  3531. return 0;
  3532. }