cpu-miner.c 38 KB

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