cpu-miner.c 35 KB

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