cpu-miner.c 30 KB

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