cpu-miner.c 34 KB

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