cpu-miner.c 30 KB

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