main.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730
  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. static const char *algo_names[] = {
  89. [ALGO_C] = "c",
  90. #ifdef WANT_SSE2_4WAY
  91. [ALGO_4WAY] = "4way",
  92. #endif
  93. #ifdef WANT_VIA_PADLOCK
  94. [ALGO_VIA] = "via",
  95. #endif
  96. [ALGO_CRYPTOPP] = "cryptopp",
  97. #ifdef WANT_CRYPTOPP_ASM32
  98. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  99. #endif
  100. #ifdef WANT_X8664_SSE2
  101. [ALGO_SSE2_64] = "sse2_64",
  102. #endif
  103. #ifdef WANT_X8664_SSE4
  104. [ALGO_SSE4_64] = "sse4_64",
  105. #endif
  106. };
  107. bool opt_debug = false;
  108. bool opt_protocol = false;
  109. bool want_longpoll = true;
  110. bool have_longpoll = false;
  111. bool use_syslog = false;
  112. static bool opt_quiet = false;
  113. static int opt_retries = -1;
  114. static int opt_fail_pause = 5;
  115. static int opt_log_interval = 5;
  116. bool opt_log_output = false;
  117. static bool opt_dynamic = true;
  118. static int opt_queue;
  119. int opt_vectors;
  120. int opt_worksize;
  121. int opt_scantime = 60;
  122. static const bool opt_time = true;
  123. #ifdef WANT_X8664_SSE4
  124. static enum sha256_algos opt_algo = ALGO_SSE4_64;
  125. #elif WANT_X8664_SSE2
  126. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  127. #else
  128. static enum sha256_algos opt_algo = ALGO_C;
  129. #endif
  130. static int nDevs;
  131. static int opt_g_threads = 2;
  132. static int opt_device;
  133. static int total_devices;
  134. static bool gpu_devices[16];
  135. static int gpu_threads;
  136. static bool forced_n_threads;
  137. static int opt_n_threads;
  138. static int mining_threads;
  139. static int num_processors;
  140. static int scan_intensity;
  141. static bool use_curses = true;
  142. struct thr_info *thr_info;
  143. static int work_thr_id;
  144. int longpoll_thr_id;
  145. static int stage_thr_id;
  146. static int watchdog_thr_id;
  147. struct work_restart *work_restart = NULL;
  148. static pthread_mutex_t hash_lock;
  149. static pthread_mutex_t qd_lock;
  150. static pthread_mutex_t stgd_lock;
  151. static pthread_mutex_t curses_lock;
  152. static double total_mhashes_done;
  153. static struct timeval total_tv_start, total_tv_end;
  154. pthread_mutex_t control_lock;
  155. int hw_errors;
  156. static int total_accepted, total_rejected;
  157. static int total_getworks, total_stale, total_discarded;
  158. static int total_queued, total_staged, lp_staged;
  159. static unsigned int new_blocks;
  160. static unsigned int local_work;
  161. static unsigned int total_lo, total_ro;
  162. static struct pool *pools = NULL;
  163. static struct pool *currentpool;
  164. static int pool_no;
  165. static int total_pools;
  166. static bool curses_active = false;
  167. static char current_block[37];
  168. static char longpoll_block[37];
  169. static char blank[37];
  170. static char datestamp[40];
  171. static char blockdate[40];
  172. struct sigaction termhandler, inthandler;
  173. struct thread_q *getq;
  174. static void applog_and_exit(const char *fmt, ...)
  175. {
  176. va_list ap;
  177. va_start(ap, fmt);
  178. vapplog(LOG_ERR, fmt, ap);
  179. va_end(ap);
  180. exit(1);
  181. }
  182. static void add_pool(void)
  183. {
  184. struct pool *pool;
  185. total_pools++;
  186. pools = realloc(pools, sizeof(struct pool) * total_pools);
  187. if (!pools) {
  188. applog(LOG_ERR, "Failed to malloc pools in add_pool");
  189. exit (1);
  190. }
  191. pool = &pools[total_pools - 1];
  192. memset(pool, 0, sizeof(struct pool));
  193. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  194. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  195. exit (1);
  196. }
  197. /* Make sure the pool doesn't think we've been idle since time 0 if
  198. * we rush to !localgen */
  199. pool->tv_localgen.tv_sec = ~0UL;
  200. }
  201. /* Pool variant of test and set */
  202. static bool pool_tset(struct pool *pool, bool *var)
  203. {
  204. bool ret;
  205. pthread_mutex_lock(&pool->pool_lock);
  206. ret = *var;
  207. *var = true;
  208. pthread_mutex_unlock(&pool->pool_lock);
  209. return ret;
  210. }
  211. static bool pool_tclear(struct pool *pool, bool *var)
  212. {
  213. bool ret;
  214. pthread_mutex_lock(&pool->pool_lock);
  215. ret = *var;
  216. *var = false;
  217. pthread_mutex_unlock(&pool->pool_lock);
  218. return ret;
  219. }
  220. static struct pool *current_pool(void)
  221. {
  222. struct pool *pool;
  223. pthread_mutex_lock(&control_lock);
  224. pool = currentpool;
  225. pthread_mutex_unlock(&control_lock);
  226. return pool;
  227. }
  228. static void switch_pools(void)
  229. {
  230. pthread_mutex_lock(&control_lock);
  231. pool_no++;
  232. if (pool_no >= total_pools)
  233. pool_no = 0;
  234. currentpool = &pools[pool_no];
  235. gettimeofday(&currentpool->tv_localgen, NULL);
  236. applog(LOG_WARNING, "Prolonged outage. Attempting to switch to %s", currentpool->rpc_url);
  237. pthread_mutex_unlock(&control_lock);
  238. }
  239. /* FIXME: Use asprintf for better errors. */
  240. static char *set_algo(const char *arg, enum sha256_algos *algo)
  241. {
  242. enum sha256_algos i;
  243. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  244. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  245. *algo = i;
  246. return NULL;
  247. }
  248. }
  249. return "Unknown algorithm";
  250. }
  251. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  252. {
  253. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  254. }
  255. static char *set_int_range(const char *arg, int *i, int min, int max)
  256. {
  257. char *err = opt_set_intval(arg, i);
  258. if (err)
  259. return err;
  260. if (*i < min || *i > max)
  261. return "Value out of range";
  262. return NULL;
  263. }
  264. static char *set_int_0_to_9999(const char *arg, int *i)
  265. {
  266. return set_int_range(arg, i, 0, 9999);
  267. }
  268. static char *forced_int_0_to_14(const char *arg, int *i)
  269. {
  270. opt_dynamic = false;
  271. return set_int_range(arg, i, 0, 14);
  272. }
  273. static char *force_nthreads_int(const char *arg, int *i)
  274. {
  275. forced_n_threads = true;
  276. return set_int_range(arg, i, 0, 9999);
  277. }
  278. static char *set_int_0_to_10(const char *arg, int *i)
  279. {
  280. return set_int_range(arg, i, 0, 10);
  281. }
  282. static char *set_devices(const char *arg, int *i)
  283. {
  284. char *err = opt_set_intval(arg, i);
  285. if (err)
  286. return err;
  287. if (*i < 0 || *i > 15)
  288. return "Invalid GPU device number";
  289. total_devices++;
  290. gpu_devices[*i] = true;
  291. return NULL;
  292. }
  293. static char *set_url(const char *arg, char **p)
  294. {
  295. struct pool *pool;
  296. add_pool();
  297. pool = &pools[total_pools - 1];
  298. opt_set_charp(arg, &pool->rpc_url);
  299. if (strncmp(arg, "http://", 7) &&
  300. strncmp(arg, "https://", 8))
  301. return "URL must start with http:// or https://";
  302. return NULL;
  303. }
  304. static char *set_user(const char *arg, char **p)
  305. {
  306. struct pool *pool;
  307. if (!total_pools)
  308. return "No URL set for user";
  309. pool = &pools[total_pools - 1];
  310. opt_set_charp(arg, &pool->rpc_user);
  311. return NULL;
  312. }
  313. static char *set_pass(const char *arg, char **p)
  314. {
  315. struct pool *pool;
  316. if (!total_pools)
  317. return "No URL set for pass";
  318. pool = &pools[total_pools - 1];
  319. opt_set_charp(arg, &pool->rpc_pass);
  320. return NULL;
  321. }
  322. static char *set_userpass(const char *arg, char **p)
  323. {
  324. struct pool *pool;
  325. if (!total_pools)
  326. return "No URL set for userpass";
  327. pool = &pools[total_pools - 1];
  328. opt_set_charp(arg, &pool->rpc_userpass);
  329. return NULL;
  330. }
  331. static char *set_vector(const char *arg, int *i)
  332. {
  333. char *err = opt_set_intval(arg, i);
  334. if (err)
  335. return err;
  336. if (*i != 1 && *i != 2 && *i != 4)
  337. return "Valid vectors are 1, 2 or 4";
  338. return NULL;
  339. }
  340. static char *enable_debug(bool *flag)
  341. {
  342. *flag = true;
  343. /* Turn out verbose output, too. */
  344. opt_log_output = true;
  345. return NULL;
  346. }
  347. static char *trpc_url;
  348. static char *trpc_userpass;
  349. static char *trpc_user, *trpc_pass;
  350. /* These options are available from config file or commandline */
  351. static struct opt_table opt_config_table[] = {
  352. OPT_WITH_ARG("--algo|-a",
  353. set_algo, show_algo, &opt_algo,
  354. "Specify sha256 implementation for CPU mining:\n"
  355. "\tc\t\tLinux kernel sha256, implemented in C"
  356. #ifdef WANT_SSE2_4WAY
  357. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  358. #endif
  359. #ifdef WANT_VIA_PADLOCK
  360. "\n\tvia\t\tVIA padlock implementation"
  361. #endif
  362. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  363. #ifdef WANT_CRYPTOPP_ASM32
  364. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  365. #endif
  366. #ifdef WANT_X8664_SSE2
  367. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  368. #endif
  369. #ifdef WANT_X8664_SSE4
  370. "\n\tsse4_64\t\tSSE4 implementation for x86_64 machines"
  371. #endif
  372. ),
  373. OPT_WITH_ARG("--cpu-threads|-t",
  374. force_nthreads_int, opt_show_intval, &opt_n_threads,
  375. "Number of miner CPU threads"),
  376. OPT_WITHOUT_ARG("--debug|-D",
  377. enable_debug, &opt_debug,
  378. "Enable debug output"),
  379. #ifdef HAVE_OPENCL
  380. OPT_WITH_ARG("--device|-d",
  381. set_devices, NULL, &opt_device,
  382. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  383. OPT_WITH_ARG("--gpu-threads|-g",
  384. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  385. "Number of threads per GPU (0 - 10)"),
  386. OPT_WITH_ARG("--intensity|-I",
  387. forced_int_0_to_14, opt_show_intval, &scan_intensity,
  388. "Intensity of GPU scanning (0 - 14, default: dynamic to maintain desktop interactivity)"),
  389. #endif
  390. OPT_WITH_ARG("--log|-l",
  391. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  392. "Interval in seconds between log output"),
  393. OPT_WITHOUT_ARG("--no-longpoll",
  394. opt_set_invbool, &want_longpoll,
  395. "Disable X-Long-Polling support"),
  396. OPT_WITH_ARG("--pass|-p",
  397. set_pass, NULL, &trpc_pass,
  398. "Password for bitcoin JSON-RPC server"),
  399. OPT_WITHOUT_ARG("--protocol-dump|-P",
  400. opt_set_bool, &opt_protocol,
  401. "Verbose dump of protocol-level activities"),
  402. OPT_WITH_ARG("--queue|-Q",
  403. set_int_0_to_10, opt_show_intval, &opt_queue,
  404. "Number of extra work items to queue (0 - 10)"),
  405. OPT_WITHOUT_ARG("--quiet|-q",
  406. opt_set_bool, &opt_quiet,
  407. "Disable per-thread hashmeter output"),
  408. OPT_WITH_ARG("--retries|-r",
  409. opt_set_intval, opt_show_intval, &opt_retries,
  410. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  411. OPT_WITH_ARG("--retry-pause|-R",
  412. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  413. "Number of seconds to pause, between retries"),
  414. OPT_WITH_ARG("--scan-time|-s",
  415. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  416. "Upper bound on time spent scanning current work, in seconds"),
  417. #ifdef HAVE_SYSLOG_H
  418. OPT_WITHOUT_ARG("--syslog",
  419. opt_set_bool, &use_syslog,
  420. "Use system log for output messages (default: standard error)"),
  421. #endif
  422. OPT_WITHOUT_ARG("--text-only|-T",
  423. opt_set_invbool, &use_curses,
  424. "Disable ncurses formatted screen output"),
  425. OPT_WITH_ARG("--url|-o",
  426. set_url, opt_show_charp, &trpc_url,
  427. "URL for bitcoin JSON-RPC server"),
  428. OPT_WITH_ARG("--user|-u",
  429. set_user, NULL, &trpc_user,
  430. "Username for bitcoin JSON-RPC server"),
  431. #ifdef HAVE_OPENCL
  432. OPT_WITH_ARG("--vectors|-v",
  433. set_vector, NULL, &opt_vectors,
  434. "Override detected optimal vector width (1, 2 or 4)"),
  435. #endif
  436. OPT_WITHOUT_ARG("--verbose",
  437. opt_set_bool, &opt_log_output,
  438. "Log verbose output to stderr as well as status output"),
  439. #ifdef HAVE_OPENCL
  440. OPT_WITH_ARG("--worksize|-w",
  441. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  442. "Override detected optimal worksize"),
  443. #endif
  444. OPT_WITH_ARG("--userpass|-O",
  445. set_userpass, NULL, &trpc_userpass,
  446. "Username:Password pair for bitcoin JSON-RPC server"),
  447. OPT_ENDTABLE
  448. };
  449. static char *parse_config(json_t *config)
  450. {
  451. static char err_buf[200];
  452. json_t *val;
  453. struct opt_table *opt;
  454. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  455. char *p, *name;
  456. /* We don't handle subtables. */
  457. assert(!(opt->type & OPT_SUBTABLE));
  458. /* Pull apart the option name(s). */
  459. name = strdup(opt->names);
  460. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  461. char *err;
  462. /* Ignore short options. */
  463. if (p[1] != '-')
  464. continue;
  465. val = json_object_get(config, p+2);
  466. if (!val)
  467. continue;
  468. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  469. err = opt->cb_arg(json_string_value(val),
  470. opt->u.arg);
  471. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  472. err = opt->cb(opt->u.arg);
  473. } else {
  474. err = "Invalid value";
  475. }
  476. if (err) {
  477. sprintf(err_buf, "Parsing JSON option %s: %s",
  478. p, err);
  479. return err_buf;
  480. }
  481. }
  482. free(name);
  483. }
  484. return NULL;
  485. }
  486. static char *load_config(const char *arg, void *unused)
  487. {
  488. json_error_t err;
  489. json_t *config;
  490. config = json_load_file(arg, 0, &err);
  491. if (!json_is_object(config))
  492. return "JSON decode of file failed";
  493. /* Parse the config now, so we can override it. That can keep pointers
  494. * so don't free config object. */
  495. return parse_config(config);
  496. }
  497. static char *print_ndevs_and_exit(int *ndevs)
  498. {
  499. printf("%i GPU devices detected\n", *ndevs);
  500. exit(*ndevs);
  501. }
  502. /* These options are available from commandline only */
  503. static struct opt_table opt_cmdline_table[] = {
  504. OPT_WITH_ARG("--config|-c",
  505. load_config, NULL, NULL,
  506. "Load a JSON-format configuration file\n"
  507. "See example-cfg.json for an example configuration."),
  508. OPT_WITHOUT_ARG("--help|-h",
  509. opt_usage_and_exit,
  510. #ifdef HAVE_OPENCL
  511. "\nBuilt with CPU and GPU mining support.\n\n",
  512. #else
  513. "\nBuilt with CPU mining support only.\n\n",
  514. #endif
  515. "Print this message"),
  516. OPT_WITHOUT_ARG("--ndevs|-n",
  517. print_ndevs_and_exit, &nDevs,
  518. "Enumerate number of detected GPUs and exit"),
  519. OPT_ENDTABLE
  520. };
  521. static bool jobj_binary(const json_t *obj, const char *key,
  522. void *buf, size_t buflen)
  523. {
  524. const char *hexstr;
  525. json_t *tmp;
  526. tmp = json_object_get(obj, key);
  527. if (unlikely(!tmp)) {
  528. applog(LOG_ERR, "JSON key '%s' not found", key);
  529. return false;
  530. }
  531. hexstr = json_string_value(tmp);
  532. if (unlikely(!hexstr)) {
  533. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  534. return false;
  535. }
  536. if (!hex2bin(buf, hexstr, buflen))
  537. return false;
  538. return true;
  539. }
  540. static bool work_decode(const json_t *val, struct work *work)
  541. {
  542. if (unlikely(!jobj_binary(val, "midstate",
  543. work->midstate, sizeof(work->midstate)))) {
  544. applog(LOG_ERR, "JSON inval midstate");
  545. goto err_out;
  546. }
  547. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  548. applog(LOG_ERR, "JSON inval data");
  549. goto err_out;
  550. }
  551. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  552. applog(LOG_ERR, "JSON inval hash1");
  553. goto err_out;
  554. }
  555. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  556. applog(LOG_ERR, "JSON inval target");
  557. goto err_out;
  558. }
  559. memset(work->hash, 0, sizeof(work->hash));
  560. return true;
  561. err_out:
  562. return false;
  563. }
  564. static inline int dev_from_id(int thr_id)
  565. {
  566. return thr_info[thr_id].cgpu->cpu_gpu;
  567. }
  568. static WINDOW *mainwin, *statuswin, *logwin;
  569. static double total_secs = 0.1;
  570. static char statusline[256];
  571. static int cpucursor, gpucursor, logstart, logcursor;
  572. static struct cgpu_info *gpus, *cpus;
  573. static void text_print_status(int thr_id)
  574. {
  575. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  576. printf(" %sPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  577. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->total_mhashes / total_secs,
  578. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  579. cgpu->efficiency, cgpu->utility);
  580. }
  581. /* Must be called with curses mutex lock held and curses_active */
  582. static void curses_print_status(int thr_id)
  583. {
  584. struct pool *pool = current_pool();
  585. wmove(statuswin, 0, 0);
  586. wattron(statuswin, A_BOLD);
  587. wprintw(statuswin, " " PROGRAM_NAME " version " VERSION " - Started: %s", datestamp);
  588. wattroff(statuswin, A_BOLD);
  589. wmove(statuswin, 1, 0);
  590. whline(statuswin, '-', 80);
  591. wmove(statuswin, 2,0);
  592. wprintw(statuswin, " %s", statusline);
  593. wclrtoeol(statuswin);
  594. wmove(statuswin, 3,0);
  595. wprintw(statuswin, " TQ: %d ST: %d LS: %d SS: %d DW: %d NB: %d LW: %d LO: %d RF: %d I: %d",
  596. total_queued, total_staged, lp_staged, total_stale, total_discarded, new_blocks,
  597. local_work, total_lo, total_ro, scan_intensity);
  598. wclrtoeol(statuswin);
  599. wmove(statuswin, 4, 0);
  600. wprintw(statuswin, " Connected to %s as user %s", pool->rpc_url, pool->rpc_user);
  601. wclrtoeol(statuswin);
  602. wmove(statuswin, 5, 0);
  603. wprintw(statuswin, " Block %s started: %s", current_block + 4, blockdate);
  604. wmove(statuswin, 6, 0);
  605. whline(statuswin, '-', 80);
  606. wmove(statuswin, logstart - 1, 0);
  607. whline(statuswin, '-', 80);
  608. if (thr_id >= 0 && thr_id < gpu_threads) {
  609. int gpu = dev_from_id(thr_id);
  610. struct cgpu_info *cgpu = &gpus[gpu];
  611. wmove(statuswin, gpucursor + gpu, 0);
  612. wprintw(statuswin, " GPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  613. gpu, cgpu->total_mhashes / total_secs,
  614. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  615. cgpu->efficiency, cgpu->utility);
  616. wclrtoeol(statuswin);
  617. } else if (thr_id >= gpu_threads) {
  618. int cpu = dev_from_id(thr_id);
  619. struct cgpu_info *cgpu = &cpus[cpu];
  620. wmove(statuswin, cpucursor + cpu, 0);
  621. wprintw(statuswin, " CPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  622. cpu, cgpu->total_mhashes / total_secs,
  623. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  624. cgpu->efficiency, cgpu->utility);
  625. wclrtoeol(statuswin);
  626. }
  627. wrefresh(statuswin);
  628. }
  629. static void print_status(int thr_id)
  630. {
  631. if (!curses_active)
  632. text_print_status(thr_id);
  633. else {
  634. pthread_mutex_lock(&curses_lock);
  635. curses_print_status(thr_id);
  636. wrefresh(statuswin);
  637. pthread_mutex_unlock(&curses_lock);
  638. }
  639. }
  640. void log_curses(const char *f, va_list ap)
  641. {
  642. if (curses_active) {
  643. pthread_mutex_lock(&curses_lock);
  644. vw_printw(logwin, f, ap);
  645. wrefresh(logwin);
  646. pthread_mutex_unlock(&curses_lock);
  647. } else
  648. vprintf(f, ap);
  649. }
  650. static bool submit_upstream_work(const struct work *work)
  651. {
  652. char *hexstr = NULL;
  653. json_t *val, *res;
  654. char s[345];
  655. bool rc = false;
  656. int thr_id = work->thr_id;
  657. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  658. CURL *curl = curl_easy_init();
  659. struct pool *pool = work->pool;
  660. if (unlikely(!curl)) {
  661. applog(LOG_ERR, "CURL initialisation failed");
  662. return rc;
  663. }
  664. /* build hex string */
  665. hexstr = bin2hex(work->data, sizeof(work->data));
  666. if (unlikely(!hexstr)) {
  667. applog(LOG_ERR, "submit_upstream_work OOM");
  668. goto out_nofree;
  669. }
  670. /* build JSON-RPC request */
  671. sprintf(s,
  672. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  673. hexstr);
  674. if (opt_debug)
  675. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  676. /* issue JSON-RPC request */
  677. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, pool);
  678. if (unlikely(!val)) {
  679. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  680. if (!pool_tset(pool, &pool->submit_fail)) {
  681. total_ro++;
  682. pool->remotefail_occasions++;
  683. applog(LOG_WARNING, "Upstream communication failure, caching submissions");
  684. }
  685. goto out;
  686. } else if (pool_tclear(pool, &pool->submit_fail))
  687. applog(LOG_WARNING, "Upstream communication resumed, submitting work");
  688. res = json_object_get(val, "result");
  689. /* Theoretically threads could race when modifying accepted and
  690. * rejected values but the chance of two submits completing at the
  691. * same time is zero so there is no point adding extra locking */
  692. if (json_is_true(res)) {
  693. cgpu->accepted++;
  694. total_accepted++;
  695. pool->accepted++;
  696. if (opt_debug)
  697. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  698. if (!opt_quiet)
  699. applog(LOG_WARNING, "Share %.8s accepted from %sPU %d thread %d",
  700. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  701. } else {
  702. cgpu->rejected++;
  703. total_rejected++;
  704. pool->rejected++;
  705. if (opt_debug)
  706. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  707. if (!opt_quiet)
  708. applog(LOG_WARNING, "Share %.8s rejected from %sPU %d thread %d",
  709. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  710. }
  711. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  712. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  713. if (!opt_quiet)
  714. print_status(thr_id);
  715. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  716. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  717. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  718. json_decref(val);
  719. rc = true;
  720. out:
  721. free(hexstr);
  722. out_nofree:
  723. curl_easy_cleanup(curl);
  724. return rc;
  725. }
  726. static const char *rpc_req =
  727. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  728. static bool get_upstream_work(struct work *work)
  729. {
  730. struct pool *pool = current_pool();
  731. json_t *val;
  732. bool rc = false;
  733. CURL *curl = curl_easy_init();
  734. if (unlikely(!curl)) {
  735. applog(LOG_ERR, "CURL initialisation failed");
  736. return rc;
  737. }
  738. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  739. want_longpoll, false, pool);
  740. if (unlikely(!val)) {
  741. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  742. goto out;
  743. }
  744. rc = work_decode(json_object_get(val, "result"), work);
  745. work->pool = pool;
  746. json_decref(val);
  747. out:
  748. curl_easy_cleanup(curl);
  749. return rc;
  750. }
  751. static void workio_cmd_free(struct workio_cmd *wc)
  752. {
  753. if (!wc)
  754. return;
  755. switch (wc->cmd) {
  756. case WC_SUBMIT_WORK:
  757. free(wc->u.work);
  758. break;
  759. default: /* do nothing */
  760. break;
  761. }
  762. memset(wc, 0, sizeof(*wc)); /* poison */
  763. free(wc);
  764. }
  765. static void disable_curses(void)
  766. {
  767. if (test_and_clear(&curses_active)) {
  768. delwin(logwin);
  769. delwin(statuswin);
  770. delwin(mainwin);
  771. endwin();
  772. refresh();
  773. }
  774. }
  775. void kill_work(void)
  776. {
  777. struct workio_cmd *wc;
  778. struct thr_info *thr;
  779. unsigned int i;
  780. disable_curses();
  781. applog(LOG_INFO, "Received kill message");
  782. /* Kill the watchdog thread */
  783. thr = &thr_info[watchdog_thr_id];
  784. pthread_cancel(thr->pth);
  785. /* Stop the mining threads*/
  786. for (i = 0; i < mining_threads; i++) {
  787. thr = &thr_info[i];
  788. tq_freeze(thr->q);
  789. /* No need to check if this succeeds or not */
  790. pthread_cancel(thr->pth);
  791. }
  792. /* Stop the others */
  793. thr = &thr_info[stage_thr_id];
  794. pthread_cancel(thr->pth);
  795. thr = &thr_info[longpoll_thr_id];
  796. pthread_cancel(thr->pth);
  797. wc = calloc(1, sizeof(*wc));
  798. if (unlikely(!wc)) {
  799. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  800. /* We're just trying to die anyway, so forget graceful */
  801. exit (1);
  802. }
  803. wc->cmd = WC_DIE;
  804. wc->thr = 0;
  805. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  806. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  807. exit (1);
  808. }
  809. }
  810. static void sighandler(int sig)
  811. {
  812. /* Restore signal handlers so we can still quit if kill_work fails */
  813. sigaction(SIGTERM, &termhandler, NULL);
  814. sigaction(SIGINT, &inthandler, NULL);
  815. kill_work();
  816. }
  817. static void *get_work_thread(void *userdata)
  818. {
  819. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  820. struct work *ret_work;
  821. int failures = 0;
  822. pthread_detach(pthread_self());
  823. ret_work = calloc(1, sizeof(*ret_work));
  824. if (unlikely(!ret_work)) {
  825. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  826. kill_work();
  827. goto out;
  828. }
  829. /* obtain new work from bitcoin via JSON-RPC */
  830. while (!get_upstream_work(ret_work)) {
  831. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  832. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  833. free(ret_work);
  834. kill_work();
  835. goto out;
  836. }
  837. /* pause, then restart work-request loop */
  838. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  839. opt_fail_pause);
  840. sleep(opt_fail_pause);
  841. }
  842. /* send work to requesting thread */
  843. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  844. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  845. kill_work();
  846. free(ret_work);
  847. }
  848. out:
  849. workio_cmd_free(wc);
  850. return NULL;
  851. }
  852. static bool workio_get_work(struct workio_cmd *wc)
  853. {
  854. pthread_t get_thread;
  855. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  856. applog(LOG_ERR, "Failed to create get_work_thread");
  857. return false;
  858. }
  859. return true;
  860. }
  861. static bool stale_work(struct work *work)
  862. {
  863. bool ret = false;
  864. char *hexstr;
  865. if (!strncmp(blank, current_block, 36))
  866. return ret;
  867. hexstr = bin2hex(work->data, 36);
  868. if (unlikely(!hexstr)) {
  869. applog(LOG_ERR, "submit_work_thread OOM");
  870. return ret;
  871. }
  872. if (strncmp(hexstr, current_block, 36))
  873. ret = true;
  874. free(hexstr);
  875. return ret;
  876. }
  877. static void *submit_work_thread(void *userdata)
  878. {
  879. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  880. struct work *work = wc->u.work;
  881. struct pool *pool = work->pool;
  882. int failures = 0;
  883. pthread_detach(pthread_self());
  884. if (stale_work(work)) {
  885. applog(LOG_WARNING, "Stale share detected, discarding");
  886. total_stale++;
  887. pool->stale_shares++;
  888. goto out;
  889. }
  890. /* submit solution to bitcoin via JSON-RPC */
  891. while (!submit_upstream_work(work)) {
  892. if (stale_work(work)) {
  893. applog(LOG_WARNING, "Stale share detected, discarding");
  894. total_stale++;
  895. pool->stale_shares++;
  896. break;
  897. }
  898. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  899. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  900. kill_work();
  901. break;
  902. }
  903. /* pause, then restart work-request loop */
  904. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  905. opt_fail_pause);
  906. sleep(opt_fail_pause);
  907. }
  908. out:
  909. workio_cmd_free(wc);
  910. return NULL;
  911. }
  912. static bool workio_submit_work(struct workio_cmd *wc)
  913. {
  914. pthread_t submit_thread;
  915. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  916. applog(LOG_ERR, "Failed to create submit_work_thread");
  917. return false;
  918. }
  919. return true;
  920. }
  921. static void inc_staged(struct pool *pool, int inc, bool lp)
  922. {
  923. pthread_mutex_lock(&stgd_lock);
  924. if (lp) {
  925. lp_staged += inc;
  926. total_staged += inc;
  927. pool->idlenet = true;
  928. } else if (lp_staged) {
  929. if (!--lp_staged) {
  930. unsigned int i;
  931. /* Make sure the watchdog thread doesn't kill the mining
  932. * threads once we unset the idlenet flag */
  933. for (i = 0; i < mining_threads; i++)
  934. gettimeofday(&thr_info[i].last, NULL);
  935. pool->idlenet = false;
  936. }
  937. } else
  938. total_staged += inc;
  939. pthread_mutex_unlock(&stgd_lock);
  940. }
  941. static void dec_staged(int inc)
  942. {
  943. pthread_mutex_lock(&stgd_lock);
  944. total_staged -= inc;
  945. pthread_mutex_unlock(&stgd_lock);
  946. }
  947. static int requests_staged(void)
  948. {
  949. int ret;
  950. pthread_mutex_lock(&stgd_lock);
  951. ret = total_staged;
  952. pthread_mutex_unlock(&stgd_lock);
  953. return ret;
  954. }
  955. static int real_staged(void)
  956. {
  957. int ret;
  958. pthread_mutex_lock(&stgd_lock);
  959. ret = total_staged - lp_staged;
  960. pthread_mutex_unlock(&stgd_lock);
  961. return ret;
  962. }
  963. static void set_curblock(char *hexstr)
  964. {
  965. struct timeval tv_now;
  966. struct tm tm;
  967. memcpy(current_block, hexstr, 36);
  968. gettimeofday(&tv_now, NULL);
  969. localtime_r(&tv_now.tv_sec, &tm);
  970. sprintf(blockdate, "[%d-%02d-%02d %02d:%02d:%02d]",
  971. tm.tm_year + 1900,
  972. tm.tm_mon + 1,
  973. tm.tm_mday,
  974. tm.tm_hour,
  975. tm.tm_min,
  976. tm.tm_sec);
  977. }
  978. static void *stage_thread(void *userdata)
  979. {
  980. struct thr_info *mythr = userdata;
  981. bool ok = true;
  982. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  983. while (ok) {
  984. struct work *work = NULL;
  985. char *hexstr;
  986. work = tq_pop(mythr->q, NULL);
  987. if (unlikely(!work)) {
  988. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  989. ok = false;
  990. break;
  991. }
  992. hexstr = bin2hex(work->data, 36);
  993. if (unlikely(!hexstr)) {
  994. applog(LOG_ERR, "stage_thread OOM");
  995. break;
  996. }
  997. /* current_block is blanked out on successful longpoll */
  998. if (likely(strncmp(current_block, blank, 36))) {
  999. if (unlikely(strncmp(hexstr, current_block, 36))) {
  1000. new_blocks++;
  1001. if (have_longpoll)
  1002. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1003. else
  1004. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1005. /* As we can't flush the work from here, signal
  1006. * the wakeup thread to restart all the
  1007. * threads */
  1008. work_restart[watchdog_thr_id].restart = 1;
  1009. set_curblock(hexstr);
  1010. }
  1011. } else {
  1012. set_curblock(hexstr);
  1013. memcpy(longpoll_block, hexstr, 36);
  1014. }
  1015. free(hexstr);
  1016. if (unlikely(!tq_push(getq, work))) {
  1017. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  1018. ok = false;
  1019. break;
  1020. }
  1021. inc_staged(work->pool, 1, false);
  1022. }
  1023. tq_freeze(mythr->q);
  1024. return NULL;
  1025. }
  1026. static void *workio_thread(void *userdata)
  1027. {
  1028. struct thr_info *mythr = userdata;
  1029. bool ok = true;
  1030. while (ok) {
  1031. struct workio_cmd *wc;
  1032. /* wait for workio_cmd sent to us, on our queue */
  1033. wc = tq_pop(mythr->q, NULL);
  1034. if (unlikely(!wc)) {
  1035. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  1036. ok = false;
  1037. break;
  1038. }
  1039. /* process workio_cmd */
  1040. switch (wc->cmd) {
  1041. case WC_GET_WORK:
  1042. ok = workio_get_work(wc);
  1043. break;
  1044. case WC_SUBMIT_WORK:
  1045. ok = workio_submit_work(wc);
  1046. break;
  1047. case WC_DIE:
  1048. default:
  1049. ok = false;
  1050. break;
  1051. }
  1052. }
  1053. tq_freeze(mythr->q);
  1054. return NULL;
  1055. }
  1056. static void hashmeter(int thr_id, struct timeval *diff,
  1057. unsigned long hashes_done)
  1058. {
  1059. struct timeval temp_tv_end, total_diff;
  1060. double khashes, secs;
  1061. double local_secs;
  1062. double utility, efficiency = 0.0;
  1063. static double local_mhashes_done = 0;
  1064. static double rolling_local = 0;
  1065. double local_mhashes = (double)hashes_done / 1000000.0;
  1066. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1067. /* Update the last time this thread reported in */
  1068. if (thr_id >= 0)
  1069. gettimeofday(&thr_info[thr_id].last, NULL);
  1070. /* Don't bother calculating anything if we're not displaying it */
  1071. if (opt_quiet || !opt_log_interval)
  1072. return;
  1073. khashes = hashes_done / 1000.0;
  1074. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  1075. if (thr_id >= 0 && secs) {
  1076. /* So we can call hashmeter from a non worker thread */
  1077. if (opt_debug)
  1078. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  1079. thr_id, hashes_done, hashes_done / secs);
  1080. cgpu->local_mhashes += local_mhashes;
  1081. cgpu->total_mhashes += local_mhashes;
  1082. }
  1083. /* Totals are updated by all threads so can race without locking */
  1084. pthread_mutex_lock(&hash_lock);
  1085. gettimeofday(&temp_tv_end, NULL);
  1086. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  1087. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  1088. total_mhashes_done += local_mhashes;
  1089. local_mhashes_done += local_mhashes;
  1090. if (total_diff.tv_sec < opt_log_interval)
  1091. /* Only update the total every opt_log_interval seconds */
  1092. goto out_unlock;
  1093. gettimeofday(&total_tv_end, NULL);
  1094. /* Use a rolling average by faking an exponential decay over 5 * log */
  1095. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  1096. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  1097. total_secs = (double)total_diff.tv_sec +
  1098. ((double)total_diff.tv_usec / 1000000.0);
  1099. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1100. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  1101. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1102. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  1103. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  1104. if (!curses_active) {
  1105. printf("%s \r", statusline);
  1106. fflush(stdout);
  1107. } else
  1108. applog(LOG_INFO, "%s", statusline);
  1109. local_mhashes_done = 0;
  1110. out_unlock:
  1111. pthread_mutex_unlock(&hash_lock);
  1112. }
  1113. /* This is overkill, but at least we'll know accurately how much work is
  1114. * queued to prevent ever being left without work */
  1115. static void inc_queued(void)
  1116. {
  1117. pthread_mutex_lock(&qd_lock);
  1118. total_queued++;
  1119. pthread_mutex_unlock(&qd_lock);
  1120. }
  1121. static void dec_queued(void)
  1122. {
  1123. pthread_mutex_lock(&qd_lock);
  1124. if (total_queued > 0)
  1125. total_queued--;
  1126. pthread_mutex_unlock(&qd_lock);
  1127. dec_staged(1);
  1128. }
  1129. static int requests_queued(void)
  1130. {
  1131. int ret;
  1132. pthread_mutex_lock(&qd_lock);
  1133. ret = total_queued;
  1134. pthread_mutex_unlock(&qd_lock);
  1135. return ret;
  1136. }
  1137. static bool queue_request(void)
  1138. {
  1139. int maxq = opt_queue + mining_threads;
  1140. struct workio_cmd *wc;
  1141. struct pool *pool;
  1142. /* If we've been generating lots of local work we may already have
  1143. * enough in the queue */
  1144. if (requests_queued() >= maxq || real_staged() >= maxq)
  1145. return true;
  1146. pool = current_pool();
  1147. /* fill out work request message */
  1148. wc = calloc(1, sizeof(*wc));
  1149. if (unlikely(!wc)) {
  1150. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  1151. return false;
  1152. }
  1153. wc->cmd = WC_GET_WORK;
  1154. /* The get work does not belong to any thread */
  1155. wc->thr = NULL;
  1156. /* send work request to workio thread */
  1157. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1158. applog(LOG_ERR, "Failed to tq_push in queue_request");
  1159. workio_cmd_free(wc);
  1160. return false;
  1161. }
  1162. total_getworks++;
  1163. pool->getwork_requested++;
  1164. inc_queued();
  1165. return true;
  1166. }
  1167. static void discard_staged(void)
  1168. {
  1169. struct work *work_heap;
  1170. struct pool *pool;
  1171. /* Just in case we fell in a hole and missed a queue filling */
  1172. if (unlikely(!requests_staged()))
  1173. return;
  1174. work_heap = tq_pop(getq, NULL);
  1175. if (unlikely(!work_heap))
  1176. return;
  1177. pool = work_heap->pool;
  1178. free(work_heap);
  1179. dec_queued();
  1180. pool->discarded_work++;
  1181. total_discarded++;
  1182. }
  1183. static void flush_requests(bool longpoll)
  1184. {
  1185. struct pool *pool = current_pool();
  1186. int i, stale;
  1187. /* We should have one fresh work item staged from the block change. */
  1188. stale = requests_staged() - 1;
  1189. if (longpoll)
  1190. memcpy(current_block, blank, 36);
  1191. /* Temporarily increase the staged count so that get_work thinks there
  1192. * is work available instead of making threads reuse existing work */
  1193. inc_staged(pool, mining_threads, true);
  1194. for (i = 0; i < stale; i++) {
  1195. /* Queue a whole batch of new requests */
  1196. if (unlikely(!queue_request())) {
  1197. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  1198. kill_work();
  1199. break;
  1200. }
  1201. /* Pop off the old requests. Cancelling the requests would be better
  1202. * but is tricky */
  1203. discard_staged();
  1204. }
  1205. }
  1206. static bool get_work(struct work *work, bool queued)
  1207. {
  1208. struct timespec abstime = {};
  1209. struct timeval now;
  1210. struct work *work_heap;
  1211. struct pool *pool;
  1212. bool ret = false;
  1213. int failures = 0;
  1214. retry:
  1215. pool = current_pool();
  1216. if (unlikely(!queued && !queue_request())) {
  1217. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1218. goto out;
  1219. }
  1220. if (!requests_staged() && !stale_work(work) && work->pool->has_rolltime) {
  1221. uint32_t *work_ntime;
  1222. uint32_t ntime;
  1223. /* Only print this message once each time we shift to localgen */
  1224. if (!pool_tset(pool, &pool->localgen)) {
  1225. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1226. pool->localgen_occasions++;
  1227. total_lo++;
  1228. gettimeofday(&pool->tv_localgen, NULL);
  1229. } else {
  1230. struct timeval tv_now, diff;
  1231. gettimeofday(&tv_now, NULL);
  1232. timeval_subtract(&diff, &tv_now, &pool->tv_localgen);
  1233. if (total_pools > 1) {
  1234. /* Attempt to switch pools if this one has been unresponsive for >half
  1235. * a block's duration */
  1236. if (diff.tv_sec > 300) {
  1237. switch_pools();
  1238. inc_staged(pool, 1, true);
  1239. goto retry;
  1240. }
  1241. } else if (diff.tv_sec > 600) {
  1242. /* A new block appears on average every 10 mins */
  1243. applog(LOG_WARNING, "Prolonged outage. Going idle till network recovers.");
  1244. /* Force every thread to wait for new work */
  1245. inc_staged(pool, 1, true);
  1246. goto retry;
  1247. }
  1248. }
  1249. work_ntime = (uint32_t *)(work->data + 68);
  1250. ntime = be32toh(*work_ntime);
  1251. ntime++;
  1252. *work_ntime = htobe32(ntime);
  1253. ret = true;
  1254. local_work++;
  1255. goto out;
  1256. }
  1257. gettimeofday(&now, NULL);
  1258. abstime.tv_sec = now.tv_sec + 60;
  1259. /* wait for 1st response, or get cached response */
  1260. work_heap = tq_pop(getq, &abstime);
  1261. if (unlikely(!work_heap)) {
  1262. if (total_pools > 1) {
  1263. /* Attempt to switch pools if this one has mandatory
  1264. * work that has timed out or does not support rolltime */
  1265. pool->localgen_occasions++;
  1266. total_lo++;
  1267. switch_pools();
  1268. inc_staged(pool, 1, true);
  1269. goto retry;
  1270. }
  1271. if (!pool_tset(pool, &pool->localgen))
  1272. applog(LOG_WARNING, "Timed out waiting for work from server");
  1273. goto retry;
  1274. }
  1275. /* If we make it here we have succeeded in getting fresh work */
  1276. if (pool_tclear(pool, &pool->localgen))
  1277. applog(LOG_WARNING, "Resuming with work from server");
  1278. dec_queued();
  1279. memcpy(work, work_heap, sizeof(*work));
  1280. ret = true;
  1281. free(work_heap);
  1282. out:
  1283. if (unlikely(ret == false)) {
  1284. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1285. applog(LOG_ERR, "Failed %d times to get_work");
  1286. return ret;
  1287. }
  1288. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1289. sleep(opt_fail_pause);
  1290. goto retry;
  1291. }
  1292. return ret;
  1293. }
  1294. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1295. {
  1296. struct workio_cmd *wc;
  1297. /* fill out work request message */
  1298. wc = calloc(1, sizeof(*wc));
  1299. if (unlikely(!wc)) {
  1300. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1301. return false;
  1302. }
  1303. wc->u.work = malloc(sizeof(*work_in));
  1304. if (unlikely(!wc->u.work)) {
  1305. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1306. goto err_out;
  1307. }
  1308. wc->cmd = WC_SUBMIT_WORK;
  1309. wc->thr = thr;
  1310. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1311. /* send solution to workio thread */
  1312. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1313. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1314. goto err_out;
  1315. }
  1316. return true;
  1317. err_out:
  1318. workio_cmd_free(wc);
  1319. return false;
  1320. }
  1321. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1322. {
  1323. work->data[64+12+0] = (nonce>>0) & 0xff;
  1324. work->data[64+12+1] = (nonce>>8) & 0xff;
  1325. work->data[64+12+2] = (nonce>>16) & 0xff;
  1326. work->data[64+12+3] = (nonce>>24) & 0xff;
  1327. return submit_work_sync(thr, work);
  1328. }
  1329. static void *miner_thread(void *userdata)
  1330. {
  1331. struct thr_info *mythr = userdata;
  1332. const int thr_id = mythr->id;
  1333. uint32_t max_nonce = 0xffffff;
  1334. unsigned long hashes_done = max_nonce;
  1335. bool needs_work = true;
  1336. /* Try to cycle approximately 5 times before each log update */
  1337. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1338. /* Request the next work item at 2/3 of the scantime */
  1339. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1340. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1341. bool requested = true;
  1342. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1343. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1344. * and if that fails, then SCHED_BATCH. No need for this to be an
  1345. * error if it fails */
  1346. setpriority(PRIO_PROCESS, 0, 19);
  1347. drop_policy();
  1348. /* Cpu affinity only makes sense if the number of threads is a multiple
  1349. * of the number of CPUs */
  1350. if (!(opt_n_threads % num_processors))
  1351. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  1352. while (1) {
  1353. struct work work __attribute__((aligned(128)));
  1354. struct timeval tv_workstart, tv_start, tv_end, diff;
  1355. uint64_t max64;
  1356. bool rc;
  1357. if (needs_work) {
  1358. gettimeofday(&tv_workstart, NULL);
  1359. /* obtain new work from internal workio thread */
  1360. if (unlikely(!get_work(&work, requested))) {
  1361. applog(LOG_ERR, "work retrieval failed, exiting "
  1362. "mining thread %d", thr_id);
  1363. goto out;
  1364. }
  1365. mythr->cgpu->getworks++;
  1366. work.thr_id = thr_id;
  1367. needs_work = requested = false;
  1368. work.blk.nonce = 0;
  1369. max_nonce = hashes_done;
  1370. }
  1371. hashes_done = 0;
  1372. gettimeofday(&tv_start, NULL);
  1373. /* scan nonces for a proof-of-work hash */
  1374. switch (opt_algo) {
  1375. case ALGO_C:
  1376. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1377. work.hash1, work.hash, work.target,
  1378. max_nonce, &hashes_done,
  1379. work.blk.nonce);
  1380. break;
  1381. #ifdef WANT_X8664_SSE2
  1382. case ALGO_SSE2_64: {
  1383. unsigned int rc5 =
  1384. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1385. work.hash1, work.hash,
  1386. work.target,
  1387. max_nonce, &hashes_done,
  1388. work.blk.nonce);
  1389. rc = (rc5 == -1) ? false : true;
  1390. }
  1391. break;
  1392. #endif
  1393. #ifdef WANT_X8664_SSE4
  1394. case ALGO_SSE4_64: {
  1395. unsigned int rc5 =
  1396. scanhash_sse4_64(thr_id, work.midstate, work.data + 64,
  1397. work.hash1, work.hash,
  1398. work.target,
  1399. max_nonce, &hashes_done,
  1400. work.blk.nonce);
  1401. rc = (rc5 == -1) ? false : true;
  1402. }
  1403. break;
  1404. #endif
  1405. #ifdef WANT_SSE2_4WAY
  1406. case ALGO_4WAY: {
  1407. unsigned int rc4 =
  1408. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1409. work.hash1, work.hash,
  1410. work.target,
  1411. max_nonce, &hashes_done,
  1412. work.blk.nonce);
  1413. rc = (rc4 == -1) ? false : true;
  1414. }
  1415. break;
  1416. #endif
  1417. #ifdef WANT_VIA_PADLOCK
  1418. case ALGO_VIA:
  1419. rc = scanhash_via(thr_id, work.data, work.target,
  1420. max_nonce, &hashes_done,
  1421. work.blk.nonce);
  1422. break;
  1423. #endif
  1424. case ALGO_CRYPTOPP:
  1425. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1426. work.hash1, work.hash, work.target,
  1427. max_nonce, &hashes_done,
  1428. work.blk.nonce);
  1429. break;
  1430. #ifdef WANT_CRYPTOPP_ASM32
  1431. case ALGO_CRYPTOPP_ASM32:
  1432. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1433. work.hash1, work.hash, work.target,
  1434. max_nonce, &hashes_done,
  1435. work.blk.nonce);
  1436. break;
  1437. #endif
  1438. default:
  1439. /* should never happen */
  1440. goto out;
  1441. }
  1442. /* record scanhash elapsed time */
  1443. gettimeofday(&tv_end, NULL);
  1444. timeval_subtract(&diff, &tv_end, &tv_start);
  1445. hashes_done -= work.blk.nonce;
  1446. hashmeter(thr_id, &diff, hashes_done);
  1447. work.blk.nonce += hashes_done;
  1448. /* adjust max_nonce to meet target cycle time */
  1449. if (diff.tv_usec > 500000)
  1450. diff.tv_sec++;
  1451. if (diff.tv_sec && diff.tv_sec != cycle) {
  1452. max64 = work.blk.nonce +
  1453. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1454. } else
  1455. max64 = work.blk.nonce + hashes_done;
  1456. if (max64 > 0xfffffffaULL)
  1457. max64 = 0xfffffffaULL;
  1458. max_nonce = max64;
  1459. /* if nonce found, submit work */
  1460. if (unlikely(rc)) {
  1461. if (opt_debug)
  1462. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  1463. if (unlikely(!submit_work_sync(mythr, &work))) {
  1464. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1465. break;
  1466. }
  1467. work.blk.nonce += 4;
  1468. }
  1469. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1470. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1471. if (unlikely(!queue_request())) {
  1472. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1473. goto out;
  1474. }
  1475. requested = true;
  1476. }
  1477. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1478. work.blk.nonce >= MAXTHREADS - hashes_done ||
  1479. stale_work(&work))
  1480. needs_work = true;
  1481. }
  1482. out:
  1483. tq_freeze(mythr->q);
  1484. return NULL;
  1485. }
  1486. enum {
  1487. STAT_SLEEP_INTERVAL = 1,
  1488. STAT_CTR_INTERVAL = 10000000,
  1489. FAILURE_INTERVAL = 30,
  1490. };
  1491. #ifdef HAVE_OPENCL
  1492. static _clState *clStates[16];
  1493. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1494. {
  1495. cl_kernel *kernel = &clState->kernel;
  1496. cl_int status = 0;
  1497. int num = 0;
  1498. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1499. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1500. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1501. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1502. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1503. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1504. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1505. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1506. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1507. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1508. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1509. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1510. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1511. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1512. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1513. if (clState->hasBitAlign == true) {
  1514. /* Parameters for phatk kernel */
  1515. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1516. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1517. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1518. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1519. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1520. } else {
  1521. /* Parameters for poclbm kernel */
  1522. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1523. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1524. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1525. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1526. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1527. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1528. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1529. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1530. }
  1531. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1532. (void *)&clState->outputBuffer);
  1533. return status;
  1534. }
  1535. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  1536. unsigned int *hashes, size_t *globalThreads)
  1537. {
  1538. *globalThreads = *threads = 1 << (15 + scan_intensity);
  1539. *hashes = *threads * vectors;
  1540. }
  1541. static void *gpuminer_thread(void *userdata)
  1542. {
  1543. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1544. struct timeval tv_start, tv_end, diff, tv_workstart;
  1545. struct thr_info *mythr = userdata;
  1546. const int thr_id = mythr->id;
  1547. uint32_t *res, *blank_res;
  1548. double gpu_ms_average = 7;
  1549. size_t globalThreads[1];
  1550. size_t localThreads[1];
  1551. cl_int status;
  1552. _clState *clState = clStates[thr_id];
  1553. const cl_kernel *kernel = &clState->kernel;
  1554. struct work *work = malloc(sizeof(struct work));
  1555. unsigned int threads = 1 << (15 + scan_intensity);
  1556. unsigned const int vectors = clState->preferred_vwidth;
  1557. unsigned int hashes = threads * vectors;
  1558. unsigned int hashes_done = 0;
  1559. /* Request the next work item at 2/3 of the scantime */
  1560. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1561. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1562. bool requested = true;
  1563. if (opt_dynamic) {
  1564. /* Minimise impact on desktop if we want dynamic mode */
  1565. setpriority(PRIO_PROCESS, 0, 19);
  1566. drop_policy();
  1567. }
  1568. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1569. res = calloc(BUFFERSIZE, 1);
  1570. blank_res = calloc(BUFFERSIZE, 1);
  1571. if (!res || !blank_res) {
  1572. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1573. goto out;
  1574. }
  1575. gettimeofday(&tv_start, NULL);
  1576. globalThreads[0] = threads;
  1577. localThreads[0] = clState->work_size;
  1578. diff.tv_sec = 0;
  1579. gettimeofday(&tv_end, NULL);
  1580. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  1581. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1582. if (unlikely(status != CL_SUCCESS))
  1583. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1584. gettimeofday(&tv_workstart, NULL);
  1585. /* obtain new work from internal workio thread */
  1586. if (unlikely(!get_work(work, requested))) {
  1587. applog(LOG_ERR, "work retrieval failed, exiting "
  1588. "gpu mining thread %d", mythr->id);
  1589. goto out;
  1590. }
  1591. mythr->cgpu->getworks++;
  1592. work->thr_id = thr_id;
  1593. requested = false;
  1594. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1595. work->blk.nonce = 0;
  1596. while (1) {
  1597. struct timeval tv_gpustart, tv_gpuend;
  1598. suseconds_t gpu_us;
  1599. gettimeofday(&tv_gpustart, NULL);
  1600. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  1601. /* This finish flushes the readbuffer set with CL_FALSE later */
  1602. clFinish(clState->commandQueue);
  1603. gettimeofday(&tv_gpuend, NULL);
  1604. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  1605. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  1606. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  1607. if (opt_dynamic) {
  1608. /* Try to not let the GPU be out for longer than 6ms, but
  1609. * increase intensity when the system is idle, unless
  1610. * dynamic is disabled. */
  1611. if (gpu_ms_average > 7) {
  1612. if (scan_intensity > 0)
  1613. scan_intensity--;
  1614. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1615. } else if (gpu_ms_average < 3) {
  1616. if (scan_intensity < 14)
  1617. scan_intensity++;
  1618. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1619. }
  1620. }
  1621. if (diff.tv_sec > opt_scantime ||
  1622. work->blk.nonce >= MAXTHREADS - hashes ||
  1623. work_restart[thr_id].restart ||
  1624. stale_work(work)) {
  1625. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1626. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1627. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1628. if (unlikely(status != CL_SUCCESS))
  1629. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1630. memset(res, 0, BUFFERSIZE);
  1631. gettimeofday(&tv_workstart, NULL);
  1632. /* obtain new work from internal workio thread */
  1633. if (unlikely(!get_work(work, requested))) {
  1634. applog(LOG_ERR, "work retrieval failed, exiting "
  1635. "gpu mining thread %d", mythr->id);
  1636. goto out;
  1637. }
  1638. mythr->cgpu->getworks++;
  1639. work->thr_id = thr_id;
  1640. requested = false;
  1641. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1642. work->blk.nonce = 0;
  1643. work_restart[thr_id].restart = 0;
  1644. if (opt_debug)
  1645. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1646. /* Flushes the writebuffer set with CL_FALSE above */
  1647. clFinish(clState->commandQueue);
  1648. }
  1649. status = queue_kernel_parameters(clState, &work->blk);
  1650. if (unlikely(status != CL_SUCCESS))
  1651. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1652. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1653. if (res[MAXBUFFERS]) {
  1654. /* Clear the buffer again */
  1655. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1656. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1657. if (unlikely(status != CL_SUCCESS))
  1658. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1659. if (opt_debug)
  1660. applog(LOG_DEBUG, "GPU %d found something?", dev_from_id(thr_id));
  1661. postcalc_hash_async(mythr, work, res);
  1662. memset(res, 0, BUFFERSIZE);
  1663. clFinish(clState->commandQueue);
  1664. }
  1665. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1666. globalThreads, localThreads, 0, NULL, NULL);
  1667. if (unlikely(status != CL_SUCCESS))
  1668. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1669. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1670. BUFFERSIZE, res, 0, NULL, NULL);
  1671. if (unlikely(status != CL_SUCCESS))
  1672. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1673. gettimeofday(&tv_end, NULL);
  1674. timeval_subtract(&diff, &tv_end, &tv_start);
  1675. hashes_done += hashes;
  1676. work->blk.nonce += hashes;
  1677. if (diff.tv_usec > 500000)
  1678. diff.tv_sec++;
  1679. if (diff.tv_sec >= cycle) {
  1680. hashmeter(thr_id, &diff, hashes_done);
  1681. gettimeofday(&tv_start, NULL);
  1682. hashes_done = 0;
  1683. }
  1684. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1685. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1686. if (unlikely(!queue_request())) {
  1687. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1688. goto out;
  1689. }
  1690. requested = true;
  1691. }
  1692. }
  1693. out:
  1694. tq_freeze(mythr->q);
  1695. return NULL;
  1696. }
  1697. #endif /* HAVE_OPENCL */
  1698. static void restart_threads(bool longpoll)
  1699. {
  1700. int i;
  1701. /* Discard old queued requests and get new ones */
  1702. flush_requests(longpoll);
  1703. for (i = 0; i < mining_threads; i++)
  1704. work_restart[i].restart = 1;
  1705. }
  1706. /* Stage another work item from the work returned in a longpoll */
  1707. static void convert_to_work(json_t *val)
  1708. {
  1709. struct work *work;
  1710. bool rc;
  1711. work = calloc(sizeof(*work), 1);
  1712. if (unlikely(!work)) {
  1713. applog(LOG_ERR, "OOM in convert_to_work");
  1714. return;
  1715. }
  1716. rc= work_decode(json_object_get(val, "result"), work);
  1717. if (unlikely(!rc)) {
  1718. applog(LOG_ERR, "Could not convert longpoll data to work");
  1719. return;
  1720. }
  1721. work->pool = current_pool();
  1722. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  1723. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  1724. else if (opt_debug)
  1725. applog(LOG_DEBUG, "Converted longpoll data to work");
  1726. }
  1727. static void *longpoll_thread(void *userdata)
  1728. {
  1729. struct thr_info *mythr = userdata;
  1730. CURL *curl = NULL;
  1731. char *copy_start, *hdr_path, *lp_url = NULL;
  1732. bool need_slash = false;
  1733. int failures = 0;
  1734. struct pool *pool = current_pool();
  1735. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1736. curl = curl_easy_init();
  1737. if (unlikely(!curl)) {
  1738. applog(LOG_ERR, "CURL initialisation failed");
  1739. goto out;
  1740. }
  1741. /* Longpoll sits waiting on next pushed url */
  1742. next_path:
  1743. hdr_path = tq_pop(mythr->q, NULL);
  1744. if (!hdr_path) {
  1745. applog(LOG_WARNING, "No long-poll found on this server");
  1746. goto next_path;
  1747. }
  1748. /* full URL */
  1749. if (strstr(hdr_path, "://")) {
  1750. lp_url = hdr_path;
  1751. hdr_path = NULL;
  1752. }
  1753. /* absolute path, on current server */
  1754. else {
  1755. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1756. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  1757. need_slash = true;
  1758. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  1759. if (!lp_url)
  1760. goto out;
  1761. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  1762. }
  1763. free(hdr_path);
  1764. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  1765. while (1) {
  1766. struct timeval start, end;
  1767. json_t *val;
  1768. gettimeofday(&start, NULL);
  1769. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  1770. false, true, pool);
  1771. if (likely(val)) {
  1772. /* Keep track of who ordered a restart_threads to make
  1773. * sure it's only done once per new block */
  1774. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1775. !strncmp(longpoll_block, current_block, 36))) {
  1776. new_blocks++;
  1777. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  1778. restart_threads(true);
  1779. } else
  1780. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  1781. convert_to_work(val);
  1782. failures = 0;
  1783. json_decref(val);
  1784. } else {
  1785. /* Some pools regularly drop the longpoll request so
  1786. * only see this as longpoll failure if it happens
  1787. * immediately and just restart it the rest of the
  1788. * time. */
  1789. gettimeofday(&end, NULL);
  1790. if (end.tv_sec - start.tv_sec > 30)
  1791. continue;
  1792. if (failures++ < 10) {
  1793. sleep(30);
  1794. applog(LOG_WARNING,
  1795. "longpoll failed, sleeping for 30s");
  1796. } else {
  1797. applog(LOG_ERR,
  1798. "longpoll failed, ending thread");
  1799. goto out;
  1800. }
  1801. }
  1802. memcpy(longpoll_block, current_block, 36);
  1803. if (pool != current_pool()) {
  1804. applog(LOG_WARNING, "Attempting to change longpoll servers");
  1805. pool = current_pool();
  1806. have_longpoll = false;
  1807. goto next_path;
  1808. }
  1809. }
  1810. out:
  1811. free(lp_url);
  1812. tq_freeze(mythr->q);
  1813. if (curl)
  1814. curl_easy_cleanup(curl);
  1815. return NULL;
  1816. }
  1817. #if 0
  1818. static void reinit_cputhread(int thr_id)
  1819. {
  1820. struct thr_info *thr = &thr_info[thr_id];
  1821. tq_freeze(thr->q);
  1822. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1823. applog(LOG_ERR, "Failed to pthread_join in reinit_cputhread");
  1824. goto failed_out;
  1825. }
  1826. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  1827. tq_thaw(thr->q);
  1828. gettimeofday(&thr->last, NULL);
  1829. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1830. applog(LOG_ERR, "thread %d create failed", thr_id);
  1831. goto failed_out;
  1832. }
  1833. return;
  1834. failed_out:
  1835. kill_work();
  1836. }
  1837. #ifdef HAVE_OPENCL
  1838. static void reinit_gputhread(int thr_id)
  1839. {
  1840. int gpu = dev_from_id(thr_id);
  1841. struct thr_info *thr = &thr_info[thr_id];
  1842. char name[256];
  1843. tq_freeze(thr->q);
  1844. if (!(pthread_cancel(thr->pth)) && pthread_join(thr->pth, NULL)) {
  1845. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1846. goto failed_out;
  1847. }
  1848. free(clStates[thr_id]);
  1849. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  1850. tq_thaw(thr->q);
  1851. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  1852. if (!clStates[thr_id]) {
  1853. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  1854. goto failed_out;
  1855. }
  1856. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1857. gettimeofday(&thr->last, NULL);
  1858. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1859. applog(LOG_ERR, "thread %d create failed", thr_id);
  1860. goto failed_out;
  1861. }
  1862. return;
  1863. failed_out:
  1864. kill_work();
  1865. }
  1866. static void reinit_thread(int thr_id)
  1867. {
  1868. if (thr_id < gpu_threads)
  1869. reinit_gputhread(thr_id);
  1870. else
  1871. reinit_cputhread(thr_id);
  1872. }
  1873. #else /* HAVE_OPENCL */
  1874. static void reinit_thread(int thr_id)
  1875. {
  1876. reinit_cputhread(thr_id);
  1877. }
  1878. #endif
  1879. #endif /* 0 */
  1880. /* Determine which are the first threads belonging to a device and if they're
  1881. * active */
  1882. static bool active_device(int thr_id)
  1883. {
  1884. if (thr_id < gpu_threads) {
  1885. if (thr_id >= total_devices)
  1886. return false;
  1887. if (!gpu_devices[dev_from_id(thr_id)])
  1888. return false;
  1889. } else if (thr_id > gpu_threads + num_processors)
  1890. return false;
  1891. return true;
  1892. }
  1893. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  1894. * the screen at regular intervals, and restarts threads if they appear to have
  1895. * died. */
  1896. static void *watchdog_thread(void *userdata)
  1897. {
  1898. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1899. struct timeval zero_tv;
  1900. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1901. memset(&zero_tv, 0, sizeof(struct timeval));
  1902. while (1) {
  1903. int x, y, logx, logy, i;
  1904. struct timeval now;
  1905. sleep(interval);
  1906. if (requests_queued() < opt_queue)
  1907. queue_request();
  1908. hashmeter(-1, &zero_tv, 0);
  1909. if (curses_active) {
  1910. pthread_mutex_lock(&curses_lock);
  1911. getmaxyx(mainwin, y, x);
  1912. getmaxyx(logwin, logy, logx);
  1913. y -= logcursor;
  1914. /* Detect screen size change */
  1915. if (x != logx || y != logy)
  1916. wresize(logwin, y, x);
  1917. for (i = 0; i < mining_threads; i++) {
  1918. if (active_device(i))
  1919. curses_print_status(i);
  1920. }
  1921. redrawwin(logwin);
  1922. redrawwin(statuswin);
  1923. pthread_mutex_unlock(&curses_lock);
  1924. }
  1925. if (unlikely(work_restart[watchdog_thr_id].restart)) {
  1926. restart_threads(false);
  1927. work_restart[watchdog_thr_id].restart = 0;
  1928. }
  1929. gettimeofday(&now, NULL);
  1930. #if 0
  1931. //for (i = 0; i < mining_threads; i++) {
  1932. for (i = 0; i < gpu_threads; i++) {
  1933. struct thr_info *thr = &thr_info[i];
  1934. /* Do not kill threads waiting on longpoll staged work
  1935. * or idle network */
  1936. if (now.tv_sec - thr->last.tv_sec > 60 && !pool->idlenet) {
  1937. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  1938. /* Create one mandatory work item */
  1939. inc_staged(1, true);
  1940. if (unlikely(!queue_request())) {
  1941. applog(LOG_ERR, "Failed to queue_request in watchdog_thread");
  1942. kill_work();
  1943. break;
  1944. }
  1945. reinit_thread(i);
  1946. applog(LOG_WARNING, "Thread %d restarted", i);
  1947. }
  1948. }
  1949. #endif
  1950. }
  1951. return NULL;
  1952. }
  1953. static void print_summary(void)
  1954. {
  1955. struct timeval diff;
  1956. int hours, mins, secs, i;
  1957. double utility, efficiency = 0.0;
  1958. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  1959. hours = diff.tv_sec / 3600;
  1960. mins = (diff.tv_sec % 3600) / 60;
  1961. secs = diff.tv_sec % 60;
  1962. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1963. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  1964. printf("\nSummary of runtime statistics:\n\n");
  1965. printf("Started at %s\n", datestamp);
  1966. printf("Runtime: %d hrs : %d mins : %d secs\n", hours, mins, secs);
  1967. if (total_secs)
  1968. printf("Average hashrate: %.1f Megahash/s\n", total_mhashes_done / total_secs);
  1969. printf("Queued work requests: %d\n", total_getworks);
  1970. printf("Share submissions: %d\n", total_accepted + total_rejected);
  1971. printf("Accepted shares: %d\n", total_accepted);
  1972. printf("Rejected shares: %d\n", total_rejected);
  1973. if (total_accepted || total_rejected)
  1974. printf("Reject ratio: %.1f\n", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  1975. printf("Hardware errors: %d\n", hw_errors);
  1976. printf("Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1977. printf("Utility (accepted shares / min): %.2f/min\n\n", utility);
  1978. printf("Discarded work due to new blocks: %d\n", total_discarded);
  1979. printf("Stale submissions discarded due to new blocks: %d\n", total_stale);
  1980. printf("Unable to get work from server occasions: %d\n", total_lo);
  1981. printf("Work items generated locally: %d\n", local_work);
  1982. printf("Submitting work remotely delay occasions: %d\n", total_ro);
  1983. printf("New blocks detected on network: %d\n\n", new_blocks);
  1984. if (total_pools > 1) {
  1985. for (i = 0; i < total_pools; i++) {
  1986. struct pool *pool = &pools[i];
  1987. printf("Pool: %s\n", pool->rpc_url);
  1988. printf(" Queued work requests: %d\n", pool->getwork_requested);
  1989. printf(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1990. printf(" Accepted shares: %d\n", pool->accepted);
  1991. printf(" Rejected shares: %d\n", pool->rejected);
  1992. if (pool->accepted || pool->rejected)
  1993. printf(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1994. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1995. printf(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1996. printf(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1997. printf(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1998. printf(" Unable to get work from server occasions: %d\n", pool->localgen_occasions);
  1999. printf(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2000. }
  2001. }
  2002. printf("Summary of per device statistics:\n\n");
  2003. for (i = 0; i < mining_threads; i++) {
  2004. if (active_device(i))
  2005. print_status(i);
  2006. }
  2007. printf("\n");
  2008. }
  2009. int main (int argc, char *argv[])
  2010. {
  2011. unsigned int i, j = 0, x, y;
  2012. struct sigaction handler;
  2013. struct thr_info *thr;
  2014. char name[256];
  2015. struct tm tm;
  2016. /* This dangerous functions tramples random dynamically allocated
  2017. * variables so do it before anything at all */
  2018. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  2019. return 1;
  2020. /* This dangerous functions tramples random dynamically allocated
  2021. * variables so do it before anything at all */
  2022. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  2023. return 1;
  2024. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  2025. return 1;
  2026. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  2027. return 1;
  2028. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  2029. return 1;
  2030. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  2031. return 1;
  2032. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  2033. return 1;
  2034. handler.sa_handler = &sighandler;
  2035. sigaction(SIGTERM, &handler, &termhandler);
  2036. sigaction(SIGINT, &handler, &inthandler);
  2037. gettimeofday(&total_tv_start, NULL);
  2038. gettimeofday(&total_tv_end, NULL);
  2039. localtime_r(&total_tv_start.tv_sec, &tm);
  2040. sprintf(datestamp, "[%d-%02d-%02d %02d:%02d:%02d]",
  2041. tm.tm_year + 1900,
  2042. tm.tm_mon + 1,
  2043. tm.tm_mday,
  2044. tm.tm_hour,
  2045. tm.tm_min,
  2046. tm.tm_sec);
  2047. for (i = 0; i < 36; i++) {
  2048. strcat(blank, "0");
  2049. strcat(current_block, "0");
  2050. strcat(longpoll_block, "0");
  2051. }
  2052. #ifdef WIN32
  2053. opt_n_threads = num_processors = 1;
  2054. #else
  2055. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  2056. opt_n_threads = num_processors;
  2057. #endif /* !WIN32 */
  2058. #ifdef HAVE_OPENCL
  2059. for (i = 0; i < 16; i++)
  2060. gpu_devices[i] = false;
  2061. nDevs = clDevicesNum();
  2062. if (nDevs < 0)
  2063. return 1;
  2064. #endif
  2065. if (nDevs)
  2066. opt_n_threads = 0;
  2067. trpc_url = strdup(DEF_RPC_URL);
  2068. /* parse command line */
  2069. opt_register_table(opt_config_table,
  2070. "Options for both config file and command line");
  2071. opt_register_table(opt_cmdline_table,
  2072. "Options for command line only");
  2073. opt_parse(&argc, argv, applog_and_exit);
  2074. if (argc != 1) {
  2075. applog(LOG_ERR, "Unexpected extra commandline arguments");
  2076. return 1;
  2077. }
  2078. if (!total_pools) {
  2079. applog(LOG_ERR, "No server specified");
  2080. return 1;
  2081. }
  2082. if (total_devices) {
  2083. if (total_devices > nDevs) {
  2084. applog(LOG_ERR, "More devices specified than exist");
  2085. return 1;
  2086. }
  2087. for (i = 0; i < 16; i++)
  2088. if (gpu_devices[i] && i + 1 > nDevs) {
  2089. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  2090. return 1;
  2091. }
  2092. gpu_threads = total_devices * opt_g_threads;
  2093. } else {
  2094. gpu_threads = nDevs * opt_g_threads;
  2095. for (i = 0; i < nDevs; i++)
  2096. gpu_devices[i] = true;
  2097. total_devices = nDevs;
  2098. }
  2099. if (!gpu_threads && !forced_n_threads) {
  2100. /* Maybe they turned GPU off; restore default CPU threads. */
  2101. opt_n_threads = num_processors;
  2102. }
  2103. logcursor = 7;
  2104. mining_threads = opt_n_threads + gpu_threads;
  2105. gpucursor = logcursor;
  2106. cpucursor = gpucursor + nDevs;
  2107. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  2108. logcursor = logstart + 1;
  2109. for (i = 0; i < total_pools; i++) {
  2110. struct pool *pool = &pools[i];
  2111. if (!pool->rpc_userpass) {
  2112. if (!pool->rpc_user || !pool->rpc_pass) {
  2113. applog(LOG_ERR, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  2114. return 1;
  2115. }
  2116. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  2117. if (!pool->rpc_userpass)
  2118. return 1;
  2119. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  2120. } else {
  2121. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  2122. if (!pool->rpc_user)
  2123. return 1;
  2124. strcpy(pool->rpc_user, pool->rpc_userpass);
  2125. pool->rpc_user = strtok(pool->rpc_user, ":");
  2126. if (!pool->rpc_user) {
  2127. applog(LOG_ERR, "Failed to find colon delimiter in userpass");
  2128. return 1;
  2129. }
  2130. }
  2131. }
  2132. /* Set the current pool to pool 0 */
  2133. currentpool = pools;
  2134. #ifdef HAVE_SYSLOG_H
  2135. if (use_syslog)
  2136. openlog("cpuminer", LOG_PID, LOG_USER);
  2137. #endif
  2138. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  2139. if (!work_restart)
  2140. return 1;
  2141. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  2142. if (!thr_info)
  2143. return 1;
  2144. /* init workio thread info */
  2145. work_thr_id = mining_threads;
  2146. thr = &thr_info[work_thr_id];
  2147. thr->id = work_thr_id;
  2148. thr->q = tq_new();
  2149. if (!thr->q)
  2150. return 1;
  2151. /* start work I/O thread */
  2152. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  2153. applog(LOG_ERR, "workio thread create failed");
  2154. return 1;
  2155. }
  2156. /* init longpoll thread info */
  2157. if (want_longpoll) {
  2158. longpoll_thr_id = mining_threads + 1;
  2159. thr = &thr_info[longpoll_thr_id];
  2160. thr->id = longpoll_thr_id;
  2161. thr->q = tq_new();
  2162. if (!thr->q)
  2163. return 1;
  2164. /* start longpoll thread */
  2165. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  2166. applog(LOG_ERR, "longpoll thread create failed");
  2167. return 1;
  2168. }
  2169. pthread_detach(thr->pth);
  2170. } else
  2171. longpoll_thr_id = -1;
  2172. /* Test each pool to see if we can retrieve and use work and for what
  2173. * it supports */
  2174. for (i = 0; i < total_pools; i++) {
  2175. struct pool *pool;
  2176. struct work work;
  2177. json_t *val;
  2178. CURL *curl;
  2179. curl = curl_easy_init();
  2180. if (unlikely(!curl)) {
  2181. applog(LOG_ERR, "CURL initialisation failed");
  2182. return 1;
  2183. }
  2184. pool = &pools[i];
  2185. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2186. true, false, pool);
  2187. if (val) {
  2188. bool rc;
  2189. rc = work_decode(json_object_get(val, "result"), &work);
  2190. if (rc)
  2191. applog(LOG_INFO, "Successfully retreived and deciphered work from pool %u %s", i, pool->rpc_url);
  2192. else
  2193. applog(LOG_WARNING, "Successfully retreived but FAILED to decipher work from pool %u %s", i, pool->rpc_url);
  2194. json_decref(val);
  2195. } else
  2196. applog(LOG_WARNING, "FAILED to retrieve work from pool %u %s", i, pool->rpc_url);
  2197. curl_easy_cleanup(curl);
  2198. }
  2199. if (opt_n_threads ) {
  2200. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  2201. if (unlikely(!cpus)) {
  2202. applog(LOG_ERR, "Failed to calloc cpus");
  2203. return 1;
  2204. }
  2205. }
  2206. if (gpu_threads) {
  2207. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  2208. if (unlikely(!gpus)) {
  2209. applog(LOG_ERR, "Failed to calloc gpus");
  2210. return 1;
  2211. }
  2212. }
  2213. stage_thr_id = mining_threads + 3;
  2214. thr = &thr_info[stage_thr_id];
  2215. thr->q = tq_new();
  2216. if (!thr->q)
  2217. return 1;
  2218. /* start stage thread */
  2219. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  2220. applog(LOG_ERR, "stage thread create failed");
  2221. return 1;
  2222. }
  2223. /* Flag the work as ready forcing the mining threads to wait till we
  2224. * actually put something into the queue */
  2225. inc_staged(current_pool(), mining_threads, true);
  2226. /* Create a unique get work queue */
  2227. getq = tq_new();
  2228. if (!getq) {
  2229. applog(LOG_ERR, "Failed to create getq");
  2230. return 1;
  2231. }
  2232. #ifdef HAVE_OPENCL
  2233. i = 0;
  2234. /* start GPU mining threads */
  2235. for (j = 0; j < nDevs * opt_g_threads; j++) {
  2236. int gpu = j % nDevs;
  2237. gpus[gpu].is_gpu = 1;
  2238. gpus[gpu].cpu_gpu = gpu;
  2239. /* Skip devices not set to mine */
  2240. if (!gpu_devices[gpu])
  2241. continue;
  2242. thr = &thr_info[i];
  2243. thr->id = i;
  2244. thr->cgpu = &gpus[gpu];
  2245. thr->q = tq_new();
  2246. if (!thr->q) {
  2247. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  2248. return 1;
  2249. }
  2250. applog(LOG_INFO, "Init GPU thread %i", i);
  2251. clStates[i] = initCl(gpu, name, sizeof(name));
  2252. if (!clStates[i]) {
  2253. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  2254. continue;
  2255. }
  2256. applog(LOG_INFO, "initCl() finished. Found %s", name);
  2257. gettimeofday(&thr->last, NULL);
  2258. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  2259. applog(LOG_ERR, "thread %d create failed", i);
  2260. return 1;
  2261. }
  2262. i++;
  2263. }
  2264. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  2265. #endif
  2266. /* start CPU mining threads */
  2267. for (i = gpu_threads; i < mining_threads; i++) {
  2268. int cpu = (i - gpu_threads) % num_processors;
  2269. thr = &thr_info[i];
  2270. thr->id = i;
  2271. cpus[cpu].cpu_gpu = cpu;
  2272. thr->cgpu = &cpus[cpu];
  2273. thr->q = tq_new();
  2274. if (!thr->q) {
  2275. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  2276. return 1;
  2277. }
  2278. gettimeofday(&thr->last, NULL);
  2279. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  2280. applog(LOG_ERR, "thread %d create failed", i);
  2281. return 1;
  2282. }
  2283. }
  2284. applog(LOG_INFO, "%d cpu miner threads started, "
  2285. "using SHA256 '%s' algorithm.",
  2286. opt_n_threads,
  2287. algo_names[opt_algo]);
  2288. watchdog_thr_id = mining_threads + 2;
  2289. thr = &thr_info[watchdog_thr_id];
  2290. /* start wakeup thread */
  2291. if (pthread_create(&thr->pth, NULL, watchdog_thread, NULL)) {
  2292. applog(LOG_ERR, "wakeup thread create failed");
  2293. return 1;
  2294. }
  2295. /* Restart count as it will be wrong till all threads are started */
  2296. pthread_mutex_lock(&hash_lock);
  2297. gettimeofday(&total_tv_start, NULL);
  2298. gettimeofday(&total_tv_end, NULL);
  2299. total_mhashes_done = 0;
  2300. pthread_mutex_unlock(&hash_lock);
  2301. /* Set up the ncurses interface */
  2302. if (!opt_quiet && use_curses) {
  2303. mainwin = initscr();
  2304. getmaxyx(mainwin, y, x);
  2305. statuswin = newwin(logstart, x, 0, 0);
  2306. logwin = newwin(y - logcursor, 0, logcursor, 0);
  2307. idlok(logwin, true);
  2308. scrollok(logwin, true);
  2309. leaveok(logwin, true);
  2310. leaveok(statuswin, true);
  2311. test_and_set(&curses_active);
  2312. for (i = 0; i < mining_threads; i++)
  2313. print_status(i);
  2314. }
  2315. /* Now that everything's ready put enough work in the queue */
  2316. for (i = 0; i < opt_queue + mining_threads; i++) {
  2317. if (unlikely(!queue_request())) {
  2318. applog(LOG_ERR, "Failed to queue_request in main");
  2319. return 1;
  2320. }
  2321. }
  2322. /* main loop - simply wait for workio thread to exit */
  2323. pthread_join(thr_info[work_thr_id].pth, NULL);
  2324. applog(LOG_INFO, "workio thread dead, exiting.");
  2325. gettimeofday(&total_tv_end, NULL);
  2326. disable_curses();
  2327. if (!opt_quiet && successful_connect)
  2328. print_summary();
  2329. if (gpu_threads)
  2330. free(gpus);
  2331. if (opt_n_threads)
  2332. free(cpus);
  2333. if (pools)
  2334. free(pools);
  2335. curl_global_cleanup();
  2336. return 0;
  2337. }