main.c 41 KB

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