cpu-miner.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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;
  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[MAXTHREADS];
  223. uint32_t res_nonce;
  224. uint32_t valid;
  225. uint32_t ready;
  226. dev_blk_ctx blk;
  227. };
  228. static bool jobj_binary(const json_t *obj, const char *key,
  229. void *buf, size_t buflen)
  230. {
  231. const char *hexstr;
  232. json_t *tmp;
  233. tmp = json_object_get(obj, key);
  234. if (unlikely(!tmp)) {
  235. applog(LOG_ERR, "JSON key '%s' not found", key);
  236. return false;
  237. }
  238. hexstr = json_string_value(tmp);
  239. if (unlikely(!hexstr)) {
  240. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  241. return false;
  242. }
  243. if (!hex2bin(buf, hexstr, buflen))
  244. return false;
  245. return true;
  246. }
  247. static bool work_decode(const json_t *val, struct work *work)
  248. {
  249. if (unlikely(!jobj_binary(val, "midstate",
  250. work->midstate, sizeof(work->midstate)))) {
  251. applog(LOG_ERR, "JSON inval midstate");
  252. goto err_out;
  253. }
  254. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  255. applog(LOG_ERR, "JSON inval data");
  256. goto err_out;
  257. }
  258. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  259. applog(LOG_ERR, "JSON inval hash1");
  260. goto err_out;
  261. }
  262. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  263. applog(LOG_ERR, "JSON inval target");
  264. goto err_out;
  265. }
  266. memset(work->hash, 0, sizeof(work->hash));
  267. return true;
  268. err_out:
  269. return false;
  270. }
  271. static bool submit_upstream_work(CURL *curl, const struct work *work)
  272. {
  273. char *hexstr = NULL;
  274. json_t *val, *res;
  275. char s[345];
  276. bool rc = false;
  277. /* build hex string */
  278. hexstr = bin2hex(work->data, sizeof(work->data));
  279. if (unlikely(!hexstr)) {
  280. applog(LOG_ERR, "submit_upstream_work OOM");
  281. goto out;
  282. }
  283. /* build JSON-RPC request */
  284. sprintf(s,
  285. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  286. hexstr);
  287. if (opt_debug)
  288. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  289. /* issue JSON-RPC request */
  290. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  291. if (unlikely(!val)) {
  292. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  293. goto out;
  294. }
  295. res = json_object_get(val, "result");
  296. if (json_is_true(res)) {
  297. accepted++;
  298. applog(LOG_INFO, "PROOF OF WORK RESULT: true (yay!!!)");
  299. } else {
  300. rejected++;
  301. applog(LOG_INFO, "PROOF OF WORK RESULT: false (booooo)");
  302. }
  303. json_decref(val);
  304. rc = true;
  305. out:
  306. free(hexstr);
  307. return rc;
  308. }
  309. static const char *rpc_req =
  310. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  311. static bool get_upstream_work(CURL *curl, struct work *work)
  312. {
  313. json_t *val;
  314. bool rc;
  315. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  316. want_longpoll, false);
  317. if (!val)
  318. return false;
  319. rc = work_decode(json_object_get(val, "result"), work);
  320. json_decref(val);
  321. return rc;
  322. }
  323. static void workio_cmd_free(struct workio_cmd *wc)
  324. {
  325. if (!wc)
  326. return;
  327. switch (wc->cmd) {
  328. case WC_SUBMIT_WORK:
  329. free(wc->u.work);
  330. break;
  331. default: /* do nothing */
  332. break;
  333. }
  334. memset(wc, 0, sizeof(*wc)); /* poison */
  335. free(wc);
  336. }
  337. static bool workio_get_work(struct workio_cmd *wc, CURL *curl)
  338. {
  339. struct work *ret_work;
  340. int failures = 0;
  341. ret_work = calloc(1, sizeof(*ret_work));
  342. if (!ret_work)
  343. return false;
  344. /* obtain new work from bitcoin via JSON-RPC */
  345. while (!get_upstream_work(curl, ret_work)) {
  346. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  347. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  348. free(ret_work);
  349. return false;
  350. }
  351. /* pause, then restart work-request loop */
  352. applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
  353. opt_fail_pause);
  354. sleep(opt_fail_pause);
  355. }
  356. /* send work to requesting thread */
  357. if (!tq_push(wc->thr->q, ret_work))
  358. free(ret_work);
  359. return true;
  360. }
  361. static bool workio_submit_work(struct workio_cmd *wc, CURL *curl)
  362. {
  363. int failures = 0;
  364. /* submit solution to bitcoin via JSON-RPC */
  365. while (!submit_upstream_work(curl, wc->u.work)) {
  366. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  367. applog(LOG_ERR, "...terminating workio thread");
  368. return false;
  369. }
  370. /* pause, then restart work-request loop */
  371. applog(LOG_ERR, "...retry after %d seconds",
  372. opt_fail_pause);
  373. sleep(opt_fail_pause);
  374. }
  375. return true;
  376. }
  377. static void *workio_thread(void *userdata)
  378. {
  379. struct thr_info *mythr = userdata;
  380. CURL *curl;
  381. bool ok = true;
  382. curl = curl_easy_init();
  383. if (unlikely(!curl)) {
  384. applog(LOG_ERR, "CURL initialization failed");
  385. return NULL;
  386. }
  387. while (ok) {
  388. struct workio_cmd *wc;
  389. /* wait for workio_cmd sent to us, on our queue */
  390. wc = tq_pop(mythr->q, NULL);
  391. if (!wc) {
  392. ok = false;
  393. break;
  394. }
  395. /* process workio_cmd */
  396. switch (wc->cmd) {
  397. case WC_GET_WORK:
  398. ok = workio_get_work(wc, curl);
  399. break;
  400. case WC_SUBMIT_WORK:
  401. ok = workio_submit_work(wc, curl);
  402. break;
  403. default: /* should never happen */
  404. ok = false;
  405. break;
  406. }
  407. workio_cmd_free(wc);
  408. }
  409. tq_freeze(mythr->q);
  410. curl_easy_cleanup(curl);
  411. return NULL;
  412. }
  413. static void hashmeter(int thr_id, struct timeval *diff,
  414. unsigned long hashes_done)
  415. {
  416. struct timeval total_tv_end, total_diff;
  417. double khashes, secs;
  418. /* Don't bother calculating anything if we're not displaying it */
  419. if (opt_quiet)
  420. return;
  421. khashes = hashes_done / 1000.0;
  422. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  423. if (opt_n_threads + nDevs > 1) {
  424. double total_mhashes, total_secs;
  425. /* Totals are updated by all threads so can race without locking */
  426. pthread_mutex_lock(&hash_lock);
  427. total_hashes_done += hashes_done;
  428. gettimeofday(&total_tv_end, NULL);
  429. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  430. total_mhashes = total_hashes_done / 1000000.0;
  431. pthread_mutex_unlock(&hash_lock);
  432. total_secs = (double)total_diff.tv_sec +
  433. ((double)total_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);
  437. if (!thr_id)
  438. applog(LOG_INFO, "[%.2f Mhash/sec] [%d Accepted] [%d Rejected]",
  439. total_mhashes / total_secs, accepted, rejected);
  440. } else {
  441. if (opt_debug)
  442. applog(LOG_DEBUG, "[%lu hashes]", hashes_done);
  443. applog(LOG_INFO, "%.0f khash/sec] [%d Accepted] [%d Rejected]",
  444. khashes / secs, accepted, rejected);
  445. }
  446. }
  447. static bool get_work(struct thr_info *thr, struct work *work)
  448. {
  449. struct workio_cmd *wc;
  450. struct work *work_heap;
  451. /* fill out work request message */
  452. wc = calloc(1, sizeof(*wc));
  453. if (!wc)
  454. return false;
  455. wc->cmd = WC_GET_WORK;
  456. wc->thr = thr;
  457. /* send work request to workio thread */
  458. if (!tq_push(thr_info[work_thr_id].q, wc)) {
  459. workio_cmd_free(wc);
  460. return false;
  461. }
  462. /* wait for response, a unit of work */
  463. work_heap = tq_pop(thr->q, NULL);
  464. if (!work_heap)
  465. return false;
  466. /* copy returned work into storage provided by caller */
  467. memcpy(work, work_heap, sizeof(*work));
  468. free(work_heap);
  469. return true;
  470. }
  471. static bool submit_work(struct thr_info *thr, const struct work *work_in)
  472. {
  473. struct workio_cmd *wc;
  474. /* fill out work request message */
  475. wc = calloc(1, sizeof(*wc));
  476. if (!wc)
  477. return false;
  478. wc->u.work = malloc(sizeof(*work_in));
  479. if (!wc->u.work)
  480. goto err_out;
  481. wc->cmd = WC_SUBMIT_WORK;
  482. wc->thr = thr;
  483. memcpy(wc->u.work, work_in, sizeof(*work_in));
  484. /* send solution to workio thread */
  485. if (!tq_push(thr_info[work_thr_id].q, wc))
  486. goto err_out;
  487. return true;
  488. err_out:
  489. workio_cmd_free(wc);
  490. return false;
  491. }
  492. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  493. {
  494. work->data[64+12+0] = (nonce>>0) & 0xff;
  495. work->data[64+12+1] = (nonce>>8) & 0xff;
  496. work->data[64+12+2] = (nonce>>16) & 0xff;
  497. work->data[64+12+3] = (nonce>>24) & 0xff;
  498. return submit_work(thr, work);
  499. }
  500. static void *miner_thread(void *userdata)
  501. {
  502. struct thr_info *mythr = userdata;
  503. int thr_id = mythr->id;
  504. uint32_t max_nonce = 0xffffff;
  505. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  506. * and if that fails, then SCHED_BATCH. No need for this to be an
  507. * error if it fails */
  508. setpriority(PRIO_PROCESS, 0, 19);
  509. drop_policy();
  510. /* Cpu affinity only makes sense if the number of threads is a multiple
  511. * of the number of CPUs */
  512. if (!(opt_n_threads % num_processors))
  513. affine_to_cpu(mythr->id, mythr->id % num_processors);
  514. while (1) {
  515. struct work work __attribute__((aligned(128)));
  516. unsigned long hashes_done;
  517. struct timeval tv_start, tv_end, diff;
  518. uint64_t max64;
  519. bool rc;
  520. /* obtain new work from internal workio thread */
  521. if (unlikely(!get_work(mythr, &work))) {
  522. applog(LOG_ERR, "work retrieval failed, exiting "
  523. "mining thread %d", mythr->id);
  524. goto out;
  525. }
  526. hashes_done = 0;
  527. gettimeofday(&tv_start, NULL);
  528. /* scan nonces for a proof-of-work hash */
  529. switch (opt_algo) {
  530. case ALGO_C:
  531. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  532. work.hash1, work.hash, work.target,
  533. max_nonce, &hashes_done);
  534. break;
  535. #ifdef WANT_X8664_SSE2
  536. case ALGO_SSE2_64: {
  537. unsigned int rc5 =
  538. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  539. work.hash1, work.hash,
  540. work.target,
  541. max_nonce, &hashes_done);
  542. rc = (rc5 == -1) ? false : true;
  543. }
  544. break;
  545. #endif
  546. #ifdef WANT_SSE2_4WAY
  547. case ALGO_4WAY: {
  548. unsigned int rc4 =
  549. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  550. work.hash1, work.hash,
  551. work.target,
  552. max_nonce, &hashes_done);
  553. rc = (rc4 == -1) ? false : true;
  554. }
  555. break;
  556. #endif
  557. #ifdef WANT_VIA_PADLOCK
  558. case ALGO_VIA:
  559. rc = scanhash_via(thr_id, work.data, work.target,
  560. max_nonce, &hashes_done);
  561. break;
  562. #endif
  563. case ALGO_CRYPTOPP:
  564. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  565. work.hash1, work.hash, work.target,
  566. max_nonce, &hashes_done);
  567. break;
  568. #ifdef WANT_CRYPTOPP_ASM32
  569. case ALGO_CRYPTOPP_ASM32:
  570. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  571. work.hash1, work.hash, work.target,
  572. max_nonce, &hashes_done);
  573. break;
  574. #endif
  575. default:
  576. /* should never happen */
  577. goto out;
  578. }
  579. /* record scanhash elapsed time */
  580. gettimeofday(&tv_end, NULL);
  581. timeval_subtract(&diff, &tv_end, &tv_start);
  582. hashmeter(thr_id, &diff, hashes_done);
  583. /* adjust max_nonce to meet target scan time */
  584. if (diff.tv_usec > 500000)
  585. diff.tv_sec++;
  586. if (diff.tv_sec > 0) {
  587. max64 =
  588. ((uint64_t)hashes_done * opt_scantime) / diff.tv_sec;
  589. if (max64 > 0xfffffffaULL)
  590. max64 = 0xfffffffaULL;
  591. max_nonce = max64;
  592. }
  593. /* if nonce found, submit work */
  594. if (rc && !submit_work(mythr, &work))
  595. break;
  596. }
  597. out:
  598. tq_freeze(mythr->q);
  599. return NULL;
  600. }
  601. enum {
  602. STAT_SLEEP_INTERVAL = 1,
  603. STAT_CTR_INTERVAL = 10000000,
  604. FAILURE_INTERVAL = 30,
  605. };
  606. static int block = 0;
  607. static _clState *clStates[16];
  608. static void *gpuminer_thread(void *userdata)
  609. {
  610. struct thr_info *mythr = userdata;
  611. int thr_id = mythr->id;
  612. int failures = 0;
  613. uint32_t res[MAXTHREADS];
  614. setpriority(PRIO_PROCESS, 0, 19);
  615. drop_policy();
  616. size_t globalThreads[1];
  617. size_t localThreads[1];
  618. cl_int status;
  619. _clState *clState = clStates[thr_id];
  620. status = clSetKernelArg(clState->kernel, 0, sizeof(cl_mem), (void *)&clState->inputBuffer);
  621. if(status != CL_SUCCESS) { printf("Error: Setting kernel argument 1.\n"); return false; }
  622. status = clSetKernelArg(clState->kernel, 1, sizeof(cl_mem), (void *)&clState->outputBuffer);
  623. if(status != CL_SUCCESS) { printf("Error: Setting kernel argument 2.\n"); return false; }
  624. struct work *work;
  625. work = malloc(sizeof(struct work)*2);
  626. work[0].ready = 0;
  627. work[1].ready = 0;
  628. int frame = 0;
  629. int res_frame = 0;
  630. int my_block = block;
  631. bool need_work = true;
  632. unsigned long hashes_done;
  633. hashes_done = 0;
  634. unsigned int h0count = 0;
  635. while (1) {
  636. struct timeval tv_start, tv_end, diff;
  637. int threads;
  638. bool rc;
  639. gettimeofday(&tv_start, NULL);
  640. if (need_work || my_block != block) {
  641. frame++;
  642. frame %= 2;
  643. if (opt_debug)
  644. fprintf(stderr, "getwork\n");
  645. /* obtain new work from internal workio thread */
  646. if (unlikely(!get_work(mythr, work + frame))) {
  647. applog(LOG_ERR, "work retrieval failed, exiting "
  648. "gpu mining thread %d", mythr->id);
  649. goto out;
  650. }
  651. precalc_hash(&work[frame].blk, (uint32_t *)(work[frame].midstate), (uint32_t *)(work[frame].data + 64));
  652. work[frame].blk.nonce = 0;
  653. work[frame].valid = true;
  654. work[frame].ready = 0;
  655. my_block = block;
  656. need_work = false;
  657. }
  658. threads = 102400 * 4;
  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[frame].blk, 0, NULL, NULL);
  663. if(status != CL_SUCCESS) { printf("Error: clEnqueueWriteBuffer failed.\n"); goto out; }
  664. clFinish(clState->commandQueue);
  665. status = clEnqueueNDRangeKernel(clState->commandQueue, clState->kernel, 1, NULL,
  666. globalThreads, localThreads, 0, NULL, NULL);
  667. if (status != CL_SUCCESS) { printf("Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)\n"); goto out; }
  668. clFlush(clState->commandQueue);
  669. hashes_done = 1024 * threads;
  670. if (work[res_frame].ready) {
  671. rc = false;
  672. uint32_t bestG = ~0;
  673. uint32_t nonce;
  674. int j;
  675. for(j = 0; j < work[res_frame].ready; j++) {
  676. if(res[j]) {
  677. uint32_t start = (work[res_frame].res_nonce + j)<<10;
  678. uint32_t my_g, my_nonce;
  679. my_g = postcalc_hash(mythr, &work[res_frame].blk, &work[res_frame], start, start + 1026, &my_nonce, &h0count);
  680. rc = true;
  681. }
  682. }
  683. work[res_frame].ready = false;
  684. uint32_t *target = (uint32_t *)(work[res_frame].target + 24);
  685. }
  686. gettimeofday(&tv_end, NULL);
  687. timeval_subtract(&diff, &tv_end, &tv_start);
  688. hashmeter(thr_id, &diff, hashes_done);
  689. /* adjust max_nonce to meet target scan time */
  690. if (diff.tv_usec > 500000)
  691. diff.tv_sec++;
  692. if (diff.tv_sec > 0)
  693. applog(LOG_INFO, "Not reaching opt_scantime by %d", diff.tv_sec);
  694. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  695. sizeof(uint32_t) * threads, res, 0, NULL, NULL);
  696. if (status != CL_SUCCESS) { printf("Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)\n"); goto out;}
  697. res_frame = frame;
  698. work[res_frame].ready = threads;
  699. work[res_frame].res_nonce = work[res_frame].blk.nonce;
  700. work[frame].blk.nonce += threads;
  701. if (unlikely(work[frame].blk.nonce > 4000000 - threads))
  702. need_work = true;
  703. failures = 0;
  704. }
  705. out:
  706. tq_freeze(mythr->q);
  707. return NULL;
  708. }
  709. static void restart_threads(void)
  710. {
  711. int i;
  712. for (i = 0; i < opt_n_threads + nDevs; i++)
  713. work_restart[i].restart = 1;
  714. }
  715. static void *longpoll_thread(void *userdata)
  716. {
  717. struct thr_info *mythr = userdata;
  718. CURL *curl = NULL;
  719. char *copy_start, *hdr_path, *lp_url = NULL;
  720. bool need_slash = false;
  721. int failures = 0;
  722. hdr_path = tq_pop(mythr->q, NULL);
  723. if (!hdr_path)
  724. goto out;
  725. /* full URL */
  726. if (strstr(hdr_path, "://")) {
  727. lp_url = hdr_path;
  728. hdr_path = NULL;
  729. }
  730. /* absolute path, on current server */
  731. else {
  732. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  733. if (rpc_url[strlen(rpc_url) - 1] != '/')
  734. need_slash = true;
  735. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  736. if (!lp_url)
  737. goto out;
  738. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  739. }
  740. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  741. curl = curl_easy_init();
  742. if (unlikely(!curl)) {
  743. applog(LOG_ERR, "CURL initialization failed");
  744. goto out;
  745. }
  746. while (1) {
  747. json_t *val;
  748. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  749. false, true);
  750. if (likely(val)) {
  751. failures = 0;
  752. json_decref(val);
  753. applog(LOG_INFO, "LONGPOLL detected new block");
  754. restart_threads();
  755. } else {
  756. if (failures++ < 10) {
  757. sleep(30);
  758. applog(LOG_ERR,
  759. "longpoll failed, sleeping for 30s");
  760. } else {
  761. applog(LOG_ERR,
  762. "longpoll failed, ending thread");
  763. goto out;
  764. }
  765. }
  766. }
  767. out:
  768. free(hdr_path);
  769. free(lp_url);
  770. tq_freeze(mythr->q);
  771. if (curl)
  772. curl_easy_cleanup(curl);
  773. return NULL;
  774. }
  775. static void show_usage(void)
  776. {
  777. int i;
  778. printf("minerd version %s\n\n", VERSION);
  779. printf("Usage:\tminerd [options]\n\nSupported options:\n");
  780. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  781. struct option_help *h;
  782. h = &options_help[i];
  783. printf("--%s\n%s\n\n", h->name, h->helptext);
  784. }
  785. exit(1);
  786. }
  787. static void parse_arg (int key, char *arg)
  788. {
  789. int v, i;
  790. switch(key) {
  791. case 'a':
  792. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  793. if (algo_names[i] &&
  794. !strcmp(arg, algo_names[i])) {
  795. opt_algo = i;
  796. break;
  797. }
  798. }
  799. if (i == ARRAY_SIZE(algo_names))
  800. show_usage();
  801. break;
  802. case 'c': {
  803. json_error_t err;
  804. if (opt_config)
  805. json_decref(opt_config);
  806. opt_config = json_load_file(arg, &err);
  807. if (!json_is_object(opt_config)) {
  808. applog(LOG_ERR, "JSON decode of %s failed", arg);
  809. show_usage();
  810. }
  811. break;
  812. }
  813. case 'q':
  814. opt_quiet = true;
  815. break;
  816. case 'D':
  817. opt_debug = true;
  818. break;
  819. case 'p':
  820. free(rpc_pass);
  821. rpc_pass = strdup(arg);
  822. break;
  823. case 'P':
  824. opt_protocol = true;
  825. break;
  826. case 'r':
  827. v = atoi(arg);
  828. if (v < -1 || v > 9999) /* sanity check */
  829. show_usage();
  830. opt_retries = v;
  831. break;
  832. case 'R':
  833. v = atoi(arg);
  834. if (v < 1 || v > 9999) /* sanity check */
  835. show_usage();
  836. opt_fail_pause = v;
  837. break;
  838. case 's':
  839. v = atoi(arg);
  840. if (v < 1 || v > 9999) /* sanity check */
  841. show_usage();
  842. opt_scantime = v;
  843. break;
  844. case 't':
  845. v = atoi(arg);
  846. if (v < 1 || v > 9999) /* sanity check */
  847. show_usage();
  848. opt_n_threads = v;
  849. break;
  850. case 'u':
  851. free(rpc_user);
  852. rpc_user = strdup(arg);
  853. break;
  854. case 1001: /* --url */
  855. if (strncmp(arg, "http://", 7) &&
  856. strncmp(arg, "https://", 8))
  857. show_usage();
  858. free(rpc_url);
  859. rpc_url = strdup(arg);
  860. break;
  861. case 1002: /* --userpass */
  862. if (!strchr(arg, ':'))
  863. show_usage();
  864. free(rpc_userpass);
  865. rpc_userpass = strdup(arg);
  866. break;
  867. case 1003:
  868. want_longpoll = false;
  869. break;
  870. case 1004:
  871. use_syslog = true;
  872. break;
  873. default:
  874. show_usage();
  875. }
  876. #ifdef WIN32
  877. if (!opt_n_threads)
  878. opt_n_threads = 1;
  879. #else
  880. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  881. if (!opt_n_threads)
  882. opt_n_threads = num_processors;
  883. #endif /* !WIN32 */
  884. }
  885. static void parse_config(void)
  886. {
  887. int i;
  888. json_t *val;
  889. if (!json_is_object(opt_config))
  890. return;
  891. for (i = 0; i < ARRAY_SIZE(options); i++) {
  892. if (!options[i].name)
  893. break;
  894. if (!strcmp(options[i].name, "config"))
  895. continue;
  896. val = json_object_get(opt_config, options[i].name);
  897. if (!val)
  898. continue;
  899. if (options[i].has_arg && json_is_string(val)) {
  900. char *s = strdup(json_string_value(val));
  901. if (!s)
  902. break;
  903. parse_arg(options[i].val, s);
  904. free(s);
  905. } else if (!options[i].has_arg && json_is_true(val))
  906. parse_arg(options[i].val, "");
  907. else
  908. applog(LOG_ERR, "JSON option %s invalid",
  909. options[i].name);
  910. }
  911. }
  912. static void parse_cmdline(int argc, char *argv[])
  913. {
  914. int key;
  915. while (1) {
  916. key = getopt_long(argc, argv, "a:c:qDPr:s:t:h?", options, NULL);
  917. if (key < 0)
  918. break;
  919. parse_arg(key, optarg);
  920. }
  921. parse_config();
  922. }
  923. int main (int argc, char *argv[])
  924. {
  925. struct thr_info *thr;
  926. int i;
  927. char name[32];
  928. nDevs = clDevicesNum();
  929. if (opt_ndevs) {
  930. printf("%i\n", nDevs);
  931. return nDevs;
  932. }
  933. rpc_url = strdup(DEF_RPC_URL);
  934. /* parse command line */
  935. parse_cmdline(argc, argv);
  936. if (!rpc_userpass) {
  937. if (!rpc_user || !rpc_pass) {
  938. applog(LOG_ERR, "No login credentials supplied");
  939. return 1;
  940. }
  941. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  942. if (!rpc_userpass)
  943. return 1;
  944. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  945. }
  946. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  947. return 1;
  948. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  949. return 1;
  950. #ifdef HAVE_SYSLOG_H
  951. if (use_syslog)
  952. openlog("cpuminer", LOG_PID, LOG_USER);
  953. #endif
  954. work_restart = calloc(opt_n_threads + nDevs, sizeof(*work_restart));
  955. if (!work_restart)
  956. return 1;
  957. thr_info = calloc(opt_n_threads + 2 + nDevs, sizeof(*thr));
  958. if (!thr_info)
  959. return 1;
  960. /* init workio thread info */
  961. work_thr_id = opt_n_threads + nDevs;
  962. thr = &thr_info[work_thr_id];
  963. thr->id = work_thr_id;
  964. thr->q = tq_new();
  965. if (!thr->q)
  966. return 1;
  967. /* start work I/O thread */
  968. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  969. applog(LOG_ERR, "workio thread create failed");
  970. return 1;
  971. }
  972. /* init longpoll thread info */
  973. if (want_longpoll) {
  974. longpoll_thr_id = opt_n_threads + nDevs + 1;
  975. thr = &thr_info[longpoll_thr_id];
  976. thr->id = longpoll_thr_id;
  977. thr->q = tq_new();
  978. if (!thr->q)
  979. return 1;
  980. /* start longpoll thread */
  981. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  982. applog(LOG_ERR, "longpoll thread create failed");
  983. return 1;
  984. }
  985. } else
  986. longpoll_thr_id = -1;
  987. gettimeofday(&total_tv_start, NULL);
  988. /* start gpu mining threads */
  989. for (i = 0; i < nDevs; i++) {
  990. thr = &thr_info[i];
  991. thr->id = i;
  992. thr->q = tq_new();
  993. if (!thr->q)
  994. return 1;
  995. printf("Init GPU %i\n", i);
  996. clStates[i] = initCl(i, name, sizeof(name));
  997. printf("initCl() finished. Found %s\n", name);
  998. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  999. applog(LOG_ERR, "thread %d create failed", i);
  1000. return 1;
  1001. }
  1002. sleep(1); /* don't pound RPC server all at once */
  1003. }
  1004. fprintf(stderr, "%d gpu miner threads started\n", i);
  1005. /* start mining threads */
  1006. for (i = nDevs; i < nDevs + opt_n_threads; i++) {
  1007. thr = &thr_info[i];
  1008. thr->id = i;
  1009. thr->q = tq_new();
  1010. if (!thr->q)
  1011. return 1;
  1012. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1013. applog(LOG_ERR, "thread %d create failed", i);
  1014. return 1;
  1015. }
  1016. sleep(1); /* don't pound RPC server all at once */
  1017. }
  1018. applog(LOG_INFO, "%d cpu miner threads started, "
  1019. "using SHA256 '%s' algorithm.",
  1020. opt_n_threads,
  1021. algo_names[opt_algo]);
  1022. /* main loop - simply wait for workio thread to exit */
  1023. pthread_join(thr_info[work_thr_id].pth, NULL);
  1024. applog(LOG_INFO, "workio thread dead, exiting.");
  1025. return 0;
  1026. }