main.c 57 KB

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