main.c 68 KB

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