cpu-miner.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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 void *gpuminer_thread(void *userdata)
  616. {
  617. struct thr_info *mythr = userdata;
  618. struct timeval tv_start;
  619. int thr_id = mythr->id;
  620. uint32_t res[128], blank_res[128];
  621. setpriority(PRIO_PROCESS, 0, 19);
  622. memset(blank_res, 0, BUFFERSIZE);
  623. size_t globalThreads[1];
  624. size_t localThreads[1];
  625. cl_int status;
  626. _clState *clState = clStates[thr_id];
  627. status = clSetKernelArg(clState->kernel, 0, sizeof(cl_mem), (void *)&clState->inputBuffer);
  628. if (unlikely(status != CL_SUCCESS))
  629. { applog(LOG_ERR, "Error: Setting kernel argument 1.\n"); goto out; }
  630. status = clSetKernelArg(clState->kernel, 1, sizeof(cl_mem), (void *)&clState->outputBuffer);
  631. if (unlikely(status != CL_SUCCESS))
  632. { applog(LOG_ERR, "Error: Setting kernel argument 2.\n"); goto out; }
  633. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  634. BUFFERSIZE, blank_res, 0, NULL, NULL);
  635. if (unlikely(status != CL_SUCCESS))
  636. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  637. struct work *work = malloc(sizeof(struct work));
  638. bool need_work = true;
  639. unsigned int threads = 1 << 22;
  640. gettimeofday(&tv_start, NULL);
  641. globalThreads[0] = threads;
  642. localThreads[0] = 128;
  643. while (1) {
  644. struct timeval tv_end, diff;
  645. int i;
  646. if (need_work) {
  647. /* obtain new work from internal workio thread */
  648. if (unlikely(!get_work(mythr, work))) {
  649. applog(LOG_ERR, "work retrieval failed, exiting "
  650. "gpu mining thread %d", mythr->id);
  651. goto out;
  652. }
  653. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  654. work->blk.nonce = 0;
  655. status = clEnqueueWriteBuffer(clState->commandQueue, clState->inputBuffer, CL_FALSE, 0,
  656. sizeof(dev_blk_ctx), (void *)&work->blk, 0, NULL, NULL);
  657. if (unlikely(status != CL_SUCCESS))
  658. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  659. work_restart[thr_id].restart = 0;
  660. need_work = false;
  661. if (opt_debug)
  662. applog(LOG_DEBUG, "getwork");
  663. }
  664. clFinish(clState->commandQueue);
  665. status = clEnqueueNDRangeKernel(clState->commandQueue, clState->kernel, 1, NULL,
  666. globalThreads, localThreads, 0, NULL, NULL);
  667. if (unlikely(status != CL_SUCCESS))
  668. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  669. /* 127 is used as a flag to say nonces exist */
  670. if (unlikely(res[127])) {
  671. /* Clear the buffer again */
  672. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  673. BUFFERSIZE, blank_res, 0, NULL, NULL);
  674. if (unlikely(status != CL_SUCCESS))
  675. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  676. for (i = 0; i < 127; i++) {
  677. if (res[i]) {
  678. applog(LOG_INFO, "GPU Found something?");
  679. postcalc_hash(mythr, &work->blk, work, res[i]);
  680. } else
  681. break;
  682. }
  683. clFinish(clState->commandQueue);
  684. }
  685. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  686. BUFFERSIZE, res, 0, NULL, NULL);
  687. if (unlikely(status != CL_SUCCESS))
  688. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  689. gettimeofday(&tv_end, NULL);
  690. timeval_subtract(&diff, &tv_end, &tv_start);
  691. hashmeter(thr_id, &diff, threads);
  692. gettimeofday(&tv_start, NULL);
  693. work->blk.nonce += threads;
  694. if (unlikely(work->blk.nonce > MAXTHREADS - threads) ||
  695. (work_restart[thr_id].restart))
  696. need_work = true;
  697. clFinish(clState->commandQueue);
  698. status = clEnqueueWriteBuffer(clState->commandQueue, clState->inputBuffer, CL_FALSE, 0,
  699. sizeof(dev_blk_ctx), (void *)&work->blk, 0, NULL, NULL);
  700. if (unlikely(status != CL_SUCCESS))
  701. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  702. }
  703. out:
  704. tq_freeze(mythr->q);
  705. return NULL;
  706. }
  707. static void restart_threads(void)
  708. {
  709. int i;
  710. for (i = 0; i < opt_n_threads + nDevs; i++)
  711. work_restart[i].restart = 1;
  712. }
  713. static void *longpoll_thread(void *userdata)
  714. {
  715. struct thr_info *mythr = userdata;
  716. CURL *curl = NULL;
  717. char *copy_start, *hdr_path, *lp_url = NULL;
  718. bool need_slash = false;
  719. int failures = 0;
  720. hdr_path = tq_pop(mythr->q, NULL);
  721. if (!hdr_path)
  722. goto out;
  723. /* full URL */
  724. if (strstr(hdr_path, "://")) {
  725. lp_url = hdr_path;
  726. hdr_path = NULL;
  727. }
  728. /* absolute path, on current server */
  729. else {
  730. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  731. if (rpc_url[strlen(rpc_url) - 1] != '/')
  732. need_slash = true;
  733. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  734. if (!lp_url)
  735. goto out;
  736. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  737. }
  738. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  739. curl = curl_easy_init();
  740. if (unlikely(!curl)) {
  741. applog(LOG_ERR, "CURL initialization failed");
  742. goto out;
  743. }
  744. while (1) {
  745. json_t *val;
  746. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  747. false, true);
  748. if (likely(val)) {
  749. failures = 0;
  750. json_decref(val);
  751. applog(LOG_INFO, "LONGPOLL detected new block");
  752. restart_threads();
  753. } else {
  754. if (failures++ < 10) {
  755. sleep(30);
  756. applog(LOG_ERR,
  757. "longpoll failed, sleeping for 30s");
  758. } else {
  759. applog(LOG_ERR,
  760. "longpoll failed, ending thread");
  761. goto out;
  762. }
  763. }
  764. }
  765. out:
  766. free(hdr_path);
  767. free(lp_url);
  768. tq_freeze(mythr->q);
  769. if (curl)
  770. curl_easy_cleanup(curl);
  771. return NULL;
  772. }
  773. static void show_usage(void)
  774. {
  775. int i;
  776. printf("minerd version %s\n\n", VERSION);
  777. printf("Usage:\tminerd [options]\n\nSupported options:\n");
  778. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  779. struct option_help *h;
  780. h = &options_help[i];
  781. printf("--%s\n%s\n\n", h->name, h->helptext);
  782. }
  783. exit(1);
  784. }
  785. static void parse_arg (int key, char *arg)
  786. {
  787. int v, i;
  788. switch(key) {
  789. case 'a':
  790. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  791. if (algo_names[i] &&
  792. !strcmp(arg, algo_names[i])) {
  793. opt_algo = i;
  794. break;
  795. }
  796. }
  797. if (i == ARRAY_SIZE(algo_names))
  798. show_usage();
  799. break;
  800. case 'c': {
  801. json_error_t err;
  802. if (opt_config)
  803. json_decref(opt_config);
  804. opt_config = json_load_file(arg, &err);
  805. if (!json_is_object(opt_config)) {
  806. applog(LOG_ERR, "JSON decode of %s failed", arg);
  807. show_usage();
  808. }
  809. break;
  810. }
  811. case 'q':
  812. opt_quiet = true;
  813. break;
  814. case 'D':
  815. opt_debug = true;
  816. break;
  817. case 'p':
  818. free(rpc_pass);
  819. rpc_pass = strdup(arg);
  820. break;
  821. case 'P':
  822. opt_protocol = true;
  823. break;
  824. case 'r':
  825. v = atoi(arg);
  826. if (v < -1 || v > 9999) /* sanity check */
  827. show_usage();
  828. opt_retries = v;
  829. break;
  830. case 'R':
  831. v = atoi(arg);
  832. if (v < 1 || v > 9999) /* sanity check */
  833. show_usage();
  834. opt_fail_pause = v;
  835. break;
  836. case 's':
  837. v = atoi(arg);
  838. if (v < 1 || v > 9999) /* sanity check */
  839. show_usage();
  840. opt_scantime = v;
  841. break;
  842. case 't':
  843. v = atoi(arg);
  844. if (v < 1 || v > 9999) /* sanity check */
  845. show_usage();
  846. opt_n_threads = v;
  847. break;
  848. case 'u':
  849. free(rpc_user);
  850. rpc_user = strdup(arg);
  851. break;
  852. case 1001: /* --url */
  853. if (strncmp(arg, "http://", 7) &&
  854. strncmp(arg, "https://", 8))
  855. show_usage();
  856. free(rpc_url);
  857. rpc_url = strdup(arg);
  858. break;
  859. case 1002: /* --userpass */
  860. if (!strchr(arg, ':'))
  861. show_usage();
  862. free(rpc_userpass);
  863. rpc_userpass = strdup(arg);
  864. break;
  865. case 1003:
  866. want_longpoll = false;
  867. break;
  868. case 1004:
  869. use_syslog = true;
  870. break;
  871. default:
  872. show_usage();
  873. }
  874. #ifdef WIN32
  875. if (!opt_n_threads)
  876. opt_n_threads = 1;
  877. #else
  878. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  879. if (!opt_n_threads)
  880. opt_n_threads = num_processors;
  881. #endif /* !WIN32 */
  882. }
  883. static void parse_config(void)
  884. {
  885. int i;
  886. json_t *val;
  887. if (!json_is_object(opt_config))
  888. return;
  889. for (i = 0; i < ARRAY_SIZE(options); i++) {
  890. if (!options[i].name)
  891. break;
  892. if (!strcmp(options[i].name, "config"))
  893. continue;
  894. val = json_object_get(opt_config, options[i].name);
  895. if (!val)
  896. continue;
  897. if (options[i].has_arg && json_is_string(val)) {
  898. char *s = strdup(json_string_value(val));
  899. if (!s)
  900. break;
  901. parse_arg(options[i].val, s);
  902. free(s);
  903. } else if (!options[i].has_arg && json_is_true(val))
  904. parse_arg(options[i].val, "");
  905. else
  906. applog(LOG_ERR, "JSON option %s invalid",
  907. options[i].name);
  908. }
  909. }
  910. static void parse_cmdline(int argc, char *argv[])
  911. {
  912. int key;
  913. while (1) {
  914. key = getopt_long(argc, argv, "a:c:qDPr:s:t:h?", options, NULL);
  915. if (key < 0)
  916. break;
  917. parse_arg(key, optarg);
  918. }
  919. parse_config();
  920. }
  921. int main (int argc, char *argv[])
  922. {
  923. struct thr_info *thr;
  924. int i;
  925. char name[32];
  926. nDevs = clDevicesNum();
  927. if (opt_ndevs) {
  928. printf("%i\n", nDevs);
  929. return nDevs;
  930. }
  931. rpc_url = strdup(DEF_RPC_URL);
  932. /* parse command line */
  933. parse_cmdline(argc, argv);
  934. if (!rpc_userpass) {
  935. if (!rpc_user || !rpc_pass) {
  936. applog(LOG_ERR, "No login credentials supplied");
  937. return 1;
  938. }
  939. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  940. if (!rpc_userpass)
  941. return 1;
  942. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  943. }
  944. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  945. return 1;
  946. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  947. return 1;
  948. #ifdef HAVE_SYSLOG_H
  949. if (use_syslog)
  950. openlog("cpuminer", LOG_PID, LOG_USER);
  951. #endif
  952. work_restart = calloc(opt_n_threads + nDevs, sizeof(*work_restart));
  953. if (!work_restart)
  954. return 1;
  955. thr_info = calloc(opt_n_threads + 2 + nDevs, sizeof(*thr));
  956. if (!thr_info)
  957. return 1;
  958. /* init workio thread info */
  959. work_thr_id = opt_n_threads + nDevs;
  960. thr = &thr_info[work_thr_id];
  961. thr->id = work_thr_id;
  962. thr->q = tq_new();
  963. if (!thr->q)
  964. return 1;
  965. /* start work I/O thread */
  966. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  967. applog(LOG_ERR, "workio thread create failed");
  968. return 1;
  969. }
  970. /* init longpoll thread info */
  971. if (want_longpoll) {
  972. longpoll_thr_id = opt_n_threads + nDevs + 1;
  973. thr = &thr_info[longpoll_thr_id];
  974. thr->id = longpoll_thr_id;
  975. thr->q = tq_new();
  976. if (!thr->q)
  977. return 1;
  978. /* start longpoll thread */
  979. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  980. applog(LOG_ERR, "longpoll thread create failed");
  981. return 1;
  982. }
  983. } else
  984. longpoll_thr_id = -1;
  985. gettimeofday(&total_tv_start, NULL);
  986. gettimeofday(&total_tv_end, NULL);
  987. /* start gpu mining threads */
  988. for (i = 0; i < nDevs; i++) {
  989. thr = &thr_info[i];
  990. thr->id = i;
  991. thr->q = tq_new();
  992. if (!thr->q)
  993. return 1;
  994. printf("Init GPU %i\n", i);
  995. clStates[i] = initCl(i, name, sizeof(name));
  996. printf("initCl() finished. Found %s\n", name);
  997. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  998. applog(LOG_ERR, "thread %d create failed", i);
  999. return 1;
  1000. }
  1001. sleep(1); /* don't pound RPC server all at once */
  1002. }
  1003. applog(LOG_INFO, "%d gpu miner threads started", i);
  1004. /* start mining threads */
  1005. for (i = nDevs; i < nDevs + opt_n_threads; i++) {
  1006. thr = &thr_info[i];
  1007. thr->id = i;
  1008. thr->q = tq_new();
  1009. if (!thr->q)
  1010. return 1;
  1011. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1012. applog(LOG_ERR, "thread %d create failed", i);
  1013. return 1;
  1014. }
  1015. sleep(1); /* don't pound RPC server all at once */
  1016. }
  1017. applog(LOG_INFO, "%d cpu miner threads started, "
  1018. "using SHA256 '%s' algorithm.",
  1019. opt_n_threads,
  1020. algo_names[opt_algo]);
  1021. /* main loop - simply wait for workio thread to exit */
  1022. pthread_join(thr_info[work_thr_id].pth, NULL);
  1023. applog(LOG_INFO, "workio thread dead, exiting.");
  1024. return 0;
  1025. }