main.c 66 KB

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