main.c 62 KB

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