main.c 92 KB

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