cpu-miner.c 27 KB

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