main.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181
  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. #ifndef WIN32
  24. #include <sys/resource.h>
  25. #endif
  26. #include <ccan/opt/opt.h>
  27. #include <jansson.h>
  28. #include <curl/curl.h>
  29. #include "compat.h"
  30. #include "miner.h"
  31. #include "findnonce.h"
  32. #include "ocl.h"
  33. #define PROGRAM_NAME "cgminer"
  34. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  35. #define DEF_RPC_USERNAME "rpcuser"
  36. #define DEF_RPC_PASSWORD "rpcpass"
  37. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  38. #ifdef __linux /* Linux specific policy and affinity management */
  39. #include <sched.h>
  40. static inline void drop_policy(void)
  41. {
  42. struct sched_param param;
  43. #ifdef SCHED_BATCH
  44. #ifdef SCHED_IDLE
  45. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  46. #endif
  47. sched_setscheduler(0, SCHED_BATCH, &param);
  48. #endif
  49. }
  50. static inline void affine_to_cpu(int id, int cpu)
  51. {
  52. cpu_set_t set;
  53. CPU_ZERO(&set);
  54. CPU_SET(cpu, &set);
  55. sched_setaffinity(0, sizeof(&set), &set);
  56. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  57. }
  58. #else
  59. static inline void drop_policy(void)
  60. {
  61. }
  62. static inline void affine_to_cpu(int id, int cpu)
  63. {
  64. }
  65. #endif
  66. enum workio_commands {
  67. WC_GET_WORK,
  68. WC_SUBMIT_WORK,
  69. WC_DIE,
  70. };
  71. struct workio_cmd {
  72. enum workio_commands cmd;
  73. struct thr_info *thr;
  74. union {
  75. struct work *work;
  76. } u;
  77. };
  78. enum sha256_algos {
  79. ALGO_C, /* plain C */
  80. ALGO_4WAY, /* parallel SSE2 */
  81. ALGO_VIA, /* VIA padlock */
  82. ALGO_CRYPTOPP, /* Crypto++ (C) */
  83. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  84. ALGO_SSE2_64, /* SSE2 for x86_64 */
  85. };
  86. static const char *algo_names[] = {
  87. [ALGO_C] = "c",
  88. #ifdef WANT_SSE2_4WAY
  89. [ALGO_4WAY] = "4way",
  90. #endif
  91. #ifdef WANT_VIA_PADLOCK
  92. [ALGO_VIA] = "via",
  93. #endif
  94. [ALGO_CRYPTOPP] = "cryptopp",
  95. #ifdef WANT_CRYPTOPP_ASM32
  96. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  97. #endif
  98. #ifdef WANT_X8664_SSE2
  99. [ALGO_SSE2_64] = "sse2_64",
  100. #endif
  101. };
  102. bool opt_debug = false;
  103. bool opt_protocol = false;
  104. bool want_longpoll = true;
  105. bool have_longpoll = false;
  106. bool use_syslog = false;
  107. static bool opt_quiet = false;
  108. static int opt_retries = -1;
  109. static int opt_fail_pause = 5;
  110. static int opt_log_interval = 5;
  111. bool opt_log_output = false;
  112. static bool opt_dynamic = true;
  113. static int opt_queue = 1;
  114. int opt_vectors;
  115. int opt_worksize;
  116. int opt_scantime = 60;
  117. static const bool opt_time = true;
  118. #ifdef WANT_X8664_SSE2
  119. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  120. #else
  121. static enum sha256_algos opt_algo = ALGO_C;
  122. #endif
  123. static int nDevs;
  124. static int opt_g_threads = 2;
  125. static int opt_device;
  126. static int total_devices;
  127. static bool gpu_devices[16];
  128. static int gpu_threads;
  129. static bool forced_n_threads;
  130. static int opt_n_threads;
  131. static int mining_threads;
  132. static int num_processors;
  133. static int scan_intensity = 4;
  134. static char *rpc_url;
  135. static char *rpc_userpass;
  136. static char *rpc_user, *rpc_pass;
  137. struct thr_info *thr_info;
  138. static int work_thr_id;
  139. int longpoll_thr_id;
  140. static int stage_thr_id;
  141. struct work_restart *work_restart = NULL;
  142. static pthread_mutex_t hash_lock;
  143. static pthread_mutex_t qd_lock;
  144. static pthread_mutex_t stgd_lock;
  145. static pthread_mutex_t curses_lock;
  146. static double total_mhashes_done;
  147. static struct timeval total_tv_start, total_tv_end;
  148. static int accepted, rejected;
  149. int hw_errors;
  150. static int total_queued, total_staged, lp_staged;
  151. static bool localgen = false;
  152. static unsigned int getwork_requested;
  153. static char current_block[37];
  154. static char longpoll_block[37];
  155. static char blank[37];
  156. static void applog_and_exit(const char *fmt, ...)
  157. {
  158. va_list ap;
  159. va_start(ap, fmt);
  160. vapplog(LOG_ERR, fmt, ap);
  161. va_end(ap);
  162. exit(1);
  163. }
  164. /* FIXME: Use asprintf for better errors. */
  165. static char *set_algo(const char *arg, enum sha256_algos *algo)
  166. {
  167. enum sha256_algos i;
  168. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  169. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  170. *algo = i;
  171. return NULL;
  172. }
  173. }
  174. return "Unknown algorithm";
  175. }
  176. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  177. {
  178. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  179. }
  180. static char *set_int_range(const char *arg, int *i, int min, int max)
  181. {
  182. char *err = opt_set_intval(arg, i);
  183. if (err)
  184. return err;
  185. if (*i < min || *i > max)
  186. return "Value out of range";
  187. return NULL;
  188. }
  189. static char *set_int_0_to_9999(const char *arg, int *i)
  190. {
  191. return set_int_range(arg, i, 0, 9999);
  192. }
  193. static char *set_int_0_to_14(const char *arg, int *i)
  194. {
  195. return set_int_range(arg, i, 0, 14);
  196. }
  197. static char *force_nthreads_int(const char *arg, int *i)
  198. {
  199. forced_n_threads = true;
  200. return set_int_range(arg, i, 0, 9999);
  201. }
  202. static char *set_int_0_to_10(const char *arg, int *i)
  203. {
  204. return set_int_range(arg, i, 0, 10);
  205. }
  206. static char *set_int_1_to_10(const char *arg, int *i)
  207. {
  208. return set_int_range(arg, i, 1, 10);
  209. }
  210. static char *set_devices(const char *arg, int *i)
  211. {
  212. char *err = opt_set_intval(arg, i);
  213. if (err)
  214. return err;
  215. if (*i < 0 || *i > 15)
  216. return "Invalid GPU device number";
  217. total_devices++;
  218. gpu_devices[*i] = true;
  219. return NULL;
  220. }
  221. static char *set_url(const char *arg, char **p)
  222. {
  223. opt_set_charp(arg, p);
  224. if (strncmp(arg, "http://", 7) &&
  225. strncmp(arg, "https://", 8))
  226. return "URL must start with http:// or https://";
  227. return NULL;
  228. }
  229. static char *set_vector(const char *arg, int *i)
  230. {
  231. char *err = opt_set_intval(arg, i);
  232. if (err)
  233. return err;
  234. if (*i != 1 && *i != 2 && *i != 4)
  235. return "Valid vectors are 1, 2 or 4";
  236. return NULL;
  237. }
  238. static char *enable_debug(bool *flag)
  239. {
  240. *flag = true;
  241. /* Turn out verbose output, too. */
  242. opt_log_output = true;
  243. return NULL;
  244. }
  245. /* These options are available from config file or commandline */
  246. static struct opt_table opt_config_table[] = {
  247. OPT_WITH_ARG("--algo|-a",
  248. set_algo, show_algo, &opt_algo,
  249. "Specify sha256 implementation:\n"
  250. "\tc\t\tLinux kernel sha256, implemented in C"
  251. #ifdef WANT_SSE2_4WAY
  252. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  253. #endif
  254. #ifdef WANT_VIA_PADLOCK
  255. "\n\tvia\t\tVIA padlock implementation"
  256. #endif
  257. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  258. #ifdef WANT_CRYPTOPP_ASM32
  259. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  260. #endif
  261. #ifdef WANT_X8664_SSE2
  262. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  263. #endif
  264. ),
  265. OPT_WITH_ARG("--cpu-threads|-t",
  266. force_nthreads_int, opt_show_intval, &opt_n_threads,
  267. "Number of miner CPU threads"),
  268. OPT_WITHOUT_ARG("--debug|-D",
  269. enable_debug, &opt_debug,
  270. "Enable debug output"),
  271. #ifdef HAVE_OPENCL
  272. OPT_WITH_ARG("--device|-d",
  273. set_devices, NULL, &opt_device,
  274. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  275. OPT_WITH_ARG("--gpu-threads|-g",
  276. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  277. "Number of threads per GPU (0 - 10)"),
  278. OPT_WITH_ARG("--intensity|-I",
  279. set_int_0_to_14, opt_show_intval, &scan_intensity,
  280. "Intensity of GPU scanning (0 - 14)"),
  281. #endif
  282. OPT_WITH_ARG("--log|-l",
  283. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  284. "Interval in seconds between log output"),
  285. #ifdef HAVE_OPENCL
  286. OPT_WITHOUT_ARG("--no-dynamic|-n",
  287. opt_set_invbool, &opt_dynamic,
  288. "Disable dynamic adjustment of intensity which normally maintains desktop interactivity"),
  289. #endif
  290. OPT_WITHOUT_ARG("--no-longpoll",
  291. opt_set_invbool, &want_longpoll,
  292. "Disable X-Long-Polling support"),
  293. OPT_WITH_ARG("--pass|-p",
  294. opt_set_charp, NULL, &rpc_pass,
  295. "Password for bitcoin JSON-RPC server"),
  296. OPT_WITHOUT_ARG("--protocol-dump|-P",
  297. opt_set_bool, &opt_protocol,
  298. "Verbose dump of protocol-level activities"),
  299. OPT_WITH_ARG("--queue|-Q",
  300. set_int_1_to_10, opt_show_intval, &opt_queue,
  301. "Number of extra work items to queue (1 - 10)"),
  302. OPT_WITHOUT_ARG("--quiet|-q",
  303. opt_set_bool, &opt_quiet,
  304. "Disable per-thread hashmeter output"),
  305. OPT_WITH_ARG("--retries|-r",
  306. opt_set_intval, opt_show_intval, &opt_retries,
  307. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  308. OPT_WITH_ARG("--retry-pause|-R",
  309. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  310. "Number of seconds to pause, between retries"),
  311. OPT_WITH_ARG("--scan-time|-s",
  312. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  313. "Upper bound on time spent scanning current work, in seconds"),
  314. #ifdef HAVE_SYSLOG_H
  315. OPT_WITHOUT_ARG("--syslog",
  316. opt_set_bool, &use_syslog,
  317. "Use system log for output messages (default: standard error)"),
  318. #endif
  319. OPT_WITH_ARG("--url|-o",
  320. set_url, opt_show_charp, &rpc_url,
  321. "URL for bitcoin JSON-RPC server"),
  322. OPT_WITH_ARG("--user|-u",
  323. opt_set_charp, NULL, &rpc_user,
  324. "Username for bitcoin JSON-RPC server"),
  325. #ifdef HAVE_OPENCL
  326. OPT_WITH_ARG("--vectors|-v",
  327. set_vector, NULL, &opt_vectors,
  328. "Override detected optimal vector width (1, 2 or 4)"),
  329. #endif
  330. OPT_WITHOUT_ARG("--verbose",
  331. opt_set_bool, &opt_log_output,
  332. "Log verbose output to stderr as well as status output"),
  333. #ifdef HAVE_OPENCL
  334. OPT_WITH_ARG("--worksize|-w",
  335. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  336. "Override detected optimal worksize"),
  337. #endif
  338. OPT_WITH_ARG("--userpass|-O",
  339. opt_set_charp, NULL, &rpc_userpass,
  340. "Username:Password pair for bitcoin JSON-RPC server"),
  341. OPT_ENDTABLE
  342. };
  343. static char *parse_config(json_t *config)
  344. {
  345. static char err_buf[200];
  346. json_t *val;
  347. struct opt_table *opt;
  348. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  349. char *p, *name;
  350. /* We don't handle subtables. */
  351. assert(!(opt->type & OPT_SUBTABLE));
  352. /* Pull apart the option name(s). */
  353. name = strdup(opt->names);
  354. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  355. char *err;
  356. /* Ignore short options. */
  357. if (p[1] != '-')
  358. continue;
  359. val = json_object_get(config, p+2);
  360. if (!val)
  361. continue;
  362. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  363. err = opt->cb_arg(json_string_value(val),
  364. opt->u.arg);
  365. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  366. err = opt->cb(opt->u.arg);
  367. } else {
  368. err = "Invalid value";
  369. }
  370. if (err) {
  371. sprintf(err_buf, "Parsing JSON option %s: %s",
  372. p, err);
  373. return err_buf;
  374. }
  375. }
  376. free(name);
  377. }
  378. return NULL;
  379. }
  380. static char *load_config(const char *arg, void *unused)
  381. {
  382. json_error_t err;
  383. json_t *config;
  384. config = json_load_file(arg, 0, &err);
  385. if (!json_is_object(config))
  386. return "JSON decode of file failed";
  387. /* Parse the config now, so we can override it. That can keep pointers
  388. * so don't free config object. */
  389. return parse_config(config);
  390. }
  391. static char *print_ndevs_and_exit(int *ndevs)
  392. {
  393. printf("%i", *ndevs);
  394. exit(*ndevs);
  395. }
  396. /* These options are available from commandline only */
  397. static struct opt_table opt_cmdline_table[] = {
  398. OPT_WITH_ARG("--config|-c",
  399. load_config, NULL, NULL,
  400. "Load a JSON-format configuration file\n"
  401. "See example-cfg.json for an example configuration."),
  402. OPT_WITHOUT_ARG("--help|-h",
  403. opt_usage_and_exit,
  404. #ifdef HAVE_OPENCL
  405. "\nBuilt with CPU and GPU mining support.\n\n",
  406. #else
  407. "\nBuilt with CPU mining support only.\n\n",
  408. #endif
  409. "Print this message"),
  410. OPT_WITHOUT_ARG("--ndevs|-e",
  411. print_ndevs_and_exit, &nDevs,
  412. "Enumerate number of detected GPUs and exit"),
  413. OPT_ENDTABLE
  414. };
  415. static bool jobj_binary(const json_t *obj, const char *key,
  416. void *buf, size_t buflen)
  417. {
  418. const char *hexstr;
  419. json_t *tmp;
  420. tmp = json_object_get(obj, key);
  421. if (unlikely(!tmp)) {
  422. applog(LOG_ERR, "JSON key '%s' not found", key);
  423. return false;
  424. }
  425. hexstr = json_string_value(tmp);
  426. if (unlikely(!hexstr)) {
  427. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  428. return false;
  429. }
  430. if (!hex2bin(buf, hexstr, buflen))
  431. return false;
  432. return true;
  433. }
  434. static bool work_decode(const json_t *val, struct work *work)
  435. {
  436. if (unlikely(!jobj_binary(val, "midstate",
  437. work->midstate, sizeof(work->midstate)))) {
  438. applog(LOG_ERR, "JSON inval midstate");
  439. goto err_out;
  440. }
  441. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  442. applog(LOG_ERR, "JSON inval data");
  443. goto err_out;
  444. }
  445. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  446. applog(LOG_ERR, "JSON inval hash1");
  447. goto err_out;
  448. }
  449. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  450. applog(LOG_ERR, "JSON inval target");
  451. goto err_out;
  452. }
  453. memset(work->hash, 0, sizeof(work->hash));
  454. return true;
  455. err_out:
  456. return false;
  457. }
  458. static inline int gpu_from_thr_id(int thr_id)
  459. {
  460. return thr_id % nDevs;
  461. }
  462. static inline int cpu_from_thr_id(int thr_id)
  463. {
  464. return (thr_id - gpu_threads) % num_processors;
  465. }
  466. static WINDOW *mainwin, *statuswin, *logwin;
  467. static double total_secs = 0.1;
  468. static char statusline[256];
  469. static int cpucursor, gpucursor, logstart, logcursor;
  470. static bool curses_active = false;
  471. static struct cgpu_info *gpus, *cpus;
  472. /* Must be called with curses mutex lock held and curses_active */
  473. static inline void __print_status(int thr_id)
  474. {
  475. wmove(statuswin, 0, 0);
  476. wattron(statuswin, A_BOLD);
  477. wprintw(statuswin, " " PROGRAM_NAME " version " VERSION);
  478. wattroff(statuswin, A_BOLD);
  479. wmove(statuswin, 1, 0);
  480. whline(statuswin, '-', 80);
  481. wmove(statuswin, 2,0);
  482. wprintw(statuswin, " %s", statusline);
  483. wclrtoeol(statuswin);
  484. wmove(statuswin, 3, 0);
  485. whline(statuswin, '-', 80);
  486. wmove(statuswin, logstart - 1, 0);
  487. whline(statuswin, '-', 80);
  488. if (thr_id >= 0 && thr_id < gpu_threads) {
  489. int gpu = gpu_from_thr_id(thr_id);
  490. struct cgpu_info *cgpu = &gpus[gpu];
  491. wmove(statuswin, gpucursor + gpu, 0);
  492. wprintw(statuswin, " GPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  493. gpu, cgpu->total_mhashes / total_secs,
  494. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  495. cgpu->efficiency, cgpu->utility);
  496. wclrtoeol(statuswin);
  497. } else if (thr_id >= gpu_threads) {
  498. int cpu = cpu_from_thr_id(thr_id);
  499. struct cgpu_info *cgpu = &cpus[cpu];
  500. wmove(statuswin, cpucursor + cpu, 0);
  501. wprintw(statuswin, " CPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  502. cpu, cgpu->total_mhashes / total_secs,
  503. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  504. cgpu->efficiency, cgpu->utility);
  505. wclrtoeol(statuswin);
  506. }
  507. }
  508. static void print_status(int thr_id)
  509. {
  510. if (unlikely(!curses_active))
  511. return;
  512. pthread_mutex_lock(&curses_lock);
  513. __print_status(thr_id);
  514. wrefresh(statuswin);
  515. pthread_mutex_unlock(&curses_lock);
  516. }
  517. void log_curses(const char *f, va_list ap)
  518. {
  519. if (unlikely(!curses_active))
  520. return;
  521. pthread_mutex_lock(&curses_lock);
  522. vw_printw(logwin, f, ap);
  523. wrefresh(logwin);
  524. pthread_mutex_unlock(&curses_lock);
  525. }
  526. static bool submit_fail = false;
  527. static bool submit_upstream_work(const struct work *work)
  528. {
  529. char *hexstr = NULL;
  530. json_t *val, *res;
  531. char s[345];
  532. bool rc = false;
  533. int thr_id = work->thr_id;
  534. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  535. CURL *curl = curl_easy_init();
  536. if (unlikely(!curl)) {
  537. applog(LOG_ERR, "CURL initialisation failed");
  538. return rc;
  539. }
  540. /* build hex string */
  541. hexstr = bin2hex(work->data, sizeof(work->data));
  542. if (unlikely(!hexstr)) {
  543. applog(LOG_ERR, "submit_upstream_work OOM");
  544. goto out_nofree;
  545. }
  546. /* build JSON-RPC request */
  547. sprintf(s,
  548. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  549. hexstr);
  550. if (opt_debug)
  551. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  552. /* issue JSON-RPC request */
  553. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  554. if (unlikely(!val)) {
  555. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  556. if (!submit_fail) {
  557. submit_fail = true;
  558. applog(LOG_WARNING, "Upstream communication failure, caching submissions");
  559. }
  560. goto out;
  561. } else if (submit_fail) {
  562. submit_fail = false;
  563. applog(LOG_WARNING, "Upstream communication resumed, submitting work");
  564. }
  565. res = json_object_get(val, "result");
  566. /* Theoretically threads could race when modifying accepted and
  567. * rejected values but the chance of two submits completing at the
  568. * same time is zero so there is no point adding extra locking */
  569. if (json_is_true(res)) {
  570. cgpu->accepted++;
  571. accepted++;
  572. if (opt_debug)
  573. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  574. if (!opt_quiet)
  575. applog(LOG_WARNING, "Share accepted from %sPU %d thread %d",
  576. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  577. } else {
  578. cgpu->rejected++;
  579. rejected++;
  580. if (opt_debug)
  581. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  582. if (!opt_quiet)
  583. applog(LOG_WARNING, "Share rejected from %sPU %d thread %d",
  584. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  585. }
  586. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  587. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  588. if (!opt_quiet)
  589. print_status(thr_id);
  590. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  591. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  592. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  593. json_decref(val);
  594. rc = true;
  595. out:
  596. free(hexstr);
  597. out_nofree:
  598. curl_easy_cleanup(curl);
  599. return rc;
  600. }
  601. static const char *rpc_req =
  602. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  603. static bool get_upstream_work(struct work *work)
  604. {
  605. json_t *val;
  606. bool rc = false;
  607. CURL *curl = curl_easy_init();
  608. if (unlikely(!curl)) {
  609. applog(LOG_ERR, "CURL initialisation failed");
  610. return rc;
  611. }
  612. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  613. want_longpoll, false);
  614. if (unlikely(!val)) {
  615. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  616. goto out;
  617. }
  618. rc = work_decode(json_object_get(val, "result"), work);
  619. json_decref(val);
  620. out:
  621. curl_easy_cleanup(curl);
  622. return rc;
  623. }
  624. static void workio_cmd_free(struct workio_cmd *wc)
  625. {
  626. if (!wc)
  627. return;
  628. switch (wc->cmd) {
  629. case WC_SUBMIT_WORK:
  630. free(wc->u.work);
  631. break;
  632. default: /* do nothing */
  633. break;
  634. }
  635. memset(wc, 0, sizeof(*wc)); /* poison */
  636. free(wc);
  637. }
  638. static void kill_work(void)
  639. {
  640. struct workio_cmd *wc;
  641. applog(LOG_INFO, "Received kill message");
  642. wc = calloc(1, sizeof(*wc));
  643. if (unlikely(!wc)) {
  644. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  645. /* We're just trying to die anyway, so forget graceful */
  646. exit (1);
  647. }
  648. wc->cmd = WC_DIE;
  649. wc->thr = 0;
  650. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  651. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  652. exit (1);
  653. }
  654. }
  655. static void *get_work_thread(void *userdata)
  656. {
  657. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  658. struct work *ret_work;
  659. int failures = 0;
  660. pthread_detach(pthread_self());
  661. ret_work = calloc(1, sizeof(*ret_work));
  662. if (unlikely(!ret_work)) {
  663. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  664. kill_work();
  665. goto out;
  666. }
  667. /* obtain new work from bitcoin via JSON-RPC */
  668. while (!get_upstream_work(ret_work)) {
  669. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  670. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  671. free(ret_work);
  672. kill_work();
  673. goto out;
  674. }
  675. /* pause, then restart work-request loop */
  676. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  677. opt_fail_pause);
  678. sleep(opt_fail_pause);
  679. }
  680. /* send work to requesting thread */
  681. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  682. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  683. kill_work();
  684. free(ret_work);
  685. }
  686. out:
  687. workio_cmd_free(wc);
  688. return NULL;
  689. }
  690. static bool workio_get_work(struct workio_cmd *wc)
  691. {
  692. pthread_t get_thread;
  693. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  694. applog(LOG_ERR, "Failed to create get_work_thread");
  695. return false;
  696. }
  697. return true;
  698. }
  699. static void *submit_work_thread(void *userdata)
  700. {
  701. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  702. int failures = 0;
  703. char *hexstr;
  704. pthread_detach(pthread_self());
  705. hexstr = bin2hex(wc->u.work->data, 36);
  706. if (unlikely(!hexstr)) {
  707. applog(LOG_ERR, "submit_work_thread OOM");
  708. goto out;
  709. }
  710. if (unlikely(strncmp(hexstr, current_block, 36))) {
  711. applog(LOG_WARNING, "Stale work detected, discarding");
  712. goto out_free;
  713. }
  714. /* submit solution to bitcoin via JSON-RPC */
  715. while (!submit_upstream_work(wc->u.work)) {
  716. if (unlikely(strncmp(hexstr, current_block, 36))) {
  717. applog(LOG_WARNING, "Stale work detected, discarding");
  718. goto out_free;
  719. }
  720. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  721. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  722. kill_work();
  723. goto out_free;
  724. }
  725. /* pause, then restart work-request loop */
  726. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  727. opt_fail_pause);
  728. sleep(opt_fail_pause);
  729. }
  730. out_free:
  731. free(hexstr);
  732. out:
  733. workio_cmd_free(wc);
  734. return NULL;
  735. }
  736. static bool workio_submit_work(struct workio_cmd *wc)
  737. {
  738. pthread_t submit_thread;
  739. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  740. applog(LOG_ERR, "Failed to create submit_work_thread");
  741. return false;
  742. }
  743. return true;
  744. }
  745. static void inc_staged(int inc, bool lp)
  746. {
  747. pthread_mutex_lock(&stgd_lock);
  748. if (lp) {
  749. lp_staged += inc;
  750. total_staged += inc;
  751. } else if (lp_staged)
  752. lp_staged--;
  753. else
  754. total_staged += inc;
  755. pthread_mutex_unlock(&stgd_lock);
  756. }
  757. static void dec_staged(int inc)
  758. {
  759. pthread_mutex_lock(&stgd_lock);
  760. if (lp_staged)
  761. lp_staged -= inc;
  762. total_staged -= inc;
  763. pthread_mutex_unlock(&stgd_lock);
  764. }
  765. static int requests_staged(void)
  766. {
  767. int ret;
  768. pthread_mutex_lock(&stgd_lock);
  769. ret = total_staged;
  770. pthread_mutex_unlock(&stgd_lock);
  771. return ret;
  772. }
  773. static void *stage_thread(void *userdata)
  774. {
  775. struct thr_info *mythr = userdata;
  776. bool ok = true;
  777. while (ok) {
  778. struct work *work = NULL;
  779. char *hexstr;
  780. work = tq_pop(mythr->q, NULL);
  781. if (unlikely(!work)) {
  782. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  783. ok = false;
  784. break;
  785. }
  786. hexstr = bin2hex(work->data, 36);
  787. if (unlikely(!hexstr)) {
  788. applog(LOG_ERR, "stage_thread OOM");
  789. break;
  790. }
  791. /* current_block is blanked out on successful longpoll */
  792. if (likely(strncmp(current_block, blank, 36))) {
  793. if (unlikely(strncmp(hexstr, current_block, 36))) {
  794. if (want_longpoll)
  795. applog(LOG_WARNING, "New block detected on network before receiving longpoll, flushing work queue");
  796. else
  797. applog(LOG_WARNING, "New block detected on network, flushing work queue");
  798. /* As we can't flush the work from here, signal
  799. * the wakeup thread to restart all the
  800. * threads */
  801. work_restart[stage_thr_id].restart = 1;
  802. }
  803. } else
  804. memcpy(longpoll_block, hexstr, 36);
  805. memcpy(current_block, hexstr, 36);
  806. free(hexstr);
  807. if (unlikely(!tq_push(thr_info[0].q, work))) {
  808. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  809. ok = false;
  810. break;
  811. }
  812. inc_staged(1, false);
  813. }
  814. tq_freeze(mythr->q);
  815. return NULL;
  816. }
  817. static void *workio_thread(void *userdata)
  818. {
  819. struct thr_info *mythr = userdata;
  820. bool ok = true;
  821. while (ok) {
  822. struct workio_cmd *wc;
  823. /* wait for workio_cmd sent to us, on our queue */
  824. wc = tq_pop(mythr->q, NULL);
  825. if (unlikely(!wc)) {
  826. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  827. ok = false;
  828. break;
  829. }
  830. /* process workio_cmd */
  831. switch (wc->cmd) {
  832. case WC_GET_WORK:
  833. ok = workio_get_work(wc);
  834. break;
  835. case WC_SUBMIT_WORK:
  836. ok = workio_submit_work(wc);
  837. break;
  838. case WC_DIE:
  839. default:
  840. ok = false;
  841. break;
  842. }
  843. }
  844. tq_freeze(mythr->q);
  845. return NULL;
  846. }
  847. static void hashmeter(int thr_id, struct timeval *diff,
  848. unsigned long hashes_done)
  849. {
  850. struct timeval temp_tv_end, total_diff;
  851. double khashes, secs;
  852. double local_secs;
  853. double utility, efficiency = 0.0;
  854. static double local_mhashes_done = 0;
  855. static double rolling_local = 0;
  856. double local_mhashes = (double)hashes_done / 1000000.0;
  857. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  858. /* Update the last time this thread reported in */
  859. if (thr_id >= 0)
  860. gettimeofday(&thr_info[thr_id].last, NULL);
  861. /* Don't bother calculating anything if we're not displaying it */
  862. if (opt_quiet || !opt_log_interval)
  863. return;
  864. khashes = hashes_done / 1000.0;
  865. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  866. if (thr_id >= 0 && secs) {
  867. /* So we can call hashmeter from a non worker thread */
  868. if (opt_debug)
  869. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  870. thr_id, hashes_done, hashes_done / secs);
  871. cgpu->local_mhashes += local_mhashes;
  872. cgpu->total_mhashes += local_mhashes;
  873. }
  874. /* Totals are updated by all threads so can race without locking */
  875. pthread_mutex_lock(&hash_lock);
  876. gettimeofday(&temp_tv_end, NULL);
  877. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  878. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  879. total_mhashes_done += local_mhashes;
  880. local_mhashes_done += local_mhashes;
  881. if (total_diff.tv_sec < opt_log_interval)
  882. /* Only update the total every opt_log_interval seconds */
  883. goto out_unlock;
  884. gettimeofday(&total_tv_end, NULL);
  885. /* Use a rolling average by faking an exponential decay over 5 * log */
  886. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  887. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  888. total_secs = (double)total_diff.tv_sec +
  889. ((double)total_diff.tv_usec / 1000000.0);
  890. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  891. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  892. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  893. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  894. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  895. print_status(thr_id);
  896. applog(LOG_INFO, "%s", statusline);
  897. local_mhashes_done = 0;
  898. out_unlock:
  899. pthread_mutex_unlock(&hash_lock);
  900. }
  901. /* This is overkill, but at least we'll know accurately how much work is
  902. * queued to prevent ever being left without work */
  903. static void inc_queued(void)
  904. {
  905. pthread_mutex_lock(&qd_lock);
  906. total_queued++;
  907. pthread_mutex_unlock(&qd_lock);
  908. }
  909. static void dec_queued(void)
  910. {
  911. pthread_mutex_lock(&qd_lock);
  912. total_queued--;
  913. pthread_mutex_unlock(&qd_lock);
  914. dec_staged(1);
  915. }
  916. static int requests_queued(void)
  917. {
  918. int ret;
  919. pthread_mutex_lock(&qd_lock);
  920. ret = total_queued;
  921. pthread_mutex_unlock(&qd_lock);
  922. return ret;
  923. }
  924. /* All work is queued flagged as being for thread 0 and then the mining thread
  925. * flags it as its own */
  926. static bool queue_request(void)
  927. {
  928. struct thr_info *thr = &thr_info[0];
  929. struct workio_cmd *wc;
  930. /* fill out work request message */
  931. wc = calloc(1, sizeof(*wc));
  932. if (unlikely(!wc)) {
  933. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  934. return false;
  935. }
  936. wc->cmd = WC_GET_WORK;
  937. wc->thr = thr;
  938. /* send work request to workio thread */
  939. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  940. applog(LOG_ERR, "Failed to tq_push in queue_request");
  941. workio_cmd_free(wc);
  942. return false;
  943. }
  944. inc_queued();
  945. return true;
  946. }
  947. static bool discard_request(void)
  948. {
  949. struct thr_info *thr = &thr_info[0];
  950. struct work *work_heap;
  951. /* Just in case we fell in a hole and missed a queue filling */
  952. if (unlikely(!requests_queued())) {
  953. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  954. return true;
  955. }
  956. work_heap = tq_pop(thr->q, NULL);
  957. if (unlikely(!work_heap)) {
  958. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  959. return false;
  960. }
  961. free(work_heap);
  962. dec_queued();
  963. return true;
  964. }
  965. static void flush_requests(bool longpoll)
  966. {
  967. int i, extra;
  968. extra = requests_queued();
  969. /* When flushing from longpoll, we don't know the new work yet. When
  970. * not flushing from longpoll, the first work item is valid so do not
  971. * discard it */
  972. if (longpoll)
  973. memcpy(current_block, blank, 36);
  974. else
  975. extra--;
  976. /* Temporarily increase the staged count so that get_work thinks there
  977. * is work available instead of making threads reuse existing work */
  978. if (extra >= mining_threads)
  979. inc_staged(mining_threads, true);
  980. else
  981. inc_staged(extra, true);
  982. for (i = 0; i < extra; i++) {
  983. /* Queue a whole batch of new requests */
  984. if (unlikely(!queue_request())) {
  985. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  986. kill_work();
  987. break;
  988. }
  989. /* Pop off the old requests. Cancelling the requests would be better
  990. * but is tricky */
  991. if (unlikely(!discard_request())) {
  992. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  993. kill_work();
  994. break;
  995. }
  996. }
  997. }
  998. static bool get_work(struct work *work, bool queued)
  999. {
  1000. struct timeval now;
  1001. struct timespec abstime = {};
  1002. struct thr_info *thr = &thr_info[0];
  1003. struct work *work_heap;
  1004. bool ret = false;
  1005. int failures = 0;
  1006. getwork_requested++;
  1007. retry:
  1008. gettimeofday(&now, NULL);
  1009. abstime.tv_sec = now.tv_sec + 60;
  1010. if (unlikely(!queued && !queue_request())) {
  1011. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1012. goto out;
  1013. }
  1014. if (!requests_staged()) {
  1015. uint32_t *work_ntime;
  1016. uint32_t ntime;
  1017. /* Only print this message once each time we shift to localgen */
  1018. if (!localgen)
  1019. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1020. localgen = true;
  1021. work_ntime = (uint32_t *)(work->data + 68);
  1022. ntime = be32toh(*work_ntime);
  1023. ntime++;
  1024. *work_ntime = htobe32(ntime);
  1025. ret = true;
  1026. goto out;
  1027. } else if (localgen) {
  1028. localgen = false;
  1029. applog(LOG_WARNING, "Resumed retrieving work from server");
  1030. }
  1031. /* Wait for 1st response, or get cached response. We really should
  1032. * never time out on the pop request but something might go amiss :/
  1033. */
  1034. work_heap = tq_pop(thr->q, &abstime);
  1035. if (unlikely(!work_heap)) {
  1036. applog(LOG_INFO, "Failed to tq_pop in get_work");
  1037. goto out;
  1038. }
  1039. dec_queued();
  1040. memcpy(work, work_heap, sizeof(*work));
  1041. ret = true;
  1042. free(work_heap);
  1043. out:
  1044. if (unlikely(ret == false)) {
  1045. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1046. applog(LOG_ERR, "Failed %d times to get_work");
  1047. return ret;
  1048. }
  1049. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1050. sleep(opt_fail_pause);
  1051. goto retry;
  1052. }
  1053. return ret;
  1054. }
  1055. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1056. {
  1057. struct workio_cmd *wc;
  1058. /* fill out work request message */
  1059. wc = calloc(1, sizeof(*wc));
  1060. if (unlikely(!wc)) {
  1061. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1062. return false;
  1063. }
  1064. wc->u.work = malloc(sizeof(*work_in));
  1065. if (unlikely(!wc->u.work)) {
  1066. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1067. goto err_out;
  1068. }
  1069. wc->cmd = WC_SUBMIT_WORK;
  1070. wc->thr = thr;
  1071. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1072. /* send solution to workio thread */
  1073. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1074. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1075. goto err_out;
  1076. }
  1077. return true;
  1078. err_out:
  1079. workio_cmd_free(wc);
  1080. return false;
  1081. }
  1082. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1083. {
  1084. work->data[64+12+0] = (nonce>>0) & 0xff;
  1085. work->data[64+12+1] = (nonce>>8) & 0xff;
  1086. work->data[64+12+2] = (nonce>>16) & 0xff;
  1087. work->data[64+12+3] = (nonce>>24) & 0xff;
  1088. return submit_work_sync(thr, work);
  1089. }
  1090. static void *miner_thread(void *userdata)
  1091. {
  1092. struct thr_info *mythr = userdata;
  1093. const int thr_id = mythr->id;
  1094. uint32_t max_nonce = 0xffffff;
  1095. bool needs_work = true;
  1096. /* Try to cycle approximately 5 times before each log update */
  1097. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1098. /* Request the next work item at 2/3 of the scantime */
  1099. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1100. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1101. bool requested = true;
  1102. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1103. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1104. * and if that fails, then SCHED_BATCH. No need for this to be an
  1105. * error if it fails */
  1106. setpriority(PRIO_PROCESS, 0, 19);
  1107. drop_policy();
  1108. /* Cpu affinity only makes sense if the number of threads is a multiple
  1109. * of the number of CPUs */
  1110. if (!(opt_n_threads % num_processors))
  1111. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  1112. while (1) {
  1113. struct work work __attribute__((aligned(128)));
  1114. unsigned long hashes_done;
  1115. struct timeval tv_workstart, tv_start, tv_end, diff;
  1116. uint64_t max64;
  1117. bool rc;
  1118. if (needs_work) {
  1119. gettimeofday(&tv_workstart, NULL);
  1120. /* obtain new work from internal workio thread */
  1121. if (unlikely(!get_work(&work, requested))) {
  1122. applog(LOG_ERR, "work retrieval failed, exiting "
  1123. "mining thread %d", thr_id);
  1124. goto out;
  1125. }
  1126. mythr->cgpu->getworks++;
  1127. work.thr_id = thr_id;
  1128. needs_work = requested = false;
  1129. work.blk.nonce = 0;
  1130. }
  1131. hashes_done = 0;
  1132. gettimeofday(&tv_start, NULL);
  1133. /* scan nonces for a proof-of-work hash */
  1134. switch (opt_algo) {
  1135. case ALGO_C:
  1136. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1137. work.hash1, work.hash, work.target,
  1138. max_nonce, &hashes_done,
  1139. work.blk.nonce);
  1140. break;
  1141. #ifdef WANT_X8664_SSE2
  1142. case ALGO_SSE2_64: {
  1143. unsigned int rc5 =
  1144. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1145. work.hash1, work.hash,
  1146. work.target,
  1147. max_nonce, &hashes_done,
  1148. work.blk.nonce);
  1149. rc = (rc5 == -1) ? false : true;
  1150. }
  1151. break;
  1152. #endif
  1153. #ifdef WANT_SSE2_4WAY
  1154. case ALGO_4WAY: {
  1155. unsigned int rc4 =
  1156. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1157. work.hash1, work.hash,
  1158. work.target,
  1159. max_nonce, &hashes_done,
  1160. work.blk.nonce);
  1161. rc = (rc4 == -1) ? false : true;
  1162. }
  1163. break;
  1164. #endif
  1165. #ifdef WANT_VIA_PADLOCK
  1166. case ALGO_VIA:
  1167. rc = scanhash_via(thr_id, work.data, work.target,
  1168. max_nonce, &hashes_done,
  1169. work.blk.nonce);
  1170. break;
  1171. #endif
  1172. case ALGO_CRYPTOPP:
  1173. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1174. work.hash1, work.hash, work.target,
  1175. max_nonce, &hashes_done,
  1176. work.blk.nonce);
  1177. break;
  1178. #ifdef WANT_CRYPTOPP_ASM32
  1179. case ALGO_CRYPTOPP_ASM32:
  1180. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1181. work.hash1, work.hash, work.target,
  1182. max_nonce, &hashes_done,
  1183. work.blk.nonce);
  1184. break;
  1185. #endif
  1186. default:
  1187. /* should never happen */
  1188. goto out;
  1189. }
  1190. /* record scanhash elapsed time */
  1191. gettimeofday(&tv_end, NULL);
  1192. timeval_subtract(&diff, &tv_end, &tv_start);
  1193. hashes_done -= work.blk.nonce;
  1194. hashmeter(thr_id, &diff, hashes_done);
  1195. work.blk.nonce += hashes_done;
  1196. /* adjust max_nonce to meet target cycle time */
  1197. if (diff.tv_usec > 500000)
  1198. diff.tv_sec++;
  1199. if (diff.tv_sec && diff.tv_sec != cycle) {
  1200. max64 = work.blk.nonce +
  1201. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1202. } else
  1203. max64 = work.blk.nonce + hashes_done;
  1204. if (max64 > 0xfffffffaULL)
  1205. max64 = 0xfffffffaULL;
  1206. max_nonce = max64;
  1207. /* if nonce found, submit work */
  1208. if (unlikely(rc)) {
  1209. if (opt_debug)
  1210. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  1211. if (unlikely(!submit_work_sync(mythr, &work))) {
  1212. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1213. break;
  1214. }
  1215. work.blk.nonce += 4;
  1216. }
  1217. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1218. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1219. if (unlikely(!queue_request())) {
  1220. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1221. goto out;
  1222. }
  1223. requested = true;
  1224. }
  1225. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1226. work.blk.nonce >= MAXTHREADS - hashes_done)
  1227. needs_work = true;
  1228. }
  1229. out:
  1230. tq_freeze(mythr->q);
  1231. return NULL;
  1232. }
  1233. enum {
  1234. STAT_SLEEP_INTERVAL = 1,
  1235. STAT_CTR_INTERVAL = 10000000,
  1236. FAILURE_INTERVAL = 30,
  1237. };
  1238. #ifdef HAVE_OPENCL
  1239. static _clState *clStates[16];
  1240. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1241. {
  1242. cl_kernel *kernel = &clState->kernel;
  1243. cl_int status = 0;
  1244. int num = 0;
  1245. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1246. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1247. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1248. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1249. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1250. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1251. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1252. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1253. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1254. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1255. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1256. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1257. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1258. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1259. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1260. if (clState->hasBitAlign == true) {
  1261. /* Parameters for phatk kernel */
  1262. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1263. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1264. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1265. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1266. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1267. } else {
  1268. /* Parameters for poclbm kernel */
  1269. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1270. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1271. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1272. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1273. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1274. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1275. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1276. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1277. }
  1278. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1279. (void *)&clState->outputBuffer);
  1280. return status;
  1281. }
  1282. static void set_threads_hashes(int vectors, int *threads, int *hashes, size_t *globalThreads)
  1283. {
  1284. *globalThreads = *threads = 1 << (15 + scan_intensity);
  1285. *hashes = *threads * vectors;
  1286. }
  1287. static void *gpuminer_thread(void *userdata)
  1288. {
  1289. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1290. struct timeval tv_start, tv_end, diff;
  1291. struct thr_info *mythr = userdata;
  1292. const int thr_id = mythr->id;
  1293. uint32_t *res, *blank_res;
  1294. size_t globalThreads[1];
  1295. size_t localThreads[1];
  1296. cl_int status;
  1297. _clState *clState = clStates[thr_id];
  1298. const cl_kernel *kernel = &clState->kernel;
  1299. struct work *work = malloc(sizeof(struct work));
  1300. unsigned int threads = 1 << (15 + scan_intensity);
  1301. unsigned const int vectors = clState->preferred_vwidth;
  1302. unsigned int hashes = threads * vectors;
  1303. unsigned int hashes_done = 0;
  1304. /* Request the next work item at 2/3 of the scantime */
  1305. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1306. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1307. bool requested = true;
  1308. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1309. res = calloc(BUFFERSIZE, 1);
  1310. blank_res = calloc(BUFFERSIZE, 1);
  1311. if (!res || !blank_res) {
  1312. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1313. goto out;
  1314. }
  1315. gettimeofday(&tv_start, NULL);
  1316. globalThreads[0] = threads;
  1317. localThreads[0] = clState->work_size;
  1318. diff.tv_sec = ~0UL;
  1319. gettimeofday(&tv_end, NULL);
  1320. while (1) {
  1321. struct timeval tv_workstart, tv_gpustart, tv_gpuend;
  1322. suseconds_t gpu_us;
  1323. double gpu_ms_average;
  1324. gettimeofday(&tv_gpustart, NULL);
  1325. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  1326. /* This finish flushes the readbuffer set with CL_FALSE later */
  1327. clFinish(clState->commandQueue);
  1328. gettimeofday(&tv_gpuend, NULL);
  1329. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  1330. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  1331. gpu_ms_average = ((gpu_us / 1000) + gpu_ms_average * 0.9) / 1.9;
  1332. if (opt_dynamic) {
  1333. /* Try to not let the GPU be out for longer than 6ms, but
  1334. * increase intensity when the system is idle, unless
  1335. * dynamic is disabled. */
  1336. if (gpu_ms_average > 7) {
  1337. if (scan_intensity > 0)
  1338. scan_intensity--;
  1339. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1340. } else if (gpu_ms_average < 3) {
  1341. if (scan_intensity < 14)
  1342. scan_intensity++;
  1343. set_threads_hashes(vectors, &threads, &hashes, globalThreads);
  1344. }
  1345. }
  1346. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  1347. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1348. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1349. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1350. if (unlikely(status != CL_SUCCESS))
  1351. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1352. memset(res, 0, BUFFERSIZE);
  1353. gettimeofday(&tv_workstart, NULL);
  1354. /* obtain new work from internal workio thread */
  1355. if (unlikely(!get_work(work, requested))) {
  1356. applog(LOG_ERR, "work retrieval failed, exiting "
  1357. "gpu mining thread %d", mythr->id);
  1358. goto out;
  1359. }
  1360. mythr->cgpu->getworks++;
  1361. work->thr_id = thr_id;
  1362. requested = false;
  1363. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1364. work->blk.nonce = 0;
  1365. work_restart[thr_id].restart = 0;
  1366. if (opt_debug)
  1367. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1368. /* Flushes the writebuffer set with CL_FALSE above */
  1369. clFinish(clState->commandQueue);
  1370. }
  1371. status = queue_kernel_parameters(clState, &work->blk);
  1372. if (unlikely(status != CL_SUCCESS))
  1373. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1374. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1375. if (res[MAXBUFFERS]) {
  1376. /* Clear the buffer again */
  1377. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1378. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1379. if (unlikely(status != CL_SUCCESS))
  1380. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1381. if (opt_debug)
  1382. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  1383. postcalc_hash_async(mythr, work, res);
  1384. memset(res, 0, BUFFERSIZE);
  1385. clFinish(clState->commandQueue);
  1386. }
  1387. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1388. globalThreads, localThreads, 0, NULL, NULL);
  1389. if (unlikely(status != CL_SUCCESS))
  1390. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1391. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1392. BUFFERSIZE, res, 0, NULL, NULL);
  1393. if (unlikely(status != CL_SUCCESS))
  1394. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1395. gettimeofday(&tv_end, NULL);
  1396. timeval_subtract(&diff, &tv_end, &tv_start);
  1397. hashes_done += hashes;
  1398. work->blk.nonce += hashes;
  1399. if (diff.tv_usec > 500000)
  1400. diff.tv_sec++;
  1401. if (diff.tv_sec >= cycle) {
  1402. hashmeter(thr_id, &diff, hashes_done);
  1403. gettimeofday(&tv_start, NULL);
  1404. hashes_done = 0;
  1405. }
  1406. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1407. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1408. if (unlikely(!queue_request())) {
  1409. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1410. goto out;
  1411. }
  1412. requested = true;
  1413. }
  1414. }
  1415. out:
  1416. tq_freeze(mythr->q);
  1417. return NULL;
  1418. }
  1419. #endif /* HAVE_OPENCL */
  1420. static void restart_threads(bool longpoll)
  1421. {
  1422. int i;
  1423. /* Discard old queued requests and get new ones */
  1424. flush_requests(longpoll);
  1425. for (i = 0; i < mining_threads; i++)
  1426. work_restart[i].restart = 1;
  1427. }
  1428. static void *longpoll_thread(void *userdata)
  1429. {
  1430. struct thr_info *mythr = userdata;
  1431. CURL *curl = NULL;
  1432. char *copy_start, *hdr_path, *lp_url = NULL;
  1433. bool need_slash = false;
  1434. int failures = 0;
  1435. hdr_path = tq_pop(mythr->q, NULL);
  1436. if (!hdr_path)
  1437. goto out;
  1438. /* full URL */
  1439. if (strstr(hdr_path, "://")) {
  1440. lp_url = hdr_path;
  1441. hdr_path = NULL;
  1442. }
  1443. /* absolute path, on current server */
  1444. else {
  1445. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1446. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1447. need_slash = true;
  1448. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1449. if (!lp_url)
  1450. goto out;
  1451. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1452. }
  1453. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1454. curl = curl_easy_init();
  1455. if (unlikely(!curl)) {
  1456. applog(LOG_ERR, "CURL initialisation failed");
  1457. goto out;
  1458. }
  1459. while (1) {
  1460. struct timeval start, end;
  1461. json_t *val;
  1462. gettimeofday(&start, NULL);
  1463. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1464. false, true);
  1465. if (likely(val)) {
  1466. failures = 0;
  1467. json_decref(val);
  1468. /* Keep track of who ordered a restart_threads to make
  1469. * sure it's only done once per new block */
  1470. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1471. !strncmp(longpoll_block, current_block, 36))) {
  1472. applog(LOG_WARNING, "LONGPOLL detected new block on network, flushing work queue");
  1473. restart_threads(true);
  1474. } else
  1475. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  1476. } else {
  1477. /* Some pools regularly drop the longpoll request so
  1478. * only see this as longpoll failure if it happens
  1479. * immediately and just restart it the rest of the
  1480. * time. */
  1481. gettimeofday(&end, NULL);
  1482. if (end.tv_sec - start.tv_sec > 30)
  1483. continue;
  1484. if (failures++ < 10) {
  1485. sleep(30);
  1486. applog(LOG_WARNING,
  1487. "longpoll failed, sleeping for 30s");
  1488. } else {
  1489. applog(LOG_ERR,
  1490. "longpoll failed, ending thread");
  1491. goto out;
  1492. }
  1493. }
  1494. memcpy(longpoll_block, current_block, 36);
  1495. }
  1496. out:
  1497. free(hdr_path);
  1498. free(lp_url);
  1499. tq_freeze(mythr->q);
  1500. if (curl)
  1501. curl_easy_cleanup(curl);
  1502. return NULL;
  1503. }
  1504. static void reinit_cputhread(int thr_id)
  1505. {
  1506. int cpu = cpu_from_thr_id(thr_id);
  1507. struct thr_info *thr = &thr_info[thr_id];
  1508. tq_freeze(thr->q);
  1509. if (unlikely(pthread_cancel(thr->pth))) {
  1510. applog(LOG_ERR, "Failed to pthread_cancel in reinit_gputhread");
  1511. goto failed_out;
  1512. }
  1513. if (unlikely(pthread_join(thr->pth, NULL))) {
  1514. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1515. goto failed_out;
  1516. }
  1517. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  1518. tq_thaw(thr->q);
  1519. gettimeofday(&thr->last, NULL);
  1520. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1521. applog(LOG_ERR, "thread %d create failed", thr_id);
  1522. goto failed_out;
  1523. }
  1524. return;
  1525. failed_out:
  1526. kill_work();
  1527. }
  1528. #ifdef HAVE_OPENCL
  1529. static void reinit_gputhread(int thr_id)
  1530. {
  1531. int gpu = gpu_from_thr_id(thr_id);
  1532. struct thr_info *thr = &thr_info[thr_id];
  1533. char name[256];
  1534. tq_freeze(thr->q);
  1535. if (unlikely(pthread_cancel(thr->pth))) {
  1536. applog(LOG_ERR, "Failed to pthread_cancel in reinit_gputhread");
  1537. goto failed_out;
  1538. }
  1539. if (unlikely(pthread_join(thr->pth, NULL))) {
  1540. applog(LOG_ERR, "Failed to pthread_join in reinit_gputhread");
  1541. goto failed_out;
  1542. }
  1543. free(clStates[thr_id]);
  1544. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  1545. tq_thaw(thr->q);
  1546. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  1547. if (!clStates[thr_id]) {
  1548. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  1549. goto failed_out;
  1550. }
  1551. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1552. gettimeofday(&thr->last, NULL);
  1553. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1554. applog(LOG_ERR, "thread %d create failed", thr_id);
  1555. goto failed_out;
  1556. }
  1557. return;
  1558. failed_out:
  1559. kill_work();
  1560. }
  1561. static void reinit_thread(int thr_id)
  1562. {
  1563. if (thr_id < gpu_threads)
  1564. reinit_gputhread(thr_id);
  1565. else
  1566. reinit_cputhread(thr_id);
  1567. }
  1568. #else
  1569. static void reinit_thread(int thr_id)
  1570. {
  1571. reinit_cputhread(thr_id);
  1572. }
  1573. #endif
  1574. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  1575. * the screen at regular intervals, and restarts threads if they appear to have
  1576. * died. */
  1577. static void *watchdog_thread(void *userdata)
  1578. {
  1579. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1580. struct timeval zero_tv;
  1581. memset(&zero_tv, 0, sizeof(struct timeval));
  1582. while (1) {
  1583. int x, y, logx, logy, i;
  1584. struct timeval now;
  1585. sleep(interval);
  1586. if (requests_queued() < opt_queue)
  1587. queue_request();
  1588. hashmeter(-1, &zero_tv, 0);
  1589. if (curses_active) {
  1590. pthread_mutex_lock(&curses_lock);
  1591. getmaxyx(mainwin, y, x);
  1592. getmaxyx(logwin, logy, logx);
  1593. y -= logcursor;
  1594. /* Detect screen size change */
  1595. if (x != logx || y != logy)
  1596. wresize(logwin, y, x);
  1597. for (i = 0; i < mining_threads; i++)
  1598. __print_status(i);
  1599. redrawwin(logwin);
  1600. redrawwin(statuswin);
  1601. pthread_mutex_unlock(&curses_lock);
  1602. }
  1603. if (unlikely(work_restart[stage_thr_id].restart)) {
  1604. restart_threads(false);
  1605. work_restart[stage_thr_id].restart = 0;
  1606. }
  1607. gettimeofday(&now, NULL);
  1608. for (i = 0; i < mining_threads; i++) {
  1609. struct thr_info *thr = &thr_info[i];
  1610. if (now.tv_sec - thr->last.tv_sec > 60) {
  1611. applog(LOG_ERR, "Attempting to restart thread %d, idle for more than 60 seconds", i);
  1612. reinit_thread(i);
  1613. applog(LOG_WARNING, "Thread %d restarted", i);
  1614. }
  1615. }
  1616. }
  1617. return NULL;
  1618. }
  1619. int main (int argc, char *argv[])
  1620. {
  1621. struct thr_info *thr;
  1622. unsigned int i, j = 0, x, y;
  1623. char name[256];
  1624. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1625. return 1;
  1626. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1627. return 1;
  1628. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1629. return 1;
  1630. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  1631. return 1;
  1632. for (i = 0; i < 36; i++) {
  1633. strcat(blank, "0");
  1634. strcat(current_block, "0");
  1635. strcat(longpoll_block, "0");
  1636. }
  1637. #ifdef WIN32
  1638. opt_n_threads = num_processors = 1;
  1639. #else
  1640. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1641. opt_n_threads = num_processors;
  1642. #endif /* !WIN32 */
  1643. #ifdef HAVE_OPENCL
  1644. for (i = 0; i < 16; i++)
  1645. gpu_devices[i] = false;
  1646. nDevs = clDevicesNum();
  1647. if (nDevs < 0)
  1648. return 1;
  1649. #endif
  1650. if (nDevs)
  1651. opt_n_threads = 0;
  1652. rpc_url = strdup(DEF_RPC_URL);
  1653. /* parse command line */
  1654. opt_register_table(opt_config_table,
  1655. "Options for both config file and command line");
  1656. opt_register_table(opt_cmdline_table,
  1657. "Options for command line only");
  1658. opt_parse(&argc, argv, applog_and_exit);
  1659. if (argc != 1) {
  1660. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1661. return 1;
  1662. }
  1663. if (total_devices) {
  1664. if (total_devices > nDevs) {
  1665. applog(LOG_ERR, "More devices specified than exist");
  1666. return 1;
  1667. }
  1668. for (i = 0; i < 16; i++)
  1669. if (gpu_devices[i] && i + 1 > nDevs) {
  1670. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1671. return 1;
  1672. }
  1673. gpu_threads = total_devices * opt_g_threads;
  1674. } else {
  1675. gpu_threads = nDevs * opt_g_threads;
  1676. for (i = 0; i < nDevs; i++)
  1677. gpu_devices[i] = true;
  1678. }
  1679. if (!gpu_threads && !forced_n_threads) {
  1680. /* Maybe they turned GPU off; restore default CPU threads. */
  1681. opt_n_threads = num_processors;
  1682. }
  1683. logcursor = 4;
  1684. mining_threads = opt_n_threads + gpu_threads;
  1685. gpucursor = logcursor;
  1686. cpucursor = gpucursor + nDevs;
  1687. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  1688. logcursor = logstart + 1;
  1689. if (!rpc_userpass) {
  1690. if (!rpc_user || !rpc_pass) {
  1691. applog(LOG_ERR, "No login credentials supplied");
  1692. return 1;
  1693. }
  1694. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1695. if (!rpc_userpass)
  1696. return 1;
  1697. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1698. }
  1699. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1700. return 1;
  1701. #ifdef HAVE_SYSLOG_H
  1702. if (use_syslog)
  1703. openlog("cpuminer", LOG_PID, LOG_USER);
  1704. #endif
  1705. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  1706. if (!work_restart)
  1707. return 1;
  1708. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  1709. if (!thr_info)
  1710. return 1;
  1711. /* init workio thread info */
  1712. work_thr_id = mining_threads;
  1713. thr = &thr_info[work_thr_id];
  1714. thr->id = work_thr_id;
  1715. thr->q = tq_new();
  1716. if (!thr->q)
  1717. return 1;
  1718. /* start work I/O thread */
  1719. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1720. applog(LOG_ERR, "workio thread create failed");
  1721. return 1;
  1722. }
  1723. /* init longpoll thread info */
  1724. if (want_longpoll) {
  1725. longpoll_thr_id = mining_threads + 1;
  1726. thr = &thr_info[longpoll_thr_id];
  1727. thr->id = longpoll_thr_id;
  1728. thr->q = tq_new();
  1729. if (!thr->q)
  1730. return 1;
  1731. /* start longpoll thread */
  1732. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1733. applog(LOG_ERR, "longpoll thread create failed");
  1734. return 1;
  1735. }
  1736. pthread_detach(thr->pth);
  1737. } else
  1738. longpoll_thr_id = -1;
  1739. gettimeofday(&total_tv_start, NULL);
  1740. gettimeofday(&total_tv_end, NULL);
  1741. if (opt_n_threads ) {
  1742. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1743. if (unlikely(!cpus)) {
  1744. applog(LOG_ERR, "Failed to calloc cpus");
  1745. return 1;
  1746. }
  1747. }
  1748. if (gpu_threads) {
  1749. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1750. if (unlikely(!gpus)) {
  1751. applog(LOG_ERR, "Failed to calloc gpus");
  1752. return 1;
  1753. }
  1754. }
  1755. stage_thr_id = mining_threads + 3;
  1756. thr = &thr_info[stage_thr_id];
  1757. thr->q = tq_new();
  1758. if (!thr->q)
  1759. return 1;
  1760. /* start stage thread */
  1761. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  1762. applog(LOG_ERR, "stage thread create failed");
  1763. return 1;
  1764. }
  1765. /* Flag the work as ready forcing the mining threads to wait till we
  1766. * actually put something into the queue */
  1767. inc_staged(mining_threads, true);
  1768. #ifdef HAVE_OPENCL
  1769. i = 0;
  1770. /* start GPU mining threads */
  1771. for (j = 0; j < nDevs * opt_g_threads; j++) {
  1772. int gpu = gpu_from_thr_id(j);
  1773. /* Skip devices not set to work */
  1774. if (!gpu_devices[gpu])
  1775. continue;
  1776. thr = &thr_info[i];
  1777. thr->id = i;
  1778. gpus[gpu].is_gpu = 1;
  1779. gpus[gpu].cpu_gpu = gpu;
  1780. thr->cgpu = &gpus[gpu];
  1781. thr->q = tq_new();
  1782. if (!thr->q) {
  1783. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1784. return 1;
  1785. }
  1786. applog(LOG_INFO, "Init GPU thread %i", i);
  1787. clStates[i] = initCl(gpu, name, sizeof(name));
  1788. if (!clStates[i]) {
  1789. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1790. continue;
  1791. }
  1792. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1793. gettimeofday(&thr->last, NULL);
  1794. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1795. applog(LOG_ERR, "thread %d create failed", i);
  1796. return 1;
  1797. }
  1798. i++;
  1799. }
  1800. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  1801. #endif
  1802. /* start CPU mining threads */
  1803. for (i = gpu_threads; i < mining_threads; i++) {
  1804. int cpu = cpu_from_thr_id(i);
  1805. thr = &thr_info[i];
  1806. thr->id = i;
  1807. cpus[cpu].cpu_gpu = cpu;
  1808. thr->cgpu = &cpus[cpu];
  1809. thr->q = tq_new();
  1810. if (!thr->q) {
  1811. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1812. return 1;
  1813. }
  1814. gettimeofday(&thr->last, NULL);
  1815. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1816. applog(LOG_ERR, "thread %d create failed", i);
  1817. return 1;
  1818. }
  1819. }
  1820. applog(LOG_INFO, "%d cpu miner threads started, "
  1821. "using SHA256 '%s' algorithm.",
  1822. opt_n_threads,
  1823. algo_names[opt_algo]);
  1824. thr = &thr_info[mining_threads + 2];
  1825. /* start wakeup thread */
  1826. if (pthread_create(&thr->pth, NULL, watchdog_thread, NULL)) {
  1827. applog(LOG_ERR, "wakeup thread create failed");
  1828. return 1;
  1829. }
  1830. /* Restart count as it will be wrong till all threads are started */
  1831. pthread_mutex_lock(&hash_lock);
  1832. gettimeofday(&total_tv_start, NULL);
  1833. gettimeofday(&total_tv_end, NULL);
  1834. total_mhashes_done = 0;
  1835. pthread_mutex_unlock(&hash_lock);
  1836. /* Set up the ncurses interface */
  1837. if (!opt_quiet) {
  1838. mainwin = initscr();
  1839. getmaxyx(mainwin, y, x);
  1840. statuswin = newwin(logstart, x, 0, 0);
  1841. logwin = newwin(y - logcursor, 0, logcursor, 0);
  1842. idlok(logwin, true);
  1843. scrollok(logwin, true);
  1844. leaveok(logwin, true);
  1845. leaveok(statuswin, true);
  1846. curses_active = true;
  1847. for (i = 0; i < mining_threads; i++)
  1848. print_status(i);
  1849. }
  1850. /* Now that everything's ready put enough work in the queue */
  1851. for (i = 0; i < opt_queue + mining_threads; i++) {
  1852. if (unlikely(!queue_request())) {
  1853. applog(LOG_ERR, "Failed to queue_request in main");
  1854. return 1;
  1855. }
  1856. }
  1857. /* main loop - simply wait for workio thread to exit */
  1858. pthread_join(thr_info[work_thr_id].pth, NULL);
  1859. curl_global_cleanup();
  1860. if (gpu_threads)
  1861. free(gpus);
  1862. if (opt_n_threads)
  1863. free(cpus);
  1864. applog(LOG_INFO, "workio thread dead, exiting.");
  1865. if (curses_active) {
  1866. delwin(logwin);
  1867. delwin(statuswin);
  1868. endwin();
  1869. refresh();
  1870. }
  1871. return 0;
  1872. }