cpu-miner.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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 cpu mining 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_vectors;
  110. int opt_worksize;
  111. int opt_scantime = 60;
  112. static json_t *opt_config;
  113. static const bool opt_time = true;
  114. #ifdef WANT_X8664_SSE2
  115. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  116. #else
  117. static enum sha256_algos opt_algo = ALGO_C;
  118. #endif
  119. static int nDevs;
  120. static int opt_g_threads = 2;
  121. static int gpu_threads;
  122. static int opt_n_threads = 1;
  123. static int num_processors;
  124. static int scan_intensity = 4;
  125. static char *rpc_url;
  126. static char *rpc_userpass;
  127. static char *rpc_user, *rpc_pass;
  128. struct thr_info *thr_info;
  129. static int work_thr_id;
  130. int longpoll_thr_id;
  131. struct work_restart *work_restart = NULL;
  132. pthread_mutex_t time_lock;
  133. static pthread_mutex_t hash_lock;
  134. static pthread_mutex_t get_lock;
  135. static double total_mhashes_done;
  136. static struct timeval total_tv_start, total_tv_end;
  137. static int accepted, rejected;
  138. int hw_errors;
  139. struct option_help {
  140. const char *name;
  141. const char *helptext;
  142. };
  143. static struct option_help options_help[] = {
  144. { "help",
  145. "(-h) Display this help text" },
  146. { "algo XXX",
  147. "(-a XXX) Specify sha256 implementation:\n"
  148. "\tc\t\tLinux kernel sha256, implemented in C (default)"
  149. #ifdef WANT_SSE2_4WAY
  150. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  151. #endif
  152. #ifdef WANT_VIA_PADLOCK
  153. "\n\tvia\t\tVIA padlock implementation"
  154. #endif
  155. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  156. #ifdef WANT_CRYPTOPP_ASM32
  157. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  158. #endif
  159. #ifdef WANT_X8664_SSE2
  160. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  161. #endif
  162. },
  163. { "config FILE",
  164. "(-c FILE) JSON-format configuration file (default: none)\n"
  165. "See example-cfg.json for an example configuration." },
  166. { "cpu-threads N",
  167. "(-t N) Number of miner CPU threads (default: number of processors or 0 if GPU mining)" },
  168. { "debug",
  169. "(-D) Enable debug output (default: off)" },
  170. { "gpu-threads N",
  171. "(-g N) Number of threads per-GPU (0 - 10, default: 2)" },
  172. { "intensity",
  173. "(-I) Intensity of scanning (0 - 14, default 4)" },
  174. { "log",
  175. "(-l) Interval in seconds between log output (default: 5)" },
  176. { "ndevs",
  177. "(-n) Display number of detected GPUs" },
  178. { "no-longpoll",
  179. "Disable X-Long-Polling support (default: enabled)" },
  180. { "pass PASSWORD",
  181. "(-p PASSWORD) Password for bitcoin JSON-RPC server "
  182. "(default: " DEF_RPC_PASSWORD ")" },
  183. { "protocol-dump",
  184. "(-P) Verbose dump of protocol-level activities (default: off)" },
  185. { "quiet",
  186. "(-q) Disable per-thread hashmeter output (default: off)" },
  187. { "retries N",
  188. "(-r N) Number of times to retry, if JSON-RPC call fails\n"
  189. "\t(default: 10; use -1 for \"never\")" },
  190. { "retry-pause N",
  191. "(-R N) Number of seconds to pause, between retries\n"
  192. "\t(default: 30)" },
  193. { "scantime N",
  194. "(-s N) Upper bound on time spent scanning current work,\n"
  195. "\tin seconds. (default: 60)" },
  196. #ifdef HAVE_SYSLOG_H
  197. { "syslog",
  198. "Use system log for output messages (default: standard error)" },
  199. #endif
  200. { "url URL",
  201. "URL for bitcoin JSON-RPC server "
  202. "(default: " DEF_RPC_URL ")" },
  203. { "userpass USERNAME:PASSWORD",
  204. "Username:Password pair for bitcoin JSON-RPC server "
  205. "(default: " DEF_RPC_USERPASS ")" },
  206. { "user USERNAME",
  207. "(-u USERNAME) Username for bitcoin JSON-RPC server "
  208. "(default: " DEF_RPC_USERNAME ")" },
  209. { "vectors N",
  210. "(-v N) Override detected optimal vector width (default: detected, 1,2 or 4)" },
  211. { "worksize N",
  212. "(-w N) Override detected optimal worksize (default: detected)" },
  213. };
  214. static struct option options[] = {
  215. { "algo", 1, NULL, 'a' },
  216. { "config", 1, NULL, 'c' },
  217. { "cpu-threads", 1, NULL, 't' },
  218. { "gpu-threads", 1, NULL, 'g' },
  219. { "debug", 0, NULL, 'D' },
  220. { "help", 0, NULL, 'h' },
  221. { "intensity", 1, NULL, 'I' },
  222. { "log", 1, NULL, 'l' },
  223. { "ndevs", 0, NULL, 'n' },
  224. { "no-longpoll", 0, NULL, 1003 },
  225. { "pass", 1, NULL, 'p' },
  226. { "protocol-dump", 0, NULL, 'P' },
  227. { "quiet", 0, NULL, 'q' },
  228. { "retries", 1, NULL, 'r' },
  229. { "retry-pause", 1, NULL, 'R' },
  230. { "scantime", 1, NULL, 's' },
  231. #ifdef HAVE_SYSLOG_H
  232. { "syslog", 0, NULL, 1004 },
  233. #endif
  234. { "url", 1, NULL, 1001 },
  235. { "user", 1, NULL, 'u' },
  236. { "vectors", 1, NULL, 'v' },
  237. { "worksize", 1, NULL, 'w' },
  238. { "userpass", 1, NULL, 1002 },
  239. };
  240. static bool jobj_binary(const json_t *obj, const char *key,
  241. void *buf, size_t buflen)
  242. {
  243. const char *hexstr;
  244. json_t *tmp;
  245. tmp = json_object_get(obj, key);
  246. if (unlikely(!tmp)) {
  247. applog(LOG_ERR, "JSON key '%s' not found", key);
  248. return false;
  249. }
  250. hexstr = json_string_value(tmp);
  251. if (unlikely(!hexstr)) {
  252. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  253. return false;
  254. }
  255. if (!hex2bin(buf, hexstr, buflen))
  256. return false;
  257. return true;
  258. }
  259. static bool work_decode(const json_t *val, struct work *work)
  260. {
  261. if (unlikely(!jobj_binary(val, "midstate",
  262. work->midstate, sizeof(work->midstate)))) {
  263. applog(LOG_ERR, "JSON inval midstate");
  264. goto err_out;
  265. }
  266. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  267. applog(LOG_ERR, "JSON inval data");
  268. goto err_out;
  269. }
  270. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  271. applog(LOG_ERR, "JSON inval hash1");
  272. goto err_out;
  273. }
  274. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  275. applog(LOG_ERR, "JSON inval target");
  276. goto err_out;
  277. }
  278. memset(work->hash, 0, sizeof(work->hash));
  279. return true;
  280. err_out:
  281. return false;
  282. }
  283. static bool submit_upstream_work(CURL *curl, const struct work *work)
  284. {
  285. char *hexstr = NULL;
  286. json_t *val, *res;
  287. char s[345];
  288. bool rc = false;
  289. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  290. /* build hex string */
  291. hexstr = bin2hex(work->data, sizeof(work->data));
  292. if (unlikely(!hexstr)) {
  293. applog(LOG_ERR, "submit_upstream_work OOM");
  294. goto out;
  295. }
  296. /* build JSON-RPC request */
  297. sprintf(s,
  298. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  299. hexstr);
  300. if (opt_debug)
  301. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  302. /* issue JSON-RPC request */
  303. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  304. if (unlikely(!val)) {
  305. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  306. goto out;
  307. }
  308. res = json_object_get(val, "result");
  309. /* Theoretically threads could race when modifying accepted and
  310. * rejected values but the chance of two submits completing at the
  311. * same time is zero so there is no point adding extra locking */
  312. if (json_is_true(res)) {
  313. cgpu->accepted++;
  314. accepted++;
  315. if (opt_debug)
  316. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  317. } else {
  318. cgpu->rejected++;
  319. rejected++;
  320. if (opt_debug)
  321. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  322. }
  323. applog(LOG_INFO, "%sPU: %d Accepted: %d Rejected: %d HW errors: %d",
  324. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->accepted, cgpu->rejected, cgpu->hw_errors);
  325. json_decref(val);
  326. rc = true;
  327. out:
  328. free(hexstr);
  329. return rc;
  330. }
  331. static const char *rpc_req =
  332. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  333. static bool get_upstream_work(CURL *curl, struct work *work)
  334. {
  335. json_t *val;
  336. bool rc;
  337. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  338. want_longpoll, false);
  339. if (!val)
  340. return false;
  341. rc = work_decode(json_object_get(val, "result"), work);
  342. json_decref(val);
  343. return rc;
  344. }
  345. static void workio_cmd_free(struct workio_cmd *wc)
  346. {
  347. if (!wc)
  348. return;
  349. switch (wc->cmd) {
  350. case WC_SUBMIT_WORK:
  351. free(wc->u.work);
  352. break;
  353. default: /* do nothing */
  354. break;
  355. }
  356. memset(wc, 0, sizeof(*wc)); /* poison */
  357. free(wc);
  358. }
  359. static bool workio_get_work(struct workio_cmd *wc, CURL *curl)
  360. {
  361. struct work *ret_work;
  362. int failures = 0;
  363. ret_work = calloc(1, sizeof(*ret_work));
  364. if (!ret_work) {
  365. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  366. return false;
  367. }
  368. /* obtain new work from bitcoin via JSON-RPC */
  369. while (!get_upstream_work(curl, ret_work)) {
  370. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  371. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  372. free(ret_work);
  373. return false;
  374. }
  375. /* pause, then restart work-request loop */
  376. applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
  377. opt_fail_pause);
  378. sleep(opt_fail_pause);
  379. }
  380. /* send work to requesting thread */
  381. if (unlikely(!tq_push(wc->thr->q, ret_work))) {
  382. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  383. free(ret_work);
  384. }
  385. return true;
  386. }
  387. static bool workio_submit_work(struct workio_cmd *wc, CURL *curl)
  388. {
  389. int failures = 0;
  390. /* submit solution to bitcoin via JSON-RPC */
  391. while (!submit_upstream_work(curl, wc->u.work)) {
  392. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  393. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  394. return false;
  395. }
  396. /* pause, then restart work-request loop */
  397. applog(LOG_ERR, "...retry after %d seconds",
  398. opt_fail_pause);
  399. sleep(opt_fail_pause);
  400. }
  401. return true;
  402. }
  403. static void *workio_thread(void *userdata)
  404. {
  405. struct thr_info *mythr = userdata;
  406. bool ok = true;
  407. CURL *curl;
  408. curl = curl_easy_init();
  409. if (unlikely(!curl)) {
  410. applog(LOG_ERR, "CURL initialization failed");
  411. return NULL;
  412. }
  413. while (ok) {
  414. struct workio_cmd *wc;
  415. /* wait for workio_cmd sent to us, on our queue */
  416. wc = tq_pop(mythr->q, NULL);
  417. if (!wc) {
  418. ok = false;
  419. break;
  420. }
  421. /* process workio_cmd */
  422. switch (wc->cmd) {
  423. case WC_GET_WORK:
  424. ok = workio_get_work(wc, curl);
  425. break;
  426. case WC_SUBMIT_WORK:
  427. ok = workio_submit_work(wc, curl);
  428. break;
  429. default: /* should never happen */
  430. ok = false;
  431. break;
  432. }
  433. workio_cmd_free(wc);
  434. }
  435. tq_freeze(mythr->q);
  436. curl_easy_cleanup(curl);
  437. return NULL;
  438. }
  439. static void hashmeter(int thr_id, struct timeval *diff,
  440. unsigned long hashes_done)
  441. {
  442. struct timeval temp_tv_end, total_diff;
  443. double khashes, secs;
  444. double total_secs;
  445. double local_secs;
  446. static double local_mhashes_done = 0;
  447. static double rolling_local = 0;
  448. double local_mhashes = (double)hashes_done / 1000000.0;
  449. /* Don't bother calculating anything if we're not displaying it */
  450. if (opt_quiet || !opt_log_interval)
  451. return;
  452. khashes = hashes_done / 1000.0;
  453. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  454. if (opt_debug)
  455. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  456. thr_id, hashes_done, hashes_done / secs);
  457. gettimeofday(&temp_tv_end, NULL);
  458. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  459. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  460. if (opt_n_threads + gpu_threads > 1) {
  461. /* Totals are updated by all threads so can race without locking */
  462. pthread_mutex_lock(&hash_lock);
  463. total_mhashes_done += local_mhashes;
  464. local_mhashes_done += local_mhashes;
  465. if (total_diff.tv_sec < opt_log_interval) {
  466. /* Only update the total every opt_log_interval seconds */
  467. pthread_mutex_unlock(&hash_lock);
  468. return;
  469. }
  470. gettimeofday(&total_tv_end, NULL);
  471. pthread_mutex_unlock(&hash_lock);
  472. } else {
  473. total_mhashes_done += local_mhashes;
  474. local_mhashes_done += local_mhashes;
  475. if (total_diff.tv_sec < opt_log_interval)
  476. return;
  477. gettimeofday(&total_tv_end, NULL);
  478. }
  479. /* Use a rolling average by faking an exponential decay over 5 * log */
  480. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  481. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  482. total_secs = (double)total_diff.tv_sec +
  483. ((double)total_diff.tv_usec / 1000000.0);
  484. applog(LOG_INFO, "[%.2f | %.2f Mhash/s] [%d Accepted] [%d Rejected] [%d HW errors]",
  485. rolling_local / local_secs,
  486. total_mhashes_done / total_secs, accepted, rejected, hw_errors);
  487. local_mhashes_done = 0;
  488. }
  489. static struct work *work_heap = NULL;
  490. /* Since we always have one extra work item queued, set the thread id to 0
  491. * for all the work and just give the work to the first thread that requests
  492. * work */
  493. static bool get_work(struct work *work)
  494. {
  495. struct thr_info *thr = &thr_info[0];
  496. struct workio_cmd *wc;
  497. bool ret = false;
  498. /* fill out work request message */
  499. wc = calloc(1, sizeof(*wc));
  500. if (unlikely(!wc))
  501. goto out;
  502. wc->cmd = WC_GET_WORK;
  503. wc->thr = thr;
  504. /* send work request to workio thread */
  505. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  506. workio_cmd_free(wc);
  507. goto out;
  508. }
  509. /* work_heap is protected by get_lock */
  510. pthread_mutex_lock(&get_lock);
  511. if (likely(work_heap)) {
  512. memcpy(work, work_heap, sizeof(*work));
  513. /* Wait for next response, a unit of work - it should be queued */
  514. free(work_heap);
  515. work_heap = tq_pop(thr->q, NULL);
  516. } else {
  517. /* wait for 1st response, or 1st response after failure */
  518. work_heap = tq_pop(thr->q, NULL);
  519. if (unlikely(!work_heap))
  520. goto out_unlock;
  521. /* send for another work request for the next time get_work
  522. * is called. */
  523. wc = calloc(1, sizeof(*wc));
  524. if (unlikely(!wc)) {
  525. free(work_heap);
  526. work_heap = NULL;
  527. goto out_unlock;
  528. }
  529. wc->cmd = WC_GET_WORK;
  530. wc->thr = thr;
  531. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  532. workio_cmd_free(wc);
  533. free(work_heap);
  534. work_heap = NULL;
  535. goto out_unlock;
  536. }
  537. }
  538. ret = true;
  539. out_unlock:
  540. pthread_mutex_unlock(&get_lock);
  541. out:
  542. return ret;
  543. }
  544. struct submit_data {
  545. struct thr_info *thr;
  546. struct work *work_in;
  547. pthread_t pth;
  548. };
  549. static void *submit_work(void *userdata)
  550. {
  551. struct submit_data *sd = (struct submit_data *)userdata;
  552. struct workio_cmd *wc;
  553. /* fill out work request message */
  554. wc = calloc(1, sizeof(*wc));
  555. if (unlikely(!wc))
  556. goto out;
  557. wc->u.work = malloc(sizeof(struct work));
  558. if (unlikely(!wc->u.work))
  559. goto err_out;
  560. wc->cmd = WC_SUBMIT_WORK;
  561. wc->thr = sd->thr;
  562. memcpy(wc->u.work, &sd->work_in, sizeof(struct work));
  563. /* send solution to workio thread */
  564. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc)))
  565. goto err_out;
  566. goto out;
  567. err_out:
  568. workio_cmd_free(wc);
  569. out:
  570. pthread_detach(pthread_self());
  571. free(sd);
  572. return NULL;
  573. }
  574. static bool submit_work_async(struct thr_info *thr, const struct work *work_in)
  575. {
  576. struct submit_data *sd = malloc(sizeof(struct submit_data));
  577. if (unlikely(!sd)) {
  578. applog(LOG_ERR, "Failed to malloc sd in submit_work_async");
  579. return false;
  580. }
  581. sd->work_in = malloc(sizeof(struct work));
  582. if (unlikely(!sd->work_in)) {
  583. applog(LOG_ERR, "Failed to malloc work_in in submit_work_async");
  584. return false;
  585. }
  586. memcpy(sd->work_in, work_in, sizeof(struct work));
  587. /* Pass the thread id to the work struct for per-thread accounting */
  588. sd->work_in->thr_id = thr->id;
  589. if (pthread_create(&sd->pth, NULL, submit_work, (void *)sd)) {
  590. applog(LOG_ERR, "Failed to create submit_thread");
  591. return false;
  592. }
  593. return true;
  594. }
  595. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  596. {
  597. struct workio_cmd *wc;
  598. /* fill out work request message */
  599. wc = calloc(1, sizeof(*wc));
  600. if (unlikely(!wc)) {
  601. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  602. return false;
  603. }
  604. wc->u.work = malloc(sizeof(*work_in));
  605. if (unlikely(!wc->u.work)) {
  606. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  607. goto err_out;
  608. }
  609. wc->cmd = WC_SUBMIT_WORK;
  610. wc->thr = thr;
  611. memcpy(wc->u.work, work_in, sizeof(*work_in));
  612. /* send solution to workio thread */
  613. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  614. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  615. goto err_out;
  616. }
  617. return true;
  618. err_out:
  619. workio_cmd_free(wc);
  620. return false;
  621. }
  622. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  623. {
  624. work->data[64+12+0] = (nonce>>0) & 0xff;
  625. work->data[64+12+1] = (nonce>>8) & 0xff;
  626. work->data[64+12+2] = (nonce>>16) & 0xff;
  627. work->data[64+12+3] = (nonce>>24) & 0xff;
  628. return submit_work_sync(thr, work);
  629. }
  630. static inline int cpu_from_thr_id(int thr_id)
  631. {
  632. return (thr_id - gpu_threads) % num_processors;
  633. }
  634. static void *miner_thread(void *userdata)
  635. {
  636. struct thr_info *mythr = userdata;
  637. const int thr_id = mythr->id;
  638. uint32_t max_nonce = 0xffffff;
  639. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  640. * and if that fails, then SCHED_BATCH. No need for this to be an
  641. * error if it fails */
  642. setpriority(PRIO_PROCESS, 0, 19);
  643. drop_policy();
  644. /* Cpu affinity only makes sense if the number of threads is a multiple
  645. * of the number of CPUs */
  646. if (!(opt_n_threads % num_processors))
  647. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  648. while (1) {
  649. struct work work __attribute__((aligned(128)));
  650. unsigned long hashes_done;
  651. struct timeval tv_start, tv_end, diff;
  652. uint64_t max64;
  653. bool rc;
  654. /* obtain new work from internal workio thread */
  655. if (unlikely(!get_work(&work))) {
  656. applog(LOG_ERR, "work retrieval failed, exiting "
  657. "mining thread %d", mythr->id);
  658. goto out;
  659. }
  660. work.thr_id = thr_id;
  661. hashes_done = 0;
  662. gettimeofday(&tv_start, NULL);
  663. /* scan nonces for a proof-of-work hash */
  664. switch (opt_algo) {
  665. case ALGO_C:
  666. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  667. work.hash1, work.hash, work.target,
  668. max_nonce, &hashes_done);
  669. break;
  670. #ifdef WANT_X8664_SSE2
  671. case ALGO_SSE2_64: {
  672. unsigned int rc5 =
  673. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  674. work.hash1, work.hash,
  675. work.target,
  676. max_nonce, &hashes_done);
  677. rc = (rc5 == -1) ? false : true;
  678. }
  679. break;
  680. #endif
  681. #ifdef WANT_SSE2_4WAY
  682. case ALGO_4WAY: {
  683. unsigned int rc4 =
  684. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  685. work.hash1, work.hash,
  686. work.target,
  687. max_nonce, &hashes_done);
  688. rc = (rc4 == -1) ? false : true;
  689. }
  690. break;
  691. #endif
  692. #ifdef WANT_VIA_PADLOCK
  693. case ALGO_VIA:
  694. rc = scanhash_via(thr_id, work.data, work.target,
  695. max_nonce, &hashes_done);
  696. break;
  697. #endif
  698. case ALGO_CRYPTOPP:
  699. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  700. work.hash1, work.hash, work.target,
  701. max_nonce, &hashes_done);
  702. break;
  703. #ifdef WANT_CRYPTOPP_ASM32
  704. case ALGO_CRYPTOPP_ASM32:
  705. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  706. work.hash1, work.hash, work.target,
  707. max_nonce, &hashes_done);
  708. break;
  709. #endif
  710. default:
  711. /* should never happen */
  712. goto out;
  713. }
  714. /* record scanhash elapsed time */
  715. gettimeofday(&tv_end, NULL);
  716. timeval_subtract(&diff, &tv_end, &tv_start);
  717. hashmeter(thr_id, &diff, hashes_done);
  718. /* adjust max_nonce to meet target scan time */
  719. if (diff.tv_usec > 500000)
  720. diff.tv_sec++;
  721. if (diff.tv_sec > 0) {
  722. max64 =
  723. ((uint64_t)hashes_done * (opt_log_interval ? : opt_scantime)) / diff.tv_sec;
  724. if (max64 > 0xfffffffaULL)
  725. max64 = 0xfffffffaULL;
  726. max_nonce = max64;
  727. }
  728. /* if nonce found, submit work */
  729. if (unlikely(rc)) {
  730. if (opt_debug)
  731. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  732. if (!submit_work_async(mythr, &work))
  733. break;
  734. }
  735. }
  736. out:
  737. tq_freeze(mythr->q);
  738. return NULL;
  739. }
  740. enum {
  741. STAT_SLEEP_INTERVAL = 1,
  742. STAT_CTR_INTERVAL = 10000000,
  743. FAILURE_INTERVAL = 30,
  744. };
  745. static _clState *clStates[16];
  746. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  747. {
  748. cl_kernel *kernel = &clState->kernel;
  749. cl_int status = 0;
  750. int num = 0;
  751. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  752. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  753. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  754. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  755. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  756. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  757. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  758. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  759. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  760. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  761. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  762. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  763. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  764. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  765. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  766. if (clState->hasBitAlign == true) {
  767. /* Parameters for phatk kernel */
  768. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  769. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  770. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  771. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  772. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  773. } else {
  774. /* Parameters for poclbm kernel */
  775. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  776. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  777. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  778. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  779. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  780. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  781. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  782. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  783. }
  784. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  785. (void *)&clState->outputBuffer);
  786. return status;
  787. }
  788. static inline int gpu_from_thr_id(int thr_id)
  789. {
  790. return thr_id % nDevs;
  791. }
  792. static void *gpuminer_thread(void *userdata)
  793. {
  794. struct thr_info *mythr = userdata;
  795. struct timeval tv_start, diff;
  796. const int thr_id = mythr->id;
  797. uint32_t *res, *blank_res;
  798. size_t globalThreads[1];
  799. size_t localThreads[1];
  800. cl_int status;
  801. _clState *clState = clStates[thr_id];
  802. const cl_kernel *kernel = &clState->kernel;
  803. struct work *work = malloc(sizeof(struct work));
  804. unsigned const int threads = 1 << (15 + scan_intensity);
  805. unsigned const int vectors = clState->preferred_vwidth;
  806. unsigned const int hashes = threads * vectors;
  807. unsigned int hashes_done = 0;
  808. res = calloc(BUFFERSIZE, 1);
  809. blank_res = calloc(BUFFERSIZE, 1);
  810. if (!res || !blank_res) {
  811. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  812. goto out;
  813. }
  814. gettimeofday(&tv_start, NULL);
  815. globalThreads[0] = threads;
  816. localThreads[0] = clState->work_size;
  817. work_restart[thr_id].restart = 1;
  818. diff.tv_sec = 0;
  819. while (1) {
  820. struct timeval tv_end, tv_workstart;
  821. /* This finish flushes the readbuffer set with CL_FALSE later */
  822. clFinish(clState->commandQueue);
  823. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  824. /* Ignore any reads since we're getting new work and queue a clean buffer */
  825. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  826. BUFFERSIZE, blank_res, 0, NULL, NULL);
  827. if (unlikely(status != CL_SUCCESS))
  828. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  829. memset(res, 0, BUFFERSIZE);
  830. gettimeofday(&tv_workstart, NULL);
  831. /* obtain new work from internal workio thread */
  832. if (unlikely(!get_work(work))) {
  833. applog(LOG_ERR, "work retrieval failed, exiting "
  834. "gpu mining thread %d", mythr->id);
  835. goto out;
  836. }
  837. work->thr_id = thr_id;
  838. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  839. work->blk.nonce = 0;
  840. work_restart[thr_id].restart = 0;
  841. if (opt_debug)
  842. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  843. /* Flushes the writebuffer set with CL_FALSE above */
  844. clFinish(clState->commandQueue);
  845. status = queue_kernel_parameters(clState, &work->blk);
  846. if (unlikely(status != CL_SUCCESS))
  847. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  848. } else {
  849. status = clSetKernelArg(*kernel, 14, sizeof(uint), (void *)&work->blk.nonce);
  850. if (unlikely(status != CL_SUCCESS))
  851. { applog(LOG_ERR, "Error: clSetKernelArg of nonce failed."); goto out; }
  852. }
  853. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  854. if (res[MAXBUFFERS]) {
  855. /* Clear the buffer again */
  856. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  857. BUFFERSIZE, blank_res, 0, NULL, NULL);
  858. if (unlikely(status != CL_SUCCESS))
  859. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  860. if (opt_debug)
  861. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  862. postcalc_hash_async(mythr, work, res);
  863. memset(res, 0, BUFFERSIZE);
  864. clFinish(clState->commandQueue);
  865. }
  866. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  867. globalThreads, localThreads, 0, NULL, NULL);
  868. if (unlikely(status != CL_SUCCESS))
  869. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  870. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  871. BUFFERSIZE, res, 0, NULL, NULL);
  872. if (unlikely(status != CL_SUCCESS))
  873. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  874. gettimeofday(&tv_end, NULL);
  875. timeval_subtract(&diff, &tv_end, &tv_start);
  876. hashes_done += hashes;
  877. work->blk.nonce += hashes;
  878. if (diff.tv_sec >= 1) {
  879. hashmeter(thr_id, &diff, hashes_done);
  880. gettimeofday(&tv_start, NULL);
  881. hashes_done = 0;
  882. }
  883. timeval_subtract(&diff, &tv_end, &tv_workstart);
  884. }
  885. out:
  886. tq_freeze(mythr->q);
  887. return NULL;
  888. }
  889. static void restart_threads(void)
  890. {
  891. int i;
  892. pthread_mutex_lock(&get_lock);
  893. for (i = 0; i < opt_n_threads + gpu_threads; i++)
  894. work_restart[i].restart = 1;
  895. /* If longpoll has detected a new block, we should discard any queued
  896. * blocks in work_heap */
  897. if (likely(work_heap)) {
  898. free(work_heap);
  899. work_heap = NULL;
  900. }
  901. pthread_mutex_unlock(&get_lock);
  902. }
  903. static void *longpoll_thread(void *userdata)
  904. {
  905. struct thr_info *mythr = userdata;
  906. CURL *curl = NULL;
  907. char *copy_start, *hdr_path, *lp_url = NULL;
  908. bool need_slash = false;
  909. int failures = 0;
  910. hdr_path = tq_pop(mythr->q, NULL);
  911. if (!hdr_path)
  912. goto out;
  913. /* full URL */
  914. if (strstr(hdr_path, "://")) {
  915. lp_url = hdr_path;
  916. hdr_path = NULL;
  917. }
  918. /* absolute path, on current server */
  919. else {
  920. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  921. if (rpc_url[strlen(rpc_url) - 1] != '/')
  922. need_slash = true;
  923. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  924. if (!lp_url)
  925. goto out;
  926. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  927. }
  928. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  929. curl = curl_easy_init();
  930. if (unlikely(!curl)) {
  931. applog(LOG_ERR, "CURL initialization failed");
  932. goto out;
  933. }
  934. while (1) {
  935. json_t *val;
  936. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  937. false, true);
  938. if (likely(val)) {
  939. failures = 0;
  940. json_decref(val);
  941. applog(LOG_INFO, "LONGPOLL detected new block");
  942. restart_threads();
  943. } else {
  944. if (failures++ < 10) {
  945. sleep(30);
  946. applog(LOG_ERR,
  947. "longpoll failed, sleeping for 30s");
  948. } else {
  949. applog(LOG_ERR,
  950. "longpoll failed, ending thread");
  951. goto out;
  952. }
  953. }
  954. }
  955. out:
  956. free(hdr_path);
  957. free(lp_url);
  958. tq_freeze(mythr->q);
  959. if (curl)
  960. curl_easy_cleanup(curl);
  961. return NULL;
  962. }
  963. static void show_usage(void)
  964. {
  965. int i;
  966. printf("minerd version %s\n\n", VERSION);
  967. printf("Usage:\tminerd [options]\n\nSupported options:\n");
  968. for (i = 0; i < ARRAY_SIZE(options_help); i++) {
  969. struct option_help *h;
  970. h = &options_help[i];
  971. printf("--%s\n%s\n\n", h->name, h->helptext);
  972. }
  973. exit(1);
  974. }
  975. static void parse_arg (int key, char *arg)
  976. {
  977. int v, i;
  978. switch(key) {
  979. case 'a':
  980. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  981. if (algo_names[i] &&
  982. !strcmp(arg, algo_names[i])) {
  983. opt_algo = i;
  984. break;
  985. }
  986. }
  987. if (i == ARRAY_SIZE(algo_names))
  988. show_usage();
  989. break;
  990. case 'c': {
  991. json_error_t err;
  992. if (opt_config)
  993. json_decref(opt_config);
  994. opt_config = json_load_file(arg, &err);
  995. if (!json_is_object(opt_config)) {
  996. applog(LOG_ERR, "JSON decode of %s failed", arg);
  997. show_usage();
  998. }
  999. break;
  1000. }
  1001. case 'g':
  1002. v = atoi(arg);
  1003. if (v < 0 || v > 10)
  1004. show_usage();
  1005. opt_g_threads = v;
  1006. break;
  1007. case 'D':
  1008. opt_debug = true;
  1009. break;
  1010. case 'I':
  1011. v = atoi(arg);
  1012. if (v < 0 || v > 14) /* sanity check */
  1013. show_usage();
  1014. scan_intensity = v;
  1015. break;
  1016. case 'l':
  1017. v = atoi(arg);
  1018. if (v < 0 || v > 9999) /* sanity check */
  1019. show_usage();
  1020. opt_log_interval = v;
  1021. break;
  1022. case 'p':
  1023. free(rpc_pass);
  1024. rpc_pass = strdup(arg);
  1025. break;
  1026. case 'P':
  1027. opt_protocol = true;
  1028. break;
  1029. case 'q':
  1030. opt_quiet = true;
  1031. break;
  1032. case 'r':
  1033. v = atoi(arg);
  1034. if (v < -1 || v > 9999) /* sanity check */
  1035. show_usage();
  1036. opt_retries = v;
  1037. break;
  1038. case 'R':
  1039. v = atoi(arg);
  1040. if (v < 1 || v > 9999) /* sanity check */
  1041. show_usage();
  1042. opt_fail_pause = v;
  1043. break;
  1044. case 's':
  1045. v = atoi(arg);
  1046. if (v < 1 || v > 9999) /* sanity check */
  1047. show_usage();
  1048. opt_scantime = v;
  1049. break;
  1050. case 't':
  1051. v = atoi(arg);
  1052. if (v < 0 || v > 9999) /* sanity check */
  1053. show_usage();
  1054. opt_n_threads = v;
  1055. break;
  1056. case 'u':
  1057. free(rpc_user);
  1058. rpc_user = strdup(arg);
  1059. break;
  1060. case 'v':
  1061. v = atoi(arg);
  1062. if (v != 1 && v != 2 && v != 4)
  1063. show_usage();
  1064. opt_vectors = v;
  1065. break;
  1066. case 'w':
  1067. v = atoi(arg);
  1068. if (v < 1 || v > 9999) /* sanity check */
  1069. show_usage();
  1070. opt_worksize = v;
  1071. break;
  1072. case 1001: /* --url */
  1073. if (strncmp(arg, "http://", 7) &&
  1074. strncmp(arg, "https://", 8))
  1075. show_usage();
  1076. free(rpc_url);
  1077. rpc_url = strdup(arg);
  1078. break;
  1079. case 1002: /* --userpass */
  1080. if (!strchr(arg, ':'))
  1081. show_usage();
  1082. free(rpc_userpass);
  1083. rpc_userpass = strdup(arg);
  1084. break;
  1085. case 1003:
  1086. want_longpoll = false;
  1087. break;
  1088. case 1004:
  1089. use_syslog = true;
  1090. break;
  1091. default:
  1092. show_usage();
  1093. }
  1094. }
  1095. static void parse_config(void)
  1096. {
  1097. int i;
  1098. json_t *val;
  1099. if (!json_is_object(opt_config))
  1100. return;
  1101. for (i = 0; i < ARRAY_SIZE(options); i++) {
  1102. if (!options[i].name)
  1103. break;
  1104. if (!strcmp(options[i].name, "config"))
  1105. continue;
  1106. val = json_object_get(opt_config, options[i].name);
  1107. if (!val)
  1108. continue;
  1109. if (options[i].has_arg && json_is_string(val)) {
  1110. char *s = strdup(json_string_value(val));
  1111. if (!s)
  1112. break;
  1113. parse_arg(options[i].val, s);
  1114. free(s);
  1115. } else if (!options[i].has_arg && json_is_true(val))
  1116. parse_arg(options[i].val, "");
  1117. else
  1118. applog(LOG_ERR, "JSON option %s invalid",
  1119. options[i].name);
  1120. }
  1121. }
  1122. static void parse_cmdline(int argc, char *argv[])
  1123. {
  1124. int key;
  1125. while (1) {
  1126. key = getopt_long(argc, argv, "a:c:qDPr:s:t:h?", options, NULL);
  1127. if (key < 0)
  1128. break;
  1129. parse_arg(key, optarg);
  1130. }
  1131. parse_config();
  1132. }
  1133. int main (int argc, char *argv[])
  1134. {
  1135. struct thr_info *thr;
  1136. unsigned int i;
  1137. char name[32];
  1138. #ifdef WIN32
  1139. opt_n_threads = 1;
  1140. #else
  1141. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1142. opt_n_threads = num_processors;
  1143. #endif /* !WIN32 */
  1144. nDevs = clDevicesNum();
  1145. if (opt_ndevs) {
  1146. applog(LOG_INFO, "%i", nDevs);
  1147. return nDevs;
  1148. }
  1149. /* Invert the value to determine if we manually set it in cmdline
  1150. * or disable gpu threads */
  1151. if (nDevs)
  1152. opt_n_threads = - opt_n_threads;
  1153. rpc_url = strdup(DEF_RPC_URL);
  1154. /* parse command line */
  1155. parse_cmdline(argc, argv);
  1156. gpu_threads = nDevs * opt_g_threads;
  1157. if (opt_n_threads < 0) {
  1158. if (gpu_threads)
  1159. opt_n_threads = 0;
  1160. else
  1161. opt_n_threads = -opt_n_threads;
  1162. }
  1163. if (!rpc_userpass) {
  1164. if (!rpc_user || !rpc_pass) {
  1165. applog(LOG_ERR, "No login credentials supplied");
  1166. return 1;
  1167. }
  1168. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1169. if (!rpc_userpass)
  1170. return 1;
  1171. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1172. }
  1173. if (unlikely(pthread_mutex_init(&time_lock, NULL)))
  1174. return 1;
  1175. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1176. return 1;
  1177. if (unlikely(pthread_mutex_init(&get_lock, NULL)))
  1178. return 1;
  1179. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1180. return 1;
  1181. #ifdef HAVE_SYSLOG_H
  1182. if (use_syslog)
  1183. openlog("cpuminer", LOG_PID, LOG_USER);
  1184. #endif
  1185. work_restart = calloc(opt_n_threads + gpu_threads, sizeof(*work_restart));
  1186. if (!work_restart)
  1187. return 1;
  1188. thr_info = calloc(opt_n_threads + 2 + gpu_threads, sizeof(*thr));
  1189. if (!thr_info)
  1190. return 1;
  1191. /* init workio thread info */
  1192. work_thr_id = opt_n_threads + gpu_threads;
  1193. thr = &thr_info[work_thr_id];
  1194. thr->id = work_thr_id;
  1195. thr->q = tq_new();
  1196. if (!thr->q)
  1197. return 1;
  1198. /* start work I/O thread */
  1199. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1200. applog(LOG_ERR, "workio thread create failed");
  1201. return 1;
  1202. }
  1203. /* init longpoll thread info */
  1204. if (want_longpoll) {
  1205. longpoll_thr_id = opt_n_threads + gpu_threads + 1;
  1206. thr = &thr_info[longpoll_thr_id];
  1207. thr->id = longpoll_thr_id;
  1208. thr->q = tq_new();
  1209. if (!thr->q)
  1210. return 1;
  1211. /* start longpoll thread */
  1212. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1213. applog(LOG_ERR, "longpoll thread create failed");
  1214. return 1;
  1215. }
  1216. pthread_detach(thr->pth);
  1217. } else
  1218. longpoll_thr_id = -1;
  1219. gettimeofday(&total_tv_start, NULL);
  1220. gettimeofday(&total_tv_end, NULL);
  1221. /* start GPU mining threads */
  1222. for (i = 0; i < gpu_threads; i++) {
  1223. int gpu = i % nDevs;
  1224. thr = &thr_info[i];
  1225. thr->id = i;
  1226. if (! (i % opt_g_threads)) {
  1227. thr->cgpu = calloc(1, sizeof(struct cgpu_info));
  1228. if (unlikely(!thr->cgpu)) {
  1229. applog(LOG_ERR, "Failed to calloc cgpu_info");
  1230. return 1;
  1231. }
  1232. thr->cgpu->is_gpu = 1;
  1233. thr->cgpu->cpu_gpu = gpu;
  1234. } else
  1235. thr->cgpu = thr_info[i - (i % opt_g_threads)].cgpu;
  1236. thr->q = tq_new();
  1237. if (!thr->q)
  1238. return 1;
  1239. applog(LOG_INFO, "Init GPU thread %i", i);
  1240. clStates[i] = initCl(gpu, name, sizeof(name));
  1241. if (!clStates[i]) {
  1242. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1243. continue;
  1244. }
  1245. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1246. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1247. applog(LOG_ERR, "thread %d create failed", i);
  1248. return 1;
  1249. }
  1250. pthread_detach(thr->pth);
  1251. }
  1252. applog(LOG_INFO, "%d gpu miner threads started", i);
  1253. /* start CPU mining threads */
  1254. for (i = gpu_threads; i < gpu_threads + opt_n_threads; i++) {
  1255. thr = &thr_info[i];
  1256. thr->id = i;
  1257. if (! (i % opt_n_threads)) {
  1258. thr->cgpu = calloc(1, sizeof(struct cgpu_info));
  1259. if (unlikely(!thr->cgpu)) {
  1260. applog(LOG_ERR, "Failed to calloc cgpu_info");
  1261. return 1;
  1262. }
  1263. thr->cgpu->cpu_gpu = cpu_from_thr_id(i);
  1264. } else
  1265. thr->cgpu = thr_info[cpu_from_thr_id(i - (i % opt_n_threads))].cgpu;
  1266. thr->q = tq_new();
  1267. if (!thr->q)
  1268. return 1;
  1269. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1270. applog(LOG_ERR, "thread %d create failed", i);
  1271. return 1;
  1272. }
  1273. pthread_detach(thr->pth);
  1274. sleep(1); /* don't pound RPC server all at once */
  1275. }
  1276. applog(LOG_INFO, "%d cpu miner threads started, "
  1277. "using SHA256 '%s' algorithm.",
  1278. opt_n_threads,
  1279. algo_names[opt_algo]);
  1280. /* Restart count as it will be wrong till all threads are started */
  1281. pthread_mutex_lock(&hash_lock);
  1282. gettimeofday(&total_tv_start, NULL);
  1283. gettimeofday(&total_tv_end, NULL);
  1284. total_mhashes_done = 0;
  1285. pthread_mutex_unlock(&hash_lock);
  1286. /* main loop - simply wait for workio thread to exit */
  1287. pthread_join(thr_info[work_thr_id].pth, NULL);
  1288. curl_global_cleanup();
  1289. applog(LOG_INFO, "workio thread dead, exiting.");
  1290. return 0;
  1291. }