cpu-miner.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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 threads (default: 1)" },
  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. /* Don't bother calculating anything if we're not displaying it */
  418. if (opt_quiet)
  419. return;
  420. khashes = hashes_done / 1000.0;
  421. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  422. if (opt_n_threads + nDevs > 1) {
  423. double total_mhashes, total_secs;
  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. /* 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. if (opt_debug)
  447. applog(LOG_DEBUG, "[%lu hashes]", hashes_done);
  448. applog(LOG_INFO, "%.0f khash/sec] [%d Accepted] [%d Rejected]",
  449. khashes / secs, accepted, rejected);
  450. }
  451. }
  452. static bool get_work(struct thr_info *thr, struct work *work)
  453. {
  454. struct workio_cmd *wc;
  455. struct work *work_heap;
  456. /* fill out work request message */
  457. wc = calloc(1, sizeof(*wc));
  458. if (!wc)
  459. return false;
  460. wc->cmd = WC_GET_WORK;
  461. wc->thr = thr;
  462. /* send work request to workio thread */
  463. if (!tq_push(thr_info[work_thr_id].q, wc)) {
  464. workio_cmd_free(wc);
  465. return false;
  466. }
  467. /* wait for response, a unit of work */
  468. work_heap = tq_pop(thr->q, NULL);
  469. if (!work_heap)
  470. return false;
  471. /* copy returned work into storage provided by caller */
  472. memcpy(work, work_heap, sizeof(*work));
  473. free(work_heap);
  474. return true;
  475. }
  476. static bool submit_work(struct thr_info *thr, const struct work *work_in)
  477. {
  478. struct workio_cmd *wc;
  479. /* fill out work request message */
  480. wc = calloc(1, sizeof(*wc));
  481. if (!wc)
  482. return false;
  483. wc->u.work = malloc(sizeof(*work_in));
  484. if (!wc->u.work)
  485. goto err_out;
  486. wc->cmd = WC_SUBMIT_WORK;
  487. wc->thr = thr;
  488. memcpy(wc->u.work, work_in, sizeof(*work_in));
  489. /* send solution to workio thread */
  490. if (!tq_push(thr_info[work_thr_id].q, wc))
  491. goto err_out;
  492. return true;
  493. err_out:
  494. workio_cmd_free(wc);
  495. return false;
  496. }
  497. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  498. {
  499. work->data[64+12+0] = (nonce>>0) & 0xff;
  500. work->data[64+12+1] = (nonce>>8) & 0xff;
  501. work->data[64+12+2] = (nonce>>16) & 0xff;
  502. work->data[64+12+3] = (nonce>>24) & 0xff;
  503. return submit_work(thr, work);
  504. }
  505. static void *miner_thread(void *userdata)
  506. {
  507. struct thr_info *mythr = userdata;
  508. int thr_id = mythr->id;
  509. uint32_t max_nonce = 0xffffff;
  510. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  511. * and if that fails, then SCHED_BATCH. No need for this to be an
  512. * error if it fails */
  513. setpriority(PRIO_PROCESS, 0, 19);
  514. drop_policy();
  515. /* Cpu affinity only makes sense if the number of threads is a multiple
  516. * of the number of CPUs */
  517. if (!(opt_n_threads % num_processors))
  518. affine_to_cpu(mythr->id, mythr->id % num_processors);
  519. while (1) {
  520. struct work work __attribute__((aligned(128)));
  521. unsigned long hashes_done;
  522. struct timeval tv_start, tv_end, diff;
  523. uint64_t max64;
  524. bool rc;
  525. /* obtain new work from internal workio thread */
  526. if (unlikely(!get_work(mythr, &work))) {
  527. applog(LOG_ERR, "work retrieval failed, exiting "
  528. "mining thread %d", mythr->id);
  529. goto out;
  530. }
  531. hashes_done = 0;
  532. gettimeofday(&tv_start, NULL);
  533. /* scan nonces for a proof-of-work hash */
  534. switch (opt_algo) {
  535. case ALGO_C:
  536. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  537. work.hash1, work.hash, work.target,
  538. max_nonce, &hashes_done);
  539. break;
  540. #ifdef WANT_X8664_SSE2
  541. case ALGO_SSE2_64: {
  542. unsigned int rc5 =
  543. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  544. work.hash1, work.hash,
  545. work.target,
  546. max_nonce, &hashes_done);
  547. rc = (rc5 == -1) ? false : true;
  548. }
  549. break;
  550. #endif
  551. #ifdef WANT_SSE2_4WAY
  552. case ALGO_4WAY: {
  553. unsigned int rc4 =
  554. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  555. work.hash1, work.hash,
  556. work.target,
  557. max_nonce, &hashes_done);
  558. rc = (rc4 == -1) ? false : true;
  559. }
  560. break;
  561. #endif
  562. #ifdef WANT_VIA_PADLOCK
  563. case ALGO_VIA:
  564. rc = scanhash_via(thr_id, work.data, work.target,
  565. max_nonce, &hashes_done);
  566. break;
  567. #endif
  568. case ALGO_CRYPTOPP:
  569. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  570. work.hash1, work.hash, work.target,
  571. max_nonce, &hashes_done);
  572. break;
  573. #ifdef WANT_CRYPTOPP_ASM32
  574. case ALGO_CRYPTOPP_ASM32:
  575. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  576. work.hash1, work.hash, work.target,
  577. max_nonce, &hashes_done);
  578. break;
  579. #endif
  580. default:
  581. /* should never happen */
  582. goto out;
  583. }
  584. /* record scanhash elapsed time */
  585. gettimeofday(&tv_end, NULL);
  586. timeval_subtract(&diff, &tv_end, &tv_start);
  587. hashmeter(thr_id, &diff, hashes_done);
  588. /* adjust max_nonce to meet target scan time */
  589. if (diff.tv_usec > 500000)
  590. diff.tv_sec++;
  591. if (diff.tv_sec > 0) {
  592. max64 =
  593. ((uint64_t)hashes_done * opt_scantime) / diff.tv_sec;
  594. if (max64 > 0xfffffffaULL)
  595. max64 = 0xfffffffaULL;
  596. max_nonce = max64;
  597. }
  598. /* if nonce found, submit work */
  599. if (unlikely(rc)) {
  600. applog(LOG_INFO, "CPU found something?");
  601. if (!submit_work(mythr, &work))
  602. break;
  603. }
  604. }
  605. out:
  606. tq_freeze(mythr->q);
  607. return NULL;
  608. }
  609. enum {
  610. STAT_SLEEP_INTERVAL = 1,
  611. STAT_CTR_INTERVAL = 10000000,
  612. FAILURE_INTERVAL = 30,
  613. };
  614. static _clState *clStates[16];
  615. static inline cl_int queue_kernel_parameters(dev_blk_ctx *blk, cl_kernel *kernel,
  616. struct _cl_mem *output)
  617. {
  618. cl_int status = 0;
  619. int num = 0;
  620. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  621. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  622. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  623. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  624. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  625. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  626. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  627. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  628. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  629. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  630. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  631. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  632. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  633. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  634. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  635. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  636. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  637. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  638. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  639. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  640. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  641. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  642. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  643. status |= clSetKernelArg(*kernel, num++, sizeof(output), (void *)&output);
  644. return status;
  645. }
  646. static void *gpuminer_thread(void *userdata)
  647. {
  648. struct thr_info *mythr = userdata;
  649. struct timeval tv_start;
  650. int thr_id = mythr->id;
  651. uint32_t res[128], blank_res[128];
  652. cl_kernel *kernel;
  653. setpriority(PRIO_PROCESS, 0, 19);
  654. memset(blank_res, 0, BUFFERSIZE);
  655. size_t globalThreads[1];
  656. size_t localThreads[1];
  657. cl_int status;
  658. _clState *clState = clStates[thr_id];
  659. kernel = &clState->kernel;
  660. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  661. BUFFERSIZE, blank_res, 0, NULL, NULL);
  662. if (unlikely(status != CL_SUCCESS))
  663. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  664. struct work *work = malloc(sizeof(struct work));
  665. bool need_work = true;
  666. unsigned int threads = 1 << 22;
  667. gettimeofday(&tv_start, NULL);
  668. globalThreads[0] = threads;
  669. localThreads[0] = 128;
  670. while (1) {
  671. struct timeval tv_end, diff;
  672. int i;
  673. if (need_work) {
  674. /* obtain new work from internal workio thread */
  675. if (unlikely(!get_work(mythr, work))) {
  676. applog(LOG_ERR, "work retrieval failed, exiting "
  677. "gpu mining thread %d", mythr->id);
  678. goto out;
  679. }
  680. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  681. work->blk.nonce = 0;
  682. status = queue_kernel_parameters(&work->blk, kernel, clState->outputBuffer);
  683. if (unlikely(status != CL_SUCCESS))
  684. { applog(LOG_ERR, "Error: clSetKernelArg failed."); exit (1); }
  685. work_restart[thr_id].restart = 0;
  686. need_work = false;
  687. if (opt_debug)
  688. applog(LOG_DEBUG, "getwork");
  689. }
  690. clFinish(clState->commandQueue);
  691. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  692. globalThreads, localThreads, 0, NULL, NULL);
  693. if (unlikely(status != CL_SUCCESS))
  694. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  695. /* 127 is used as a flag to say nonces exist */
  696. if (unlikely(res[127])) {
  697. /* Clear the buffer again */
  698. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  699. BUFFERSIZE, blank_res, 0, NULL, NULL);
  700. if (unlikely(status != CL_SUCCESS))
  701. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  702. for (i = 0; i < 127; i++) {
  703. if (res[i]) {
  704. applog(LOG_INFO, "GPU Found something?");
  705. postcalc_hash(mythr, &work->blk, work, res[i]);
  706. } else
  707. break;
  708. }
  709. clFinish(clState->commandQueue);
  710. }
  711. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  712. BUFFERSIZE, res, 0, NULL, NULL);
  713. if (unlikely(status != CL_SUCCESS))
  714. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  715. gettimeofday(&tv_end, NULL);
  716. timeval_subtract(&diff, &tv_end, &tv_start);
  717. hashmeter(thr_id, &diff, threads);
  718. gettimeofday(&tv_start, NULL);
  719. work->blk.nonce += threads;
  720. if (unlikely(work->blk.nonce > MAXTHREADS - threads) ||
  721. (work_restart[thr_id].restart))
  722. need_work = true;
  723. clFinish(clState->commandQueue);
  724. status = clSetKernelArg(*kernel, 14, sizeof(uint), (void *)&work->blk.nonce);
  725. if (unlikely(status != CL_SUCCESS))
  726. { applog(LOG_ERR, "Error: clSetKernelArg failed."); goto out; }
  727. }
  728. out:
  729. tq_freeze(mythr->q);
  730. return NULL;
  731. }
  732. static void restart_threads(void)
  733. {
  734. int i;
  735. for (i = 0; i < opt_n_threads + nDevs; i++)
  736. work_restart[i].restart = 1;
  737. }
  738. static void *longpoll_thread(void *userdata)
  739. {
  740. struct thr_info *mythr = userdata;
  741. CURL *curl = NULL;
  742. char *copy_start, *hdr_path, *lp_url = NULL;
  743. bool need_slash = false;
  744. int failures = 0;
  745. hdr_path = tq_pop(mythr->q, NULL);
  746. if (!hdr_path)
  747. goto out;
  748. /* full URL */
  749. if (strstr(hdr_path, "://")) {
  750. lp_url = hdr_path;
  751. hdr_path = NULL;
  752. }
  753. /* absolute path, on current server */
  754. else {
  755. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  756. if (rpc_url[strlen(rpc_url) - 1] != '/')
  757. need_slash = true;
  758. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  759. if (!lp_url)
  760. goto out;
  761. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  762. }
  763. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  764. curl = curl_easy_init();
  765. if (unlikely(!curl)) {
  766. applog(LOG_ERR, "CURL initialization failed");
  767. goto out;
  768. }
  769. while (1) {
  770. json_t *val;
  771. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  772. false, true);
  773. if (likely(val)) {
  774. failures = 0;
  775. json_decref(val);
  776. applog(LOG_INFO, "LONGPOLL detected new block");
  777. restart_threads();
  778. } else {
  779. if (failures++ < 10) {
  780. sleep(30);
  781. applog(LOG_ERR,
  782. "longpoll failed, sleeping for 30s");
  783. } else {
  784. applog(LOG_ERR,
  785. "longpoll failed, ending thread");
  786. goto out;
  787. }
  788. }
  789. }
  790. out:
  791. free(hdr_path);
  792. free(lp_url);
  793. tq_freeze(mythr->q);
  794. if (curl)
  795. curl_easy_cleanup(curl);
  796. return NULL;
  797. }
  798. static void show_usage(void)
  799. {
  800. int i;
  801. printf("minerd version %s\n\n", VERSION);
  802. printf("Usage:\tminerd [options]\n\nSupported options:\n");
  803. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  804. struct option_help *h;
  805. h = &options_help[i];
  806. printf("--%s\n%s\n\n", h->name, h->helptext);
  807. }
  808. exit(1);
  809. }
  810. static void parse_arg (int key, char *arg)
  811. {
  812. int v, i;
  813. switch(key) {
  814. case 'a':
  815. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  816. if (algo_names[i] &&
  817. !strcmp(arg, algo_names[i])) {
  818. opt_algo = i;
  819. break;
  820. }
  821. }
  822. if (i == ARRAY_SIZE(algo_names))
  823. show_usage();
  824. break;
  825. case 'c': {
  826. json_error_t err;
  827. if (opt_config)
  828. json_decref(opt_config);
  829. opt_config = json_load_file(arg, &err);
  830. if (!json_is_object(opt_config)) {
  831. applog(LOG_ERR, "JSON decode of %s failed", arg);
  832. show_usage();
  833. }
  834. break;
  835. }
  836. case 'q':
  837. opt_quiet = true;
  838. break;
  839. case 'D':
  840. opt_debug = true;
  841. break;
  842. case 'p':
  843. free(rpc_pass);
  844. rpc_pass = strdup(arg);
  845. break;
  846. case 'P':
  847. opt_protocol = true;
  848. break;
  849. case 'r':
  850. v = atoi(arg);
  851. if (v < -1 || v > 9999) /* sanity check */
  852. show_usage();
  853. opt_retries = v;
  854. break;
  855. case 'R':
  856. v = atoi(arg);
  857. if (v < 1 || v > 9999) /* sanity check */
  858. show_usage();
  859. opt_fail_pause = v;
  860. break;
  861. case 's':
  862. v = atoi(arg);
  863. if (v < 1 || v > 9999) /* sanity check */
  864. show_usage();
  865. opt_scantime = v;
  866. break;
  867. case 't':
  868. v = atoi(arg);
  869. if (v < 1 || v > 9999) /* sanity check */
  870. show_usage();
  871. opt_n_threads = v;
  872. break;
  873. case 'u':
  874. free(rpc_user);
  875. rpc_user = strdup(arg);
  876. break;
  877. case 1001: /* --url */
  878. if (strncmp(arg, "http://", 7) &&
  879. strncmp(arg, "https://", 8))
  880. show_usage();
  881. free(rpc_url);
  882. rpc_url = strdup(arg);
  883. break;
  884. case 1002: /* --userpass */
  885. if (!strchr(arg, ':'))
  886. show_usage();
  887. free(rpc_userpass);
  888. rpc_userpass = strdup(arg);
  889. break;
  890. case 1003:
  891. want_longpoll = false;
  892. break;
  893. case 1004:
  894. use_syslog = true;
  895. break;
  896. default:
  897. show_usage();
  898. }
  899. #ifdef WIN32
  900. if (!opt_n_threads)
  901. opt_n_threads = 1;
  902. #else
  903. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  904. if (!opt_n_threads)
  905. opt_n_threads = num_processors;
  906. #endif /* !WIN32 */
  907. }
  908. static void parse_config(void)
  909. {
  910. int i;
  911. json_t *val;
  912. if (!json_is_object(opt_config))
  913. return;
  914. for (i = 0; i < ARRAY_SIZE(options); i++) {
  915. if (!options[i].name)
  916. break;
  917. if (!strcmp(options[i].name, "config"))
  918. continue;
  919. val = json_object_get(opt_config, options[i].name);
  920. if (!val)
  921. continue;
  922. if (options[i].has_arg && json_is_string(val)) {
  923. char *s = strdup(json_string_value(val));
  924. if (!s)
  925. break;
  926. parse_arg(options[i].val, s);
  927. free(s);
  928. } else if (!options[i].has_arg && json_is_true(val))
  929. parse_arg(options[i].val, "");
  930. else
  931. applog(LOG_ERR, "JSON option %s invalid",
  932. options[i].name);
  933. }
  934. }
  935. static void parse_cmdline(int argc, char *argv[])
  936. {
  937. int key;
  938. while (1) {
  939. key = getopt_long(argc, argv, "a:c:qDPr:s:t:h?", options, NULL);
  940. if (key < 0)
  941. break;
  942. parse_arg(key, optarg);
  943. }
  944. parse_config();
  945. }
  946. int main (int argc, char *argv[])
  947. {
  948. struct thr_info *thr;
  949. int i;
  950. char name[32];
  951. nDevs = clDevicesNum();
  952. if (opt_ndevs) {
  953. printf("%i\n", nDevs);
  954. return nDevs;
  955. }
  956. rpc_url = strdup(DEF_RPC_URL);
  957. /* parse command line */
  958. parse_cmdline(argc, argv);
  959. if (!rpc_userpass) {
  960. if (!rpc_user || !rpc_pass) {
  961. applog(LOG_ERR, "No login credentials supplied");
  962. return 1;
  963. }
  964. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  965. if (!rpc_userpass)
  966. return 1;
  967. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  968. }
  969. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  970. return 1;
  971. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  972. return 1;
  973. #ifdef HAVE_SYSLOG_H
  974. if (use_syslog)
  975. openlog("cpuminer", LOG_PID, LOG_USER);
  976. #endif
  977. work_restart = calloc(opt_n_threads + nDevs, sizeof(*work_restart));
  978. if (!work_restart)
  979. return 1;
  980. thr_info = calloc(opt_n_threads + 2 + nDevs, sizeof(*thr));
  981. if (!thr_info)
  982. return 1;
  983. /* init workio thread info */
  984. work_thr_id = opt_n_threads + nDevs;
  985. thr = &thr_info[work_thr_id];
  986. thr->id = work_thr_id;
  987. thr->q = tq_new();
  988. if (!thr->q)
  989. return 1;
  990. /* start work I/O thread */
  991. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  992. applog(LOG_ERR, "workio thread create failed");
  993. return 1;
  994. }
  995. /* init longpoll thread info */
  996. if (want_longpoll) {
  997. longpoll_thr_id = opt_n_threads + nDevs + 1;
  998. thr = &thr_info[longpoll_thr_id];
  999. thr->id = longpoll_thr_id;
  1000. thr->q = tq_new();
  1001. if (!thr->q)
  1002. return 1;
  1003. /* start longpoll thread */
  1004. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1005. applog(LOG_ERR, "longpoll thread create failed");
  1006. return 1;
  1007. }
  1008. } else
  1009. longpoll_thr_id = -1;
  1010. gettimeofday(&total_tv_start, NULL);
  1011. gettimeofday(&total_tv_end, NULL);
  1012. /* start gpu mining threads */
  1013. for (i = 0; i < nDevs; i++) {
  1014. thr = &thr_info[i];
  1015. thr->id = i;
  1016. thr->q = tq_new();
  1017. if (!thr->q)
  1018. return 1;
  1019. printf("Init GPU %i\n", i);
  1020. clStates[i] = initCl(i, name, sizeof(name));
  1021. printf("initCl() finished. Found %s\n", name);
  1022. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1023. applog(LOG_ERR, "thread %d create failed", i);
  1024. return 1;
  1025. }
  1026. sleep(1); /* don't pound RPC server all at once */
  1027. }
  1028. applog(LOG_INFO, "%d gpu miner threads started", i);
  1029. /* start mining threads */
  1030. for (i = nDevs; i < nDevs + opt_n_threads; i++) {
  1031. thr = &thr_info[i];
  1032. thr->id = i;
  1033. thr->q = tq_new();
  1034. if (!thr->q)
  1035. return 1;
  1036. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1037. applog(LOG_ERR, "thread %d create failed", i);
  1038. return 1;
  1039. }
  1040. sleep(1); /* don't pound RPC server all at once */
  1041. }
  1042. applog(LOG_INFO, "%d cpu miner threads started, "
  1043. "using SHA256 '%s' algorithm.",
  1044. opt_n_threads,
  1045. algo_names[opt_algo]);
  1046. /* main loop - simply wait for workio thread to exit */
  1047. pthread_join(thr_info[work_thr_id].pth, NULL);
  1048. applog(LOG_INFO, "workio thread dead, exiting.");
  1049. return 0;
  1050. }