main.c 62 KB

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