cpu-miner.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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 "cpuminer-config.h"
  11. #define _GNU_SOURCE
  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. #ifndef WIN32
  22. #include <sys/resource.h>
  23. #endif
  24. #include <getopt.h>
  25. #include <jansson.h>
  26. #include <curl/curl.h>
  27. #include "compat.h"
  28. #include "miner.h"
  29. #include "findnonce.h"
  30. #include "ocl.h"
  31. #define PROGRAM_NAME "minerd"
  32. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  33. #define DEF_RPC_USERNAME "rpcuser"
  34. #define DEF_RPC_PASSWORD "rpcpass"
  35. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  36. #ifdef __linux /* Linux specific policy and affinity management */
  37. #include <sched.h>
  38. static inline void drop_policy(void)
  39. {
  40. struct sched_param param;
  41. #ifdef SCHED_IDLE
  42. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  43. #endif
  44. #ifdef SCHED_BATCH
  45. sched_setscheduler(0, SCHED_BATCH, &param);
  46. #endif
  47. }
  48. static inline void affine_to_cpu(int id, int cpu)
  49. {
  50. cpu_set_t set;
  51. CPU_ZERO(&set);
  52. CPU_SET(cpu, &set);
  53. sched_setaffinity(0, sizeof(&set), &set);
  54. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  55. }
  56. #else
  57. static inline void drop_policy(void)
  58. {
  59. }
  60. static inline void affine_to_cpu(int id, int cpu)
  61. {
  62. }
  63. #endif
  64. enum workio_commands {
  65. WC_GET_WORK,
  66. WC_SUBMIT_WORK,
  67. };
  68. struct workio_cmd {
  69. enum workio_commands cmd;
  70. struct thr_info *thr;
  71. union {
  72. struct work *work;
  73. } u;
  74. };
  75. enum sha256_algos {
  76. ALGO_C, /* plain C */
  77. ALGO_4WAY, /* parallel SSE2 */
  78. ALGO_VIA, /* VIA padlock */
  79. ALGO_CRYPTOPP, /* Crypto++ (C) */
  80. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  81. ALGO_SSE2_64, /* SSE2 for x86_64 */
  82. };
  83. static const char *algo_names[] = {
  84. [ALGO_C] = "c",
  85. #ifdef WANT_SSE2_4WAY
  86. [ALGO_4WAY] = "4way",
  87. #endif
  88. #ifdef WANT_VIA_PADLOCK
  89. [ALGO_VIA] = "via",
  90. #endif
  91. [ALGO_CRYPTOPP] = "cryptopp",
  92. #ifdef WANT_CRYPTOPP_ASM32
  93. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  94. #endif
  95. #ifdef WANT_X8664_SSE2
  96. [ALGO_SSE2_64] = "sse2_64",
  97. #endif
  98. };
  99. bool opt_debug = false;
  100. bool opt_protocol = false;
  101. bool opt_ndevs = false;
  102. bool want_longpoll = true;
  103. bool have_longpoll = false;
  104. bool use_syslog = false;
  105. static bool opt_quiet = false;
  106. static int opt_retries = 10;
  107. static int opt_fail_pause = 30;
  108. static int opt_log_interval = 5;
  109. int opt_vectors;
  110. int opt_worksize;
  111. int opt_scantime = 60;
  112. static json_t *opt_config;
  113. static const bool opt_time = true;
  114. #ifdef WANT_X8664_SSE2
  115. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  116. #else
  117. static enum sha256_algos opt_algo = ALGO_C;
  118. #endif
  119. static int nDevs;
  120. static int opt_g_threads = 2;
  121. static int gpu_threads;
  122. static int opt_n_threads = 1;
  123. static int num_processors;
  124. static int scan_intensity = 4;
  125. static char *rpc_url;
  126. static char *rpc_userpass;
  127. static char *rpc_user, *rpc_pass;
  128. struct thr_info *thr_info;
  129. static int work_thr_id;
  130. int longpoll_thr_id;
  131. struct work_restart *work_restart = NULL;
  132. pthread_mutex_t time_lock;
  133. static pthread_mutex_t hash_lock;
  134. static pthread_mutex_t get_lock;
  135. static double total_mhashes_done;
  136. static struct timeval total_tv_start, total_tv_end;
  137. static int accepted, rejected;
  138. struct option_help {
  139. const char *name;
  140. const char *helptext;
  141. };
  142. static struct option_help options_help[] = {
  143. { "help",
  144. "(-h) Display this help text" },
  145. { "algo XXX",
  146. "(-a XXX) Specify sha256 implementation:\n"
  147. "\tc\t\tLinux kernel sha256, implemented in C (default)"
  148. #ifdef WANT_SSE2_4WAY
  149. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  150. #endif
  151. #ifdef WANT_VIA_PADLOCK
  152. "\n\tvia\t\tVIA padlock implementation"
  153. #endif
  154. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  155. #ifdef WANT_CRYPTOPP_ASM32
  156. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  157. #endif
  158. #ifdef WANT_X8664_SSE2
  159. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  160. #endif
  161. },
  162. { "config FILE",
  163. "(-c FILE) JSON-format configuration file (default: none)\n"
  164. "See example-cfg.json for an example configuration." },
  165. { "cpu-threads N",
  166. "(-t N) Number of miner CPU threads (default: number of processors or 0 if GPU mining)" },
  167. { "debug",
  168. "(-D) Enable debug output (default: off)" },
  169. { "gpu-threads N",
  170. "(-g N) Number of threads per-GPU (1 - 10, default: 2)" },
  171. { "intensity",
  172. "(-I) Intensity of scanning (0 - 10, default 4)" },
  173. { "log",
  174. "(-l) Interval in seconds between log output (default: 5)" },
  175. { "ndevs",
  176. "(-n) Display number of detected GPUs" },
  177. { "no-longpoll",
  178. "Disable X-Long-Polling support (default: enabled)" },
  179. { "pass PASSWORD",
  180. "(-p PASSWORD) Password for bitcoin JSON-RPC server "
  181. "(default: " DEF_RPC_PASSWORD ")" },
  182. { "protocol-dump",
  183. "(-P) Verbose dump of protocol-level activities (default: off)" },
  184. { "quiet",
  185. "(-q) Disable per-thread hashmeter output (default: off)" },
  186. { "retries N",
  187. "(-r N) Number of times to retry, if JSON-RPC call fails\n"
  188. "\t(default: 10; use -1 for \"never\")" },
  189. { "retry-pause N",
  190. "(-R N) Number of seconds to pause, between retries\n"
  191. "\t(default: 30)" },
  192. { "scantime N",
  193. "(-s N) Upper bound on time spent scanning current work,\n"
  194. "\tin seconds. (default: 60)" },
  195. #ifdef HAVE_SYSLOG_H
  196. { "syslog",
  197. "Use system log for output messages (default: standard error)" },
  198. #endif
  199. { "url URL",
  200. "URL for bitcoin JSON-RPC server "
  201. "(default: " DEF_RPC_URL ")" },
  202. { "userpass USERNAME:PASSWORD",
  203. "Username:Password pair for bitcoin JSON-RPC server "
  204. "(default: " DEF_RPC_USERPASS ")" },
  205. { "user USERNAME",
  206. "(-u USERNAME) Username for bitcoin JSON-RPC server "
  207. "(default: " DEF_RPC_USERNAME ")" },
  208. { "vectors N",
  209. "(-v N) Override detected optimal vector width (default: detected, 1,2 or 4)" },
  210. { "worksize N",
  211. "(-w N) Override detected optimal worksize (default: detected)" },
  212. };
  213. static struct option options[] = {
  214. { "algo", 1, NULL, 'a' },
  215. { "config", 1, NULL, 'c' },
  216. { "cpu-threads", 1, NULL, 't' },
  217. { "gpu-threads", 1, NULL, 'g' },
  218. { "debug", 0, NULL, 'D' },
  219. { "help", 0, NULL, 'h' },
  220. { "intensity", 1, NULL, 'I' },
  221. { "log", 1, NULL, 'l' },
  222. { "ndevs", 0, NULL, 'n' },
  223. { "no-longpoll", 0, NULL, 1003 },
  224. { "pass", 1, NULL, 'p' },
  225. { "protocol-dump", 0, NULL, 'P' },
  226. { "quiet", 0, NULL, 'q' },
  227. { "retries", 1, NULL, 'r' },
  228. { "retry-pause", 1, NULL, 'R' },
  229. { "scantime", 1, NULL, 's' },
  230. #ifdef HAVE_SYSLOG_H
  231. { "syslog", 0, NULL, 1004 },
  232. #endif
  233. { "url", 1, NULL, 1001 },
  234. { "user", 1, NULL, 'u' },
  235. { "vectors", 1, NULL, 'v' },
  236. { "worksize", 1, NULL, 'w' },
  237. { "userpass", 1, NULL, 1002 },
  238. };
  239. static bool jobj_binary(const json_t *obj, const char *key,
  240. void *buf, size_t buflen)
  241. {
  242. const char *hexstr;
  243. json_t *tmp;
  244. tmp = json_object_get(obj, key);
  245. if (unlikely(!tmp)) {
  246. applog(LOG_ERR, "JSON key '%s' not found", key);
  247. return false;
  248. }
  249. hexstr = json_string_value(tmp);
  250. if (unlikely(!hexstr)) {
  251. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  252. return false;
  253. }
  254. if (!hex2bin(buf, hexstr, buflen))
  255. return false;
  256. return true;
  257. }
  258. static bool work_decode(const json_t *val, struct work *work)
  259. {
  260. if (unlikely(!jobj_binary(val, "midstate",
  261. work->midstate, sizeof(work->midstate)))) {
  262. applog(LOG_ERR, "JSON inval midstate");
  263. goto err_out;
  264. }
  265. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  266. applog(LOG_ERR, "JSON inval data");
  267. goto err_out;
  268. }
  269. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  270. applog(LOG_ERR, "JSON inval hash1");
  271. goto err_out;
  272. }
  273. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  274. applog(LOG_ERR, "JSON inval target");
  275. goto err_out;
  276. }
  277. memset(work->hash, 0, sizeof(work->hash));
  278. return true;
  279. err_out:
  280. return false;
  281. }
  282. static bool submit_upstream_work(CURL *curl, const struct work *work)
  283. {
  284. char *hexstr = NULL;
  285. json_t *val, *res;
  286. char s[345];
  287. bool rc = false;
  288. /* build hex string */
  289. hexstr = bin2hex(work->data, sizeof(work->data));
  290. if (unlikely(!hexstr)) {
  291. applog(LOG_ERR, "submit_upstream_work OOM");
  292. goto out;
  293. }
  294. /* build JSON-RPC request */
  295. sprintf(s,
  296. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  297. hexstr);
  298. if (opt_debug)
  299. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  300. /* issue JSON-RPC request */
  301. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  302. if (unlikely(!val)) {
  303. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  304. goto out;
  305. }
  306. res = json_object_get(val, "result");
  307. /* Theoretically threads could race when modifying accepted and
  308. * rejected values but the chance of two submits completing at the
  309. * same time is zero so there is no point adding extra locking */
  310. if (json_is_true(res)) {
  311. accepted++;
  312. applog(LOG_INFO, "PROOF OF WORK RESULT: true (yay!!!)");
  313. } else {
  314. rejected++;
  315. applog(LOG_INFO, "PROOF OF WORK RESULT: false (booooo)");
  316. }
  317. json_decref(val);
  318. rc = true;
  319. out:
  320. free(hexstr);
  321. return rc;
  322. }
  323. static const char *rpc_req =
  324. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  325. static bool get_upstream_work(CURL *curl, struct work *work)
  326. {
  327. json_t *val;
  328. bool rc;
  329. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  330. want_longpoll, false);
  331. if (!val)
  332. return false;
  333. rc = work_decode(json_object_get(val, "result"), work);
  334. json_decref(val);
  335. return rc;
  336. }
  337. static void workio_cmd_free(struct workio_cmd *wc)
  338. {
  339. if (!wc)
  340. return;
  341. switch (wc->cmd) {
  342. case WC_SUBMIT_WORK:
  343. free(wc->u.work);
  344. break;
  345. default: /* do nothing */
  346. break;
  347. }
  348. memset(wc, 0, sizeof(*wc)); /* poison */
  349. free(wc);
  350. }
  351. static bool workio_get_work(struct workio_cmd *wc, CURL *curl)
  352. {
  353. struct work *ret_work;
  354. int failures = 0;
  355. ret_work = calloc(1, sizeof(*ret_work));
  356. if (!ret_work) {
  357. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  358. return false;
  359. }
  360. /* obtain new work from bitcoin via JSON-RPC */
  361. while (!get_upstream_work(curl, ret_work)) {
  362. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  363. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  364. free(ret_work);
  365. return false;
  366. }
  367. /* pause, then restart work-request loop */
  368. applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
  369. opt_fail_pause);
  370. sleep(opt_fail_pause);
  371. }
  372. /* send work to requesting thread */
  373. if (unlikely(!tq_push(wc->thr->q, ret_work))) {
  374. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  375. free(ret_work);
  376. }
  377. return true;
  378. }
  379. static bool workio_submit_work(struct workio_cmd *wc, CURL *curl)
  380. {
  381. int failures = 0;
  382. /* submit solution to bitcoin via JSON-RPC */
  383. while (!submit_upstream_work(curl, wc->u.work)) {
  384. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  385. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  386. return false;
  387. }
  388. /* pause, then restart work-request loop */
  389. applog(LOG_ERR, "...retry after %d seconds",
  390. opt_fail_pause);
  391. sleep(opt_fail_pause);
  392. }
  393. return true;
  394. }
  395. static void *workio_thread(void *userdata)
  396. {
  397. struct thr_info *mythr = userdata;
  398. bool ok = true;
  399. CURL *curl;
  400. curl = curl_easy_init();
  401. if (unlikely(!curl)) {
  402. applog(LOG_ERR, "CURL initialization failed");
  403. return NULL;
  404. }
  405. while (ok) {
  406. struct workio_cmd *wc;
  407. /* wait for workio_cmd sent to us, on our queue */
  408. wc = tq_pop(mythr->q, NULL);
  409. if (!wc) {
  410. ok = false;
  411. break;
  412. }
  413. /* process workio_cmd */
  414. switch (wc->cmd) {
  415. case WC_GET_WORK:
  416. ok = workio_get_work(wc, curl);
  417. break;
  418. case WC_SUBMIT_WORK:
  419. ok = workio_submit_work(wc, curl);
  420. break;
  421. default: /* should never happen */
  422. ok = false;
  423. break;
  424. }
  425. workio_cmd_free(wc);
  426. }
  427. tq_freeze(mythr->q);
  428. curl_easy_cleanup(curl);
  429. return NULL;
  430. }
  431. static void hashmeter(int thr_id, struct timeval *diff,
  432. unsigned long hashes_done)
  433. {
  434. struct timeval temp_tv_end, total_diff;
  435. double khashes, secs;
  436. double total_secs;
  437. double local_secs;
  438. static double local_mhashes_done = 0;
  439. double local_mhashes = (double)hashes_done / 1000000.0;
  440. /* Don't bother calculating anything if we're not displaying it */
  441. if (opt_quiet || !opt_log_interval)
  442. return;
  443. khashes = hashes_done / 1000.0;
  444. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  445. if (opt_debug)
  446. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  447. thr_id, hashes_done, hashes_done / secs);
  448. gettimeofday(&temp_tv_end, NULL);
  449. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  450. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  451. if (opt_n_threads + gpu_threads > 1) {
  452. /* Totals are updated by all threads so can race without locking */
  453. pthread_mutex_lock(&hash_lock);
  454. total_mhashes_done += local_mhashes;
  455. local_mhashes_done += local_mhashes;
  456. if (total_diff.tv_sec < opt_log_interval) {
  457. /* Only update the total every opt_log_interval seconds */
  458. pthread_mutex_unlock(&hash_lock);
  459. return;
  460. }
  461. gettimeofday(&total_tv_end, NULL);
  462. pthread_mutex_unlock(&hash_lock);
  463. } else {
  464. total_mhashes_done += local_mhashes;
  465. local_mhashes_done += local_mhashes;
  466. if (total_diff.tv_sec < opt_log_interval)
  467. return;
  468. gettimeofday(&total_tv_end, NULL);
  469. }
  470. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  471. total_secs = (double)total_diff.tv_sec +
  472. ((double)total_diff.tv_usec / 1000000.0);
  473. applog(LOG_INFO, "[%.2f | %.2f Mhash/s] [%d Accepted] [%d Rejected]",
  474. local_mhashes_done / local_secs,
  475. total_mhashes_done / total_secs, accepted, rejected);
  476. local_mhashes_done = 0;
  477. }
  478. static struct work *work_heap = NULL;
  479. /* Since we always have one extra work item queued, set the thread id to 0
  480. * for all the work and just give the work to the first thread that requests
  481. * work */
  482. static bool get_work(struct work *work)
  483. {
  484. struct thr_info *thr = &thr_info[0];
  485. struct workio_cmd *wc;
  486. bool ret = false;
  487. /* fill out work request message */
  488. wc = calloc(1, sizeof(*wc));
  489. if (unlikely(!wc))
  490. goto out;
  491. wc->cmd = WC_GET_WORK;
  492. wc->thr = thr;
  493. /* send work request to workio thread */
  494. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  495. workio_cmd_free(wc);
  496. goto out;
  497. }
  498. /* work_heap is protected by get_lock */
  499. pthread_mutex_lock(&get_lock);
  500. if (likely(work_heap)) {
  501. memcpy(work, work_heap, sizeof(*work));
  502. /* Wait for next response, a unit of work - it should be queued */
  503. free(work_heap);
  504. work_heap = tq_pop(thr->q, NULL);
  505. } else {
  506. /* wait for 1st response, or 1st response after failure */
  507. work_heap = tq_pop(thr->q, NULL);
  508. if (unlikely(!work_heap))
  509. goto out_unlock;
  510. /* send for another work request for the next time get_work
  511. * is called. */
  512. wc = calloc(1, sizeof(*wc));
  513. if (unlikely(!wc)) {
  514. free(work_heap);
  515. work_heap = NULL;
  516. goto out_unlock;
  517. }
  518. wc->cmd = WC_GET_WORK;
  519. wc->thr = thr;
  520. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  521. workio_cmd_free(wc);
  522. free(work_heap);
  523. work_heap = NULL;
  524. goto out_unlock;
  525. }
  526. }
  527. ret = true;
  528. out_unlock:
  529. pthread_mutex_unlock(&get_lock);
  530. out:
  531. return ret;
  532. }
  533. struct submit_data {
  534. struct thr_info *thr;
  535. struct work work_in;
  536. pthread_t pth;
  537. };
  538. static void *submit_work(void *userdata)
  539. {
  540. struct submit_data *sd = (struct submit_data *)userdata;
  541. struct workio_cmd *wc;
  542. /* fill out work request message */
  543. wc = calloc(1, sizeof(*wc));
  544. if (unlikely(!wc))
  545. goto out;
  546. wc->u.work = malloc(sizeof(struct work));
  547. if (unlikely(!wc->u.work))
  548. goto err_out;
  549. wc->cmd = WC_SUBMIT_WORK;
  550. wc->thr = sd->thr;
  551. memcpy(wc->u.work, &sd->work_in, sizeof(struct work));
  552. /* send solution to workio thread */
  553. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc)))
  554. goto err_out;
  555. goto out;
  556. err_out:
  557. workio_cmd_free(wc);
  558. out:
  559. free(sd);
  560. }
  561. static bool submit_work_async(struct thr_info *thr, const struct work *work_in)
  562. {
  563. struct submit_data *sd = malloc(sizeof(struct submit_data));
  564. if (unlikely(!sd)) {
  565. applog(LOG_ERR, "Failed to malloc sd in submit_work_async");
  566. return false;
  567. }
  568. memcpy(&sd->work_in, work_in, sizeof(struct work));
  569. if (pthread_create(&sd->pth, NULL, submit_work, (void *)sd)) {
  570. applog(LOG_ERR, "Failed to create submit_thread");
  571. return false;
  572. }
  573. pthread_detach(sd->pth);
  574. return true;
  575. }
  576. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  577. {
  578. work->data[64+12+0] = (nonce>>0) & 0xff;
  579. work->data[64+12+1] = (nonce>>8) & 0xff;
  580. work->data[64+12+2] = (nonce>>16) & 0xff;
  581. work->data[64+12+3] = (nonce>>24) & 0xff;
  582. return submit_work_async(thr, work);
  583. }
  584. static inline int cpu_from_thr_id(int thr_id)
  585. {
  586. return (thr_id - gpu_threads) % num_processors;
  587. }
  588. static void *miner_thread(void *userdata)
  589. {
  590. struct thr_info *mythr = userdata;
  591. int thr_id = mythr->id;
  592. uint32_t max_nonce = 0xffffff;
  593. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  594. * and if that fails, then SCHED_BATCH. No need for this to be an
  595. * error if it fails */
  596. setpriority(PRIO_PROCESS, 0, 19);
  597. drop_policy();
  598. /* Cpu affinity only makes sense if the number of threads is a multiple
  599. * of the number of CPUs */
  600. if (!(opt_n_threads % num_processors))
  601. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  602. while (1) {
  603. struct work work __attribute__((aligned(128)));
  604. unsigned long hashes_done;
  605. struct timeval tv_start, tv_end, diff;
  606. uint64_t max64;
  607. bool rc;
  608. /* obtain new work from internal workio thread */
  609. if (unlikely(!get_work(&work))) {
  610. applog(LOG_ERR, "work retrieval failed, exiting "
  611. "mining thread %d", mythr->id);
  612. goto out;
  613. }
  614. hashes_done = 0;
  615. gettimeofday(&tv_start, NULL);
  616. /* scan nonces for a proof-of-work hash */
  617. switch (opt_algo) {
  618. case ALGO_C:
  619. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  620. work.hash1, work.hash, work.target,
  621. max_nonce, &hashes_done);
  622. break;
  623. #ifdef WANT_X8664_SSE2
  624. case ALGO_SSE2_64: {
  625. unsigned int rc5 =
  626. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  627. work.hash1, work.hash,
  628. work.target,
  629. max_nonce, &hashes_done);
  630. rc = (rc5 == -1) ? false : true;
  631. }
  632. break;
  633. #endif
  634. #ifdef WANT_SSE2_4WAY
  635. case ALGO_4WAY: {
  636. unsigned int rc4 =
  637. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  638. work.hash1, work.hash,
  639. work.target,
  640. max_nonce, &hashes_done);
  641. rc = (rc4 == -1) ? false : true;
  642. }
  643. break;
  644. #endif
  645. #ifdef WANT_VIA_PADLOCK
  646. case ALGO_VIA:
  647. rc = scanhash_via(thr_id, work.data, work.target,
  648. max_nonce, &hashes_done);
  649. break;
  650. #endif
  651. case ALGO_CRYPTOPP:
  652. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  653. work.hash1, work.hash, work.target,
  654. max_nonce, &hashes_done);
  655. break;
  656. #ifdef WANT_CRYPTOPP_ASM32
  657. case ALGO_CRYPTOPP_ASM32:
  658. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  659. work.hash1, work.hash, work.target,
  660. max_nonce, &hashes_done);
  661. break;
  662. #endif
  663. default:
  664. /* should never happen */
  665. goto out;
  666. }
  667. /* record scanhash elapsed time */
  668. gettimeofday(&tv_end, NULL);
  669. timeval_subtract(&diff, &tv_end, &tv_start);
  670. hashmeter(thr_id, &diff, hashes_done);
  671. /* adjust max_nonce to meet target scan time */
  672. if (diff.tv_usec > 500000)
  673. diff.tv_sec++;
  674. if (diff.tv_sec > 0) {
  675. max64 =
  676. ((uint64_t)hashes_done * opt_scantime) / diff.tv_sec;
  677. if (max64 > 0xfffffffaULL)
  678. max64 = 0xfffffffaULL;
  679. max_nonce = max64;
  680. }
  681. /* if nonce found, submit work */
  682. if (unlikely(rc)) {
  683. applog(LOG_INFO, "CPU %d found something?", cpu_from_thr_id(thr_id));
  684. if (!submit_work_async(mythr, &work))
  685. break;
  686. }
  687. }
  688. out:
  689. tq_freeze(mythr->q);
  690. return NULL;
  691. }
  692. enum {
  693. STAT_SLEEP_INTERVAL = 1,
  694. STAT_CTR_INTERVAL = 10000000,
  695. FAILURE_INTERVAL = 30,
  696. };
  697. static _clState *clStates[16];
  698. static inline cl_int queue_kernel_parameters(dev_blk_ctx *blk, cl_kernel *kernel,
  699. struct _cl_mem *output)
  700. {
  701. cl_int status = 0;
  702. int num = 0;
  703. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  704. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  705. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  706. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  707. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  708. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  709. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  710. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  711. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  712. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  713. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  714. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  715. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  716. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  717. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  718. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  719. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  720. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  721. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  722. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  723. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  724. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  725. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  726. status |= clSetKernelArg(*kernel, num++, sizeof(output), (void *)&output);
  727. return status;
  728. }
  729. static inline int gpu_from_thr_id(int thr_id)
  730. {
  731. return thr_id % nDevs;
  732. }
  733. static void *gpuminer_thread(void *userdata)
  734. {
  735. struct thr_info *mythr = userdata;
  736. struct timeval tv_start;
  737. int thr_id = mythr->id;
  738. uint32_t res[128], blank_res[128];
  739. cl_kernel *kernel;
  740. memset(blank_res, 0, BUFFERSIZE);
  741. size_t globalThreads[1];
  742. size_t localThreads[1];
  743. cl_int status;
  744. _clState *clState = clStates[thr_id];
  745. kernel = &clState->kernel;
  746. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  747. BUFFERSIZE, blank_res, 0, NULL, NULL);
  748. if (unlikely(status != CL_SUCCESS))
  749. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  750. struct work *work = malloc(sizeof(struct work));
  751. bool need_work = true;
  752. unsigned const int threads = 1 << (15 + scan_intensity);
  753. unsigned const int vectors = clState->preferred_vwidth;
  754. unsigned const int hashes = threads * vectors;
  755. unsigned int hashes_done = 0;
  756. gettimeofday(&tv_start, NULL);
  757. globalThreads[0] = threads;
  758. localThreads[0] = clState->work_size;
  759. while (1) {
  760. struct timeval tv_end, diff, tv_workstart;
  761. unsigned int i;
  762. clFinish(clState->commandQueue);
  763. if (need_work) {
  764. gettimeofday(&tv_workstart, NULL);
  765. /* obtain new work from internal workio thread */
  766. if (unlikely(!get_work(work))) {
  767. applog(LOG_ERR, "work retrieval failed, exiting "
  768. "gpu mining thread %d", mythr->id);
  769. goto out;
  770. }
  771. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  772. work->blk.nonce = 0;
  773. status = queue_kernel_parameters(&work->blk, kernel, clState->outputBuffer);
  774. if (unlikely(status != CL_SUCCESS))
  775. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  776. work_restart[thr_id].restart = 0;
  777. need_work = false;
  778. if (opt_debug)
  779. applog(LOG_DEBUG, "getwork");
  780. } else {
  781. status = clSetKernelArg(*kernel, 14, sizeof(uint), (void *)&work->blk.nonce);
  782. if (unlikely(status != CL_SUCCESS))
  783. { applog(LOG_ERR, "Error: clSetKernelArg of nonce failed."); goto out; }
  784. }
  785. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  786. globalThreads, localThreads, 0, NULL, NULL);
  787. if (unlikely(status != CL_SUCCESS))
  788. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  789. /* 127 is used as a flag to say nonces exist */
  790. if (unlikely(res[127])) {
  791. /* Clear the buffer again */
  792. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  793. BUFFERSIZE, blank_res, 0, NULL, NULL);
  794. if (unlikely(status != CL_SUCCESS))
  795. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  796. for (i = 0; i < 127; i++) {
  797. if (res[i]) {
  798. applog(LOG_INFO, "GPU %d found something?", gpu_from_thr_id(thr_id));
  799. postcalc_hash_async(mythr, work, res[i]);
  800. } else
  801. break;
  802. }
  803. clFinish(clState->commandQueue);
  804. }
  805. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  806. BUFFERSIZE, res, 0, NULL, NULL);
  807. if (unlikely(status != CL_SUCCESS))
  808. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  809. gettimeofday(&tv_end, NULL);
  810. timeval_subtract(&diff, &tv_end, &tv_start);
  811. hashes_done += hashes;
  812. work->blk.nonce += hashes;
  813. if (diff.tv_sec >= 1) {
  814. hashmeter(thr_id, &diff, hashes_done);
  815. gettimeofday(&tv_start, NULL);
  816. hashes_done = 0;
  817. }
  818. timeval_subtract(&diff, &tv_end, &tv_workstart);
  819. if (diff.tv_sec > opt_scantime ||
  820. work->blk.nonce > MAXTHREADS - hashes ||
  821. work_restart[thr_id].restart)
  822. need_work = true;
  823. }
  824. out:
  825. tq_freeze(mythr->q);
  826. return NULL;
  827. }
  828. static void restart_threads(void)
  829. {
  830. int i;
  831. for (i = 0; i < opt_n_threads + gpu_threads; i++)
  832. work_restart[i].restart = 1;
  833. /* If longpoll has detected a new block, we should discard any queued
  834. * blocks in work_heap */
  835. pthread_mutex_lock(&get_lock);
  836. if (likely(work_heap)) {
  837. free(work_heap);
  838. work_heap = NULL;
  839. }
  840. pthread_mutex_unlock(&get_lock);
  841. }
  842. static void *longpoll_thread(void *userdata)
  843. {
  844. struct thr_info *mythr = userdata;
  845. CURL *curl = NULL;
  846. char *copy_start, *hdr_path, *lp_url = NULL;
  847. bool need_slash = false;
  848. int failures = 0;
  849. hdr_path = tq_pop(mythr->q, NULL);
  850. if (!hdr_path)
  851. goto out;
  852. /* full URL */
  853. if (strstr(hdr_path, "://")) {
  854. lp_url = hdr_path;
  855. hdr_path = NULL;
  856. }
  857. /* absolute path, on current server */
  858. else {
  859. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  860. if (rpc_url[strlen(rpc_url) - 1] != '/')
  861. need_slash = true;
  862. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  863. if (!lp_url)
  864. goto out;
  865. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  866. }
  867. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  868. curl = curl_easy_init();
  869. if (unlikely(!curl)) {
  870. applog(LOG_ERR, "CURL initialization failed");
  871. goto out;
  872. }
  873. while (1) {
  874. json_t *val;
  875. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  876. false, true);
  877. if (likely(val)) {
  878. failures = 0;
  879. json_decref(val);
  880. applog(LOG_INFO, "LONGPOLL detected new block");
  881. restart_threads();
  882. } else {
  883. if (failures++ < 10) {
  884. sleep(30);
  885. applog(LOG_ERR,
  886. "longpoll failed, sleeping for 30s");
  887. } else {
  888. applog(LOG_ERR,
  889. "longpoll failed, ending thread");
  890. goto out;
  891. }
  892. }
  893. }
  894. out:
  895. free(hdr_path);
  896. free(lp_url);
  897. tq_freeze(mythr->q);
  898. if (curl)
  899. curl_easy_cleanup(curl);
  900. return NULL;
  901. }
  902. static void show_usage(void)
  903. {
  904. int i;
  905. printf("minerd version %s\n\n", VERSION);
  906. printf("Usage:\tminerd [options]\n\nSupported options:\n");
  907. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  908. struct option_help *h;
  909. h = &options_help[i];
  910. printf("--%s\n%s\n\n", h->name, h->helptext);
  911. }
  912. exit(1);
  913. }
  914. static void parse_arg (int key, char *arg)
  915. {
  916. int v, i;
  917. switch(key) {
  918. case 'a':
  919. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  920. if (algo_names[i] &&
  921. !strcmp(arg, algo_names[i])) {
  922. opt_algo = i;
  923. break;
  924. }
  925. }
  926. if (i == ARRAY_SIZE(algo_names))
  927. show_usage();
  928. break;
  929. case 'c': {
  930. json_error_t err;
  931. if (opt_config)
  932. json_decref(opt_config);
  933. opt_config = json_load_file(arg, &err);
  934. if (!json_is_object(opt_config)) {
  935. applog(LOG_ERR, "JSON decode of %s failed", arg);
  936. show_usage();
  937. }
  938. break;
  939. }
  940. case 'g':
  941. v = atoi(arg);
  942. if (v < 1 || v > 10)
  943. show_usage();
  944. opt_g_threads = v;
  945. break;
  946. case 'D':
  947. opt_debug = true;
  948. break;
  949. case 'I':
  950. v = atoi(arg);
  951. if (v < 0 || v > 10) /* sanity check */
  952. show_usage();
  953. scan_intensity = v;
  954. break;
  955. case 'l':
  956. v = atoi(arg);
  957. if (v < 0 || v > 9999) /* sanity check */
  958. show_usage();
  959. opt_log_interval = v;
  960. break;
  961. case 'p':
  962. free(rpc_pass);
  963. rpc_pass = strdup(arg);
  964. break;
  965. case 'P':
  966. opt_protocol = true;
  967. break;
  968. case 'q':
  969. opt_quiet = true;
  970. break;
  971. case 'r':
  972. v = atoi(arg);
  973. if (v < -1 || v > 9999) /* sanity check */
  974. show_usage();
  975. opt_retries = v;
  976. break;
  977. case 'R':
  978. v = atoi(arg);
  979. if (v < 1 || v > 9999) /* sanity check */
  980. show_usage();
  981. opt_fail_pause = v;
  982. break;
  983. case 's':
  984. v = atoi(arg);
  985. if (v < 1 || v > 9999) /* sanity check */
  986. show_usage();
  987. opt_scantime = v;
  988. break;
  989. case 't':
  990. v = atoi(arg);
  991. if (v < 0 || v > 9999) /* sanity check */
  992. show_usage();
  993. opt_n_threads = v;
  994. break;
  995. case 'u':
  996. free(rpc_user);
  997. rpc_user = strdup(arg);
  998. break;
  999. case 'v':
  1000. v = atoi(arg);
  1001. if (v != 1 && v != 2 && v != 4)
  1002. show_usage();
  1003. opt_vectors = v;
  1004. break;
  1005. case 'w':
  1006. v = atoi(arg);
  1007. if (v < 1 || v > 9999) /* sanity check */
  1008. show_usage();
  1009. opt_worksize = v;
  1010. break;
  1011. case 1001: /* --url */
  1012. if (strncmp(arg, "http://", 7) &&
  1013. strncmp(arg, "https://", 8))
  1014. show_usage();
  1015. free(rpc_url);
  1016. rpc_url = strdup(arg);
  1017. break;
  1018. case 1002: /* --userpass */
  1019. if (!strchr(arg, ':'))
  1020. show_usage();
  1021. free(rpc_userpass);
  1022. rpc_userpass = strdup(arg);
  1023. break;
  1024. case 1003:
  1025. want_longpoll = false;
  1026. break;
  1027. case 1004:
  1028. use_syslog = true;
  1029. break;
  1030. default:
  1031. show_usage();
  1032. }
  1033. }
  1034. static void parse_config(void)
  1035. {
  1036. int i;
  1037. json_t *val;
  1038. if (!json_is_object(opt_config))
  1039. return;
  1040. for (i = 0; i < ARRAY_SIZE(options); i++) {
  1041. if (!options[i].name)
  1042. break;
  1043. if (!strcmp(options[i].name, "config"))
  1044. continue;
  1045. val = json_object_get(opt_config, options[i].name);
  1046. if (!val)
  1047. continue;
  1048. if (options[i].has_arg && json_is_string(val)) {
  1049. char *s = strdup(json_string_value(val));
  1050. if (!s)
  1051. break;
  1052. parse_arg(options[i].val, s);
  1053. free(s);
  1054. } else if (!options[i].has_arg && json_is_true(val))
  1055. parse_arg(options[i].val, "");
  1056. else
  1057. applog(LOG_ERR, "JSON option %s invalid",
  1058. options[i].name);
  1059. }
  1060. }
  1061. static void parse_cmdline(int argc, char *argv[])
  1062. {
  1063. int key;
  1064. while (1) {
  1065. key = getopt_long(argc, argv, "a:c:qDPr:s:t:h?", options, NULL);
  1066. if (key < 0)
  1067. break;
  1068. parse_arg(key, optarg);
  1069. }
  1070. parse_config();
  1071. }
  1072. int main (int argc, char *argv[])
  1073. {
  1074. struct thr_info *thr;
  1075. unsigned int i;
  1076. char name[32];
  1077. #ifdef WIN32
  1078. opt_n_threads = 1;
  1079. #else
  1080. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1081. opt_n_threads = num_processors;
  1082. #endif /* !WIN32 */
  1083. nDevs = clDevicesNum();
  1084. if (opt_ndevs) {
  1085. applog(LOG_INFO, "%i", nDevs);
  1086. return nDevs;
  1087. }
  1088. if (nDevs)
  1089. opt_n_threads = 0;
  1090. rpc_url = strdup(DEF_RPC_URL);
  1091. /* parse command line */
  1092. parse_cmdline(argc, argv);
  1093. gpu_threads = nDevs * opt_g_threads;
  1094. if (!rpc_userpass) {
  1095. if (!rpc_user || !rpc_pass) {
  1096. applog(LOG_ERR, "No login credentials supplied");
  1097. return 1;
  1098. }
  1099. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1100. if (!rpc_userpass)
  1101. return 1;
  1102. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1103. }
  1104. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  1105. return 1;
  1106. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1107. return 1;
  1108. if (unlikely(pthread_mutex_init(&get_lock, NULL)))
  1109. return 1;
  1110. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1111. return 1;
  1112. #ifdef HAVE_SYSLOG_H
  1113. if (use_syslog)
  1114. openlog("cpuminer", LOG_PID, LOG_USER);
  1115. #endif
  1116. work_restart = calloc(opt_n_threads + gpu_threads, sizeof(*work_restart));
  1117. if (!work_restart)
  1118. return 1;
  1119. thr_info = calloc(opt_n_threads + 2 + gpu_threads, sizeof(*thr));
  1120. if (!thr_info)
  1121. return 1;
  1122. /* init workio thread info */
  1123. work_thr_id = opt_n_threads + gpu_threads;
  1124. thr = &thr_info[work_thr_id];
  1125. thr->id = work_thr_id;
  1126. thr->q = tq_new();
  1127. if (!thr->q)
  1128. return 1;
  1129. /* start work I/O thread */
  1130. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1131. applog(LOG_ERR, "workio thread create failed");
  1132. return 1;
  1133. }
  1134. /* init longpoll thread info */
  1135. if (want_longpoll) {
  1136. longpoll_thr_id = opt_n_threads + gpu_threads + 1;
  1137. thr = &thr_info[longpoll_thr_id];
  1138. thr->id = longpoll_thr_id;
  1139. thr->q = tq_new();
  1140. if (!thr->q)
  1141. return 1;
  1142. /* start longpoll thread */
  1143. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1144. applog(LOG_ERR, "longpoll thread create failed");
  1145. return 1;
  1146. }
  1147. pthread_detach(thr->pth);
  1148. } else
  1149. longpoll_thr_id = -1;
  1150. gettimeofday(&total_tv_start, NULL);
  1151. gettimeofday(&total_tv_end, NULL);
  1152. /* start GPU mining threads */
  1153. for (i = 0; i < gpu_threads; i++) {
  1154. int gpu = i % nDevs;
  1155. thr = &thr_info[i];
  1156. thr->id = i;
  1157. thr->q = tq_new();
  1158. if (!thr->q)
  1159. return 1;
  1160. applog(LOG_INFO, "Init GPU thread %i", i);
  1161. clStates[i] = initCl(gpu, name, sizeof(name));
  1162. if (!clStates[i]) {
  1163. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1164. continue;
  1165. }
  1166. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1167. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1168. applog(LOG_ERR, "thread %d create failed", i);
  1169. return 1;
  1170. }
  1171. pthread_detach(thr->pth);
  1172. }
  1173. applog(LOG_INFO, "%d gpu miner threads started", i);
  1174. /* start CPU mining threads */
  1175. for (i = gpu_threads; i < gpu_threads + opt_n_threads; i++) {
  1176. thr = &thr_info[i];
  1177. thr->id = i;
  1178. thr->q = tq_new();
  1179. if (!thr->q)
  1180. return 1;
  1181. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1182. applog(LOG_ERR, "thread %d create failed", i);
  1183. return 1;
  1184. }
  1185. pthread_detach(thr->pth);
  1186. sleep(1); /* don't pound RPC server all at once */
  1187. }
  1188. applog(LOG_INFO, "%d cpu miner threads started, "
  1189. "using SHA256 '%s' algorithm.",
  1190. opt_n_threads,
  1191. algo_names[opt_algo]);
  1192. /* Restart count as it will be wrong till all threads are started */
  1193. pthread_mutex_lock(&hash_lock);
  1194. gettimeofday(&total_tv_start, NULL);
  1195. gettimeofday(&total_tv_end, NULL);
  1196. total_mhashes_done = 0;
  1197. pthread_mutex_unlock(&hash_lock);
  1198. /* main loop - simply wait for workio thread to exit */
  1199. pthread_join(thr_info[work_thr_id].pth, NULL);
  1200. curl_global_cleanup();
  1201. applog(LOG_INFO, "workio thread dead, exiting.");
  1202. return 0;
  1203. }