main.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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 <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <unistd.h>
  17. #include <sys/time.h>
  18. #include <time.h>
  19. #include <math.h>
  20. #include <stdarg.h>
  21. #include <assert.h>
  22. #ifndef WIN32
  23. #include <sys/resource.h>
  24. #endif
  25. #include <ccan/opt/opt.h>
  26. #include <jansson.h>
  27. #include <curl/curl.h>
  28. #include "compat.h"
  29. #include "miner.h"
  30. #include "findnonce.h"
  31. #include "ocl.h"
  32. #define PROGRAM_NAME "cgminer"
  33. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  34. #define DEF_RPC_USERNAME "rpcuser"
  35. #define DEF_RPC_PASSWORD "rpcpass"
  36. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  37. #ifdef __linux /* Linux specific policy and affinity management */
  38. #include <sched.h>
  39. static inline void drop_policy(void)
  40. {
  41. struct sched_param param;
  42. #ifdef SCHED_BATCH
  43. #ifdef SCHED_IDLE
  44. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  45. #endif
  46. sched_setscheduler(0, SCHED_BATCH, &param);
  47. #endif
  48. }
  49. static inline void affine_to_cpu(int id, int cpu)
  50. {
  51. cpu_set_t set;
  52. CPU_ZERO(&set);
  53. CPU_SET(cpu, &set);
  54. sched_setaffinity(0, sizeof(&set), &set);
  55. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  56. }
  57. #else
  58. static inline void drop_policy(void)
  59. {
  60. }
  61. static inline void affine_to_cpu(int id, int cpu)
  62. {
  63. }
  64. #endif
  65. enum workio_commands {
  66. WC_GET_WORK,
  67. WC_SUBMIT_WORK,
  68. WC_DIE,
  69. };
  70. struct workio_cmd {
  71. enum workio_commands cmd;
  72. struct thr_info *thr;
  73. union {
  74. struct work *work;
  75. } u;
  76. };
  77. enum sha256_algos {
  78. ALGO_C, /* plain C */
  79. ALGO_4WAY, /* parallel SSE2 */
  80. ALGO_VIA, /* VIA padlock */
  81. ALGO_CRYPTOPP, /* Crypto++ (C) */
  82. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  83. ALGO_SSE2_64, /* SSE2 for x86_64 */
  84. };
  85. static const char *algo_names[] = {
  86. [ALGO_C] = "c",
  87. #ifdef WANT_SSE2_4WAY
  88. [ALGO_4WAY] = "4way",
  89. #endif
  90. #ifdef WANT_VIA_PADLOCK
  91. [ALGO_VIA] = "via",
  92. #endif
  93. [ALGO_CRYPTOPP] = "cryptopp",
  94. #ifdef WANT_CRYPTOPP_ASM32
  95. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  96. #endif
  97. #ifdef WANT_X8664_SSE2
  98. [ALGO_SSE2_64] = "sse2_64",
  99. #endif
  100. };
  101. bool opt_debug = false;
  102. bool opt_protocol = false;
  103. bool want_longpoll = true;
  104. bool have_longpoll = false;
  105. bool use_syslog = false;
  106. static bool opt_quiet = false;
  107. static int opt_retries = -1;
  108. static int opt_fail_pause = 5;
  109. static int opt_log_interval = 5;
  110. bool opt_log_output = false;
  111. static int opt_queue = 0;
  112. int opt_vectors;
  113. int opt_worksize;
  114. int opt_scantime = 60;
  115. static const bool opt_time = true;
  116. #ifdef WANT_X8664_SSE2
  117. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  118. #else
  119. static enum sha256_algos opt_algo = ALGO_C;
  120. #endif
  121. static int nDevs;
  122. static int opt_g_threads = 2;
  123. static int gpu_threads;
  124. static bool forced_n_threads;
  125. static int opt_n_threads;
  126. static int num_processors;
  127. static int scan_intensity = 4;
  128. static char *rpc_url;
  129. static char *rpc_userpass;
  130. static char *rpc_user, *rpc_pass;
  131. struct thr_info *thr_info;
  132. static int work_thr_id;
  133. int longpoll_thr_id;
  134. struct work_restart *work_restart = NULL;
  135. pthread_mutex_t time_lock;
  136. static pthread_mutex_t hash_lock;
  137. static pthread_mutex_t qd_lock;
  138. static double total_mhashes_done;
  139. static struct timeval total_tv_start, total_tv_end;
  140. static int accepted, rejected;
  141. int hw_errors;
  142. static int total_queued;
  143. static void applog_and_exit(const char *fmt, ...)
  144. {
  145. va_list ap;
  146. va_start(ap, fmt);
  147. vapplog(LOG_ERR, fmt, ap);
  148. va_end(ap);
  149. exit(1);
  150. }
  151. /* FIXME: Use asprintf for better errors. */
  152. static char *set_algo(const char *arg, enum sha256_algos *algo)
  153. {
  154. enum sha256_algos i;
  155. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  156. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  157. *algo = i;
  158. return NULL;
  159. }
  160. }
  161. return "Unknown algorithm";
  162. }
  163. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  164. {
  165. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  166. }
  167. static char *set_int_range(const char *arg, int *i, int min, int max)
  168. {
  169. char *err = opt_set_intval(arg, i);
  170. if (err)
  171. return err;
  172. if (*i < min || *i > max)
  173. return "Value out of range";
  174. return NULL;
  175. }
  176. static char *set_int_0_to_9999(const char *arg, int *i)
  177. {
  178. return set_int_range(arg, i, 0, 9999);
  179. }
  180. static char *set_int_0_to_14(const char *arg, int *i)
  181. {
  182. return set_int_range(arg, i, 0, 14);
  183. }
  184. static char *force_nthreads_int(const char *arg, int *i)
  185. {
  186. forced_n_threads = true;
  187. return set_int_range(arg, i, 0, 9999);
  188. }
  189. static char *set_int_0_to_10(const char *arg, int *i)
  190. {
  191. return set_int_range(arg, i, 0, 10);
  192. }
  193. static char *set_url(const char *arg, char **p)
  194. {
  195. opt_set_charp(arg, p);
  196. if (strncmp(arg, "http://", 7) &&
  197. strncmp(arg, "https://", 8))
  198. return "URL must start with http:// or https://";
  199. return NULL;
  200. }
  201. static char *set_vector(const char *arg, int *i)
  202. {
  203. char *err = opt_set_intval(arg, i);
  204. if (err)
  205. return err;
  206. if (*i != 1 && *i != 2 && *i != 4)
  207. return "Valid vectors are 1, 2 or 4";
  208. return NULL;
  209. }
  210. static char *enable_debug(bool *flag)
  211. {
  212. *flag = true;
  213. /* Turn out verbose output, too. */
  214. opt_log_output = true;
  215. return NULL;
  216. }
  217. /* These options are available from config file or commandline */
  218. static struct opt_table opt_config_table[] = {
  219. OPT_WITH_ARG("--algo|-a",
  220. set_algo, show_algo, &opt_algo,
  221. "Specify sha256 implementation:\n"
  222. "\tc\t\tLinux kernel sha256, implemented in C"
  223. #ifdef WANT_SSE2_4WAY
  224. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  225. #endif
  226. #ifdef WANT_VIA_PADLOCK
  227. "\n\tvia\t\tVIA padlock implementation"
  228. #endif
  229. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  230. #ifdef WANT_CRYPTOPP_ASM32
  231. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  232. #endif
  233. #ifdef WANT_X8664_SSE2
  234. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  235. #endif
  236. ),
  237. OPT_WITH_ARG("--cpu-threads|-t",
  238. force_nthreads_int, opt_show_intval, &opt_n_threads,
  239. "Number of miner CPU threads"),
  240. OPT_WITHOUT_ARG("--debug|-D",
  241. enable_debug, &opt_debug,
  242. "Enable debug output"),
  243. #ifdef HAVE_OPENCL
  244. OPT_WITH_ARG("--gpu-threads|-g",
  245. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  246. "Number of threads per GPU (0 - 10)"),
  247. OPT_WITH_ARG("--intensity|-I",
  248. set_int_0_to_14, opt_show_intval, &scan_intensity,
  249. "Intensity of GPU scanning (0 - 14)"),
  250. #endif
  251. OPT_WITH_ARG("--log|-l",
  252. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  253. "Interval in seconds between log output"),
  254. OPT_WITHOUT_ARG("--no-longpoll",
  255. opt_set_invbool, &want_longpoll,
  256. "Disable X-Long-Polling support"),
  257. OPT_WITH_ARG("--pass|-p",
  258. opt_set_charp, NULL, &rpc_pass,
  259. "Password for bitcoin JSON-RPC server"),
  260. OPT_WITHOUT_ARG("--protocol-dump|-P",
  261. opt_set_bool, &opt_protocol,
  262. "Verbose dump of protocol-level activities"),
  263. OPT_WITH_ARG("--queue|-Q",
  264. set_int_0_to_9999, opt_show_intval, &opt_queue,
  265. "Number of extra work items to queue"),
  266. OPT_WITHOUT_ARG("--quiet|-q",
  267. opt_set_bool, &opt_quiet,
  268. "Disable per-thread hashmeter output"),
  269. OPT_WITH_ARG("--retries|-r",
  270. opt_set_intval, opt_show_intval, &opt_retries,
  271. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  272. OPT_WITH_ARG("--retry-pause|-R",
  273. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  274. "Number of seconds to pause, between retries"),
  275. OPT_WITH_ARG("--scan-time|-s",
  276. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  277. "Upper bound on time spent scanning current work, in seconds"),
  278. #ifdef HAVE_SYSLOG_H
  279. OPT_WITHOUT_ARG("--syslog",
  280. opt_set_bool, &use_syslog,
  281. "Use system log for output messages (default: standard error)"),
  282. #endif
  283. OPT_WITH_ARG("--url|-o",
  284. set_url, opt_show_charp, &rpc_url,
  285. "URL for bitcoin JSON-RPC server"),
  286. OPT_WITH_ARG("--user|-u",
  287. opt_set_charp, NULL, &rpc_user,
  288. "Username for bitcoin JSON-RPC server"),
  289. #ifdef HAVE_OPENCL
  290. OPT_WITH_ARG("--vectors|-v",
  291. set_vector, NULL, &opt_vectors,
  292. "Override detected optimal vector width (1, 2 or 4)"),
  293. #endif
  294. OPT_WITHOUT_ARG("--verbose",
  295. opt_set_bool, &opt_log_output,
  296. "Log verbose output to stderr as well as status output"),
  297. #ifdef HAVE_OPENCL
  298. OPT_WITH_ARG("--worksize|-w",
  299. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  300. "Override detected optimal worksize"),
  301. #endif
  302. OPT_WITH_ARG("--userpass|-O",
  303. opt_set_charp, NULL, &rpc_userpass,
  304. "Username:Password pair for bitcoin JSON-RPC server"),
  305. OPT_ENDTABLE
  306. };
  307. static char *parse_config(json_t *config)
  308. {
  309. static char err_buf[200];
  310. json_t *val;
  311. struct opt_table *opt;
  312. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  313. char *p, *name;
  314. /* We don't handle subtables. */
  315. assert(!(opt->type & OPT_SUBTABLE));
  316. /* Pull apart the option name(s). */
  317. name = strdup(opt->names);
  318. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  319. char *err;
  320. /* Ignore short options. */
  321. if (p[1] != '-')
  322. continue;
  323. val = json_object_get(config, p+2);
  324. if (!val)
  325. continue;
  326. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  327. err = opt->cb_arg(json_string_value(val),
  328. opt->u.arg);
  329. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  330. err = opt->cb(opt->u.arg);
  331. } else {
  332. err = "Invalid value";
  333. }
  334. if (err) {
  335. sprintf(err_buf, "Parsing JSON option %s: %s",
  336. p, err);
  337. return err_buf;
  338. }
  339. }
  340. free(name);
  341. }
  342. return NULL;
  343. }
  344. static char *load_config(const char *arg, void *unused)
  345. {
  346. json_error_t err;
  347. json_t *config;
  348. config = json_load_file(arg, &err);
  349. if (!json_is_object(config))
  350. return "JSON decode of file failed";
  351. /* Parse the config now, so we can override it. That can keep pointers
  352. * so don't free config object. */
  353. return parse_config(config);
  354. }
  355. static char *print_ndevs_and_exit(int *ndevs)
  356. {
  357. printf("%i", *ndevs);
  358. exit(*ndevs);
  359. }
  360. /* These options are available from commandline only */
  361. static struct opt_table opt_cmdline_table[] = {
  362. OPT_WITH_ARG("--config|-c",
  363. load_config, NULL, NULL,
  364. "Load a JSON-format configuration file\n"
  365. "See example-cfg.json for an example configuration."),
  366. OPT_WITHOUT_ARG("--help|-h",
  367. opt_usage_and_exit,
  368. #ifdef HAVE_OPENCL
  369. "\nBuilt with CPU and GPU mining support.\n\n",
  370. #else
  371. "\nBuilt with CPU mining support only.\n\n",
  372. #endif
  373. "Print this message"),
  374. OPT_WITHOUT_ARG("--ndevs|-n",
  375. print_ndevs_and_exit, &nDevs,
  376. "Display number of detected GPUs and exit"),
  377. OPT_ENDTABLE
  378. };
  379. static bool jobj_binary(const json_t *obj, const char *key,
  380. void *buf, size_t buflen)
  381. {
  382. const char *hexstr;
  383. json_t *tmp;
  384. tmp = json_object_get(obj, key);
  385. if (unlikely(!tmp)) {
  386. applog(LOG_ERR, "JSON key '%s' not found", key);
  387. return false;
  388. }
  389. hexstr = json_string_value(tmp);
  390. if (unlikely(!hexstr)) {
  391. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  392. return false;
  393. }
  394. if (!hex2bin(buf, hexstr, buflen))
  395. return false;
  396. return true;
  397. }
  398. static bool work_decode(const json_t *val, struct work *work)
  399. {
  400. if (unlikely(!jobj_binary(val, "midstate",
  401. work->midstate, sizeof(work->midstate)))) {
  402. applog(LOG_ERR, "JSON inval midstate");
  403. goto err_out;
  404. }
  405. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  406. applog(LOG_ERR, "JSON inval data");
  407. goto err_out;
  408. }
  409. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  410. applog(LOG_ERR, "JSON inval hash1");
  411. goto err_out;
  412. }
  413. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  414. applog(LOG_ERR, "JSON inval target");
  415. goto err_out;
  416. }
  417. memset(work->hash, 0, sizeof(work->hash));
  418. return true;
  419. err_out:
  420. return false;
  421. }
  422. static double total_secs;
  423. static bool submit_upstream_work(const struct work *work)
  424. {
  425. char *hexstr = NULL;
  426. json_t *val, *res;
  427. char s[345];
  428. bool rc = false;
  429. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  430. CURL *curl = curl_easy_init();
  431. if (unlikely(!curl)) {
  432. applog(LOG_ERR, "CURL initialisation failed");
  433. return rc;
  434. }
  435. /* build hex string */
  436. hexstr = bin2hex(work->data, sizeof(work->data));
  437. if (unlikely(!hexstr)) {
  438. applog(LOG_ERR, "submit_upstream_work OOM");
  439. goto out_nofree;
  440. }
  441. /* build JSON-RPC request */
  442. sprintf(s,
  443. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  444. hexstr);
  445. if (opt_debug)
  446. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  447. /* issue JSON-RPC request */
  448. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  449. if (unlikely(!val)) {
  450. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  451. goto out;
  452. }
  453. res = json_object_get(val, "result");
  454. /* Theoretically threads could race when modifying accepted and
  455. * rejected values but the chance of two submits completing at the
  456. * same time is zero so there is no point adding extra locking */
  457. if (json_is_true(res)) {
  458. cgpu->accepted++;
  459. accepted++;
  460. if (opt_debug)
  461. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  462. printf("[Accepted] ");
  463. } else {
  464. cgpu->rejected++;
  465. rejected++;
  466. if (opt_debug)
  467. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  468. printf("[Rejected] ");
  469. }
  470. if (!opt_quiet) {
  471. printf("[%sPU: %d] [Rate: %.2f Mhash/s] [Accepted: %d Rejected: %d HW errors: %d] \n",
  472. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->total_mhashes / total_secs,
  473. cgpu->accepted, cgpu->rejected, cgpu->hw_errors);
  474. }
  475. applog(LOG_INFO, "%sPU: %d Accepted: %d Rejected: %d HW errors: %d",
  476. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->accepted, cgpu->rejected, cgpu->hw_errors);
  477. json_decref(val);
  478. rc = true;
  479. out:
  480. free(hexstr);
  481. out_nofree:
  482. curl_easy_cleanup(curl);
  483. return rc;
  484. }
  485. static const char *rpc_req =
  486. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  487. static bool get_upstream_work(struct work *work)
  488. {
  489. json_t *val;
  490. bool rc = false;
  491. CURL *curl = curl_easy_init();
  492. if (unlikely(!curl)) {
  493. applog(LOG_ERR, "CURL initialisation failed");
  494. return rc;
  495. }
  496. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  497. want_longpoll, false);
  498. if (unlikely(!val)) {
  499. applog(LOG_ERR, "Failed json_rpc_call in get_upstream_work");
  500. goto out;
  501. }
  502. rc = work_decode(json_object_get(val, "result"), work);
  503. json_decref(val);
  504. out:
  505. curl_easy_cleanup(curl);
  506. return rc;
  507. }
  508. static void workio_cmd_free(struct workio_cmd *wc)
  509. {
  510. if (!wc)
  511. return;
  512. switch (wc->cmd) {
  513. case WC_SUBMIT_WORK:
  514. free(wc->u.work);
  515. break;
  516. default: /* do nothing */
  517. break;
  518. }
  519. memset(wc, 0, sizeof(*wc)); /* poison */
  520. free(wc);
  521. }
  522. static void kill_work(void)
  523. {
  524. struct workio_cmd *wc;
  525. applog(LOG_INFO, "Received kill message");
  526. wc = calloc(1, sizeof(*wc));
  527. if (unlikely(!wc)) {
  528. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  529. /* We're just trying to die anyway, so forget graceful */
  530. exit (1);
  531. }
  532. wc->cmd = WC_DIE;
  533. wc->thr = 0;
  534. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  535. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  536. exit (1);
  537. }
  538. }
  539. static char current_block[36];
  540. static void *get_work_thread(void *userdata)
  541. {
  542. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  543. struct work *ret_work;
  544. int failures = 0;
  545. pthread_detach(pthread_self());
  546. ret_work = calloc(1, sizeof(*ret_work));
  547. if (unlikely(!ret_work)) {
  548. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  549. kill_work();
  550. goto out;
  551. }
  552. /* obtain new work from bitcoin via JSON-RPC */
  553. while (!get_upstream_work(ret_work)) {
  554. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  555. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  556. free(ret_work);
  557. kill_work();
  558. goto out;
  559. }
  560. /* pause, then restart work-request loop */
  561. applog(LOG_ERR, "json_rpc_call failed on get work, retry after %d seconds",
  562. opt_fail_pause);
  563. sleep(opt_fail_pause);
  564. }
  565. /* send work to requesting thread */
  566. if (unlikely(!tq_push(wc->thr->q, ret_work))) {
  567. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  568. kill_work();
  569. free(ret_work);
  570. }
  571. out:
  572. workio_cmd_free(wc);
  573. return NULL;
  574. }
  575. static bool workio_get_work(struct workio_cmd *wc)
  576. {
  577. pthread_t get_thread;
  578. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  579. applog(LOG_ERR, "Failed to create get_work_thread");
  580. return false;
  581. }
  582. return true;
  583. }
  584. static void *submit_work_thread(void *userdata)
  585. {
  586. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  587. int failures = 0;
  588. pthread_detach(pthread_self());
  589. if (unlikely(strncmp((const char *)wc->u.work->data, current_block, 36))) {
  590. applog(LOG_INFO, "Stale work detected, discarding");
  591. goto out;
  592. }
  593. /* submit solution to bitcoin via JSON-RPC */
  594. while (!submit_upstream_work(wc->u.work)) {
  595. if (unlikely(strncmp((const char *)wc->u.work->data, current_block, 36))) {
  596. applog(LOG_INFO, "Stale work detected, discarding");
  597. goto out;
  598. }
  599. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  600. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  601. kill_work();
  602. goto out;
  603. }
  604. /* pause, then restart work-request loop */
  605. applog(LOG_ERR, "json_rpc_call failed on submit_work, retry after %d seconds",
  606. opt_fail_pause);
  607. sleep(opt_fail_pause);
  608. }
  609. out:
  610. workio_cmd_free(wc);
  611. return NULL;
  612. }
  613. static bool workio_submit_work(struct workio_cmd *wc)
  614. {
  615. pthread_t submit_thread;
  616. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  617. applog(LOG_ERR, "Failed to create submit_work_thread");
  618. return false;
  619. }
  620. return true;
  621. }
  622. static void *workio_thread(void *userdata)
  623. {
  624. struct thr_info *mythr = userdata;
  625. bool ok = true;
  626. while (ok) {
  627. struct workio_cmd *wc;
  628. /* wait for workio_cmd sent to us, on our queue */
  629. wc = tq_pop(mythr->q, NULL);
  630. if (unlikely(!wc)) {
  631. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  632. ok = false;
  633. break;
  634. }
  635. /* process workio_cmd */
  636. switch (wc->cmd) {
  637. case WC_GET_WORK:
  638. ok = workio_get_work(wc);
  639. break;
  640. case WC_SUBMIT_WORK:
  641. ok = workio_submit_work(wc);
  642. break;
  643. case WC_DIE:
  644. default:
  645. ok = false;
  646. break;
  647. }
  648. }
  649. tq_freeze(mythr->q);
  650. return NULL;
  651. }
  652. static void hashmeter(int thr_id, struct timeval *diff,
  653. unsigned long hashes_done)
  654. {
  655. struct timeval temp_tv_end, total_diff;
  656. double khashes, secs;
  657. double local_secs;
  658. static double local_mhashes_done = 0;
  659. static double rolling_local = 0;
  660. double local_mhashes = (double)hashes_done / 1000000.0;
  661. /* Don't bother calculating anything if we're not displaying it */
  662. if (opt_quiet || !opt_log_interval)
  663. return;
  664. khashes = hashes_done / 1000.0;
  665. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  666. if (thr_id >= 0) {
  667. /* So we can call hashmeter from a non worker thread */
  668. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  669. if (opt_debug)
  670. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  671. thr_id, hashes_done, hashes_done / secs);
  672. cgpu->local_mhashes += local_mhashes;
  673. cgpu->total_mhashes += local_mhashes;
  674. }
  675. /* Totals are updated by all threads so can race without locking */
  676. pthread_mutex_lock(&hash_lock);
  677. gettimeofday(&temp_tv_end, NULL);
  678. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  679. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  680. total_mhashes_done += local_mhashes;
  681. local_mhashes_done += local_mhashes;
  682. if (total_diff.tv_sec < opt_log_interval)
  683. /* Only update the total every opt_log_interval seconds */
  684. goto out_unlock;
  685. gettimeofday(&total_tv_end, NULL);
  686. /* Use a rolling average by faking an exponential decay over 5 * log */
  687. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  688. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  689. total_secs = (double)total_diff.tv_sec +
  690. ((double)total_diff.tv_usec / 1000000.0);
  691. printf("[Rate (%ds): %.2f (avg): %.2f Mhash/s] [Accepted: %d Rejected: %d HW errors: %d] \r",
  692. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  693. accepted, rejected, hw_errors);
  694. fflush(stdout);
  695. applog(LOG_INFO, "[Rate (%ds): %.2f (avg): %.2f Mhash/s] [Accepted: %d Rejected: %d HW errors: %d]",
  696. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  697. accepted, rejected, hw_errors);
  698. local_mhashes_done = 0;
  699. out_unlock:
  700. pthread_mutex_unlock(&hash_lock);
  701. }
  702. /* This is overkill, but at least we'll know accurately how much work is
  703. * queued to prevent ever being left without work */
  704. static void inc_queued(void)
  705. {
  706. pthread_mutex_lock(&qd_lock);
  707. total_queued++;
  708. pthread_mutex_unlock(&qd_lock);
  709. }
  710. static void dec_queued(void)
  711. {
  712. pthread_mutex_lock(&qd_lock);
  713. total_queued--;
  714. pthread_mutex_unlock(&qd_lock);
  715. }
  716. static int requests_queued(void)
  717. {
  718. int ret;
  719. pthread_mutex_lock(&qd_lock);
  720. ret = total_queued;
  721. pthread_mutex_unlock(&qd_lock);
  722. return ret;
  723. }
  724. /* All work is queued flagged as being for thread 0 and then the mining thread
  725. * flags it as its own */
  726. static bool queue_request(void)
  727. {
  728. struct thr_info *thr = &thr_info[0];
  729. struct workio_cmd *wc;
  730. /* fill out work request message */
  731. wc = calloc(1, sizeof(*wc));
  732. if (unlikely(!wc)) {
  733. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  734. return false;
  735. }
  736. wc->cmd = WC_GET_WORK;
  737. wc->thr = thr;
  738. /* send work request to workio thread */
  739. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  740. applog(LOG_ERR, "Failed to tq_push in queue_request");
  741. workio_cmd_free(wc);
  742. return false;
  743. }
  744. inc_queued();
  745. return true;
  746. }
  747. static bool discard_request(void)
  748. {
  749. struct thr_info *thr = &thr_info[0];
  750. struct work *work_heap;
  751. /* Just in case we fell in a hole and missed a queue filling */
  752. if (unlikely(!requests_queued())) {
  753. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  754. return true;
  755. }
  756. work_heap = tq_pop(thr->q, NULL);
  757. if (unlikely(!work_heap)) {
  758. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  759. return false;
  760. }
  761. free(work_heap);
  762. dec_queued();
  763. return true;
  764. }
  765. static void flush_requests(void)
  766. {
  767. int i, extra;
  768. extra = requests_queued();
  769. for (i = 0; i < extra; i++) {
  770. /* Queue a whole batch of new requests */
  771. if (unlikely(!queue_request())) {
  772. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  773. kill_work();
  774. break;
  775. }
  776. /* Pop off the old requests. Cancelling the requests would be better
  777. * but is tricky */
  778. if (unlikely(!discard_request())) {
  779. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  780. kill_work();
  781. break;
  782. }
  783. }
  784. }
  785. static bool get_work(struct work *work, bool queued)
  786. {
  787. struct thr_info *thr = &thr_info[0];
  788. struct work *work_heap;
  789. bool ret = false;
  790. int failures = 0;
  791. retry:
  792. if (unlikely(!queued && !queue_request())) {
  793. applog(LOG_WARNING, "Failed to queue_request in get_work");
  794. goto out;
  795. }
  796. /* wait for 1st response, or get cached response */
  797. work_heap = tq_pop(thr->q, NULL);
  798. if (unlikely(!work_heap)) {
  799. applog(LOG_WARNING, "Failed to tq_pop in get_work");
  800. goto out;
  801. }
  802. dec_queued();
  803. memcpy(work, work_heap, sizeof(*work));
  804. memcpy(current_block, work->data, 36);
  805. ret = true;
  806. free(work_heap);
  807. out:
  808. if (unlikely(ret == false)) {
  809. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  810. applog(LOG_ERR, "Failed %d times to get_work");
  811. return ret;
  812. }
  813. applog(LOG_WARNING, "Retrying after %d seconds", opt_fail_pause);
  814. sleep(opt_fail_pause);
  815. goto retry;
  816. }
  817. return ret;
  818. }
  819. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  820. {
  821. struct workio_cmd *wc;
  822. /* fill out work request message */
  823. wc = calloc(1, sizeof(*wc));
  824. if (unlikely(!wc)) {
  825. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  826. return false;
  827. }
  828. wc->u.work = malloc(sizeof(*work_in));
  829. if (unlikely(!wc->u.work)) {
  830. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  831. goto err_out;
  832. }
  833. wc->cmd = WC_SUBMIT_WORK;
  834. wc->thr = thr;
  835. memcpy(wc->u.work, work_in, sizeof(*work_in));
  836. /* send solution to workio thread */
  837. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  838. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  839. goto err_out;
  840. }
  841. return true;
  842. err_out:
  843. workio_cmd_free(wc);
  844. return false;
  845. }
  846. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  847. {
  848. work->data[64+12+0] = (nonce>>0) & 0xff;
  849. work->data[64+12+1] = (nonce>>8) & 0xff;
  850. work->data[64+12+2] = (nonce>>16) & 0xff;
  851. work->data[64+12+3] = (nonce>>24) & 0xff;
  852. return submit_work_sync(thr, work);
  853. }
  854. static inline int cpu_from_thr_id(int thr_id)
  855. {
  856. return (thr_id - gpu_threads) % num_processors;
  857. }
  858. static void *miner_thread(void *userdata)
  859. {
  860. struct thr_info *mythr = userdata;
  861. const int thr_id = mythr->id;
  862. uint32_t max_nonce = 0xffffff;
  863. bool needs_work = true;
  864. /* Try to cycle approximately 5 times before each log update */
  865. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  866. /* Request the next work item at 2/3 of the scantime */
  867. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  868. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  869. bool requested = true;
  870. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  871. * and if that fails, then SCHED_BATCH. No need for this to be an
  872. * error if it fails */
  873. setpriority(PRIO_PROCESS, 0, 19);
  874. drop_policy();
  875. /* Cpu affinity only makes sense if the number of threads is a multiple
  876. * of the number of CPUs */
  877. if (!(opt_n_threads % num_processors))
  878. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  879. while (1) {
  880. struct work work __attribute__((aligned(128)));
  881. unsigned long hashes_done;
  882. struct timeval tv_workstart, tv_start, tv_end, diff;
  883. uint64_t max64;
  884. bool rc;
  885. if (needs_work) {
  886. gettimeofday(&tv_workstart, NULL);
  887. /* obtain new work from internal workio thread */
  888. if (unlikely(!get_work(&work, requested))) {
  889. applog(LOG_ERR, "work retrieval failed, exiting "
  890. "mining thread %d", mythr->id);
  891. goto out;
  892. }
  893. work.thr_id = thr_id;
  894. needs_work = requested = false;
  895. work.blk.nonce = 0;
  896. }
  897. hashes_done = 0;
  898. gettimeofday(&tv_start, NULL);
  899. /* scan nonces for a proof-of-work hash */
  900. switch (opt_algo) {
  901. case ALGO_C:
  902. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  903. work.hash1, work.hash, work.target,
  904. max_nonce, &hashes_done,
  905. work.blk.nonce);
  906. break;
  907. #ifdef WANT_X8664_SSE2
  908. case ALGO_SSE2_64: {
  909. unsigned int rc5 =
  910. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  911. work.hash1, work.hash,
  912. work.target,
  913. max_nonce, &hashes_done,
  914. work.blk.nonce);
  915. rc = (rc5 == -1) ? false : true;
  916. }
  917. break;
  918. #endif
  919. #ifdef WANT_SSE2_4WAY
  920. case ALGO_4WAY: {
  921. unsigned int rc4 =
  922. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  923. work.hash1, work.hash,
  924. work.target,
  925. max_nonce, &hashes_done,
  926. work.blk.nonce);
  927. rc = (rc4 == -1) ? false : true;
  928. }
  929. break;
  930. #endif
  931. #ifdef WANT_VIA_PADLOCK
  932. case ALGO_VIA:
  933. rc = scanhash_via(thr_id, work.data, work.target,
  934. max_nonce, &hashes_done,
  935. work.blk.nonce);
  936. break;
  937. #endif
  938. case ALGO_CRYPTOPP:
  939. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  940. work.hash1, work.hash, work.target,
  941. max_nonce, &hashes_done,
  942. work.blk.nonce);
  943. break;
  944. #ifdef WANT_CRYPTOPP_ASM32
  945. case ALGO_CRYPTOPP_ASM32:
  946. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  947. work.hash1, work.hash, work.target,
  948. max_nonce, &hashes_done,
  949. work.blk.nonce);
  950. break;
  951. #endif
  952. default:
  953. /* should never happen */
  954. goto out;
  955. }
  956. /* record scanhash elapsed time */
  957. gettimeofday(&tv_end, NULL);
  958. timeval_subtract(&diff, &tv_end, &tv_start);
  959. hashes_done -= work.blk.nonce;
  960. hashmeter(thr_id, &diff, hashes_done);
  961. work.blk.nonce += hashes_done;
  962. /* adjust max_nonce to meet target cycle time */
  963. if (diff.tv_usec > 500000)
  964. diff.tv_sec++;
  965. if (diff.tv_sec && diff.tv_sec != cycle) {
  966. max64 = work.blk.nonce +
  967. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  968. } else
  969. max64 = work.blk.nonce + hashes_done;
  970. if (max64 > 0xfffffffaULL)
  971. max64 = 0xfffffffaULL;
  972. max_nonce = max64;
  973. /* if nonce found, submit work */
  974. if (unlikely(rc)) {
  975. if (opt_debug)
  976. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  977. if (unlikely(!submit_work_sync(mythr, &work))) {
  978. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  979. break;
  980. }
  981. work.blk.nonce += 4;
  982. }
  983. timeval_subtract(&diff, &tv_end, &tv_workstart);
  984. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  985. if (unlikely(!queue_request())) {
  986. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  987. goto out;
  988. }
  989. requested = true;
  990. }
  991. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  992. work.blk.nonce >= MAXTHREADS - hashes_done)
  993. needs_work = true;
  994. }
  995. out:
  996. tq_freeze(mythr->q);
  997. return NULL;
  998. }
  999. enum {
  1000. STAT_SLEEP_INTERVAL = 1,
  1001. STAT_CTR_INTERVAL = 10000000,
  1002. FAILURE_INTERVAL = 30,
  1003. };
  1004. #ifdef HAVE_OPENCL
  1005. static _clState *clStates[16];
  1006. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1007. {
  1008. cl_kernel *kernel = &clState->kernel;
  1009. cl_int status = 0;
  1010. int num = 0;
  1011. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1012. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1013. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1014. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1015. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1016. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1017. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1018. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1019. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1020. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1021. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1022. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1023. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1024. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1025. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1026. if (clState->hasBitAlign == true) {
  1027. /* Parameters for phatk kernel */
  1028. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1029. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1030. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1031. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1032. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1033. } else {
  1034. /* Parameters for poclbm kernel */
  1035. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1036. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1037. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1038. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1039. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1040. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1041. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1042. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1043. }
  1044. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1045. (void *)&clState->outputBuffer);
  1046. return status;
  1047. }
  1048. static inline int gpu_from_thr_id(int thr_id)
  1049. {
  1050. return thr_id % nDevs;
  1051. }
  1052. static void *gpuminer_thread(void *userdata)
  1053. {
  1054. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1055. struct timeval tv_start, tv_end, diff;
  1056. struct thr_info *mythr = userdata;
  1057. const int thr_id = mythr->id;
  1058. uint32_t *res, *blank_res;
  1059. size_t globalThreads[1];
  1060. size_t localThreads[1];
  1061. cl_int status;
  1062. _clState *clState = clStates[thr_id];
  1063. const cl_kernel *kernel = &clState->kernel;
  1064. struct work *work = malloc(sizeof(struct work));
  1065. unsigned const int threads = 1 << (15 + scan_intensity);
  1066. unsigned const int vectors = clState->preferred_vwidth;
  1067. unsigned const int hashes = threads * vectors;
  1068. unsigned int hashes_done = 0;
  1069. /* Request the next work item at 2/3 of the scantime */
  1070. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1071. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1072. bool requested = true;
  1073. res = calloc(BUFFERSIZE, 1);
  1074. blank_res = calloc(BUFFERSIZE, 1);
  1075. if (!res || !blank_res) {
  1076. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1077. goto out;
  1078. }
  1079. gettimeofday(&tv_start, NULL);
  1080. globalThreads[0] = threads;
  1081. localThreads[0] = clState->work_size;
  1082. diff.tv_sec = ~0UL;
  1083. gettimeofday(&tv_end, NULL);
  1084. while (1) {
  1085. struct timeval tv_workstart;
  1086. /* This finish flushes the readbuffer set with CL_FALSE later */
  1087. clFinish(clState->commandQueue);
  1088. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  1089. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1090. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1091. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1092. if (unlikely(status != CL_SUCCESS))
  1093. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1094. memset(res, 0, BUFFERSIZE);
  1095. gettimeofday(&tv_workstart, NULL);
  1096. /* obtain new work from internal workio thread */
  1097. if (unlikely(!get_work(work, requested))) {
  1098. applog(LOG_ERR, "work retrieval failed, exiting "
  1099. "gpu mining thread %d", mythr->id);
  1100. goto out;
  1101. }
  1102. work->thr_id = thr_id;
  1103. requested = false;
  1104. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1105. work->blk.nonce = 0;
  1106. work_restart[thr_id].restart = 0;
  1107. if (opt_debug)
  1108. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1109. /* Flushes the writebuffer set with CL_FALSE above */
  1110. clFinish(clState->commandQueue);
  1111. }
  1112. status = queue_kernel_parameters(clState, &work->blk);
  1113. if (unlikely(status != CL_SUCCESS))
  1114. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1115. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1116. if (res[MAXBUFFERS]) {
  1117. /* Clear the buffer again */
  1118. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1119. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1120. if (unlikely(status != CL_SUCCESS))
  1121. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1122. if (opt_debug)
  1123. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  1124. postcalc_hash_async(mythr, work, res);
  1125. memset(res, 0, BUFFERSIZE);
  1126. clFinish(clState->commandQueue);
  1127. }
  1128. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1129. globalThreads, localThreads, 0, NULL, NULL);
  1130. if (unlikely(status != CL_SUCCESS))
  1131. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1132. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1133. BUFFERSIZE, res, 0, NULL, NULL);
  1134. if (unlikely(status != CL_SUCCESS))
  1135. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1136. gettimeofday(&tv_end, NULL);
  1137. timeval_subtract(&diff, &tv_end, &tv_start);
  1138. hashes_done += hashes;
  1139. work->blk.nonce += hashes;
  1140. if (diff.tv_usec > 500000)
  1141. diff.tv_sec++;
  1142. if (diff.tv_sec >= cycle) {
  1143. hashmeter(thr_id, &diff, hashes_done);
  1144. gettimeofday(&tv_start, NULL);
  1145. hashes_done = 0;
  1146. }
  1147. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1148. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1149. if (unlikely(!queue_request())) {
  1150. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1151. goto out;
  1152. }
  1153. requested = true;
  1154. }
  1155. }
  1156. out:
  1157. tq_freeze(mythr->q);
  1158. return NULL;
  1159. }
  1160. #endif /* HAVE_OPENCL */
  1161. static void restart_threads(void)
  1162. {
  1163. int i;
  1164. /* Discard old queued requests and get new ones */
  1165. flush_requests();
  1166. for (i = 0; i < opt_n_threads + gpu_threads; i++)
  1167. work_restart[i].restart = 1;
  1168. }
  1169. static void *longpoll_thread(void *userdata)
  1170. {
  1171. struct thr_info *mythr = userdata;
  1172. CURL *curl = NULL;
  1173. char *copy_start, *hdr_path, *lp_url = NULL;
  1174. bool need_slash = false;
  1175. int failures = 0;
  1176. hdr_path = tq_pop(mythr->q, NULL);
  1177. if (!hdr_path)
  1178. goto out;
  1179. /* full URL */
  1180. if (strstr(hdr_path, "://")) {
  1181. lp_url = hdr_path;
  1182. hdr_path = NULL;
  1183. }
  1184. /* absolute path, on current server */
  1185. else {
  1186. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1187. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1188. need_slash = true;
  1189. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1190. if (!lp_url)
  1191. goto out;
  1192. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1193. }
  1194. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1195. curl = curl_easy_init();
  1196. if (unlikely(!curl)) {
  1197. applog(LOG_ERR, "CURL initialisation failed");
  1198. goto out;
  1199. }
  1200. while (1) {
  1201. json_t *val;
  1202. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1203. false, true);
  1204. if (likely(val)) {
  1205. failures = 0;
  1206. json_decref(val);
  1207. if (!opt_quiet)
  1208. printf("LONGPOLL detected new block \n");
  1209. applog(LOG_INFO, "LONGPOLL detected new block");
  1210. restart_threads();
  1211. } else {
  1212. if (failures++ < 10) {
  1213. sleep(30);
  1214. applog(LOG_ERR,
  1215. "longpoll failed, sleeping for 30s");
  1216. } else {
  1217. applog(LOG_ERR,
  1218. "longpoll failed, ending thread");
  1219. goto out;
  1220. }
  1221. }
  1222. }
  1223. out:
  1224. free(hdr_path);
  1225. free(lp_url);
  1226. tq_freeze(mythr->q);
  1227. if (curl)
  1228. curl_easy_cleanup(curl);
  1229. return NULL;
  1230. }
  1231. /* Makes sure the hashmeter keeps going even if mining threads stall */
  1232. static void *wakeup_thread(void *userdata)
  1233. {
  1234. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1235. struct timeval zero_tv;
  1236. memset(&zero_tv, 0, sizeof(struct timeval));
  1237. while (1) {
  1238. sleep(interval);
  1239. hashmeter(-1, &zero_tv, 0);
  1240. }
  1241. return NULL;
  1242. }
  1243. int main (int argc, char *argv[])
  1244. {
  1245. struct thr_info *thr;
  1246. unsigned int i;
  1247. char name[32];
  1248. struct cgpu_info *gpus = NULL, *cpus = NULL;
  1249. #ifdef WIN32
  1250. opt_n_threads = num_processors = 1;
  1251. #else
  1252. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1253. opt_n_threads = num_processors;
  1254. #endif /* !WIN32 */
  1255. #ifdef HAVE_OPENCL
  1256. nDevs = clDevicesNum();
  1257. if (nDevs < 0)
  1258. return 1;
  1259. #endif
  1260. if (nDevs)
  1261. opt_n_threads = 0;
  1262. rpc_url = strdup(DEF_RPC_URL);
  1263. /* parse command line */
  1264. opt_register_table(opt_config_table,
  1265. "Options for both config file and command line");
  1266. opt_register_table(opt_cmdline_table,
  1267. "Options for command line only");
  1268. opt_parse(&argc, argv, applog_and_exit);
  1269. if (argc != 1) {
  1270. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1271. return 1;
  1272. }
  1273. gpu_threads = nDevs * opt_g_threads;
  1274. if (!gpu_threads && !forced_n_threads) {
  1275. /* Maybe they turned GPU off; restore default CPU threads. */
  1276. opt_n_threads = num_processors;
  1277. }
  1278. if (!rpc_userpass) {
  1279. if (!rpc_user || !rpc_pass) {
  1280. applog(LOG_ERR, "No login credentials supplied");
  1281. return 1;
  1282. }
  1283. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1284. if (!rpc_userpass)
  1285. return 1;
  1286. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1287. }
  1288. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  1289. return 1;
  1290. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1291. return 1;
  1292. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1293. return 1;
  1294. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1295. return 1;
  1296. #ifdef HAVE_SYSLOG_H
  1297. if (use_syslog)
  1298. openlog("cpuminer", LOG_PID, LOG_USER);
  1299. #endif
  1300. work_restart = calloc(opt_n_threads + gpu_threads, sizeof(*work_restart));
  1301. if (!work_restart)
  1302. return 1;
  1303. thr_info = calloc(opt_n_threads + 3 + gpu_threads, sizeof(*thr));
  1304. if (!thr_info)
  1305. return 1;
  1306. /* init workio thread info */
  1307. work_thr_id = opt_n_threads + gpu_threads;
  1308. thr = &thr_info[work_thr_id];
  1309. thr->id = work_thr_id;
  1310. thr->q = tq_new();
  1311. if (!thr->q)
  1312. return 1;
  1313. /* start work I/O thread */
  1314. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1315. applog(LOG_ERR, "workio thread create failed");
  1316. return 1;
  1317. }
  1318. /* init longpoll thread info */
  1319. if (want_longpoll) {
  1320. longpoll_thr_id = opt_n_threads + gpu_threads + 1;
  1321. thr = &thr_info[longpoll_thr_id];
  1322. thr->id = longpoll_thr_id;
  1323. thr->q = tq_new();
  1324. if (!thr->q)
  1325. return 1;
  1326. /* start longpoll thread */
  1327. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1328. applog(LOG_ERR, "longpoll thread create failed");
  1329. return 1;
  1330. }
  1331. pthread_detach(thr->pth);
  1332. } else
  1333. longpoll_thr_id = -1;
  1334. gettimeofday(&total_tv_start, NULL);
  1335. gettimeofday(&total_tv_end, NULL);
  1336. if (opt_n_threads ) {
  1337. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1338. if (unlikely(!cpus)) {
  1339. applog(LOG_ERR, "Failed to calloc cpus");
  1340. return 1;
  1341. }
  1342. }
  1343. if (gpu_threads) {
  1344. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1345. if (unlikely(!gpus)) {
  1346. applog(LOG_ERR, "Failed to calloc gpus");
  1347. return 1;
  1348. }
  1349. }
  1350. /* Put enough work in the queue */
  1351. for (i = 0; i < opt_queue + opt_n_threads + gpu_threads; i++) {
  1352. if (unlikely(!queue_request())) {
  1353. applog(LOG_ERR, "Failed to queue_request in main");
  1354. return 1;
  1355. }
  1356. }
  1357. #ifdef HAVE_OPENCL
  1358. /* start GPU mining threads */
  1359. for (i = 0; i < gpu_threads; i++) {
  1360. int gpu = gpu_from_thr_id(i);
  1361. thr = &thr_info[i];
  1362. thr->id = i;
  1363. gpus[gpu].is_gpu = 1;
  1364. gpus[gpu].cpu_gpu = gpu;
  1365. thr->cgpu = &gpus[gpu];
  1366. thr->q = tq_new();
  1367. if (!thr->q) {
  1368. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1369. return 1;
  1370. }
  1371. applog(LOG_INFO, "Init GPU thread %i", i);
  1372. clStates[i] = initCl(gpu, name, sizeof(name));
  1373. if (!clStates[i]) {
  1374. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1375. continue;
  1376. }
  1377. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1378. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1379. applog(LOG_ERR, "thread %d create failed", i);
  1380. return 1;
  1381. }
  1382. pthread_detach(thr->pth);
  1383. }
  1384. applog(LOG_INFO, "%d gpu miner threads started", i);
  1385. #endif
  1386. /* start CPU mining threads */
  1387. for (i = gpu_threads; i < gpu_threads + opt_n_threads; i++) {
  1388. int cpu = cpu_from_thr_id(i);
  1389. thr = &thr_info[i];
  1390. thr->id = i;
  1391. cpus[cpu].cpu_gpu = cpu;
  1392. thr->cgpu = &cpus[cpu];
  1393. thr->q = tq_new();
  1394. if (!thr->q) {
  1395. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1396. return 1;
  1397. }
  1398. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1399. applog(LOG_ERR, "thread %d create failed", i);
  1400. return 1;
  1401. }
  1402. pthread_detach(thr->pth);
  1403. }
  1404. applog(LOG_INFO, "%d cpu miner threads started, "
  1405. "using SHA256 '%s' algorithm.",
  1406. opt_n_threads,
  1407. algo_names[opt_algo]);
  1408. thr = &thr_info[opt_n_threads + gpu_threads + 2];
  1409. /* start wakeup thread */
  1410. if (pthread_create(&thr->pth, NULL, wakeup_thread, NULL)) {
  1411. applog(LOG_ERR, "wakeup thread create failed");
  1412. return 1;
  1413. }
  1414. /* Restart count as it will be wrong till all threads are started */
  1415. pthread_mutex_lock(&hash_lock);
  1416. gettimeofday(&total_tv_start, NULL);
  1417. gettimeofday(&total_tv_end, NULL);
  1418. total_mhashes_done = 0;
  1419. pthread_mutex_unlock(&hash_lock);
  1420. /* main loop - simply wait for workio thread to exit */
  1421. pthread_join(thr_info[work_thr_id].pth, NULL);
  1422. curl_global_cleanup();
  1423. if (gpu_threads)
  1424. free(gpus);
  1425. if (opt_n_threads)
  1426. free(cpus);
  1427. applog(LOG_INFO, "workio thread dead, exiting.");
  1428. return 0;
  1429. }