main.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020
  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 <curses.h>
  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. #include <stdarg.h>
  22. #include <assert.h>
  23. #ifndef WIN32
  24. #include <sys/resource.h>
  25. #endif
  26. #include <ccan/opt/opt.h>
  27. #include <jansson.h>
  28. #include <curl/curl.h>
  29. #include "compat.h"
  30. #include "miner.h"
  31. #include "findnonce.h"
  32. #include "ocl.h"
  33. #define PROGRAM_NAME "cgminer"
  34. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  35. #define DEF_RPC_USERNAME "rpcuser"
  36. #define DEF_RPC_PASSWORD "rpcpass"
  37. #define DEF_RPC_USERPASS DEF_RPC_USERNAME ":" DEF_RPC_PASSWORD
  38. #ifdef __linux /* Linux specific policy and affinity management */
  39. #include <sched.h>
  40. static inline void drop_policy(void)
  41. {
  42. struct sched_param param;
  43. #ifdef SCHED_BATCH
  44. #ifdef SCHED_IDLE
  45. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  46. #endif
  47. sched_setscheduler(0, SCHED_BATCH, &param);
  48. #endif
  49. }
  50. static inline void affine_to_cpu(int id, int cpu)
  51. {
  52. cpu_set_t set;
  53. CPU_ZERO(&set);
  54. CPU_SET(cpu, &set);
  55. sched_setaffinity(0, sizeof(&set), &set);
  56. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  57. }
  58. #else
  59. static inline void drop_policy(void)
  60. {
  61. }
  62. static inline void affine_to_cpu(int id, int cpu)
  63. {
  64. }
  65. #endif
  66. enum workio_commands {
  67. WC_GET_WORK,
  68. WC_SUBMIT_WORK,
  69. WC_DIE,
  70. };
  71. struct workio_cmd {
  72. enum workio_commands cmd;
  73. struct thr_info *thr;
  74. union {
  75. struct work *work;
  76. } u;
  77. };
  78. enum sha256_algos {
  79. ALGO_C, /* plain C */
  80. ALGO_4WAY, /* parallel SSE2 */
  81. ALGO_VIA, /* VIA padlock */
  82. ALGO_CRYPTOPP, /* Crypto++ (C) */
  83. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  84. ALGO_SSE2_64, /* SSE2 for x86_64 */
  85. };
  86. static const char *algo_names[] = {
  87. [ALGO_C] = "c",
  88. #ifdef WANT_SSE2_4WAY
  89. [ALGO_4WAY] = "4way",
  90. #endif
  91. #ifdef WANT_VIA_PADLOCK
  92. [ALGO_VIA] = "via",
  93. #endif
  94. [ALGO_CRYPTOPP] = "cryptopp",
  95. #ifdef WANT_CRYPTOPP_ASM32
  96. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  97. #endif
  98. #ifdef WANT_X8664_SSE2
  99. [ALGO_SSE2_64] = "sse2_64",
  100. #endif
  101. };
  102. bool opt_debug = false;
  103. bool opt_protocol = false;
  104. bool want_longpoll = true;
  105. bool have_longpoll = false;
  106. bool use_syslog = false;
  107. static bool opt_quiet = false;
  108. static int opt_retries = -1;
  109. static int opt_fail_pause = 5;
  110. static int opt_log_interval = 5;
  111. bool opt_log_output = false;
  112. static int opt_queue = 1;
  113. int opt_vectors;
  114. int opt_worksize;
  115. int opt_scantime = 60;
  116. static const bool opt_time = true;
  117. #ifdef WANT_X8664_SSE2
  118. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  119. #else
  120. static enum sha256_algos opt_algo = ALGO_C;
  121. #endif
  122. static int nDevs;
  123. static int opt_g_threads = 2;
  124. static int opt_device;
  125. static int total_devices;
  126. static bool gpu_devices[16];
  127. static int gpu_threads;
  128. static bool forced_n_threads;
  129. static int opt_n_threads;
  130. static int mining_threads;
  131. static int num_processors;
  132. static int scan_intensity = 4;
  133. static char *rpc_url;
  134. static char *rpc_userpass;
  135. static char *rpc_user, *rpc_pass;
  136. struct thr_info *thr_info;
  137. static int work_thr_id;
  138. int longpoll_thr_id;
  139. static int stage_thr_id;
  140. struct work_restart *work_restart = NULL;
  141. static pthread_mutex_t hash_lock;
  142. static pthread_mutex_t qd_lock;
  143. static pthread_mutex_t stgd_lock;
  144. static double total_mhashes_done;
  145. static struct timeval total_tv_start, total_tv_end;
  146. static int accepted, rejected;
  147. int hw_errors;
  148. static int total_queued, total_staged, lp_staged;
  149. static bool localgen = false;
  150. static unsigned int getwork_requested;
  151. static char current_block[37];
  152. static char longpoll_block[37];
  153. static char blank[37];
  154. static void applog_and_exit(const char *fmt, ...)
  155. {
  156. va_list ap;
  157. va_start(ap, fmt);
  158. vapplog(LOG_ERR, fmt, ap);
  159. va_end(ap);
  160. exit(1);
  161. }
  162. /* FIXME: Use asprintf for better errors. */
  163. static char *set_algo(const char *arg, enum sha256_algos *algo)
  164. {
  165. enum sha256_algos i;
  166. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  167. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  168. *algo = i;
  169. return NULL;
  170. }
  171. }
  172. return "Unknown algorithm";
  173. }
  174. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  175. {
  176. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  177. }
  178. static char *set_int_range(const char *arg, int *i, int min, int max)
  179. {
  180. char *err = opt_set_intval(arg, i);
  181. if (err)
  182. return err;
  183. if (*i < min || *i > max)
  184. return "Value out of range";
  185. return NULL;
  186. }
  187. static char *set_int_0_to_9999(const char *arg, int *i)
  188. {
  189. return set_int_range(arg, i, 0, 9999);
  190. }
  191. static char *set_int_0_to_14(const char *arg, int *i)
  192. {
  193. return set_int_range(arg, i, 0, 14);
  194. }
  195. static char *force_nthreads_int(const char *arg, int *i)
  196. {
  197. forced_n_threads = true;
  198. return set_int_range(arg, i, 0, 9999);
  199. }
  200. static char *set_int_0_to_10(const char *arg, int *i)
  201. {
  202. return set_int_range(arg, i, 0, 10);
  203. }
  204. static char *set_int_1_to_10(const char *arg, int *i)
  205. {
  206. return set_int_range(arg, i, 1, 10);
  207. }
  208. static char *set_devices(const char *arg, int *i)
  209. {
  210. char *err = opt_set_intval(arg, i);
  211. if (err)
  212. return err;
  213. if (*i < 0 || *i > 15)
  214. return "Invalid GPU device number";
  215. total_devices++;
  216. gpu_devices[*i] = true;
  217. return NULL;
  218. }
  219. static char *set_url(const char *arg, char **p)
  220. {
  221. opt_set_charp(arg, p);
  222. if (strncmp(arg, "http://", 7) &&
  223. strncmp(arg, "https://", 8))
  224. return "URL must start with http:// or https://";
  225. return NULL;
  226. }
  227. static char *set_vector(const char *arg, int *i)
  228. {
  229. char *err = opt_set_intval(arg, i);
  230. if (err)
  231. return err;
  232. if (*i != 1 && *i != 2 && *i != 4)
  233. return "Valid vectors are 1, 2 or 4";
  234. return NULL;
  235. }
  236. static char *enable_debug(bool *flag)
  237. {
  238. *flag = true;
  239. /* Turn out verbose output, too. */
  240. opt_log_output = true;
  241. return NULL;
  242. }
  243. /* These options are available from config file or commandline */
  244. static struct opt_table opt_config_table[] = {
  245. OPT_WITH_ARG("--algo|-a",
  246. set_algo, show_algo, &opt_algo,
  247. "Specify sha256 implementation:\n"
  248. "\tc\t\tLinux kernel sha256, implemented in C"
  249. #ifdef WANT_SSE2_4WAY
  250. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  251. #endif
  252. #ifdef WANT_VIA_PADLOCK
  253. "\n\tvia\t\tVIA padlock implementation"
  254. #endif
  255. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  256. #ifdef WANT_CRYPTOPP_ASM32
  257. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  258. #endif
  259. #ifdef WANT_X8664_SSE2
  260. "\n\tsse2_64\t\tSSE2 implementation for x86_64 machines"
  261. #endif
  262. ),
  263. OPT_WITH_ARG("--cpu-threads|-t",
  264. force_nthreads_int, opt_show_intval, &opt_n_threads,
  265. "Number of miner CPU threads"),
  266. OPT_WITHOUT_ARG("--debug|-D",
  267. enable_debug, &opt_debug,
  268. "Enable debug output"),
  269. #ifdef HAVE_OPENCL
  270. OPT_WITH_ARG("--device|-d",
  271. set_devices, NULL, &opt_device,
  272. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  273. OPT_WITH_ARG("--gpu-threads|-g",
  274. set_int_0_to_10, opt_show_intval, &opt_g_threads,
  275. "Number of threads per GPU (0 - 10)"),
  276. OPT_WITH_ARG("--intensity|-I",
  277. set_int_0_to_14, opt_show_intval, &scan_intensity,
  278. "Intensity of GPU scanning (0 - 14)"),
  279. #endif
  280. OPT_WITH_ARG("--log|-l",
  281. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  282. "Interval in seconds between log output"),
  283. OPT_WITHOUT_ARG("--no-longpoll",
  284. opt_set_invbool, &want_longpoll,
  285. "Disable X-Long-Polling support"),
  286. OPT_WITH_ARG("--pass|-p",
  287. opt_set_charp, NULL, &rpc_pass,
  288. "Password for bitcoin JSON-RPC server"),
  289. OPT_WITHOUT_ARG("--protocol-dump|-P",
  290. opt_set_bool, &opt_protocol,
  291. "Verbose dump of protocol-level activities"),
  292. OPT_WITH_ARG("--queue|-Q",
  293. set_int_1_to_10, opt_show_intval, &opt_queue,
  294. "Number of extra work items to queue (1 - 10)"),
  295. OPT_WITHOUT_ARG("--quiet|-q",
  296. opt_set_bool, &opt_quiet,
  297. "Disable per-thread hashmeter output"),
  298. OPT_WITH_ARG("--retries|-r",
  299. opt_set_intval, opt_show_intval, &opt_retries,
  300. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  301. OPT_WITH_ARG("--retry-pause|-R",
  302. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  303. "Number of seconds to pause, between retries"),
  304. OPT_WITH_ARG("--scan-time|-s",
  305. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  306. "Upper bound on time spent scanning current work, in seconds"),
  307. #ifdef HAVE_SYSLOG_H
  308. OPT_WITHOUT_ARG("--syslog",
  309. opt_set_bool, &use_syslog,
  310. "Use system log for output messages (default: standard error)"),
  311. #endif
  312. OPT_WITH_ARG("--url|-o",
  313. set_url, opt_show_charp, &rpc_url,
  314. "URL for bitcoin JSON-RPC server"),
  315. OPT_WITH_ARG("--user|-u",
  316. opt_set_charp, NULL, &rpc_user,
  317. "Username for bitcoin JSON-RPC server"),
  318. #ifdef HAVE_OPENCL
  319. OPT_WITH_ARG("--vectors|-v",
  320. set_vector, NULL, &opt_vectors,
  321. "Override detected optimal vector width (1, 2 or 4)"),
  322. #endif
  323. OPT_WITHOUT_ARG("--verbose",
  324. opt_set_bool, &opt_log_output,
  325. "Log verbose output to stderr as well as status output"),
  326. #ifdef HAVE_OPENCL
  327. OPT_WITH_ARG("--worksize|-w",
  328. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  329. "Override detected optimal worksize"),
  330. #endif
  331. OPT_WITH_ARG("--userpass|-O",
  332. opt_set_charp, NULL, &rpc_userpass,
  333. "Username:Password pair for bitcoin JSON-RPC server"),
  334. OPT_ENDTABLE
  335. };
  336. static char *parse_config(json_t *config)
  337. {
  338. static char err_buf[200];
  339. json_t *val;
  340. struct opt_table *opt;
  341. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  342. char *p, *name;
  343. /* We don't handle subtables. */
  344. assert(!(opt->type & OPT_SUBTABLE));
  345. /* Pull apart the option name(s). */
  346. name = strdup(opt->names);
  347. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  348. char *err;
  349. /* Ignore short options. */
  350. if (p[1] != '-')
  351. continue;
  352. val = json_object_get(config, p+2);
  353. if (!val)
  354. continue;
  355. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  356. err = opt->cb_arg(json_string_value(val),
  357. opt->u.arg);
  358. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  359. err = opt->cb(opt->u.arg);
  360. } else {
  361. err = "Invalid value";
  362. }
  363. if (err) {
  364. sprintf(err_buf, "Parsing JSON option %s: %s",
  365. p, err);
  366. return err_buf;
  367. }
  368. }
  369. free(name);
  370. }
  371. return NULL;
  372. }
  373. static char *load_config(const char *arg, void *unused)
  374. {
  375. json_error_t err;
  376. json_t *config;
  377. config = json_load_file(arg, &err);
  378. if (!json_is_object(config))
  379. return "JSON decode of file failed";
  380. /* Parse the config now, so we can override it. That can keep pointers
  381. * so don't free config object. */
  382. return parse_config(config);
  383. }
  384. static char *print_ndevs_and_exit(int *ndevs)
  385. {
  386. printf("%i", *ndevs);
  387. exit(*ndevs);
  388. }
  389. /* These options are available from commandline only */
  390. static struct opt_table opt_cmdline_table[] = {
  391. OPT_WITH_ARG("--config|-c",
  392. load_config, NULL, NULL,
  393. "Load a JSON-format configuration file\n"
  394. "See example-cfg.json for an example configuration."),
  395. OPT_WITHOUT_ARG("--help|-h",
  396. opt_usage_and_exit,
  397. #ifdef HAVE_OPENCL
  398. "\nBuilt with CPU and GPU mining support.\n\n",
  399. #else
  400. "\nBuilt with CPU mining support only.\n\n",
  401. #endif
  402. "Print this message"),
  403. OPT_WITHOUT_ARG("--ndevs|-n",
  404. print_ndevs_and_exit, &nDevs,
  405. "Display number of detected GPUs and exit"),
  406. OPT_ENDTABLE
  407. };
  408. static bool jobj_binary(const json_t *obj, const char *key,
  409. void *buf, size_t buflen)
  410. {
  411. const char *hexstr;
  412. json_t *tmp;
  413. tmp = json_object_get(obj, key);
  414. if (unlikely(!tmp)) {
  415. applog(LOG_ERR, "JSON key '%s' not found", key);
  416. return false;
  417. }
  418. hexstr = json_string_value(tmp);
  419. if (unlikely(!hexstr)) {
  420. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  421. return false;
  422. }
  423. if (!hex2bin(buf, hexstr, buflen))
  424. return false;
  425. return true;
  426. }
  427. static bool work_decode(const json_t *val, struct work *work)
  428. {
  429. if (unlikely(!jobj_binary(val, "midstate",
  430. work->midstate, sizeof(work->midstate)))) {
  431. applog(LOG_ERR, "JSON inval midstate");
  432. goto err_out;
  433. }
  434. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  435. applog(LOG_ERR, "JSON inval data");
  436. goto err_out;
  437. }
  438. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  439. applog(LOG_ERR, "JSON inval hash1");
  440. goto err_out;
  441. }
  442. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  443. applog(LOG_ERR, "JSON inval target");
  444. goto err_out;
  445. }
  446. memset(work->hash, 0, sizeof(work->hash));
  447. return true;
  448. err_out:
  449. return false;
  450. }
  451. static inline int gpu_from_thr_id(int thr_id)
  452. {
  453. return thr_id % nDevs;
  454. }
  455. static inline int cpu_from_thr_id(int thr_id)
  456. {
  457. return (thr_id - gpu_threads) % num_processors;
  458. }
  459. static WINDOW * mainwin;
  460. static double total_secs = 0.1;
  461. static char statusline[256];
  462. static int cpucursor, gpucursor, logstart, logcursor;
  463. static bool curses_active = false;
  464. static struct cgpu_info *gpus, *cpus;
  465. static inline void print_status(int thr_id)
  466. {
  467. int x;
  468. if (unlikely(!curses_active))
  469. return;
  470. move(2,0);
  471. printw("Totals: %s", statusline);
  472. clrtoeol();
  473. if (thr_id >= 0 && thr_id < gpu_threads) {
  474. int gpu = gpu_from_thr_id(thr_id);
  475. struct cgpu_info *cgpu = &gpus[gpu];
  476. move(gpucursor + gpu, 0);
  477. printw("GPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m] ",
  478. gpu, cgpu->total_mhashes / total_secs,
  479. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  480. cgpu->efficiency, cgpu->utility);
  481. clrtoeol();
  482. } else if (thr_id >= gpu_threads) {
  483. int cpu = cpu_from_thr_id(thr_id);
  484. struct cgpu_info *cgpu = &cpus[cpu];
  485. move(cpucursor + cpu, 0);
  486. printw("CPU %d: [%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  487. cpu, cgpu->total_mhashes / total_secs,
  488. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  489. cgpu->efficiency, cgpu->utility);
  490. clrtoeol();
  491. }
  492. move(logcursor, 0);
  493. refresh();
  494. }
  495. static void refresh_display(void)
  496. {
  497. int i, x;
  498. if (unlikely(!curses_active))
  499. return;
  500. move(0,0);
  501. attron(A_BOLD);
  502. printw(PROGRAM_NAME " version " VERSION);
  503. attroff(A_BOLD);
  504. clrtoeol();
  505. move(1, 0);
  506. clrtoeol();
  507. hline('-', 80);
  508. move(3, 0);
  509. clrtoeol();
  510. hline('-', 80);
  511. move(logstart, 0);
  512. clrtoeol();
  513. hline('-', 80);
  514. for (i = 0; i < mining_threads; i++)
  515. print_status(i);
  516. move(logcursor, 0);
  517. redrawwin(mainwin);
  518. }
  519. void log_curses(const char *f, va_list ap)
  520. {
  521. int x;
  522. if (unlikely(!curses_active))
  523. return;
  524. /* Scroll log output downwards */
  525. getmaxyx(mainwin, logcursor, x);
  526. move(--logcursor, 0);
  527. vw_printw(mainwin, f, ap);
  528. clrtoeol();
  529. refresh_display();
  530. }
  531. static bool submit_fail = false;
  532. static bool submit_upstream_work(const struct work *work)
  533. {
  534. char *hexstr = NULL;
  535. json_t *val, *res;
  536. char s[345];
  537. bool rc = false;
  538. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  539. CURL *curl = curl_easy_init();
  540. if (unlikely(!curl)) {
  541. applog(LOG_ERR, "CURL initialisation failed");
  542. return rc;
  543. }
  544. /* build hex string */
  545. hexstr = bin2hex(work->data, sizeof(work->data));
  546. if (unlikely(!hexstr)) {
  547. applog(LOG_ERR, "submit_upstream_work OOM");
  548. goto out_nofree;
  549. }
  550. /* build JSON-RPC request */
  551. sprintf(s,
  552. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  553. hexstr);
  554. if (opt_debug)
  555. applog(LOG_DEBUG, "DBG: sending RPC call: %s", s);
  556. /* issue JSON-RPC request */
  557. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false);
  558. if (unlikely(!val)) {
  559. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  560. if (!submit_fail) {
  561. submit_fail = true;
  562. applog(LOG_WARNING, "Upstream communication failure, caching submissions");
  563. }
  564. goto out;
  565. } else if (submit_fail) {
  566. submit_fail = false;
  567. applog(LOG_WARNING, "Upstream communication resumed, submitting work");
  568. }
  569. res = json_object_get(val, "result");
  570. /* Theoretically threads could race when modifying accepted and
  571. * rejected values but the chance of two submits completing at the
  572. * same time is zero so there is no point adding extra locking */
  573. if (json_is_true(res)) {
  574. cgpu->accepted++;
  575. accepted++;
  576. if (opt_debug)
  577. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  578. if (!opt_quiet)
  579. applog(LOG_WARNING, "Share accepted from %sPU %d",
  580. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu);
  581. } else {
  582. cgpu->rejected++;
  583. rejected++;
  584. if (opt_debug)
  585. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  586. if (!opt_quiet)
  587. applog(LOG_WARNING, "Share rejected from %sPU %d",
  588. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu);
  589. }
  590. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  591. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  592. if (!opt_quiet)
  593. print_status(work->thr_id);
  594. applog(LOG_INFO, "%sPU %d Requested:%d Accepted:%d Rejected:%d HW errors:%d Efficiency:%.0f%% Utility:%.2f/m",
  595. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  596. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  597. json_decref(val);
  598. rc = true;
  599. out:
  600. free(hexstr);
  601. out_nofree:
  602. curl_easy_cleanup(curl);
  603. return rc;
  604. }
  605. static const char *rpc_req =
  606. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  607. static bool get_upstream_work(struct work *work)
  608. {
  609. json_t *val;
  610. bool rc = false;
  611. CURL *curl = curl_easy_init();
  612. if (unlikely(!curl)) {
  613. applog(LOG_ERR, "CURL initialisation failed");
  614. return rc;
  615. }
  616. val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
  617. want_longpoll, false);
  618. if (unlikely(!val)) {
  619. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  620. goto out;
  621. }
  622. rc = work_decode(json_object_get(val, "result"), work);
  623. json_decref(val);
  624. out:
  625. curl_easy_cleanup(curl);
  626. return rc;
  627. }
  628. static void workio_cmd_free(struct workio_cmd *wc)
  629. {
  630. if (!wc)
  631. return;
  632. switch (wc->cmd) {
  633. case WC_SUBMIT_WORK:
  634. free(wc->u.work);
  635. break;
  636. default: /* do nothing */
  637. break;
  638. }
  639. memset(wc, 0, sizeof(*wc)); /* poison */
  640. free(wc);
  641. }
  642. static void kill_work(void)
  643. {
  644. struct workio_cmd *wc;
  645. applog(LOG_INFO, "Received kill message");
  646. wc = calloc(1, sizeof(*wc));
  647. if (unlikely(!wc)) {
  648. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  649. /* We're just trying to die anyway, so forget graceful */
  650. exit (1);
  651. }
  652. wc->cmd = WC_DIE;
  653. wc->thr = 0;
  654. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  655. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  656. exit (1);
  657. }
  658. }
  659. static void *get_work_thread(void *userdata)
  660. {
  661. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  662. struct work *ret_work;
  663. int failures = 0;
  664. pthread_detach(pthread_self());
  665. ret_work = calloc(1, sizeof(*ret_work));
  666. if (unlikely(!ret_work)) {
  667. applog(LOG_ERR, "Failed to calloc ret_work in workio_get_work");
  668. kill_work();
  669. goto out;
  670. }
  671. /* obtain new work from bitcoin via JSON-RPC */
  672. while (!get_upstream_work(ret_work)) {
  673. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  674. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  675. free(ret_work);
  676. kill_work();
  677. goto out;
  678. }
  679. /* pause, then restart work-request loop */
  680. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  681. opt_fail_pause);
  682. sleep(opt_fail_pause);
  683. }
  684. /* send work to requesting thread */
  685. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  686. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  687. kill_work();
  688. free(ret_work);
  689. }
  690. out:
  691. workio_cmd_free(wc);
  692. return NULL;
  693. }
  694. static bool workio_get_work(struct workio_cmd *wc)
  695. {
  696. pthread_t get_thread;
  697. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  698. applog(LOG_ERR, "Failed to create get_work_thread");
  699. return false;
  700. }
  701. return true;
  702. }
  703. static void *submit_work_thread(void *userdata)
  704. {
  705. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  706. int failures = 0;
  707. char *hexstr;
  708. pthread_detach(pthread_self());
  709. hexstr = bin2hex(wc->u.work->data, 36);
  710. if (unlikely(!hexstr)) {
  711. applog(LOG_ERR, "submit_work_thread OOM");
  712. goto out;
  713. }
  714. if (unlikely(strncmp(hexstr, current_block, 36))) {
  715. applog(LOG_WARNING, "Stale work detected, discarding");
  716. goto out_free;
  717. }
  718. /* submit solution to bitcoin via JSON-RPC */
  719. while (!submit_upstream_work(wc->u.work)) {
  720. if (unlikely(strncmp(hexstr, current_block, 36))) {
  721. applog(LOG_WARNING, "Stale work detected, discarding");
  722. goto out_free;
  723. }
  724. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  725. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  726. kill_work();
  727. goto out_free;
  728. }
  729. /* pause, then restart work-request loop */
  730. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  731. opt_fail_pause);
  732. sleep(opt_fail_pause);
  733. }
  734. out_free:
  735. free(hexstr);
  736. out:
  737. workio_cmd_free(wc);
  738. return NULL;
  739. }
  740. static bool workio_submit_work(struct workio_cmd *wc)
  741. {
  742. pthread_t submit_thread;
  743. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  744. applog(LOG_ERR, "Failed to create submit_work_thread");
  745. return false;
  746. }
  747. return true;
  748. }
  749. static void inc_staged(int inc, bool lp)
  750. {
  751. pthread_mutex_lock(&stgd_lock);
  752. if (lp) {
  753. lp_staged += inc;
  754. total_staged += inc;
  755. } else if (lp_staged)
  756. lp_staged--;
  757. else
  758. total_staged += inc;
  759. pthread_mutex_unlock(&stgd_lock);
  760. }
  761. static void dec_staged(int inc)
  762. {
  763. pthread_mutex_lock(&stgd_lock);
  764. if (lp_staged)
  765. lp_staged -= inc;
  766. total_staged -= inc;
  767. pthread_mutex_unlock(&stgd_lock);
  768. }
  769. static int requests_staged(void)
  770. {
  771. int ret;
  772. pthread_mutex_lock(&stgd_lock);
  773. ret = total_staged;
  774. pthread_mutex_unlock(&stgd_lock);
  775. return ret;
  776. }
  777. static void *stage_thread(void *userdata)
  778. {
  779. struct thr_info *mythr = userdata;
  780. bool ok = true;
  781. unsigned int i;
  782. for (i = 0; i < 36; i++) {
  783. strcat(current_block, "0");
  784. strcat(blank, "0");
  785. }
  786. while (ok) {
  787. struct work *work = NULL;
  788. char *hexstr;
  789. work = tq_pop(mythr->q, NULL);
  790. if (unlikely(!work)) {
  791. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  792. ok = false;
  793. break;
  794. }
  795. hexstr = bin2hex(work->data, 36);
  796. if (unlikely(!hexstr)) {
  797. applog(LOG_ERR, "stage_thread OOM");
  798. break;
  799. }
  800. /* current_block is blanked out on successful longpoll */
  801. if (likely(strncmp(current_block, blank, 36))) {
  802. if (unlikely(strncmp(hexstr, current_block, 36))) {
  803. if (want_longpoll)
  804. applog(LOG_WARNING, "New block detected, possible missed longpoll, flushing work queue");
  805. else
  806. applog(LOG_WARNING, "New block detected, flushing work queue");
  807. /* As we can't flush the work from here, signal
  808. * the wakeup thread to restart all the
  809. * threads */
  810. work_restart[stage_thr_id].restart = 1;
  811. }
  812. } else
  813. memcpy(longpoll_block, hexstr, 36);
  814. memcpy(current_block, hexstr, 36);
  815. free(hexstr);
  816. if (unlikely(!tq_push(thr_info[0].q, work))) {
  817. applog(LOG_ERR, "Failed to tq_push work in stage_thread");
  818. ok = false;
  819. break;
  820. }
  821. inc_staged(1, false);
  822. }
  823. tq_freeze(mythr->q);
  824. return NULL;
  825. }
  826. static void *workio_thread(void *userdata)
  827. {
  828. struct thr_info *mythr = userdata;
  829. bool ok = true;
  830. while (ok) {
  831. struct workio_cmd *wc;
  832. /* wait for workio_cmd sent to us, on our queue */
  833. wc = tq_pop(mythr->q, NULL);
  834. if (unlikely(!wc)) {
  835. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  836. ok = false;
  837. break;
  838. }
  839. /* process workio_cmd */
  840. switch (wc->cmd) {
  841. case WC_GET_WORK:
  842. ok = workio_get_work(wc);
  843. break;
  844. case WC_SUBMIT_WORK:
  845. ok = workio_submit_work(wc);
  846. break;
  847. case WC_DIE:
  848. default:
  849. ok = false;
  850. break;
  851. }
  852. }
  853. tq_freeze(mythr->q);
  854. return NULL;
  855. }
  856. static void hashmeter(int thr_id, struct timeval *diff,
  857. unsigned long hashes_done)
  858. {
  859. struct timeval temp_tv_end, total_diff;
  860. double khashes, secs;
  861. double local_secs;
  862. double utility, efficiency = 0.0;
  863. static double local_mhashes_done = 0;
  864. static double rolling_local = 0;
  865. double local_mhashes = (double)hashes_done / 1000000.0;
  866. /* Don't bother calculating anything if we're not displaying it */
  867. if (opt_quiet || !opt_log_interval)
  868. return;
  869. khashes = hashes_done / 1000.0;
  870. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  871. if (thr_id >= 0 && secs) {
  872. /* So we can call hashmeter from a non worker thread */
  873. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  874. if (opt_debug)
  875. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  876. thr_id, hashes_done, hashes_done / secs);
  877. cgpu->local_mhashes += local_mhashes;
  878. cgpu->total_mhashes += local_mhashes;
  879. }
  880. /* Totals are updated by all threads so can race without locking */
  881. pthread_mutex_lock(&hash_lock);
  882. gettimeofday(&temp_tv_end, NULL);
  883. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  884. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  885. total_mhashes_done += local_mhashes;
  886. local_mhashes_done += local_mhashes;
  887. if (total_diff.tv_sec < opt_log_interval)
  888. /* Only update the total every opt_log_interval seconds */
  889. goto out_unlock;
  890. gettimeofday(&total_tv_end, NULL);
  891. /* Use a rolling average by faking an exponential decay over 5 * log */
  892. rolling_local = ((rolling_local * 0.9) + local_mhashes_done) / 1.9;
  893. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  894. total_secs = (double)total_diff.tv_sec +
  895. ((double)total_diff.tv_usec / 1000000.0);
  896. utility = accepted / ( total_secs ? total_secs : 1 ) * 60;
  897. efficiency = getwork_requested ? accepted * 100.0 / getwork_requested : 0.0;
  898. sprintf(statusline, "[(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m] ",
  899. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  900. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  901. print_status(thr_id);
  902. applog(LOG_INFO, "[Rate (%ds):%.1f (avg):%.2f Mhash/s] [Requested:%d Accepted:%d Rejected:%d HW errors:%d Efficiency:%.0f%% Utility:%.2f/m]",
  903. opt_log_interval, rolling_local / local_secs, total_mhashes_done / total_secs,
  904. getwork_requested, accepted, rejected, hw_errors, efficiency, utility);
  905. local_mhashes_done = 0;
  906. out_unlock:
  907. pthread_mutex_unlock(&hash_lock);
  908. }
  909. /* This is overkill, but at least we'll know accurately how much work is
  910. * queued to prevent ever being left without work */
  911. static void inc_queued(void)
  912. {
  913. pthread_mutex_lock(&qd_lock);
  914. total_queued++;
  915. pthread_mutex_unlock(&qd_lock);
  916. }
  917. static void dec_queued(void)
  918. {
  919. pthread_mutex_lock(&qd_lock);
  920. total_queued--;
  921. pthread_mutex_unlock(&qd_lock);
  922. dec_staged(1);
  923. }
  924. static int requests_queued(void)
  925. {
  926. int ret;
  927. pthread_mutex_lock(&qd_lock);
  928. ret = total_queued;
  929. pthread_mutex_unlock(&qd_lock);
  930. return ret;
  931. }
  932. /* All work is queued flagged as being for thread 0 and then the mining thread
  933. * flags it as its own */
  934. static bool queue_request(void)
  935. {
  936. struct thr_info *thr = &thr_info[0];
  937. struct workio_cmd *wc;
  938. /* fill out work request message */
  939. wc = calloc(1, sizeof(*wc));
  940. if (unlikely(!wc)) {
  941. applog(LOG_ERR, "Failed to tq_pop in queue_request");
  942. return false;
  943. }
  944. wc->cmd = WC_GET_WORK;
  945. wc->thr = thr;
  946. /* send work request to workio thread */
  947. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  948. applog(LOG_ERR, "Failed to tq_push in queue_request");
  949. workio_cmd_free(wc);
  950. return false;
  951. }
  952. inc_queued();
  953. return true;
  954. }
  955. static bool discard_request(void)
  956. {
  957. struct thr_info *thr = &thr_info[0];
  958. struct work *work_heap;
  959. /* Just in case we fell in a hole and missed a queue filling */
  960. if (unlikely(!requests_queued())) {
  961. applog(LOG_WARNING, "Tried to discard_request with nil queued");
  962. return true;
  963. }
  964. work_heap = tq_pop(thr->q, NULL);
  965. if (unlikely(!work_heap)) {
  966. applog(LOG_ERR, "Failed to tq_pop in discard_request");
  967. return false;
  968. }
  969. free(work_heap);
  970. dec_queued();
  971. return true;
  972. }
  973. static void flush_requests(bool longpoll)
  974. {
  975. int i, extra;
  976. extra = requests_queued();
  977. /* When flushing from longpoll, we don't know the new work yet. When
  978. * not flushing from longpoll, the first work item is valid so do not
  979. * discard it */
  980. if (longpoll)
  981. memcpy(current_block, blank, 36);
  982. else
  983. extra--;
  984. /* Temporarily increase the staged count so that get_work thinks there
  985. * is work available instead of making threads reuse existing work */
  986. if (extra >= mining_threads)
  987. inc_staged(mining_threads, true);
  988. else
  989. inc_staged(extra, true);
  990. for (i = 0; i < extra; i++) {
  991. /* Queue a whole batch of new requests */
  992. if (unlikely(!queue_request())) {
  993. applog(LOG_ERR, "Failed to queue requests in flush_requests");
  994. kill_work();
  995. break;
  996. }
  997. /* Pop off the old requests. Cancelling the requests would be better
  998. * but is tricky */
  999. if (unlikely(!discard_request())) {
  1000. applog(LOG_ERR, "Failed to discard requests in flush_requests");
  1001. kill_work();
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. static bool get_work(struct work *work, bool queued)
  1007. {
  1008. struct thr_info *thr = &thr_info[0];
  1009. struct work *work_heap;
  1010. bool ret = false;
  1011. int failures = 0;
  1012. getwork_requested++;
  1013. retry:
  1014. if (unlikely(!queued && !queue_request())) {
  1015. applog(LOG_WARNING, "Failed to queue_request in get_work");
  1016. goto out;
  1017. }
  1018. if (!requests_staged()) {
  1019. uint32_t *work_ntime;
  1020. uint32_t ntime;
  1021. /* Only print this message once each time we shift to localgen */
  1022. if (!localgen)
  1023. applog(LOG_WARNING, "Server not providing work fast enough, generating work locally");
  1024. localgen = true;
  1025. work_ntime = (uint32_t *)(work->data + 68);
  1026. ntime = be32toh(*work_ntime);
  1027. ntime++;
  1028. *work_ntime = htobe32(ntime);
  1029. ret = true;
  1030. goto out;
  1031. } else if (localgen) {
  1032. localgen = false;
  1033. applog(LOG_WARNING, "Resumed retrieving work from server");
  1034. }
  1035. /* wait for 1st response, or get cached response */
  1036. work_heap = tq_pop(thr->q, NULL);
  1037. if (unlikely(!work_heap)) {
  1038. applog(LOG_WARNING, "Failed to tq_pop in get_work");
  1039. goto out;
  1040. }
  1041. dec_queued();
  1042. memcpy(work, work_heap, sizeof(*work));
  1043. ret = true;
  1044. free(work_heap);
  1045. out:
  1046. if (unlikely(ret == false)) {
  1047. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  1048. applog(LOG_ERR, "Failed %d times to get_work");
  1049. return ret;
  1050. }
  1051. applog(LOG_DEBUG, "Retrying after %d seconds", opt_fail_pause);
  1052. sleep(opt_fail_pause);
  1053. goto retry;
  1054. }
  1055. return ret;
  1056. }
  1057. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  1058. {
  1059. struct workio_cmd *wc;
  1060. /* fill out work request message */
  1061. wc = calloc(1, sizeof(*wc));
  1062. if (unlikely(!wc)) {
  1063. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  1064. return false;
  1065. }
  1066. wc->u.work = malloc(sizeof(*work_in));
  1067. if (unlikely(!wc->u.work)) {
  1068. applog(LOG_ERR, "Failed to calloc work in submit_work_sync");
  1069. goto err_out;
  1070. }
  1071. wc->cmd = WC_SUBMIT_WORK;
  1072. wc->thr = thr;
  1073. memcpy(wc->u.work, work_in, sizeof(*work_in));
  1074. /* send solution to workio thread */
  1075. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1076. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  1077. goto err_out;
  1078. }
  1079. return true;
  1080. err_out:
  1081. workio_cmd_free(wc);
  1082. return false;
  1083. }
  1084. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  1085. {
  1086. work->data[64+12+0] = (nonce>>0) & 0xff;
  1087. work->data[64+12+1] = (nonce>>8) & 0xff;
  1088. work->data[64+12+2] = (nonce>>16) & 0xff;
  1089. work->data[64+12+3] = (nonce>>24) & 0xff;
  1090. return submit_work_sync(thr, work);
  1091. }
  1092. static void *miner_thread(void *userdata)
  1093. {
  1094. struct thr_info *mythr = userdata;
  1095. const int thr_id = mythr->id;
  1096. uint32_t max_nonce = 0xffffff;
  1097. bool needs_work = true;
  1098. /* Try to cycle approximately 5 times before each log update */
  1099. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1100. /* Request the next work item at 2/3 of the scantime */
  1101. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1102. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1103. bool requested = true;
  1104. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1105. * and if that fails, then SCHED_BATCH. No need for this to be an
  1106. * error if it fails */
  1107. setpriority(PRIO_PROCESS, 0, 19);
  1108. drop_policy();
  1109. /* Cpu affinity only makes sense if the number of threads is a multiple
  1110. * of the number of CPUs */
  1111. if (!(opt_n_threads % num_processors))
  1112. affine_to_cpu(thr_id - gpu_threads, cpu_from_thr_id(thr_id));
  1113. while (1) {
  1114. struct work work __attribute__((aligned(128)));
  1115. unsigned long hashes_done;
  1116. struct timeval tv_workstart, tv_start, tv_end, diff;
  1117. uint64_t max64;
  1118. bool rc;
  1119. if (needs_work) {
  1120. gettimeofday(&tv_workstart, NULL);
  1121. /* obtain new work from internal workio thread */
  1122. if (unlikely(!get_work(&work, requested))) {
  1123. applog(LOG_ERR, "work retrieval failed, exiting "
  1124. "mining thread %d", thr_id);
  1125. goto out;
  1126. }
  1127. mythr->cgpu->getworks++;
  1128. work.thr_id = thr_id;
  1129. needs_work = requested = false;
  1130. work.blk.nonce = 0;
  1131. }
  1132. hashes_done = 0;
  1133. gettimeofday(&tv_start, NULL);
  1134. /* scan nonces for a proof-of-work hash */
  1135. switch (opt_algo) {
  1136. case ALGO_C:
  1137. rc = scanhash_c(thr_id, work.midstate, work.data + 64,
  1138. work.hash1, work.hash, work.target,
  1139. max_nonce, &hashes_done,
  1140. work.blk.nonce);
  1141. break;
  1142. #ifdef WANT_X8664_SSE2
  1143. case ALGO_SSE2_64: {
  1144. unsigned int rc5 =
  1145. scanhash_sse2_64(thr_id, work.midstate, work.data + 64,
  1146. work.hash1, work.hash,
  1147. work.target,
  1148. max_nonce, &hashes_done,
  1149. work.blk.nonce);
  1150. rc = (rc5 == -1) ? false : true;
  1151. }
  1152. break;
  1153. #endif
  1154. #ifdef WANT_SSE2_4WAY
  1155. case ALGO_4WAY: {
  1156. unsigned int rc4 =
  1157. ScanHash_4WaySSE2(thr_id, work.midstate, work.data + 64,
  1158. work.hash1, work.hash,
  1159. work.target,
  1160. max_nonce, &hashes_done,
  1161. work.blk.nonce);
  1162. rc = (rc4 == -1) ? false : true;
  1163. }
  1164. break;
  1165. #endif
  1166. #ifdef WANT_VIA_PADLOCK
  1167. case ALGO_VIA:
  1168. rc = scanhash_via(thr_id, work.data, work.target,
  1169. max_nonce, &hashes_done,
  1170. work.blk.nonce);
  1171. break;
  1172. #endif
  1173. case ALGO_CRYPTOPP:
  1174. rc = scanhash_cryptopp(thr_id, work.midstate, work.data + 64,
  1175. work.hash1, work.hash, work.target,
  1176. max_nonce, &hashes_done,
  1177. work.blk.nonce);
  1178. break;
  1179. #ifdef WANT_CRYPTOPP_ASM32
  1180. case ALGO_CRYPTOPP_ASM32:
  1181. rc = scanhash_asm32(thr_id, work.midstate, work.data + 64,
  1182. work.hash1, work.hash, work.target,
  1183. max_nonce, &hashes_done,
  1184. work.blk.nonce);
  1185. break;
  1186. #endif
  1187. default:
  1188. /* should never happen */
  1189. goto out;
  1190. }
  1191. /* record scanhash elapsed time */
  1192. gettimeofday(&tv_end, NULL);
  1193. timeval_subtract(&diff, &tv_end, &tv_start);
  1194. hashes_done -= work.blk.nonce;
  1195. hashmeter(thr_id, &diff, hashes_done);
  1196. work.blk.nonce += hashes_done;
  1197. /* adjust max_nonce to meet target cycle time */
  1198. if (diff.tv_usec > 500000)
  1199. diff.tv_sec++;
  1200. if (diff.tv_sec && diff.tv_sec != cycle) {
  1201. max64 = work.blk.nonce +
  1202. ((uint64_t)hashes_done * cycle) / diff.tv_sec;
  1203. } else
  1204. max64 = work.blk.nonce + hashes_done;
  1205. if (max64 > 0xfffffffaULL)
  1206. max64 = 0xfffffffaULL;
  1207. max_nonce = max64;
  1208. /* if nonce found, submit work */
  1209. if (unlikely(rc)) {
  1210. if (opt_debug)
  1211. applog(LOG_DEBUG, "CPU %d found something?", cpu_from_thr_id(thr_id));
  1212. if (unlikely(!submit_work_sync(mythr, &work))) {
  1213. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  1214. break;
  1215. }
  1216. work.blk.nonce += 4;
  1217. }
  1218. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1219. if (!requested && (diff.tv_sec > request_interval || work.blk.nonce > request_nonce)) {
  1220. if (unlikely(!queue_request())) {
  1221. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  1222. goto out;
  1223. }
  1224. requested = true;
  1225. }
  1226. if (diff.tv_sec > opt_scantime || work_restart[thr_id].restart ||
  1227. work.blk.nonce >= MAXTHREADS - hashes_done)
  1228. needs_work = true;
  1229. }
  1230. out:
  1231. tq_freeze(mythr->q);
  1232. return NULL;
  1233. }
  1234. enum {
  1235. STAT_SLEEP_INTERVAL = 1,
  1236. STAT_CTR_INTERVAL = 10000000,
  1237. FAILURE_INTERVAL = 30,
  1238. };
  1239. #ifdef HAVE_OPENCL
  1240. static _clState *clStates[16];
  1241. static inline cl_int queue_kernel_parameters(_clState *clState, dev_blk_ctx *blk)
  1242. {
  1243. cl_kernel *kernel = &clState->kernel;
  1244. cl_int status = 0;
  1245. int num = 0;
  1246. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  1247. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  1248. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  1249. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  1250. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  1251. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  1252. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  1253. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  1254. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  1255. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  1256. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  1257. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  1258. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  1259. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  1260. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  1261. if (clState->hasBitAlign == true) {
  1262. /* Parameters for phatk kernel */
  1263. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W2);
  1264. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  1265. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  1266. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4);
  1267. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->T1);
  1268. } else {
  1269. /* Parameters for poclbm kernel */
  1270. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  1271. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  1272. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  1273. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  1274. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  1275. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  1276. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  1277. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  1278. }
  1279. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  1280. (void *)&clState->outputBuffer);
  1281. return status;
  1282. }
  1283. static void *gpuminer_thread(void *userdata)
  1284. {
  1285. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  1286. struct timeval tv_start, tv_end, diff;
  1287. struct thr_info *mythr = userdata;
  1288. const int thr_id = mythr->id;
  1289. uint32_t *res, *blank_res;
  1290. size_t globalThreads[1];
  1291. size_t localThreads[1];
  1292. cl_int status;
  1293. _clState *clState = clStates[thr_id];
  1294. const cl_kernel *kernel = &clState->kernel;
  1295. struct work *work = malloc(sizeof(struct work));
  1296. unsigned const int threads = 1 << (15 + scan_intensity);
  1297. unsigned const int vectors = clState->preferred_vwidth;
  1298. unsigned const int hashes = threads * vectors;
  1299. unsigned int hashes_done = 0;
  1300. /* Request the next work item at 2/3 of the scantime */
  1301. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  1302. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  1303. bool requested = true;
  1304. res = calloc(BUFFERSIZE, 1);
  1305. blank_res = calloc(BUFFERSIZE, 1);
  1306. if (!res || !blank_res) {
  1307. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  1308. goto out;
  1309. }
  1310. gettimeofday(&tv_start, NULL);
  1311. globalThreads[0] = threads;
  1312. localThreads[0] = clState->work_size;
  1313. diff.tv_sec = ~0UL;
  1314. gettimeofday(&tv_end, NULL);
  1315. while (1) {
  1316. struct timeval tv_workstart;
  1317. /* This finish flushes the readbuffer set with CL_FALSE later */
  1318. clFinish(clState->commandQueue);
  1319. if (diff.tv_sec > opt_scantime || work->blk.nonce >= MAXTHREADS - hashes || work_restart[thr_id].restart) {
  1320. /* Ignore any reads since we're getting new work and queue a clean buffer */
  1321. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1322. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1323. if (unlikely(status != CL_SUCCESS))
  1324. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1325. memset(res, 0, BUFFERSIZE);
  1326. gettimeofday(&tv_workstart, NULL);
  1327. /* obtain new work from internal workio thread */
  1328. if (unlikely(!get_work(work, requested))) {
  1329. applog(LOG_ERR, "work retrieval failed, exiting "
  1330. "gpu mining thread %d", mythr->id);
  1331. goto out;
  1332. }
  1333. mythr->cgpu->getworks++;
  1334. work->thr_id = thr_id;
  1335. requested = false;
  1336. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  1337. work->blk.nonce = 0;
  1338. work_restart[thr_id].restart = 0;
  1339. if (opt_debug)
  1340. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  1341. /* Flushes the writebuffer set with CL_FALSE above */
  1342. clFinish(clState->commandQueue);
  1343. }
  1344. status = queue_kernel_parameters(clState, &work->blk);
  1345. if (unlikely(status != CL_SUCCESS))
  1346. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  1347. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  1348. if (res[MAXBUFFERS]) {
  1349. /* Clear the buffer again */
  1350. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1351. BUFFERSIZE, blank_res, 0, NULL, NULL);
  1352. if (unlikely(status != CL_SUCCESS))
  1353. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  1354. if (opt_debug)
  1355. applog(LOG_DEBUG, "GPU %d found something?", gpu_from_thr_id(thr_id));
  1356. postcalc_hash_async(mythr, work, res);
  1357. memset(res, 0, BUFFERSIZE);
  1358. clFinish(clState->commandQueue);
  1359. }
  1360. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  1361. globalThreads, localThreads, 0, NULL, NULL);
  1362. if (unlikely(status != CL_SUCCESS))
  1363. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  1364. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  1365. BUFFERSIZE, res, 0, NULL, NULL);
  1366. if (unlikely(status != CL_SUCCESS))
  1367. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  1368. gettimeofday(&tv_end, NULL);
  1369. timeval_subtract(&diff, &tv_end, &tv_start);
  1370. hashes_done += hashes;
  1371. work->blk.nonce += hashes;
  1372. if (diff.tv_usec > 500000)
  1373. diff.tv_sec++;
  1374. if (diff.tv_sec >= cycle) {
  1375. hashmeter(thr_id, &diff, hashes_done);
  1376. gettimeofday(&tv_start, NULL);
  1377. hashes_done = 0;
  1378. }
  1379. timeval_subtract(&diff, &tv_end, &tv_workstart);
  1380. if (!requested && (diff.tv_sec > request_interval || work->blk.nonce > request_nonce)) {
  1381. if (unlikely(!queue_request())) {
  1382. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  1383. goto out;
  1384. }
  1385. requested = true;
  1386. }
  1387. }
  1388. out:
  1389. tq_freeze(mythr->q);
  1390. return NULL;
  1391. }
  1392. #endif /* HAVE_OPENCL */
  1393. static void restart_threads(bool longpoll)
  1394. {
  1395. int i;
  1396. /* Discard old queued requests and get new ones */
  1397. flush_requests(longpoll);
  1398. for (i = 0; i < mining_threads; i++)
  1399. work_restart[i].restart = 1;
  1400. }
  1401. static void *longpoll_thread(void *userdata)
  1402. {
  1403. struct thr_info *mythr = userdata;
  1404. CURL *curl = NULL;
  1405. char *copy_start, *hdr_path, *lp_url = NULL;
  1406. bool need_slash = false;
  1407. int failures = 0;
  1408. unsigned int i;
  1409. hdr_path = tq_pop(mythr->q, NULL);
  1410. if (!hdr_path)
  1411. goto out;
  1412. /* full URL */
  1413. if (strstr(hdr_path, "://")) {
  1414. lp_url = hdr_path;
  1415. hdr_path = NULL;
  1416. }
  1417. /* absolute path, on current server */
  1418. else {
  1419. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  1420. if (rpc_url[strlen(rpc_url) - 1] != '/')
  1421. need_slash = true;
  1422. lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  1423. if (!lp_url)
  1424. goto out;
  1425. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  1426. }
  1427. applog(LOG_INFO, "Long-polling activated for %s", lp_url);
  1428. curl = curl_easy_init();
  1429. if (unlikely(!curl)) {
  1430. applog(LOG_ERR, "CURL initialisation failed");
  1431. goto out;
  1432. }
  1433. for (i = 0; i < 36; i++)
  1434. strcat(longpoll_block, "0");
  1435. while (1) {
  1436. json_t *val;
  1437. val = json_rpc_call(curl, lp_url, rpc_userpass, rpc_req,
  1438. false, true);
  1439. if (likely(val)) {
  1440. failures = 0;
  1441. json_decref(val);
  1442. /* Keep track of who ordered a restart_threads to make
  1443. * sure it's only done once per new block */
  1444. if (likely(!strncmp(longpoll_block, blank, 36) ||
  1445. !strncmp(longpoll_block, current_block, 36))) {
  1446. applog(LOG_WARNING, "LONGPOLL detected new block, flushing work queue");
  1447. restart_threads(true);
  1448. } else
  1449. applog(LOG_WARNING, "LONGPOLL received - new block detected and work flushed already");
  1450. } else {
  1451. if (failures++ < 10) {
  1452. sleep(30);
  1453. applog(LOG_WARNING,
  1454. "longpoll failed, sleeping for 30s");
  1455. } else {
  1456. applog(LOG_ERR,
  1457. "longpoll failed, ending thread");
  1458. goto out;
  1459. }
  1460. }
  1461. memcpy(longpoll_block, current_block, 36);
  1462. }
  1463. out:
  1464. free(hdr_path);
  1465. free(lp_url);
  1466. tq_freeze(mythr->q);
  1467. if (curl)
  1468. curl_easy_cleanup(curl);
  1469. return NULL;
  1470. }
  1471. /* Makes sure the hashmeter keeps going even if mining threads stall */
  1472. static void *wakeup_thread(void *userdata)
  1473. {
  1474. const unsigned int interval = opt_log_interval / 2 ? : 1;
  1475. struct timeval zero_tv;
  1476. memset(&zero_tv, 0, sizeof(struct timeval));
  1477. while (1) {
  1478. sleep(interval);
  1479. if (requests_queued() < opt_queue)
  1480. queue_request();
  1481. hashmeter(-1, &zero_tv, 0);
  1482. if (unlikely(work_restart[stage_thr_id].restart)) {
  1483. restart_threads(false);
  1484. work_restart[stage_thr_id].restart = 0;
  1485. }
  1486. }
  1487. return NULL;
  1488. }
  1489. int main (int argc, char *argv[])
  1490. {
  1491. struct thr_info *thr;
  1492. unsigned int i, j = 0;
  1493. char name[32];
  1494. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  1495. return 1;
  1496. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  1497. return 1;
  1498. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  1499. return 1;
  1500. #ifdef WIN32
  1501. opt_n_threads = num_processors = 1;
  1502. #else
  1503. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  1504. opt_n_threads = num_processors;
  1505. #endif /* !WIN32 */
  1506. #ifdef HAVE_OPENCL
  1507. for (i = 0; i < 16; i++)
  1508. gpu_devices[true] = false;
  1509. nDevs = clDevicesNum();
  1510. if (nDevs < 0)
  1511. return 1;
  1512. #endif
  1513. if (nDevs)
  1514. opt_n_threads = 0;
  1515. rpc_url = strdup(DEF_RPC_URL);
  1516. /* parse command line */
  1517. opt_register_table(opt_config_table,
  1518. "Options for both config file and command line");
  1519. opt_register_table(opt_cmdline_table,
  1520. "Options for command line only");
  1521. opt_parse(&argc, argv, applog_and_exit);
  1522. if (argc != 1) {
  1523. applog(LOG_ERR, "Unexpected extra commandline arguments");
  1524. return 1;
  1525. }
  1526. if (total_devices) {
  1527. if (total_devices > nDevs) {
  1528. applog(LOG_ERR, "More devices specified than exist");
  1529. return 1;
  1530. }
  1531. for (i = 0; i < 16; i++)
  1532. if (gpu_devices[i] && i + 1 > nDevs) {
  1533. applog(LOG_ERR, "Command line options set a device that doesn't exist");
  1534. return 1;
  1535. }
  1536. gpu_threads = total_devices * opt_g_threads;
  1537. } else {
  1538. gpu_threads = nDevs * opt_g_threads;
  1539. for (i = 0; i < nDevs; i++)
  1540. gpu_devices[i] = true;
  1541. }
  1542. if (!gpu_threads && !forced_n_threads) {
  1543. /* Maybe they turned GPU off; restore default CPU threads. */
  1544. opt_n_threads = num_processors;
  1545. }
  1546. logcursor = 4;
  1547. mining_threads = opt_n_threads + gpu_threads;
  1548. gpucursor = logcursor;
  1549. cpucursor = gpucursor + nDevs;
  1550. logstart = cpucursor + (opt_n_threads ? num_processors : 0);
  1551. logcursor = logstart + 1;
  1552. if (!rpc_userpass) {
  1553. if (!rpc_user || !rpc_pass) {
  1554. applog(LOG_ERR, "No login credentials supplied");
  1555. return 1;
  1556. }
  1557. rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  1558. if (!rpc_userpass)
  1559. return 1;
  1560. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  1561. }
  1562. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  1563. return 1;
  1564. #ifdef HAVE_SYSLOG_H
  1565. if (use_syslog)
  1566. openlog("cpuminer", LOG_PID, LOG_USER);
  1567. #endif
  1568. work_restart = calloc(mining_threads + 4, sizeof(*work_restart));
  1569. if (!work_restart)
  1570. return 1;
  1571. thr_info = calloc(mining_threads + 4, sizeof(*thr));
  1572. if (!thr_info)
  1573. return 1;
  1574. /* init workio thread info */
  1575. work_thr_id = mining_threads;
  1576. thr = &thr_info[work_thr_id];
  1577. thr->id = work_thr_id;
  1578. thr->q = tq_new();
  1579. if (!thr->q)
  1580. return 1;
  1581. /* start work I/O thread */
  1582. if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
  1583. applog(LOG_ERR, "workio thread create failed");
  1584. return 1;
  1585. }
  1586. /* init longpoll thread info */
  1587. if (want_longpoll) {
  1588. longpoll_thr_id = mining_threads + 1;
  1589. thr = &thr_info[longpoll_thr_id];
  1590. thr->id = longpoll_thr_id;
  1591. thr->q = tq_new();
  1592. if (!thr->q)
  1593. return 1;
  1594. /* start longpoll thread */
  1595. if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
  1596. applog(LOG_ERR, "longpoll thread create failed");
  1597. return 1;
  1598. }
  1599. pthread_detach(thr->pth);
  1600. } else
  1601. longpoll_thr_id = -1;
  1602. gettimeofday(&total_tv_start, NULL);
  1603. gettimeofday(&total_tv_end, NULL);
  1604. if (opt_n_threads ) {
  1605. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  1606. if (unlikely(!cpus)) {
  1607. applog(LOG_ERR, "Failed to calloc cpus");
  1608. return 1;
  1609. }
  1610. }
  1611. if (gpu_threads) {
  1612. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  1613. if (unlikely(!gpus)) {
  1614. applog(LOG_ERR, "Failed to calloc gpus");
  1615. return 1;
  1616. }
  1617. }
  1618. stage_thr_id = mining_threads + 3;
  1619. thr = &thr_info[stage_thr_id];
  1620. thr->q = tq_new();
  1621. if (!thr->q)
  1622. return 1;
  1623. /* start stage thread */
  1624. if (pthread_create(&thr->pth, NULL, stage_thread, thr)) {
  1625. applog(LOG_ERR, "stage thread create failed");
  1626. return 1;
  1627. }
  1628. /* Flag the work as ready forcing the mining threads to wait till we
  1629. * actually put something into the queue */
  1630. inc_staged(mining_threads, true);
  1631. #ifdef HAVE_OPENCL
  1632. i = 0;
  1633. /* start GPU mining threads */
  1634. for (j = 0; j < nDevs * opt_g_threads; j++) {
  1635. int gpu = gpu_from_thr_id(j);
  1636. /* Skip devices not set to work */
  1637. if (!gpu_devices[gpu])
  1638. continue;
  1639. thr = &thr_info[i];
  1640. thr->id = i;
  1641. gpus[gpu].is_gpu = 1;
  1642. gpus[gpu].cpu_gpu = gpu;
  1643. thr->cgpu = &gpus[gpu];
  1644. thr->q = tq_new();
  1645. if (!thr->q) {
  1646. applog(LOG_ERR, "tq_new failed in starting gpu mining threads");
  1647. return 1;
  1648. }
  1649. applog(LOG_INFO, "Init GPU thread %i", i);
  1650. clStates[i] = initCl(gpu, name, sizeof(name));
  1651. if (!clStates[i]) {
  1652. applog(LOG_ERR, "Failed to init GPU thread %d", i);
  1653. continue;
  1654. }
  1655. applog(LOG_INFO, "initCl() finished. Found %s", name);
  1656. if (unlikely(pthread_create(&thr->pth, NULL, gpuminer_thread, thr))) {
  1657. applog(LOG_ERR, "thread %d create failed", i);
  1658. return 1;
  1659. }
  1660. pthread_detach(thr->pth);
  1661. i++;
  1662. }
  1663. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  1664. #endif
  1665. /* start CPU mining threads */
  1666. for (i = gpu_threads; i < mining_threads; i++) {
  1667. int cpu = cpu_from_thr_id(i);
  1668. thr = &thr_info[i];
  1669. thr->id = i;
  1670. cpus[cpu].cpu_gpu = cpu;
  1671. thr->cgpu = &cpus[cpu];
  1672. thr->q = tq_new();
  1673. if (!thr->q) {
  1674. applog(LOG_ERR, "tq_new failed in starting cpu mining threads");
  1675. return 1;
  1676. }
  1677. if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
  1678. applog(LOG_ERR, "thread %d create failed", i);
  1679. return 1;
  1680. }
  1681. pthread_detach(thr->pth);
  1682. }
  1683. applog(LOG_INFO, "%d cpu miner threads started, "
  1684. "using SHA256 '%s' algorithm.",
  1685. opt_n_threads,
  1686. algo_names[opt_algo]);
  1687. thr = &thr_info[mining_threads + 2];
  1688. /* start wakeup thread */
  1689. if (pthread_create(&thr->pth, NULL, wakeup_thread, NULL)) {
  1690. applog(LOG_ERR, "wakeup thread create failed");
  1691. return 1;
  1692. }
  1693. /* Restart count as it will be wrong till all threads are started */
  1694. pthread_mutex_lock(&hash_lock);
  1695. gettimeofday(&total_tv_start, NULL);
  1696. gettimeofday(&total_tv_end, NULL);
  1697. total_mhashes_done = 0;
  1698. pthread_mutex_unlock(&hash_lock);
  1699. /* Set up the ncurses interface */
  1700. if ((mainwin = initscr()) == NULL) {
  1701. applog(LOG_ERR, "Failed to initscr");
  1702. return 1;
  1703. }
  1704. idlok(mainwin, true);
  1705. scrollok(mainwin, true);
  1706. curses_active = true;
  1707. getmaxyx(mainwin, logcursor, i);
  1708. move(logcursor, 0);
  1709. refresh_display();
  1710. /* Now that everything's ready put enough work in the queue */
  1711. for (i = 0; i < opt_queue + mining_threads; i++) {
  1712. if (unlikely(!queue_request())) {
  1713. applog(LOG_ERR, "Failed to queue_request in main");
  1714. return 1;
  1715. }
  1716. }
  1717. /* main loop - simply wait for workio thread to exit */
  1718. pthread_join(thr_info[work_thr_id].pth, NULL);
  1719. curl_global_cleanup();
  1720. if (gpu_threads)
  1721. free(gpus);
  1722. if (opt_n_threads)
  1723. free(cpus);
  1724. applog(LOG_INFO, "workio thread dead, exiting.");
  1725. delwin(mainwin);
  1726. endwin();
  1727. refresh();
  1728. return 0;
  1729. }