cpu-miner.c 34 KB

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