cpu-miner.c 31 KB

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