cpu-miner.c 38 KB

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