main.c 55 KB

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