cpu-miner.c 31 KB

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